Quirrel4.41.0

types.Array.findvalue

Method on every array
pure array.findvalue(predicate: function, [default_value], ...): any

Finds the first element for which predicate returns a true value.

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

predicatefunctionpredicate(value, [index], [array]), tested against each element, in order
default_valueanyreturned when nothing matches, instead of null optional
...any repeats

Return value

The first matching element; default_value if nothing matched and it was given; null if nothing matched and it was not.

Errors

Whatever predicate throws, on the first element where it throws.

Throws Too many arguments for findvalue() when called with a third real argument. Unlike slice or sort, which silently ignore arguments past what they use, findvalue treats one as a mistake, since a value beyond default_value cannot mean anything.

Notes

predicate gets exactly as many of the arguments listed above as it declares parameters for, and never more.

Example

examples/types/array/findvalue.nut
let a = [10, 20, 30];
println("a.findvalue(v > 15) =", a.findvalue(function(v) { return v > 15 }));
println("a.findvalue(v > 999) =", a.findvalue(function(v) { return v > 999 }));         // not found, no default
println("a.findvalue(v > 999, -1) =", a.findvalue(function(v) { return v > 999 }, -1));     // not found, default given

try { a.findvalue(function(v) { return true }, 1, 2) }
catch (e) { println("a.findvalue(..., 1, 2) throws:", e); }   // a third real argument is one too many
Output:
a.findvalue(v > 15) = 20
a.findvalue(v > 999) = null
a.findvalue(v > 999, -1) = -1
a.findvalue(..., 1, 2) throws: Too many arguments for findvalue()

See also

findindexFinds the index of the first element for which callback returns a true value.
filterCollects the elements for which callback returns a true value.
arrayclass index