![]() ![]() ![]() |
In addition to evaluating expressions whose text is generated dynamically, ColdFusion allows developers to assign values to variables whose names are dynamic using the SetVariable function. SetVariable returns the value that was set. The following simple example shows how SetVariable can be used:
<CFSET VariableName="MyVariable"> <CFSET Value=2 ^ 10> <CFSET ValueJustSet=SetVariable(VariableName, Value)>
After the third CFSET statement, the resulting value of the MyVariable variable is 1024.
The following example demonstrates how the SetVariable and Evaluate functions can work together. The first loop sets ten variables with names MyVar1, MyVar2, etc. to the values 100, 200, etc. up to 1000. The second loop outputs the names and values of these variables.
<CFLOOP INDEX="Counter" FROM="1" TO="10"> <CFSET Result=SetVariable("MyVar#Counter#", Counter*100)> </CFLOOP> <CFLOOP INDEX="Counter" FROM="1" TO="10"> <CFOUTPUT> MyVar#Counter#=#Evaluate("MyVar#Counter#")#<BR> </CFOUTPUT> </CFLOOP>
The final example shows how you might implement the <CFPARAM NAME="VariableName" DEFAULT="DefaultValue">
tag in CFML:
<!--- Initialize the necessary variables ---> <CFSET VariableName="SomeVariable"> <CFSET DefaultValue="Default value"> <!--- Use Evaluate to call ParameterExists with the name of the variable whose existence we want to check for ---> <CFIF NOT Evaluate("ParameterExists(#VariableName#)")> <!--- If the variable does not exist, use SetVariable to set its value to the default ---> <CFSET Result=SetVariable(VariableName, DefaultValue)> </CFIF> <!--- Check to see that the variable has been created ---> <CFOUTPUT> #VariableName#=#Evaluate(VariableName)# </CFOUTPUT>
The CFML above executes as if the condition inside the CFIF tag were:
NOT ParameterExists(SomeVariable)
There are two additional dynamic expression evaluation functions, IIf and DE. For more information on these functions, refer to the Functions and Expressions chapter in this book.
See the CFML Language Reference for details on specific CFML functions.
![]() ![]() ![]() |
AllaireDoc@allaire.com
Copyright © 1998, Allaire Corporation. All rights reserved.