Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- algorithm to do all math in a string
- str = "I'm not really sure why I made this but 128*2 should be 256. Yeet."
- -- look for mAth
- local function is_number(x)
- x = tostring(x)
- 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
- return true
- else
- return false
- end
- end
- local function is_operator(x)
- x = tostring(x)
- if x == "+" or x == "*" or x == "-" or x == "/" then
- return {true,x}
- else
- return {false,x}
- end
- end
- for i=1,#str do
- local find_number1
- local find_number2
- local sub1
- local sub2
- local sign
- if is_number(string.sub(str,i,i)) == true then
- find_number1 = i
- sub1 = i
- for k=i,#str do
- if is_number(string.sub(str,k,k)) == false then
- find_number1 = string.sub(str,i,k-1)
- print(find_number1)
- local op = is_operator(string.sub(str,k,k))
- if op[1] == true then
- sign = op[2]
- if is_number(string.sub(str,k+1,k+1)) then
- for l=k+1,#str do
- find_number2 = l
- if is_number(string.sub(str,l,l)) == false then
- find_number2 = string.sub(str,find_number2,l-1)
- sub2 = l-1
- end
- break
- end
- end
- end
- break
- end
- end
- end
- local sum
- if find_number1 ~= nil and find_number2 ~= nil and sub1 ~= nil and sub2 ~= nil then
- if sign == "+" then
- sum = tonumber(find_number1) + tonumber(find_number2)
- elseif sign == "-" then
- sum = tonumber(find_number1) - tonumber(find_number2)
- elseif sign == "*" then
- sum = tonumber(find_number1) * tonumber(find_number2)
- elseif sign == "/" then
- sum = tonumber(find_number1) / tonumber(find_number2)
- end
- str = string.sub(str,1,sub1)..tostring(sum)..string.sub(str,sub2)
- i = sub2
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement