Thursday, February 7, 2008

int bug

I found a little bug in actionscript 2, which apparantly has been fixed in actionscript 3 but which I found funny enough to show you guys.

Trying to fix a bug in an older source, where I took part of a symbolname "Button037", and cut out the 035 part as a substring, which I then used to flip to some page in a pageflipper component.
After the pageflipper bugged out (trying to add 5 to "037" which ended up with "0375" instead of 37 ..duh, I know) I put an int() around the value I got from the symbol name.
(Never having looked at the manual entry for int() but beeing used to its function from ASP/vbscript, I didn't know it was deprecated and I should use Math.floor() instead ...lesson learned :)


Whats the bug you ask?
Well.. If you use int() to convert a string to a number, it doesn't always work correctly in actionscript 2.0 if you have leading zero's.

trace(int("037")); returns 31 for example
I plotted the values out in a graph to see if there was some kind of pattern to it, and there was. Click here to see it

Sourcecode for that is:

for (intT=0; intT<400; intT++)
trace(intT + " : " + int("0" + intT));
_root.lineTo(intT, int("0" + intT));

Anyway.. it's fixed in actionscript 3, and you shouldn't use int() anyway, but hey, it might come in handy to know this if you're still using int() in your code, and it doesnt work the way it should :)

Edit : My Collegue Hugo asked if Number() had the same bug. Apparantly it does, BUT. its not what I thought it was.

When you use Number() to convert a string to a number, you can use a leading zero to indicate you're using an OCTAL value just like 0x denotes a hexadecimal value.

So the bug actually isn't that int() works incorrectly, but that the manual doesn't say that you can use a leading 0 to indicate an octal value.
So why does it seem to be 'fixed' in as3.0? Well, you can use octal notation in as2.0, but this doesnt work anymore in as3.0.

Not sure why anyone would want to use octal notation, but to prove this, try this little example in as3.0 and as2.0

for (var intT=00; intT< 020; intT++)

as2.0 will count to 15
as3.0 will count to 19

No comments:

Post a Comment