Reputation: 4217
This is not really a problem as the fix is simple and pretty costless. I'm guessing it's some property of for
or uint
that I don't understand and I just would like to know what is going on so...
Using ActionScript 3 I set up a for
loop to run backwards through the elements of a Vector
.
var limit:uint = myVector.length-1;
for(var a:uint = limit; a >= 0; a--)
{
trace(a);
}
When I run this it outputs 2, 1, 0
as expected but then moves on to 4294967295
and begins counting down from there until the loop times out and throws an Error #1502
.
The fix is simply to type a
as int
rather than uint
but I don't get why. Surely I am dealing with values of 0 and greater so uint
is the correct data type right?
I guess that 4294967295
is the max value for uint
but how does my count get there?
If you do
var myUint:uint = 0;
trace(myUint - 1);
Then the output is -1
so why, in my loop should I suddenly jump back up to 4294967295
?
Sorry for the slightly rambling question and cheers for any help.
Upvotes: 1
Views: 174
Reputation: 11
In binary - first BIT of number is minus, that is in int values. In UINT value that is just a BIT of value. One byte int looks like 1000 0000 == -127 and 0111 1111 = 127 One byte uint looks like 1000 0000 == 128 and 0111 1111 = 128
This is it.
Upvotes: 1
Reputation: 5705
You are close. As you said, your loop gives you 2, 1, 0, 4294967295. This is because uint can't be negative. Your loop will always run while a >= 0
and since it is never -1 to break the loop condition, it continues to loop forever.
var myUint:uint = 0;
trace(myUint - 1);
I didn't test this but what is probably happening is that myUint is being converted to an int and then having 1 subtracted. The following code should be able to confirm this.
var myUint:uint = 0;
trace((myUint - 1) is uint);
trace((myUint - 1) is int);
To fix your loop you could use int or you could use a for each(var x:Type in myVector)
loop if you don't need the index (a
).
Upvotes: 4
Reputation: 2094
an iteration and a a-- will occur when a is 0, thus as your int is not signed, the max value for this type will be set -> this is the way minus values are set in unsigned types.
Change your code into:
var limit:uint = myVector.length-1;
for(var a:uint = limit; a > 0; a--)
{
trace(a);
}
Upvotes: 3