Skip to content

Instantly share code, notes, and snippets.

@Reselim
Created July 19, 2020 18:24
Show Gist options
  • Save Reselim/e4020eb84120ee16a93e0b644127c598 to your computer and use it in GitHub Desktop.
Save Reselim/e4020eb84120ee16a93e0b644127c598 to your computer and use it in GitHub Desktop.
local Event = {}
Event.__index = Event
function Event.new()
return setmetatable({
_listeners = {},
_threads = {},
-- TODO: Remove when Roblox fixes coroutine.yield in pcall
_compatibilityEvent = Instance.new("BindableEvent")
}, Event)
end
function Event:Fire(...)
self._currentArgs = { ... }
self._compatibilityEvent:Fire()
self._currentArgs = nil
for _, handler in pairs(self._listeners) do
handler(...)
end
for _, thread in pairs(self._threads) do
coroutine.resume(thread, ...)
end
self._threads = {}
end
function Event:Connect(handler)
table.insert(self._listeners, handler)
return {
Connected = true,
Disconnect = function(connection)
if connection.Connected then
connection.Connected = false
for index, listener in pairs(self._listeners) do
if listener == handler then
return table.remove(self._listeners, index)
end
end
end
end
}
end
function Event:Wait()
table.insert(self._threads, coroutine.running())
return coroutine.yield()
end
function Event:WaitCompatibility()
self._compatibilityEvent.Event:Wait()
return unpack(self._currentArgs)
end
return Event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment