-
Notifications
You must be signed in to change notification settings - Fork 1
/
list.lua
76 lines (62 loc) · 1.58 KB
/
list.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
local List = {}
List.__index = List
--- Creates a new List.
-- @return A new list
function List.new()
return setmetatable({
objects = {},
pointers = {},
size = 0,
}, List)
end
--- Clears the List completely.
-- @return self
function List:clear()
self.objects = {}
self.pointers = {}
self.size = 0
return self
end
--- Adds an object to the List.
-- @param obj The object to add
-- @return self
function List:add(obj)
local size = self.size + 1
self.objects[size] = obj
self.pointers[obj] = size
self.size = size
return self
end
--- Removes an object from the List.
-- @param obj The object to remove
-- @param index The known index
-- @return self
function List:remove(obj, index)
index = index or self.pointers[obj]
local size = self.size
if index == size then
self.objects[size] = nil
else
local other = self.objects[size]
self.objects[index] = other
self.pointers[other] = index
self.objects[size] = nil
end
self.pointers[obj] = nil
self.size = size - 1
end
--- Gets an object by numerical index.
-- @param index The index to look at
-- @return The object at the index
function List:get(index)
return self.objects[index]
end
--- Gets if the List has the object.
-- @param obj The object to search for
-- @param true if the list has the object, false otherwise
function List:has(obj)
return self.pointers[obj] and true
end
return setmetatable(List, {
__call = function() return List.new() end,
})