Lots of random documentation fixes
[awesome.git] / lib / gears / object.lua.in
blob7b1c5171ae0ca273b93fcff3b114a37f1803486a
1 ---------------------------------------------------------------------------
2 -- @author Uli Schlachter
3 -- @copyright 2010 Uli Schlachter
4 -- @release @AWESOME_VERSION@
5 ---------------------------------------------------------------------------
7 local setmetatable = setmetatable
8 local pairs = pairs
9 local type = type
10 local error = error
12 -- gears.object
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")
19 end
20 end
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 -- @return The signal table
27 local function find_signal(obj, name, error_msg)
28 check(obj)
29 if not obj._signals[name] then
30 error("Trying to " .. error_msg .. " non-existent signal '" .. name .. "'")
31 end
32 return obj._signals[name]
33 end
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)
38 check(self)
39 if not self._signals[name] then
40 self._signals[name] = {}
41 end
42 end
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")
49 sig[func] = func
50 end
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")
57 sig[func] = nil
58 end
60 --- Emit a signal
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
68 func(self, ...)
69 end
70 end
72 -- Returns a new object. You can call :emit_signal(), :disconnect_signal,
73 -- :connect_signal() and :add_signal() on the resulting object.
74 local function new()
75 local ret = {}
77 -- Copy all our global functions to our new object
78 for k, v in pairs(object) do
79 if type(v) == "function" then
80 ret[k] = v
81 end
82 end
84 ret._signals = {}
86 return ret
87 end
89 function object.mt:__call(...)
90 return new(...)
91 end
93 return setmetatable(object, object.mt)
95 -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80