2.2 – Environments and the Global Environment
As will be discussed in §3.2 and §3.3.3, 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 §3.3.2), 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 §3.5).
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 §4.5). In Lua, the global variable _G
is initialized with this same value. (_G
is never used internally.)
When Lua loads a chunk, the default value for its _ENV
upvalue 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.)