A body of code can be executed a number of times using a ‘while’ loop. The ‘while’ loop evaluates a condition, and while the condition is ‘true’, it executes the enclosed block of code. For example:
$count = 0; while( $count < 10 ) { log.info( "In loop, count = " . $count ); $count = $count + 1; }
The 'break
' and 'continue
' statements can be used within a loop to either stop the loop processing immediately, or to restart the loop processing again.
If you want the loop to be executed at least once, then you can swap the while and the do to make a do while loop:
$count = 10; do { log.info( $count ); } while( $count-- );
This will print the numbers 10 - 0 to the Event Log.
A for loop contains the following elements:
The initialization statement is executed once at the start of the loop. The condition is assessed at the start of every iteration of the loop. If it evaluates to true the loop body will be executed, if it evaluates to false the program will continue. After every iteration of the loop the counter statement is executed.
A typical for loop in TrafficScript looks like this:
for( $i = 0; $i < 10; $i++ ) { log.info( $i ); }
This will first initialise $i to 0, then determine that 0 is less than 10, will execute the loop (and log '0' to the Event Log) and finally increment $i to 1. The condition will be evaluated again, and the loop will continue to execute until $i is 10, when the loop will end.
The result will be the numbers 0 - 9 being printed to the Event Log.
As with while loops, the 'break
' and 'continue
' statements can be used to either stop the loop processing immediately, or to restart the loop processing again.
The foreach loop is used to iterate over Arrays and Hashes. Its use is described in the article HowTo: TrafficScript Arrays and Hashes.