I took a shot at metatables today, and I’m completely stumped. I thought that they would greatly streamline my game in terms of combat abilities that I’m working on. Everything is working fine, except for the function Charge:Destroy().
local Charge = {}
Charge.__index = Charge
function Charge.new(data)
local chargeinstance = {}
setmetatable(chargeinstance,Charge)
chargeinstance.Prefab = data["ChargeEffect"]
chargeinstance.Ancestors = data["ChargeParent"]
chargeinstance.Offset = data["ChargePosition"]
return chargeinstance
end
function Charge:Destroy()
self:Destroy()
end
When I call Charge:Destroy(), I get this error. What am I doing wrong? Or am I approaching metatables the wrong way?
function Charge.Destroy(self)
self.Destroy(self)
end
and Charge:Destroy() is akin to Charge.Destroy(Charge).
You get a stack overflow because Charge’s Destroy is calling the method itself.
See in the function above when self = Charge, the Destroy method of Charge is being called again.
The reason why you are getting this error is because you are attempting to call the :Destroy method within it’s self. This wont work because each time you call :Destroy it will call it’s self again.
Instead you should put in the :Destroy method what you actually want to destroy. With that you are doing it looks like you are trying to destroy self which isn’t possible because it is a table. Instead you should state what you want to destroy within self. Here is a quick example:
local module = {}
module.__index = module
function module.new()
local self = setmetatable({}, module)
self.Name = "This is a name"
self.Level = 10
return self
end
function module:Destroy()
self.Name = nil -- Makes name nil
self.Level = nil -- Makes level nil
end
return module