Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Dynamic Variable name In ActionScript 3.0

I need to set custom variable name for every iteration. Why this isn't possible?

for (var i:uint = 0; i < 50; i++)
{
   var ['name' +i] = new Sprite();
}
*//1840: Syntax error: expecting identifier before left bracket*
like image 544
dd . Avatar asked Oct 11 '09 22:10

dd .


2 Answers

You want to use a hash map to do this.

var map:Object = {};
for (var i:uint = 0; i < 50; i++)
{
   map['name' +i] = new Sprite();
}

Otherwise you're confusing the compiler. Dynamic names for local variables aren't allowed.

like image 174
Glenn Avatar answered Nov 15 '22 06:11

Glenn


There is sort of a way around this, depending on what you're doing. If these clips are all added to stage then you can use the getChildByName method to access them. Your setup would look something like this:

var clips:Array = [];

for (var i:int = 0; i < 100; i++) {
    clips[i] = new MovieClip();
    clips[i].name = "clip" + i;
    addChild(clips[i]);
}

trace (getChildByName("clip2")); // traces [object MovieClip]

This is done by querying the display API, though, so you can't use getChildByName on anything that's not added to a display list somewhere.

Hope that helps!

like image 30
Myk Avatar answered Nov 15 '22 06:11

Myk