lua-users home
lua-l archive

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


> Lua 5.2+ has function debug.upvalueid(f, n) returning a light userdata.
> Does Lua guarantee debug.upvalueid() returns the same result during the
> lifespan of the closure?
> 
> local f = function()....end
> local n = ....
> local old_id = debug.upvalueid(f, n)
> .... GC activity may happen here
> local new_id = debug.upvalueid(f, n)
> print(new_id == old_id)  -- Is it always true?

The documentation says:

   These unique identifiers allow a program to check whether different
   closures share upvalues.  Lua closures that share an upvalue (that
   is, that access a same external local variable) will return identical
   ids for those upvalue indices.

If the identifer changed, it would mean the closure is not sharing the
upvalue with itself. That can actually happen, but only if the program
asks for it:

> local n; function f1 () return n end
> local n; function f2 () return n end
> debug.upvalueid(f1, 1)
  --> userdata: 0x55c0c4f588a0
> debug.joinupvalue(f1, 1, f2, 1)
> debug.upvalueid(f1, 1)
  --> userdata: 0x55c0c4f5a130

-- Roberto