Question on Object Oriented Programming

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 am going off of this tutorial from 2014: All about Object Oriented Programming

Thank you for your help!

2 Likes

You misspelled the metamethod, It’s __index not _index.

4 Likes

Thank you! I fixed it but I still get the same error in the output.

1 Like

How does the new object work?

Is it a model/part in replicatedstorage or workspace?

1 Like

It is a part in the workspace. Nothing happens to the part when i run the game.

1 Like

I’m just taking a guess but, try

newPart:Enlarge()

2 Likes

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.

3 Likes

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()	
2 Likes

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):

2 Likes

Thank you so much! I will definitely tackle this :smiley:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.