Before the closure of a smattering of knowledge, on the internet can not find an article to make it clear, today seems like the first time to it a little clear understanding, write a blog to remember
The LUA function is a first-class Value thing, what is it?
Is that they are no different from the traditional type of change.
Can be stored in a variable,
Can be stored in a table,
can be passed as arguments to other functions,
Can be a return value for another function.
They also have a specific lexical domain (lexical scoping), in other words, a function can be nested within another function, and internal functions can access variables in external functions.
As in the following example:
Copy Code code as follows:
function test (x)
return function (value)
return value * x
End
End
Func = Test (10)
Print (func (11))
In Test (), an anonymous function is nested as the return value, and an external value variable can be accessed in this anonymous function
Let's look at another example.
Copy Code code as follows:
function Newcounter ()
Local i = 0
Func = function ()
i = i + 1
return I
End
return func
End
c = Newcounter ()
Print (c ())
Print (c ())
C1 = Newcounter ()
Print (C1 ())
Print (C1 ())
In the code, a "non-local variable" I is accessed in the function Func to hold a counter
Initially, because the function newcounter that created the variable i has been returned, each call to Func should be more than the scope
In fact, LUA deals with this situation with a closure concept.
A closure is a function plus all the "nonlocal variables" that the function needs to access.
So in the example above C1, C2 is the two different closure created by the same function, each owning a separate instance of the local variable i.
Technically, there is only closure in Lua, and there is no "function". Because "function" itself is a special kind of closure.
PostScript, C + + class objects can not also achieve similar effects?