2007年4月2日星期一

Label Statements

ActionScript 3 introcuduces labels, new identifiers that can be associated with loop blocks. Why would you want to identify a loop block? Because you can use that identifier as a target for break and continue commands. Consider two loops where one is nested in the other. If at some point you want to exit both loops while in the nested loop, you can't. The break command only exits the current block. A common workaround is to use a flag variable to be able to check that, when in the first loop, if that should be exited as well. ex:

ActionScript Code:

var i:Number;
var j:
Number;
var exit:
Boolean = false;
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (i > 3 && j > 3) {
exit = true;
break;
}
}
if (exit) {
break;
}
}


When i is greater than 3 and j is greater than 3, break is used to exit the current loop, but this only exits the j loop. To exit the i loop too, the exit variable was used with an if condition in the i loop to exit that one as well.

Labels let you identify and break from a specific loop (and consequently any nested loops within). The format for a label is label: statement
Ex:

ActionScript Code:

var i:Number;
var j:
Number;
mainLoop:
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
if (i > 3 && j > 3) {
break mainLoop;
}
}
}


By giving the first loop a label of mainLoop, it can be broken out of easily within the nested loop using break mainLoop; This creates cleaner code and removes the necessity for the extra variable.

0 评论: