Mario
Mario

Reputation: 13

Convert String into an object instance name

I'm trying to turn an string into an instance name.

stage.focus = ["box_"+[i+1]];

this gives me back = box_2;

but I need it to be an object not a string.

In as2 I could use eval. How do I do it in as3?

Upvotes: 1

Views: 6052

Answers (3)

Jorjon
Jorjon

Reputation: 5434

If you want to access a member of the current class, the answers already given will work. But if the instance you are looking isn't part of the class, you are out of luck.

For example:

private function foo():void {
    var box_2:Sprite;
    trace(this["box_"+(i+1)]);
}

Won't work, because box_2 isn't a part of the class. In that case, it is highly recommended to use an array.

If you want to access a DisplayObject (for example, a Sprite or a MovieClip) you also can use getChildByName. But in that case, box_2 will be the name of the object, instead of the name of the variable. You set the name like

var box:Sprite;
box.name = "box_2";

But again, I recommend an array.

Upvotes: 0

rzetterberg
rzetterberg

Reputation: 10268

For example if you would like to call the function "start" in your main class, you'd do it this way:

this["start"]();

Same thing goes for variables. Since all classes are a subclass of Object you can retrieve their variables like you would with an ordinary object. A class like this:

package{
    import flash.display.Sprite;
    public class Main extends Sprite{
        public var button:Sprite;

        public function Main(){
            trace(this["button"]);
        }
    }
}

Would output:

[object Sprite]

Upvotes: 2

danii
danii

Reputation: 5703

The correct syntax is:

this["box_"+(i+1)]

Upvotes: 9

Related Questions