ActionScript 3 101: Advanced Functions (Part 6.1)

In the last tutorial we looked at writing your first function in your ActionScript 3 web project.

This tutorial will look at doing more with functions, as well as look into functions which return a value. We will do this by creating a basic, two value, calculator (see below). This project will span more than one tutorial so today we are just going to introduce you to the basic function and the logic operators, then we will look at expanding it and building the user interface.

Firstly create yourself an ActionScript 3 project (follow this post for guidance: Your first ActionScript 3 Project)

Create a layer in the time line, call it actions and place your script in the first frame on the time line.

Now we will write our calculator function, write the code as it appears below:

function myCalculator (firstNumber:Number, secondNumber:Number, calcType:String):Number
{
  if(calcType=="+")
  {
    return firstNumber+secondNumber;
  }
  else if (calcType=="-")
  {
    return firstNumber-secondNumber;
  }
  else if (calcType=="*")
  {
    return firstNumber*secondNumber;
  }
  else if(calcType=="/")
  {
  return firstNumber/secondNumber;
  }
  else
  {
    return 0
  }
}

This is the basic function for our calculator and will operate accepting three values – two numbers and the calculation operator (*, -, /, +)
I am aware we have not covered conditional statements yet in this series but we will look at the code more closely in the next post.

In the next post we will break down the code and explain each section.

Be Social:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>