Saturday, April 5, 2008

Live Geek Report: Boolean Saturday Night!


Yes, it's Saturday night. And I'm sitting in Scott's living room writing ActionScript. The file below is basically a newbie "how to create and toggle an ActionScript Boolean variable tutorial." I sum up the resolution to my goofy problem in this way: When dealing with Boolean variables and conditions in Flash, remember the difference between "=" and "==" .

In ActionScript, "==" means what we usually think of as plain ol' "=." That is, "==" means is equal to. "=" by contrast means gets or sets to. 

If you write an if statement to toggle a boolean value using "=" you will create bizarro code that won't work. Observe. 

I first create a boolean variable called "dog" and set its initial state to true.
var dog:Boolean = true; 

No problem. Now, I want the user to click on a button (called "btn") to change the dog variable to the opposite of whatever the dog variable is set to when the button is pushed. If dog is false, clicking the button needs to set dog to true. If dog is true, clicking the button needs to set dog to false. 

No problem. I'll use an if statement. Oops, I'm not very bright. Here's the code written THE WRONG WAY, using "=" instead of "==". The following code WILL NOT WORK CORRECTLY though it looked perfectly fine to me for a long time. The incorrect code is highlighted in RED.

btn.onRelease = function () {
if (dog = true) {
dog = false;
} else {
dog = true;
} // end if
} // end btn.onRelease

Here's the code written the right way. The following code WILL WORK FINE. The correction is made in green on the second line.

btn.onRelease = function () {
if (dog == true) {
dog = false;
} else {
dog = true;
} // end if
} // end btn.onRelease

So duh. . . the perils of self-teaching. Here's a link to a sample file if you're having trouble with the most primitive, idiotic use of basic boolean variables in ActionScript as I was. It contains a button, that when clicked turns the visibility of a dog on and off using the above code. Thrillsville.

No comments: