comp-tg/etc/events.lua

75 lines
1.4 KiB
Lua

-- Events library
-- (c) Er2 2022 <er2@dismail.de>
-- Zlib License
require 'class'
class 'Events' {
function(this)
this._ev_ = {}
end,
_add = function(this, type, name, func)
table.insert(this._ev_, {
type = tostring(type),
name = tostring(name),
func = func,
})
end,
on = function(this, name, func)
this:_add('on', name, func)
end,
once = function(this, name, func)
this:_add('once', name, func)
end,
off = function(this, func)
for k, v in pairs(this._ev_) do
if v.func == func
then table.remove(this._ev_, k)
end
end
end,
_ev = function(this, t, i, name, ...)
local v = t[i]
if v.name == name then
v.func(...)
if v.type == 'once'
then table.remove(t, i)
end
end
end,
emit = function(this, name, ...)
local t = this._ev_
for i = 1, #t do
local v = t[i]
if type(v) == 'table'
and type(v.name) == 'string'
and type(v.type) == 'string'
and type(v.func) == 'function'
then this:_ev(t, i, name, ...)
else print 'Invalid event'
if v then print(v, v.name, v.type, v.func)
else print 'nil' end
end
end
end,
}
class 'EventsThis' : inherits 'Events' {
_ev = function(this, t, i, name, ...)
local v = t[i]
if v.name == name then
v.func(this, ...)
if v.type == 'once'
then table.remove(t, i)
end
end
end,
}