A Flash Developer Resource Site

Results 1 to 3 of 3

Thread: strange linked array?

  1. #1
    Junior Member
    Join Date
    Mar 2001
    Posts
    4
    hi,

    i'm currently doing some stuff for a flash game and have come across an odd problem...

    heres the relevent lines of code...

    var statsAry = new Array();
    statsAry[1] = {utype: "tank", movespeed: 2, ap: 100, hp: 250, mcost: 50, fcost: 50, damage: 75};

    _root["unit"+numunits].stats = _root.statsAry[1];

    there can be multiple units with the same stats, so i thought the above would be a nice clean way of generating their details

    thing is though, when you get into the game and start changing the values e.g.

    _root.unit5.stats.ap = 50;

    it not only changes that unit, but all other units of the same type *and* the initial root array?? why?? :/

  2. #2
    half as fun, double the price senocular's Avatar
    Join Date
    Feb 2002
    Location
    San Francisco, CA (USA)
    Posts
    4,358
    array variables are "pointers" to the array in memory. If you have:

    arrayOne = [1,2,3,4,5];

    then the variable arrayOne is pointing to a block of 5 variable values (numbers) somewhere out in your computers memory. When you try to assign another variable name to be that array ie.

    arrayTwo = arrayOne;

    Then that new variable will get the pointer aspect of the old one, where it would then point back to that same block in memory and each arrayOne and arrayTwo would be accessing and changing the same values.

    To prevent this, you need to make a copy of the array. In flash you can do this using the Array objects slice method which extracts a portion (or all) of the given array and returns it as a new array.

    arrayOne = [1,2,3,4,5];
    arrayTwo = arrayOne.slice();
    arrayOne[0] = "a";
    trace(arrayOne); // a,2,3,4,5
    trace(arrayTwo); // 1,2,3,4,5

  3. #3
    Junior Member
    Join Date
    Mar 2001
    Posts
    4
    ta muchly

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center