Ross Henderson
Ross Henderson

Reputation: 1779

Changing the value of a var via reference in AS3

I'm pretty positive what I want to do isn't possible with ActionScript, but it would be nice to be wrong.

I need to pass a variable reference to a function, and have the function change the value of the variable.

So, simplified and not in completely correct syntax, something like this:

function replaceValue(element:*, newValue:String):void  
{ 
    element = newValue;  
}

var variableToModify:String = "Hello";  
replaceValue(variableToModify, "Goodbye");

trace(variableToModify) // traces value of 'Hello', but want it to trace value of 'Goodbye'

Of course, in the replaceValue function, element is a new reference to fungibleValue (or, rather, a new reference to fungibleValue's value). So, while element gets set to the value of newValue, fungibleValue does not change. That's expected but totally not what I want, in this case.

There's a similar question, for Ruby, here Changing value of ruby variables/references

As the question points out, Ruby has a way to accomplish this. BUT is there any way to do this in ActionScript?

If so, it's going to make something stupid a lot easier for me.

Upvotes: 0

Views: 513

Answers (1)

Patrick
Patrick

Reputation: 15717

No it's not possible the function will always get the value and not the reference. But if you are able to call replaceValue why not returning the new value from your function :

function replaceValue(element:*, newValue:String):String  
{ 
 // .. do your work
 return newValue;  
}

var variableToModify:String = "Hello";  
variableToModify = replaceValue(variableToModify, "Goodbye");

trace(variableToModify)

If you pass an Object or a Class, you can modify one fiels based on his name as :

function replaceValue(base:Object, fieldName:String, newValue:String):void {
 // do your work
 base[fieldName] = newValue;
}

var o:Object={ variableToModify:"Hello" };
replaceValue(o, "variableToModify", "Goodbye");

trace(o.variableToModify);

Upvotes: 1

Related Questions