Maid
Manages the cleaning of events and other things. Useful for encapsulating state and make deconstructors easy.
See the Five Powerful Code Patterns talk for a more in-depth look at Maids in top games.
local maid = Maid.new()
maid:GiveTask(function()
print("Cleaning up")
end)
maid:GiveTask(workspace.ChildAdded:Connect(print))
-- Disconnects all events, and executes all functions
maid:DoCleaning()
Functions
new
Constructs a new Maid object
local maid = Maid.new()
isMaid
Maid.
isMaid
(
value:
any
) →
boolean
Returns true if the class is a maid, and false otherwise.
print(Maid.isMaid(Maid.new())) --> true
print(Maid.isMaid(nil)) --> false
Destroy
Maid.
Destroy
(
) →
(
)
Alias for Maid.DoCleaning()
__index
Returns Maid[key] if not part of Maid metatable
local maid = Maid.new()
maid._current = Instance.new("Part")
print(maid._current) --> Part
maid._current = nil
print(maid._current) --> nil
__newindex
Add a task to clean up. Tasks given to a maid will be cleaned when maid[index] is set to a different value.
Task cleanup is such that if the task is an event, it is disconnected. If it is an object, it is destroyed.
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.
Add
Gives a task to the maid for cleanup and returns the resulting value
GiveTask
Gives a task to the maid for cleanup, but uses an incremented number as a key.
GivePromise
Gives a promise to the maid for clean.
DoCleaning
Maid:
DoCleaning
(
) →
(
)
Cleans up all tasks and removes them as entries from the Maid.
note
Signals that are already connected are always disconnected first. After that any signals added during a cleaning phase will be disconnected at random times.
tip
DoCleaning() may be recursively invoked. This allows the you to ensure that tasks or other tasks. Each task will be executed once.
However, adding tasks while cleaning is not generally a good idea, as if you add a function that adds itself, this will loop indefinitely.