Variable Declaration, aka Iterative Sanity
I was just talking to Tai U, a friend of the Spaceship, about this one. We were discussing how all these new young hooligan coders out there are committing the sin of looping using reserved variable names for iterators. Something sorta like this:
for(var x:int=0;x<foo;x++) {
// x?! what are you doing?!!?
};
Young friends, that may fly for other languages, but in ActionScript you are playing with fire. I have labored for many moons over a better solution for this and the most sensible in my head is described as follows:
/* code below assumes some multidimensional array named grid was created before we got to this loop.*/
for(var i:int=0;i<grid.length;i++)
{
var a:Array = grid[i];
for(var ii:int=0;ii<a.length;ii++)
{
var b:Array = a[ii];
for(var iii:int=0;iii<b.length;iii++)
{
var mc:MovieClip = b[iii];
mc.gotoAndPlay("IN");
}
}
I use roman numerals instead of i,j,k because I find that easier to track back to how many loops I’ve gotten myself into… plus, if I start digging into ix territory, I’m probably writing WAY too many loops. :)
At the start of each loop I declare a variable that allows for easy reference for the item in whatever nested array I’m pointing at. These variables are organized alphabetically, so grid[i] will always be referred to as “a”, grid[i][ii] as “b” and so on. I realize this isn’t exactly the FASTEST way to loop through something, but I can always remove these pointers later if I really need a performance boost.
I doubt it’s the best convention out there. I’m sure the i,j,k camp will have something to say, and I’d love to hear it… I’m open to changing back to it if the argument is compelling enough. What I know we can all agree on is that declaring your variables “x” and “y”, or any other reserved keyword is a no no. You’re simply setting yourself up for complex irregular bugs and behavior. So to all you new coders out there: Quit it! And take off your shoes before you come in the house! Geesh.
September 15th, 2008 by Jamie / 15 Commentsactionscript



