Dynamic variables in a loop

9 posts

Flag Post

Hi, can I do something like this in actionscript?

for (i=1;i<5;i++){
myvar&i = i;

so in the end I have 5 variables:

myvar1 = 1
myvar2 = 2
myvar3 = 3
myvar4 = 4
myvar5 = 5

Or is this impossible? I’m trying to clean up some of my code and would love to get this working. Thanks!


Flag Post

Found my answer finally. Thanks!

set (“myvar” + i, i);

Flag Post

You could just use an array. In as2 (not sure about as3) you don’t even need to specify the length of the array, you can just keep adding elements.

Flag Post

Why do you need variables like that? Its better to use proper methods like an array as undersiege pointed out. The set() method is a Flash 4 method, which shouldn’t really be used anymore.

Flag Post

As the other two have said, that’s a really bad method of doing it – It’ll be a real pain to try and get that information back out again, using an array would be better:

myArray = new Array()

for (i=1;i<5;i++){ myArray[i] = i; }

However, if you are desperate to go about it your way, I think you can do something along the lines of

myvar.i = i;

which ends up as myvar1, myvar2 etc., but that probably isn’t the exact solution, you’ll need to look it up. Much better to use the array

Flag Post

You can do _root["myvar"+i] = i; (as2)

Not really recommended, though – use an array…

@kalinium, that can’t be right. Surely that would just set the “i” variable of myvar over and over?

Flag Post

It’s actually 5 different movie clips. I’m using the same logic based on info I store in a tree to set their visibility to true or false. My code looks like this:

set(“myvid” + i + “._visible”, false); (or true based on logic statements before it)

Should I create an array of movieclips and enter each of those into the array and change it like that?

Flag Post

No, just do:

root["myvid"+i].visible = false;

Flag Post

Hmmm… That worked.

Wow, I really have no idea how to program in flash =).

Thanks for everyone’s help. And everyone’s help in the past as well. This forum has been a great place to get answers for my stupid questions!