# How would you make a calculator that takes strings?

Hey! I’m basically trying to make a calculator that takes strings for example “add”, “subtract”, … and then does the thing with the two numbers.
Here is my code:

``````local mathOperations = {
["times"] = "*"; --Had to make it a string or it would be underlined red
["subtract"] = "-";
}
----------------------------------------------------
local function calculate(number, input, number2)
local mathOperation = tonumber(mathOperations[input])
end
----------------------------------------------------
``````

This doesn’t work, this is just a type of pseudo-code I guess?
Thank you!

Edit: At line 8, I made it a tonumber so the strings get removed so it’s * instead of “*”

1 Like

you would want to make your math operations dictionary return a function, I’ll give an example

``````local mathOperations = {
["+"] = function(a, b)
return a + b
end,
["-"] = function(a, b)
return a - b
end
}

local function calculate(num1, num2, op)
num1 = tonumber(num1)
num2 = tonumber(num2)
return mathOperations[op](num1, num2)
end
``````

make sure to do error checking of course

1 Like

You could make it a table of functions or use `loadstring` but make sure to enable `LoadStringEnabled` from ServerScriptService.

Using table of functions:

``````local math_operations = {
["multiply"] = function(lhs, rhs) return lhs*rhs end,
["add"] = function(lhs, rhs) return lhs + rhs end,
["subtract"] = function(lhs, rhs) return lhs - rhs end
}

local function calculate(lhs, operation, rhs)
return math_operations[operation](lhs, rhs)
end

Second method, using `loadstring`:
``````local function calculate(lhs, operation, rhs)