One feature of Lua is that variables that are defined by default are global. To avoid this, we need to use the local keyword when defining variables.
But it is inevitable that there will be forgotten situations, at this time some bugs are difficult to find. So we can take a little trick to change the way we create global variables.
Copy Code code 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 then get an error message by defining the global variable.
But sometimes global variables are required, such as some global functions. We can use the new definition method:
Copy Code code 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 are set global variable, get an error
Invalid_global = "No"