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
1 | local players = game:GetService( "Players" ) |
3 | local playersIngame = players:GetPlayers() |
5 | for i, player in pairs (playersIngame) do |
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
7 | local lengthOfMyTable = #myTable |
With an output of:
3
The Final Product
1 | local players = game:GetService( "Players" ) |
3 | local playersIngame = players:GetPlayers() |
4 | local numberOfPlayers = #playersIngame |
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