comp-tg/etc/events.lua

52 lines
977 B
Lua
Raw Normal View History

2021-07-19 07:55:01 +00:00
--[[ Events library
-- (c) Er2 2021 <er2@dismail.de>
-- Zlib License
--]]
local events = {}
events.__index = events
function events:_add(t, n, f)
table.insert(self._ev_, {
type = t,
name = n,
fn = f,
})
end
function events:on(n,f) self:_add('on', n,f) end
function events:once(n,f) self:_add('once', n,f) end
2022-01-18 19:48:06 +00:00
function events:off(f)
for k, v in pairs(self._ev_) do
if v.fn == f then
table.remove(self._ev_, k)
end
end
end
2021-07-19 07:55:01 +00:00
function events:_ev(t, i, name, ...)
local v = t[i]
if v.name == name then
v.fn(...)
if v.type == 'once' then table.remove(t, i) end
end
end
function events:emit(name, ...)
local t = self._ev_
for i = 1, #t do
local v = t[i] or {}
2021-07-20 06:56:14 +00:00
if type(v) == 'table'
and type(v.name) == 'string'
2021-07-19 07:55:01 +00:00
and type(v.type) == 'string'
2021-07-20 06:56:14 +00:00
and type(v.fn) == 'function'
2021-07-19 07:55:01 +00:00
then self:_ev(t, i, name, ...) end
end
end
2021-07-21 08:40:31 +00:00
return function(t)
t._ev_ = {}
return setmetatable(t, events)
end