Nyx by Example

Control Flow

Nyx provides the standard set of control flow constructs: conditional branches with if/else if/else, counter loops with while, and iteration with for over ranges and collections. Loop control uses break and continue.

Code

// Control de flujo: if/else, while, for con range, break y continue

fn main() -> int {
    // if / else if / else
    let x: int = 7
    if x > 10 {
        print("mayor que 10")
    } else if x > 5 {
        print("entre 5 y 10")
    } else {
        print("5 o menos")
    }

    // while que cuenta del 1 al 5
    var i: int = 1
    while i <= 5 {
        print("while: " + int_to_string(i))
        i = i + 1
    }

    // for con range (0..5 excluye el 5)
    for n in 0..5 {
        print("range: " + int_to_string(n))
    }

    // for con array
    let colores: Array = ["rojo", "verde", "azul"]
    for c in colores {
        print("color: " + c)
    }

    // break y continue
    var k: int = 0
    while k < 10 {
        k = k + 1
        if k == 3 {
            continue
        }
        if k == 6 {
            break
        }
        print("k = " + int_to_string(k))
    }

    return 0
}

Output

entre 5 y 10
while: 1
while: 2
while: 3
while: 4
while: 5
range: 0
range: 1
range: 2
range: 3
range: 4
color: rojo
color: verde
color: azul
k = 1
k = 2
k = 4
k = 5

Explanation

The if statement evaluates a boolean condition without parentheses. You can chain conditions with else if and provide a fallback with else. All branch bodies must be enclosed in curly braces — no single-line shortcuts.

The while loop runs its body as long as the condition is true. Because Nyx does not have a built-in for (int i = 0; i < n; i++) form, while fills that role when you need a manual counter.

The for x in start..end form iterates over a half-open range: 0..5 produces 0, 1, 2, 3, 4 (5 is excluded). The for x in collection form iterates over any array or iterable value.

continue skips the remainder of the current loop iteration and jumps to the next one. break exits the loop immediately. In the example, k = 3 is skipped by continue, and the loop stops when k reaches 6.

← Previous Next →

Source: examples/by-example/04-control-flow.nx