As I currently work for my AI course's project, I have a lot to do with QtScript resp. JavaScript. Generally, a nice language, as it allows pretty fast development, however, I'm a fan of strong typed languages. But no matter.
Generally, when working with it, it does what one expects. Well.. mostly.
What gave me some real headache lately: The plugin tended to give some errors. Not reproduceable and (much more worse) with pretty senseless messages. Now, today I found out why:
var i2 = parseInt( 0.1 );
If you don't know parseInt: It takes a string (or as here float) value as input and returns a corresponding integer. So, what would you expect it to give here? 10 and 0? Eh?
Well, at last, I belonged to the stupid who believe in this behavior. Too bad.
Why? The function takes an optional second parameter, the base the input is encoded into! Usually, if omitted, the function will try to guess the base from the input. So, if the input starts with "0x", base is assumed to be 16. A leading zero will let it assume base 8 and everything else will cause it to use base 10. And that's the problem:
This detection works well for almost every real number (including 10.1). However, as soon as you try to feed parseInt with a value out of (-1.0..1.0) it will fail! It will see the leading zero and use base 8 encoding. However, as it cannot process the following character (the dot) it will fail - and return NaN.
So, to make sure parseInt uses base 10 encoding, just pass the seconds argument:
var i2 = parseInt( 0.1, 10 );
That's it. And what I've learned from this episode: Smart APIs with good default values are cool, but even they have their limitations ;)
