Quirrel4.41.0

types.Table.map

Method on every table
table.map(callback: function): any

Returns a new table with the same keys, each mapped through callback.

The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing ... from the prose below, not from the signature.

Parameters

callbackfunctioncallback(value, [key], [table]), called for every slot; its return value becomes the new value for that key

Return value

A new table, same keys as the original, each value replaced by callback's return value for that slot.

Errors

Whatever callback throws propagates out of map, with one exception: a callback that does throw null for a given slot is not an error here - that slot is silently left out of the result table instead of being mapped. Throwing anything else still aborts the call.

Notes

Takes exactly one argument, callback.

callback gets exactly as many of the arguments listed above as it declares parameters for, and never more - the same rule as each; table is the original, before any slot is replaced.

The result is always a new table; the original is never modified.

Example

examples/types/table/map.nut
let t = {a=1, b=2, c=3}
let doubled = t.map(function(v) { return v * 2 })
println("doubled.a =", doubled.a, "doubled.b =", doubled.b, "doubled.c =", doubled.c)
println("t.a =", t.a)                     // the original table is unchanged

// throw null inside the callback skips that slot instead of aborting
let skipped = t.map(function(v) { if (v == 2) throw null; return v })
println("skipped.len() =", skipped.len())         // "b" is missing, the others made it through
println("skipped.rawin(\"b\") =", skipped.rawin("b"))
Output:
doubled.a = 2 doubled.b = 4 doubled.c = 6
t.a = 1
skipped.len() = 2
skipped.rawin("b") = false

See also

filterReturns a new table holding only the slots for which callback returns a truthy result.
eachCalls callback once for every slot in the table.
reduceCombines every value in the table into one result by calling callback repeatedly.
tableclass index