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