←  Ask a Pro

ComputerCraft | Programmable Computers for Minecraft

»

Get code acces to local Vars

Wilma456's Photo Wilma456 11 Jan 2017

I want to code a plugin system and it need acces to the local vars of my programm. I had tried it with load(), but it don't have acces.
Quote

Lupus590's Photo Lupus590 11 Jan 2017

so you want your plugins to share the enviroment of your program?

I'm not 100% sure, but I think you can put everything into a table and use the table as the enviroment, how you do that I don't know.
Quote

Sewbacca's Photo Sewbacca 11 Jan 2017

Os.run() provides a similar possibility (No access to locals! It is just possible out of Lua or with the debug API to access them (CCTweaks support it)), you can put vars into a table and share it for your programs (They will be able to access _G). Otherwise you can create a table like os.run, with more possibilities (loadfile(setmetatable({<Your vars>}, { __index = _G --[[To allow the program to use APIs]]})). If you are new at environments, i would recommend to look at the Lua manual. Sorry for so manny links. I am just in a link hype ^^.
Edited by Sewbacca, 04 March 2017 - 10:37 PM.
Quote

KingofGamesYami's Photo KingofGamesYami 11 Jan 2017

You can't do that. Even if you could, it would be a bad idea.

A better idea would be to pass the variables as arguments.
Quote

TheZen's Photo TheZen 27 Jan 2017

Here is how you it's done.
I have some example vars.
First program
local Var1 = "i'm first"
local Var2 = "i'm second"
local Var3 = "and i'm third"
vars = {Var1,Var2,Var3}
Second Program
local Var1 = vars[1]
local Var2 = vars[2]
local Var3 = vars[3]
-- not rquired just so that they are used
print(Var1) -- should write "i'm first"
print(Var2) -- should write "i'm second"
print(Var3) -- should write "and im third"

Edited by KidBrine, 27 January 2017 - 12:42 AM.
Quote

Bomb Bloke's Photo Bomb Bloke 27 Jan 2017

That won't work. You won't have access to the original variables, but rather just to the copies you placed into the "vars" table. Altering those won't alter the original locals.
Quote