add signal module
This commit is contained in:
parent
d766e4e34b
commit
aff1bfd247
30
data/scripts/types/signal.lua
Normal file
30
data/scripts/types/signal.lua
Normal file
@ -0,0 +1,30 @@
|
||||
local util = require "util"
|
||||
|
||||
local Signal = {}
|
||||
|
||||
Signal.__index = Signal
|
||||
|
||||
function Signal:connect(f)
|
||||
util.list_insert_once(self._connections, f)
|
||||
end
|
||||
|
||||
function Signal:disconnect(f)
|
||||
util.list_remove_value(self._connections, f)
|
||||
end
|
||||
|
||||
function Signal:emit(...)
|
||||
-- don't care about order
|
||||
for _, v in pairs(self._connections) do
|
||||
v(...)
|
||||
end
|
||||
end
|
||||
|
||||
function Signal.new()
|
||||
local s = {
|
||||
_connections = {},
|
||||
}
|
||||
|
||||
return setmetatable(s, Signal)
|
||||
end
|
||||
|
||||
return Signal
|
@ -65,4 +65,36 @@ function util.merge(t1, t2, overwrite)
|
||||
return t3
|
||||
end
|
||||
|
||||
---Finds the index of value in list t. If the value does not exist in the list, returns -1.
|
||||
---@param t table
|
||||
---@param value any
|
||||
---@return integer
|
||||
function util.list_find(t, value)
|
||||
local idx = -1
|
||||
for i, v in ipairs(t) do
|
||||
if v == value then
|
||||
idx = i
|
||||
break
|
||||
end
|
||||
end
|
||||
return idx
|
||||
end
|
||||
|
||||
---Removes an element from a list, if it exists. Does nothing if the value doesn't exist.
|
||||
---@param t table
|
||||
---@param value any
|
||||
function util.list_remove_value(t, value)
|
||||
local idx = util.list_find(t, value)
|
||||
if idx ~= -1 then
|
||||
table.remove(t, idx)
|
||||
end
|
||||
end
|
||||
|
||||
---Inserts value into the list only if it does not exist.
|
||||
---@param t table
|
||||
---@param value any
|
||||
function util.list_insert_once(t, value)
|
||||
if util.list_find(t, value) ~= -1 then return end
|
||||
table.insert(t, value)
|
||||
end
|
||||
return util
|
Loading…
Reference in New Issue
Block a user