Quirrel4.41.0

types.Table.filter

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

Returns a new table holding only the slots for which callback returns a truthy result.

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]), tested against every slot

Return value

A new table with the same key and value as the original for every slot that passed the test; callback's return value only decides membership, it never replaces the value the way map's does.

Errors

Whatever callback throws propagates out of filter - unlike map, filter has no special case for throw null; any thrown value, including null, 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.

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

Example

examples/types/table/filter.nut
let t = {a=1, b=2, c=3, d=4}
let evens = t.filter(function(v) { return v % 2 == 0 })
println("evens.len() =", evens.len())      // only "b" and "d" passed the test
println("evens.b =", evens.b)          // the original value is kept, not the callback's

println("t.len() =", t.len())          // the original table is unchanged

// unlike map, filter has no special case for throw null - it aborts
try {
  t.filter(function(v) { if (v == 2) throw null; return true })
} catch (e) {
  println("caught e == null:", e == null)
}
Output:
evens.len() = 2
evens.b = 2
t.len() = 4
caught e == null: true

See also

mapReturns a new table with the same keys, each mapped through callback.
eachCalls callback once for every slot in the table.
findvalueReturns the first value for which callback returns a truthy result.
tableclass index