02.02.2013 Views

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

Flash MX 2004 Games : Art to ActionScript

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

11 Debugging<br />

No matter how experienced you get at writing code, there will be times when the code you<br />

write doesn’t work the way you expect. Isolating and fixing the errors is called debugging and is<br />

a fascinating mental challenge, or a complete headache depending on how you are feeling that<br />

day! In this chapter we will look at many of the more common errors and look at techniques for<br />

isolating the problem and then fixing it.<br />

Strings and numbers<br />

You have created a game that allows the user <strong>to</strong> input a numeric value using an input box. Then<br />

you run this code:<br />

on (release){<br />

num = num + userInput;<br />

}<br />

You have a num of 14, and a userInput of 10. You expect the num <strong>to</strong> be set <strong>to</strong> 24; instead it is set <strong>to</strong><br />

1410. Why? Simple really, userInput is a string; all input boxes s<strong>to</strong>re data as a string. The operation<br />

‘+’ can be applied <strong>to</strong> strings, so <strong>Flash</strong> converts num, 14, in<strong>to</strong> the string ‘14’ and ‘adds’ it <strong>to</strong> the<br />

string ‘10’. The string operation ‘+’ is concatenation, the string <strong>to</strong> the left of the opera<strong>to</strong>r and the<br />

string <strong>to</strong> the right are joined <strong>to</strong>gether. This is not the method that was intended; in your code you<br />

wanted the string ‘10’ <strong>to</strong> be used as a number. One solution is <strong>to</strong> make sure <strong>Flash</strong> realizes <strong>to</strong> use<br />

userInput as a number by using the ‘Number’ method:<br />

on (release){<br />

num = num + Number(userInput);<br />

}<br />

The result will now be a number, 24, as you intended. If the combination operation were any<br />

other arithmetic operation then <strong>Flash</strong> would have realized that you intended <strong>to</strong> use userInput as a<br />

numeric quantity, because no other arithmetic operation applies <strong>to</strong> strings. Therefore:<br />

152<br />

on (release){<br />

num = num - userInput;<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!