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.
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.