Uh oh!
There was an error while loading. Please reload this page.
This repository was archived by the owner on Nov 20, 2020. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtuple.lua
More file actions
Latest commit
82 lines (71 loc) · 2.03 KB
/
Copy pathtuple.lua
File metadata and controls
82 lines (71 loc) · 2.03 KB
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
77
78
79
80
81
82
require'classlib'
class.Tuple()
functionTuple:__init(...) -- construct with initial elements
self.elem= {...}
self.n=#self.elem
end
functionTuple:__tostring() -- string representation
localfunctionascii(e)
returntype(e) =='string' andstring.format('%q', e) ortostring(e)
end
locals=''
fori, vinipairs(self.elem) do
s=#s==0andascii(v) ors..', ' ..ascii(v)
end
return'(' ..s..')'
end
localfunctioncheckrange(i, max)
assert(i>=1andi<=max,
'Index must be >= 1 and <= ' ..max)
end
localfunctioncheckindex(i, max)
assert(type(i) =='number', 'Index must be a number')
checkrange(i, max)
end
functionTuple:push(i, v) -- push an element anywhere
ifv==nilthen
v=i
i=self.n+1-- by default push at the end
end
ifv==nilthenreturnend-- pushing nil has no effect
checkindex(i, self.n+1) -- allow appending
table.insert(self.elem, i, v) -- insert it
self.n=self.n+1-- count it
end
functionTuple:pop(i) -- pop an element anywhere
ifi==nilthen
i=self.n-- by default pop at the end
ifi==0thenreturnnilend
end
locale=self[i]
self[i] =nil-- remove it
returne-- return it
end
functionTuple:clear() -- empty tuple
self.elem= {}
self.n=0
end
functionTuple:size() -- tuple size
returnself.n
end
functionTuple:__get(i) -- read an element
iftype(i) ~='number' thenreturnnilend
checkrange(i, self.n+1) -- allow reading one past the end
returnself.elem[i] -- read it
end
functionTuple:__set(i, v) -- assign an element
iftype(i) ~='number' thenreturnfalseend
checkrange(i, self.n+1) -- allow assigning one past the end
ifv==nilthen
ifi<=self.nthen-- if removing, count it
table.remove(self.elem, i)
self.n=self.n-1
end
returntrue
end
ifi==self.n+1then-- if appending, count it
self.n=i
end
self.elem[i] =v-- assign it
returntrue
end