views:

25

answers:

1

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 http://stackoverflow.com/questions/2155335/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.

+1  A: 

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);
Patrick
Thanks, Patrick. Your suggestions helped me think through the last stages of this problem. I almost went with the idea of wrapping the variable in an Object, but I ended up passing a callback function to the 'replaceValue' method (which is a static method on a different object, btw). Just setting the value of the variable in the callback, now. Which, yeah, is pretty gross, but... is a decent solution in this case. Thanks, again.
Ross Henderson