Basically I want to add players names to a table when they join and remove them when they leave. How do you search through the table and remove the players name when they leave. This is what I have so far.
listofaccounts = {} function inTable(listofaccounts, item) for key, value in pairs(listofaccounts) do if value == item then return key end end return false end game.Players.PlayerAdded:connect(function(player) local player1 = player.Name table.insert(listofaccounts, player1) end) game.Players.PlayerRemoving:connect(function(player) local player1 = player.Name if listofaccounts[player.Name] then table.remove(listofaccounts, inTable(listofaccounts, player.Name)) end end)
Here's something that should work:
local playerNames = {} game.Players.PlayerAdded:connect(function(player) playerNames[player.UserId] = player.Name end) game.Players.PlayerRemoving:connect(function(player) playerNames[player.UserId] = nil end)
Here's an explanation to what all of this is:
First off, we have this:
local playerNames = {}
That tells Lua we want to create a blank table called playerNames
. Notice how we use the keyword local
before the name of the variable. Using the local
keyword for variables has numerous positive effects.
Next, we have the PlayerAdded
event handler:
game.Players.PlayerAdded:connect(function(player) playerNames[player.UserId] = player.Name end)
When the player connects, we add the player's name to the playerNames
table with their UserId as the index.
Finally, we have the PlayerRemoving
event handler:
game.Players.PlayerRemoving:connect(function(player) playerNames[player.UserId] = nil end)
When a player disconnects, we set the player's name to nil
in the playerNames
table using the same index as before (their UserId). Setting a value in a table to nil
triggers garbage collection, or more simply, removes the entry from the list.
I hope this helped. Good luck!