Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to inherit the default methods when writing your own custom methods?

Hi. I am learning metatables and wanted to create like my own methods to work on parts.

I have created some methods that work flawlessly on it. My problem now is that when I try to general methods such as :Destroy(), it will not work.

I understand why this is happening. But I have no idea how I can fix it.

Any suggestions is appreciated.

Uhh Here is a basic example. When I call the method Destroy it will say its a nil value

local Container = {}
Container.__index = Container

function Container.new ()
	local newContainer = {}
	newContainer.part = Instance.new("Part")
	newContainer.part.Anchored = true
	newContainer.part.Parent = workspace
	
	setmetatable(newContainer, Container)
	return newContainer
end

function Container:PrintName ()
	print(self.part.Name)
end

local part = Container.new()
part:PrintName()
part:Destroy()

I tried doing setmetatable(Container, Instance) but that would not work.

Please help.

4 comments

1

But there might be so you should post it anyway

0

alright

0

Once sec. I keep getting 403 error :/

0

there updated.

1 answer

✓ Accepted answer

The issue is not that your methods are interfering with Roblox's. You are actually creating a table that has a part at index part (in Lua .part is the same as ["part"]). When you call the :Destroy() method on your variable "part" you are really calling the :Destroy() method on your newContainer table that you return from the Container.new function. You would need to call the :Destroy method on the actual part, which you have at index part in the newContainer table. Here is what your fixed code looks like, with a wait added in to show you that the part is created and then destroyed.

local Container = {}
Container.__index = Container

function Container.new ()
    local newContainer = {}
    newContainer.part = Instance.new("Part")
    newContainer.part.Anchored = true
    newContainer.part.Parent = workspace

    setmetatable(newContainer, Container)
    return newContainer
end

function Container:PrintName ()
    print(self.part.Name)
end

local part = Container.new()
part:PrintName()
wait(3)
part.part:Destroy()

You even do this with self.part.Name in the PrintName method, I just think you missed what the part variable really is (a table). I recommend that you name your variables something that helps you remember what is actually inside of them, and don't confuse you like this.

I hope this helps. Have a great day scripting!

2 comments

0

I have tested this in an empty baseplate and it worked. So, if it doesn't work for you, the issue is caused by something else in your game. If you have any additional questions, feel free to ask them below.

0

THIS.

This discussion is preserved as it was. New answers, comments, and votes are closed.