ColdFusion Struct References

You need to be careful with references to objects or structs. I was looking at some old code the other day and I noticed I hadn't var'ed some local variables - very naughty of me. So I fixed the code but it no longer worked.

Here's what the code was like:

view plain print about
1<cfloop>
2<cfset items = arraynew()>
3<cfloop from="1" to="#listlen(list)#" index="i">
4 <cfset item = structnew()>
5 <cfset item.name = listgetat(list,i)>
6 <cfset item.id = i>
7 <cfset items[i] = item>
8</cfloop>
9</cfloop>

And what I changed it to:

view plain print about
1<cfset var items = arraynew()>
2<cfset var item = structnew()>
3
4<cfloop from="1" to="#listlen(list)#" index="i">
5 <cfset item.name = listgetat(list,i)>
6 <cfset item.id = i>
7 <cfset items[i] = item>
8</cfloop>

In ColdFusion all the var's need to be at the top of the function, however this introduces a bug into this code.

As the item is only created once, every time around the loop it's properties are changed but the same item is being changed. The array ends up of an array of the same items being the last item of the list.

Here's the correct code:

view plain print about
1<cfset var items = arraynew()>
2<cfset var item = structnew()>
3
4<cfloop from="1" to="#listlen(list)#" index="i">
5 <cfset item = structnew()>
6 <cfset item.name = listgetat(list,i)>
7 <cfset item.id = i>
8 <cfset items[i] = item>
9</cfloop>

Something to watch out for.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
I normally var the i for the loops as well (well, useually I just create a &quot;local&quot; struct and have all the variables in the function contained within that struct. It's nothing I've ever had a problem with, but I imagine it would lead to pretty sticky situations in figuring out what's going on.
# Posted By Sammy Larbi | 6/3/07 2:15 AM
Yes the i should be var'ed as well (it was in my code but that wasn't cause the issue so I left it out in the code above). I can't think of a situation that it would cause an issue, it's better to be safe than sorry.
# Posted By Justin Mclean | 6/3/07 11:09 AM
I guess if the class was a singleton and you had i as an iterator in 2+ methods it might be a problem, but for transients, I would assume the loop always gets completed and i is reset when complete (and generally, &quot;i&quot; wouldn't be used for anything else).
# Posted By Sammy Larbi | 6/4/07 2:25 AM