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 5 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 5 years ago
Edited 5 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

1local players = game:GetService("Players")
2 
3local playersIngame = players:GetPlayers()
4 
5for i, player in pairs(playersIngame) do
6    print(player.Name)
7end

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

1local myTable = {
2    "apple",
3    "pear",
4    "banana"
5}
6 
7local lengthOfMyTable = #myTable
8 
9print(lengthOfMyTable)

With an output of:

3

The Final Product

1local players = game:GetService("Players") --// define players service
2 
3local playersIngame = players:GetPlayers() --// get the players ingame
4local numberOfPlayers = #playersIngame --// get the length of the array containing the players
5 
6print(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 5 years ago
Edited 5 years ago

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

1print(#game.Players:GetPlayers())

Answer this question