✓ Accepted answer
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
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
local Table = {}
local Players = game:GetService("Players")
local playercount = 0
local RemovePlayerTimer = 30
local playersLeftTab = {}
local function playerlistprint()
print("Current Players: [Active: ",playercount,"], Just Left: [",#playersLeftTab,"]")
for i, v in pairs(Table) do
print(i," = ",v)
end
end
Players.PlayerAdded:Connect(function(user)
playercount = playercount + 1
local PlrIndex = table.find(playersLeftTab,user.Name)
if(PlrIndex ~= nil) then
table.remove(playersLeftTab,PlrIndex)
end
if(Table[user.Name]== nil) then
Table[user.Name] = user
print(user.Name.." has joined")
else
print(user.Name.." has Re-Joined")
end
playerlistprint()
end)
Players.PlayerRemoving:Connect(function(user)
if(Table[user.Name] ~= nil)then
table.insert(playersLeftTab, {
Name = user.Name,
Time = RemovePlayerTimer,
Ticker = tick()
}
)
end
playercount = playercount - 1
print(user.Name.." Has Left!")
playerlistprint()
end)
while true do
local NowTick = tick()
for k,v in pairs(playersLeftTab) do
local Name = v.Name
local Time = v.Time
local Tick = v.Ticker
local DTick = NowTick - Tick
if(DTick >= Time) then
Table[Name] = nil
table.remove(playersLeftTab,k)
playerlistprint()
end
end
wait()
end
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!
1 comment
I skimmed Gazza's post and I think he might've mentioned this but I'd use a dictionary. Table[plr.Name] = true...... print(Table["greatneil80"]).... true, it'd save a lot of time and effort.