lua-users home
lua-l archive

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

On Sat, Nov 30, 2013 at 11:33 AM, Georgios Petsagourakis
<> wrote:
> In this I assume you mean something like this:
>     local function something(env, ...)
>       local old_env = _ENV
>       _ENV = env
>       -- do code here, `env` is your environment
>       _ENV = old_env
>     end
If you want to have access to the function's *actual* environment,
then yes, this works well.

>> ---if you wanted to keep the current env as a shadow:
>> local func(env, ...)
>>     _ENV = setmetatable(env, {__index = _ENV}) --or the other way around
>>    ---code that does stuff
>> end
> I am not clear here, shouldn't the initial _ENV be restored at some point ?

No, the code will work fine. The following is equivalent:

local func(env, ...)
   local oe = _ENV
    _ENV = setmetatable(env, {__index = oe})

> Nice explanation, thanks for putting this into words.

You are most welcome!

If func is an external function loaded by "load" or "loadfile", then
that is where your patching should take place. In 5.2, load takes an
environment as an optional value in the last position:

`load (ld [, source [, mode [, env]]])`

Without `env` set, it defaults to the current value of _ENV. Instead,
you'd pass in a table that you held another reference to, with perhaps
the current (or some default env) as the fallback value for `__index.`

People more-or-less stopped complaining about the proposed death of
`setfenv` when this was added to `load`. :)

Let us know how it works out for you!