Purpose
Defines a loop which will execute until a specified condition becomes TRUE (or FALSE).
Restrictions
You cannot issue a Do Loop statement through the MapBasic window.
Syntax 1
Do
statement_list
Loop [ { Until | While } condition ]
Syntax 2
Do [ { Until | While } condition ]
statement_list
Loop
statement_list is a group of statements to be executed zero or more times.
condition is a conditional expression which controls when the loop terminates.
Description
The Do...Loop statement provides loop control. Generally speaking, the Do...Loop repeatedly executes the statements in a statement_list as long as a While condition remains TRUE (or, conversely, the loop repeatedly executes the statement_list until the Until condition becomes TRUE).
If the Do...Loop does not contain the optional Until / While clause, the loop will repeat indefinitely. In such a case, a flow control statement, such as Goto statement or Exit Do statement, will be needed to halt or exit the loop. The Exit Do statement halts any Do...Loop immediately (regardless of whether the loop has an Until / While clause), and resumes program execution with the first statement following the Loop clause.
As indicated above, the optional Until / While clause may either follow the Do keyword or the Loop keyword. The position of the Until / While clause dictates whether MapBasic tests the condition before or after executing the statement_list. This is of particular importance during the first iteration of the loop. A loop using the following syntax:
Do
statement_list
Loop While condition
will execute the statement_list and then test the condition. If the condition is TRUE, MapBasic will continue to execute the statement_list until the condition becomes FALSE. Thus, a Do...Loop using the above syntax will execute the statement_list at least once.
By contrast, a Do...Loop of the following form will only execute the statement_list if the condition is TRUE.
Do While condition
statement_list
Loop
Example
The following example uses a Do...Loop statement to read the first ten records of a table.
Dim sum As Float, counter As Integer
Open Table "world"
Fetch First From world
counter = 1
Do
sum = sum + world.population
Fetch Next From world
counter = counter + 1
Loop While counter <= 10
See Also:
Exit Do statement, For...Next statement