Merge pull request #1202 from Gellipapa/ESX.GetNumOfPlayers

♻️ Little refactor and handle job counter with GlobalState
This commit is contained in:
Gellipapa
2023-09-17 15:31:40 +02:00
committed by GitHub
3 changed files with 53 additions and 1 deletions
+1
View File
@@ -1,6 +1,7 @@
ESX = {}
ESX.Players = {}
ESX.Jobs = {}
ESX.JobsPlayerCount = {}
ESX.Items = {}
Core = {}
Core.UsableItemsCallbacks = {}
+28
View File
@@ -276,6 +276,34 @@ function ESX.GetExtendedPlayers(key, val)
return xPlayers
end
function ESX.GetNumPlayers(key, val)
if not key then
return #GetPlayers()
end
if type(val) == "table" then
local numPlayers = {}
if key == "job" then
for _, v in ipairs(val) do
numPlayers[v] = (ESX.JobsPlayerCount[v] or 0)
end
return numPlayers
end
local filteredPlayers = ESX.GetExtendedPlayers(key, val)
for i, v in pairs(filteredPlayers) do
numPlayers[i] = (#v or 0)
end
return numPlayers
end
if key == "job" then
return (ESX.JobsPlayerCount[val] or 0)
end
return #ESX.GetExtendedPlayers(key, val)
end
function ESX.GetPlayerFromId(source)
return ESX.Players[tonumber(source)]
end
+24 -1
View File
@@ -386,7 +386,10 @@ AddEventHandler('playerDropped', function(reason)
if xPlayer then
TriggerEvent('esx:playerDropped', playerId, reason)
local job = xPlayer.getJob().name
local currentJob = ESX.JobsPlayerCount[job]
ESX.JobsPlayerCount[job] = ((currentJob and currentJob > 0) and currentJob or 1) -1
GlobalState[("%s:count"):format(job)] = ESX.JobsPlayerCount[job]
Core.playersByIdentifier[xPlayer.identifier] = nil
Core.SavePlayer(xPlayer, function()
ESX.Players[playerId] = nil
@@ -394,6 +397,26 @@ AddEventHandler('playerDropped', function(reason)
end
end)
AddEventHandler("esx:playerLoaded", function(playerId, xPlayer, isNew)
local job = xPlayer.getJob().name
local jobKey = ("%s:count"):format(job)
ESX.JobsPlayerCount[job] = (ESX.JobsPlayerCount[job] or 0) +1
GlobalState[jobKey] = ESX.JobsPlayerCount[job]
end)
AddEventHandler("esx:setJob", function(src, job, lastJob)
local lastJobKey = ('%s:count'):format(lastJob.name)
local jobKey = ('%s:count'):format(job.name)
local currentLastJob = ESX.JobsPlayerCount[lastJob.name]
ESX.JobsPlayerCount[lastJob.name] = ((currentLastJob and currentLastJob > 0) and currentLastJob or 1) -1
ESX.JobsPlayerCount[job.name] = (ESX.JobsPlayerCount[job.name] or 0) + 1
GlobalState[lastJobKey] = ESX.JobsPlayerCount[lastJob.name]
GlobalState[jobKey] = ESX.JobsPlayerCount[job.name]
end)
AddEventHandler('esx:playerLogout', function(playerId, cb)
local xPlayer = ESX.GetPlayerFromId(playerId)
if xPlayer then