Tips for creating global variables in Lua (forbid unexpected global variables)

Time:2022-6-11

Lua has a feature that the variables defined by default are global. To avoid this, we need to use the local keyword when defining variables.

However, it is inevitable that there will be forgetting. It is difficult to find some bugs at this time. So we can use a little trick to change the way we create global variables.

 

Copy codeThe codes are as follows:


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
})

 

After adding the above code, we will get an error message if we want to define the global variable again.

But sometimes global variables are necessary, such as some global functions. We can use a new definition:

 

Copy codeThe codes are as follows:


— 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”