Today I was writing this simple function to recursively create XML based on a struct, and ran into
a minor gotcha:
<cfcomponent>
<cfscript>
function structToXML(struct)
{
var result = ""
;
for (item in struct)
{
if(not isStruct(struct[item]))
result = result & "<#item#>#struct[item]#</#item#>"
;
else
result = result & "<#item#>"
& structToXML(struct[item]) & "</#item#>"
;
}
return result;
}
</cfscript>
</cfcomponent>
Can you spot the problem? Its easy to miss: I forgot to
var
my loop variable,
item
. I normally remember to put most variables in the var scope, but I often forget to do so when variables are being defined in or by a tag, or in a loop. Things like item, index, and query names. So I spent some time trying to figure out why ColdFusion's stack didn't seem to be working properly: instead of closing the tag with the correct element name, it was closing it with the last used one on recursive calls.
I was about to ask if anyone could help me spot the flaw in my logic when it hit me - the
var
scope!
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
There are no comments for this entry yet.
Leave a comment