Slide 12 of 74

Loops

The counting loop
proc main(): void {
	for i := 0; i < 3; i++ {
		echo "frame {i}"
	}
	for i := 10; i > 7; i-- {       // the counter is the loop's own
		echo "countdown {i}"
	}

	// Any clause may be left out. With only a condition, it is a while loop.
	mut left := 3
	for ; left > 0; {
		left -= 1
	}
	echo left
}
for each, break and continue
proc main(): void {
	for each name: Str in ["north", "", "south", "orchard"] {
		if name == "" {
			continue          // skip to the next one
		}
		if name == "south" {
			break             // leave the loop entirely
		}
		echo name
	}
}

There are two loops.

The counting one is for i := 0; i < 10; i++. Its counter belongs to the loop — the next loop may name its counter the same — and is mutable without saying mut, though it is still held to the camelCase rule. Any of its three clauses may be left out, which is how a while loop is written: for ; left > 0; { … }.

The walking one is for each name in values. It binds each element of a vector to an immutable name, in order, and since it never indexes it needs no bounds proof. for each name: T in values states the element type instead of inferring it, and a type the elements do not fit is a compile error. A Str and a map are not vectors, so neither can be walked this way: split(text, "") is a string's characters, and a map's keys are shown on its slide.

break leaves the innermost loop and continue skips to its next turn; either outside a loop is a compile error.