Thursday, June 17, 2010

AS3 Boolean Assignment

I came across a situation where I had a series of function calls that could alter an array of objects and I wanted to know at the end if any of them had actually made any changes. I decided to have each function return true if it had made a change and false otherwise. Then I created a boolean variable before running through the set of functions and assigned the result of each of the function calls to that variable using the following:

b = foo() || b;

I did it this way because boolean logic operators work left to right and had I done either of these:

b = b || foo();
b ||= foo();

then if b was true foo() would never have been called.

I found myself wishing that there was a way to explicitly set which direction the expressions would be checked in ( =|| instead of ||= for right to left) or even a means of indicating that you want ALL of the expressions to be validated (efficiency be damned!).

Fortunately there is a (less optimized?) way to do something similar using numerical operators. When a boolean is used in a numerical operator it gets treated as a 1 or 0. This allow you do do the following

var b:Boolean = true;
var c:Boolean; //defaults to false
var d:Boolean;

trace(b+b+c+b)// 3
trace(b+c+c+c)// 1

d = c+b+b
trace(d)// true;
d = c+c+c+b;
trace(d)// true;
d = c+c;
trace(d)// false;

d = false;
d += b // true;

This means I can do the following in my example situation:

var b:Boolean;
b += foo();
b += boo();
b += who();
b += do();

and if any of the functions return true b will become true.