PDA

View Full Version : while loop problem



Ricmar
August 15th, 2008, 11:15 AM
Wonder if someone more experienced could help. When i run this flash file the movies freezes. Its specifically when i click the button that activates this function. I dont think its a never ending loop. Having changed a few things around I know for sure this code is the prob

function calculateScore() {
var i:Number = 0;
while (i < dealerScoreArray.length) {
trace("SCORE " + i);
}
}

Any ideas whats wrong? the dealerScoreArray always has an item pushed into it before this function is called so will have at least 1 in length

Thanks if anyone can help

Krilnon
August 15th, 2008, 11:19 AM
It's kind of difficult to tell what's happening with such a small snippet of code that would work fairly well on its own unless the array was gigantic.

You could make some small optimizations or post more of your code:
function calculateScore() {
var i:int = 0;
var size:int = dealerScoreArray.length;
while (i++ < size) {
trace("SCORE " + i);
}
}

senocular
August 15th, 2008, 11:21 AM
Look at the logic. While 0 is less than some array's length, trace something. Well, if the array has any length at all, something will trace since the length will be above 0. Now once you're in that loop, you trace, and loop again. What's changed? Nothing; the array length is still greater than 0, so it loops again, and again, and again...

You have nothing in your loop changing your condition so it will loop forever.

If you just want to loop through the indices of your array, use:

var i:int= dealerScoreArray.length;
while (i--) {
trace("SCORE " + i);
}
This decrements i in each while condition check until it eventually reduces it to 0 which resolves to false. Then the loop stops. ;)

Beaten!

biznuge
August 15th, 2008, 11:22 AM
logic == FAIL

num=0
while (num==0){
don't change num!
}

Krilnon
August 15th, 2008, 11:22 AM
Surprisingly, I did not notice that. :trout: I probably should have slept last night!

Ricmar
August 15th, 2008, 11:42 AM
Excellant thanks guys, I have a very blurry patch in my brain where i should store info about while loops. Hate them.

Super