Use while to repetitively perform the same logic over and over again so long as a specified condition is true. For example:
fn fact(mut n i32) i32 mut result = 1 while n > 1 result *= n --n result
This function calculates the factorial of some number n. So long as n stays greater than one, the inner block repeatedly multiplies result by n and then decrements n. So, if n is 5, result will be calculated as 5 * 4 * 3 * 2, returning 120.
The while statement's condition can be any conditional expression, as described for if. The condition is checked when encountering the while statement, and then again every time after the block's statements have been performed. Whenever the condition evaluates as false, execution continues at the first statement after the while block.
Alternatively, while (like if) may be used as a control suffix after any statement. The following logic is identical to the above.
fn fact(mut n i32) i32 mut return = 1 result *= n-- while n > 1 return
break statements may be placed anywhere within a while block to terminate the repetitive loop early. We can code the factorial function yet another way using 'break':
fn fact(mut n i32) i32 mut result = 1 while true break if n < 2 result *= n-- result
As this example shows, break is typically found within an if block. A break statement terminates the control flow for the innermost loop block it is found within.
The continue statement also changes the loop's control flow. Instead of terminating the loop, it resumes execution at the top of the loop, re-evaluating the conditional expression. Effectively, continue ignores all subsequent statements in the loop's block.
fn countOdd(n i32) i32 mut result = 0 while n > 0 continue if n-- % 2 == 0 ++result result
loop as expression
To use a loop as an expression, use loop instead of while. This is the equivalent of while true. One or more break statements will be required to signal when the loop needs to terminate,.
These break statements may specify a value to be returned from the loop.
imm found = loop break -1 if idx > maxidx break idx if matches(idx) ++idx
If this feature is used, all break statements in the loop must return a value, all of the same type.
Outer block breaks
To make it possible for break or continue to apply to a loop outside the loop it is in, mark the outer loop with a lifetime annotation and then use that same annotation on the break or continue statement.
'outer: each n in 1...5 while obj.fireAShot() continue 'outer if obj.impacted