< Day Day Up > |
The flaw we find in Figure 3.3 is that it is not adding the two numbers ; instead, it is concatenating them. In ActionScript 2.0, as well as several other languages, the + operator is overloaded . This means it will perform different operations, based on the types of data on which it is acting; when acting on numbers, it will add them, when acting on strings, it will concatenate them.
As we learned in Chapter 1, "What's New in ActionScript 2.0?," ActionScript 2.0 is a strongly typed language. This means that when Flash determines what type of data a variable (or property) will hold, it won't accept other types of data, unless specifically instructed to do so. The text property of a text field is typed as a String object. Therefore, when Flash was instructed to show the results of the following: input1.text + input2.text; it took the string entered in the first box and concatenated it with the string in the second. If we truly want Flash to add the numbers instead of concatenating them, we will need to cast them to the proper datatype. Casting is how we instruct Flash to change the datatype of an object. If we want to cast a string as a number, we use the built-in Number() function. Equally, if we wanted to cast a number as a String object, we could use the String() function. Listing 3.1 shows the onRelease handler for the button rewritten to properly add the numbers that have been input. Listing 3.1. The Addition Tool Now Shows the Expected ResultsbtAdd.onRelease = function(){ var theTotal:Number = Number(input1.text)+Number(input2.text); total.text = String(theTotal); } Here, we can see that we are explicitly casting the input from the text fields to numbers so that Flash can add them properly. We also need to cast the resulting number back to a string, as the text property of a text field is built to accept only strings. Figure 3.4 shows the full code, Stage, and results with the proper casting. Figure 3.4. The Addition tool working properly with the help of casting.
|
< Day Day Up > |