for loop mucking up again
#1



ok well i been programming a bit again and ran into a weird issue with 1 of my for bugs
Код:
new IsPlayerWorking[ MAX_PLAYERS ];


public othercounting()
{
	if (dtime > 0)
	{
		new str[5];
 		format(str, sizeof str, "~w~%d", dtime);
		for( new i = 0; i <= MAX_PLAYERS; i ++ ) // ISSUE IS HERE WITH MAX_PLAYERS
		{
			if (IsPlayerWorking[i])
			{
				GameTextForPlayer(i, str, 2500, 3);
 			}
		}
		dtime --;
		dtimer = SetTimer("othercounting", 1000, 0);
	}
for some reason, if i have i < MAX_PLAYERS it works, but i assume that means it would leave out the last player. i have tried i <= MAX_PLAYERS and i < MAX_PLAYERS+1 but neither work. am i doing something wrong or am i missing the point?
Reply
#2

Quote:
Originally Posted by kazai
but i assume that means it would leave out the last player.
You're wrong.

When you create an array of MAX_PLAYERS cells, say 200, then the valid cells are from 0 to 199. And the max playerid that a player can be is 199.
When you use i <= MAX_PLAYERS, the last iteration will 'call' cell 200 (IsPlayerWorking[200]), which is an invalid cell, and will most likely crash your script.

That is the correct loop:
pawn Код:
for( new i = 0; i < MAX_PLAYERS; i ++ )
Reply
#3

Correct, besides, do you really plan on having a full server with 200 players?
Reply
#4

I've got something like this:

pawn Код:
// On the very top:

// UN define MAX_PLAYERS
#undef MAX_PLAYERS

// RE define MAX_PLAYERS (to the amount of your server slots)
#define MAX_PLAYERS 32
pawn Код:
// Custom loop thingy:
#define loopPlayers(%1) for (new %1=0;%1<MAX_PLAYERS;%1++) if(IsPlayerConnected(%1))
pawn Код:
// OnGameModeInit:
if(GetMaxPlayers() > MAX_PLAYERS)
{
  printf("[error] Server slots (%d) is higher as MAX_PLAYERS (%d)",GetMaxPlayers,MAX_PLAYERS);
  SendRconCommand("exit");
  return 1;
}
pawn Код:
// Random public function
forward Sneaky();
public Sneaky()
{
  loopPlayers(i)
  {
    SetPlayerHealth(i, 0);
  }
  return 1;
}

Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)