Repeat-Until Loops in Scripts

Repeat-Until loops are one of four different types of loops provided in the Script element.  They are used to loop through a set of statements.  Common applications are defining and manipulating arrays, and doing an iterative calculation.  Repeat-Until loops require a single input: a condition that specifies whether the loop is to continue (which is evaluated at the bottom of the loop).  As a result, a Repeat-Until loop is always evaluated at least once.

A Repeat-Until loop can be inserted by selecting “REPEAT-UNTIL Loop” from the Script element’s Insert menu (or pressing Ctrl+P when in the Script dialog). The block is inserted below the statement that was selected when this is done.  The following dialog will be displayed:

Loop until true must be specified as a scalar condition. This condition is evaluated at the end of each loop. If it is False, another loop is carried out.  If it is True, control drops out the bottom of the loop.

   Note: If the condition is initially True (the default), one loop will be carried out.

After defining the properties of the Repeat-Until loop, the script will look like this:

Note that the last line indicates the “loop until” condition.

Obviously, such a loop serves no function unless it contains some statements inside the looping block. To insert a statement inside the block, you would select the first part of the block (in this case, line 1), and insert a statement.  In the example below, a Variable Assignment statement has been inserted (and a condition has been defined):

In general, the condition for the Repeat-Until loop will involve a local variable that is also being assigned inside the loop. In this example, when control exits the loop, the variable Local would be incremented by 10.

You can also move existing statements that are above or below the loop into the loop by using the buttons at the bottom of the Script dialog.

   Note: If multiple statements are selected (by left-clicking and dragging the line numbers) when the Repeat-Until loop is first inserted (and the selection is a logically complete block of code), GoldSim will “wrap” the selection in the loop. 

Repeat-Until loops can have any number of statements within them.  For example, a Repeat-Until loop could contain other nested loops, as well as complex if, then logic.  Here is an example of a Repeat-Until loop with a nested Repeat-Until loop and an If-Else block:

One key property of Repeat-Until loops that must be understood is that the loop creates a local scope for any variables that are defined within it.  Hence any variables defined in the loop could not be referenced outside of the loop (without first redefining them).

Related Topics…

Learn more about: