Repeated Execution ("while" Loop)
Sometimes, an action or a group of actions must be performed repeatedly, for example on every entry of a table. Rather than pasting the sequence n times into the script, you put them in a loop.
%count = GetGridRowCount(ENTRIES)
%i = 0
while (%i < %count)
{
%reference_number = GetGridFieldContent(ENTRIES, %i, NUMBER)
%i = %i + 1
if (%reference_number == 999)
{
break
}
// do something useful
if (%referece_number > 1000)
{
continue
}
// do more useful stuff
}
The loop starts with the while
keyword. This keyword is followed by the parenthesized control condition, and then by a pair of curly braces which encloses the loop body.
The control condition controls whether the loop is executed. If it evaluates to a ‘true’ value, the loop body is executed, then the condition is tested again. As long as the condition is ‘true’, loop execution repeats. A typical loop condition is to compare a loop counter (%i
in the example) against a limit (%count
). However, care must be taken to increment the loop counter because otherwise, an infinite loop may result. The loop counter must be initialized outside the loop.
The loop body contains the instruction that should be executed while the loop is running. The loop body can contain simple instructions, conditional instructions (if
-- else
), or even nested loops. However, this is dangerous because it is easy to confuse the loop counter of the outer loop with that of the inner loop.
Two instructions are specific to loops:
break
causes the script to immediately exit the loop, irrespective of whether the control condition evaluates to 'false' or to 'true'. Execution continues with the statement following the closing curly brace that finishes the loop body.continue
causes execution to skip immediately to the end of the loop, but as opposed tobreak
, the control condition is re-tested, and if it is still 'true', loop execution continues. In the example, the “more useful stuff” is skipped for reference numbers above 1000.
When using continue
, be careful not to inadvertently skip the code that increments the loop counter.
If the loop is a part of the body of a script-defined function, a return
statement immediately exits the loop and the function.