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)文章
Lua中調(diào)用函數(shù)使用點號和冒號的區(qū)別
這篇文章主要介紹了Lua中調(diào)用函數(shù)使用點號和冒號的區(qū)別,本文涉及了Lua中面向?qū)ο蟮囊恍┑闹R,并給出了一個簡單的類代碼實例,需要的朋友可以參考下2014-09-09