How is type casting done?
BlitzMax Forums/BlitzMax Beginners Area/How is type casting done?
| ||
The BlitzMax documentation is not entirely clear on the topic of explicit type casting (type conversation). The automatic conversion doesn't work with this code: Local aspectRatio:Float = width / height The variables width and height are of type Int. The expression doesn't automatically evaluate to a Float, so some explicit casting is necessary. One way to force a conversion is by doing this: Local w:Float = width Local h:Float = height Local aspectRatio:Float = w / h I just hate to have unnecessary (intermediate) variables cluttering up the readability of my code, but can't figure how to do a proper type cast! The documentation talks about "brackets", but using them I just get a compile error. Does anyone know how to do this? |
| ||
You would cast to a float like this...Local width:int = 10 Local height:int = 6 Local aspectRatio:Float = Float(width)/Float(height) Print "The aspect ratio is: "+aspectRatio You can also use Int(whatever) Double(whatever) ect, and even a custom type like myType(whatever:Object) |
| ||
From Help>Language>Types The rules governing type balancing are: If either argument is Double then result is Double else if either argument is Float then result is Float else if either argument is Long then result is Long else result is Int |
| ||
Thanks for clearing this up! It now works like magic. The active forum sure creates added value for BlitzMax. My mind was partly clouded by how this is done in C++, where the parenthesis, of course, goes around the type specifier. Also, English is not my native tongue, but I thought "brackets" meant "[ or ]" ("square brackets") and did not realize it was a synonym for parenthesis "( or )". Perhaps this part of the post should have gone into the "BlitzMax Bug Reports" forum. ;) |