Skip to main content
Known Participant
November 15, 2012
Answered

Using variables for function arguments AS2

  • November 15, 2012
  • 1 reply
  • 771 views

 

Hello,

I am trying to create a function in AS2.

After creating the function, I want to use values stored in variables for the function arguments rather than manually typing static values for carrying out the function calculation. Also, I want to use the function to assign a new value to the existing variable.

I have asked a similar question 2 days ago here and got the answer (thank you), but now I got one more question - How can I create the function to assign a value to the variable while that variable itself is also a function argument?

For example, I have 6 numeric variables:

var CoinA:Number = 10;
var CoinB:Number = 20;
var CoinC:Number;

var CoinD:Number = 30;
var CoinE:Number = 40;
var CoinF:Number;

Then I tried to create a function to assign values to variables CoinC and CoinF:

function CalculationA(FirstCoin, SecondCoin, ThirdCoin):Void {

     FirstCoin = SecondCoin + ThirdCoin;

}

CalculationA(CoinC, CoinA, CoinB);
CalculationA(CoinF, CoinE, CoinF);

The above code didn't really assign the values 30 and 70 to the variables CoinC and CoinF but instead, values of CoinC and CoinF are undefined.

Please give me the correct code if there's a correct way of doing this.

Thank you,

This topic has been closed for replies.
Correct answer Ned Murphy

Here is one way of doing it, by passing a string value of the variable name instead of the actual variable name....

var CoinA:Number = 10;
var CoinB:Number = 20;
var CoinC:Number;
var CoinD:Number = 30;
var CoinE:Number = 40;
var CoinF:Number;

function CalculationA(FirstCoin, SecondCoin, ThirdCoin):Void {
     this[FirstCoin] = SecondCoin + ThirdCoin;
}


CalculationA("CoinC", CoinA, CoinB);
CalculationA("CoinF", CoinD, CoinE);

(Note that in your second function call I changed the coins since CoinF (ThirdCoin) is undefined at that point.)

1 reply

Ned Murphy
Ned MurphyCorrect answer
Legend
November 15, 2012

Here is one way of doing it, by passing a string value of the variable name instead of the actual variable name....

var CoinA:Number = 10;
var CoinB:Number = 20;
var CoinC:Number;
var CoinD:Number = 30;
var CoinE:Number = 40;
var CoinF:Number;

function CalculationA(FirstCoin, SecondCoin, ThirdCoin):Void {
     this[FirstCoin] = SecondCoin + ThirdCoin;
}


CalculationA("CoinC", CoinA, CoinB);
CalculationA("CoinF", CoinD, CoinE);

(Note that in your second function call I changed the coins since CoinF (ThirdCoin) is undefined at that point.)

ZKM128Author
Known Participant
November 15, 2012

Oh, Thank you so much!! Works beautifully

Ned Murphy
Legend
November 16, 2012

You're welcome