Advertisement
Guest User

Game Script RPN calculator example

a guest
Jul 17th, 2023
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. // https://ratfactor.com/forth/the_programming_language_that_writes_itself.html
  2. // https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
  3.  
  4. var stack = []
  5. var depth = 0
  6.  
  7. fn stackPush(v) {
  8. if (depth >= 256) {
  9. printConsoleShowWindow()
  10. printConsoleClear()
  11. printConsole("Error: stack depth overflow.")
  12. }
  13. stack[depth] = v
  14. depth += 1
  15. }
  16.  
  17. fn stackPop() {
  18. if (depth <= 0) {
  19. printConsoleShowWindow()
  20. printConsoleClear()
  21. printConsole("Error: stack depth underflow.")
  22. }
  23. depth -= 1
  24. return stack[depth]
  25. }
  26.  
  27. fn printStack() {
  28. printConsole("[")
  29. for (var i = 0; i < depth; i += 1) {
  30. printConsole(numberToString(stack[i]))
  31. if (i != (depth-1)) {
  32. printConsole(", ")
  33. }
  34. }
  35. printConsole("]")
  36. }
  37.  
  38. fn logOperatorToken(t) {
  39. printConsole("Token | Action | Stack: ")
  40. printConsole(t)
  41. printConsole(" | ")
  42. printConsole("Apply operator to top of stack")
  43. printConsole(" | ")
  44. printStack()
  45. printConsole("\n")
  46. }
  47.  
  48. fn logNumberToken(t) {
  49. printConsole("Token | Action | Stack: ")
  50. printConsole(t)
  51. printConsole(" | ")
  52. printConsole("Push number onto top of stack")
  53. printConsole(" | ")
  54. printStack()
  55. printConsole("\n")
  56. }
  57.  
  58. // RPN init
  59.  
  60. for (var i = 0; i < 256; i += 1) {
  61. append(stack, 0.0)
  62. }
  63. let s = " 3 4 2 * 1 5 - 2 3 ^ ^ / + "
  64.  
  65. // RPN
  66.  
  67. var buffer = ""
  68. for (var i = 0; i < len(s); i += 1) {
  69. let c = s[i]
  70. if (c == ' ') {
  71. let t = buffer
  72. buffer = ""
  73. if (t == "") {
  74. continue
  75. }
  76. if (t == "+" || t == "-" || t == "*" || t == "/" || t == "^") {
  77. let secondOperand = stackPop()
  78. let firstOperand = stackPop()
  79. if (t == "+") {
  80. stackPush(firstOperand + secondOperand)
  81. }
  82. if (t == "-") {
  83. stackPush(firstOperand - secondOperand)
  84. }
  85. if (t == "*") {
  86. stackPush(firstOperand * secondOperand)
  87. }
  88. if (t == "/") {
  89. stackPush(firstOperand / secondOperand)
  90. }
  91. if (t == "^") {
  92. stackPush(pow(firstOperand, secondOperand))
  93. }
  94. logOperatorToken(t)
  95. } else {
  96. let n = interpretStringToInteger(t)
  97. stackPush(n)
  98. logNumberToken(t)
  99. }
  100. } else {
  101. buffer += c
  102. }
  103. }
  104.  
  105. printConsole("Stack depth: " + numberToString(depth) + "\n")
  106. printConsole("Stack value: " + numberToString(stack[0]) + "\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement