lua-users home
lua-l archive

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


Javier Guerra wrote:
> >  > If so, how can they hold a reference to a simple
> >  > value (as opposed, for example, as to a table)?
> >  compiler magic, upvalue is a special reference that is invisible to
> >  user (but you can examine it with debug library).
> 
> i think 'upvalue' is a misleading term.  it's just a local variable,
> local to the do...end block and not to either of the functions.  (of
> course that block exists inside the chunk's function).
> 
> AFAIUI, the execution of the do...end block creates the storage for
> the variables (how would that be called? i guess it's not a 'stack
> frame'), and the functions (closures, in fact) reference that local
> vars frame.

Nope. The upvalue _is_ a true Lua object, handled by the GC, but
usually invisible. It only holds a pointer and a tagged value.

Upvalues are created on-demand when a closure is created and it
needs a reference to a stack slot which does not have an open
upvalue yet. Initially the pointer inside the upvalue points to
the corresponding stack slot, i.e. the upvalue is "open".

But as you can see from the bytecode there's a CLOSE instruction
just before the end of the do...end block. This "closes" the
upvalue by copying the contents of the stack slot to the upvalue
structure and setting the pointer to its address.

Recommended reading:
  "The Implementation of Lua 5.0"
  http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/sblp2005.pdf

--Mike