Getting the highest ID
#1

Hello!

Since I have a bunch of loops and I make my loops as efficient as possible, like this:
pawn Код:
new maxPlayers,
  i;

// OnGameModeInit
maxPlayers = GetMaxPlayers();

// Loop
for(i = 0; i < maxPlayers; i++)
{
  if(!IsPlayerConnected(i)) continue;
  // code
}
My question is if looping for the highest ID can improve the performance a little? Sure can, but how do I make a variable store the highest ID?
pawn Код:
new highestID;

// OnPlayerConnect
if(playerid > highestID)
{
  highestID = playerid;
}

// OnPlayerDisconnect
if(playerid == highestID)
{
  highestID = playerid - 1;
}
And then loop like this:
pawn Код:
for(i = 0; i < highestID; i++)
{
  if(!IsPlayerConnected(i)) continue;
  // code
}
Will that highestID thing work? specially the OnPlayer(Dis)Connect code I showed.
Reply
#2

http://forum.sa-mp.com/index.php?topic=117573.0
Reply
#3

I would place below code in OnPlayerConnect and OnPlayerDisconnect

pawn Код:
for(i=0; i < MAX_PLAYERS, i++)
{
   if(IsPlayerConnected(i) == 1) HighestID=i;
}
MAX_PLAYERS is defined as capacity of your server and you don't need to define it in the code once again
Reply
#4

Maybe this will help:
pawn Код:
stock GetHighestID()
{
  new highestID = -1;
  for(new i = 0; i < MAX_PLAYERS; i++) highestID = i;
  return highestID;
}
Return the highest ID, or -1 if there are no highest ID (0 online players).
Example:
pawn Код:
new HighestID = GetHighestID();
Reply
#5

Quote:
Originally Posted by Amit B
Maybe this will help:
pawn Код:
stock GetHighestID()
{
  new highestID = -1;
  for(new i = 0; i < MAX_PLAYERS; i++) highestID = i;
  return highestID;
}
Return the highest ID, or -1 if there are no highest ID (0 online players).
Example:
pawn Код:
new HighestID = GetHighestID();
That would simply return MAX_PLAYERS - 1
It would have to be:
pawn Код:
stock GetHighestID()
{
  new highestID = -1;
  for(new i = 0; i < MAX_PLAYERS && IsPlayerConnected(i); i++) highestID = i;
  return highestID;
}
Or if that doesn't work:
pawn Код:
stock GetHighestID()
{
  new highestID = -1;
  for(new i = 0; i < MAX_PLAYERS; i++) if(IsPlayerConnected(i)) highestID = i;
  return highestID;
}

EDIT: However, IMO, looping normally using MAX_PLAYERS then checking IsPlayerConnected would be faster than looping with GetHighestID(). Also, you would still need to check IsPlayerConnected with GetHighestID, because player ID's aren't always in order. Eg. if there are 6 players on the server (ID's 0-5), and player 5 (ID 4) leaves, then you have ID's 0,1,2,3,5; 5 is the highest ID, but not all players up to that ID are connected.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)