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

Developing coldfusion mx applications
Table of Contents

Advertisement

A simple CFScript example
The following example function adds the two arguments and returns the result:
<cfscript>
function Sum(a,b) {
var sum = a + b;
return sum;
}
</cfscript>
In this example, a single line declares the function variable and uses an expression to set it to the
value to be returned. This function can be simplified so that it does not use a function variable, as
follows:
function MySum(a,b) {Return a + b;}
You must always use curly braces around the function definition body, even if it is a single
statement.
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
and
Arguments[1]
Arguments[2]
optional arguments as
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.
. You must refer to the third, fourth, and any additional
,
Arguments[3]
Arguments[4],
and
Arg1
Arg2
and so on.
Creating user-defined functions
or as
199

Advertisement

Table of Contents
loading
Need help?

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

This manual is also suitable for:

Coldfusion mx

Table of Contents