Created
January 17, 2014 05:36
-
-
Save qiuyuzhou/a88cf7e5c6474d2f0d1a to your computer and use it in GitHub Desktop.
signal/slot
This file contains hidden or 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
module('signals',package.seeall) | |
local oo = require "loop.base" | |
Signal = oo.class{ | |
name = '', | |
slots = {} | |
} | |
function Signal:__init(name) | |
local obj = oo.rawnew(self, { | |
name = name, | |
next_slot_id = 1, | |
slots={}, | |
} | |
) | |
return obj | |
end | |
function Signal:connect(fun) | |
assert( fun ~= nil, 'Signal:Connect - signal can not connect to nil' ) | |
local id = self.next_slot_id | |
self.next_slot_id = self.next_slot_id + 1 | |
self.slots[id] = fun | |
return id | |
end | |
function Signal:disconnect(id) | |
self.slots[id] = nil | |
end | |
local function error_hook( err ) | |
local msg = string.format("%s\n%s",err,debug.traceback()) | |
--logger:warn( msg ) | |
print(msg) | |
end | |
function Signal:trigger() | |
local f = function(...) | |
local arg={... } | |
print(string.format('signal: (%s) is triggered.',self.name)) | |
for _,fn in pairs(self.slots) do | |
xpcall( function() fn(unpack(arg)) end,error_hook) | |
end | |
end | |
return f | |
end | |
function Signal:dump() | |
for _,v in pairs(self.slots) do | |
print( prettytostring(debug.getinfo( v )) ) | |
end | |
end | |
signals = {} | |
function get(sigName) | |
if signals[sigName] == nil then | |
signals[sigName] = Signal(sigName) | |
end | |
return signals[sigName] | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment