-
The scope of a function
i have a function that changes a root variable that i pass into it. the problem is that the changes to the variable are only present in the function, once the function ends the new value disappears as well. here is a simple example of what i'm talking about:
Code:
//there's the variable i want to manipulate
fakeVar=100;
function mult(whichVar){
//let's multiple the variable by 2.
whichVar*=2;
trace(whichVar) // traces 200...correct.
trace(fakeVar) //traces 100, the original value, not correct
}
box.onRelease=function(){
//call the function with the variable i want to update.
mult(fakeVar)
}
the function changes the variable within its own scope, but is there a way for it to change the variable outside of its own scope as well? In my real code, the code within the function is in an onEnterFrame event, so i need it to update the variable every frame....
-
Welcome to FK.
When you pass in a primitive value (such as a number ) then it is passed by copy (not by reference as in the case of an object)..
So basically in your function the parameter whichVar simply has the value 100 and is in no way connected to the variable fakeVar
if you actually want to change the value of fakeVar then you will need to do reference it directly within the function e.g
Code:
var fakeVar:Number = 100;
function mult(whichVar:String) {
this[whichVar] *= 2;
trace(fakeVar);
}
box.onRelease=function(){
mult("fakeVar");
}
-
Thanks for the advice
wow, wouldn't have thought to structure it like that....makes perfect sense.
while waiting for a response i came up with such a convoluted way around this problem, i was returning an array with the values i needed and then setting the variables to the corresponding array items outside the function...this will save me so much time.
thanks!
-