PDA

View Full Version : cast string to variable name


Toyfruit
10-02-2009, 05:29 PM
Hi All

I have a variable in flash:

var myVariableName:Number = 0;

I then have a multidimensional array which has this variable name in it, but as a string

var myArray:Array = new Array(new Array("mySomething Else", "myVariableName"));

What I need to do is be able to reference the string item in the array, but then cast it so that when I add a number to it the ACTUAL variable with the same name will be altered - anyone know how I can do this?

For reasons I won't go into I can't pass it straight into the variable, it has to go through the multidimensional array item.

Help??

rawmantick
10-02-2009, 05:55 PM
Store the values in a Dictionary (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/Dictionary.html)...

Toyfruit
10-02-2009, 06:04 PM
Ok... thanks .. I'm not familiar with Dictionary ... looks like I'll have to investigate that ... is this the AS3 equivalent of the AS2 way you might have written this, which would be something like:

this[myArray[1]] = 20;

?

rawmantick
10-02-2009, 06:08 PM
var vars:Dictionary = new Dictionary();

vars["myVar1"] = 1;
vars["myVar2"] = 2;

trace(vars["myVar1"]);
Dictionary is an associative array, that allows you to access elements by some key (not only string).

RogerClark
10-02-2009, 09:01 PM
You can also use Object

var vars:Object = new Object();

vars["myVar1"] = 1.234;
vars["myVar2"] = 2;

trace(vars["myVar1"]);

Which may be faster than Dictionary, but its always struck me as being a bit of a hack.
So you are probably better off using Dictionary

henke37
10-03-2009, 09:50 AM
It's not a hack if it's designed to be used that way.