Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


  Show Posts
Pages: [1]
1  Off Topic / Spam / New GTA mod comes out... on: March 07, 2011, 11:58:23 pm

2  Scripting / Script Snippets / Get a list of players as a table. on: March 01, 2011, 12:48:28 am
Code: (squirrel) [Select]
function GetPlayersTable()
{
local players = {};

for (local player, id = 0, count = GetMaxPlayers(); id < count; id++)
if ((player = FindPlayer(id))) players.rawset(player.Name,player);

return players;
}

This function returns a Squirrel table containing a list of all the players currently on the server. This allows you to use foreach to iterate through all the players on the server. For example:

Code: (squirrel) [Select]
local players = GetPlayersTable();

foreach(player in players)
player.Frozen = true;

The above code would freeze every player on the server. You can also check if a certain player is in the table by name:

Code: (squirrel) [Select]
function onPlayerCommand( player, cmd, args )
{
local players = GetPlayersTable();
local arglist = split( args, " " );

switch(cmd)
{
case "ouch":
local name = arglist[0];

local pos = player.Pos;
pos.z += 5;

if (name in players)
players[name].Pos = pos;

return 1;
}

return 0;
}

The above code would create a new command '/ouch' which a player could use to drop another player on their head by typing '/ouch someguy'.

An optimised way to handle player lists:

One potential efficiency problem with the GetPlayersTable() function above is that when using it in a foreach loop you will essentially be looping through the players list twice. One way to avoid this is to keep a global table containing an active list of players. Using GetPlayersTable() to populate a global table would not be sufficient as the list would become invalid as players join and part the server. A solution to this is to use the onPlayerJoin and onPlayerPart callbacks to manage an active list of players:

Code: (squirrel) [Select]
players <- {};

function onPlayerJoin( player )
{
players.rawset(player.Name,player);
}

function onPlayerPart( player, reason )
{
players.rawdelete(player.Name);
}

This way the global 'players' table always contains a valid list of players currently on the server. You would then use this global table in the same way as above, but without the need to define it locally or call GetPlayersTable().
3  Archive / Archived Items / ... on: April 10, 2010, 11:35:59 pm
Pages: [1]
© Liberty Unleashed Team.