lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

2009/11/30 spir <>:
> Follow-up. Just for curiosity.
> function f()
>  local t = {1}
>  function g()
>    print (t[1])
>  end
>  g()           --> 1
>  t = {2}
>  g()           --> 2
> end
> f()
> This seems to show upvalues are referenced by names (what I called symbolic reference) rather than by address (pointer reference). Else the full replacement of t would not be seen by the closure, as its address has changed.
> Is this interpretation correct?

When you write local t = {1}, you have created two distinct and very
different objects. First you have an anonymous table ({1}), and you
have a local variable (t). The variable point to the table. Assigning
it a new value (t = {2}) make it point to another value, without
changing the original value.

Upvalues are references to these "variable" objects. When you access
the upvalue (by writing "print(t[1])"), you dereference it, and obtain
the object that the variable points to at that dereferencing moment,
not when it was created, not when the code was compiled, not when the
closure was closed.

If several functions access the same variable (here f and g access t),
there is still a single variable, and the functions can exchange
values through there.