Finding an empty slot in array and using it

2.9k views Asked by At

So I have a problem that I have been messing with for a while in Squirrel. I want to create something that goes through everything inside an array, e.g:

local array = [1, 2, 3, -1, 5, -1, 7, -1];

and look for those that are -1, I want to use just one of them, the one that comes up first (which in this case is between 3 and 5).

In my script, when someone destroys a certain object, it sets that objects id to -1 instead of a regular number, because otherwise it will just through out errors when trying to use that object. Don't really know if I'm doing a good job explaining this.

Another example is when players connect to a certain game server, so we have players with id 0, 1, 3 and 4 connected, so when next player connects they get the id 2. That is the thing i'm after with the arrays.

I have tried several things, only thing that is closest to it is this:

for(local i=1; i < Array.len(); i++){
    if(Array[i].id != -1){
      count++;
    } else {
      count = i;
    }
}

But the problem with this one is that it only takes the last ID and replaces it, so we have objects 0, 1, 2 and 3 If I would destroy 3 and create a new one, no problem. If I would destroy either 0, 1 or 2 instead and create a new one it would not take that slot, but instead go for number 4, which then does not work.

Thanks for reading, hopefully anyone out there can help me with this.


SOLVED:
It was really simple, for anyone else with the same problem this is what I did. Follow along now, this can get really tricky.
What I did was I added a "break;" in the else statement, code below:

for(local i=1; i < Array.len(); i++){
    if(Array[i].id != -1){
        count++;
    } else {
        count = i;
        break; // THIS
    }
}

Yes, I did hit myself in the head later...

1

There are 1 answers

0
PhilMY On
array.find(-1)

From the documentation:

Performs a linear search for the value in the array. Returns the index of the value if it was found null otherwise.