MACROMEDIA COLDFUSION MX 61-DEVELOPING COLDFUSION MX Develop Manual page 211

Developing coldfusion mx applications
Table of Contents

Advertisement

Passing arrays
If you want your function to modify the caller's copy of the array, the simplest solution is to pass
the array to the function and return the changed array to the caller in the function
statement. In the caller, use same variable name in the function argument and return variable.
The following example shows how to directly pass and return arrays. In this example, the
function doubles the value of each element in a one-dimensional array.
doubleOneDArray
<cfscript>
//Initialize some variables
//This creates a simple array.
a=ArrayNew(1);
a[1]=2;
a[2]=22;
//Define the function.
function doubleOneDArray(OneDArray) {
var i = 0;
for ( i = 1; i LE arrayLen(OneDArray); i = i + 1)
{ OneDArray[i] = OneDArray[i] * 2; }
return OneDArray;
}
//Call the function.
a = doubleOneDArray(a);
</cfscript>
<cfdump var="#a#">
This solution is simple, but it is not always optimal:
This technique requires ColdFusion to copy the entire array twice, once when you call the
function and once when the function returns. This is inefficient for large arrays and can reduce
performance, particularly if the function is called frequently.
You can use the return value of other purposes, such as a status variable.
If you do not use the
return
an element in a structure and change the array values inside the structure. Then the calling page
can access the changed data by using the structure variable it passed to the UDF.
The following code shows how to rewrite the previous example using an array in a structure. It
returns True as a status indicator to the calling page and uses the structure to pass the array data
back to the calling page.
<cfscript>
//Initialize some variables.
//This creates an simple array as an element in a structure.
arrayStruct=StructNew();
arrayStruct.Array=ArrayNew(1);
arrayStruct.Array[1]=2;
arrayStruct.Array[2]=22;
//Define the function.
function doubleOneDArrayS(OneDArrayStruct) {
var i = 0;
for ( i = 1; i LE arrayLen(OneDArrayStruct.Array); i = i + 1)
{ OneDArrayStruct.Array[i] = OneDArrayStruct.Array[i] * 2; }
return True;
}
//Call the function.
Status = doubleOneDArrayS(arrayStruct);
WriteOutput("Status: " & Status);
</cfscript>
statement to return the array to the caller, you can pass the array as
return
Using UDFs effectively
211

Advertisement

Table of Contents
loading

This manual is also suitable for:

Coldfusion mx

Table of Contents