[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Environment behavior
- From: Peter Cawley <lua@...>
- Date: Sat, 7 Dec 2013 15:49:40 +0000
If we replace the call to load() and the subsequent execution with
plain Lua code, and desugar the environment references, then your code
is transformed to the following:
-----
local env1 = {print=print, a=1}
local env2 = {print=print, a=2}
do
local _G = _ENV
local _ENV -- I'll call this "inner _ENV"
_G.item = {
func = function()
_ENV.print(_ENV.a)
end,
subItem = {
func = function()
_ENV.print(_ENV.a)
end,
}
}
end
debug.setupvalue(item.func, 1, env1)
debug.setupvalue(item.subItem.func, 1, env2)
item.func()
item.subItem.func()
-----
The inner _ENV is an upvalue of func and subItem.func, and crucially
is a shared upvalue: the first upvalue of func is inner _ENV, and the
first upvalue of subItem.func is inner _ENV. As such,
debug.setupvalue(item.func, 1, x) and
debug.setupvalue(item.subItem.func, 1, x) have the same effect.
On Sat, Dec 7, 2013 at 3:39 PM, Bruno Deligny <bruno.deligny@gmail.com> wrote:
> Hi
>
> I was playing with environements and i dont understand this behavior.
>
> local env1 = {print=print, a=1}
> local env2 = {print=print, a=2}
>
> local component = load([[
> item = {
> func = function()
> print(a)
> end,
> subItem = {
> func = function()
> print(a)
> end,
> }
> }
> ]])
>
> component()
>
> debug.setupvalue(item.func, 1, env1)
> debug.setupvalue(item.subItem.func, 1, env2)
>
> item.func()
> item.subItem.func()
>
> This print:
> 2
> 2
>
> I was hoping it printed:
> 1
> 2
>
> It would be great if someone could explain to me how env is propagated.
>
> Thanks
>