Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to store/remove players in a table?

Asked by
Uzuntu 6
6 years ago

I'm working on a game that needs to register when players have died during a round, and I thought storing them all in a table was a good way of doing this. I know how tables work, but I'm not entirely sure how to do this? Any help is appreciated.

2 answers

Log in to vote
0
Answered by 6 years ago

This is called "Reading and Writing" ( I call it indexing but you'd get confused).

To index to a table. Simply get the table in a script, get the key in the table that you want to change. and change that with a separate line. here is an example from the wiki.

local myArray = {"A string", 3.14159, Workspace.Part}
--creates a table with three values

myArray[2] = "Pi"
print(myArray[2])
--Sets the second value in the table to "Pi", then prints the newly changed value
0
I'm aware of how tables work, I'm just not sure how to store players as they join. Uzuntu 6 — 6y
Ad
Log in to vote
0
Answered by
Vulkarin 581 Moderation Voter
6 years ago

If you want to add players who join:

players = game:GetService("Players")
playerTable = {}

players.PlayerAdded:Connect(function(player)
    table.insert(playerTable, player)
end)

If you want to remove players who leave:

players = game:GetService("Players")
playerTable = {}

players.PlayerRemoving:Connect(function(player)
    for i = 1,#playerTable do
        if playerTable[i] == player then
            table.remove(playerTable, i)
        end
    end
end)

And of course if you want to remove players once they die:

for i = 1,#playerTable do
    playerTable[i].Character.Humanoid.Died:Connect(function()
        table.remove(playerTable, i)
    end)
end

Answer this question