Get the full commented source code of

HTML5 Suika Watermelon Game

Talking about Actionscript 3 and Flash.

Today I was porting my Sudoku creator/solver with PHP in AS3 when I found this strange behavior.

I am calling it “strange behavior” because it’s not properly a bug… let’s say an issue.

Look at this script and its comments…

package {
	import flash.display.Sprite;
	public class wtf extends Sprite {
		public function wtf() {
			var my_array = new Array(1,2,3);
			var my_saved_array = new Array();
			trace(my_array);
			// 1,2,3 ... of course
			my_saved_array.push(my_array);
			trace(my_saved_array);
			// 1,2,3 ... of course
			my_array[2] = 4;
			trace(my_array);
			// 1,2,4 ... of course
			trace(my_saved_array);
			// 1,2,4 !!!! WHY? WHY?
			my_saved_array.push(my_array.slice())
			trace(my_saved_array);
			// 1,2,4,1,2,4 ... dirty trick...
			my_array[2] = 5;
			trace(my_saved_array);
			// 1,2,5,1,2,4 ... yeah!
		}
	}
}

I wanted to save various instances of my_array in my_saved_array in order to make some backtracking, when I found push() does not save the array content but the array itself, so if I change some my_array values, the pushed array will also change.

You can prevent it by saving a copy of your original array like I did with slice().

This does not happen neither with Php nor, as far as I remember, with C

What I know, I had an hard time debugging the script I was writing…

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.