while and each are control flow blocks that make it possible to repetitively loop through execution of the same code.
while offers a simple mechanism: it executes a block's statements over and over as long as its condition remains true. The condition is checked right away and every time after the block's statements have been performed.
For example, this code logs the same message 5 times:
mut x = 1 while x<=5 $.log "DANGER, DANGER!! Will Robinson" x+=1
while may be used as a control suffix following a statement:
$$.show(list.extract) while !list.isEmpty
is equivalent to:
while !list.isEmpty $$.show(list.extract)
break and continue
Within a while block, break or continue statements may be used to modify the loop's control flow behavior.
The break statement, placed anywhere within a while block, provides a way to stop performance of the 'while' block. break is typically accompanied with if:
while true // without the break, this loop would run forever actor.walkstep // will happen at least once break if keypress==0x20 // stops whenever the space bar is pressed
By contrast, the continue statement ignores all subsequent statements in the 'while' block, returning control back to the top of the while block where the conditional expression is re-evaluated.
Although while is sufficient to support any kind of loop, each offers a more convenient way to iterate over some sequence of values. As with while, each may be used as a control prefix. break and continue are supported within an each block.
Iterating over numbers
If one simply wants to iterate evenly over a range of integer or floating point numbers:
mut sum = 0 each x in 0 <= 5 // iterates: 0, 1, 2, 3, 4, 5 sum += x sum // 15
Let's examine the elements of this each statement:
- x is a new mutable variable that will successively hold a single number within a range of numbers.
- 0 is the start of the range of numbers. x's first value in the loop will be 0. Each subsequent iteration of the loop increments x by 1.
- <= 5 indicates when the loop should stop, when x <= 5. That is, 5 will be the last value of x. After that, the loop ceases.
One may use any of the four comparison operators: <, <=, >, or >=. With the latter two, the variable will be decremented instead of incremented.
Optionally, the statement can specify a step value using by:
mut sum = 0 each x in 0 <= 10 by 2 // iterates: 0, 2, 4, 6, 7, 10 sum += x