Monday, January 7, 2008

Setting flags

A flag in most languages is a variable that is only used to tell the state of a different object.
For example, you can have a button change alternate a flag every time it is pressed to know if it's state should be on or off.

var flag:Boolean = false;
function btnPress(){
if(flag == false) {
flag = true;
//code to make the thing move around the stage
} else{
flag = true;
//code to make the thing stop moving
}

By far the most common flags need only two states (such as in the code above), true and false.

While the code above is not entirely uncommon, it is entirely inefficient. Here are some better techniques:

1) Use the Bang (!) operator: [flag = !flag;]
The bang means 'not', the opposite of false is true, and not true is false

var flag:Boolean = false;
function btnPress(){
flag = !flag;
if(flag == false) {
//code to make the thing move around the stage
} else{
//code to make the thing stop moving
}

3) Use a modulized number [flag = ++flag%2;]:
While a bit messier than the last method, this has a huge advantage - you can set a flag for an unlimited number of states. Eg. If you want to keep track of which row in a table you are in, change the limit to match.
This works as follows:
++ before a variable increments the value by one.
% means that when it reaches the number after the '%', it should start again from zero.
The first time this is called, flag becomes '1'. The second time, flag is made into a '2', which is than modulized into a zero. The third time it is moved back to '1', etc.

var flag:Number = 0;
var rows:Number = 5;
function tblFill(){
flag = ++flag%rows;
if(flag == 0) {
border-left:solid;
} else if(flag==5){
border-right:solid;
} else{
border:none;
}

3) Use a ternary [flag = flag ? false : true;]:
This is not as neat as the first method, but has an advantage (I might post about later).

var flag:Boolean = false;
function btnPress(){
flag = flag ? false : true;
if(flag == false) {
//code to make the thing move around the stage
} else{
//code to make the thing stop moving
}

4) Use absolute numbers: [flag = Math.absolute(--flag);]
I cannot think of any advantage to this method, 'cept that it's really ingenious, and came from a programmer I respect.
The math.absolute function converts a number to a positive value. So that absolute -5 is the same as absolute 5.
-- decrements a value, so the second time this is run, flag becomes -1, and is than made into a 1 via the absolute. The second time it becomes a 0. The third time, back to 1, etc.

var flag:Number = 0;
function btnPress(){
flag = Math.absolute(--flag);
if(flag == false) {
//code to make the thing move around the stage
} else{
//code to make the thing stop moving
}

The first two are very, very, useful.

No comments: