--- Add a task to clean up
-- Maid[key] = (function)            Adds a task to perform
-- Maid[key] = (event connection)    Manages an event connection
-- Maid[key] = (Maid)                Maids can act as an event connection, allowing a Maid to have other maids to clean up.
-- Maid[key] = (Object)              Maids can cleanup objects with a `Destroy` method
-- Maid[key] = nil                   Removes a named task. If the task is an event, it is disconnected. If it is an object, it is destroyed.

function Maid:__newindex(Index, NewTask)
	if Maid[Index] ~= nil then
		error(("'%s' is reserved"):format(tostring(Index)), 2)
	end

	local Tasks = self.Tasks
	local OldTask = Tasks[Index]
	Tasks[Index] = NewTask

	if OldTask then
		if type(OldTask) == "function" then
			OldTask()
		elseif typeof(OldTask) == "RBXScriptConnection" then
			OldTask:disconnect()
		elseif OldTask.disconnect then
			OldTask:disconnect()
		elseif OldTask.Destroy then
			OldTask:Destroy()
		elseif OldTask.destroy then
			OldTask:destroy()
		end
	end
end
