In my game I have a sword. The sword can have 1, 2 or more blades the player can swap out as they go. Each time there is a blade added I create an instance of a class for it (to toggle effects for the blade). But when the blade is deleted, I don’t think the module script attached is cleaned up (memory leak).
How do I go about disconnecting/getting rid of the module scripts associated to the object?
Class = {}
Class.__index == Class
function Class.new(blade)
local self = setmetatable({}, Class)
self.blade = blade
return self
end
function Class:method()
end
Like this, so my question is, even after blade is destroyed, won’t the methods be sticking around?
function Class:Destroy()
setmetatable(self, nil)
for index, value in self do
if typeof(value) == "RBXScriptConnection" then
value:Disconnect()
continue
end
value = nil
end
end
Tables are pure Lua objects, so the Garbage Collector will always take care of them. The methods and metatables attached are also static, so you don’t need to worry about them.
Roblox Instances, however, will not be GC’d when they are strongly referenced, so you should create a deconstructor class that unreferenced it. Connections to Instances should also be disconnected, but you can simply do
-- In Constructing
self.OnTouched = self.Blade.Touched:Connect(...)
-- Later in Destroy Method
self.OnTouched:Disconnect()
self.Blade = nil
Correct, because you’d still have a reference to it. Instead of relying on Roblox methods for destroying it, you should wrap a Destroy method in the Class that also destroys blade.
Basically, have a function in Class that you call to destroy and unreference blade with instead of the normal Instance/Destroy method.
function Class.new(Blade: Instance)
return setmetatable({
Blade = Blade
}, Class)
end
function Class:Destroy()
self.Blade:Destroy() -- Blade's Connections are Disconnected
self.Blade = nil -- Blade can now GC
end