Lua Higher-Order Functions
A higher-order function takes a function as an argument or returns one. Lua's standard library doesn't include map or filter, but they are short to write, and you'll use the pattern all the time: table.sort takes a comparison function, string.gsub can take a replacement function, and game engines take callbacks.
map, filter and reduce
local function map(list, fn)
local out = {}
for i, v in ipairs(list) do out[i] = fn(v) end
return out
end
local function filter(list, pred)
local out = {}
for _, v in ipairs(list) do
if pred(v) then out[#out + 1] = v end
end
return out
end
local function reduce(list, fn, init)
local acc = init
for _, v in ipairs(list) do acc = fn(acc, v) end
return acc
end
local prices = { 12, 45, 7, 30, 18 }
local withTax = map(prices, function(p) return p * 1.2 end)
local cheap = filter(prices, function(p) return p < 20 end)
local total = reduce(prices, function(a, b) return a + b end, 0)
print(table.concat(withTax, " "))
print(table.concat(cheap, " "))
print(total)14.4 54.0 8.4 36.0 21.6
12 7 18
112
Anonymous functions inline
Functions without a name (function(x) … end) are written right where they are needed. A sort order is the classic case:
local players = {
{ name = "Ivy", score = 820 },
{ name = "Bo", score = 1340 },
{ name = "Cal", score = 820 },
{ name = "Dee", score = 990 },
}
table.sort(players, function(a, b)
if a.score ~= b.score then
return a.score > b.score -- highest score first
end
return a.name < b.name -- ties: alphabetical
end)
for rank, p in ipairs(players) do
print(rank, p.name, p.score)
end1 Bo 1340
2 Dee 990
3 Cal 820
4 Ivy 820
Functions that return functions
Combining functions creates new ones. compose(f, g) returns a function that applies g first, then f:
local function compose(f, g)
return function(...) return f(g(...)) end
end
local function trim(s) return (s:gsub("^%s+", ""):gsub("%s+quot;, "")) end
local shout = compose(string.upper, trim)
print("[" .. shout(" hello there ") .. "]")
local function partial(fn, first)
return function(...) return fn(first, ...) end
end
local add = function(a, b) return a + b end
local addTen = partial(add, 10)
print(addTen(5), addTen(-3))[HELLO THERE]
15 7
Callbacks
A callback is a function you hand to some code so that it can "call you back" later, for example when an event happens. This tiny event emitter is the core of many game and UI frameworks:
local Emitter = { handlers = {} }
function Emitter.on(event, fn)
Emitter.handlers[event] = Emitter.handlers[event] or {}
table.insert(Emitter.handlers[event], fn)
end
function Emitter.emit(event, ...)
for _, fn in ipairs(Emitter.handlers[event] or {}) do
fn(...)
end
end
Emitter.on("coin", function(amount) print("+" .. amount .. " coins") end)
Emitter.on("coin", function(amount) print("play sound: ding") end)
Emitter.on("hit", function(dmg, src) print("took " .. dmg .. " damage from " .. src) end)
Emitter.emit("coin", 5)
Emitter.emit("hit", 12, "slime")
Emitter.emit("jump") -- no handlers: nothing happens+5 coins
play sound: ding
took 12 damage from slime
gsub with a function
string.gsub calls a function for each match and uses its return value as the replacement. Returning nil or false keeps the original text:
local template = "Hello {name}, you have {count} new {thing}."
local values = { name = "Sam", count = 3 }
local result = template:gsub("{(%w+)}", function(key)
local v = values[key]
return v and tostring(v)
end)
print(result)Hello Sam, you have 3 new {thing}.
{thing} stays untouched because the function returned nil for it.
Test yourself
What makes a function "higher-order"?
- It is recursive
- It takes or returns a function
- It is global
- It has more than three parameters
What should the comparison function passed to table.sort return?
- -1, 0 or 1
trueif the first argument should come before the second- The smaller value
- A new table
In s:gsub(pattern, fn), what happens when fn returns nil?
- The match is deleted
- The original match is kept
- An error is raised
- The string becomes nil