← Back to Docs

for Loops

VDX supports two styles of for loop: C-style and for-in (array iteration).

⚠️ Loop Protection

C-style for loops are subject to the same loop safety protection as while loops. Use @unsafe for fast loops.

C-style for loop

for (init; condition; update) {
    // body
}
class App {
    @unsafe for (let i = 0; i < 5; i = i + 1) {
        print("i:", i);
    }
    // Output: i: 0, i: 1, i: 2, i: 3, i: 4
}

The init part can use let to declare a new variable, or assign to an existing one. The update part is an assignment (no semicolon needed).

for-in loop

Iterate over each element in an array:

for (variable in array) {
    // body — variable holds the current element
}
class App {
    let fruits = ["apple", "banana", "cherry"];
    for (fruit in fruits) {
        print("fruit:", fruit);
    }
}

The for-in loop does not have loop safety protection since it always terminates (bounded by array length).

Accumulating with for

class App {
    let sum: float = 0.0;
    let values = [1.5, 2.5, 3.0];
    for (v in values) {
        sum = sum + v;
    }
    print("sum:", sum);   // sum: 7.0
}

Nested for loops

class App {
    @unsafe for (let i = 0; i < 3; i = i + 1) {
        @unsafe for (let j = 0; j < 3; j = j + 1) {
            print(i, j);
        }
    }
}

Scoping

The loop variable in a C-style for is scoped to the loop. In a for-in loop, the iteration variable is scoped to each iteration. See Scoping Rules.