do loop is a loop that executes a statement or a block of statements repeatedly, as long as a given condition evaluates to
true. The condition will be re-evaluated at the beginning of each iteration of the loop, allowing code inside the loop to affect the condition in order to terminate it.
Since the condition is evaluated before the loop is entered, it is possible for a
do loop to never be executed even once, if the condition is already
false when execution arrives at the loop.
As an alternative to the
do loop, the
until block loop will evaluate a condition at the end of each iteration, thus providing a loop that is guaranteed to be entered at least once.
The basic syntax for a
do loop looks like this:
while x < 10 do DoSomething();
where a conditional expression is specified between the
do keywords, and the
do keyword is followed by the statement that is to be executed repeatedly.
If the condition is a simple boolean, the
do loop will execute as long as the condition evaluates to true.
If the condition is a Nullable Boolean type, then the additional case of the condition evaluating to
nil needs to be considered. While a
nil nullable boolean strictly speaking is not equivalent to false, the
do loop treats them the same, and will stop executing the loop if the condition evaluates to either
do Loops and
On its own, the
do loop only takes a single statement to be executed for each iteration. To execute more than one statement, multiple statements can be grouped using a
end Block Statement:
while x > 10 do begin DoSomething(); DoSomethingElse(); end;
Prematurely Exiting the Loop or a Loop Iteration
Like all loops,
do loops can be exited prematurely using the
exit statements, and a single loop iteration can be cut short by using the
continue statement, which jumps to the next loop iteration.