How can I fix overwriting in OOP

So this issue has been bugging me for a while now, in scripts I normally pass over plr parameter to the module script so that I could use it later on while working around with UIs

Problem here is that if I pass it once it does what I want but if I’m doing this with multiple player it overwrites the value to the last plr that has used the function.

Is there a way to assign plr to you only without it getting overwritten, I want to do this on server than locally

Example:

function SideMenu.new(plr)
	local Menu = {}
	setmetatable(Menu)

	SideMenu.plr = plr --  Becomes the plr instance

	return Menu
end

local Menu = require(SideMenu)

Menu.new(plr)

I think you’re meant to set Menu’s plr, not SideMenu’s plr

function SideMenu.new(plr)
	local Menu = {}
	setmetatable(Menu, SideMenu)

	Menu.plr = plr --  Becomes the plr instance

	return Menu
end

If I do it like Menu.plr then I can’t use these values later on, like I can’t do self.plr

Then it’s probably something wrong with your implementation of OOP, could it be that you also forgot to correctly set a metatable to Menu in your original code?

This is how it looks:

local SideMenu = {}
SideMenu.__index = SideMenu

function SideMenu.new(plr)
	local Menu = {}
	setmetatable(Menu, SideMenu)

	SideMenu.plr = plr

	return Menu
end

I’m pretty sure in that case you’d just need to set Menu’s plr instead of SideMenu and it should work fine.

Try creating a random function such as

function SideMenu:PrintPlayer()
   print(self.plr)
end

And see if it prints after changing SideMenu.plr to Menu.plr, using the returned Menu object from Menu.new

From that function is prints nil

How are you calling the function?

SideMenu:PrintPlayer() at the bottom off the .new before it returns Menu

SideMenu has nothing inside of the plr key, to properly do it, try something like this where you required SideMenu

local menu = Menu.new(plr)
menu:PrintPlayer()

Although I’m not sure if this is exactly what you wanted in the end, if you need the plr objects to be in SideMenu, then you need to use a table and just add the player in that table

Yep it worked, would I need to do this for every script with .new function then?

Yep if they also have a plr key, the key must be set to the object you’re creating and then returning