types.Table.reduce
Combines every value in the table into one result by calling callback repeatedly.
... from the prose below, not from the signature.Parameters
callback | function | callback(accum, value, [key], [table]), called for every slot; its return value becomes the next accum |
... | any | repeats |
Return value
The final accum. On an empty table with no initial value, returns nothing (null) without calling callback. On a table with exactly one slot and no initial value, returns that slot's value directly, again without calling callback.
Errors
Whatever callback throws propagates out of reduce.
Notes
Takes 1 required argument (callback) plus 1 truly optional one: an initial value for accum. The VM-reported signature is reduce(arg1: function, ...) - the optional initial value has no placeholder of its own, it is absorbed into the trailing ..., so the signature undercounts the real parameter list rather than mislabeling it (contrast findvalue, whose optional parameter at least gets its own bracketed placeholder). Only the callback name comes from this page's front matter for that reason.
Anything passed after the initial value is silently ignored rather than rejected - t.reduce(f, 1, "extra") does not throw, unlike findvalue's explicit check for too many arguments.
Without an initial value, the first slot's value seeds accum and callback is not called for it - callback only runs for the second slot onward. With an initial value, callback runs once per slot, from the first.
callback gets exactly as many of the arguments listed above as it declares parameters for, and never more - one more than map's callback, because accum comes first.
Example
let t = {a=1, b=2, c=3}
println("t.reduce(add), no initial =", t.reduce(function(acc, v) { return acc + v }))
println("t.reduce(add), initial 100 =", t.reduce(function(acc, v) { return acc + v }, 100))
let one = {a=42}
local calls = 0
println("one.reduce(add) =", one.reduce(function(acc, v) { calls++; return acc + v }))
println("calls =", calls) // a single slot short-circuits: callback never runs
println("{}.reduce(add) == null:", {}.reduce(function(acc, v) { return acc + v }) == null)
// extra arguments beyond the initial value are accepted and ignored
println("t.reduce(add, 0, \"unused\") =", t.reduce(function(acc, v) { return acc + v }, 0, "unused"))t.reduce(add), no initial = 6
t.reduce(add), initial 100 = 106
one.reduce(add) = 42
calls = 0
{}.reduce(add) == null: true
t.reduce(add, 0, "unused") = 6See also
map | Returns a new table with the same keys, each mapped through callback. |
findvalue | Returns the first value for which callback returns a truthy result. |
each | Calls callback once for every slot in the table. |
| table | class index |