While...Wend

From Xojo Documentation

(Redirected from While)
Language Keyword

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

Usage

While condition

[Statements]
[ Continue ]
[ Exit ]

[Statements]

Wend

Part Description
While Begins the loop.
Condition Any valid Boolean expression. When this expression evaluates to True, the loop will continue to execute.
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, in cases of multiple nested loops.

Exit If an Exit statement is present, execution of the loop is terminated and resumes with the next line following the loop.
Wend Ends the loop. Condition is evaluated to determine if the loop should exit.

Notes

If Condition is True, all statements are executed until the Wend statement is reached. If Condition is still True, the process is repeated. If Condition is False, then execution continues with the statement following the Wend statement.

While...Wend statements can be nested to any level. Each Wend statement goes with the previous While statement. It is permissible to place Var statements inside loops, including While loops.

If a variable is declared inside a While statement, it goes out of scope after the last iteration of the loop. For example,

Var i As Integer
While I < 100
Var a As Integer
a = i + 1
Wend
MessageBox(a.ToString) // 'a' is out of scope

This loop makes sense with the variable "a" declared outside the loop.

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 can move the code for the loop to a separate Thread, allowing it to execute in the background.

Sample Code

This example uses the While...Wend statement to increment a variable.

Var x As Integer
While x < 100
x = x + 1
Wend

Using Exit:

Const kAttempts = 10
Var attempt As Integer = 1
Var output As String

While attempt <= kAttempts
Var randomValue As Integer = Xojo.Math.RandomInt(1, 10)
If randomValue > 5 Then
output = "Found a random value above 5 after " + Str(attempt) + " iterations."
Exit
End If
attempt = attempt + 1
Wend

If attempt > kAttempts Then
output = "Found NO random value above 5 after " + Str(kAttempts) + " iterations."
End If

Using Continue:

Const kAttempts = 100
Var matchCount As Integer
Var attempt As Integer

While attempt < kAttempts
attempt = attempt + 1
Var randomValue As Integer = Xojo.Math.RandomInt(1, 10)
If randomValue <= 5 Then
Continue
End If
matchCount = matchCount + 1
Wend

Var output As String
output = "Found " + Str(matchCount) + " random values above 5 within " + Str(kAttempts) + " iterations."

See Also

Continue, Do...Loop, Exit, For...Next statements; Application, Thread classes.