Nyx by Example

Arrays

Arrays in Nyx are dynamic, ordered collections that grow automatically. You can create them with a literal syntax, access elements by index, append with push, and iterate with for-in.

Code

// Arrays: crear, push, length, acceso por índice, iterar

fn main() -> int {
    // Crear array literal
    let numeros: Array = [10, 20, 30]

    // Acceso por índice
    print("primer: " + int_to_string(numeros[0]))
    print("ultimo: " + int_to_string(numeros[2]))

    // length
    print("longitud: " + int_to_string(numeros.length()))

    // Array mutable con push
    var lista: Array = [1, 2, 3]
    lista.push(4)
    lista.push(5)
    print("tras push, longitud: " + int_to_string(lista.length()))

    // Iterar con for-in
    print("elementos:")
    for n: int in lista {
        print("  " + int_to_string(n))
    }

    // Modificar elemento
    lista[0] = 99
    print("lista[0] tras modificar: " + int_to_string(lista[0]))

    return 0
}

Output

primer: 10
ultimo: 30
longitud: 3
tras push, longitud: 5
elementos:
  1
  2
  3
  4
  5
lista[0] tras modificar: 99

Explanation

Array literals use square brackets: [10, 20, 30]. Elements are zero-indexed, so arr[0] is the first element and arr[arr.length() - 1] is the last. Accessing an out-of-bounds index is a runtime error.

The .length() method returns the number of elements currently in the array as an int. The .push(value) method appends a new element to the end, growing the array automatically — no manual resizing needed.

When iterating with for n: int in lista, the type annotation : int tells the compiler what type to expect for each element. This is optional when the compiler can infer it, but being explicit avoids ambiguity with heterogeneous arrays.

Element assignment (lista[0] = 99) requires the array to be declared with var, not let. A let array cannot be mutated after creation.

← Previous Next →

Source: examples/by-example/05-arrays.nx