Simple Garbage (Sub-Mutation of Maid module)

Simple garbage module. Made this a while back.
Use this for your game, or as a learning resource :+1:

local garbage = {}

local function cleanup(t, deep)
	for i, v in next, t do
		local foundType = typeof(v)
		if foundType == "function" then
			v()
			t[i] = nil
		elseif foundType == "Instance" then
			v:Destroy()
		elseif foundType == "RBXScriptConnection" then
			v:Disconnect()
		elseif foundType == "table" and deep then
			cleanup(v, deep)
		else
			t[i] = nil
		end
	end
end

function garbage.new()
	local VirtualBin = {}
	local Methods = {}
	
	function Methods:trash(deep)
		task.spawn(cleanup, VirtualBin, deep)
	end
	
	return setmetatable(Methods, {__index = VirtualBin, __newindex = VirtualBin})
end

return garbage


It’s an insanely simple module. Usage below

local Trash = Garbage.new()

Trash.SomeInstance = Instance.new("BoolValue")
--// The functions are called upon :trash()
Trash.thisIsRanOnTrash = function() end
Trash.onTrash = function() end
--// Only cleaned if :trash(true) is called.
Trash.Table = {Instance.new("Part"), Instance.new("Model")}

Trash:trash()
--// The optional parameter "deep" allows it to collect garbage inside of tables stored within the instance.

--// Calling this method by itself would leave `Trash.Table` instances.
Trash:trash(true)
--// Would deep clean the entire table.

The module might be a bit iffy, but it does have it’s usages. Just wanted to share this with everyone :+1:

:warning: I might’ve missed some tiny optimizations

2 Likes

Not too bad for such a short module, I’ll try it out and let you know if it works well!

2 Likes

You should use t[i] = nil, right? Setting that variable to nil does nothing because it’s forgotten at the next for loop iteration anyways, while it remains in the table.

1 Like

You would be correct. I must’ve forgotten to even test that. Allow me to change that real quick.
Thanks!

1 Like

I am curious to know if next, pairs, or ipairs passes the variable? or the pointer to the value in the table.

local List = {"Apple", "Banana", "Orange"}

for i, v in pairs(List) do
	v = nil
end

print(List) --> {"Apple", "Banana", "Orange"}

for i, v in ipairs(List) do
	v = nil
end

print(List) --> {"Apple", "Banana", "Orange"}

It passes a new variable which is set to the exact value in the table. Setting the new variable to nil does nothing!

1 Like

this is really good im going to use it for my future projects

Whats the use for this? Whats the point

Works like maid, you give it some data and it’ll clean it up for you. Instead this one gives you a table, allowing you to manipulate it to your will. E.g, an easier way to create a :Destroy function in your class/module.

No major advantages between Maid. Really just a situational and preference thing.