Tuesday, June 16th, 2009 | Author: Dave

I’ve been using the uint type in AS3 quite a lot, just because it makes sense for what I’m doing. But yesterday I ran into a gotcha with it. I was using it for a bonus score in a game, that was being decremented every so often by a timer. Since I wanted it to stop when it reached 0, I did the typical:

function updateBonus(e:TimerEvent){
  bonus -= 3;
  if(bonus < 0){
    bonus = 0;
    bonusTimer.removeEventListener(TimerEvent.TIMER, updateBonus);
  }
  bonusText.text = String(bonus);
}

But the field never stopped updating, in fact it would get really big values in it after a while. Like 4294967295

Try this:

var a:uint = 0;
trace(a - 10);
// -10

Odd because I was expecting to see the large values I mention above, not -10. Because I’m not assigning the decrement to a.

var a:uint = 0;
a -= 10;
trace(a);
// 4294967286

There it is. Since a is unsigned, it rolls over to the maximum integer when less than 0. So the test I had (if a < 0) would never be true, and the bonus would eventually get huge. Good for the player, bad for the folks handing out prizes based on score.

So, simply changing the bonus’ type from uint to int fixed the issue. Such a simple thing to be tripped up by.

Category: as3
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.