Bleamer
Bleamer

Reputation: 647

How to pass an array containing all the argument to a function requesting multiple arguments in ActionScript 3?

The idea is to pass an array args[] having [<int>, <String>, <int>]

to a function accepting multiple arguments like:

myFunc (int arg1, String arg2, int arg2 ):void

Such that the function call :

myFunc(args[]); can be realized without altering the original function call.

Any suggestions are welcome.

Upvotes: 1

Views: 189

Answers (3)

Boris
Boris

Reputation: 1191

strictly speaking, polymorphism is not supported, so if your function has this signature :

myFunc (arg1:int, arg2:String, arg3:int):void

any call of myFunc(array); will throw a compile error. There are two ways of achieving what I think you want : either you define your first arg as :* or you use the special AS3 ...rest

  1. first solution, the function is defined as such:

    myFunc (arg1:*, arg2:String = null, arg3:int = null):void{
      if(arg1 is Array){
        var array:Array = arg1 as Array;
        arg1 = array[0] as int;
        arg2 = array[1] as String;
        arg3 = array[2] as int;
      }
      //here you would have to verify your args for coherence
      ...//your code here
    }
    
  2. second solution (I like it better, but it's mainly a 'taste' thing) :

    myFunc (...rest):void{
      var array:Array = rest[0] as Array,
          arg1:int = rest[0] as int,
          arg2:String = rest[1] as String,
          arg3:int = rest[2] as int,
      if(array is Array){
        arg1 = array[0] as int;
        arg2 = array[1] as String;
        arg3 = array[2] as int;
      }
      //here you would have to verify your args for coherence
      ...//your code here
    }
    

hope this helps.

Upvotes: 0

crooksy88
crooksy88

Reputation: 3851

myFunc (args[0], args[1], args[2]);

Upvotes: -2

Raja Jaganathan
Raja Jaganathan

Reputation: 36197

You can use Function.apply().

In your case

myFunc.apply(null,args);

Your args[] should contain same order of your myFunc args list match with your datatype.

So that you can't alter you original function.

Performance wise apply() is not so good. Other situation you can use call().

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()

Upvotes: 7

Related Questions