0Pricing
Lua Academy · Lesson

Transforming Tables: map, filter, reduce

Build functional higher-order helpers for table transformation.

Functional Patterns in Lua

Lua has no built-in map/filter/reduce, but they are trivial to implement using closures and generic for loops.

map: Transform Every Element

map applies a function to each element and returns a new table of results.

local function map(t, fn)
  local result = {}
  for i, v in ipairs(t) do result[i] = fn(v) end
  return result
end
local doubled = map({1,2,3}, function(x) return x * 2 end)
print(table.concat(doubled, ", "))  -- 2, 4, 6

All lessons in this course

  1. table.sort with Comparators
  2. table.concat and table.move
  3. Deep Copy and Shallow Copy
  4. Transforming Tables: map, filter, reduce
← Back to Lua Academy