lua-users home
lua-l archive

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



On Mar 27, 2015, at 11:30 PM, Dirk Laurie <dirk.laurie@gmail.com> wrote:

In the first case, the Lua compiler had access to existing values
for those names. In the second, it did not. It did not even know
the names. All that it knows is that the function has two upvalues.
Since the Lua compiler is a very friendly person that aims to
please, it helpfully generates code that will initialize the first
upvalue to the current _ENV, since it knows that this is quite
often what the user wants.

Not quite. The compiler generates the top-level (aka “main”) function for a chunk as if it had one upvalue, _ENV. It’s the bytecode *loader* (and only the Lua one, not the C API one) that wires this to the supplied (or distinguished) environment. Since, at the bytecode level, the “main” function of a chunk is indistinguishable from an arbitrary function dumped with string.dump(), the various behaviors observed by Sean are a result.

In fact, this behavior makes it HARDER to sandbox untrusted functions, though Roberto would no doubt point out that you cannot trust bytecode anyway, and should only load Lua text, which will have a correctly wired “main” chunk function.

—TIm