containertables.inc.lua

1
--[[ I created this class for an easy way of managing the objects inside a container in the MOO. ]]
2
 
3
containertable = { };
4
 
5
function containertable:add(object)
6
	local subt = self[(object and object._properties.name) or ""];
7
	if not subt then subt = { };
8
		self[(object and object._properties.name) or ""] = subt; 
9
		-- Also, all object's aliases need to point to subt
10
		if object._tags then
11
			for i, tag in ipairs(object._tags) do
12
				self[tag] = subt;
13
			end
14
		end
15
	end
16
	table.insert(subt, object);
17
	return object;
18
end
19
 
20
function containertable:remove(object)
21
	local subt = self[(object._properties and object._properties.name) or ""];
22
	if not subt then return false; end
23
	for n, stored_object in pairs(subt) do
24
		if object == stored_object then table.remove(subt, n); return object; end
25
	end
26
	return false;
27
end
28
 
29
function containertable:addalias(name, tag)
30
	self[tag] = self[name];
31
end
32
 
33
function containertable:findobject(name)
34
	local subt = self[name or ""];
35
	if not subt then subt = self[""]; if not subt then return; end end
36
	return subt[1];
37
end
38
 
39
function containertable:getallobjects()
40
	all = {};
41
	for tag, list in pairs(self) do
42
		for n, object in ipairs(list) do
43
			all[object] = true;
44
		end
45
	end
46
	return all; -- We return a table, where the objects are the keys, and the values are true
47
end
48
 
49
function createcontainertable(t)
50
	return setmetatable(t or {}, { __index = containertable });
51
end