lua-users home
lua-l archive

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

2014-10-24 16:49 GMT+02:00 Roberto Ierusalimschy <>:

> Both dump and load work with any function, with any number of upvalues.
> However, dump does not save (and therefore load cannot restore) the
> values of those upvalues, as that would involve a complete data
> serialization system way out of the scope of Lua. So, when load
> restores a function with upvalues, its upvalues are instanciated
> with fresh instances containing nil.

Except when there is exactly one upvalue, even when the
chunk is not a main chunk, as shown by the OP:

~~~ file upvaluedemo.lua
local x
local f1 = function() return x end
local f2 = function() return x,y end
local g1 = load(string.dump(f1))
print('g1()',g1()) --> _ENV
local g2 = load(string.dump(f2))
print('g2()',g2()) --> error message

I can almost, but not quite, persuade myself that I understand what
is happening.

1. f1 is a function with exactly one upvalue x.
2. Therefore when g1 is loaded, _ENV is assigned to that upvalue.
3. Therefore x==_ENV in g1.
4. f2 is a function with two upvalues, x and _ENV (implied by the
reference to the unknown name y).
5. Therefore both are initialized to nil.
6. Therefore the reference to y fails.

> Programmers can use functions like lua_upvalueid and lua_upvaluejoin
> to save/restore upvalues when necessary.

debug.setupvalue etc at the Lua level.