Advertisement
BobMe

failed thing

Sep 24th, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. -- algorithm to do all math in a string
  2.  
  3. str = "I'm not really sure why I made this but 128*2 should be 256. Yeet."
  4.  
  5. -- look for mAth
  6.  
  7. local function is_number(x)
  8. x = tostring(x)
  9. if x == "0" or x == "1" or x == "2" or x == "3" or x == "4" or x == "5" or x == "6" or x == "7" or x == "8" or x == "9" then
  10. return true
  11. else
  12. return false
  13. end
  14. end
  15.  
  16. local function is_operator(x)
  17. x = tostring(x)
  18. if x == "+" or x == "*" or x == "-" or x == "/" then
  19. return {true,x}
  20. else
  21. return {false,x}
  22. end
  23. end
  24.  
  25. for i=1,#str do
  26. local find_number1
  27. local find_number2
  28. local sub1
  29. local sub2
  30. local sign
  31. if is_number(string.sub(str,i,i)) == true then
  32. find_number1 = i
  33. sub1 = i
  34. for k=i,#str do
  35. if is_number(string.sub(str,k,k)) == false then
  36. find_number1 = string.sub(str,i,k-1)
  37. print(find_number1)
  38. local op = is_operator(string.sub(str,k,k))
  39. if op[1] == true then
  40. sign = op[2]
  41. if is_number(string.sub(str,k+1,k+1)) then
  42. for l=k+1,#str do
  43. find_number2 = l
  44. if is_number(string.sub(str,l,l)) == false then
  45. find_number2 = string.sub(str,find_number2,l-1)
  46. sub2 = l-1
  47. end
  48. break
  49. end
  50. end
  51. end
  52. break
  53. end
  54. end
  55. end
  56. local sum
  57. if find_number1 ~= nil and find_number2 ~= nil and sub1 ~= nil and sub2 ~= nil then
  58. if sign == "+" then
  59. sum = tonumber(find_number1) + tonumber(find_number2)
  60. elseif sign == "-" then
  61. sum = tonumber(find_number1) - tonumber(find_number2)
  62. elseif sign == "*" then
  63. sum = tonumber(find_number1) * tonumber(find_number2)
  64. elseif sign == "/" then
  65. sum = tonumber(find_number1) / tonumber(find_number2)
  66. end
  67. str = string.sub(str,1,sub1)..tostring(sum)..string.sub(str,sub2)
  68. i = sub2
  69. end
  70. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement