Lua 會把所有全域變數放入一個稱為全局環境的 table,並將此 table 保存在 _G 中。因此 _G._G == _G,且 math、pairs 等標準庫通常也存在於其中。
function treaverse_global_env(curtable, level)
for key, value in pairs(curtable or {}) do
local prefix = string.rep(" ", level * 5)
print(string.format("%s%s(%s)", prefix, key, type(value)))
if type(value) == "table" and key ~= "_G" and (not value.package) then
treaverse_global_env(value, level + 1)
elseif type(value) == "table" and value.package then
print(string.format("%sSKIPTABLE:%s", prefix, key))
end
end
end
treaverse_global_env(_G, 0)Lua 虛擬機本身不會強制使用 _G 這個變數。即使在腳本中重新指定 _G,已建立函數的執行環境仍可能保持原樣。透過 load 或 loadfile 建立 chunk 時,第一個 upvalue 通常就是全局環境,也可以被替換。
在 C 中,_G 是註冊的變數。lua_pushglobaltable 會把全局環境壓入棧。在 Lua 5.2 中,它實質是從註冊表取得全局環境:
#define lua_pushglobaltable(L) \
lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS)註冊表是 Lua 狀態機範圍內全局唯一的,因此全局環境也具有唯一性。