for Loops
VDX supports two styles of for loop: C-style and for-in (array/string/dict iteration).
⚠️ Loop Protection
Both C-style for loops and for-in 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 any assignment or increment/decrement — i++, arr[i] = v, obj.n-- all work (v0.1.5+; no semicolon needed).
for-in loop
Iterate over an array (elements), a string (characters, v0.1.5+), or a dict (keys in sorted order, v0.1.5+):
for (variable in iterable) {
// body — variable holds the current element / char / key
}class App {
let fruits = ["apple", "banana", "cherry"];
for (fruit in fruits) {
print("fruit:", fruit);
}
for (ch in "hi") { // v0.1.5+ — h, i
print("char:", ch);
}
let d = {"b": 2, "a": 1};
for (k in d) { // v0.1.5+ — keys sorted: a, b
print(k, "=", d[k]);
}
}For-in loops are also subject to loop safety protection — halted if an iteration takes more than 2s of work or the loop exceeds 1,000,000 iterations (v0.1.5+). Use @unsafe to bypass.
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.