Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

GetPlayers() loop, no Players?

Asked by 8 years ago

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

Log in to vote
2
Answered by
XAXA 1569 Moderation Voter
8 years ago

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

Ad

Answer this question