lua-users home
lua-l archive

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




On 2019-05-07 5:14 p.m., Egor Skriptunoff wrote:
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.


Sandbox killer.

What's next, string.dump(stack_offset)?

I don't believe string.dump should return upvalues. It's not a persistence library. (Altho the idea of a pure-Lua persistence library *does* seem interesting.)

On the other hand, it's perfectly safe to load arbitrary well-formed bytecode with arbitrary upvalues.

See: https://github.com/SoniEx2/loadx/