Higher-order functions in Lua
map and filter are three-line helpers over ipairs.
-- Higher-order helpers are three lines each in Lua.
local function map(t, f)
local out = {}
for i, v in ipairs(t) do out[i] = f(v) end
return out
end
local function filter(t, keep)
local out = {}
for _, v in ipairs(t) do
if keep(v) then out[#out + 1] = v end
end
return out
end
local hauls = { 12, 45, 3, 78, 22 }
local doubled = map(hauls, function(g) return g * 2 end)
print(table.concat(doubled, " "))
local rich = filter(hauls, function(g) return g > 20 end)
print("Big hauls: " .. table.concat(rich, ", "))
How it works
mapbuilds a new table by applyingfslot by slot.filterappends without[#out + 1]when the test passes.- Anonymous functions inline the transforms at the call.
Keywords and builtins used here
doendffilterforfunctionifinipairskeeplocalmapprintreturnthen
The run, in numbers
- Lines
- 20
- Characters to type
- 514
- Tokens
- 149
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 138 seconds.
Step 2 of 3 in Closures, step 15 of 27 in Language basics.