0Pricing
Lua Academy · Lesson

map, filter, reduce

Build higher-order helpers.

map, filter, reduce is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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, ", "))

Map Keeps Length

A map always returns a list with the same number of elements as the input. Every item maps to exactly one output item.

If you need to drop items, that is the job of filter, not map.

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

local names = {"ada", "lin", "sam"}
local caps = map(names, string.upper)
print(table.concat(caps, " "))
print(#caps)

Filter: Keep Some Items

Filter keeps only the elements for which a predicate returns true. A predicate is a function that returns a boolean.

The result is a new list that may be shorter than the original, but never longer.

local function filter(t, pred)
  local out = {}
  for _, v in ipairs(t) do
    if pred(v) then out[#out + 1] = v end
  end
  return out
end

local evens = filter({1,2,3,4,5,6}, function(x) return x % 2 == 0 end)
print(table.concat(evens, ", "))

Filter Preserves Order

Filter walks the list in order and appends each kept item, so the surviving elements stay in their original sequence.

Using #out + 1 as the index keeps the result a gap-free array, which Lua treats as a proper sequence.

local function filter(t, pred)
  local out = {}
  for _, v in ipairs(t) do
    if pred(v) then out[#out + 1] = v end
  end
  return out
end

local long = filter({"hi", "hello", "yo", "howdy"},
  function(s) return #s > 2 end)
print(table.concat(long, ", "))

Reduce: Combine Into One

Reduce (also called fold) collapses a list into a single value. It carries an accumulator and combines it with each element using your function.

You supply a starting value and a combining function, and reduce threads the accumulator through every item.

local function reduce(t, f, acc)
  for _, v in ipairs(t) do
    acc = f(acc, v)
  end
  return acc
end

local sum = reduce({1,2,3,4}, function(a, x) return a + x end, 0)
print(sum)

Reduce Is Flexible

By changing the combining function and starting value, reduce can sum, multiply, find a maximum, or build a string.

Here the accumulator starts at 1 and multiplies, producing a factorial-style product.

local function reduce(t, f, acc)
  for _, v in ipairs(t) do acc = f(acc, v) end
  return acc
end

local product = reduce({1,2,3,4,5}, function(a, x) return a * x end, 1)
print(product)

Reduce to a Maximum

Reduce is not limited to arithmetic. The combiner can compare values and keep the larger one each step.

Starting the accumulator at the first element, or at a very small number, lets reduce find a maximum cleanly.

local function reduce(t, f, acc)
  for _, v in ipairs(t) do acc = f(acc, v) end
  return acc
end

local max = reduce({3, 8, 2, 11, 6},
  function(a, x) if x > a then return x else return a end end, -math.huge)
print(max)

Chaining Them Together

The real power appears when you chain the three. Filter narrows the data, map transforms it, and reduce summarizes it.

Each stage is a small, clear step, and together they replace a tangled manual loop.

local function filter(t, p) local o={} for _,v in ipairs(t) do if p(v) then o[#o+1]=v end end return o end
local function map(t, f) local o={} for i,v in ipairs(t) do o[i]=f(v) end return o end
local function reduce(t, f, a) for _,v in ipairs(t) do a=f(a,v) end return a end

local nums = {1,2,3,4,5,6}
local r = reduce(map(filter(nums, function(x) return x%2==0 end),
  function(x) return x*x end), function(a,x) return a+x end, 0)
print(r)

Originals Stay Safe

Map and filter always build new tables and never mutate the input. This makes pipelines predictable: earlier data is still available after each stage.

Reduce also leaves the list untouched, returning only the combined result.

Generic Over Any List

Because the function is a parameter, these tools work on any data. The same map uppercases strings, scales prices, or formats records.

Writing the loop once and passing different functions is exactly why first-class functions are so useful.

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

local prices = {10, 20, 30}
local withTax = map(prices, function(p) return p * 1.18 end)
print(table.concat(withTax, ", "))

Quick Check

Think about how these operations affect list length.

Recap

Map transforms each item and keeps length, filter keeps items passing a predicate, and reduce folds a list into one value with an accumulator.

Chaining filter, map, and reduce builds clear data pipelines without manual loops, and the original tables stay unchanged.

Frequently asked questions

Is the “map, filter, reduce” lesson free?

Yes — the full text of “map, filter, reduce” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “map, filter, reduce”?

Build higher-order helpers. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “map, filter, reduce” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

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