Liberty Unleashed

Scripting => Scripting Discussion => Topic started by: Theremin on February 10, 2017, 11:45:14 pm

Title: Table vs array
Post by: Theremin on February 10, 2017, 11:45:14 pm
Which one of these two methods is better and why?
I'm not interested to know which one is better as much as knowing why one is actually better. Keep that in mind before replying


1. Keeping players in an array. Shadow's method (http://forum.liberty-unleashed.co.uk/index.php/topic,1314.0.html)

Code: [Select]
playerson <- [];

function onPlayerJoin( player )
{
playerson.push( player.ID );
}

function onPlayerPart( player, reason )
{
playerson.remove( player.ID );
}


2. Keeping players in a table. himselfe's method (http://forum.liberty-unleashed.co.uk/index.php/topic,639.0.html)

Code: [Select]
players <- {};

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

function onPlayerPart( player, reason )
{
players.rawdelete(player.Name);
}
Title: Re: Table vs array
Post by: Vortrex on February 10, 2017, 11:59:26 pm
My method was very similar to himselfe. I just didn't use the rawset or rawdelete methods. Instead I just declared a new table slot on connect, and nulled the slot on part.

Anyway, here's my analysis:
It's not by much, and definitely not noticeable during runtime, but arrays are indexed by an integer while tables are index by a "key" which is usually a string. Iterating through an array is going to be faster than doing so with a table because processing an integer is faster than a string.

However, using the table might be more efficient between the two examples you provided. In the table, you provide a direct reference to the player instance, and can use it without having to use FindPlayer. Again, however, I doubt the performance differences are significant.

But it might be worth noting, that you index the table by player name. I don't recommend this. I would suggest using a player ID. The player name can change during gameplay by either scripting methods or a hack, but the player ID is going to remain the same.