How to access an object?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

I am attempting to make an OOP data module.

  1. What is the issue? Include screenshots / videos if possible!

I want to access the data object of a certain player without making a whole new one each time I access it from outside the player added script.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I tried returing self but cant find anything that helps me out with this issue roblox.

module

function StatsManager.new(player)
	local self = {}
	setmetatable(self, StatsManager)
	
	self.Key = "hello"
	
	return self
end

function StatsManager:GetManager(player)
	return self
end

server script


local StatsManger = require(script.Parent.StatsManager)

game.Players.PlayerAdded:Connect(function(player)
	local PlayerStatManager = StatsManger.new(player)
	
	local Manager = StatsManger:GetManager(player)
	print(Manager.Key)
end)

Good question :slight_smile:

Usually, this is done by keeping a separate list of data objects that you add/remove items from when players enter/leave. There’s a similar principle at the bottom of the CollectionService wiki page which deals with Tags being added/removed, but it’s the same process.

Basically:

local StatsManger = require(script.Parent.StatsManager)

local playerStatsManagers = {}

game.Players.PlayerAdded:Connect(function(player)
	local PlayerStatManager = StatsManger.new(player)
	
	-- keep track of it!
	playerStatsManagers[player] = PlayerStatManager
end)

game.Players.PlayerRemoving:Connect(function(player)
	if playerStatsManagers[player] then
		-- clean it up (also call a Destroy method if your object has any
		-- cleanup it needs to do)
		playerStatsManagers[player] = nil
	end
end)

Then you just do playerStatsManagers[player] whenever you need the stats for a player.