Scripting: Loops and Iterations
This documentation is partially reproduced from the excellent Mozilla Developer Network Reference for JavaScript.
Loops allow you to execute a piece of script numerous times, generally using the current item or count of the loop inside that pieces of repeating script.
Contents
Looping Through Values (for each…in
)
The most common type of loop you will want to use allows you to loop through every value in a list or map. This is a non-standard feature of the Waltz JavaScript engine.
When looping over a list or map each value is provided in turn when using the for each…in
loop. The syntax of that loop is as follows:
for each (var value in list) { print(value); }
for each (var value in map) { print(value); }
Notice that for the map, only the value is accessible. This may not be the desired behavior. If you need both the key and the value, you should use a for…in
loop.
Looping Through Keys (for…in
)
In some situations, it is helpful to get both the index/key and value at the same time when looping through a list or map. In those cases, the for…in
loop is the correct choice.
for (var index in list) { print(index + “ = ” + list[index]); }
for (var key in map) { print(key + “ = ” + map[key]); }
Repeating Something x
Times (for
)
If you wish to simply repeat an action some number of times, the tradition C-style for
loop is the best choice.
for ([initialExpression]; [condition]; [incrementExpression]) { statement }
When a for
loop executes, the following occurs:
- The initializing expression
initialExpression
, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables. - The
condition
expression is evaluated. If the value ofcondition
is true, the loop statements execute. If the value ofcondition
is false, thefor
loop terminates. If thecondition
expression is omitted entirely, the condition is assumed to be true. - The
statement
executes. To execute multiple statements, use a block statement ({ ... }
) to group those statements. - If present, the update expression
incrementExpression
is executed. - Control returns to step 2.
Dangerous Loops (while
and do…while
)
Two other common types of loops are the while
and do…while
loops. These loops are inherently dangerous as they are unbounded, and will continue to execute until some value is false. Because these loops can result in Waltz waiting forever for their execution to finish, their use is discouraged and they are not documented here.
Expressions and Scripting | |
---|---|
Concepts | Script Expressions · JavaScript |
Fundamentals | Constructors · Functions · Grammar · Operations · Outputs · Parameters · Referencing Nodes |
Advanced Topics | Flow Control · Consumer Functions · Loops and Iterations · Reference Chains |
Errors | Recursion · Script Exceptions · Syntax Errors · Try and Catch |