lua-users home
lua-l archive

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


Op Wo. 10 Apr. 2019 om 11:21 het Dennis Fischer
<DarkWiiPlayer@hotmail.com> geskryf:

> The last argument to `load` is passed as the first upvalue to the new closure that is returned. This is usually the environment (at least for what the manual refers to as "main chunks"), which is what this argument is supposedly meant for.
> If, however, you dump any function as bytecode and load it again, its environment may be the second, third or fifth upvalue, or it may not have an environment at all (a function that accesses no globals).
>
> So my question is, why make the first upvaue a special case in the first place?

If you load from Lua source code, which is the only case 99% of Lua
users ever utilize, the first upvalue is the only upvalue, and there
is no risk.

The thing is, upvalues are highly context-dependent. You can't tell
from reading the source code whether non-local variables are supposed
to be upvalues or globals. Thus you don't know, when you are setting
the second, third or fifth upvalue, which named variable that would
refer to, unless you use the debug library.

> This seems very un-Lua to me.

I don't think it is un-Lua to omit support for features that 99% per
cent of Lua users would never need. For example, the hyperbolic
functions were deprecated in Lua 5.3.

> 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 [, ...]]])
> The code to set the n-th upvalue obviously already exists and gets called by the load function, so, I expect, to someone who's familiar with Luas C implementation this change should be trivial (At least one could assume so).

You can (and should) check that upvalues have the names that you
expect whenever you set them.
    f = load(chunk [, chunkname [, mode [, env]]])
    assert ("myname"==debug.setupvalue(f,2,value)

Having extra arguments therefore adds no functionality, it merely
encourages users to set upvalues without checking their names.

No thanks.