On this page
article
Chapter 5: Control Flow
Loops
-- for: iterate a collection
for item in items {
process(item);
}
-- for with index
for item, i in items {
debug.print("[{}] {}\n", .{i, item});
}
-- for over a range
for i in 0..10 { -- exclusive: 0, 1, ..., 9
debug.print("{}\n", .{i});
}
for i in 0..=10 { -- inclusive: 0, 1, ..., 10
debug.print("{}\n", .{i});
}
-- while: condition-based
var n: i32 = 1;
while n < 100 {
n *= 2;
}
-- loop: infinite, exit with break
var count: i32 = 0;
loop {
count += 1;
if count = 10 { break; }
}
-- loop with a value
var found = loop {
var candidate = try nextCandidate();
if candidate.valid { break candidate; }
};
-- repeat...until: post-condition (runs at least once)
var input: []const u8 = "";
repeat {
input = try readLine();
} until input != "";
Multi-sequence For
for x, y in xs, ys {
debug.print("{} {}\n", .{x, y});
}
-- with shared index
for x, y, i in xs, ys {
debug.print("[{}] {} {}\n", .{i, x, y});
}
Break and Continue
outer: for i in 0..10 {
for j in 0..10 {
if i + j = 15 { break outer; }
}
}
for item in items {
if item.* = 0 { continue; }
process(item);
}