Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Remove Player from Table, when he dies or disconnects?

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.

2 answers

✓ Accepted answer

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.

6 comments

0

lol, you sent same code but using for index,value. Here is nothing modular

0

Of course it is modular, it works for multiple tables and not just checking if the name is the same.

0

mine too. Please re-read my answer

0

I have. Just a suggestion, start with proper naming. OnRemovePlayer is confusing since you're just removing them from a table.

0

name isnt important thing

0

Then you're wrong about coding, sadly. Proper naming plays a huge role when it comes to coding. If you cannot name your functions, variables and other things in your code properly, you have still yet to learn.

This discussion is preserved as it was. New answers, comments, and votes are closed.