Wednesday, February 25, 2009
The Classic Artist's Programming Error
Here's a self-inflicted error you're likely to hit upon as the quarter comes crashing down upon your head. Hey, I just made this same mistake twice in the past hour. I am not Spock, clearly. Let it forever be known to us as, "The Equal Sign As Used In Programming Does NOT Equal The Equal Sign as Used in Math Error."
In other words:
= ≠ =
Ah ha ha ha ha ha!
We're used to saying things like "5 = 5," or "2 + 2 = 4." Ho hum. In a math context, "=" could be translated as "is." "5 is 5," or "2 + 2 is 4." In ActionScript, however, when we want to make plain old "is" statements we use the "==" operator, as in "5 == 5."
Here's the rub. In ActionScript, "=" is an active command, not a passive statement of fact. In programming, we can translate "=" as "gets" or "is now assigned the value of". For example, in ActionScript, the simple line of code written as
dx = 5;
is a command to the computer to, "under pain of death, drop whatever you were doing before and hold on to the value 5, you little maggot."
If you don't understand the difference between the two meanings, this will destroy you when you start working with if statements.
For example, here's a perfectly innocent looking function that is buggy as the day is long:
function checkLives (){
if (lives = 0) {
gameOver;
} // end if
}
In this trashy code, the computer will interpret "lives = 0" as a command to stop whatever the hell else it is doing and set the lives variable to 0. The effect is that the computer whilst innocently checking the "if"condition freaks out (pain of death, remember) and set the "lives" variable to 0. This makes the "if" condition true and so the gameOver function runs constantly. The game ends before it begins and you, the programmer are puzzled.
What you want to write instead is something like this:
function checkLives(){
if (lives == 0) {
gameOver;
} // end if
}
Our translation is now in line with what we actually want: "If lives equals 0, then run the gameOver function."
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment