The best way to do this is not through loops as many of the other replies would suggest.
First, start by getting the Players Service, since we will be using that, and defining your TextLabel. For example's sake, I'm just creating one - feel free to assign this variable to an already existing TextLabel
local Players = game:GetService("Players")
local TextLabel = Instance.new("TextLabel")
Now, initially assign the text the amount of players in game. Do this by making your code look like:
local Players = game:GetService("Players")
local TextLabel = Instance.new("TextLabel")
local NumberOfPlayers = #Players:GetPlayers()
NumberOfPlayers = tostring(NumberOfPlayers)
TextLabel.Text = NumberOfPlayers
All I am doing in this is getting the number of players (by calling the GetPlayers function which returns a table of how many players are in the server, and then getting the amount of elements (Players) in this table)
Then I convert that (number of players) into a string, so that it can fill the text field of the TextLabel
Then I set the text of the TextLabel to this value
After doing this, I am going to use two events - PlayerAdded and PlayerRemoving - to detect when the number of Players changes. This is better than using a loop because these events are built in to the engine and more efficient since they only fire when the action occurs rather than checking all the time. The code, with that added, looks like below:
local Players = game:GetService("Players")
local TextLabel = Instance.new("TextLabel")
local NumberOfPlayers = #Players:GetPlayers()
NumberOfPlayers = tostring(NumberOfPlayers)
TextLabel.Text = NumberOfPlayers
Players.PlayerAdded:Connect(function(Player)
NumberOfPlayers = tonumber(NumberOfPlayers)
NumberOfPlayers = NumberOfPlayers + 1
NumberOfPlayers = tostring(NumberOfPlayers)
TextLabel.Text = NumberOfPlayers
end)
Players.PlayerRemoving:Connect(function(Player)
NumberOfPlayers = tonumber(NumberOfPlayers)
NumberOfPlayers = NumberOfPlayers - 1
NumberOfPlayers = tostring(NumberOfPlayers)
TextLabel.Text = NumberOfPlayers
end)
The above code is what you are looking for. I would recommend adjusting the TextLabel (referring to the variable in the code, not the instance) by assigning that variable to the actual TextLabel that you want the code to apply to.
Hope that helps!