July 2018
Beginner
202 pages
5h 42m
English
Closures capture the enclosing state of a chunk. A great example of this is having a function that returns an anonymous function. The anonymous function can see the local variables of the enclosing function. However, because the anonymous function is returned, it can outlive the existing function.
When returning an anonymous function, it creates a closure. This closure captures its enclosing state (visible chunks). This mechanism lets you access the state of the enclosing function, even though that function is no longer executing. This description may sound confusing, but the code for it is pretty straightforward:
function NextNumber() -- local to the NextNumber function local currentNumber = 0 return function () -- anonymous function ...