Greetings, I’ve attempted to remove a player from a table. However, it doesn’t seem to work. I’ve tried numerous things that have been suggested on the Wiki and Forums. To be quite honest, I don’t know what is wrong with this code. Any help would do.
local Players = game:GetService("Players")
Players.PlayerRemoving:Connect(function(Player)
for i = 1, #Boat1 do -- Boat1 is a table.
if Boat1[i] == Player then
table.remove(Boat1, i)
warn(Player.Name..", Was Removed From Boat1 Because They've Left The Game!")
end
end
for i = 1, #Boat2 do -- Boat2 is a table.
if Boat2[i] == Player then
table.remove(Boat2, i)
warn(Player.Name..", Was Removed From Boat2 Because They've Left The Game!")
end
end
for i = 1, #Boat3 do -- Boat3 is a table.
if Boat3[i] == Player then
table.remove(Boat3, i)
warn(Player.Name..", Was Removed From Boat3 Because They've Left The Game!")
end
end
end)
I looked again at the code and I think it will not work, because Player is the value and not the index, but Boat1[i] = nil, it should work and if it does not work then the problem is elsewhere.
Can you show us how you are inserting the player into the table?
I quickly setup a simple script and it works fine and should be about the same as what you’re doing.
local Players = game:GetService("Players")
local Table = {}
Players.PlayerAdded:Connect(function(Player)
table.insert(Table, #Table + 1, Player)
end)
Players.PlayerRemoving:Connect(function(Player)
for i = 1, #Table do
if Table[i] == Player then
print(Table[i])
table.remove(Table, i)
print(Table[i])
end
end
end)
When the player leaves the output is:
CleverSource
nil
this is correct as I print the player before I remove them from the table, I remove them, and then print the index of the table again and it is nil.
I think you’ve mistaken how this code works. Boat1[i] would return the value in Boat1 with the index of the variable i.
E.g.
If the items within Boat1 would be {“hello”,“there”,“my”,“name”,“is”,“bob”}
and the value of i would be 3,
print(Boat1[i]) would output the string “my”.
Storing the player object is fine though. That should not be a mistake. If you review the sample code I’ve provided, I am storing the player object, the sample code I am referring to is here.
Not sure how storing player objects is affected by when players leave, but if you’re going to change it to store the player’s usernames, make sure to also compare them to the player’s username and not the object.
That is your error. You need to do table.insert(Boat1, #Boat1 + 1, Player) and so on. table.insert takes 3 parameters, the table which you want to add the value to, the index you wish to add it to, and the value you want to add.