-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.lua
More file actions
45 lines (40 loc) · 886 Bytes
/
stack.lua
File metadata and controls
45 lines (40 loc) · 886 Bytes
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
Stack = {}
function Stack:new()
-- create a new stack
local stack = {}
setmetatable(stack, self)
self.__index = self
stack.stack = {}
return stack
end
function Stack:init(list)
if not list then
-- create an empty stack
self.stack = {}
else
-- initialise the stack
self.stack = list
end
return self
end
function Stack:push(item)
-- put an item on the stack
self.stack[#self.stack+1] = item
end
function Stack:pop()
-- make sure there's something to pop off the stack
if #self.stack > 0 then
-- remove item (pop) from stack and return item
return table.remove(self.stack, #self.stack)
end
end
function Stack:size()
return #self.stack
end
function Stack:iterator()
-- wrap the pop method in a function
return function()
-- call pop to iterate through all items on a stack
return self:pop()
end
end