查找全局变量
方法一
setmetatable(_G, {
__newindex = function (_, k)
error("Attempt to write to undeclared variable " .. k)
end,
__index = function (_, k)
error("Attempt to read undeclared variable " .. k)
end
})
--测试
a = 1
print(b)
方法二 tolua框架里有一个strict.lua文件专门用来判断未声明就使用的变量,引用了也不起作用的原因是判断条件不满足,这个自己研究一下if 语句的内容,把if语句注释掉肯定起作用。
方法三:这个是从网上其他博主那抄过来的,这个用法和strict.lua很像,判断条件变了一下。
local mt = {
__index = function(_, key)
local info = debug.getinfo(2, "S")
if info and info.what ~= "main" and info.what ~= "C" then
print("访问不存在的全局变量:" .. key)
end
return rawget(_G, key)
end,
__newindex = function(_, key, value)
local info = debug.getinfo(2, "S")
if info and info.what ~= "main" and info.what ~= "C" then
print("赋值不存在的全局变量:" .. key)
end
return rawset(_G, key, value)
end
}
setmetatable(_G, mt)
--测试
a = 1
print(b)
关键字和全局变量重名了如何查找
实现面向对象