3.12 – Manipulating Environments
All global variables are kept in ordinary Lua tables, called environments. The initial environment is called the global environment. This table is always at pseudo-index LUA_GLOBALSINDEX.
To access and change the value of global variables, you can use regular table operations over an environment table. For instance, to access the value of a global variable, do
- lua_pushstring(L, varname);
- lua_gettable(L, LUA_GLOBALSINDEX);
You can change the global environment of a Lua thread using lua_replace.
The following functions get and set the environment of Lua functions:
- void lua_getfenv (lua_State *L, int index);
- int lua_setfenv (lua_State *L, int index);
lua_getfenv pushes on the stack the environment table of the function at index index in the stack. If the function is a C function, lua_getfenv pushes the global environment. lua_setfenv pops a table from the stack and sets it as the new environment for the function at index index in the stack. If the object at the given index is not a Lua function, lua_setfenv returns 0.