全局变量保存在_G表中。
全局变量不需要声明,对小的程序很方便。当程序很大时,可能会导致很难发现的bug.
方法1:
function declare(name, initval )
rawset(_G, name, initval or false) --rawset是会绕过metamethod的
end
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,
})
--测试
declare("a")
a = 1
print(a)
方法2:允许全局变量可以为nil
local declareNames = {}
function declare(name, initval)
rawset(_G, name, initval)
declareNames[name] = true
end
setmetatable(_G, {
__newindex = function(t, n, v)
if not declareNames[n] then
error("attempt to write to undeclared var."..n,2)
else
rawset(t, n, v)
end
end,
__index = function (_, n)
print("attempt to read n")
if not declareNames[n]