User Guide

Table Of Contents
184 Chapter 9: Writing and Calling User-Defined Functions
Using the Arguments scope in CFScript
A function can have optional arguments that you do not have to specify when you call the
function. To determine the number of arguments passed to the function, use the following
function:
ArrayLen(Arguments)
When you define a function using CFScript, the function must use the Arguments scope to
retrieve the optional arguments. For example, the following SumN function adds two or more
numbers together. It requires two arguments and supports any number of additional optional
arguments. You can refer to the first two, required, arguments as
Arg1 and Arg2 or as
Arguments[1] and Arguments[2]. You must refer to the third, fourth, and any additional
optional arguments as
Arguments[3], Arguments[4], and so on.
function SumN(Arg1,Arg2) {
var arg_count = ArrayLen(Arguments);
var sum = 0;
var i = 0;
for( i = 1 ; i LTE arg_count; i = i + 1 )
{
sum = sum + Arguments[i];
}
return sum;
}
With this function, any of the following function calls are valid:
SumN(Value1, Value2)
SumN(Value1, Value2, Value3)
SumN(Value1, Value2, Value3, Value4)
and so on.
The code never uses the Arg1 and Arg2 argument variables directly, because their values are
always the first two elements in the Arguments array and it is simpler to step through the array.
Specifying Arg1 and Arg2 in the function definition ensures that ColdFusion generates an error if
you pass the function one or no arguments.
Note: Avoid referring to a required argument in the body of a function by both the argument name
and its place in the Arguments scope array or structure, as this can be confusing and makes it easier
to introduce errors.
For more information on the Arguments scope, see About the Arguments scope” on page 181.
Using the Arguments scope in cffunction definitions
When you define a function using the
cffunction tag, you generally refer to the arguments
directly by name if all arguments are named in the
cfargument tags. If you do use the Arguments
scope identifier, follow the rules listed in About the Arguments scope” on page 181.