Shaun Mccran

My digital playground

09
J
U
L
2009

Cfscript looping over lists

I really like cfscript, but as with any skill I don't use it often in my current role (its not 'standard') so I find that my knowledge of it is on the wane.

I do develop extensively outside of a working environment, so I find myself deliberately writing cfscript code rather than 'normal' coldfusion. I think it is because it is more like javascript, actionScript or .Net, I like the script formatting.

So I find myself looping over a series of lists in a form action template, I thought I would experiment with the different ways of doing the loop, cfscript and non script. So I create a simple list.

view plain print about
1<cfset variables.myList = "Banana,Apple,Orange,Pear,Strawberry,Kiwi,Mandarin,Melon">

Now loop over it in the traditional way.

view plain print about
1<cfoutput>
2    <cfloop from="1" to="#listLen(variables.myList)#" index="L">
3    #ListGetAt(variables.myList, L)#<br/>
4    </cfloop>
5</cfoutput>

And now the cfscript way.

view plain print about
1<cfscript>
2 For (i=1;i LTE ListLen(variables.myList); i=i+1)
3 writeoutput(ListGetAt(variables.myList, i)&'<BR>');
4
</cfscript>

Both code blocks give the same output, I much prefer the code style of the second block though.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Dan Vega's Gravatar Remember that scripting got a nice upgrade in version 8. If you are on anything lower than 8 this is the must way to do it. However if your on 8+ you can use another way.

for (i=1;i <= listLen(variables.myList); i++) {
}
# Posted By Dan Vega | 14/07/2009 14:29
BenNadel's Gravatar Also, you might want to rock out a list-to-array conversion pre-looping... sometimes makes things easier to work with:

myArray = listToArray( myList )
# Posted By BenNadel | 14/07/2009 16:02
Shaun McCran's Gravatar Thanks Dan, that is a more succinct way of writing the loop, and ‘reads’ even more easily than the example above.

I really like where CF9 is going with CFScript, the idea that Ray Camden posts here (http://www.coldfusionjedi.com/index.cfm/2008/5/2/A...) is interesting, that CF9 will have full CFScript CFC functionality. Building CFC’s in CFScript would be an intriguing change, especially in the translation to and from Flex.
# Posted By Shaun McCran | 15/07/2009 09:57
Back to top