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
82 lines (71 loc) · 2.03 KB
/
tuple.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()
function Tuple:__init(...) -- construct with initial elements
self.elem = {...}
self.n = #self.elem
end
function Tuple:__tostring() -- string representation
local function ascii(e)
return type(e) == 'string' and string.format('%q', e) or tostring(e)
end
local s = ''
for i, v in ipairs(self.elem) do
s = #s == 0 and ascii(v) or s .. ', ' .. ascii(v)
end
return '(' .. s .. ')'
end
local function checkrange(i, max)
assert(i >= 1 and i <= max,
'Index must be >= 1 and <= ' .. max)
end
local function checkindex(i, max)
assert(type(i) == 'number', 'Index must be a number')
checkrange(i, max)
end
function Tuple:push(i, v) -- push an element anywhere
if v == nil then
v = i
i = self.n + 1 -- by default push at the end
end
if v == nil then return end -- 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
function Tuple:pop(i) -- pop an element anywhere
if i == nil then
i = self.n -- by default pop at the end
if i == 0 then return nil end
end
local e = self[i]
self[i] = nil -- remove it
return e -- return it
end
function Tuple:clear() -- empty tuple
self.elem = {}
self.n = 0
end
function Tuple:size() -- tuple size
return self.n
end
function Tuple:__get(i) -- read an element
if type(i) ~= 'number' then return nil end
checkrange(i, self.n + 1) -- allow reading one past the end
return self.elem[i] -- read it
end
function Tuple:__set(i, v) -- assign an element
if type(i) ~= 'number' then return false end
checkrange(i, self.n + 1) -- allow assigning one past the end
if v == nil then
if i <= self.n then -- if removing, count it
table.remove(self.elem, i)
self.n = self.n - 1
end
return true
end
if i == self.n + 1 then -- if appending, count it
self.n = i
end
self.elem[i] = v -- assign it
return true
end