3 ms·
Ooooh, maybe this is relevant: > function foo() >> local a = _ENV >> local _ENV = a >> return {a=function() _ENV = {r=6} end, b = function() re
by pygy_ 9y ago
Ooooh, maybe this is relevant:
> function foo()
>> local a = _ENV
>> local _ENV = a
>> return {a=function() _ENV = {r=6} end, b = function() return r end}
>> end
> r = 5
> x = foo()
> x.b()
> =x.b()
5
> return x.a()
> return x.b()
6
>
vs
> function foo()
return {
a = function() return setfenv(2, {r = 6}) end,
b = function() return r end
}
end
> x = foo()
> = x.a()
bad argument #1 to '?' (invalid level)
stack traceback:
[builtin#11]: at 0x0101faf2a0
[C]: at 0x0101f4ea60
> function foo()
function bar()
setfenv(2, {x=6})
end
bar()
return function() return x end
end
> e = foo()
> =e()
6
I hadn't thought of that...
- rweichler 9y agowat?
- pygy_ 9y agoWith setfenv, the environment definition is lexical by default, but if you change the environment of the parent after creating a child function, the environment of the child doesn't change. You must `setfenv` the child as well. With _ENV, it is fully dynamic, and can be changed "at a distance". Also: > function foo() >> local function bar() return a end >> setfenv(1,{a=4}) >> return bar >> end > a = 9 > =foo()() 9