Okay so I’m making a script that insert the player into a table and I also add a code of line where
when the player leaves it removes the player from the table
local tab = {}
game.Players.PlayerAdded:Connect(function(plr)
table.insert(tab,plr)
end)
game.Players.PlayerRemoving:Connect(function(plr)
table.remove(tab,plr)
if #tab == 0 then
print("Table is empty")
end
if #tab >0 then
print("There is still a variable in the table")
end
end)
but I get an error saying
[Workspace.Script:9: invalid argument #2 to ‘remove’ (number expected, got Instance)]
local PlayersInServer = {} -- Use a dictionary for easy key, pair references
game.Players.PlayerAdded:Connect(function(player)
PlayersInServer[player] = player;
end)
game.Players.PlayerRemoving:Connect(function(player)
if (PlayersInServer[player]) then
PlayersInServer[player] = nil; -- Removes the key, pair for the dictionary
end
end)
Not tested but it should work. If you still get an error, you can try PlayersInServer[player.Name] = player, since the name cannot be nil.
Edit: game.Players is a service with a table of its own. You could simply call game.Players:GetChildren() and operate on the returned table. It will always be correct. You do need to make nil checks to check that the player is still in the game, but it’s the same case for any table.
Open the Output view
The output window will tell you all you need to know regarding errors in your code. You just have to learn how to use it.
For example, in the example above, you would get an error something like this
Error on line 1: "players" is not a member of game.
As for your actual issue. You have a reference to ”Player" which doesn’t appear in the highlighted code. @Exeplex code should work fine for you though.
One last thing.
Please learn to use proper structure when writing code, like in his example.
local PlayersInServer = {} -- Use a dictionary for easy key, pair references
game.Players.PlayerAdded:Connect(function(player)
PlayersInServer[player] = player;
end)
game.Players.PlayerRemoving:Connect(function(player)
If (PlayersInServer[player]) then
PlayersInServer[player] = nil; -- Removes the key, pair for the dictionary
end
end)
-- this is functional code, but it's harder to read because there's no tabs.
Learning to wiring structured code and using the Output window will go a long way for you.
Okay from reading this and from a other post related to this I think I understand now
instead of using just the player variable
I’m going to use a for i,v in pair for the table and when the player.Name == v.Name then
table.remove(table,i)