Loops
A body of code can be executed a number of times using a loop. TrafficScript supports “for”, “while”, “do”, and “foreach” loops.
“for” Loops
A “for” loop contains an initialization step, a test and an increment step, bracketing the body of code to be executed on each iteration:
for( <initialization> ; <condition> ; <increment> ) {
<statement list>
}For example:
for( $count = 0; $count < 10; $count++ ) {
log.info( "In loop, count = " . $count );
}This loop will print the message 10 times, with $count running from 0 to 9.
‘while’ Loops
The “while” loop evaluates a condition, and while the condition is true, it executes the enclosed block of code:
while( <condition> ) {
<statement list>
}For example:
$count = 0;
while( $count < 10 ) {
log.info( "In loop, count = " . $count );
$count = $count + 1;
}This loop will print the message 10 times, with $count running from 0 to 9.
“do” Loops
The “do” loop executes the enclosed block of code, then checks the condition. It repeats the code while the condition evaluates to true:
do {
<statement list>
} while( <condition> );For example:
$count = 0;
do {
log.info( "In loop, count = " . $count );
$count = $count + 1;
} while( $count < 10 );This loop will print the message 10 times, with $count running from 0 to 9.
TrafficScript contains a number of helper functions to manipulate complex data, such as HTTP requests or long strings. Consequently, it is rarely necessary to use loops in TrafficScript.
“foreach” Loops
Typically used with arrays and hashes, a “foreach” loop executes the bracketed body of code with each element of the supplied array in turn. The variable to the left of the “in” operator is initialized with the next array element prior to executing the code block.
foreach ( <element> in <array> ) {
<statement list>
}For example:
$array = [ "Alex", "Matt", "Oliver", "Laurence" ];
$i = 0;
foreach ( $element in $array ) {
log.info( "Element #" . $i . " " . $element );
$i++;
}For an example of a foreach loop with a hash, see Hashes.
