Advertisement
Guest User

NOT COMPLETE! Forth in OC Lua

a guest
Apr 4th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.94 KB | None | 0 0
  1. local computer = require("computer")
  2. local term = require("term")
  3. local text = require("text")
  4. local interpret
  5.  
  6. -- Current Word List and additional information
  7. local WORDS = {WORDS = {isLua = true}, ["."] = {isLua = true},
  8.                ["+"] = {isLua = true}}
  9.  
  10. local STACK = {n = 0} -- Stack, n is number of items in the stack
  11. local VER = "0a" -- Version
  12. local HOE = true -- H.O.E. Halt on error
  13.  
  14. WORDS.WORDS[1] = function()
  15.   for i, word in pairs(WORDS) do
  16.     io.write(i.." ")
  17.   end
  18.   io.write("\n")
  19.   return 0
  20. end
  21.  
  22. WORDS["."][1] = function()
  23.   if not pcall(function()
  24.     io.write(STACK[STACK.n].."\n")
  25.     STACK.n = STACK.n - 1
  26.     return 0 -- No error
  27.   end) then
  28.     io.write("ERROR: Stack Empty\n")
  29.     return 1 -- An error happened
  30.   end
  31. end
  32.  
  33. WORDS["+"][1] = function()
  34.   if not pcall(function()
  35.     STACK[STACK.n-1] = STACK[STACK.n] + STACK[STACK.n-1]
  36.     STACK.n = STACK.n-1
  37.   end) then
  38.     io.write("ERROR: Not enough items in stack\n")
  39.     return 1
  40.   end
  41. end
  42.  
  43. -- Actual Running
  44.  
  45. term.clear()
  46. io.write("Zef's FORTH "..VER.."\n")
  47. io.write(computer.freeMemory().." bytes free\n\n")
  48. io.write("> ")
  49. local input = io.read()
  50.  
  51. local function interpret(input)
  52.   local splitInput = text.tokenize(input)
  53.  
  54.   for wordIndex, wordText in pairs(splitInput) do
  55.     if tonumber(wordText) then
  56.       -- Current "word" is just a number
  57.       STACK[STACK.n+1] = tonumber(wordText)
  58.       STACK.n = STACK.n + 1
  59.     else
  60.       if WORDS[wordText] then
  61.         -- The Word Exists
  62.         if WORDS[wordText].isLua then
  63.           -- Function is implemented in lua
  64.           if WORDS[wordText][1]() == 1 and HOE then
  65.             io.write("\nExecuting Stopped, View Error Above\n")
  66.             break
  67.           end
  68.  
  69.         else
  70.           -- Function is implemented in Forth
  71.           interpret(WORDS[wordText][1])
  72.         end
  73.       else
  74.         -- The Word Does Not Exist
  75.  
  76.       end
  77.  
  78.     end
  79.   end
  80. end
  81.  
  82. interpret(input)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement