Using CFScript statements

The following sections describe how to use these CFScript statements:

Using assignment statements and functions

CFScript assignment statements are the equivalent of the cfset tag. These statements have the following form:

lval = expression;

lval is any ColdFusion variable reference; for example:

x = "positive";
y = x; 
a[3]=5; 
structure.member=10;
ArrayCopy=myArray;

You can use ColdFusion function calls, including UDFs, directly in CFScript. For example, the following line is a valid CFScript statement:

StructInsert(employee,"lastname",FORM.lastname);

Using conditional processing statements

CFScript includes the following conditional processing statements:

Using if and else statements

The if and else statements have the following syntax:

if(expr) statement [else statement]

In its simplest form, an if statement looks like this:

if(value EQ 2700)
  message = "You've reached the maximum";

A simple if-else statement looks like the following:

if(score GT 1)
  result = "positive";
else
  result = "negative";

CFScript does not include an elseif statement. However, you can use an if statement immediately after an else statement to create the equivalent of a cfelseif tag, as the following example shows:

if(score GT 1)
  result = "positive";
else if(score EQ 0)
  result = "zero";
else
  result = "negative";

As with all conditional processing statements, you can have multiple statements for each condition, as follows:

if(score GT 1)
  {
  result = "positive";
  message = "The result was positive.";
else
  {
  result = "negative";
  message = "The result was negative.";
  }

Note:   Often, you can make your code clearer by using braces even where they are not required.

Using switch and case statements

The switch statement and its dependent case and default statements have the following syntax:

switch (expression) {
  case constant: [case constant:]... statement(s) break; 
  [case constant: [case constant:]... statement(s) break;]... 
  [default: statement(s)] }

Use the following rules and recommendations for switch statements:

The following switch statement takes the value of a name variable:

  1. If the name is John or Robert, it sets both the male variable and the found variable to True.
  2. If the name is Mary, it sets the male variable to False and the found variable to True.
  3. Otherwise, it sets the found variable to False.
switch(name)
{
  case "John": case "Robert":
    male=True;
    found=True;
    break;
  case "Mary":
    male=False;
    found=True;
    break;
  default:
    found=False;
} //end switch

Using looping statements

CFScript provides a richer selection of looping constructs than those supplied by CFML tags. It enables you to create efficient looping constructs similar to those in most programming and scripting languages. CFScript provides the following looping constructs:

CFScript also includes the continue and break statements that control loop processing.

The following sections describe these types of loops and their uses.

Using for loops

The for loop has the following format:

for (inital-expression; test-expression; final-expression) statement

The initial-expression and final-expression can be one of the following:

The test-expression can be one of the following:

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:

  1. Evaluates the initial expression.
  2. Evaluates the test-expression.
  3. If the test-expression is False, exits the loop and processing continues following the statement.

    If the test-expression is True:

    1. Executes the statement (or statement block).
    2. Evaluates the final-expression.
    3. Returns to step 2.

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:

<cfscript>
strings=ArrayNew(1);
ArraySet(strings, 1, 10, "lock");
strings[5]="key";
indx=0;
for( ; ; )
{
  indx=indx+1;
  if(Find("key",strings[indx],1)) {
    WriteOutput("Found key at " & indx & ".<br>");
    break;
    }
  else if (indx IS ArrayLen(strings))
    {
    WriteOutput("Exited at " & indx & ".<br>");
    break;
    }
}
</cfscript>

This example shows one important issue that you must remember when creating loops: you must always ensure that the loop ends. If this example lacked the else if statement, and there was no "key" in the array, ColdFusion would loop forever or until a system error occurred; you would have to stop the server to end the loop.

The example also shows two issues with index arithmetic: in this form of loop you must make sure to initialize the index, and you must keep track of where the index is incremented. In this case, because the index is incremented at the top of the loop, you must initialize it to 0 so it becomes 1 in the first loop.

Using while loops

The while loop has the following format:

while (expression) statement

The while statement does the following:

  1. Evaluates the expression.
  2. If the expression is True, it does the following:
    1. Executes the statement, which can be a single semicolon-terminated statement or a statement block in curly braces.
    2. Returns to step 1.

      If the expression is False, processing continues with the next statement.

The following example uses a while loop to populate a 10-element array with multiples of five.

a = ArrayNew(1);
loop = 1;
while (loop LE 10)
{
 a[loop] = loop * 5;
 loop = loop + 1;
}

As with other loops, you must make sure that at some point the while expression is False and you must be careful to check your index arithmetic.

Using do-while loops

The do-while loop is like a while loop, except that it tests the loop condition after executing the loop statement block. The do-while loop has the following format:

do statement while (expression);

The do while statement does the following:

  1. Executes the statement, which can be a single semicolon-terminated statement or a statement block in curly braces.
  2. Evaluates the expression.
  3. If the expression is true, it returns to step 1.

    If the expression is False, processing continues with the next statement.

The following example, like the while loop example, populates a 10-element array with multiples of 5:

a = ArrayNew(1);
loop = 1;
do
{
  a[loop] = loop * 5;
  loop = loop + 1;
}
while (loop LE 10);

Because the loop index increment follows the array value assignment, the example initializes the loop variable to 1 and tests to make sure that it is less than or equal to 10.

The following example generates the same results as the previous two examples, but it increments the index before assigning the array value. As a result, it initializes the index to 0, and the end condition tests that the index is less than 10.

a = ArrayNew(1);
loop = 0;
do {loop = loop + 1; a[loop] = loop * 5;} while (loop LT 10);

using for-in loops

The for-in loop loops over the elements in a ColdFusion structure. It has the following format:

for (variable in structure) statement

The variable can be any ColdFusion identifier; it holds each structure key name as ColdFusion loops through the structure. The structure must be the name of an existing ColdFusion structure. The statement can be a single semicolon terminated statement or a statement block in curly braces.

The following example creates a structure with three elements. It then loops through the structure and displays the name and value of each key. Although the curly braces are not required here, they make it easier to determine the contents of the relatively long WriteOutput function. In general, you can make structured control flow, especially loops, clearer by using curly braces.

myStruct=StructNew();
myStruct.productName="kumquat";
mystruct.quality="fine";
myStruct.quantity=25;
for (keyName in myStruct) 
{
  WriteOutput("myStruct." & Keyname & " has the value: " &
    myStruct[keyName] &"<br>");
}  

Note:   Unlike the cfloop tag, you cannot use the CFSCript for-in loops to loop over a query, list, or object.

Using continue and break statements

The continue and break statements enable you to control the processing inside loops:

Using continue

The continue statement ends the current loop iteration, skips any code following it in the loop, and jumps to the beginning of the next loop iteration. For example, the following code loops through an array and display's each value that is not an empty string:

for ( loop=1; loop LE 10; loop = loop+1)
{
  if(a[loop] EQ "") continue;
  WriteOutput(loop);
}

(To test this code snippet, you must first create an array, a, with 10 or more elements, some of which are not empty strings.)

In general, the continue statement is particularly useful if you loop over arrays or structures and you want to skip processing for array elements or structure members with specific values, such as the empty string.

Using break

The break statement exits the current loop or case statement. Processing continues at the next CFScript statement. You end case statement processing blocks with a break statement. You can also use a test case with a break statement to prevent infinite loops, as shown in the following example. This script loops through an array and prints out the array indexes that contain the value key. It uses a conditional test and a break statement to make sure that the loop ends when at the end of the array.

strings=ArrayNew(1);
ArraySet(strings, 1, 10, "lock");
strings[5]="key";
strings[9]="key";
indx=0;
for( ; ; )
{
  indx=indx+1;
  if(Find("key",strings[indx],1)) 
  {
    WriteOutput("Found a key at " & indx & ".<br>");
    }
  else if (indx IS ArrayLen(strings))
  {
    WriteOutput("Array ends at index " & indx & ".<br>");
    break;
  }
}

Comments