On Wed, Apr 10, 2019 at 12:22 PM Dennis Fischer wrote:
So my question is, why make the first upvaue a special case in the
first place? This seems very un-Lua to me. A more generic (and
backwards-compatible) alternative would be for all additional
arguments to load to be passed as upvalues to the new closure in
order of appearance.
load(chunk [, chunkname [, mode [, ...]]])
This makes sense.
I like this suggestion (although it would be useful to very small
amount of Lua users).
Both *string.dump()* and *load()* should take into account function's
upvalues.
If number of upvalues is known:
local bytecode, upvalues_num, upv1, upv2, upv3 = string.dump(some_func)
...
local restored_func = load(bytecode, "=loaded", "b", upv1, upv2, upv3)
If number of upvalues is unknown:
local dumped = {string.dump(some_func)}
...
local restored_func = load(dumped[1], "=loaded", "b",
table.unpack(dumped, 3, dumped[2] + 2))
This approach is backward-compatible after the following modification:
If no upvalues are given to *load()* and bytecode represents main
chunk (this could be easily determined by examining bytecode) then
global environment is used as the first upvalue.
P.S.
Of course, this would not help when you need to dump and load two
functions which share the same upvalue.
P.P.S.
Using debug library is considered as "dirty trick" and should be
avoided whenever possible.
Meanwhile dumping/loading functions having upvalues is a pretty legal
job, but we can't do it without debug library.