While Loops in Scripts

While 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.  While loops are a common construct in a number of programming languages. They require a single input: a condition that specifies whether the loop is to continue (the condition is evaluated at the top of the loop).

A While loop can be inserted by selecting “WHILE Loop” from the Script element’s Insert menu (or pressing Ctrl+W 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 while true must be specified as a scalar condition. This condition is evaluated at the beginning of each loop. If it is True, another loop is carried out.  If it is False, control drops out the bottom of the loop.

   Note: If the condition is initially False (the default), no loops will be carried out at all.

After defining the properties of the While loop, the script will look like this:

Note that the first line indicates the loop’s “while” 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 While 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 While loop is first inserted (and the selection is a logically complete block of code), GoldSim will “wrap” the selection in the loop. 

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

One key property of While 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 can not be referenced outside of the loop (without first redefining them).

Related Topics…

Learn more about: