PDA

View Full Version : passing around variables


saltzmanjoelh
02-03-2009, 11:55 PM
If I have an arrayCollection and I pass it into a function. Then I want to set the arrayCollection to a new array collection how do I do that?

myAc = new ArrayCollection(["1", "2"]);
updateAc(myAc);


private function updateAc(ac:ArrayCollection):void{
ac = new ArrayCollection(["3", "4"]);
}

this would update the ac var in the function not what the ac var represents. I want to update what the ac in the function represents or points to...

x33905
02-04-2009, 05:47 AM
Right, because you're declaring ac in the function as being a new ArrayCollection. It's no longer referencing the array that was passed to the function.
Assuming arrayCollection extends the Array class, if you just said...

private function updateAc(ac:ArrayCollection):void{
ac.splice(0, ac.length);
ac.push("3", "4");
}

It would be editing the original array.

saltzmanjoelh
02-04-2009, 09:41 PM
I understand that. I would describe your method as modifying the properties of the original AC. There are many ways to modify the original AC. I could just add each item to the AC. I dont want to modify it though. I dont want to do that.

I want to set the original AC to a new AC through the reference in the function.

x33905
02-05-2009, 04:15 AM
Would this meet your needs?


var array1:Array = new Array();
array1.push(1, 2, 3);
array1 = function1(array1);
trace(array1);

function function1(array1:Array):Array
{
var array2:Array = new Array();
array2.push(4, 5, 6);
return array2;
}

x33905
02-05-2009, 04:24 AM
Although strictly speaking this is just modifying the first array as well. I could tell you how to do this in C++ but unfortunately AS3 doesn't give you the ability to specify &address pointers. I don't know how it would work though when the new array you create in the function goes out of scope though - I haven't used C++ in a while and I'm not sure how Flash handles this.

saltzmanjoelh
02-05-2009, 08:34 PM
Yeah, Im looking for that c++ solution for AS3. I have a remote call that on async return it needs to replace the old variable.

x33905's example works for the ac but I guess I should have used an object example.

private var oldObject:Object;
update(oldObject);

public function update(obj:Object):void{
var token:AsyncToken = service.update.send();
token.oldobject = obj;
var responder:Responder = new Responder(updateComplete, updateFault);
token.responder = responder;
}

public function updateComplete(e:ResultEvent):void{
e.token.oldObject = e.token.result; // this changes e.token.oldObject not what oldObject points to...
}