lua-users home
lua-l archive

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


This is my current understanding of how _G and _ENV work based on my
reading of the manual and Pil^3 along with Roberto's response to my
first email:

When you create a new Lua state, its registry (i.e. the table at
LUA_REGISTRYINDEX) contains a special table somewhere which is
henceforth known as "the global environment".

When you load a new chunk for Lua to execute, something essentially
equivalent to the following pseudocode happens:

    local _ENV = lua_gettable(L, LUA_REGISTRYINDEX, <global environment's key>)
    _ENV._G = _ENV

That is, _G is a "global" (i.e. a field on the key _ENV) referring to
the initial value of _ENV, which is "the global environment".

As for C code that use lua_getglobal and lua_setglobal, they are
equivalent to operating directly on the table retrieved by doing:

    // assuming temporarily that <global environment's key> is a string:
    lua_pushstring(L, <global environment's key>);
    lua_gettable(L, LUA_REGISTRYINDEX);

Now, ignoring what the type of <global environment's key> happens to
be, is this a correct understanding of how both _G and _ENV are
created?

I am not so much interested to hear about /how/ they behave with other
Lua code, because once I am sure this is how they are created, and
assuming they are using otherwise-normal Lua semantics, it is very
easy to infer how they behave with any Lua code.

On Tue, Aug 12, 2014 at 8:56 AM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
>> The 5.2 ref manual (section 2.2) states “When Lua compiles a
>> chunk it initializes the value of its _ENV upvalue…”. When I
>> was initially studying Lua this did confuse me until I realized
>> that it really means “When Lua LOADS a chunk…” [...]
>
> Thanks!
>
> -- Roberto
>