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.
The while statement's condition may be omitted, if there should not be an exit condition at the start of the loop. Within the while block must be found at least one break statement (see below) that will terminate the loop. A loop with no condition and no breaks would otherwise repeat forever.
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: if n < 2: break 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(mut n i32) i32: mut result = 0 while n > 0: if n-- % 2 == 0: continue ++result result
loop as expression
A while loop may be used within an expression, where it is expected to return a value. The value(s) returned by a while loop are specified by the loop's break statements. The while statement cannot specify a conditional expression, as this condition does not specify the loop's returned value.
This example shows use of a while loop as an expression. Notice the lack of conditional expression on the while and the specification of values on the break statements.
imm found = loop: if idx > maxidx: break -1 if matches(idx): break 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(): if obj.impacted: continue 'outer