Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

GetPlayers() loop, no Players?

So, I have a for loop that is suppose to get a list of all the players in the game using GetPlayers(), as shown here:

local PlayerList = {}

do
	for _,player in pairs(game.Players:GetPlayers()) do
		if player:IsA("Player") then
			PlayerList[player] = true
		end
	end		
	PlayerAmount = (#PlayerList)
end

However something wasn't working later in the code when I needed PlayerAmount, so for debugging I added this:

print(PlayerAmount)

And it prints 0. Anyone have any idea whats wrong? Any help is appreciated, thanks! :)

And no, it's not disabled. :)

1 answer

✓ Accepted answer

You can't use # to get the correct number of elements of a table unless:

  1. The first index is 1,
  2. The rest of the indices are sequential, and
  3. None of the values are nil
t = {["this"] = "is", ["a"] = "dictionary"}
print(#t) -- prints 0

t = {[2] = "b"}
print(#t) -- prints 0

t = {[1] = "a", [2] = nil}
print(#t) -- prints 1

t = {[1] = "a", [3] = "c"}
print(#t) -- prints 1

t = {[1] = "a", [2] = "b", [3] = "c"}
print(#t) -- prints 3

Instead of doing PlayerList[player] = true, just do table.insert(PlayerList, player). That way, all indices are guaranteed to be sequential (unless, of course, you're inserting nil).

This discussion is preserved as it was. New answers, comments, and votes are closed.