[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: _ENV vs _G
- From: Dirk Laurie <dirk.laurie@...>
- Date: Wed, 13 Aug 2014 13:55:50 +0200
2014-08-13 9:38 GMT+02:00 Tim Hill <drtimhill@gmail.com>:
>
> On Aug 13, 2014, at 12:17 AM, Dirk Laurie <dirk.laurie@gmail.com> wrote:
>
>>>>>
>>>>> 4. If you compile a function using `load` or `loadstring`, its _ENV is one
>>>>> of:
>>>>> a. An _ENV parameter.
>>>>> b. The _ENV specified in the `load`.
>>>>> c. An _ENV upvalue.
>>>>>
>>>>
>>>> It's only the one specified in the registry if that still happens to be
>>>> the current upvalue called _ENV. And even the one in the registry
>>>> may not be the one you started with. You can assign something
>>>> to debug.getregistry[2]; not recommended, though.
>>>
>>>
>>> That’s not my reading of the docs/source, though they are rather
>>> unclear.
>>
>> Have you read my code in env.lua, verified that it gives the specified
>> results, and checked my logic in claiming why it gives those results?
>>
>> If not, there is not much point in my trying to argue with you.
>>
>
> Indeed I did, though I was discussing and not arguing.
> Perhaps we are talking about different things. My reading of your
> post was that a compiled chunk (which is, by definition, a function)
> could have any of (a), (b) or (c) as it’s _ENV. My point was that this
> isn’t true, it can only be (b) or the distinguished environment.
If by "compiled chunk" you mean "the result of `load` or `loadfile`
with no _ENV argument" I almost, but not quite, agree. [1]
If by "distinguished environment" you mean "the original global
environment of the Lua state created by the host program",
I almost, but not quite, agree. [2]
> If, however, you mean that lexically NESTED functions WITHIN
> a compiled chunk may have (a), (b) or (c) then yes of course
> that is true as per the Lua documentation.
That is what my code demonstrates, so yes, I mean it.
[1] Binary chunks can have _ENV parameters, so (a) is possible.
[2] The correct description is "the global environment stored
in the registry at the time the chunk is loaded". Demo:
$ lua
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> f = load"return _ENV, id"
> debug.getregistry()[2] = {id="mytable",f=f,load=load,print=print,tostring=tostring}
> g = load"return _ENV, id"
> =f()
table: 0x1fe05f0 nil
> =g()
table: 0x2003f10 mytable
But you are right that (c) is impossible for a loaded chunk, since
merely `_ENV = ` instead of `debug.getregistry()[2] =` does not have
the above effect.
- References:
- _ENV vs _G, Mason Mackaman
- Re: _ENV vs _G, Steven Degutis
- Re: _ENV vs _G, Roberto Ierusalimschy
- Re: _ENV vs _G, Tim Hill
- Re: _ENV vs _G, Roberto Ierusalimschy
- Re: _ENV vs _G, Steven Degutis
- Re: _ENV vs _G, Dirk Laurie
- Re: _ENV vs _G, Tim Hill
- Re: _ENV vs _G, Dirk Laurie
- Re: _ENV vs _G, Tim Hill
- Re: _ENV vs _G, Dirk Laurie
- Re: _ENV vs _G, Tim Hill