Utilities

Patterns

EventEmitter, Maid, StateMachine and Promise.

EventEmitter

Named events without creating a Signal for each.

EventEmitter.new()

Creates an emitter.

e:on(name, fn)

Calls fn whenever the event name is emitted. Returns a function that removes the listener when called.

e:once(name, fn)

Like on, but only for the first emit.

e:emit(name, ...)

Calls every listener of name with ..., each in its own coroutine.

e:off(name)

Removes all listeners of name.

local events = EventEmitter.new()
local off = events:on("hit", function(dmg) print("took", dmg) end)
events:emit("hit", 4)
off()

Maid

Collects things that need cleaning up, and cleans them all at once.

Maid.new()

Creates a maid.

m:give(item)

Adds an item and returns it. An item can be a function (called on cleanup) or a table with Disconnect, Remove or Destroy (that method is called).

m:cleanup()

Cleans up everything, last added first. Errors are ignored.

local maid = Maid.new()
maid:give(RunService.Heartbeat:Connect(function() end))
maid:give(Drawing.new("Square"))
-- later
maid:cleanup()

StateMachine

StateMachine.new(initialState)

Creates a machine that starts in initialState. It does not call enter for the initial state.

s:add(name, definition)

Registers a state. definition can have these functions, all optional:

FunctionCalled
enter(machine, previousState, ...)When the state becomes active
leave(machine, nextState)When the state is left
update(machine, ...)Every s:update(...) while active

Returns the machine, so calls can be chained.

s:set(name, ...)

Switches state, calling leave on the old one and enter on the new one.

s:update(...)

Calls the current state's update.

s:state()

Returns the name of the current state.

Promise

Values that arrive later. The function you give to Promise.new runs right away in its own coroutine.

Promise.new(executor)

executor(resolve, reject) is called. Call resolve(value) for success or reject(error) for failure. A Lua error counts as a rejection.

p:andThen(onResolved, onRejected)

Returns a new promise. Either function can be nil.

p:catch(onRejected)

Same as p:andThen(nil, onRejected).

p:await()

Pauses the current coroutine until the promise is settled. Returns true, value on success or false, error on failure.

Promise.all(list)

Resolves with an array of values once every promise in list has resolved. Rejects as soon as one rejects.

Promise.delay(seconds)

A promise that resolves after the delay.

Promise.resolve(value)

A promise that is already resolved.

local p = Promise.new(function(resolve)
  task.wait(1)
  resolve(42)
end)

local ok, value = p:await()
print(ok, value) -- true   42