-- Your existing Compute function
function Compute(operator, op1, op2)
if operator == "+" then return op1 + op2 end
if operator == "-" then return op1 - op2 end
if operator == "*" then return op1 * op2 end
if operator == "/" then return op1 / op2 end
error("Unknown operator: " .. operator)
end
-- The recursive evaluation function
function EvaluatePrefix(token_list)
if #token_list == 0 then
error("Invalid expression: missing operands")
end
local current_token = table.remove(token_list, 1)
local number_value = tonumber(current_token)
if number_value ~= nil then
return number_value
else
local left_operand = EvaluatePrefix(token_list)
local right_operand = EvaluatePrefix(token_list)
return Compute(current_token, left_operand, right_operand)
end
end
-- Wrapper Function to parse the custom string format
function MainEvaluate(expression_string)
local token_list = {}
local i = 1
local len = string.len(expression_string)
while i <= len do
local char = string.sub(expression_string, i, i)
if char == "+" or char == "-" or char == "*" or char == "/" then
table.insert(token_list, char)
i = i + 1
elseif char == "&" or char == " " then
-- Skips both ampersands AND empty spaces for safety
i = i + 1
else
local num_str = ""
while i <= len do
local next_char = string.sub(expression_string, i, i)
if next_char == "&" or next_char == " " or next_char == "+" or next_char == "-" or next_char == "*" or next_char == "/" then
break
end
num_str = num_str .. next_char
i = i + 1
end
if num_str ~= "" then
table.insert(token_list, num_str)
end
end
end
local final_result = EvaluatePrefix(token_list)
if #token_list > 0 then
error("Invalid expression: too many operands")
end
return final_result
end
-- --- USER INPUT LOOP ---
while true do
io.write("\nEnter expression: ")
local input = io.read()
-- Exit condition
if input == nil or input == "exit" or input == "quit" then
print("Goodbye!")
break
end
-- Skip empty entries
if input ~= "" then
-- pcall runs the function safely so the whole program doesn't crash if the user types a bad formula
local success, result = pcall(MainEvaluate, input)
if success then
print("Result: " .. result)
else
print("Error: " .. result)
end
end
end
To embed this project on your website, copy the following code and paste it into your website's HTML: