-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.lua
More file actions
125 lines (105 loc) · 2.14 KB
/
stack.lua
File metadata and controls
125 lines (105 loc) · 2.14 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
--[[
Stack class.
Data structure that follows the LIFO policy.
Uses an indexed table for items.
]]
local Stack = {}
Stack.__index = Stack
-- new method
function Stack:new()
return Stack:init()
end
-- init method
function Stack:init()
local obj = {}
setmetatable(obj, Stack)
-- allows no params
obj._data = {}
return obj
end
--[[
tostring(x) method
Returns all stack's items as strings.
]]
function Stack:__tostring()
-- empty stack
if self:is_empty() then return "[]" end
local items = {}
for i = 1, #self._data do
items[#items+1] = tostring(self._data[i])
end
return "[" .. table.concat(items, ", ") .. "]"
end
--[[
#x method
Returns stack's number of items.
]]
function Stack:__len()
return #self._data
end
--[[
x:size() method
Returns stack's number of items.
]]
function Stack:size()
return #self
end
--[[
x:is_empty() method
Returns a boolean if the stack is empty.
]]
function Stack:is_empty()
return #self == 0
end
--[[
x:top() method
Returns stack's top item without removing it.
Raises error if the stack is empty.
]]
function Stack:top()
if self:is_empty() then
error("top() on empty stack", 2)
end
return self._data[#self._data]
end
--[[
x:peek() method
Returns stack's top item without removing it.
Raises error if the stack is empty.
]]
function Stack:peek()
return self:top()
end
--[[
x:pop() method
Removes the last item pushed onto the stack.
Raises error if the stack is empty.
]]
function Stack:pop()
if self:is_empty() then
error("pop() on empty stack", 2)
end
local latest_element = self._data[#self._data]
self._data[#self._data] = nil
return latest_element
end
--[[
x:push(element) method
Pushes an item onto the stack.
Recieves parameter "element" with the item to push.
Raises error if no "element" is given.
]]
function Stack:push(element)
if not element then
error("push() parameter missing or nil", 2)
end
self._data[#self._data+1] = element
end
--[[
x:clear() method
Clears all items on the stack.
]]
function Stack:clear()
self._data = {}
end
return Stack