Last active
March 20, 2019 20:18
-
-
Save headjoe3/6367678f4560a2c3999996ee86039b4c to your computer and use it in GitHub Desktop.
Simple maid class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Makes destructors easy to create | |
local FastSpawnEvent = Instance.new("BindableEvent") | |
FastSpawnEvent.Event:Connect(function(callback, argsPointer) | |
callback(argsPointer()) | |
end) | |
local function createPointer(...) | |
local args = { ... } | |
return function() | |
return unpack(args) | |
end | |
end | |
local FastSpawn = function(func, ...) | |
assert(type(func) == "function", "Invalid arguments (function expected, got " .. typeof(func) .. ")") | |
FastSpawnEvent:Fire(func, createPointer(...)) | |
end | |
local Maid = {} | |
Maid.__index = Maid | |
function Maid:GiveTask(thing) | |
table.insert(self.tasks, thing) | |
return thing --- mmm syntactic sugar... That's basically what the maid is. | |
end | |
function Maid:DoCleaning() | |
local tasks = self.tasks | |
-- Disconnect all events first as we know this is safe | |
for index, task in pairs(tasks) do | |
if typeof(task) == "RBXScriptConnection" then | |
tasks[index] = nil | |
task:Disconnect() | |
end | |
end | |
-- Clear out tasks table completely, even if clean up tasks add more tasks to the maid | |
local index, task = next(tasks) | |
while task ~= nil do | |
tasks[index] = nil | |
if type(task) == "function" then | |
-- Callbacks | |
FastSpawn(task) | |
elseif typeof(task) == "RBXScriptConnection" then | |
-- Connections | |
task:Disconnect() | |
elseif typeof(task) == "string" then | |
-- Render step bindings | |
pcall(function() | |
game:GetService("RunService"):UnbindFromRenderStep(task) | |
end) | |
elseif task.Destroy then | |
-- Instances | |
task:Destroy() | |
else | |
warn("Unhandled maid task '" .. tostring(task) .. "' of type '" .. typeof(task) .. "'") | |
end | |
index, task = next(tasks) | |
end | |
end | |
function Maid.new() | |
local self = setmetatable({}, Maid) | |
self.tasks = {} | |
return self | |
end | |
return Maid |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment