I am trying to make a calculator, and I am getting an expression from the textbox, but I do not know how to evaluate the expression. I tried printing it, but it would come out as a normal string. For example, if I input 3+2 it would print 3+2:
equal.MouseButton1Click:Connect(function()
local str = text.Text
print(str)
end)
This is actually a harder problem than it seems. You could just loadstring the equation, but that’s generally a bad idea.
The fully correct way to do it is to tokenize the expression, run that token sequence through the shunting-yard algorithm to transform it into a reverse-polish-notation sequence, then process that sequence to get the answer.
Use string.split(str, “+”) to store the table where the character will be separated by the + character.
Store the result in a variable, which will actually be a table, because that’s what string.split() returns.
You then can create a variable, and store the sum in it.
sum = tonumber(tablee[1]) + tonumber(tablee[2]) -- tonumber() needed because string.split returns strings as elements.
You will need to loop through the string before you do all of these to find what operator is used there, (+, -, /, *), check it with if, each iteration. However, if you have more than 2 operators, or more than 2 numbers, then you probably need to make the code more complex. You can loop through the table using ipairs, to add more than 2 numbers, but I am not sure how you would make the code work with more than 2 operators.
This helped a lot, but I do not know how to check if it would give out nil. I tried this:
equal.MouseButton1Click:Connect(function()
local str = text.Text
local tabplus = string.split(str, "+")
local tabminus = string.split(str, "-")
local sum = tonumber(tabplus[1]) + tonumber(tabplus[2])
if sum == nil then
local diff = tonumber(tabminus[1]) - tonumber(tabminus[2])
text.Text = diff
else
text.Text = sum
end
end)
You can add a simple condition to check if the values of these elements are not nil.
if tabplus[1] and tabplus [2] then
--your code for addition (including the sum variable initialisation)
elseif tabminus[1] and tabminus[2] then
--your code for subtraction (including the diff variable initialisation)
end