Lua Tutorial (10): Global variables and Non-global environment _lua

Source: Internet
Author: User
Tags lua

Lua saves all of its global variables in a regular table, which is called the "environment." It is saved in the global variable _g.

1. Global variable declaration:

Global variables in Lua do not need to be declared to be available. Although convenient, a clerical error can result in a difficult to find mistake. We can protect the reading and setting of global variables by giving _g table of Canadian dollars, thus reducing the chance of this clerical error. See the following sample code:

Copy Code code as follows:

--This table is used to store all declared global variable names
Local declarednames = {}
Local MT = {
__newindex = function (Table,name,value)
--Check to see if the new name has been declared, and if so, this is set directly through the Rawset function.
If not declarednames[name] Then
--Check if the operation is done in the main program or C code, and if so, continue to set up, or error.
Local w = debug.getinfo (2, "S"). What
If W ~= "main" and W ~= "C" Then
Error ("Attempt to write to undeclared variable".) Name
End
--Before the actual settings, update the Declarednames table, the next time you do not need to check the settings.
Declarednames[name] = True
End
Print ("Setting" ...). Name.. "To". Value
Rawset (Table,name,value)
End

__index = function (_,name)
If not declarednames[name] Then
Error ("Attempt to read undeclared variable".) Name
Else
Return Rawget (_,name)
End
End
}
Setmetatable (_G,MT)

A = 11
Local KK = AA

--The output result is:
--[[
Setting A to 11
Lua:d:/test.lua:21:attempt to read undeclared variable AA
Stack Traceback:
[C]: in function ' ERROR '
D:/test.lua:21:in function <d:/test.lua:19>
D:/test.lua:30:in main Chunk
[C]:?
--]]

2. Non-Global Environment:

The global environment has a rigid problem, that is, its modification affects all parts of the program. Lua 5 has made some improvements, with new features that enable each function to have its own independent global environment, and the closure function created by the function inherits the function's global variable table. Here we can change the environment of a function by using the SETFENV function, which takes two parameters, one is the function name and the other is the new environment table. The first parameter, in addition to the function name itself, can also be specified as a number to represent the number of layers in the current function call stack. The number 1 represents the current function, 2 represents its calling function, and so on. See the following code:

Copy Code code as follows:

A = 1
Setfenv (1,{})
Print (a)

--The output result is:
--[[
Lua:d:/test.lua:3: Attempt to call global ' print ' (a nil value)
Stack Traceback:
D:/test.lua:3: in main chunk
[C]:?
--]]

Why did you get such a result? Because print and variable A are all fields in the global table, and the new global table is empty, the print call will complain.

To deal with this side effect, we can have the existing global table _g as the internal table of the new global table, and when accessing existing global variables, you can go directly to the fields in _g, and for the new global field, remain in the new global table. This will not affect other places where global variables (_g) are used, even if they are incorrectly modified in the function. See the following code:

Copy Code code as follows:

A = 1
Local NEWGT = {}-New environment table
Setmetatable (Newgt,{__index = _g})
Setfenv (1,NEWGT)
Print (a)--Output 1

A = 10
Print (a)--output 10
Print (_G.A)--Output 1
_G.A = 20
Print (a)--output 10

The last example given is the inheritance of a function environment variable. See the following code:

Copy Code code as follows:

function Factory ()
return function () return a
End
A = 3
F1 = Factory ()
F2 = Factory ()
Print (F1 ())--Output 3
Print (F2 ())--Output 3

Setfenv (f1,{a = 10})
Print (F1 ())--Output 10
Print (F2 ())--Output 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.