Control flow
if
hp := 25
if hp <= 0 {
print("dead")
} else if hp < 30 {
print("low")
} else {
print("ok")
}
low
The condition has to be a bool. Write if count != 0, not if count.
while
n := 1
while n < 100 {
n *= 2
}
print(n)
128
while true { ... } runs until a break.
for
.. stops before the end. to includes it:
for i in 0..3 {
print("a{i}")
}
for i in 1 to 3 {
print("b{i}")
}
a0
a1
a2
b1
b2
b3
for also counts through chars:
word := ""
for c in 'a' to 'e' {
word += "{c}"
}
print(word)
abcde
The end is worked out once, before the loop starts. If the start is already past the end, the loop doesn't run.
The counter belongs to the loop: it can't be replaced with := or destroyed.
break and continue
break leaves the loop. continue skips to the next round:
for i in 1 to 10 {
if i == 3 { continue }
if i == 6 { break }
print(i)
}
1
2
4
5
For choosing between many values, see switch.