The following code looks complicated at first, I've expanded on your example to include a timer.
Your way is good and as you say it works
but the script might get out of sync with too many players leaving and rejoining or even adding the same player to your Table
But with a different index!.
The following code will fix this issues by using the Names of the players as index.
For example
1 | table.insert(Table,user.Name) |
inserts the user at the end of the table Table = {}
this is great in an ideal world but knowing the real world, things happen, like players leaving before they get registered etc... Or they join for a second then leave due to connection problems. So the following code is my attempt at fixing and coding for these problems. And added a 30-second cool down timer for lag drops.
Brace your self for the code! It's quite complex! :P
002 | local Players = game:GetService( "Players" ) |
007 | local RemovePlayerTimer = 30 |
010 | local playersLeftTab = { } |
014 | local function playerlistprint() |
015 | print ( "Current Players: [Active: " ,playercount, "], Just Left: [" ,#playersLeftTab, "]" ) |
016 | for i, v in pairs (Table) do |
022 | Players.PlayerAdded:Connect( function (user) |
025 | playercount = playercount + 1 |
028 | local PlrIndex = table.find(playersLeftTab,user.Name) |
031 | if (PlrIndex ~ = nil ) then |
032 | table.remove(playersLeftTab,PlrIndex) |
037 | if (Table [ user.Name ] = = nil ) then |
039 | Table [ user.Name ] = user |
042 | print (user.Name.. " has joined" ) |
045 | print (user.Name.. " has Re-Joined" ) |
053 | Players.PlayerRemoving:Connect( function (user) |
055 | if (Table [ user.Name ] ~ = nil ) then |
057 | table.insert(playersLeftTab, { |
059 | Time = RemovePlayerTimer, |
066 | playercount = playercount - 1 |
068 | print (user.Name.. " Has Left!" ) |
077 | local NowTick = tick() |
079 | for k,v in pairs (playersLeftTab) do |
088 | local Tick = v.Ticker |
091 | local DTick = NowTick - Tick |
094 | if (DTick > = Time) then |
097 | table.remove(playersLeftTab,k) |
I've tried to comment what bit does what as plainly as i can. Feel free to ask if you need help! :)
The above code works when put into the ServerScriptService
Service. I've tested it online and it appears to work well. (had two accounts sign in to the game then one leaves then re-joins before the 30 secs. The script successfully detects this and if they leave and let the 30 secs count down the script forgets them!)
Hope this helps!