[SOLVED] Array Cloning: TypeError: Error #1034:


(Darrin) #1

I’m looking to do a Deep Copy of an Array like this. My Array is an Array of Entities called Squares. I’ve gotten the code to basically work but I’m getting error messages in FlashDevelop even though it does seem to copy.

TypeError: Error #1034: Type Coercion failed: cannot convert Object@92d0d49 to net.flashpunk.Graphic.

Some people have said, “But you can still get the error #1034 for nested classes. You need register aliases for all nested classes to prevent this before making copy, for example in some startup method.”

The following code has no effect:

registerClassAlias("net.flashpunk.Graphic", net.flashpunk.Graphic); 

This code gives an error:

registerClassAlias("net.flashpunk.Graphic", Graphic); 

I saw one note on a forum that you can’t clone Display Objects. So how are you supposed to make a deep copy of an array?

Since the game compiles are runs should I just ignore it, even though it is going to bother the heck out of me.

	private function clone(source:Object):* 
	{	 
		var myBA:ByteArray = new ByteArray(); 
		myBA.writeObject(source); 
		myBA.position = 0; 
		return(myBA.readObject()); 
	}
	//
	// Remove the word and moves down others
	// 
	public function removeWord():void {		
		
		// Nothing to do if word is short.  Defensive coding.
		if (pressedArray.length < 3) {
			return; 
		}
		
		// Make a copy of the pressed array			
		registerClassAlias("Square", Square); 			
		replacementArray = clone(pressedArray) as Array;			
		
	}

(Martí Angelats i Ribera) #2

To clone a Array simply use this function (you can have it in your utils class if you want):

public static function cloneArray(array:Array):Array
{
var cloned:Array = [];
for (var i:int in array)
{
cloned[i] = array[i];
}
return cloned;
}

And the error may be cased by the fact that the cloned Array contains Objects not Graphics. And AS3 don’t have the way to convert it automatically.

PS:This won’t clone the graphics so they are actually two arrays with the pointers to the same objects. If you want to clone them you’ll have to change the line

cloned[i] = array[i];

for

cloned[i] = clone(array[i]) as Graphic;

and the clone function is the same as you have (but you should make it public and static to be used with my function).


(Darrin) #3

Nice! Worked perfectly with one change. I had to change i to a String, not sure why that is. It is an array of entities…maybe it just likes the String for the class name.

		public static function cloneArray(array:Array):Array
	{
		var cloned:Array = [];
		for (var i:String in array)
		{
			cloned[i] = array[i];
		}
		return cloned;
	}

(Martí Angelats i Ribera) #4

Oh ok, I missunderstood that. Well it’s the same changing Graphic for Entity if you want to clone it.