Doing Math with Strings in Actionscript, General Type Casting
I have been getting some calls about addition not working with point values from Inetsupervisor. I have no way of knowing what type of value that will be sent to the connector so I assign conn.output as a string type so I can handle all form of data values. In AS2.0 most all values that are generic objects or just are not explicitly typed are implicitly cast to string. So if you need to do addition, and 1 or more object is a string then, explicitly type cast them to the Number.
Example:
a = status_txt.text + 15; //add the values of text box and 15. If the text is 1 but the all text is cast as string so a string concatenation will happen
trace(a);// value is 115. Bad
a = Number(status_txt.text) + 15; //add the values of text box and 15. The text value is still 1 but I have cast it to a number. 2 numbers will do math operations
trace(a);// value is 16. Good
This is most common casting you will have to work with, but sometimes you need to insert a number to a string:
var num:Number = 5;
a = "Hello all " + String(num) + " of you"; //num is a typed as a number with the value of 5 so it needs a cast to do string concatenation
trace(a);// Hello all 5 of you. Good
So since all values in AS are based as generic objects they all can be cast to some other type when needed.
Example:
a = status_txt.text + 15; //add the values of text box and 15. If the text is 1 but the all text is cast as string so a string concatenation will happen
trace(a);// value is 115. Bad
a = Number(status_txt.text) + 15; //add the values of text box and 15. The text value is still 1 but I have cast it to a number. 2 numbers will do math operations
trace(a);// value is 16. Good
This is most common casting you will have to work with, but sometimes you need to insert a number to a string:
var num:Number = 5;
a = "Hello all " + String(num) + " of you"; //num is a typed as a number with the value of 5 so it needs a cast to do string concatenation
trace(a);// Hello all 5 of you. Good
So since all values in AS are based as generic objects they all can be cast to some other type when needed.
Labels: code, flash, inetsupervisor

0 Comments:
Post a Comment
<< Home