What are closures?
A lot of the power of functions in Lua comes from closures. It helps to think of functions as dynamically-created objects, like tables. Consider this function which returns a function:
function count()
local i = 0
return function()
i = i + 1
return i
end end
Each time it is called, it returns a new closure.
> c1 = count()
> = c1()
1
> = c1()
2
> c2 = count()
> = c2()
1
> = c1()
3
For this to work, the variable i
must be treated specially. If all the functions returned shared the same variable, then they would always return the next shared value of i
. Instead, each function keeps its own copy of i
- this variable is said to be an upvalue of the function. So one definition of closure is that it is a function plus any upvalues. This means something important: functions (like objects) can encapsulate state. This is one reason why the lack of a formal class concept is not seriously missed in Lua.
It allows for functional-style programming. Consider creating a new function with the first argument bound to some value (called partial function application)
function bind1(val,f)
return function(...)
return f(val,...)
end end
...
> print1 = bind1('hello',print)
> print1(10,20)
hello 10 20
Again, f
and val
are upvalues; every new call to bind1
generates a new closure with its own references to f
and val
.