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
]]
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
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).
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()
.
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.