Lua 有一個特性就是默認定義的變量都是全局的。為了避免這一點,我們需要在定義變量時使用 local 關鍵字。
但難免會出現遺忘的情況,這時候出現的一些 bug 是很難查找的。所以我們可以采取一點小技巧,改變創建全局變量的方式。
-- 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
})
增加上面的代碼后,我們要再定義全局變量就會的得到一個錯誤信息。
但有時候全局變量是必須的,例如一些全局函數。我們可以使用新的定義方式:
-- 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"
新聞熱點
疑難解答