PageRenderTime 62ms CodeModel.GetById 31ms app.highlight 5ms RepoModel.GetById 24ms app.codeStats 0ms

/asyncoperations.lua

http://github.com/JakobOvrum/LuaIRC
Lua | 89 lines | 70 code | 17 blank | 2 comment | 11 complexity | 85d502aa33ba569a9ff21822d1e66ec1 MD5 | raw file
 1local table = table
 2local assert = assert
 3local error = error
 4local select = select
 5local pairs = pairs
 6
 7module "irc"
 8
 9local meta = _META
10
11function meta:send(msg, ...)
12	if select("#", ...) > 0 then
13		msg = msg:format(...)
14	end
15	self:invoke("OnSend", msg)
16
17	local bytes, err = self.socket:send(msg .. "\r\n")
18
19	if not bytes and err ~= "timeout" and err ~= "wantwrite" then
20		self:invoke("OnDisconnect", err, true)
21		self:shutdown()
22		error(err, errlevel)
23	end
24end
25
26local function verify(str, errLevel)
27	if str:find("^:") or str:find("%s%z") then
28		error(("malformed parameter '%s' to irc command"):format(str), errLevel)
29	end
30
31	return str
32end
33
34function meta:sendChat(target, msg)
35	-- Split the message into segments if it includes newlines.
36	for line in msg:gmatch("([^\r\n]+)") do
37		self:send("PRIVMSG %s :%s", verify(target, 3), line)
38	end
39end
40
41function meta:sendNotice(target, msg)
42	-- Split the message into segments if it includes newlines.
43	for line in msg:gmatch("([^\r\n]+)") do
44		self:send("NOTICE %s :%s", verify(target, 3), line)
45	end
46end
47
48function meta:join(channel, key)
49	if key then
50		self:send("JOIN %s :%s", verify(channel, 3), verify(key, 3))
51	else
52		self:send("JOIN %s", verify(channel, 3))
53	end
54end
55
56function meta:part(channel)
57	channel = verify(channel, 3)
58	self:send("PART %s", channel)
59	if self.track_users then
60		self.channels[channel] = nil
61	end
62end
63
64function meta:trackUsers(b)
65	self.track_users = b
66	if not b then
67		for k,v in pairs(self.channels) do
68			self.channels[k] = nil
69		end
70	end
71end
72
73function meta:setMode(t)
74	local target = t.target or self.nick
75	local mode = ""
76	local add, rem = t.add, t.remove
77
78	assert(add or rem, "table contains neither 'add' nor 'remove'")
79
80	if add then
81		mode = table.concat{"+", verify(add, 3)}
82	end
83
84	if rem then
85		mode = table.concat{mode, "-", verify(rem, 3)}
86	end
87
88	self:send("MODE %s %s", verify(target, 3), mode)
89end