If a function is written in another function, the internal function can access local variables in the external function. This feature is called a lexical domain.
Function newcounter ()
Local I = 0
Return function ()
I = I + 1
Return I
End
End
C1 = newcounter ()
Print (C1 ())
Print (C1 ())
C2 = newcounter ()
Print (C2 ())
Print (C2 ())
Print (C1 ())
A closure is all the non-local variables that a function needs to access. If newcounter is called again, it creates a new local variable I to get a new clousre.
Technically speaking, Lua only has closure, and no function exists. Because the function itself is a special closure, as long as it does not cause confusion, it will still use a glossary to refer to closure.
Closure is a valuable tool in many cases. As we can see before, they can be used as parameters of higher-order functions such as sort. Closure is also useful for functions that create other functions. For example, newcounter. This mechanism allows Lua programs to mix proven programming technologies in the functional programming world. In addition, closure is also useful for callback functions. Here is a typical example. A traditional GUI toolkit can be used to create buttons. Each button has a callback function.
Function digitbutton (DIGIT)
Return button {label = tostring (DIGIT ),
Action = function ()
Add_to_display (DIGIT)
End}
End
Closure is also very useful in another scenario. For example, in Lua, the function is stored in a common variable, so you can easily redefine some functions, you can even redefine the predefined functions. This is one of the reasons why Lua is quite flexible. When you redefine a function, you need to call the original function in the new implementation. For example, if you want to redefine the sin function so that its parameters can use degrees to replace the original radians, then the new function needs to convert its real parameters, and call the original sin function to complete the real computation. This code may be like this:
Oldsin = math. Sin
Math. Sin = function (X)
Return oldsin (x * Math. PI/180)
End
Do
Local oldsin = math. Sin
Local K = math. PI/180
Math. Sin = function (X)
Return oldsin (x * K)
End
End
Lua Closure Function