Removing item from table by string instead of index position

I’m trying to create a match system that inserts a player into a table once they click on a button and remove them from the table after they leave the match. My question is how can I remove a player from the table by using the player’s username instead of the position of the item in the table, or is there a way I can get the index position of the player from the table and then remove it.

local joinEvent = events:WaitForChild("JoinGame")

local leaveEvent = events:WaitForChild("LeaveGame")

local JoinedPlayers = {}

local function onJoin(player)

table.insert(JoinedPlayers, player.Name)

end

joinEvent.Event:Connect(onJoin)

local function onLeave(player)

table.remove(JoinedPlayers, player.Name)

end

leaveEvent.Event:Connect(onLeave)

Any help is appreciated, thanks!

to remove a string from a table, you can do this

for i, v in pairs(JoinedPlayers) do
   if v == player.Name then
      table.remove(v, i)
   end
end
3 Likes

Thanks! Sorry I’m pretty new to tables

1 Like

To answer your question specifically about getting the index with the name: the canonical and proper way to do this now is table.find, which allow you to find a position given an element. You should avoid adding or removing indices within a for loop as it could interrupt iteration. Additionally, ipairs should be used over pairs when iterating over arrays, but that still doesn’t make it appropriate to use.

local position = table.find(JoinedPlayers, player.Name)
if position then
    table.remove(JoinedPlayers, position)
end

EDIT: As pointed out below, if your table is filled predictably then you don’t need the if statement. A bit of a minor nitpick and ultimately irrelevant but it’s solid advice!

4 Likes
table.remove(JoinedPlayers, table.find(JoinedPlayers, player.Name))

If statement redundant here as the player will always exist in the table (as they are added when they join the game).