Created
February 17, 2019 02:24
-
-
Save j-walk/b38f551bdf29bc8fb81b0a34625e03d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function classify(str) | |
if tonumber(str) == nil then | |
return str | |
else | |
return tonumber(str) | |
end | |
end | |
local stack = function() | |
local t = {} | |
t.stack = {} | |
t.push = function(self, number) table.insert(self.stack, number, 1) end | |
t.pop = function(self) return table.remove(self.stack, 1) end | |
return t | |
end | |
function main() | |
local mode = 0 | |
local func = "" | |
local body = {} | |
local stack = {} | |
local plus = function() | |
table.insert(stack, table.remove(stack) + table.remove(stack)) | |
end | |
local dup = function() | |
local a = table.remove(stack) | |
table.insert(stack, a) | |
table.insert(stack, a) | |
end | |
local drop = function() table.remove(stack) end | |
local swap = function() | |
local a = table.remove(stack) | |
local b = table.remove(stack) | |
table.insert(stack, a) | |
table.insert(stack, b) | |
end | |
local env = { plus = plus, dup = dup, drop = drop, swap = swap} | |
while (mode >= 0) do | |
local currBuff = {} | |
for str in read():gmatch("[^%s]+") do | |
table.insert(currBuff, classify(str)) | |
end | |
while #currBuff > 0 do | |
local tok = table.remove(currBuff, 1) | |
if tok == "exit" then mode = -1; break; end | |
if mode == 0 then -- live execution | |
if type(tok) == "number" then | |
table.insert(stack, tok) | |
else | |
if tok == ":" then mode = 1 end -- entering compilation | |
if tok == ";" then mode = -1 break end | |
if tok == ".s" then | |
for k, v in pairs(stack) do | |
io.write(v, " ") | |
end | |
print("") | |
end | |
if tok == "." then | |
if #stack == 0 then return -1 else | |
print(table.remove(stack)) | |
end | |
end | |
if not (env[tok] == nil) then | |
local body = env[tok] | |
if type(body) == "table" then | |
for i = #body, 1, -1 do | |
table.insert(currBuff, 1, body[i]) | |
end | |
elseif type(body) == "function" then | |
body() | |
end | |
end | |
end | |
elseif mode == 1 then -- getting name | |
func = tok | |
mode = 2 | |
elseif mode == 2 then -- building | |
if tok == ";" then | |
env[func] = body | |
func = "" | |
body = {} | |
mode = 0 | |
else table.insert(body, tok) end | |
end | |
end | |
io.write(" ok\n") | |
end | |
return mode | |
end | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment