forth-stuff/ForthStack.lua

52 lines
1.0 KiB
Lua

local _tl_compat; if (tonumber((_VERSION or ''):match('[%d.]*$')) or 0) < 5.3 then local p, m = pcall(require, 'compat53.module'); if p then _tl_compat = m end end; local table = _tl_compat and _tl_compat.table or table; local ForthStack = {}
Stack = {}
function Stack:push(val)
self.top = self.top + 1
table.insert(self.contents, val)
end
function Stack:pop()
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()
return setmetatable({ contents = {}, top = 0 }, stack_mt)
end
function ForthStack.add(stack)
local a = stack:pop()
local b = stack:pop()
if type(a) == "number" and type(b) == "number" then
local c = a + b
stack:push(c)
else
error("invalid operands for add operation!")
end
end
function ForthStack.dot(s)
print(s:pop())
end
local s = Stack:new()
s:push(1)
s:push(4)
ForthStack.add(s)
print(ForthStack.dot(s))
return ForthStack