int and Number type madness

Recently 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

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;
    var k:int = (i+ j) / 2;
    trace(k, k is int, k is Number); //4.5, false, true
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.


  1. Sindisil

    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?

  2. 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”

  3. 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.

  4. That looks like a compiler bug, probably related to optimization. Scary indeed.

  5. What compiler are you using? I have “4 true true” both times in CS3.

  6. I’m using the flex2 and flex3 compiler.

  7. MarioPlusPlus

    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).


  1. […] 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 […]