Constantly updated table

I would like it so that I have a table of all players that are alive, and a table of all players that are dead. I want the list to be constantly updated and accessible by all scripts. I previously tried setting the parent of the characters to folders but this is unreliable and doesn’t work. I read the documentation for module scripts but it said it only runs once. What would be the best way to approach this?

2 Likes

You can use a module script, for example this is what you could do:

local DeadPlayers = {}
local AlivePlayers = {}

local PlayerStateHandler = {}

--call this to put a player in the Alive List
function PlayerStateHandler.MakeAlive(Player)
    --[[
        Adding player to the Alive list
        and removing from the Dead list
    ]]
     AlivePlayers[Player.UserId] = true
     DeadPlayers[Player.UserId] = nil
end

--call this to put a player in the Dead List 
function PlayerStateHandler.MakeDead(Player)
    --[[
        Adding player to the Dead list
        and removing from the Alive list
    ]]
     DeadPlayers[Player.UserId] = true
     AlivePlayers[Player.UserId] = false
end

--checks if the player is in the Alive List
function PlayerStateHandler.IsAlive(Player)
     return AlivePlayers[Player.UserId] ~= nil
end

--checks if the player is in the Dead List
function PlayerStateHandler.IsDead(Player)
     return DeadPlayers[Player.UserId] ~= nil
end

return PlayerStateHandler
2 Likes

How would I access the Deadplayers and Aliveplayers tables from other scripts?

You would just do require(PathToModulescriptInHere), and then you can access the PlayerStateHandler table from any script that requires that module.

If you want just add a function that returns the DeadPlayers and AlivePlayers table:

function PlayerStateHandler.GetAlivePlayers()
    return AlivePlayers
end

function PlayerStateHandler.GetDeadPlayers()
    return DeadPlayers
end

Remember that right now the user id of the player is only being stored, if you need to store the player object themselves you can easily add them, but ensure you remove the reference when the player leaves or you will have memory leak.

1 Like

So is there anyway I can go on another script and just have the AlivePlayers table. Like I can say something like:

Local module = require(game.ServerScriptStorage.Module)

Local alive = module.AlivePlayers

For I, v in pairs(alive) do
   Print(I,v)
End

And what does returning a table even do? Where can I access the table values after that?