function newcounter () local i=0 returnfunction() i=i+1 return i endendC1=newcounter ()Print (C1 ())print(C1 ())
The above code output
Closure = function + reference environment. The Newcounter function in the preceding code returns a function, and the returned anonymous function is the function in the part of the closure, and the reference environment is the environment where the variable I resides. In fact, closures are just like functions in form and expression, but actually not functions, and we all know that functions are a combination of some executable statements that are determined after the function is defined and no longer executed, so the function has only one instance. While closures can have multiple instances at run time, different reference environments and the same combination of functions can produce different instances, just like the same class code, which can create different class instances. When you look at someone else's article, you see that the child function can use a local variable in the parent function, which is called a closure!
Functions can be defined in LUA functions, which are inline functions, which can access all local variables that an external function has already created, and these variables are called the upvalue,upvalue of the inline function actually refer to variables rather than values, which can be shared between internal functions. such as the following code:
functionfun1 ()LocalVal=Ten functionifunc1 ()Print(val)End functionIfunc2 () Val=val+Ten End returnIFUNC1,IFUNC2EndLocala,b=fun1 () A ()--Output TenB () A ()--Output
function mypower (x) return function (y) return y^x endendpower2=mypower (2) Power3 =mypower (3)print(Power2 (4))print( Power3 (5))
Closure summary in Lua