function Maid.__newindex(X,n,I)if Maid[n]~=nil then error(("\067\097\110\110\111\116 \117\115\101 \'\037\115\' \097\115 \097 \077\097\105\100 \107\101\121"):format(tostring(n)),2)end local r=X._tasks local t=r[n]if t==I then return end r[n]=I if t then if type(t)=="\102\117\110\099\116\105\111\110"then t()elseif type(t)=="\116\104\114\101\097\100"then local n if coroutine.running()~=t then n=pcall(function()task.cancel(t)end)end if not n then task.defer(function()task.cancel(t)end)end elseif typeof(t)=="\082\066\088\083\099\114\105\112\116\067\111\110\110\101\099\116\105\111\110"then t:Disconnect()elseif t.Destroy then t:Destroy()end end end
--- Add a task to clean up
-- @usage
-- Maid[key] = (function)         Adds a task to perform
-- Maid[key] = (event connection) Manages an event connection
-- Maid[key] = (thread)           Manages a thread
-- 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(("Cannot use '%s' as a Maid key"):format(tostring(index)), 2)
	end

	local tasks = self._tasks
	local oldTask = tasks[index]

	if oldTask == newTask then
		return
	end

	tasks[index] = newTask

	if oldTask then
		if type(oldTask) == "function" then
			oldTask()
		elseif type(oldTask) == "thread" then
			local cancelled
			if coroutine.running() ~= oldTask then
				cancelled = pcall(function()
					task.cancel(oldTask)
				end)
			end

			if not cancelled then
				task.defer(function()
					task.cancel(oldTask)
				end)
			end
		elseif typeof(oldTask) == "RBXScriptConnection" then
			oldTask:Disconnect()
		elseif oldTask.Destroy then
			oldTask:Destroy()
		end
	end
end
