User Guide
Defining and Using Custom Functions 253
used elsewhere in your application. If a function must use a variable from another
scope that has the same name as a function variable, just prefix the external variable
with its scope identifier, such as Variables or Form.
For example, if you use the variable name
x for a function scope (var) variable and
for a Variables scope (local) variable in the body of a page that calls the function, the
two variables are independent of each other. You cannot refer to the function
variable in the body of the page, but you can refer to the local variable in the function
as Variables.x.
Identifying custom functions
You can use the IsCustomFunction function to determine whether a name
represents a custom function. The function throws an error if its argument is not
defined as a ColdFusion object. As a result, if your code context does not ensure that
the name exists, you should use the
isDefined function to ensure that it is defined.
For example:
<cfscript>
if( IsDefined("MyFunc"))
if( IsCustomFunction( MyFunc ))
WriteOutput( "MyFunc is a custom function");
else
WriteOutput( "Myfunc is defined but is NOT a custom function");
else
WriteOutput( "MyFunc is not defined");
</cfscript>
Note that the you do not surround the argument to IsCustomFunction in quotation
marks.
Examples of custom functons
The following simple examples show the use of custom functions.
Example 1 This function takes a principal amount, an annual percentage rate, and a loan
duration in months and returns the total amount of interest to be paid over the
period. You can optionally use the percent sign for the percentage rate, and include
the dollar sign and comma separators for the principal amount.
<cfscript>
function TotalInterest(principal, annualPercent, months)
{
Var years = 0;
Var interestRate = 0;
Var totalInterest = 0;
principal = trim(principal);
principal = REReplace(principal,"[\$,]","","ALL");
years = months / 12;
annualPercent = Replace(annualPercent,"%","","ALL");
interestRate = annualPercent / 100;
totalInterest = principal*(((1+ interestRate)^years)-1);