I am learning Lua and have come across the concept of anonymous functions. It’s interesting but I was wondering what additional advantage it provides over non anonymous functions.
So If I have something like
function(a,b) return (a+b) end
The function is anonymous and if I have
function add(a,b) return (a+b) end
The function is non anonymous. The second is better because I can call it wherever I want and I also know what my function is doing. So what’s the advantage of anonymous functions? Am I missing something here?
To be honest, there is no such thing as a named function in Lua. All functions are actually anonymous, but can be stored in variables (which have a name).
The named function syntax
function add(a,b) return a+b endis actually a syntactic sugar foradd = function(a,b) return a+b end.Functions are often used as event handlers and for decisions which a library does not/cannot know, the most famous example being
table.sort()– using your function, you can specify the sorting order:The point is that most probably you won’t need the function later. Of course, you can also save the function to a (possibly local) variable and use that:
For more information, read this section on functions in PiL.