1

I have a for loop in action script which I'm trying to use to dynamically create variable.

Example

for( i = 0 ; i < 3 ; i++)
{
    var MyVar+i = i;
}

after this for loop runs, i would like to have 3 variables named MyVar1, MyVar2, MyVar3. I know the code above will give you a syntax error, but that is just to illustrate what I am trying to do. Any takers?

The primary reason i'm doing this is because I'm having scope problems noted here in this other unanswered Action Script question: How to pass variables into inline functions in Action Script 2

Thanks!

2 Answers 2

4

I could be wrong (I haven't done AS2 for a long while), but I think you can do this using array syntax:

 for( i = 0 ; i < 3 ; i++)
{
    this["myVar"+i] = i;
}

and then for variable access:

var foo = this["myVar0"] //etc
Sign up to request clarification or add additional context in comments.

Comments

1

First answer is correct, but if you make the class dynamic (ie. new members can be created dynamically) ...

dynamic class ClassName { // etc. }

... then you can reference the variable in normal syntax:

var foo = this.myVar0;

You won't be able to access the variable at all without 'this' whether the class is dynamic or not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.