Lua Functions as Values
A function is a value in Lua, just like a number or a string. It can sit in a variable, be passed into another function, or be handed back as a result.
An anonymous function in a variable
square holds a function with no name of its own. Calling the variable runs it, and 6 squared prints 36.
local square = function(x)
return x * x
end
print(square(6))Sorting descending with a comparator
table.sort gets a small function that returns a > b for each pair. The sorted list prints largest first, which proves the comparator was used.
local scores = {42, 87, 15, 63}
table.sort(scores, function(a, b) return a > b end)
for i, v in ipairs(scores) do
print(v)
endOne function, two different helpers
apply calls whatever function it is given. Passing double gives 10, and passing addTen gives 15, from the same input 5.
local function apply(f, x)
return f(x)
end
local double = function(n) return n * 2 end
local addTen = function(n) return n + 10 end
print(apply(double, 5))
print(apply(addTen, 5))Example
local function applyTwice(f, x)
return f(f(x))
end
local inc = function(n) return n + 1 end
print(applyTwice(inc, 10))Key points
- Anonymous: a function written without a name is an anonymous function.
- Store: local square = function(x) ... end keeps a function in a variable, ready to call.
- Pass: a function can be given to another function as one of its arguments.
- Return: a function can also hand back another function as its result.
- Comparator: table.sort can take a second argument, a comparison function that decides the order of two values.
- Descending: a comparator that returns a > b sorts the largest values first.
In this example, applyTwice receives the inc function and the number 10. The inner call turns 10 into 11, the outer call turns 11 into 12, and that final value is printed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In table.sort(scores, function(a, b) return a > b end), what does the comparator function return for one pair of values?