So Im trying to pratice Object Oriented Programming and I tried to making my own class and it was working fine but I want it to work without me having to make a metatable everytime I want to make a new object , this is the error in the output

Server Script
local Cars = require(game.ReplicatedStorage.Pratice)
local Honda = Cars({Name = "Honda"})
print(Honda:GetName())
Module Script
function Class(tbl)
setmetatable(tbl, {
__call = function(cls, ...)
local self = {}
setmetatable(self, {
__index = cls
})
self:constructor(...)
end
})
return tbl
end
local Cars = Class({
constructor = function(self, Name)
self:GetName(Name)
end;
Dealer = "Default";
GetName = function(self)
return self.Name
end;
GetDealer = function(self)
return self.Dealer
end;
})
return Cars
You never defined “Name” anywhere in the original table, and also you’re trying to treat a table Cars
as a function. I’ve fixed up both things and it is functioning as it should.
function Class(tbl)
setmetatable(tbl, {
__call = function(cls, ...)
local self = {}
setmetatable(self, {
__index = cls
})
self:constructor(...)
end
})
return tbl
end
local Cars = function(tbl)
local tbl2 = Class({
constructor = function(self, Name)
self:GetName(Name)
end;
Dealer = "Default";
Name = tbl.Name;
GetName = function(self)
return self.Name
end;
GetDealer = function(self)
return self.Dealer
end;
})
return tbl2
end
return Cars
1 Like
Alright it worked and thanks but, could you further explain what you did for it to work please?
Well, as I already had mentioned you were originally trying to identify the “Cars” variable as a function when in reality you had defined it was a table.
local Cars = Class({
You were returning Cars through the module script, however you were also identifying Cars as a table (through the Class function). To fix this I turned Cars into a function that ran the Class function inside of it, rather than having it defined as the Table that Class()
returns.
local Cars = function(tbl)
local tbl2 = Class({
-- skip lines
return tbl2
Another thing was, even though you sent Name as a parameter in the tbl attached to “Cars” (Cars({Name = "Honda"}))
, you never defined it in your table inside of the ModuleScript.
Name = tbl.Name;
GetName = function(self)
return self.Name
end;
All I did was define “Name” in the table as the Name passed through the Cars function.
Oh alright that makes a whole lot more sense thank you for explaining it
Wait do I even need this function/method?
Because I just deleted it and it’s still working fine.
constructor = function(self, Name)
self:GetName(Name)
end;
No, you don’t need that function at all. I left it in because you had referenced it in the metatable for the car, so I imagined you had left out parts of the script that utilized it.