A for loop is used to run code repeatedly for some defined number of iterations. We can adapt our last example to use a for loop instead.
for counter in [init_val, 5]
print(counter, " ")
end for | or endf
print("-- done!\n")
Notice how this saves us two steps: counter is automatically initialized at the beginning of the loop, and incremented by 1 (by default) after each iteration. (It is assumed that we already defined counter since the for loop will not do this for us). This example corresponds more closely to the one we gave for the while loop than it does to the do loop example, since if init_val is greater than 5 the loop will not run even once. Note that, for convenience, we can abbreviate `end for' as `endf'.
By default counter increases by 1 after each pass of the loop. The for loop comes with the option of changing this, by using the step keyword. For example, if we were to change the for line above to
for counter in [1, 5] step 2
then we would get 1 3 5 -- done! as output. The step parameter is quite flexible; for example, we could change that same line to
for counter in [1, 10] step counter
to get the output 1 2 4 8 -- done!. We can also have a fractional step, and a negative step is also legal -- but regarding that second possibility what we cannot do is use a negative step variable. Thus
for counter in [10, 1] step -1
print(counter, " ")
end for
works just fine, printing 10 through 1 in reverse order, but
loop_step := -1
for counter in [10, 1] step loop_step
print(counter, " ")
end for
will not print anything. The reason is Yazoo decides whether to terminate the loop above or below the final loop index based on the sign of the counter variable, and if that's not a constant then it will assume a positive step. Here that assumption terminates the loop immediately because when counter is first initialized to 10 it is already above the cutoff threshold of 1, which is construed as an upper bound.
It may look suspicious that the same square brackets [] are used in both for loops and arrays to denote ranges. There is in truth no reason for this at all except that the keyboard manufacturers only put four pairs of bracket-like marks on their boards, and that the other three are already overworked as it is. The brackets, the comma, in and any step keyword along with for and endf are not even operators; they are simply signposts marking off the different parts of the loop. When the compiler comes across a for statement it simply lifts the expressions between these posts, compiles them and plops them into a precooked for-loop code involving gotos. The if, while and do blocks are all handled in the same way.
Last update: July 28, 2013