Game Development Reference
In-Depth Information
In this case, the body of the while instruction isn't executed—not even once! Therefore, in this
example, the variable x retains the value 1.
Infinite Repeat
One of the dangers of using while instructions (and, to a lesser extent, for instructions) is that they
might never end, if you're not careful. You can easily write such an instruction:
while (1 + 1 === 2)
x = x + 1;
In this case, the value of x is incremented without end. This is because the condition 1 + 1 === 2
always yields true , no matter what is done in the body of the instruction. This example is quite
easy to avoid, but often a while instruction ends in an infinite loop because of a programming error.
Consider the following example:
var x = 1;
var n = 0;
while (n < 10)
x = x * 2;
n = n + 1;
The intention of this code is that the value of x is doubled ten times. But unfortunately, the programmer
forgot to put the two instructions in the body between braces. This intention is suggested by the layout of
the program, but the script interpreter doesn't care about that. Only the x=x*2; instruction is repeated, so
the value of n will never be greater than or equal to ten. After the while instruction, the instruction n=n+1;
will be executed, but the program never gets there. What the programmer actually meant was
var x = 1;
var n = 0;
while (n < 10) {
x = x * 2;
n = n + 1;
}
It would be a pity if you had to throw away your computer or mobile device after it was put into a
coma because you forgot to write braces around your while instruction. Fortunately, the operating
system can stop the execution of a program by force, even if it hasn't finished. Even browsers
nowadays can detect scripts that are running indefinitely, in which case the browser can stop the
script execution. Once that's done, you can start to look for the cause of the program hanging.
Although such hang-ups occur occasionally in programs, it's your job as a game programmer to
make sure that once the game is publicly available, these kinds of programming errors have been
removed from the game code. This is why proper testing is so important.
In general, if the program you wrote doesn't seem to do anything on startup, or if it hangs
indefinitely, check out what is happening in the while instructions. A very common mistake is to
forget to increment the counter variable, so the condition of the while instruction never becomes
false and the while loop continues indefinitely. Many other programming errors may lead to an
infinite loop. In fact, infinite loops are so common that a street in Cupertino, California has been
named after them—and located on that street is Apple headquarters!
 
Search WWH ::




Custom Search