0Pricing
Lua Academy · Lesson

map, filter, reduce

Build higher-order helpers.

The Big Three

Map, filter, and reduce are the core tools of functional list processing. Each takes a list and a function, and returns a result without you writing the loop by hand.

Lua does not ship them built in, but they are short to write and reveal how higher-order functions work.

Map: Transform Each Item

Map applies a function to every element and collects the results into a new list. The original list is left unchanged.

The function you pass decides the transformation, so one map handles doubling, squaring, or any per-item change.

local function map(t, f)
  local out = {}
  for i, v in ipairs(t) do
    out[i] = f(v)
  end
  return out
end

local r = map({1, 2, 3}, function(x) return x * x end)
print(table.concat(r, ", "))

All lessons in this course

  1. Functions as Values
  2. map, filter, reduce
  3. Partial Application
  4. Composing Functions
← Back to Lua Academy