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

Why is my players variable saving as an object?

Asked by 6 years ago

I have a script that needs to run through all of the players. It's telling me this error though

ServerScriptService.LevelHandler:2: bad argument #1 to 'pairs' (table expected, got Object)
local players = game:GetService("Players")
for _, player in pairs(players) do
    print("works")
end

Why does it think that players is an object?

0
pairs takes in a table, so it would be player:GetPlayers() User#23365 30 — 6y

2 answers

Log in to vote
1
Answered by
yHasteeD 1819 Moderation Voter
6 years ago
Edited 6 years ago

You need to use game:GetService("Players"):GetPlayers()

Fixed script:

local players = game:GetService("Players") -- Or you can use :GetPlayers() here and on pairs(...) dont need to put it.
for _, player in pairs(players:GetPlayers()) do
    print("works")
end

This method returns a table of all presently connected Player. It functions the same way GetChildren would except that it only returns Player objects. It functions similarly to Instance:GetChildren when called on Players. When used in conjunction with a for-loop, it is useful for iterating over all players in a game.

You need to use a "table" and :GetChildren()/:GetPlayers() transform this to a "table" for catch players.

Hope it helped :D

Wiki pages:

GetPlayers


Solved your problems? put in title [SOLVED] or accept a answer.
0
Thank you, I forgot about that repgainer3 35 — 6y
Ad
Log in to vote
2
Answered by 6 years ago

Hi repgainer3,

The reason it's giving you the error is because you're trying to iterate through the service 'Players', and not a table. You can get the table by using :GetPlayers(). Like this:

local players = game:GetService("Players"):GetPlayers() -- Makes it a table with all the players.
for _, player in pairs(players) do
    print("works")
end

Hope I helped and have a wonderful day/night.

Thanks,

Best regards,

KingLoneCat

Answer this question