Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3: Using string as variable

Is there a possibility to extract variable name from string and using it as variable

var myvar:String = "flash";
var flash:Number = 10;
trace( myvar as variable );

something like that

like image 385
Muhammad Avatar asked Dec 15 '22 23:12

Muhammad


2 Answers

Variable name as Strings can be done like so:

this["myvar"] = "flash";

Notes:

  • This will throw a ReferenceError if the property has not been previously defined AND the this refers to an object which is not dynamic.
  • You can of course replace this with the instance name of an object you want to use a property from, e.g. mySprite["x"].
  • You can also use this approach to call methods: this["addChild"](mySprite);
like image 93
Marty Avatar answered Jan 04 '23 08:01

Marty


You can use it as a property of an object.

public dynamic class MyClass {
    function MyClass(propName:String, propValue:*) {
        this[propName] = propValue;
    }
}

or

var myvar:String = "flash";
var o : Object = {};
o[myvar] = 10;
trace(o.flash); //10

If you don't know what property name is going to be, then you should use dynamic class (Object is dynamic by default)

like image 38
Timofei Davydik Avatar answered Jan 04 '23 09:01

Timofei Davydik