_root["string" + var] - question

So I wanna merge a string and a variable to get another variable. I tried this syntax, but I get “undefined” as output. What am I doing wrong?


	var temp_1 = "testing";
  	var temp_2 = 1;
  	trace(_root["temp_" + temp_2]);
 

Simple typo:

var temp_1 = "testing";
var temp_2 = 1;
trace(_root["temp_**1**"+temp_2]);

If you don’t have an object of some kind (movie clip, variable, array, etc), somewhere called _root.testing1, then the trace will have nothing to show:


  var testing1 = "Hello World";
  
  var temp_1 = "testing";
  var temp_2 = 1;
  trace(_root["temp_1"+temp_2]);
  

What are you trying to do MrFlashALot?

Actually flash will search for an object named temp_11

Ehm …


var temp_1 = "testing";
var temp_2 = 1;
trace(_root["temp_"+temp_2]);

outputs “testing”, as it should. By the way, it’s better to use this in this situation instead of _root.

Yes voets, i noticed that only after i had already replied :stuck_out_tongue:

Oops… heh… should have looked at what the code ACTUALLY said, rather than what I THOUGHT it said…

Lol, what did you think you said then ? :stuck_out_tongue:

Same here :stuck_out_tongue: :stuck_out_tongue:

Im just trying to display the text within the variable “temp_1” by merging the string “temp_” with the value inside variable “temp_2” (which is 1).

But even trying your code I get undefined as trace-output. I just cant get it to work very confused

Are you using Flash 5 ?

Do you actually get “testing” as output with that code?


var temp_1 = "testing";
var temp_2 = 1;
trace(_root["temp_"+temp_2]);

Ive tried pinning it to a simple button, but it ouputs “undefined”.

This is really strange - maby I got some bug here or something?

nope, using flash mx 2004 (v.7.2)

Wait wait.

  1. Are you using Flash 5 ? **edit: nvm
  2. If this code is on a button, then the _root may be your problem. Where is this button located ? On the main timeline ?

yes, right on the main timeline (using a button-component, with on(click){} code)

Ill be ****ed (or darned, if you prefer) - I tried the exact same code but on a button I created and with the on(press){} code instead, and what do you know, it worked fine!!

So, the component button was the villain :stuck_out_tongue:

Use this:


on (click) {
	temp_1 = "testing";
	temp_2 = 1;
	trace(this["temp_"+temp_2]);
}

:wink:

Ok :slight_smile: Thanks a lot for the help, guys :slight_smile:

No problem :slight_smile: