2
\$\begingroup\$

I'm a beginner at Lua and programming in general and I just made a simple calculator and I was wondering where I could make improvements.

print("Choose numbers:")
print("Num1:")
local num1 = io.read()
print("num2:")
local num2 = io.read()
print("Choose operator: + / - / * / /")
local operator = io.read()
if operator == "+" then
   local add = num1 + num2
   print(add)     
end 
if operator == "-" then
   local subtract = num1 - num2
   print(subtract)   
end
if operator == "*" then
   local multiply = num1 * num2
   print(multiply)
end   
if operator == "/" then  
   local devide = num1 / num2
   print(devide) 
end
io.read()
\$\endgroup\$

migrated from stackoverflow.com May 27 '16 at 4:53

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ What exactly do you want to improve? \$\endgroup\$ – user6245072 May 26 '16 at 20:16
9
\$\begingroup\$

Try some features, typically available from functional languages. For example, functions that is first class values.

local operators = {
    ["+"] = function(x,y) return x+y end,
    ["-"] = function(x,y) return x-y end,
    ["*"] = function(x,y) return x*y end,
    ["/"] = function(x,y) return x/y end
}

local function default()
    print "No such operator"
end

print("Choose numbers:")
print("Num1:")
local num1 = io.read()
print("num2:")
local num2 = io.read()
print("Choose operator: + / - / * / /")

local func = operators[io.read()] or default
print(func(num1,num2))

io.read()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy