Lua 用一个名为 environment 普通的表来保存所有的全局变量。
- for n in pairs(_G) do --打印所有全局变量的名字
- print(n)
- end
动态名字访问全局变量:
- function getfield(f)
- local v=_G --全局变量表
- for w in string.gfind(f,"[%w_]+") do
- v=v[w]
- end
- return v
- end
- function setfield(f,v)
- local t=_G --全局变量表
- for w,d in string.gfind(f,"([%w_]+)(.?)") do
- if d=="." then
- t[w]=t[w] or {} --创建一个表
- t=t[w] --获取表
- else
- t[w]=v
- end
- end
- end
- setfield("t.x.y",10)
- print(t.x.y)
- print(getfield("t.x.y"))
声明全局变量:
- setmetatable(
- _G,{
- _newindex=function(_,n)
- error("attempt to write to undeclared variable" .. n,2)
- end,
- _index=function(_,n)
- error("attempt to read undeclared variable " .. n,2)
- end
- }
- )
- function declare(name,initval)
- rawset(_G,name,initval or false)
- end
- if rawget(_G, var) == nil then
- print("Hello")
- end
- ------------------------------------------------------------------
- local declaredNames = {}
- function declare (name, initval)
- rawset(_G, name, initval)
- declaredNames[name] = true
- end
- setmetatable(_G, {
- __newindex = function (t, n, v)
- if not declaredNames[n] then
- error("attempt to write to undeclared var. "..n, 2)
- else
- rawset(t, n, v) -- do the actual set
- end
- end,
- __index = function (_, n)
- if not declaredNames[n] then
- error("attempt to read undeclared var. "..n, 2)
- else
- return nil
- end
- end,
- })
非全局的环境:
- a=1
- setfenv(1,{_G=_G})
- _G.print(a) --nil
- _G.print(_G.a) --1
- ------------------------------------------------------
- a = 1
- local newgt = {} -- create new environment
- setmetatable(newgt, {__index = _G})
- setfenv(1, newgt) -- set it
- print(a) --> 1
- ------------------------------------------------------
- a=10
- print(a) --10
- print(_G.a) --10
- _G.a=20
- print(_G.a) --20