User defined functions allow developers to keep frequently used pieces of code together in reusable units. For example, you may often find yourself checking the size of a particular file or counting the number of records in a database table. You might find that you need to find out if a string is upper or lowercase, or convert a string to an array of single characters.
Whatever your need, user defined functions (UDFs) can help you accomplish your goal. In this article, I’ll show you how to create user defined functions using cfscript so that your function is compatible with both ColdFusion 5 and ColdFusion MX.
cfscript
Functions
cfscript has been around since at least version 4.01. It basically allows a developer to write ColdFusion code in C-style syntax. There are limitations to cfscript
, though. For example, you can’t call ColdFusion tags from within cfscript
. You have to use available functions. cfscript
has been proven to offer some performance benefits over the use of tags in some situations, and it often results in your using less code than you may otherwise need. In addition, in ColdFusion 5 you can create your own functions only by using cfscript
. It’s in this context that we’ll use cfscript
to build our own functions that are compatible all the way back to version 5.
For our first examples, we’ll use a couple of functions I posted in the ColdFusion blog back in April, which allow us to figure out if a character is uppercase or lowercase. We’ll then add a couple of functions to increase the script’s capabilities in ways that may be useful in the future.
The Uppercase Function
To start, let’s build a function to tell us if a character is uppercase. We’ll then build one to tell us if a character is lowercase. Here’s the code for the function:
<cfscript>
function isUpperCase(character) {
if (Asc(character) gte 65 and Asc(character) lte 90)
return true;
return false;
}
</cfscript>
First, we open our cfscript
block. Next, we create a function using the function keyword. We give it a name and then specify, in parentheses, the parameters that it takes. Does this look familiar to you? If you’ve ever worked with JavaScript, it should. This is exactly how a JavaScript function is declared (except for the cfscript
block). There are a few things to note about ColdFusion UDFs, though:
- You cannot overload or re-declare a function. Once you create it, you cannot create another function of the same name.
- You cannot specify default values for parameters in a ColdFusion UDF.
- You cannot specify optional parameters for a UDF. Every parameter you use in the declaration must be passed in the function call.
Now that I’ve told you what you cannot do with UDFs, here’s something you can do: you can specify parameters that are not declared. For example, I have only declared one parameter for the function above, but I can pass in three, or four, or more parameters. So, a normal function call would look like this:
<cfoutput>
#isUpperCase("A")#
</cfoutput>
This would display the value “true”. Note that if I passed in the string “Aaaa” it would still be true, because the Asc
function uses the first character of the string passed in and ignores the rest.
However, if I call it with a couple of extra parameters, it will still work:
<cfoutput>
#isUpperCase("A", "a", "b")#
</cfoutput>
This will still display “true”. It doesn’t use those additional parameters. But what if we want to use the additional parameters passed into the function? How do we get to them, you ask? It’s really quite simple. Inside the function, we have an array called “arguments”. So, if we want to use the second and third parameters, we can simply access them via this array.
<cfscript>
function argsTest() {
for (i = 1; i lte ArrayLen(arguments); i = i + 1) {
WriteOutput(arguments[i] & "<br />");
}
}
</cfscript>
This will write out all the arguments that we pass in. We call the function this way:
<cfset a = argsTest("I", "am", "ready", "to", "code")>
Using the above code, we’ll get each of those arguments printed on a separate line. Notice a few things about our function here:
- We use
"lte"
for our comparison. This is because, even though it’s a different syntax, it is still ColdFusion. We must use normal CF operators for comparisons and logic. - We use
i = i + 1
instead ofi++
. This is because, again, we’re still using ColdFusion, which does not support the++
operator. - We use the
WriteOutput()
function to display variables and other information to the page. This is sort of like usingdocument.write()
in a JavaScript function. - As in our uppercase function, note that we can use normal ColdFusion functions, such as
Asc(), Chr(), Len(), ArrayLen(), ArrayNew()
, etc., as well. - Notice the return statement in our uppercase function. In this function, we return a simple Boolean, which can then be assigned to any variable we choose. But, we can also return complex values, such as structs and arrays. We’ll see this in just a minute.
The Lowercase Function
Now, let’s code our lowercase function. The ASCII values for our lowercase characters are 97 through 122, so we’ll basically copy and paste the uppercase function and modify those two values.
<cfscript>
function isLowerCase(character) {
if (Asc(character) lte 97 and Asc(character) gte 122)
return true;
return false;
}
</cfscript>
That will do for those functions. Now, let’s build a function to decide if it is upper or lower case, and alert us to that. We’ll return the value “upper”, “lower”, or “false” depending on the character passed.
<cfscript>
function isUpperOrLowerCase(character) {
if (Asc(character) gte 65 and Asc(character) lte 90)
return "upper";
else if (Asc(character) gte 97 and Asc(character) lte 122)
return "lower";
return false;
}
</cfscript>
We can use the function in this way:
<cfif not isUpperOrLowerCase("a")>
This is not a character.
<cfelseif isUpperOrLowerCase("a") eq "upper">
This is an uppercase character.
<cfelse>
This is a lowercase character.
</cfif>
This demonstrates the ability to return a data type other than a Boolean from a UDF. Now, let’s return something more complex: an array. We’ll create a function that will turn a string into an array of characters.
<cfscript>
function toCharacterArray(str) {
var CharArray = ArrayNew(1);
for (i = 1; i lte Len(str); i = i + 1) {
CharArray[i] = Mid(str, i, 1);
}
return CharArray;
}
</cfscript>
This accepts a string as an argument, creates a new, one-dimensional array, loops from 1 to the length of the string, and pulls out each character, stuffing it into the array at the current index, represented by the variable i
. We then return the character array.
<cfset a = toCharacterArray('This is my array")>
<cfdump var="#a#">
The script above displays a neat little table that shows every value in the array. It really is that easy to create user defined functions in ColdFusion. Now that you know how to create user-defined functions in ColdFusion using cfscript, here’s your assignment:
Go through a current project, or a Website that you’ve previously built in ColdFusion, and identify the pieces of that project that could be built into functions. It may be that you use the same functionality in several places, or that you could clean up your code and simplify it by removing it from the body of your templates and putting it into a template. Then, build your functions, store them in a single file (if there are not too many) and simply include them where you need them. You could also create a directory in your site called “udfs”, or something like that, and put each function in a file of the same name. Then you simply include the functions you need.
If you want free user defined functions, you may want to look at CFLib – you’ll find tons of very handy functions there.
Frequently Asked Questions about ColdFusion Defined Functions
What are the different types of functions in ColdFusion?
ColdFusion offers a wide range of functions that can be categorized into various types. These include Array functions, Date and Time functions, Decision functions, List functions, and Struct functions, among others. Each category has specific functions that perform unique tasks. For instance, Array functions are used to manipulate arrays, while Date and Time functions are used to handle date and time data.
How do I define a function in ColdFusion?
In ColdFusion, you can define a function using the
Can I use ColdFusion functions in a CFML script?
Yes, you can use ColdFusion functions in a CFML script. The syntax for calling a function in a script is similar to that in a tag-based code. You simply need to use the function name followed by parentheses, and include any required arguments within the parentheses.
How do I use array functions in ColdFusion?
Array functions in ColdFusion are used to manipulate arrays. For instance, the ArrayAppend function is used to add an element to the end of an array. The syntax for using this function is ArrayAppend(array, value), where ‘array’ is the array to which you want to add an element, and ‘value’ is the element you want to add.
What are decision functions in ColdFusion?
Decision functions in ColdFusion are used to make decisions based on certain conditions. These functions return a Boolean value (true or false) depending on whether the condition is met. For example, the IsDefined function checks if a variable is defined and returns true if it is, and false if it isn’t.
How do I use list functions in ColdFusion?
List functions in ColdFusion are used to manipulate lists. For example, the ListAppend function is used to add an element to the end of a list. The syntax for using this function is ListAppend(list, value), where ‘list’ is the list to which you want to add an element, and ‘value’ is the element you want to add.
What are struct functions in ColdFusion?
Struct functions in ColdFusion are used to manipulate structures. These functions allow you to perform tasks such as adding elements to a structure, deleting elements from a structure, and checking if a structure contains a specific key.
Can I create custom functions in ColdFusion?
Yes, you can create custom functions in ColdFusion. These functions are defined using the
How do I call a function in ColdFusion?
To call a function in ColdFusion, you simply use the function name followed by parentheses. If the function requires arguments, you include them within the parentheses. For example, to call a function named ‘myFunction’ that requires two arguments, you would use the syntax myFunction(arg1, arg2).
Can I use ColdFusion functions in other programming languages?
ColdFusion functions are specific to the ColdFusion Markup Language (CFML) and cannot be used directly in other programming languages. However, you can use ColdFusion to interact with other languages through various methods, such as web services or HTTP requests.
David operates MedlockWeb, a web consulting firm that focuses on building solid relationships and web applications with entrepreneurs and investors. He also maintains a web business blog at WebDevSuccess.com.