Thursday, March 15, 2007

AS3 object mistake

Most of my experience in coding is with a procedural language on an IBM iSeries. And on occasion I fall into old habits in as3. For example, I coded:

var var1:Text = new Text();
var var2:Text = new Text();
var1.text = "Var 1 text";
var2.text = "Var 2 text";
trace(var1.text, var2.text);
var2=var1;
trace(var1.text, var2.text);
var1.text="Some new var1 text";
trace(var1.text, var2.text);

and didn't expect these results:

Var 1 text Var 2 text
Var 1 text Var 1 text
Some new var1 text Some new var1 text


Oops. Old (and bad) habits die hard. In RPG, I'd expect the system to take care of instantiating a new object, so a change to var1 didn't also change var2. I know better in as3, but it had me puzzled for a few minutes. This works:

var var1:Text = new Text();
var var2:Text = new Text();
var1.text = "Var 1 text";
var2.text = "Var 2 text";
trace(var1.text, var2.text);
var2=var1;
trace(var1.text, var2.text);
var1 = new Text();
var1.text="Some new var1 text";
trace("Final var1: " + var1.text, " -- Final var2: " + var2.text);

and yields:

Var 1 text Var 2 text
Var 1 text Var 1 text
Final var1: Some new var1 text -- Final var2: Var 1 text


Note new object instantiation before the last "Some new var1 text" assignment.

Learning curve.

2 comments:

  1. Hmm. I am not sure this is anything to do with procedural languages. I don't see why the first code produces the result you got. Does the "var2=var1" line permanently link the two variables in memory or something?
    I would never of dreamed you would have to instantiate var1 again as a new object (when it isn't) before you can set its value again. I am probably highlighting my ignorance and demonstrating why I stick to the design, delivery and big picture stuff ;-)

    ReplyDelete
  2. When you copy the object, you also copy that object's reference-to-memory. So you're duplicating the entire object, and not just the handled data referenced by that object name. So if I want to use a new Var1 (which is the purpose for moving it to var2 anyway), I need to instantiate a new one.

    ReplyDelete