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)
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!