The difference between a closure and an anonymous function has to do with the concept of upvalues. The idea being that the returned function has access to the variable ‘param’ from an entirely different scope relative to where it’s called from. Some languages allow you to maintain the reference scope from where it was declared, and not from where it’s being called from, C# and Lua being the two I’m most familiar with. That and metamethods are probably my two favourite Lua features that help make it stand above most other interpreted languages.
There is one other Closure helper function I use a lot:
function generateCommand(func, ...)
local temp = {n=select('#', ...), ...}
return function()
return func(unpack(temp, 1, temp.n))
end
end
This one allows you to attach as many parameters as you want to be invoked later. i.e. generateCommand(print, “This”, “is”, “a”, “Test”) will give you a parameterless function that when invoked will call print(“This”, “is”, “a”, “Test”). The downside to this one is that it won’t accept any parameters later, meaning that to use this instead would mean you’d lose the event from a Corona Event. temp is a single upvalue that stores all parameters in a table (and n, being the number of parameters stored, otherwise a nil in the middle of the parameters would break it), and is accessible to the returned function (and only the returned function, effectively) regardless of where it is invoked.
edit: in the previous wrapParam example, the fact that you can access func and param inside of function(…) is the unique part, since that function, and stack memory are long gone by the time you call the function. Those two variables are accessible to the function variable for it’s entire lifetime. If you want to get very tricky, we do a few instances in our own code with hand offs, where a chain of functions pass their upvalues (usually callbacks at the end of the chain) down the chain of function calls, which means that 5 anonymous function calls later you can still access variables given to you in the first function call, without actually having to store them anywhere (each new function declaration can access the upvalue if it’s within the scope the function was declared in). It helps us write very little code for sometimes very complex sequential actions. [import]uid: 134101 topic_id: 33208 reply_id: 131965[/import]