I would like to know if there is a way to work out maths when the user inputs a string like:
- "1+1" (would return 2)
- "2+2" (4)
- "5-4" (1)
- "5-6" (-1)
- "6*2.5" (15)
- "6/2.5" (2.4)
- "6+4+5-2" (13)
Edit: String.
Posted 07 July 2013 - 06:19 AM
Posted 07 July 2013 - 11:19 AM
Posted 07 July 2013 - 12:18 PM
Posted 07 July 2013 - 12:54 PM
Lyqyd, on 07 July 2013 - 11:19 AM, said:
Hellkid98, on 07 July 2013 - 12:18 PM, said:
Posted 08 July 2013 - 06:43 PM
while true do
write(">")
local inStr=read()
if inStr==nil or inStr=="" then
break
end
if inStr:match("^[%s%d%.%-%+%*%/%%%^]+$") then
local f,err=loadstring("return "..inStr)
if f then
local succ, res=pcall(f)
print(res)
else
print(err)
end
else
print("Invalid Expression!")
end
end
Posted 09 July 2013 - 05:59 PM
Posted 09 July 2013 - 06:12 PM
Posted 09 July 2013 - 07:08 PM
local calc = ('calc string here'):gsub(' ', '')
if not calc:find('^[0-9%-%+/%*%%%^]') then
local digits = {}
for i = 1, calc:len() do
table.insert( digits, calc:sub( i, i )
end
-- actual calculating here
end
Posted 09 July 2013 - 07:50 PM
Engineer, on 09 July 2013 - 07:08 PM, said:
local calc = ('calc string here'):gsub(' ', '')
if not calc:find('^[0-9%-%+/%*%%%^]') then
local digits = {}
for i = 1, calc:len() do
table.insert( digits, calc:sub( i, i )
end
-- actual calculating here
end
Posted 09 July 2013 - 07:55 PM
Posted 09 July 2013 - 07:59 PM
local input = read()
local func = loadstring("return "..input)
if func then
setfenv(func, {})
local ok, result = pcall(func)
if ok then
print(result)
else
printError("Error: ", result)
end
else
printError("Invalid input")
end
Posted 09 July 2013 - 08:05 PM
MysticT, on 09 July 2013 - 07:59 PM, said:
local input = read()
local func = loadstring("return "..input)
if func then
setfenv(func, {})
local ok, result = pcall(func)
if ok then
print(result)
else
printError("Error: ", result)
end
else
printError("Invalid input")
end
setfenv(func, setmetatable({}, {__index=math}))
Posted 10 July 2013 - 01:01 AM
ElvishJerricco, on 09 July 2013 - 07:50 PM, said:
Posted 10 July 2013 - 02:10 AM
Engineer, on 10 July 2013 - 01:01 AM, said:
Posted 10 July 2013 - 02:34 AM
ElvishJerricco, on 10 July 2013 - 02:10 AM, said:
Posted 10 July 2013 - 02:38 AM
Engineer, on 10 July 2013 - 02:34 AM, said:
Posted 10 July 2013 - 09:40 AM
Posted 10 July 2013 - 11:50 AM
Pharap, on 09 July 2013 - 07:55 PM, said:
MysticT, on 09 July 2013 - 07:59 PM, said:
local input = read()
local func = loadstring("return "..input)
if func then
setfenv(func, {})
local ok, result = pcall(func)
if ok then
print(result)
else
printError("Error: ", result)
end
else
printError("Invalid input")
end
Edited by Lyqyd, 10 July 2013 - 12:35 PM.
cleanup.
Posted 10 July 2013 - 12:53 PM
Posted 10 July 2013 - 05:16 PM

0 members, 1 guests, 0 anonymous users