In programming, we commonly use loops to make programs run through a set amount of iterations. For example, you may want to increment a variable x amount of times in a loop. GLang implements that with the walk loop.
walk i = 0 through 10 {
bark(i);
}
In this case, iterator i is incremented 0 through 10 (10 times), making the output of the program:
0
1
2
3
4
5
6
7
8
9
Why only 0 through 9? This is because everything in programming starts at 0. In the case of the walk loop, you can imagine each value is shifted by one. To get values 1 through 10, just shift the iteration amount by one:
walk i = 1 through 11 {
bark(i);
}
More about the walk loop here.
Another common loop in programming is known as the while loop. This loop runs "while" a condition is true. GLang implements a simple while loop with the while keyword:
while true {
bark("This loop runs forever");
}
The loop runs forever because the condition is always true. We can prevent a loop from running infinitely by having a condition that is only true for so long:
obj x = 0;
while x != 10 {
obj x = x + 1;
}
If you look closely, this looks exactly like the walk loop! Variable x is incremented 0 through 10 until stopping at 10.
What if we want to control the loop manually? Sometimes you don't want to use a condition to run a while loop. You can actually control a loop with the leave and next keywords!
obj x = 0;
while true {
if x == 5 {
next; # 'next' skips to the next iteration of while and walk loops
}
obj x = x + 1;
if x == 10 {
leave; # 'leave' stops while and walk loops
}
}
In this case, we use the leave and next keywords to manually control what the loop does based on the value of x!