-
AS3 - how to do eval() the right way
Posted on June 27th, 2008 8 commentsIn AS2 we used to be able to refer to an instance name of an object by coding:
///AS2.0\\\
eval("my_mc"+i);This would allow you to create and/or refer to instance names using a string. I have heard quite a bit of negativity about eval() but it did come in handy at times. In AS2, you could also use:
///AS2.0\\\
_root["my_mc"+i];which worked well for me when pushing items to an array, before AS3 was available.
Now, the correct AS3 way to do it is either this:
///AS3.0\\\
this["my_mc" + i];or:
///AS3.0\\\
this.getChildByName("my_mc" + i);I would recommend the second way of doing it, because to me it just makes more sense.
8 responses to “AS3 - how to do eval() the right way”
-
testor April 30th, 2009 at 06:37
Hey great !!! after 20 min searching on google, you are the only one giving a REAL solution to this problem(solution 2 is the best yeah :))
Thanks a lot !
-
Glad I could help!
-
davidesieb July 28th, 2009 at 03:13
Hello, but how make AS3 “evaluate” a variable value?
Say I have a variable:
var vMyExampleVar_X:Number = 100;
var vMyExampleVarTwo_X:Number = 50;and I want to dynamically access to it :
function fReturnVarValue (vVarName) {
var vValue = this["v"+vVarName+"_X"];
return vValue;
}
//
fReturnVarValue (”MyExampleVar”);
fReturnVarValue (”MyExampleVarTwo”);-> this doesn’t work… See what I mean?
Thanks for your help -
I tested your code that you wrote and it seems to work just fine that way. created variables from your function and traced them and they are returning correctly - see the updated code below
var vMyExampleVar_X:Number = 100;
var vMyExampleVarTwo_X:Number = 50;
//
function fReturnVarValue (vVarName) {
var vValue = this["v"+vVarName+"_X"];
return(vValue);
}
//
var newVar1:Number = fReturnVarValue (”MyExampleVar”);
var newVar2:Number = fReturnVarValue (”MyExampleVarTwo”);
trace (newVar1)
trace (newVar2)Hope this helps you - let me know if you have any other troubles.
-
Vinay July 30th, 2009 at 02:06
Hi Thanks a lot for wonderfull solution
-
Thanks!, this helps so much…but i have a new question. Im trying to create a new instance dinamicaly, like this:
———————————-
….
var slidesNum:int = 1;
var mcString = “mc”+1;
var oMc1:MovieClip = new[mcString]();
….
———————————-and it returns this:
TypeError: Error #1007: Instantiation attempted on a non-constructor.should this works?
Im really stuck… can u give-me a little hand?..(or a entire arm?)
-
i try this too
———————————-
….
var slidesNum:int = 1;
var mcString = “mc”+1;
var oMc1:MovieClip = new this[mcString]();
….
———————————-the result is the same!
-
Try this out:
var slidesNum:int = 1;
var mcString:String = “mc”+1;var oMc1:MovieClip = new MovieClip();
oMc1.name = mcString;Let me know if that is what you are trying to do. Without seeing more of your code I am not sure if that is what you will need.
Leave a reply
-


