views:

311

answers:

4

I am trying to find the index from an array using a loop function, but I am getting an error:

private function findMatch(matchValue:int):int {
        for (var i:int = 0; i < playersList.length; i++) {
           if (playersList[i].value + matchValue == levelTarget) {
                        return i;
                } 
                }
    }

Is it not possible to return a value from inside a loop, or rather, am I getting an error everytime it doesn't return a value?!?

A: 

What is your error:

1170: Function does not return a value?

If that is the case, then yes, the error is from your function never returning anything. Generally, when using a function that returns an array index you should return -1 for no-match.

So, just add

return -1;

after your for loop.

If the match is found, the index will be returned. Otherwise, -1 is returned.

sberry2A
That works great, thanks!!
redconservatory
A: 

You can return from anywhere in a function, but you have to satisfy all code paths with a return value. As described above, you'll need to return a "non-valid" value to indicate no index is found, which is commonly -1.

Nick Bedford
A: 

In many programming languages you can return from any point in a method. The compiler is probably complaining because it can't be sure that it will find the right value in the loop, and then will have nothing to return (even if you as the developer are convinced that it will return before exiting the loop).

So yeah, adding some default return at the end is the right thing to do, and -1 is a common default answer for this kind of thing.

Henry Jackson
+1  A: 
private function findMatch(matchValue:int):int {
    var _i:int = -1;
    for (var i:int = 0; i < playersList.length; i++) {
       if (playersList[i].value + matchValue == levelTarget) {
                 _i = i;
                break;  
        } 
    }
    return _i;
}
Ian