How can I calculate an equation from a string, and get an answer?

I am making a game which involves math, and the equations are randomly generated. The operations are stored in a table and numbers are made with math.random, like this:

local Operations = {" + ", " * ", " - ", " / "}
Base.Question.Text = math.random(1,10) .. Operations[math.random(1,#Operations)] .. math.random(1,10)

How can I calculate the answer for the strings generated?

This topic has been made but loadstring or tonumber didn’t seem to work for my situation.

I know its a bad fix but sadly you cant make operators into variables. Which means you need to use the actual thing. So you can make something like

local Value1 = 5
local Value2 = 16
if operator == "*" then 
Value1 * Value2
end

Loadstring seems to be the only possible way unless you want to do what @Dodoslayerlid suggested. What was the issue when you tried it?

1 Like

this seems like my best bet right now. works fine right now. thanks!

1 Like

it returned either nil or the first number.

1 Like

This might be overkill for your case, but I wanted to add that you could implement the Shunting yard algorithm to convert the expression from infix notation (normal readable math notation) into postfix notation. From there, you could evaluate the postfix expression to get the answer.

Again, might be overkill but it’s a general solution for this type of problem.