I had only a little understanding of closure before, and I couldn't find an article online to explain it clearly. Today, I think I have a clear understanding of it for the first time. I will write a BLOG to remember it.
Lua's function is a First-Class Value thing, what exactly is it?
They are no different from traditional types of variable values.
Can be stored in a variable,
Can be saved to the table,
Can be passed as an actual parameter to other functions,
Can be used as the return value of other functions.
They also have specific lexical domains (Lexical Scoping), that is, one function can be nested in another function, and the inner function can access variables in the external function.
As in the following example:
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 in this anonymous function, external value variables can be accessed
Look at another example
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, which is used to save a counter
Initial view, since the function newCounter that creates the variable i has returned, every time func is called, it should exceed the scope of action.
In fact, lua will handle this situation with the concept of closure.
A closure is a function plus all "non-local variables" that the function needs to access
So in the above example, c1 and c2 are two different closures created by the same function, each of which has independent instances of the local variable i.
Technically speaking, there is only closure in lua, but no "function" exists. Because "function" itself is a special closure.
Postscript: Can C++ class objects also achieve similar effects?