July 2017
Intermediate to advanced
284 pages
6h 45m
English
We had to define our own map() earlier, which we’ll use again in a minute. Let’s define a few more functional primitives that we can arrange into bigger and better things:
| | function each (things, fn) |
| | for i, thing in ipairs(things) do |
| | fn(thing) |
| | end |
| | end |
| | function filter (things, fn) |
| | local filtered = {} |
| | each(things, function(thing) |
| | if fn(thing) then |
| | table.insert(filtered, thing) |
| | end |
| | end) |
| | return filtered |
| | end |
| | function cons (things, ...) |
| | local all = {} |
| | each({...}, function(t) |
| | table.insert(all, t) |
| | end) |
| | each(things, function(t) |
| | table.insert(all, t) |
| | end) |
| | return all |
| | end |
I should point out that all of these are relatively slow, because they copy elements between Lua tables. We ...
Read now
Unlock full access