int and Number type madness
March 7, 2008 on 11:32 pm | In Actionscript | 8 CommentsRecently I came across a strange behaviour of the AS3 compiler with int and Number types. It took some time to extract the flawed portion of my code to reproduce the error, so here is an example starting with the case where everything’s fine:
var i:int = 3;
var j:int = 6;
while (true)
{
var k:int = (i + j) / 2;
trace(k, k is int, k is Number); //4, true, false
break;
}
The term ‘(i + j) / 2′ evaluates to 4.5, and assigning it to the variable k removes everything after the decimal point. Now below is another example with just the while loop replaced with a do..while variant. But now the variable k “forgets” that it was typed to an int and becomes a Number storing a float:
var i:int = 3;
var j:int = 6;
do
{
var k:int = (i+ j) / 2;
trace(k, k is int, k is Number); //4.5, false, true
break;
}
while (true);
This is really bad since using k to access arrays will throw a runtime error. A workaround is to explicitly cast the value to an int or declare the variable outside the do..while loop.
That’s not “strange behavior”, that there’s a bug.
I didn’t see this bug on a quick glance at Adobe’s Flex bug system – have you opened a bug on it?
Comment by Sindisil — March, 8 2008 #
i don’t think this is a bug or even a strange behaviour. instead, the code is wrong.
“is” checks the class of an object.
“as” casts to another class
simply use “as” instead of “is”
Comment by Fabien — March, 21 2008 #
The code is not wrong, its demonstrating that the int is being stored as a Number instead of an int. Its not trying to type cast.
Comment by Pleh — March, 25 2008 #
That looks like a compiler bug, probably related to optimization. Scary indeed.
Comment by Martin Vilcans — March, 30 2008 #
What compiler are you using? I have “4 true true” both times in CS3.
Comment by makc — April, 3 2008 #
I’m using the flex2 and flex3 compiler.
Comment by Michael — April, 3 2008 #
The problem is true in Flex 3.0 and Flash CS3 but only happens when the code is inside a function.
The code work well inside a MovieClip (in a frame).
Comment by MarioPlusPlus — April, 3 2008 #
[...] to me recently, however, that has gotten me thinking about Adobe. He said he “read some funny / scary things about actionscript 3.” At first the words meant little to me. But as time passed, I [...]
Pingback by GigglingCorpse » Adobe and Flash — January, 13 2009 #