Do...Loop

From Xojo Documentation

Language Keyword

Repeatedly executes a series of statements while a specified condition is True.

Usage

Do [Until condition]

[Statements]
[Statements]

Loop [Until condition]

Part Description
Do [Until] Begins the loop. If the optional Until and condition are included, the condition is evaluated to determine if the loop should exit.
Condition Any valid Boolean expression. When this expression evaluates to True, the loop will exit.
Statements Statements to be executed repeatedly (until condition evaluates to False).
Continue If a Continue statement is present, execution will skip over the remaining statements in the loop and resume with a new iteration of the loop.

Optional arguments of the Continue statement allow you to specify which loop will iterate next

Exit If an Exit statement is present, execution of the loop is terminated and resumes with the next line following the loop.
Loop[Until condition] Ends the loop. If the optional Until and condition are included, the condition is evaluated to determine if the loop should exit.

Notes

The Do...Loop statement continues to execute statements repeatedly until condition is True or an Exit statement within the loop is executed.

If statements should only be executed if condition is already True, test for condition at the beginning of the loop. If statements should execute at least once, test condition at the end of the loop.

If condition is not used to cause the loop to exit, your logic must call the Exit statement somewhere inside the Do...Loop or the loop will never end.

Do...Loop statements can be nested to any level. Each Loop statement goes with the previous Do statement.

When a loop runs it takes over the interface, preventing the user from interacting with menus and controls. If the loop is very lengthy, you should move the code for the loop to a separate Thread, allowing it to execute in the background.

You can declare variables using the Var statement within the loop. However, such variables are local to the loop (rather than the method) and go out of scope after the last iteration of the loop. For example,

Var x As Integer
Do Until x > 100
Var a As Integer
a = x + 1
Loop
MessageBox a.ToString // out of scope

This code makes sense only if the variable "a" is declared prior to the loop.

Sample Code

This example uses the Do...Loop statement to increment a variable. If the variable is greater than 100 before the loop begins, the variable will not be modified.

Do Until x > 100
x = x * 2
Loop

In this example, the variable will be modified at least once because condition is tested at the end of the loop.

Do
x = x * 2
Loop Until x > 100

More sample code:

Var x As Integer
Do
x = x + 1
Loop Until x = 100
' x = 100

x = 0
Do
x = x + 1
If x >= 100 Then Exit
Loop
' x = 100

See Also

Continue, Exit, For...Next, While...Wend statements; Application, Thread classes.