Would this keep up with object instances?

local Player = {}

Player.players = {} -- Keep up with instances
Player._index = Player

-- Constructor
function Player.new(PlayerID)
	local self = setmetatable({}, Player)
	
	self.PlayerID = PlayerID
	table.insert(Player.players, self)
	
	return self
end

Well, it depends on how you implement it. If you keep a single reference to the player object module, such as in the following:

local PlayerObject = require(my.PlayerObject)

game:GetService("Players").PlayerAdded:Connect(function(player)
    local playerObj = PlayerObject.new(player.UserId)
end)

then yeah it would, but if you were to do:

game:GetService("Players").PlayerAdded:Connect(function(player)
    local playerObj = require(my.PlayerObject).new(player.UserId)
end)

… then you wouldn’t have a solid reference to the module, so you wouldn’t be able keep track of player objects that way.

An alternative is to just store the player object in the script that requires the player object.

local PlayersList = {}
local PlayerObject = require(my.PlayerObject)

game:GetService("Players").PlayerAdded:Connect(function(player)
    local playerObj = PlayerObject.new(player.UserId)
    PlayersList[player.UserId] = playerObj
end)

TLDR; if you have a single, solid reference to the module you required (via a variable), then yes, it would store the object instances for you. (See first code block). If you were to do this, I think storing them in a dictionary, using their UserId as a key, would be much simpler for you later on.

1 Like