Environments and the Global Environment
As we will discuss further in Variables and Assignment, any reference to a free name (that is, a name not bound to any declaration) var
is syntactically translated to _ENV.var
. Moreover, every chunk is compiled in the scope of an external local variable named _ENV
(see Chunks), so _ENV
itself is never a free name in a chunk.
Despite the existence of this external _ENV
variable and the translation of free names, _ENV
is a completely regular name. In particular, you can define new variables and parameters with that name. Each reference to a free name uses the _ENV
that is visible at that point in the program, following the usual visibility rules of Lua (see Visibility Rules).
Any table used as the value of _ENV
is called an environment.
Lua keeps a distinguished environment called the global environment. This value is kept at a special index in the C registry (see Registry). In Lua, the global variable _G
is initialized with this same value. (_G
is never used internally, so changing its value will affect only your own code.)
When Lua loads a chunk, the default value for its _ENV
variable is the global environment (see load
). Therefore, by default, free names in Lua code refer to entries in the global environment and, therefore, they are also called global variables. Moreover, all standard libraries are loaded in the global environment and some functions there operate on that environment. You can use load
(or loadfile
) to load a chunk with a different environment. (In C, you have to load the chunk and then change the value of its first upvalue; see lua_setupvalue
.)