If I make a list of players (using :getplayers) and a player leaves, will their key be removed or just set to nil?

Example of code:

--Players in game: Rob, Bobby
local usersIngame = game:GetService("Players"):GetPlayers()

print(usersIngame)
--If Rob leaves will this print:
--[[
1) [1] = nil, [2] = Bobby (Sets Value to nil)
or
2) [1] = Bobby  (Removed value
]]

it will be unchanged. the player instance will stay referenced in your table until you remove it

you should work with events like PlayerAdded and PlayerRemoved to add or remove players from the list, or to update the list

2 Likes

If I refer to the item in the list will it be nil?

Example:

--Players in game: Rob, Bobby
local usersIngame = game:GetService("Players"):GetPlayers()

for i, v in ipairs(usersIngame) do
     if v then 
          print(v)
     end
end
--Will this print Rob or not print because its nil?

the key will still stay ofc but the value will be set to nil

yes.

Like @4SHN said, the Player object is an instance and will remain referenced in the table. It won’t appear as nil, however its parent will be nil as the Player object becomes “Destroyed” when a player disconnects. So if you run your code, it will print the name of the Player object (which would be the Player’s username).

2 Likes

i mean it just return array so it automatically removes i forgot that

So to filter the list can I simply add:

local usersIngame = game:GetService("Players"):GetPlayers()

for i, v in ipairs(usersIngame) do
     if not v then 
          table.remove(usersIngame, v)
     end
end
local playerList = {}
local players = game:GetService('Players')

players.PlayerAdded:Connect(function(player)
	table.insert(playerList,player)
end)

players.PlayerRemoving:Connect(function(player)
	local value = table.find(playerList,player)
	if value then
		table.remove(playerList,value)
	end
end)

Though you don’t really need the if statement, it’s just in case.
table.remove() only takes an array and a number value (the value position in the array), so you’ll need to use table.find().

1 Like

no, v will still be that player, not nil
you can test this in a Local Server in studio
also, it’s similar to saving a part in a table, then destroying the part

table.remove() will accept a ‘nil’ value as its second argument, it just won’t remove anything from the array if the case.