Thursday, February 3, 2011

Copy Vector in AS3

Problem: 
When dealing with complex datatypes, you will find the normal assignment doesn't work to make a copy as it does with simple datatypes like int, string, etc.
var vec:Vector. = oldVec; // returns the same object - not a copy!
In short, all this does is passes the reference to the complex datatype so that it now has two variables that point to the same data. Therefor manipulating the oldVec variable would reflect in vec and visa vera.
vec.push("hello"); // this is manipulating the object at the reference - in other words, vec and oldVec still contain the same thing including the new string "hello".

Solution:
With some complex objects (generally visual components), there is a 'clone' method available which allows deep copying of the complex datatype so that you have two separate datatypes. Others have written methods which will copy your data. If you are looking for a shallow copy, Vector provided a concat() method which when passed no parameters, returns a copy of your original vector.
var newVec:Vector. = oldVec.concat(); // returns a shallow copy
Note: Shallow copy means that if you have a vector of complex datatypes, only so many depths are copied to the returned vector object. This solution works well for shallow copies of vectors containing simple datatypes (i.e. int, uint, string, etc.).

1 comment:

Unknown said...

How about using slice()? Tried that?

var newVec:Vector. = oldVec.slice()

// oldVec has to be of the same type ofcourse.

Best,
Sidney