Lua 有一個特性就是預設定義的變數都是全域的。為了避免這一點,我們需要在定義變數時使用 local 關鍵字。
但難免會出現遺忘的情況,這時候出現的一些 bug 是很難尋找的。所以我們可以採取一點小技巧,改變建立全域變數的方式。
複製代碼 代碼如下:
local __g = _G
-- export global variable
cc.exports = {}
setmetatable(cc.exports, {
__newindex = function(_, name, value)
rawset(__g, name, value)
end,
__index = function(_, name)
return rawget(__g, name)
end
})
-- disable create unexpected global variable
setmetatable(__g, {
__newindex = function(_, name, value)
local msg = "USE 'cc.exports.%s = value' INSTEAD OF SET GLOBAL VARIABLE"
error(string.format(msg, name), 0)
end
})
增加上面的代碼後,我們要再定義全域變數就會的得到一個錯誤資訊。
但有時候全域變數是必須的,例如一些全域函數。我們可以使用新的定義方式:
複製代碼 代碼如下:
-- export global
cc.exports.MY_GLOBAL = "hello"
-- use global
print(MY_GLOBAL)
-- or
print(_G.MY_GLOBAL)
-- or
print(cc.exports.MY_GLOBAL)
-- delete global
cc.exports.MY_GLOBAL = nil
-- global function
local function test_function_()
end
cc.exports.test_function = test_function_
-- if you set global variable, get an error
INVALID_GLOBAL = "no"