Subscribe

  • Subscribe  

Can I have a variable number of arguments in AS3?

Posted by Jay | April 14, 2008 .

Having programmed in Java extensively before, I am used to the various features of Java that I take them for granted. Even today, when I first think of the logic for a program, it is based on what can be done in Java and what can’t. So, when I had to use ActionScript for a client, I felt a little disoriented (But naturally!) And that’s when I started trying to figure out how to use the features of Java that I am so accustomed to, for instance, the varargs functionality, in AS3. Whether such features existed in AS3 or whether I needed to adapt my programming to a whole new set of features? To my relief, I found that most of the Java features that I was used to were part of AS3 too.

Getting back to the example mentioned above, I figured out that an AS3 function can be defined to take a variable number of arguments similar to the varargs functionality of Java. What’s more is that there are two ways to accomplish the same: one by using the (rest) parameter and the other by using the arguments object.

I’ll give you a sample of the first method:

private function addition(… args):Number{

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

Now all the following calls can be used without the hassle of redefining the function

  var a:Number = addition(10,50);

  a = addition(10,50,100);
  a = addition(10,50,100,500);
  a = addition(10,50,100,500,1000);

This little discovery definitely took some stress off me. I hope it helps you too.

Leave a Comment

If you would like to make a comment, please fill out the form below.


Name

Email

Website

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Comments


Related Posts


Cox offers . Comcast cable deals . Safety and Signs . Direct TV Offers - usdirect has the best directtv deals