-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStack.lua
More file actions
42 lines (34 loc) · 829 Bytes
/
Stack.lua
File metadata and controls
42 lines (34 loc) · 829 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
-- Stack.lua
-- a generic stack class. Piles of blocks are stacks.
-- Also used to keep track of the user program stack
Stack = class()
function Stack:init()
self.elems = {}
end
-- removes and return the top elem
function Stack:pop()
local elem = self:peek()
table.remove(self.elems,#self.elems)
return elem
end
-- adds a new elem at the top
function Stack:push(elem)
table.insert(self.elems,elem)
end
-- returns the last elem, but doesn't remove it
function Stack:peek(idx)
idx = idx or #self.elems
return self.elems[idx]
end
function Stack:size()
return #self.elems
end
-- returns an iterator over the elems of the stack
function Stack:iter()
local i = 0
local n = self:size()
return function()
i = i + 1
if i <= n then return self.elems[i] end
end
end