PASZ.COM LABS

Monday, March 20, 2006

Flash Dev Gotchas #10 - Array Initialization

Over the next few weeks on my blog, I'll be posting my top ten list of Flash Development Gotchas. These are the mistakes that plague me over and over again. I thought maybe if I compiled a list, it would help me keep them in mind from now on. I also thought posting the list here might help other Flash Developers avoid some of the pain I've been through. So, without further ado, there is number 10.

Initialize arrays before adding values to them!


This one may seem like a no-brainer, and if you're doing procedural programming, it's no big deal because you can initialize the array as soon as it's declared:

var myArray: Array = new Array();

If you're creating classes, though, it gets a trickier because you can't initialize arrays or objects during the property declaration section of your class, like this:

public var myArray: Array = new Array();

Instead, you have to initialize the array in the constructor, or some other method of your class.

public var myArray: Array;
...
public function MyClass(){
...
myArray.push(1);
myArray.push(2);
trace(myArray); //outputs "undefined"
myArray = new Array();
myArray.push(3);
myArray.push(4);
trace(myArray); //outputs "3,4"
...
}


Unfortunately, neither the Flash Compiler or MTASC warn you if you try to use an array that is undefined. They just fail silently. This can lead to wild goose chases and other frustrations until you figure out that the array isn't storing any of your data because it doesn't exist! I recommend getting into the habit of initializing all your arrays in the constructor.

Check back soon for more!

15 Comments:

Post a Comment

<< Home