Lua中创建全局变量的小技巧(禁止未预期的全局变量)
Lua有一个特性就是默认定义的变量都是全局的。为了避免这一点,我们需要在定义变量时使用local关键字。
但难免会出现遗忘的情况,这时候出现的一些bug是很难查找的。所以我们可以采取一点小技巧,改变创建全局变量的方式。
local__g=_G
--exportglobalvariable cc.exports={} setmetatable(cc.exports,{ __newindex=function(_,name,value) rawset(__g,name,value) end,
__index=function(_,name) returnrawget(__g,name) end })
--disablecreateunexpectedglobalvariable setmetatable(__g,{ __newindex=function(_,name,value) localmsg="USE'cc.exports.%s=value'INSTEADOFSETGLOBALVARIABLE" error(string.format(msg,name),0) end })