| Home | Previous Lesson: IF Next Lesson: DO UNTIL...LOOP |
Just as the IF statement is the basic control statement that allows PowerScript to make decisions, the DO WHILE statement is the basic statement that allows PowerScript to perform repetitive actions. It has the following syntax:
DO WHILE /*condition*/
/*statementblock*/
LOOP
The DO WHILE statement works by first evaluating the expression. If it is false, PowerScript moves to the next statement after corresponding LOOP label in the script. It is true, the statement that forms the body of the loop is executed and expression is evaluated again. This cycle continues until the expression evaluates to false, at which point the DO WHILE statement ends and PowerScript moves on. Note that to create an infinite loop with the syntax, use DO WHILE TRUE.
Usually, you do not want PowerScript to perform exactly the same operation over and over again, so in almost every loop, one or more variables change with each iteration of the loop. Since the variables change, the actions performed by executing statement may differ each time through the loop. Furthermore, if the changing variable or variables are involved in expression, the value of the expression may be different each time through the loop. This is important, otherwise an expression that starts off true would never change and the loop would never end! Here is an example DO WHILE loop:
Int li_counter = 0
DO WHILE li_counter < 5
MessageBox('Hello', 'Iteration #' + String(li_counter))
li_counter++
LOOP
As you can see, the variable li_counter starts off at zero in this example and is incremented each time the body of the loop runs. Once the loop executed five times, the expression becomes FALSE i.e., the variable li_counter is no longer less than five, the DO WHILE finishes and PowerScript can move on to the next statement in the script. Most loops have a counter variable like li_counter. The variable names i, j, and k are commonly used as a loop counters, though you should use more descriptive names if it makes your code easier to understand.
| Home | Previous Lesson: IF Next Lesson: DO UNTIL...LOOP |