Flash Explained

Learn Flash easily.

How to use the modulo operator (%) in ActionScript

October 12th, 2008 | Author: Luka | Category: ActionScript


Learn to use the modulo operator (%) in Flash! There arenā€™t a lot of explanations for it around, but it can be really useful in some cases. You will also learn the way a conditional statement in ActionScript works.

You will use the modulo operator to check if a certain number is even or odd, and to see when a certain number of movie clips, or other objects have been loaded, attached, etc.

Click on the buttons below ā€“ the result in the text field will tell you if the number on the button is even or odd. You will make a similar, albeit a simpler thing in a moment.

This tutorial is written in ActionScript 2.0, but there are soucre FLA files with both ActionScript 1.0 and 2.0 available for download at the bottom of this page.

Setting up the scene

1 Open a new flash document.

2 Call the first layer (and the only one for now) text field.

3 Select the Text tool (T). In the Properties panel, on its left side, choose Dynamic Text as type of text field. Choose any font, size and color you like. Since this is an ActionScript lesson, the visual aspect isn't important.

Setting the type of text field in the Properties panel.

4 Click and drag on the stage to create a dynamic text field.

A dynamic text field.

5 Again, in the Properties panel, give the dynamic text field an Instance name, otherwise you wouldn't be able to control its output with ActionScript. Call the field resultField. Lock this layer.

Assigning an Instance name to a textfield.

6 Create a new layer and call it actions. Click on this layer's first keyframe to select it and open the Actions panel (select Window > Actions or press F9).

Write the following code inside the Actions window:

var someNumber:Number = 4;
var evenOrOdd:String;
if (someNumber%2 != 0) {
evenOrOdd = "odd";
} else {
evenOrOdd = "even";
}
resultField.text = someNumber + " is an " + evenOrOdd + " number";

Test your movie (CTRL+ENTER) and see the result! Wow! 4 is indeed an even number šŸ˜‰

Top of page

The use of the modulo operator explained

The first two lines of code define the variables which are used.

var someNumber:Number = 4;
var evenOrOdd:String;

Since this is ActionScript 2.0 code, strict typing is used. What does that mean? That means that you must define the type of the variable when you are creating it. You must tell Flash is it a variable that will hold a numerical value, a string (text) value, boolean (true or false) or some other type of value.

So, by writing var evenOrOdd:String; you tell Flash that the variable evenOrOdd will hold a string value. The syntax (the way you write the code) is always: name of variable, semicolon, type of value.

You can define the variable and assign it a value in the same line (like you did in the first line) or you can assign a value later (this is the case in the second line of your code). I wrote the number 4 arbitrarily. You can put in any number you like - 1, 8, 3, 14, 100...

Next comes a conditional statement. And what's that? Simple. If the condition that must be met is true, the code between the { curly braces } is executed. If it isn't, that line is skipped like it never existed at all. It is completely ignored.

So, the line:

if (someNumber%2 != 0) {

has a condition between parentheses that uses the modulo operator. The modulo operator divides the first number by the second and returns the remainder of the division. Example:

10%2 would return zero. Why? Because there is simply no remainder left. 10 divided by 2 is exactly 5, so there is no remainder.

But, if you, say, did the following division with the modulo operator: 15%2, you would get 1 as the result. Why? If you divide 15 by 2, you get 7 as the first whole number. 7 multiplied by 2 equals 14, plus 1 as the remainder to reach 15. OK?

So, this is used to check if a number is odd or even. In your case, the consition is evaluated in the following way. someNumber variable (it has a value of 4 or any other number you may have put there) is divided with the modulo operator:

someNumber%2

4%2

0

The result of the above operation is zero, because 4 or any other even number divided by 2 leaves no reminder.

Next, Flash checks if this result does not equal zero. This is done with the inequality operator (!=). So, what happens is this:

0 != 0

The condition between the parentheses proves false for all even numbers, because they all give zero as the result of the division with the modulo operator.

In the above line, it says (translated from ActionScript into english): zero does not equal zero. This is false. So in the case of every even number, the line of code between the curly braces

evenOrOdd = "odd";

is skipped. Which is exactly what you want. Then comes an else statement, which basically means if the first condition is false, execute the portion of code between the next curly braces.

} else {
evenOrOdd = "even";
}

This line sets the value of the variable evenOrOdd to "even". What happens if there is an odd number at the start? Let's say it is 7. The condition would be evaluated like this:

if (someNumber%2 != 0)

if (7%2 != 0)

if (1 != 0)

There is 1 left as the remainder of the division of 7 by 2 with the modulo operator. So, at the end of the operation it says that 1 does not equal zero. Which is true. So the code between the first pair of curly braces is executed. This code sets the value of the evenOrOdd variable to "odd". The next pair of curly braces and the line of code it contains are completely ignored.

The last line simply displays the result in the dynamic text field you created in the first portion of this tutorial.

resultField.text = someNumber + " is an " + evenOrOdd + " number";

The resultField.text literally says, the text of the text field which has an Instance name resultField should be the one found on the right side of the equality sign.

ActionScript is case sensitive. That means that you must write the Instance name of your dynamic text field in the code exactly as you entered it in the Properties panel. Therefore, resultField and resultfield (or ResultField) are two different Instance names.

Everything that is written between the quotation marks will be literally displayed in the text field. The spaces also. If you wrote

resultField.text = someNumber + "is an" + evenOrOdd + "number";

all the text would appear "glued toghether" as a result. someNumber and evenOrOdd are variables, so their values are displayed in their respective places. If you put those two between quotation marks("someNumber"), they would appear literally as a result:

someNumber is an evenOrOdd number

Remember, Flash considers everything between the quotation marks as ordinary text. That's why variable names must never be put between them.

Download the zipped source .fla files for this tutorial in both ActionScript 2.0 and 1.0 formats.

Download the zipped source .fla file for the example found on top of this page.

Comments

Submit a comment

  • Marc Oct 24, 2008 at 12:46 am

    This is good as far as it goes, but it falls short of an important feature of modulo.

    When any number (dividend) is divided by another number (divisor), modulo tells you what the remainder is. So modulo can be used with any divisor, not just the number 2. For example, I might want to know if a number is exactly divisible by 7:
    someNumber: Number = 39;
    if (someNumber % 7 ==0){
    trace (“It’s exactly divisible by 7!”);
    } else {
    trace (“There’s a remainder of ” + someNumber % 7);
    }

    Let’s say you design a game and you want to ring a bell every 10 points. Each time the player scores, you could use modulo to determine if the new score is exactly divisible by 10, in which case you’d ring the bell.

  • Luka Oct 24, 2008 at 1:32 pm

    Marc: I have written the tutorial for one option only, which is much widely used. Your idea just didn’t spring to mind at the time – thanks for the tip! Good info.

  • Jason Sep 14, 2009 at 9:19 am

    Yeah .. but the moduli does not work for negative numbers.

    eg. i was had to use moduli 26, and i didn’t have a calculator nearby, so i grabbed my laptop and scripted up some code and it works for negatives too

    \\variable is set to as ans1, inputtext is the text box
    \\26 is what you would use as the “% 26”
    \\Math.floor rounds the answer down to an integer
    ans1 = Math.floor(inputtext / 26);
    \\answer is a textbox set to display the answer
    answer = num1 – (ans1 * 26);

    Hope this helps someone.

  • vincent Mar 13, 2010 at 1:02 pm

    how to use the modulo operator in this problem

    101 hours = 61 minutes

  • Ale Jul 7, 2010 at 4:05 pm

    Muy bueno man.

  • D Jun 21, 2011 at 6:06 am

    The important thing to note here is that Actionscript uses a non-standard definition of the modulo operator. It returns the remainder of a division and can thus return negative results on negative inputs, opposite to the mathematical definition of modulo which only returns positive results. The definition varies between different coding languages, the mathematical being the most common.

    Mathematical: -7 % 3 = 2
    ActionScript: -7 % 3 = -1

  • Irakli Geleishvili Apr 2, 2015 at 9:32 pm

    To stay in positive range, you can do:

    var currentNumber = 1;
    // decrement by -1;
    currentNumber = (8 + –currentNumber – 1) % 8 + 1;

    You stay in range 1-8 looping around.

  • Irakli Geleishvili Apr 2, 2015 at 9:35 pm

    Sorry, comments system deleted one “-“.
    (8 + [[double minus here]]currentNumber ā€“ 1) % 8 + 1;

You must log in to post a comment.