全局变量不需要声明,虽然这对一些小程序来说很方便,但程序很大时,一个简单的拼写错误可能引起bug并且很难发现。然而,如果我们喜欢,我们可以改变这种行为。因为Lua所有的全局变量都保存在一个普通的表中,我们可以使用metatables来改变访问全局变量的行为。
第一个方法如下:
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,
})
这样一来,任何企图访问一个不存在的全局变量的操作都会引起错误:
> a = 1
stdin:1: attempt to write to undeclared variable a

本文介绍了如何通过设置元表来限制Lua全局变量的访问,并在尝试访问未声明的变量时引发错误,以此提高代码的安全性和健壮性。
1万+

被折叠的 条评论
为什么被折叠?



