function GenerateQuestion()
local numbers = 3 -- Amount of numbers the question will have.
local numberMin = -20 -- Lower limit for the number randomization.
local numberMax = 20 -- Upper limit for the number randomization.
local asterisks = 0 -- Number of multiplication operators (a chunk later on ensures that there's only one multiplication).
local signs = {'+', '-', '*'} -- Available operators.
question = "" -- The question which the function will output.
for i = 1, numbers, 1 do -- Generates random numbers and formats them into the question string.
local number = tostring(math.random(numberMin, numberMax)) -- Generates a random number within the specified limits.
if i < numbers then -- Ensures that an operator is only placed after a number if the number is not the last in the sequence.
local sign = signs[math.random(1, #signs)] -- Randomly picks an operator.
if sign == '*' then
asterisks = asterisks + 1 -- Increments the number of multiplication operators.
end
if tonumber(number) < 0 then
number = "("..number..")" -- Adds parentheses around a number if it's negative.
end
question = question..number.." "..sign.." " -- Concatenates the number and sign onto the question string.
else -- Gets called once the loop reaches the last number, and doesn't place an operator after the number.
if tonumber(number) < 0 then
number = "("..number..")" -- Adds parentheses around a number if it's negative.
end
question = question..number -- Concatenates the number onto the question string.
end
end
if asterisks > 1 then
question = question:gsub('*', signs[math.random(1, #signs - 1)], numbers - 2) -- Ensures that there's only one multiplication.
end
return question -- Returns the final question string.
end
function EvaluateQuestion()
local s = "solution = "..question -- Concatenates the question string onto an assignment syntax.
RunString(s) -- Parses the code contained in s, and calculates the value of the solution variable.
return solution -- Returns the solution to the question.
end
function PrintQuestion()
print(GenerateQuestion())
print(EvaluateQuestion())
end
timer.Create("timer", 120, 0, PrintQuestion)
concommand.Add("generate_question", PrintQuestion)