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, 6All lessons in this course
- table.sort with Comparators
- table.concat and table.move
- Deep Copy and Shallow Copy
- Transforming Tables: map, filter, reduce