Little help with OOP

I dont understand this piece of code.In the first line, we are setting the metatable “BaseWeapon” to an empty table.I understood this. But the second line doesn’t make any sense to me…

Please help me understand

local self = setmetatable({}, BaseWeapon)
	self.connections = {}

I’m not too experienced with these, and I might be wrong, but I’m pretty sure the second line is just setting an empty table.

to the “setmetatable” function ?..I can’t understand what it is…
variable “self” is containing the “setmetatable” function
and by doing this:

self.connections = {}

how is this possible to set a new empty table to the “setmetatable” function …?

So I just tested this out in Studio, and it returns an empty table.

yep i tried it too…But I still can’t understand this…

So, I hope I’m not misguiding you here. But I’m pretty sure it’s just adding another table to a metatable.
Read more here:

The following post covers absolutely everything you need to know for a good start. Cheers to @JonData for this article! Good job!

You should start by taking a look at so called objective oriented programming. It involves creating so called class. We create a table, and assign properties, states, and behaviours to the given class. They are all sort of pack of information and methods we can use to manage certain object.

local Class = {}
Class.__index = Class

-- Create new class using these contructors:
function Class.new()
	local self = {}
	
	-- Properties
	self.name = "Sample"
	self.connections = {}
	
	-- States
	self.is_active = false
	
	return setmetatable(self, Class)
end

--[[
	Where is self used?
		When colon (:) is used, class is automatically
		assigned as an argument to the method (function).
]]

-- The following are so called public methods; both
-- do exactly the same thing.
function Class:activate()
	self.is_active = true
end

function Class.activate(self)
	self.is_active = true
end

return Class
2 Likes

thank you for helping me…! :smiley:

1 Like