forth-stuff/CoreWords.tl

68 lines
1.9 KiB
Plaintext
Raw Normal View History

2021-05-12 08:32:25 +00:00
local ds = require("DataStructures")
local Dictionary, Stack, WordInfo, State = ds.Dictionary, ds.Stack, ds.WordInfo, ds.State
local helpers = require("CoreHelpers")
local areNumbers, getActiveDataStack, isNumber, isWhitespace= helpers.areNumbers, helpers.getActiveDataStack, helpers.isNumber, helpers.isWhitespace
local skipWhitespace, parseToken = helpers.skipWhitespace, helpers.parseToken
local popTwoOperands = helpers.popTwoOperands
2021-05-11 08:19:54 +00:00
-- Mathematical operations
local function add(state: State)
2021-05-11 08:19:54 +00:00
local a, b = popTwoOperands(state)
if areNumbers(a,b) then
2021-05-11 08:19:54 +00:00
local c = (a as number) + (b as number)
getActiveDataStack(state):push(c)
2021-05-11 06:58:09 +00:00
else
error("invalid operands for add operation!")
end
end
local function sub(state: State)
2021-05-11 08:19:54 +00:00
local a, b = popTwoOperands(state)
if areNumbers(a, b) then
2021-05-11 08:19:54 +00:00
local c = (a as number) - (b as number)
getActiveDataStack(state):push(c)
else
error("invalid operands for sub operation!")
end
2021-05-11 06:58:09 +00:00
end
local function mul(state: State)
2021-05-11 08:19:54 +00:00
local a, b = popTwoOperands(state)
if areNumbers(a, b) then
2021-05-11 08:19:54 +00:00
local c = (a as number) * (b as number)
getActiveDataStack(state):push(c)
else
error("invalid operands for mul operation!")
end
end
local function div(state: State)
2021-05-11 08:19:54 +00:00
local a, b = popTwoOperands(state)
if areNumbers(a, b) then
2021-05-11 08:19:54 +00:00
local c = (a as number) / (b as number)
getActiveDataStack(state):push(c)
else
error("invalid operands for div operation!")
end
end
-- I/O operations
local function dot(state: State)
2021-05-11 08:19:54 +00:00
local out = state.activeDataStack:pop()
print(out)
end
local CoreWords = Dictionary:new()
local addInfo = WordInfo:new(add, false)
local subInfo = WordInfo:new(sub, false)
local mulInfo = WordInfo:new(mul, false)
local divInfo = WordInfo:new(div, false)
local dotInfo = WordInfo:new(dot, false)
CoreWords:define("+", addInfo)
CoreWords:define("-", subInfo)
CoreWords:define("*", mulInfo)
CoreWords:define("/", divInfo)
CoreWords:define(".", dotInfo)
2021-05-11 08:19:54 +00:00
return CoreWords
2021-05-11 06:55:13 +00:00