Roblox OOP referencing classes

I’ve recently gotten into Object-Oriented Programming (OOP) with Roblox and I was wondering if there was a way to reference the base metastable. For example:

-- ModuleScript

local Gun = {}
Gun.__index = Gun

function Gun.new(tool, owner)
    local newGun = {}
    setmetatable (newGun, Gun)
    newGun.Tool = tool
    newGun.Owner = owner
end

Gun:GetMetatable()
    print(-- Reference to the metatable here)
end

return Gun

-- Is there anyway to do that? ^

Lua has getmetatable(table) function, which returns the metatable of the provided table. You can simply write this:

function Gun:GetMetatable()
    print(getmetatable(self))
end

However, if the metatable has __metatable value in it, then the getmetatable function will return that value instead of an actual metatable. This is used for security to prevent overriding the functions. For example, using getmetatable on any instance (which are actually just userdata values with metatables) will return a string "The metatable is locked".

3 Likes

So then, I can’t do something along the lines of

-- Module Script

local Fire = RPS:WaitForChild('Fire')


Gun.__index = Gun 

Fire.OnServerEvent:Connect(function(plr, tool)
	local gun = getmetatable(tool)
	gun:Shoot()
end)

function Gun.new(tool, owner)
	local NewGun = {}
	setmetatable(NewGun, Gun)

	NewGun.Tool = SS:WaitForChild(tool):Clone()
	NewGun.Owner = PS:FindFirstChild(owner)
	NewGun.Tool.Parent = NewGun.Owner.Backpack
	
	return NewGun
end

function Gun:Shoot()
	print 'FIRE'
end

Because the tool is an instance, not a table?

If not, can one still reference the ‘parented’ table another way?
For example, how would one reference this:

local part = workspace.Part
local Table = {'One', false, part}

print(part. -- Reference its table here)

Is this possible?

You cannot transfer metatables between client and server.
You don’t need to get the metatable to call the functions, just call them from the table itself.
And you can’t store a table reference in the instance.

Thanks! Really helps me understand, and move on from Procedural Programming to OOP!