Foreach and for loops
#1

Using for(the loop) and foreach in the same script can make the for loops not work? Because I'm using a timer repeating every second which contains a for loop and it doesn't work at all.

Note: for loops in my script don't work only in callbacks called by a timer.
Reply
#2

They work fine together. You should only use foreach when you want to do someone to connected players. If you want to, for example set the values of an array for every slot you need to use for().

pawn Код:
for(new i=0; i<MAX_PLAYERS; i++)
{
    somevar[i] = -1;
}
Reply
#3

Well, it means that it's caused by something else.. So the problem is that loops (for, not foreach) don't work in callbacks called by a timer, but work fine in commands, default callbacks, etc.

Do you know what's the cause? I can paste the code, if you need it.
Reply
#4

I printed messages at the start and the end of the function, and both messages are printed in the server console. By the way, i found out something:

Looks like global variables work fine, only player variables don't work.

pawn Код:
public SecondTimer()
{
    for(new i=0; i<MAX_PLAYERS; i++)
    {
         if(Info[i][pVar] > 0) Info[i][pVar] --; // DOESN'T work
         if(dmvtime > 0) dmvtime --;   // DOES WORK
    }
    return 1;
}
Reply
#5

I used exactly the same code in the past, and it worked... Oh, and when I run the server on my computer it works just fine. On the host(linux, ~80 players) it doesn't.
Reply
#6

I had some weird thing happen like this when i accessed an array out of bounds at runtime. Random things would just stop working. I also noticed it because it stopped all my timers from working.

I had a variable that counts vehicles as they are created, and i used that variable as an index to an array. I forgot to reset the var when the vehicles were destroyed, which led to indexing an array OOB at runtime. Can be a pain in the ass to find this kind of bug because when you think it's a bug in your code you seldom look at array sizes.

I'm not saying this IS your problem, just saying it may be.
Reply
#7

Can you give me an example code of this? I think I might have this problem, too
Reply
#8

Straight forward example, bugs in your code will be harder to find than this.

pawn Код:
new random_array[ 10 ];//array with 10 slots

foo(  )
{
    for( new i; i < 20; ++i )//loop through 20 slots
    {
        if( i > 10 )//array is now above top index
        {
            random_array[ i ] = 5;//runtime error (out of bounds) causes undefined behaviour
        }
   
    }
   
}
Quote:
Originally Posted by ******
Посмотреть сообщение
I'd suggest you look there more - that's one of the most common bugs I see people asking about.
The first place i look now after spending hours trying to find a bug in my code
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)