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
Variable name as Strings can be done like so:
this["myvar"] = "flash";
Notes:
ReferenceError if the property has not been previously defined AND the this refers to an object which is not dynamic.this with the instance name of an object you want to use a property from, e.g. mySprite["x"].this["addChild"](mySprite);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)
What you require is similar to the Dictionary class in .NET, and it is available by default in the Object class of AS3.
var key:String="hello";
var value:int=100;
var map:Object=new Object();
map[key]=value;
Now, you can get your stored value as
trace(map[key]);
If you want, you can also build on this to make a class like the following:
public class Dictionary {
private var _keys:Array;
private var _maps:Object;
public function Dictionary() {
_keys=[];
_maps:Object={};
}
//Returns the array of all saved keys
public function get keys():Array {
return _keys;
}
//Sets a key-value pair
public function setProperty(key:*, value:*):int {
_maps[key]=value;
return _keys.push(key);
}
//Returns the value stored at a particular key
public function getProperty(key:*):* {
if(_keys.indexOf(key) != -1) {
return _maps[key];
}
return null;
}
//Removes a key-value pair if it exists and returns if the key existed
public function deleteProperty(key:*):Boolean {
var ix:int;
if((ix=_keys.indexOf(key)) != -1) {
//dissociate value from key
delete _maps[key];
//delete key
_keys.splice[ix,1];
return true;
}
return false;
}
}
And you can use this as:
var dict:Dictionary=new Dictionary();
//set the value
dict.setProperty("flash", 10);
//get the value
dict.getProperty("flash");
//delete if not required
dict.deleteProperty("flash");
Note that this can be used to set keys and values of ANY type. Also it resolves the issue of the ReferenceError if the property is not defined, and you don't need to use any dynamic class in YOUR code (since the Dictionary class handles it internally).
One very typical use of this would be to define parse functions. e.g. in a spreadsheet viewer:
var parseFuncts:Dictionary=new Dictionary();
parseFuncts.setProperty("csv", Parsers.parseCSV);
parseFuncts.setProperty("xml", Parsers.parseXML);
parseFuncts.setProperty("txt", Parsers.parseTXT);
parseFuncts.setProperty("xls", Parsers.parseXLS);
parseFuncts.setProperty("xlsx", Parsers.parseXLSX);
var fileToOpen:File; //Already contains the file to open
private function open():void {
var f:Function=parseFuncts.getProperty(fileToOpen.extension);
f.apply(this);
}