1 ---------------------------------------------------------------------------
2 -- @author Uli Schlachter
3 -- @copyright 2010 Uli Schlachter
4 -- @release @AWESOME_VERSION@
5 ---------------------------------------------------------------------------
7 local setmetatable
= setmetatable
13 local object
= { mt
= {} }
15 -- Verify that obj is indeed a valid object as returned by new()
16 local function check(obj
)
17 if type(obj
) ~= "table" or type(obj
._signals
) ~= "table" then
18 error("add_signal() called on non-object")
22 --- Find a given signal
23 -- @param obj The object to search in
24 -- @param name The signal to find
25 -- @param error_msg Error message for if the signal is not found
26 -- @returns The signal table
27 local function find_signal(obj
, name
, error_msg
)
29 if not obj
._signals
[name
] then
30 error("Trying to " .. error_msg
.. " non-existent signal '" .. name
.. "'")
32 return obj
._signals
[name
]
35 --- Add a signal to an object. All signals must be added before they can be used.
36 -- @param name The name of the new signal.
37 function object
:add_signal(name
)
39 if not self
._signals
[name
] then
40 self
._signals
[name
] = {}
44 --- Connect to a signal
45 -- @param name The name of the signal
46 -- @param func The callback to call when the signal is emitted
47 function object
:connect_signal(name
, func
)
48 local sig
= find_signal(self
, name
, "connect to")
52 --- Disonnect to a signal
53 -- @param name The name of the signal
54 -- @param func The callback that should be disconnected
55 function object
:disconnect_signal(name
, func
)
56 local sig
= find_signal(self
, name
, "disconnect from")
61 -- @param name The name of the signal
62 -- @param ... Extra arguments for the callback functions. Each connected
63 -- function receives the object as first argument and then any extra
64 -- arguments that are given to emit_signal()
65 function object
:emit_signal(name
, ...)
66 local sig
= find_signal(self
, name
, "emit")
67 for func
in pairs(sig
) do
72 -- Returns a new object. You can call :emit_signal(), :disconnect_signal,
73 -- :connect_signal() and :add_signal() on the resulting object.
77 -- Copy all our global functions to our new object
78 for k
, v
in pairs(object
) do
79 if type(v
) == "function" then
89 function object
.mt
:__call(...)
93 return setmetatable(object
, object
.mt
)
95 -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80