forth-stuff/Stack.tl

29 lines
539 B
Plaintext
Raw Normal View History

2021-05-10 06:23:32 +00:00
2021-05-11 06:55:13 +00:00
local type Stack = record
2021-05-10 06:23:32 +00:00
contents: {any}
top: number
push: function(Stack, any)
pop: function(Stack)
new: function(Stack): Stack
end
function Stack:push(val: any)
self.top = self.top + 1
table.insert(self.contents,val)
end
function Stack:pop(): any
self.top = self.top -1
if self.top < 0 then
error("Stack underflow")
end
return table.remove(self.contents)
end
local stack_mt = {__index = Stack}
function Stack:new(): Stack
return setmetatable({contents = {}, top = 0} as Stack, stack_mt)
end
-- operations
2021-05-11 06:55:13 +00:00
return Stack