How do two closures share an upvalue? And how does it work?
function print_env()
print(_ENV) --_ENV is an upvalue
end
function foo()
_ENV = { print = print, print_env = print_env} --redefine the _ENV upvalue
print(_ENV) --prints: 0094CF40
print_env() --prints: 0094CF40
end
When I call print_env()
from foo()
it prints the _ENV
defined in foo()
, however since they are different functions shouldn't their closures have different upvalues? So when one function modifies its upvalue the other remains the same. Or is _ENV
a special upvalue?
Thanks
Upvalues are external local variables. Two functions can share upvalues when they use the same external local variables. This is determined by lexical scoping. Furthermore, every chunk sees an external local variable named _ENV
, which is used to resolve global names.