hb.
hb.

Reputation: 1765

Arbitrary number of parameters in AS3

Does ActionScript 3.0 offer any means to accept an arbitrary number of parameters? I usually use .NET, but I'm being forced to use AS3 for a project and something along the lines of function blah(params double[] x) would be awesome for a helper library.

Thanks;

Upvotes: 6

Views: 5956

Answers (4)

Parappa
Parappa

Reputation: 7676

In addition to the "rest" parameter, there is an "arguments" object.

function foo() {
    for (var i:Number = 0; i < arguments.length; i++) {
        trace(arguments[i]);
    }
}

Upvotes: 2

James Keesey
James Keesey

Reputation: 1217

If you want to pass an undetermined number of ordered values just pass an array

function foobar(values:Array):void
{
    ...
}


foobat([1.0, 3.4, 4.5]);
foobat([34.6, 52.3, 434.5, 3344.5, 3562.435, 1, 1, 2, 5]);

If you want to pass named parameters where only some of them are passed then use an object

   function woof(params:object):string
   {
       if (params.hasProperty('name')) {
           return name + "xxx";
       }
       ...
   }

   woof({name:'Joe Blow', count: 123, title: 'Mr. Wonderful'});

Upvotes: 0

eduffy
eduffy

Reputation: 40224

Try an ellipse (like C) ...

function trace_all (... args): void {
    for each (a in args) {
       trace (a);
    }
}

Upvotes: 3

Christophe Herreman
Christophe Herreman

Reputation: 16085

Check out the rest parameter: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/statements.html#..._(rest)_parameter

package {
  import flash.display.MovieClip;

  public class RestParamExample extends MovieClip {
    public function RestParamExample() {
        traceParams(100, 130, "two"); // 100,130,two
        trace(average(4, 7, 13));     // 8
    }
  }
}


function traceParams(... rest) {
 trace(rest);
}

function average(... args) : Number{
  var sum:Number = 0;
  for (var i:uint = 0; i < args.length; i++) {
    sum += args[i];
  }
  return (sum / args.length);
}

Upvotes: 14

Related Questions