On other occasions, you might want the loop continuations to depend on a condition:
-
You may want to continue while a certain condition is true, and stop with the loop when the condition turns false
-
You may want to do the opposite—loop until a certain condition is true
Here is an example of the while word, printing out the odd integers smaller than 10:
n: 1
while [n <= 10 ][
if odd? n [prin n prin " "]
n: n + 1
] ;== 1 3 5 7 9
We can have the same result by simulating a second step:
n: 1
while [n <= 10 ][
prin n prin " "
n: n + 2
] ;== 1 3 5 7 9
Every while can be turned into an until by inverting the condition. But be careful—the condition, that should become true at a certain moment, must appear as the last expression in the until block:
n: 1
until [
prin n prin " "
n: n + 2
n > 10 ; the condition to end the loop
] ;== 1 3 5 7 9
This also means that the block will be executed at least once.
The break word can be used to break out of any kind of loop. If it's useful, you can return a value with break/return value. If you want to skip the current iteration of the loop, use continue to transfer control back to the start of the loop to begin the next iteration. The following code snippet illustrates this:
repeat n 8 [
prin ["Before" n " - "]
if n < 3 [continue]
if n = 6 [break]
prin ["After" n " - "]
]
This prints out the following:
Before 1 - Before 2 - Before 3 - After 3 - Before 4 - After 4 -
Before 5 - After 5 - Before 6 -
When looping through a series in a block, you'll most often use foreach and forall, which we'll discuss in the next chapter.
=> Now answer question 7 from the Questions section.