Main Content
If / Else
If
Every minute of every day you will most likely make some kind of decision. For example, while I am typing this I am making decisions about what to type next. These, when found in ActionScript, are called If statements. You will inevitably come across these soon in game development, or in fact, in any type of interactive application. Although this might seem a bit daunting, we shall start off simply, with an obvious example being deciding what to wear:
If it is cold, then I will wear a coat.
That is the part that if statements play in programming - choices. In ActionScript, simple choice would be represented as such:
if(it is cold){
then I will wear a coat
}
In general terms:
if(expression){
then do this
}
If the expression evaluates to (ends up as) a true value, then Flash executes (does) whatever is within the curly braces ( '{' and '}' ).
If: the quick way
If you just want to do something short, say trace one thing, you can skip the curly braces and put it all on one line. This makes things look tidier and helps readability of your code:
if(expression) then do this;
Else
Now consider this real life circumstance:
If it is cold, I will wear a coat. If it is not cold I will wear a shirt.
This is how we show such a circumstance in ActionScript, using 'else':
if(it is cold){
then I will wear a coat
} else {
I will wear a shirt
}
In general terms:
if(expression){
then do this
} else {
do something else
}
Never will you both wear a coat and a shirt, it should be noted. An expression will always fit into one of these brackets: either the expression is true or not. The "not" group can also include badly formed expressions.
Else If
Finally we move on to Else Ifs. These are useful if you want to consider multiple values for something, as in this example:
If it is cold, I will wear a coat. If it is not cold, but sunny, I will wear a sun hat. If it is neither cold nor sunny, I will just wear a shirt.
An else/If structure can be used in many circumstances and reads quite logically. This is how you would put that example above into ActionScript:
if(it is cold){
then I will wear a coat
} else if(it is sunny){
I will wear a sun hat
} else {
I will just wear a shirt
}
In general terms:
if(expression){
then do this
} else if(expression){
do something
} else {
do something else
}
Only ever one of those three things will get done.
Thanks for reading this, and if it has taught you something, it will have been worth it. Look out for another tutorial about building the expressions to fill if statements.
Thanks again,
Harry.