Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --(C) 2017 Taigaclaw some rights reserved (licenced WTFPL).
- function table.slice(tbl, first, last, step)
- local sliced = {}
- for i = first or 1, last or #tbl, step or 1 do
- sliced[#sliced+1] = tbl[i]
- end
- return sliced
- end
- function split(s)
- s = s:gsub('%s+', '')
- local parts = {}
- local i = 1
- while i <= #s do
- local char = s:sub(i, i)
- if tonumber(char) or char == '.' then
- if tonumber(parts[#parts]) and parts[#parts] ~= '-' then
- parts[#parts] = parts[#parts]..char
- else
- table.insert(parts, char)
- end
- else
- table.insert(parts, char)
- end
- i = i + 1
- end
- return parts
- end
- function evaluate(e)
- if type(e) ~= 'table' then
- e = split(e)
- end
- local total = 0
- local scan = true
- local i = 0
- while i <= #e do
- local char = e[i]
- if scan == true then
- if char == '(' then
- local scope = 0
- local starter = i
- local ender = 0
- local tape = i
- while true do
- if e[tape] == '(' then
- scope = scope + 1
- elseif e[tape] == ')' then
- scope = scope - 1
- if scope == 0 then
- ender = tape
- break
- end
- end
- tape = tape + 1
- end
- local ans = evaluate(table.slice(e, starter + 1, ender - 1, 1))
- local first = table.slice(e, 1, starter - 1, 1)
- local last = table.slice(e, ender + 1, #e, 1)
- e = {}
- for _, i in ipairs(first) do
- table.insert(e, i)
- end
- table.insert(e, tostring(ans))
- for _, i in ipairs(last) do
- table.insert(e, i)
- end
- end
- i = i + 1
- if i >= #e then
- i = 1
- scan = false
- end
- else
- if char == '+' then
- total = total + e[i + 1]
- i = i + 1
- elseif char == '-' then
- total = total - e[i + 1]
- i = i + 1
- elseif char == '/' then
- total = total / e[i + 1]
- i = i + 1
- elseif char == '*' then
- total = total * e[i + 1]
- i = i + 1
- elseif char == '%' then
- total = total % e[i + 1]
- i = i + 1
- else
- total = e[i]
- end
- i = i + 1
- end
- end
- return total
- end
- print(evaluate('1 + 1'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement