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

8 thoughts on “int and Number type madness”

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

Comments are closed.