The Title up there says it all. Any way to make this possible? I tried it myself but my code didnt work
What im trying to do When a player dies or leaves remove him from the Table.
To remove string from table, you need to use "table.remove" function. Here is an example
local Playerstable = {"Player1","Player2"} function OnRemovePlayer(playerName, Table) for i = 1, #Playerstable do local CurPlayer = Playerstable[i] --get current player name from table if CurPlayer == playerName then -- checking if player name in table table.remove(Table, i) -- removing name from table end end end game.Players.PlayerRemoving:Connect(function(player) -- fires when player leave OnRemovePlayer(player.Name, Playerstable) end) game.Players.PlayerAdded:Connect(function(player) local char = player.Character or player.CharacterAdded:Wait() --get player's character if char ~= nil then char.Humanoid.Died:Connect(function() -- fires when player dies OnRemovePlayer(player.Name,Playerstable) end) end end)
Instead of the other answer, I recommend making your code modular that can suit more than one situation. This is simply done with the function below
function removeFromTable (argTable, argValue) for index,value in pairs (argTable) do if value == argValue then table.remove(argTable, index) return argTable; end end return argTable; end
That makes your code more modular and can be used in multiple situations instead of just one.
Simply call it like so: removeFromTable(table, valueToRemove)
The solution to your question is simply the following:
local playersTable = {}; local Players = game:GetService("Players"); Players.PlayerAdded:Connect(function(newPlayer) table.insert(playersTable, newPlayer) end) Players.PlayerRemoving:Connect(function(player) playersTable = removeFromTable(playersTable, player); end)
This will insert the player that joined into the table playersTable
and remove them from it when they leave.