User Guide

Table Of Contents
180 Chapter 9: Writing and Calling User-Defined Functions
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 for other purposes, such as a status variable.
If you do not use the
return statement to return the array to the caller, you can pass the array as
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>
</br>
<cfdump var="#arrayStruct#">
You must use the same structure element name for the array (in this case Array) in the calling page
and the function.