Advertisement
CaptainSpaceCat

Calculator

May 17th, 2015
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.35 KB | None | 0 0
  1. w, h = term.getSize()
  2. term.setBackgroundColor(colors.green)
  3. term.clear()
  4. term.setCursorPos(w/2 - 4, 1)
  5. term.write("Calculator")
  6. term.setCursorPos(1, 2)
  7. term.write("   +  -  *  /  **  ^  %   ")
  8. term.setCursorPos(1, 4)
  9. term.write("Input: ")
  10. term.setCursorPos(8, 4)
  11. local input = read()
  12. local tArgs = {}
  13. local count = 1
  14. for i in string.gmatch(input, "%S+") do
  15.   tArgs[count] = i
  16.   count = count + 1
  17. end
  18. local nums = {}
  19. local operands = {}
  20. local result = nil
  21. for i, v in pairs(tArgs) do
  22.   if tonumber(v) and v ~= "-" then
  23.     nums[i] = tonumber(v)
  24.     operands[i] = false
  25.   else
  26.     nums[i] = false
  27.     operands[i] = v
  28.   end
  29. end
  30.  
  31. local initial = true
  32. for i = 1, #tArgs do
  33.   if nums[i] == false then
  34.     if initial then
  35.       result = nums[i - 1]
  36.       initial = false
  37.     end
  38.     if operands[i] == "+" then
  39.       result = result + nums[i + 1]
  40.     elseif operands[i] == "-" then
  41.       result = result - nums[i + 1]
  42.     elseif operands[i] == "*" then
  43.       result = result * nums[i + 1]
  44.     elseif operands[i] == "/" then
  45.       result = result / nums[i + 1]
  46.     elseif operands[i] == "**" or operands[i] == "^" then
  47.       result = result ^ nums[i + 1]
  48.     elseif operands[i] == "%" then
  49.       result = result % nums[i + 1]
  50.     else
  51.       print("ERROR: Unsupported operation")
  52.       result = nil
  53.     end
  54.   end
  55. end
  56. print(result)
  57. sleep(2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement