Lua中建立全域變數的小技巧(禁止未預期的全域變數)_Lua

來源:互聯網
上載者:User

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"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.