So I am attempting to learn object oriented programming and I am so lost because my simple code returns errors in the output.
Part = {}
Part._index = Part
function Part.ClonePart(position, model)
local newPart = {}
setmetatable(newPart, Part)
newPart.Position = position
newPart.Model = model
return newPart
end
function Part:Enlarge()
self.Size = self.Size + Vector3.new(10,10,10)
end
newPart = Part.ClonePart(Vector3.new(10,10,10), workspace.Part)
------Trying to make the part bigger----
Part:Enlarge()
In the output, I get the error saying “attempt to perform arithmetic on nil value and vector 3”
Can anyone help? I am trying to make the part’s size bigger through object oriented programming.
I believe you should be using newPart:Enlarge() instead of Part:Enlarge() as you are calling the module when you do that with no parameters, which returns nil.
Youre calling the classes “Enlarge” method which has no size property resulting in the error. Youre basically trying to add onto a nil value. Instead call the objects "Enlarge method which has the basepart:
local Part = {}
Part.__index = Part
function Part.ClonePart(position, model)
local newPart = {}
setmetatable(newPart, Part)
newPart.Position = position
newPart.Model = model
return newPart
end
function Part:Enlarge()
self.Model.Size = self.Model.Size + Vector3.new(10,10,10)
end
newPart = Part.ClonePart(Vector3.new(10,10,10), workspace.Part)
------Trying to make the part bigger----
newPart:Enlarge()
May I suggest this other guide on utilizing Luau type annotations for OOP. It’s more on the advanced side, so you might want to bookmark it and come back to it later.
If you didn’t know, type annotations are essentially comments in your code that the IDE can read and make predictions based off it. It can help you catch mistakes by analyzing the datatypes and increase your productivity by providing you with more accurate autocomplete suggestions. Give it a try!
And this is an example of what coding OOP with typing could look like (my own take that is pretty different from the guide):