How do i improve the way i create objects?

this is how i create the objects in OOP.

Is there a better way of creating objects?

function module.new(player, distance, partsFolder)
	local self = setmetatable({},module)
	
	
	self.Player = player
	self.Distance = distance
	self.Folder = partsFolder
	
	return self
end
1 Like

I mean I don’t think there’s any “better” ways to do so. There’s just different syntax and your personal programming style.

local table = {}
table.Player = player
table["Player"] = player

You could also just do:

local object = {
    Player = player,
    Distance = distance,
    Folder = partsFolder
}

-- index object list
print(object.Player, object["Distance"])

I often just make a default object list for like inventory datastores. But you could request a modulescript and it’ll do the same thing. Whatever makes more sense to you and your team unless the project is performance-sensitive which I wouldn’t have the details on.

1 Like

When you create a new table, it’s more performant to include the properties known at that point in the program than to defer their initialization. For instance, this snippet:

local self = {
  Player = player,
  Distance = distance,
  Folder = partsFolder,
};

is slightly more performant than this snippet:

local self = {};
self.Parent = parent;
self.Distance = distance;
self.Folder = partsFolder;

As for developer ergonomics, I’d recommend the first snippet as well simply due to the lack of repeating self. before every assignment. Then—purely a subjective take—its much easier reviewing commits and other features found in any VCS in the first snippet than the second.

As for what @beecivil said, I disagree slightly; while it is a matter of preference, you should always be consistent across the project. My preference I typically advocate for is as needed: You should always prefer property-access syntax (value.key) over element-access syntax (value[index]) whenever possible.

2 Likes

I mean. I use

local proxyObject = newproxy(true)
local proxyMT = getmetatable(proxyObject)

proxyObject.__index = ...
proxyObject.__tostring = ...

return proxyObject

That returns an actual UserData value, But. Allowes you to assign meta methods, If thats what you mean?