Quirrel4.41.0

types.Array.hasindex

Method on every array
pure array.hasindex(index: number): any

Reports whether index is a valid element index.

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

indexnumberthe index to check

Return value

true when 0 <= index < len(), false otherwise, including for a negative index.

Notes

hasindex never throws, even for a far out-of-range index; indexing the array directly does, with the index '<value>' (type='integer') does not exist. Check with hasindex first when an out-of-range index is expected rather than exceptional.

Unlike slice and swap, a negative index here is not counted back from the end; it is out of range.

Example

examples/types/array/hasindex.nut
let a = [1, 2, 3];
println("a.hasindex(0) =", a.hasindex(0));
println("a.hasindex(2) =", a.hasindex(2));
println("a.hasindex(3) =", a.hasindex(3));
println("a.hasindex(-1) =", a.hasindex(-1));

// contrast with plain indexing, which throws instead of returning false
try { let x = a[3]; } catch (e) { println("a[3] throws:", e); }
Output:
a.hasindex(0) = true
a.hasindex(2) = true
a.hasindex(3) = false
a.hasindex(-1) = false
a[3] throws: the index '3' (type='integer') does not exist

See also

hasvalueReports whether any element equals value.
lenReturns the number of elements in the array.
arrayclass index