Lua and serialized shutters

I am trying to serialize and deserialize the closure of Lua

my main understanding is that below the factory should generate closures (and that Lua doesn't really distinguish between functions and closures - i.e. there is no closure of type)

> function ffactory(x) return function() return x end end
> f1 = ffactory(5)
> print(f1())
5                        <-- so far so good
> s = string.dump(f1)
> f2 = load(s)
> print(f2())
table: 00000000002F7BA0  <-- expected the integer 5
> print(f2()==_ENV)
true                     <-- definitely didn't expect this!

I was expecting the integer 5 to be serialized with f1. Or, if string.dumpit cannot handle closures, I expected an error.

I get a completely different (but more than what I expected) leads to moderate changes. It seems like it f2really is a closure, but string.dump did not try to serialize the value of x at the time it was serialized.

docs do not really help me. (what do they mean by "... with new upvalues"?)

> function ffactory(x) return function() return x+1 end end
> f1 = ffactory(5)
> print(f1())
6                        <-- good
> s = string.dump(f1)
> f2 = load(s)
> print(f2())
stdin:1: attempt to perform arithmetic on upvalue 'x' (a table value)
stack traceback:
        stdin:1: in function 'f2'
        stdin:1: in main chunk
        [C]: in ?
+5
source share
2

- , / ( , , ):

local function capture(func)
  local vars = {}
  local i = 1
  while true do
    local name, value = debug.getupvalue(func, i)
    if not name then break end
    vars[i] = value
    i = i + 1
  end
  return vars
end

local function restore(func, vars)
  for i, value in ipairs(vars) do
    debug.setupvalue(func, i, value)
  end
end  

function ffactory(x) return function() return x end end
local f1 = ffactory(5)
local f2 = (loadstring or load)(string.dump(f1))
restore(f2, capture(f1)) --<-- this restored upvalues from f1 for f2

print(f1(), f2())

Lua 5.1, Lua 5.2.

, ffactory ( math.abs(0); , ):

function ffactory(x) return function() math.abs(0) return x end end

, upvalues, , upvalues, Lua 5.2:

lua.exe: upvalues.lua:19: attempt to index upvalue '_ENV' (a nil value)
stack traceback:
upvalues.lua:19: in function 'f2'
upvalues.lua:24: in main chunk
[C]: in ?
+6

. string.dump upvalues. , upvalues ​​ ( userdata, Lua , ?)

upvalues ​​- , - /. x upvalue , ffactory, .

- , upvalues ​​ , :

function ffactory(x)
    return function() return x+1 end
end

local f1 = ffactory(5)
print(f1())

local s = string.dump(f1)
f2 = loadstring(s)
debug.setupvalue(f2, 1, 5)
print(f2())
+1

All Articles