This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Hydrotronics's profile picture

local variable storage

Started by Hydrotronics, 08 October 2016 - 11:37 AM
Hydrotronics #1
Posted 08 October 2016 - 01:37 PM
Simple question. Where are local variables stored?
I'm fairly sure global variables, tables and functions are stored in _G but I'm not sure where to find local variables. There's no particular reason to this, I was just curious
SquidDev #2
Posted 08 October 2016 - 01:42 PM
Under LuaJ (the implementation which ComputerCraft uses) when each function gets called it allocates an array of LuaValues to represent a local variable. When you do:

local a, b = 1, 2
return a + b
It will store 1 in slot 0, 2 in slot 1 and then get slots 0 and 1 and add them together.

You can Cobalt's implementation of the VM here which is mostly the same as LuaJ's: note the stack variable: this stores all the locals.
Edited on 08 October 2016 - 11:42 AM
Hydrotronics #3
Posted 08 October 2016 - 01:50 PM
Oh ok, I'd assume we can't access stack in-game
Bomb Bloke #4
Posted 08 October 2016 - 02:38 PM
I'd assume not; certainly there's no accessible equivalent in regular Lua.

Furthermore, within ComputerCraft at least, globals you declare aren't going into _G. The bios script each system runs on boot starts the shell with a unique environment table, and all globals go into there. The shell and multishell scripts load their APIs into the current global environment, which means you can't find those through _G for example - this is why other APIs can't access shell / multishell (because they don't get access to any specific shell's environment table).

If you want the current environment table, getfenv() can return it to you.
Hydrotronics #5
Posted 08 October 2016 - 03:19 PM
oh cool. How would I use getfenv()? I tried using it in the lua prompt but I kept being returned with table: 68953f
SquidDev #6
Posted 08 October 2016 - 03:27 PM
Oh ok, I'd assume we can't access stack in-game
Shameless plug: If you have CCTweaks installed then you can add the debug library which allows direct access to the stack and upvalues.

oh cool. How would I use getfenv()? I tried using it in the lua prompt but I kept being returned with table: 68953f
That table is the environment just CC's pretty printing functions don't handle it. You can use it like any other table:

local env = getfenv()
assert(env == _ENV)
assert(env.print == print)

for k, v in pairs(env) do print(k, v) end
It is worth noting that in later versions you should use _ENV rather than getfenv() as the latter is being phased out. You may note when iterating over the environment that it doesn't have any members: this is because it uses metatables to lookup in the parent environment if it can't find it in this one: try getmetatable(_ENV).__index.
Hydrotronics #7
Posted 08 October 2016 - 05:04 PM
okie! Ta :)/>