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:
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>
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:
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>
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:
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>
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.)
[Add Comment]
[Subscribe to Comments]

# Posted By Sammy Larbi
| 6/3/07 2:15 AM

# Posted By Justin Mclean
| 6/3/07 11:09 AM

# Posted By Sammy Larbi
| 6/4/07 2:25 AM
[Add Comment]