« Benefit design contest | Main | Page through thumbnails with flash. »

Ambiguous data-types in flash

Today I ran into one of those quirks of flash: ambiguous data-types. I recall reading about this somewhere, but hadn't run into it yet.

I'm pulling mixed data-types from an XML document, and found that numbers were getting passed as strings, and that flash seems to determine data-type based on action performed on the data. I'll have to do some reading on that.

Anyway, I kept getting strange results when I used the numbers. And then it finally occured to me that I needed to "force" the data from a string into a number. Colin Moock's book came to my rescue, with a suggestion to convert by subtracting zero. Worked like a dream.

So, if it looks like your concatenating instead of numerically incrementing, try subtracting zero.

Here's a snippet of code I was working on:

if(this.list_order < 9){
//subtract 0, to force value as integer not string
pos = this.list_order - 0;
} else {
pos = this.list_order - ((this.thisSet-1)*9);
}

Comments

> pos = this.list_order - 0;

Are you sure there isn't a more elegant way of doing that? Maybe something like toInt() or a API class that would do it like Integer.parseInt(), bit strange if there isn't.

Btw: other way works as well probably
{ int i; => string = "" + i; }

Yes, those are more elegant, but I think that this method is faster (within flash). Perhaps this has improved (im MX), but flash often takes much longer to perform more elegant code. To get performance, sometimes elegance has to be sacrificed...it's a balancing act.

Hey Edwin, I bet you have some thoughts on this.

Any reason why you wouldn't just use for instance:
pos = Number(this.list_order);
?
From the very small benchmarking I just did it doesn't show any significant speed-difference, so use either :) I tested this on a 50,000 iterations-loop btw... parseInt (for when yer absolutely sure the var's an integer) and parseFloat (for when yer sure it's a floating number) are almost 500ms slower than the Number/-0 methods over 50,000 iterations, which to me is negligable considering loops over 50,000 iterations are usually very rare...

The code I used (uncomment method you want to test):
myNum = "500";
sT = getTimer();
i=50000;
while (--i) {
newNum = Number(myNum);
//newNum = myNum-0;
//newNum = parseInt(myNum);
//newNum = parseFloat(myNum);
}
trace("time elapsed: "+(getTimer()-sT));

Thanks, Edwin!