How can i create Garbage Collection Module?

Today i made topic and one guy explained me i should use GC module such as maid or janitor, but i want to make it myself and understand how they work, can anyone explain me and eventually give example of one? because i need to know how to clear instances with multiple references and ect.

thx for help.

Start by defining the module and a table to hold tasks, then create a method to add tasks to the module. Tasks can be any object or function that needs to be cleaned up, define a method to clean up all tasks. This method will loop through the tasks and do the cleanup.

1 Like

Why not just use Maid or Janitor as the examples? They’re both open source and you can use it as a reference to make your own.

I want to make it myself, also i want to know more… universal way and simplier one because those modules use it in their style

thx. idk if you can, but can you write me a example code for function like that? i better understand when i read the code, it can be simple, i want only basic understanding of it

Yes, i was writing an example for you

That’s the module that handles everything:

local GCModule = {}
GCModule.__index = GCModule

function GCModule.new()
    local self = setmetatable({}, GCModule)
    self.tasks = {}
    return self
end

function GCModule:Add(task)
    table.insert(self.tasks, task)
end

function GCModule:Cleanup()
    for _, task in ipairs(self.tasks) do
        if typeof(task) == "RBXScriptConnection" then
            task:Disconnect()
        elseif typeof(task) == "Instance" then
            task:Destroy()
        elseif type(task) == "function" then
            task()
        end
    end
    self.tasks = {}
end

return GCModule

you can use it like this:

local GCModule = require(path to GCModule)

local gc = GCModule.new()

local connection = game:GetService("RunService").Stepped:Connect(function()
    print("Running")
end)

gc:Add(connection)

local part = Instance.new("Part")
part.Parent = workspace

gc:Add(part)

gc:Cleanup()
1 Like