Loops

From SA-MP Wiki

Jump to: navigation, search
Image:32px-Ambox_warning_orange.png It has been suggested that this page or section be merged into [[Keywords:Statements#for]]. Discuss.


for() loops.

for(new i = 0; i < MAX_PLAYERS; i++)
{
    // Do stuff here
}

Explained

new i = 0;
Creates the variable 'i' and sets it to 0

i < MAX_PLAYERS;
If the loop is less than MAX_PLAYERS (X amount of slots on a server) it will continue

i++
Adds one to i each time


Description:

Loops are usually used to loop through all vehicles or players, and do something to them


public OnPlayerSpawn(playerid)
{
    for(new i = 0; i < MAX_PLAYERS; i++)
    {
        if(!IsPlayerConnected(i)) continue;
        SendClientMessage(i, 0x33AA33AA, "Someone spawned!");
    }
    return 1;
}

That could be an alternative to SendClientMessageToAll.

Also, the variable does not have to be called 'i', it can be assigned any name.

for(new blah = 0; blah < MAX_VEHICLES; blah++)


Example with loop

If you want to send a message to all RCON admins when a player connects, then you can do it like this.

public OnPlayerConnect(playerid)
{
    for(new all = 0; all < MAX_PLAYERS; all++)
    {
        if(IsPlayerAdmin(all))
        {
            new playername[MAX_PLAYER_NAME], string[84];
            GetPlayerName(playerid, playername, sizeof(playername));
            format(string, sizeof(string), "*Player [%i] %s has connected to the server!", playerid, playername);
            SendClientMessage(all, 0xFF0000FF, string);
        }
    }
    return 1;
}
Image:Stub.png This article/section is a stub
You can help SA-MP by expanding it
Image:Stub.png
Personal tools
Navigation
Toolbox