Vectors (ActionScript 3)


Many people still use Arrays when programming in Actionscript 3 when they should be using Vectors, so I’m going to give a brief synopsis of Vectors, especially their various constructors. Just as a warning, vectors are normally thought of as a math or geometric thing, a magnitude and direction. In Actionscript, they are not. If you are looking for this functionality either use Point for basic 2d stuff (or create your own Vector2D), or Vector3D for 3D geometric vectors. Why Flash named two totally different classes Vector and Vector3D is beyond me.

On to the Vector class in flash. A Vector is just a typed array – an array where all the objects in it are the same type. The benefits of using vectors include faster performance (major benefit) and not having to cast objects.

To create a vector, you have to use a generics system implemented specifically for vectors:

// var instName:Vector.<Type> = new Vector.<Type>();
//Ex:
var vector:Vector.<Sprite> = new Vector.<Sprite>();

You can also specify two parameters in the constructor, the first is an int representing initial length and the second is a boolean that determines if the length is fixed.

This is where it gets odd – there are two ways to declare a Vector quickly. First, the older and slower (processing and typing) way. Notice that the keyword new is not used and that an Array is the only parameter inside the constructor. A Vector may also be used.

// var instName:Vector.<Type> = Vector.<Type>([obj1,obj2...);
//Ex:
var vector:Vector.<Sprite> = Vector.<Sprite>([sprite1,sprite2,sprite3]);

Here’s the better way. Notice that the new keyword is used and that the syntax may appear slightly odd.

// var instName:Vector.<Type> = new <Type>[obj1,obj2...];
//Ex:
var vector:Vector.<Sprite> = new <Sprite>[sprite1,sprite2,sprite3];
//NOTE: Flash may not like this syntax sometimes
//Compiling with flex it's fine

Two dimensional Vectors also are fine. Here’s an example of a 2×3 Vector of ints – the outer Vector is type Vector.:

var grid:Vector.<Vector.<int>> = new <Vector.<int>> [new <int>[5,6,7], new <int>[1,2,3]];

Always make sure that when you construct a Vector that you are populating it with objects of the correct type.

Other than the differences in constructors, Vectors work almost exactly the same as Arrays.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s