Lua中創(chuàng)建全局變量的小技巧(禁止未預(yù)期的全局變量)
Lua 有一個特性就是默認定義的變量都是全局的。為了避免這一點,我們需要在定義變量時使用 local 關(guān)鍵字。
但難免會出現(xiàn)遺忘的情況,這時候出現(xiàn)的一些 bug 是很難查找的。所以我們可以采取一點小技巧,改變創(chuàng)建全局變量的方式。
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
})
增加上面的代碼后,我們要再定義全局變量就會的得到一個錯誤信息。
但有時候全局變量是必須的,例如一些全局函數(shù)。我們可以使用新的定義方式:
-- 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"
相關(guān)文章
實現(xiàn)Lua中數(shù)據(jù)類型的源碼分享
在Lua中有8種基礎(chǔ)類型,像其他動態(tài)語言一樣,在語言中沒有類型定義的語法,每個值都攜帶了它自身的類型信息。下面我們就來嘗試通過Lua 5.2.1的源碼來看類型的實現(xiàn)2015-04-04

