How would I do this

Okay so I am making a bank robbery script
and what I am trying to do is check if the player is already in a table else run a code you see what I am doing currently is not working
here is what I am doing:
for i,v in pairs(TheNameOfTable) do
if v.Name == player.Name then
print(Player is already in table)
else
–code here to add them to the table and when they leave the game or died remove them from table code here
end
end

You see what the problem with this code is if there is more then 1 player in this table the code will run the else code more than once and this will create a lot of problems like memory leaks and stuff
so does anyone have any other better way to do this

any help will be appreciated if confused please ask questions

local playerFound = false
if not table.find(TheNameOfTable, player) then
    table.insert(TheNameOfTable, player)
    local diedConn, leftConn
    diedConn = player.Character.Humanoid.Died:Connect(function()
        diedConn:Disconnect()
        leftConn:Disconnect()
        table.remove(table.find(TheNameOfTable, player))
    end)
    leftConn = game:GetService("Players").PlayerRemoving:Connect(function(playerWhoLeft)
        if playerWhoLeft == player then
            diedConn:Disconnect()
            leftConn:Disconnect()
            table.remove(table.find(TheNameOfTable, player))
        end
    end)
end
2 Likes

Thank you this seems to work out good so far
I thought table.find only works for index

Table.find gives the index of the value in the table. If the table isn’t an array, table.find won’t work.

1 Like

If your problem has been solved by @RoBoPoJu, it would be good to mark him as a “Solution” at the bottom of his reply.

2 Likes