Posted tagged ‘usages’

Understanding the if and }else{ statements, as well as the ! operator

August 13, 2008

It’s important that you do understand the two statements if and }else{ while coding in AS2.0. Those are actually some of the most used, and most useful statements in the language. I’m gonna learn you what they do, and what you can use them for!

STEP 1:

Let’s start with the statement if only. if is used to check if one thing is true, and then it will do the decided command. If you want to put this code on a movieclip, then remember to have it under an onClipEvent(){ or under an on(){ statement. But we will start by putting if on the frame.

if(1==1){ //If 1 is equal to 1
trace("true");//Will type "true" in the debugging window
}

So, I’m sure you know that 1 is equal to 1. We used == and not = because = is the assignment operator, and what it does is to change a to b, in this case, 1 would’ve been changed to 1, but if it would’ve been 1=2, then 1 would’ve been changed to 2.

STEP 2:

Well, let’s check what happens if we change the first line to:

if(1==2){//1 isn't 2, so this is false

Well, no message. That’s because 1 is NOT 2. But you might want a false message anyway. This is where the }else{ statement will be used. Read the following code.

if(1==2){ //1 isn't 2, so this is false
trace("true"); //The message if it's true
}else{//Else in actionscript is the same thing as in English.
trace("false");//The message if it's false
}

So, now it says false. But you can change the expressions the if tag have got to something else. If you change it to 1==1, it will be true, as well as if you change it to 3==3, it will be true, but if you change it to 11==1, for example, it will turn out as false. I think you get it now, right?

USAGES:

Well, basically anything, you use this for hitTest (checks if one object touches another), checking if a variable is what and doing something if it is that and so on…. Basically, think about what the word stands for in English.

The ! (false):

This operator stands for false. You can use it with the if statement. Here’s one example, doing pretty much the same as the previous code examples, but this time the other way!
if(!1==1){ //If 1 isn't 1
trace("true"); //The message if that's true
}else{//Well, if 1 actually is 1, then the following message will appear
trace("false");//The message if that's false
}

The ! operator is basically useful, so I hope you will remember that part of the tutorial, as well as the other parts, because those parts was important things too! Thank you for your interest!