Anonymous and Anonymous Lua Functions

I am learning Lua and came across the concept of anonymous functions. This is 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 not anonymous. The second is better, because I can name it wherever I want, and also know what my function does. So what is the advantage of anonymous functions? Did I miss something?

+6
source share
2 answers

To be honest, Lua doesn't have a function like a named function. 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 end is actually the syntactic sugar for add = function(a,b) return a+b end .

Functions are often used as event handlers and for solutions that the library does not know / cannot know, the most famous example is table.sort() - with your function you can specify the sort order:

 people = {{name="John", age=20}, {name="Ann", age=25}} table.sort(people, function (a,b) return a.name < b.name end) 

The fact is that, most likely, you will not need a function later. Of course, you can also save the function in a (possibly local) variable and use it:

 local nameComparator = function (a,b) return a.name < b.name end table.sort(people, nameComparator) 

For more information, read the section on functions in PiL .

+20
source

The second example is equivalent to add = function(a,b) return a+b end
So you use anonymous functions all the time in a trivial sense.

But anonymous functions can become much more useful in other contexts. For example, using functions to change other functions (the soul of functional programming.)

 function make_version_with_n_args (func, n) if n == 1 then return function (x) return x end else return function (x, ...) return func (x, make_version_with_n_args (func, n-1)(...)) end end end add_four = make_version_with_n_args (function (a, b) return a+b end, 4) print (add_four(3, 3, 3, 3)) add_sizes = {} for i = 1, 5 do add_sizes[i] = make_version_with_n_args(function (a, b) return a+b end, i) end func_args = {} for i = 1, 5 do func_args[#func_args+1] = 2 print (add_sizes[i](unpack(func_args))) end function make_general_version (func) return function (...) local args = {...} local result = args[#args] for i = #args-1,1,-1 do result = func(args[i], result) end return result end end general_add = make_general_version (function (a, b) return a+b end) print (general_add(4, 4, 4, 4)) 

Basically, you can create a name for each individual function if you want, but in situations where you drop so many one-time functions, it’s more convenient not to do this.

+4
source

Source: https://habr.com/ru/post/901550/


All Articles