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

Why is my players variable saving as an object?

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?

1 comment

0

pairs takes in a table, so it would be player:GetPlayers()

2 answers

✓ Accepted answer

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.

1 comment

0

Thank you, I forgot about that

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

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