typestar

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

  1. map builds a new table by applying f slot by slot.
  2. filter appends with out[#out + 1] when the test passes.
  3. Anonymous functions inline the transforms at the call.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Closures, step 15 of 27 in Language basics.

← Previous Next →