Skip to content

Commit

Permalink
Added signal.lua
Browse files Browse the repository at this point in the history
  • Loading branch information
Björn Ritzl committed Sep 19, 2017
1 parent 219f7eb commit f8b5cbf
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions ludobits/m/signal.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
local M = {}

function M.create(signal_id)
assert(signal_id, "You must provide a signal_id")
local signal = {}

local listeners = {}

function signal.add(cb)
assert(cb, "You must provide a callback")
if type(cb) == "function" then
listeners[cb] = { fn = cb }
else
local key = hash_to_hex(cb.socket or hash("")) .. hash_to_hex(cb.path or hash("")) .. hash_to_hex(cb.fragment or hash(""))
listeners[key] = { fn = function(message) msg.post(cb, signal_id, message) end }
end
end

function signal.remove(cb)
assert(cb, "You must provide a callback")
if type(cb) == "function" then
listeners[cb] = nil
else
local key = hash_to_hex(cb.socket or hash("")) .. hash_to_hex(cb.path or hash("")) .. hash_to_hex(cb.fragment or hash(""))
listeners[key] = nil
end
end

function signal.trigger(message)
assert(message, "You must provide a message")
for k,v in pairs(listeners) do
v.fn(message)
end
end

return signal
end

return M

0 comments on commit f8b5cbf

Please sign in to comment.