HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Simple four-operation calculator in Lua

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplefouroperationcalculatorlua

Problem

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()

Solution

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()

Code Snippets

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()

Context

StackExchange Code Review Q#129423, answer score: 9

Revisions (0)

No revisions yet.