lua-users home
lua-l archive

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


2015-03-28 6:16 GMT+02:00 Sean Conner <sean@conman.org>:

>         1       a       3
>         2       _ENV    table: 0x9af23c0
>
>   Okay.  No guarentee that the first upvalue is _ENV.
...
>      1       a       table: 0x9b4b3c0
>      2       _ENV    nil
>
> Um ... to me, this looks like a bug.  The *names* are in the right order,
> but the *values* appear to have been swapped.

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.

The point is that debug.setupvalue is a tool to be used only in
a trusted-protocol situation. If the function is written by you, or
anybody in your organization that has to say yes-boss when you
give orders, the first upvalue can be guaranteed to be _ENV,
for example by putting

    local _ENV = _ENV

If the function is compiled with debug information, you can find
out which upvalue, if any, is named _ENV. That is still OK, sort of,
but just to remind you that is already perilous, you need functions
from the debug library.

If the function is written by some untrusted third party, amd supplied
without debug information, it is not much different from any other
untrusted piece of code (such as that interesting-looking zipfile in
the e-mail that will tell you how to retrieve those ten million dollars
left to you by an eccentric anonymous benefactor). You should
load it with a non-null 'env' argument, providing only tools that
can do no harm.

I can understand that people who got addicted to getfenv/setfenv
find it hard to kick the habit. But they should. It's dangerous to
your health.