Quirrel4.41.0

array

Global, available without an import
array(size: int, [default_value]): array

Creates an array of size elements, each set to default_value.

examples/globals/array-basic.nut
let squad = array(3, "recruit")

println("squad[0] =", squad[0])
println("squad[2] =", squad[2])
Output:
squad[0] = recruit
squad[2] = recruit

Parameters

sizeintnumber of elements
default_valueanyvalue stored in every element optional

Return value

The new array.

Errors

Throws array size must be non-negative when size is negative.

Notes

default_value fills every element as is, not a fresh copy per element: if it is a table or array, every element aliases the same object, and a change through one element shows up in all of them. Fill the array in a loop instead when the elements must be independent.

When default_value is left out, every element is null.

Example

examples/globals/array.nut
let a = array(3)
println("type(a[0]) =", type(a[0]))     // fill value when none is given

let b = array(3, 0)
b[1] = 9
println("b[0] =", b[0])
println("b[1] =", b[1])
println("b[2] =", b[2])

// default_value is stored as is, not cloned per slot
let c = array(2, {n = 0})
c[0].n = 5
println("c[1].n =", c[1].n)

try { array(-1) } catch (e) { println("array(-1) throws:", e) }
Output:
type(a[0]) = null
b[0] = 0
b[1] = 9
b[2] = 0
c[1].n = 5
array(-1) throws: array size must be non-negative

See also

freezeReturns a reference to obj with the immutable flag set.
resizeGrows or shrinks the array to size elements.
globalsmodule index