lua-users home
lua-l archive

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


On Aug 12, 2014, at 8:11 AM, Steven Degutis <sbdegutis@gmail.com> wrote:

> 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”.
> 


Read my earlier post. I don’t think the _ENV_G assignment happens when you do a load (after all, this would have the effect of resetting _G after every call to load()). My reading is that setting _G happens ONCE only for the distinguished environment (when the Lua_State is initialized I presume), and never again.

This also means that if you supply your OWN environment table at load() time, it will NOT contain an _G unless you explicitly set it.

—Tim