PageRenderTime 1ms CodeModel.GetById 99ms app.highlight 3ms RepoModel.GetById 47ms app.codeStats 0ms

/set.lua

http://github.com/JakobOvrum/LuaIRC
Lua | 56 lines | 44 code | 11 blank | 1 comment | 6 complexity | 1dcba32f71dfefd439b4a3c1d9a8fd4b MD5 | raw file
 1local select = require "socket".select
 2
 3local setmetatable = setmetatable
 4local insert = table.insert
 5local remove = table.remove
 6local ipairs = ipairs
 7local error = error
 8
 9module "irc.set"
10
11local set = {}
12set.__index = set
13
14function new(t)
15	t.connections = {}
16	t.sockets = {}
17	return setmetatable(t, set)
18end
19
20function set:add(connection)
21	local socket = connection.socket
22	insert(self.sockets, socket)
23	
24	self.connections[socket] = connection
25	insert(self.connections, connection)
26end
27
28function set:remove(connection)
29	local socket = connection.socket
30	self.connections[socket] = nil
31	for k, s in ipairs(self.sockets) do
32		if socket == s then
33			remove(self.sockets, k)
34			remove(self.connections, k)
35			break
36		end
37	end
38end
39
40function set:select()
41	local read, write, err = select(self.sockets, nil, self.timeout)
42	
43	if read then
44		for k, socket in ipairs(read) do
45			read[k] = self.connections[socket]
46		end
47	end
48	
49	return read, err
50end
51
52-- Select - but if it times out, it returns all connections.
53function set:poll()
54	local read, err = self:select()
55	return err == "timeout" and self.connections or read
56end