Cleaning up classes

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?

1 Like

Could you please go into more detail of how you are creating these classes?

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
1 Like

Ah I see, so this will then be garbage collected?

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

Hello, yup I get that but what I mean for example is:

If I make a blade

A = Class.new(blade)

and then the blade is destroyed

blade:Destroy()

I can still access the methods and whatnot of A even though blade is gone.

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.

Can you explain what you mean sorry?

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
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.