I’m new to Actionscript programming. I’m trying to figure out what is the best way to return multiple variables, each having a different data type, from a function. For example, if a function needs to return variable aa ( a string) and variable bb (a number).
The function I’m using just crunches a lot of math, and doesn’t relate to an object in a GUI. One method I got from a Google search used an Object, but as (I think) this requires me to create a class, I wondered if there was a simpler way. Since an array can hold elements of different data types, perhaps this is a simpler approach (?).
Here’s an example mxml and AS3 file taken from “Flash Builder 4 and Flex 4 Bible” by David Gassner.
file: Calculator.mxml
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:components="components.*">
<fx:Script source="calculator.as"/>
<s:Panel title="Calculator" horizontalCenter="0" top="20">
<s:layout>
<s:VerticalLayout horizontalAlign="center"/>
</s:layout>
<mx:Form>
<components:ButtonTile id="input"
select="selectHandler(event)"
calculate="calculateHandler(event)"/>
<mx:FormItem label="Entry:">
<s:TextInput text="{currentInput}" editable="false" width="80"/>
</mx:FormItem>
<mx:FormItem label="Total:">
<s:TextInput text="{currentResult}" editable="false" width="80"/>
</mx:FormItem>
</mx:Form>
file: calculator.as
//ActionScript code for Calculator.mxml
[Bindable]
private var currentResult:Number=0;
[Bindable]
private var currentInput:String="";
private function calculateHandler(event:Event):void
{
currentResult += Number(currentInput);
currentInput="";
}
private function selectHandler(event:TextEvent):void
{
currentInput += event.text;
}
Could someone illustrate how to modify one of the functions in calculator.as, just as an example how to return two values, where one is a number and the other a string? Is there an obvious best-way to do this, or, what would be the pros/cons of different approaches? Thanks in advance!
You could just simply return an
Objectwhich isdynamicand thus lets you define values on the fly, like this:Or:
But in my opinion this is really poor practice (especially if your function is to return the same sets of information with new values).
I’d take this route:
You can create your own class that holds various properties. From there you can return an instance of this object with the properties defined as you wish.
Example:
This would be in an external file called
CollisionData.asAnd your function could be:
Then you can create your own collision data based off the result:
And fetch the details: