Using for loops
The for loop has the following format:
for (initial-expression; test-expression; final-expression) statement
The initial-expression and final-expression can be one of the following:
•
A single assignment expression; for example, x=5 or loop=loop+1
•
Any ColdFusion expression; for example, SetVariable("a",a+1)
•
Empty
The test-expression can be one of the following:
•
Any ColdFusion expression; for example:
A LT 5
index LE x
status EQ "not found" AND index LT end
•
Empty
Note: The test expression is re-evaluated before each repeat of the loop. If code inside the loop
changes any part of the test expression, it can affect the number of iterations in the loop.
The statement can be a single semicolon terminated statement or a statement block in curly
braces.
When ColdFusion executes a for loop, it does the following:
Evaluates the initial expression.
1
Evaluates the test-expression.
2
If the test-expression is False, exits the loop and processing continues following the statement.
3
If the test-expression is True:
Executes the statement (or statement block).
a
Evaluates the final-expression.
b
Returns to step 2.
c
For loops are most commonly used for processing in which an index variable is incremented each
time through the loop, but it is not limited to this use.
The following simple for loop sets each element in a 10-element array with its index number.
for(index=1;
index LT 10;
index = index + 1)
a[index]=index;
The following, more complex, example demonstrates two features:
•
The use of curly braces to group multiple statements into a single block.
•
An empty condition statement. All loop control logic is in the statement block.
<cfscript>
strings=ArrayNew(1);
ArraySet(strings, 1, 10, "lock");
strings[5]="key";
indx=0;
for( ; ; ) {
indx=indx+1;
Using CFScript statements
135
Need help?
Do you have a question about the COLDFUSION MX 61-DEVELOPING COLDFUSION MX and is the answer not in the manual?
Questions and answers