-- Calculator Code in BDScript 2
-- Variables for calculator
local display = ""
local operator = nil
local firstNumber = nil
-- Function to update display
function updateDisplay(value)
display = display .. value
renderDisplay()
end
-- Function to render display
function renderDisplay()
-- Your code to render the display here
print("Display: " .. display)
end
-- Function to clear display
function clearDisplay()
display = ""
firstNumber = nil
operator = nil
renderDisplay()
end
-- Function to set operator
function setOperator(op)
if display ~= "" then
firstNumber = tonumber(display)
operator = op
display = ""
end
end
-- Function to calculate result
function calculate()
if firstNumber and operator and display ~= "" then
local secondNumber = tonumber(display)
if operator == "+" then
display = tostring(firstNumber + secondNumber)
elseif operator == "-" then
display = tostring(firstNumber - secondNumber)
elseif operator == "*" then
display = tostring(firstNumber * secondNumber)
elseif operator == "/" and secondNumber ~= 0 then
display = tostring(firstNumber / secondNumber)
else
display = "Error"
end
firstNumber = nil
operator = nil
renderDisplay()
end
end
-- Button functions
function onButtonClick(value)
if value == "C" then
clearDisplay()
elseif value == "=" then
calculate()
elseif value == "+" or value == "-" or value == "*" or value == "/" then
setOperator(value)
else
updateDisplay(value)
end
end
-- Example button setup (pseudo code)
local buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
}
-- Function to simulate button clicks (this would be linked to your UI in practice)
for _, button in ipairs(buttons) do
onButtonClick(button)
end
This code outlines a basic text-based calculator. In a real BDScript 2 environment, you would need to adapt the renderDisplay function to suit your UI framework (if any), as well as integrate actual button elements that call the onButtonClick function with their respective values when pressed.