Last active
September 9, 2019 20:31
-
-
Save drhayes/8a82429f5219b4fae8114f449fb73eeb to your computer and use it in GitHub Desktop.
`EventEmitter` in Lua (primarily) for my OOP-y, retained-mode, gamepad-friendly UI library.
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
local Object = require 'lib.classic' | |
local function push (t, ...) | |
local pushed = select('#', ...) | |
for i = 1, pushed do | |
t[t.n + i] = select(i, ...) | |
end | |
return t.n + pushed | |
end | |
local function clean (t, n) | |
for i = t.n, n do | |
t[i] = nil | |
end | |
end | |
local EventEmitter = Object:extend() | |
function EventEmitter:emit(eventName, ...) | |
if not self.subscribers then return end | |
local subscriptions = self.subscribers[eventName] | |
if not subscriptions or #subscriptions == 0 then return end | |
for i = 1, #subscriptions do | |
local sub = subscriptions[i] | |
local ok, message | |
if sub.args then | |
local n = push(sub.args, ...) | |
ok, message = pcall(sub.listener, unpack(sub.args, 1, n)) | |
clean(sub.args, n) | |
else | |
ok, message = pcall(sub.listener, ...) | |
end | |
if not ok then | |
log.error(message) | |
end | |
end | |
end | |
function EventEmitter:on(eventName, listener, ...) | |
if not self.subscribers then | |
self.subscribers = setmetatable({}, { __k = 'kv' }) | |
end | |
if not self.subscribers[eventName] then | |
self.subscribers[eventName] = {} | |
end | |
local newSub = { | |
listener = listener, | |
} | |
local n = select('#', ...) | |
if n > 0 then | |
newSub.args = { n = n, ... } | |
end | |
table.insert(self.subscribers[eventName], newSub) | |
end | |
return EventEmitter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated with very useful bugfix and garbage control from https://gist.github.com/pablomayobre/f90491235e7143bbe9e12aca52c23c13 using techniques from his own https://gist.github.com/pablomayobre/adc1ed058a9ae350df559e2b100949dc.