lua-users home
lua-l archive

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


A closure is composed of two elements: a (reference to a) piece of
code in bytecode format and (references to) values for outer local
variables (upvalues).
The string.dump function only dumps the piece of code and *not* the
values stored in the upvalues.
So when you load them again, upvalues are logically initialized to nil.

Using debug.setupvalue it is possible to save and restore upvalues in code dump.
This is what my serialization function "DataDumper" [1] is able to do
(for Lua 5.1).
It outputs the following code for your example (notice that it is
quite complex) :

> =DataDumper(foo)
local closures = {}
local function closure(t)
  closures[#closures+1] = t
  t[1] = assert(loadstring(t[1]))
  return t[1]
end
local t = closure {
  "←LuaQ\000☺♦\000\000\000\000=stdin\000♠\000\000\000♠\000\000\000☺\000 ... ",
  "local x"
}
for _,t in pairs(closures) do
  for i = 2,#t do
    debug.setupvalue(t[1], i-1, t[i])
  end
end
return t

[1] http://lua-users.org/wiki/DataDumper or https://gist.github.com/766518