Skip to content

Instantly share code, notes, and snippets.

@howmanysmall
Created September 5, 2019 20:10
Show Gist options
  • Save howmanysmall/e60d458eeac204d8669024499f7815d4 to your computer and use it in GitHub Desktop.
Save howmanysmall/e60d458eeac204d8669024499f7815d4 to your computer and use it in GitHub Desktop.
-- VARIABLES
local ServersHandler = {}
local ServerList = {}
-- This is O(1) vs table.remove being O(n) (I think)
local function FastRemove(Table, Index)
local Length = #Table
Table[Index] = Table[Length]
Table[Length] = nil
end
local CurrentPlayers = PlayersS:GetPlayers()
local CurrentLength = #CurrentPlayers do
local function PlayerAdded(Player)
CurrentLength = CurrentLength + 1
CurrentPlayers[CurrentLength] = Player
end
local function PlayerRemoving(Player)
for Index = 1, CurrentLength do
if CurrentPlayers[Index] == Player then
CurrentPlayers[Index] = CurrentPlayers[CurrentLength]
CurrentPlayers[CurrentLength] = nil
CurrentLength = CurrentLength - 1
break
end
end
end
PlayersS.PlayerAdded:Connect(PlayerAdded)
PlayersS.PlayerRemoving:Connect(PlayerRemoving)
end
-- FUNCTIONS
function ServersHandler.Added(Data)
-- I'd avoid mixed tables if possible.
ServerList[Data.JobId] = {JobId = Data.JobId, Players = Data.Players}
table.insert(ServerList,Data.JobId)
print('Servers|',#ServerList)
end
function ServersHandler.Removing(Data)
ServerList[Data.JobId] = nil
for i = 1, #ServerList do
if ServerList[i] == Data.JobId then
FastRemove(ServerList,i)
print('Servers|',#ServerList)
end
end
end
function ServersHandler.PlayerAdded(Data)
ServerList[Data.JobId].Players = Data.Players
end
function ServersHandler.PlayerRemoving(Data)
ServerList[Data.JobId].Players = Data.Players
end
local function ServersHandler_Func(Message)
if ServersHandler[Message.Data.Status] then
ServersHandler[Message.Data.Status](Message.Data)
end
end
local function GetPlayers()
local PlayersTable = {}
for Index = 1, CurrentLength do
local Player = CurrentPlayers[Index]
PlayersTable[Player.Name] = {UserId = Player.UserId, Name = Player.Name}
end
return PlayersTable
end
-- SCRIPTS
MessagingS:SubscribeAsync('Servers',ServersHandler_Func)
MessagingS:PublishAsync('Servers',{Status = "Added", JobId = game.JobId, Players = GetPlayers()})
PlayerS.PlayerAdded:Connect(function(plr)
MessagingS:PublishAsync('Servers',{Status = "PlayerAdded", JobId = game.JobId, Players = GetPlayers()})
plr:LoadCharacter()
end)
PlayerS.PlayerRemoving:Connect(function(plr)
plr.AncestryChanged:Wait()
MessagingS:PublishAsync('Servers',{Status = "PlayerRemoving", JobId = game.JobId, Players = GetPlayers()})
end)
if not RunS:IsStudio() then
game:BindToClose(function()
wait(5)
MessagingS:PublishAsync('Servers',{Status = "Removing", JobId = game.JobId})
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment