Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are shared upvalues?

Tags:

lua

upvalue

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

like image 918
Tiago Costa Avatar asked Aug 13 '26 16:08

Tiago Costa


1 Answers

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.

like image 140
lhf Avatar answered Aug 17 '26 08:08

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!