|
| 24 Aug 2017 02:46 PM |
Hey,
I'm trying to remove a player from a table but don't know the position the player is in the table so i cant use table.remove as it is intended.
is there a way to find out where the player is in the table to remove them or is there a way to remove a player from the table without knowing their position in the table?
|
|
|
| Report Abuse |
|
|
|
| 24 Aug 2017 03:17 PM |
Unfortunately, for this specific scenario, you have to scan through the entire table to find the index, and then remove the player:
for i,player in pairs(playersTable) do if player == playerToRemove then table.remove(playersTable, i) end end |
|
|
| Report Abuse |
|
|
|
| 24 Aug 2017 03:18 PM |
Oops, I should have added a 'break' statement in there too:
for i,player in pairs(playersTable) do if player == playerToRemove then table.remove(playersTable, i) break end end |
|
|
| Report Abuse |
|
|
Ajastra
|
  |
| Joined: 01 Aug 2017 |
| Total Posts: 1461 |
|
|
| 24 Aug 2017 03:18 PM |
The better solution is to use a hash table, because in Lua any non-nil value can be both a key and a value in tables.
local aTable = {}
aTable[player] = true
vs.
local aTable = {}
table.insert(aTable, player)
print(aTable[player])
A hash table lookup is far more efficient than linear search.
It may not always be possible to do this though, I don't know your use case.
|
|
|
| Report Abuse |
|
|
|
| 24 Aug 2017 03:21 PM |
| Yeah, a hash table is nice when you can use it, but there's certainly scenarios where a standard array works best still. |
|
|
| Report Abuse |
|
|
|
| 24 Aug 2017 03:57 PM |
well the script is for a match game, so it adds all players to a table when the game starts, and then as they reach the finish line i need to remove them from the table and anyone left at the end of the match (who is still in the table) gets teleported somewhere.
i have it all working and such like, i just need to remove the player from the table as when they finish it still counts them as playing and when the timer runs out they get teleported too, even though they have finished the map.
|
|
|
| Report Abuse |
|
|