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

How to see how many players there are in your server?

Asked by 4 years ago

Is it possible to see how many players are playing in your server right now, in a script?

2 answers

Log in to vote
6
Answered by 4 years ago
Edited 4 years ago

Note

I already see an answer on the question but it doesn't give a comprehensive explanation on how it works.

Question

How to see how many players there are in your server?

Answer

Short Answer

Get the length of an array generated from :GetPlayers()

Long Answer

To start off, we should look at the API documentation for the Players service A look at that will reveal the :GetPlayers() method which returns an array containing all of the players that are in game.

Example of using :GetPlayers()

Get all the ingame players and output their names

local players = game:GetService("Players")

local playersIngame = players:GetPlayers()

for i, player in pairs(playersIngame) do
    print(player.Name)
end

The number of players in the game will be the length of the array. How do we get the length of an array? you may ask. You can use the # operator which when invoked on a table will return the length of the table.

Example of Length Operator

Output the length of myTable

local myTable = {
    "apple",
    "pear",
    "banana"
}

local lengthOfMyTable = #myTable

print(lengthOfMyTable)

With an output of:

3

The Final Product

local players = game:GetService("Players") --// define players service

local playersIngame = players:GetPlayers() --// get the players ingame
local numberOfPlayers = #playersIngame --// get the length of the array containing the players

print(numberOfPlayers) --// output the length which is how many players are ingame

Reading Resources:

https://developer.roblox.com/en-us/api-reference/function/Players/GetPlayers

https://en.wikibooks.org/wiki/Lua_Programming/length_operator

https://developer.roblox.com/en-us/api-reference/function/ServiceProvider/GetService

https://www.lua.org/pil/2.5.html

https://www.lua.org/pil/7.1.html

Ad
Log in to vote
2
Answered by 4 years ago
Edited 4 years ago

Do this to get how many players there are in a server.

print(#game.Players:GetPlayers())

Answer this question