00:00
00:00
Newgrounds Background Image Theme

KouteiFK just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

As: ? Operators And Switch Case

2,632 Views | 6 Replies
New Topic Respond to this Topic

As: ? Operators And Switch Case 2007-03-31 08:18:42


AS ? Main : break;

I'm bored of the standard If/Else block. Time for something new...

The Conditional Operator (?)

This takes me back to when I used Excel and had to code everything on one line...
This thing's been arround since Flash 4, but I've never seen anyone use it. So like what I did with %, I'm going to write a few words about it.

Conditional Operators are a shorthand If/Else blocks, and are useful for assignment of single variables. They save space when you are working on the Actions window (by taking up a single line instead of a minimum of four when you hit the autoformat button). Not sure how fast they are compared to if/else, but microprocessor speed is best handled by serious pros like Gust and Delta.

Usage
(condition) ? expression1 : expression2
Flash evaluates the condition as a Boolean value (so it returns true, or false). If the condition returns true, the conditional operator returns expression1. Otherwise, it returns expression2.

From the Language Reference (F1 in Flash 8):

var timecode:String = (new Date().getHours() < 11) ? "AM" : "PM";
trace(timecode);

This checks the time of day and returns whether it is morning or afternoon.

What's its practical use then?...

If/Else Example

var my_age:Number = 18;
var my_ageBracket:String;
if (my_age<18) {
my_ageBracket = "CHILD";
} else {
my_ageBracket = "GROWN UP";
}
trace("I AM "+my_age+" AND I AM THEREFORE A "+my_ageBracket);

This should be easy enough to read for everyone who's ever used an if/else block before. We're making the computer tell us how old it thinks it is, and therefore whether it is an adult or a child.

? Example

var my_age:Number = 18;
var my_ageBracket:String;
my_age<18 ? my_ageBracket="CHILD" : my_ageBracket="GROWN UP";
trace("I AM "+my_age+" AND I AM THEREFORE A "+my_ageBracket);

This looks tidier though, doesn't it? We could also write it like this:

var my_age:Number = 18;
var my_ageBracket:String = (my_age<18) ? "CHILD" : "GROWN UP";
trace("I AM "+my_age+" AND I AM THEREFORE A "+my_ageBracket);

And use an assignment value to trim another line down. This starts to get really useful when we start nesting them...

var my_age:Number = 13;
var my_gender:String = "FEMALE"
var my_status:String = my_age<18 ? ((my_gender == "MALE") ? "BOY": "GIRL") : ((my_gender == "MALE") ? "MAN" : "WOMAN");
trace("I AM A "+my_age+" YEAR OLD "+my_gender+" AND I AM THEREFORE A "+my_status);

And now we've given it a gender and told it whether it is a man, woman, boy or girl...
Those four lines define three variables and trace them, rather than use the a gigantic if/else loop to set those same variables.

You could also have it return a function call instead, if you so wish.

Conditional operators can only have one expression returned. You can't for instance, call three functions from this. Instead, the if/else loop should be properly used.

my_age<10 ? function1() function2() function3(): function4() function5(); // ERRORS!!
// Instead Use...
if (my_age<10){
function1();
function2();
function3();
} else{
function4();
function5();
}

I use it to keep my code tidy. When I'm defining a huge list of variables, I prefer them to be in a nice, organised block, instead of seeing an IF/ELSE block interupt it. I also like using Autoformat to keep everything in order, and so typing an if/else block on one line won't make sense. Using ? I can keep it all in order, and use IF/ELSE for the more important things, like calling multiple functions.

Switch Case Blocks
Okay. So some things aren't just black or white, AM or PM, Man or Woman, True or False. Sometimes we have a huge chain of conditions that we want to check for.

var my_eyes:String = "GREEN";
if (my_eyes == "BLUE") {
trace("I HAVE EYES LIKE THE SEA");
} else if (my_eyes == "GREEN") {
trace("I HAVE EYES LIKE THE FIELDS OF IRELAND");
} else if (my_eyes == "BROWN") {
trace("I HAVE EYES LIKE...");
} else if (my_eyes == "RED") {
trace("MY CAMERA'S RUBBISH...");
} else{
trace("I'M BLIND!!!");
}

Problem is, it's ugly. And you're testing for the same variable each time. The efficiency of that must be terrible.

And yes you could chain "?" Operators on for eternity like you can 'else if', but there's only so much you can bear to see on one line before it becomes unreadable.

So we have an alternative. The Switch/Case Block

Usage

switch (expression) {
case "X" :
expression2;
break;
case "Y" :
expression3;
break;
case "A":
case "a":
expression4;
break;
default :
expression5;
}

Flash tests the case values to the switch values, and if they are equal to each other, runs the expressions it is connected to (so if expression is equal to X, expression2 is called).

Break is a statement that terminates any for or while loop, or a switch statement - immediately jumping out of it and continuing with the code as if it had ended there - so Flash would not continue checking cases after checking for case "Y", but would treat "A" and "a" as the same (both would call expression4").

While loop users - maybe you can use break as an emergency escape from infinate loops?

Default is placed at the end of a switch-case block. It is always called unless the switch statement is broken by a break statement.

Phew... Lot to take in there... An example is needed...

Switch Case Eye Colour Example

var my_eyes:String = "GREEN";
switch (my_eyes) {
case "BLUE" :
trace("I HAVE EYES LIKE THE SEA");
break;
case "GREEN" :
trace("I HAVE EYES LIKE THE FIELDS OF IRELAND");
break;
case "BROWN" :
trace("I HAVE EYES LIKE...");
break;
case "RED" :
trace("MY CAMERA IS RUBBISH");
break;
default :
trace("I'M BLIND!!");
break;
}

Okay. So it takes more lines up. But I find it more organised than an if-else block doing the same thing. It's also more efficient than an if-else block (instead of checking Else if after Else if after If, you're checking a single Switch, a single Case, and then breaking).


...

BBS Signature

Response to As: ? Operators And Switch Case 2007-03-31 08:22:55


Hahahaha.
(Though if you actually expect someone to learn you should've made it shorter. :P)


BBS Signature

Response to As: ? Operators And Switch Case 2007-03-31 08:32:58


function singSong(day_of_xmas:Number) {
var ender:String;
switch (day_of_xmas) {
case 1 :
ender = "st";
break;
case 2 :
ender = "nd";
break;
case 3 :
ender = "rd";
break;
default :
ender = "th";
break;
}
trace("On the "+day_of_xmas+ender+" of Christmas, my true love sent to me...")
switch (day_of_xmas) {
case 12 :
trace("Twelve drummers drumming, ");
case 11 :
trace("Eleven pipers piping, ");
case 10 :
trace("Ten lords a-leaping, ");
case 9 :
trace("Nine ladies dancing, ");
case 8 :
trace("Eight maids a-milking, ");
case 7 :
trace("Seven swans a-swimming, ");
case 6 :
trace("Six geese a-laying, ");
case 5 :
trace("Five golden rings, ");
case 4 :
trace("Four calling birds, ");
case 3 :
trace("Three French hens, ");
case 2 :
trace("Two turtle doves, and");
default :
trace("A partridge in a pear tree!\n");
}
day_of_xmas<=11 ? singSong(day_of_xmas+1) : "";
}
singSong(1);

Just something I quickly made and found amusing using what I ranted on about...


...

BBS Signature

Response to As: ? Operators And Switch Case 2007-03-31 09:40:46


At 3/31/07 08:32 AM, KaynSlamdyke wrote:
trace("Twelve drummers drumming, ");
case 11 :
trace("Eleven pipers piping, ");
case 10 :
trace("Ten lords a-leaping, ");
case 9 :
trace("Nine ladies dancing, ");
case 8 :
trace("Eight maids a-milking, ");
case 7 :
trace("Seven swans a-swimming, ");
case 6 :
trace("Six geese a-laying, ");
case 5 :
trace("Five golden rings, ");
case 4 :
trace("Four calling birds, ");
case 3 :
trace("Three French hens, ");
case 2 :
trace("Two turtle doves, and");
default :
trace("A partridge in a pear tree!\n");
}

an array would suffice. damnit too many quoted characters!! i hate this rule so much. ..........

Response to As: ? Operators And Switch Case 2007-03-31 09:54:23


At 3/31/07 09:40 AM, ImpotentBoy2 wrote:
At 3/31/07 08:32 AM, KaynSlamdyke wrote:
an array would suffice. damnit too many quoted characters!! i hate this rule so much. ..........

i retract that statement with an array you would need to loop each low day gift. this actually seems easier

Response to As: ? Operators And Switch Case 2007-03-31 12:23:54


Case statements are very useful. You know you need to use one if you start having a lot of what looks like "if ... else if ... else if... else if" logic!

Response to As: ? Operators And Switch Case 2007-03-31 14:50:32


At 3/31/07 09:54 AM, ImpotentBoy2 wrote: i retract that statement with an array you would need to loop each low day gift. this actually seems easier

Mwahaha... Switchcase strikes again

You could also use a recursive function, but this one's less prone to breaking into an infinate loop. And although an array would make sense, at least this one will always give you a day of christmas, regardless of what number you throw into it (try it... try seeing what your true love gives to you on the 13th day of christmas... ^_^)

This one just takes advantage of the fact that once one case has been found, the remaining cases all activate regardless of whether their own conditions have been met unless it runs into a break statement. And personally, I like it better than the simple alternative of a decreasing for loop.

At 3/31/07 12:23 PM, Newsdee wrote: Case statements are very useful. You know you need to use one if you start having a lot of what looks like "if ... else if ... else if... else if" logic!

Thanks for the show of support.

Was always wondering why no one ever wrote a tute for this topic...


...

BBS Signature