Skip to content

Instantly share code, notes, and snippets.

@bethropolis
Created July 26, 2024 09:28
Show Gist options
  • Save bethropolis/b1186b380b12a00d83d54d24807b188d to your computer and use it in GitHub Desktop.
Save bethropolis/b1186b380b12a00d83d54d24807b188d to your computer and use it in GitHub Desktop.
local iup = require("iup")
-- Helper functions
local function updateDisplay(value)
local display = iup.GetHandle("display")
local currentValue = display.value
if currentValue == "0" or currentValue == "Error" then
display.value = value
else
display.value = currentValue .. value
end
end
local function clearDisplay()
iup.GetHandle("display").value = "0"
end
local function calculateResult()
local display = iup.GetHandle("display")
local expression = display.value
local success, result = pcall(function()
return loadstring("return " .. expression)()
end)
if success then
display.value = tostring(result)
else
display.value = "Error"
end
end
-- Create number buttons
local function createNumberButton(number)
return iup.button{
title = tostring(number),
size = "40x40",
action = function() updateDisplay(number) end
}
end
-- Create operator buttons
local function createOperatorButton(operator)
return iup.button{
title = operator,
size = "40x40",
action = function() updateDisplay(operator) end
}
end
-- Create special buttons
local clearButton = iup.button{
title = "C",
size = "40x40",
action = clearDisplay
}
local equalsButton = iup.button{
title = "=",
size = "40x40",
action = calculateResult
}
-- Create display
local display = iup.text{
id = "display",
value = "0",
readonly = "YES",
size = "160x40",
alignment = "ARIGHT",
expand = "HORIZONTAL",
}
-- Create calculator layout
local layout = iup.vbox{
display,
iup.hbox{
createNumberButton(7),
createNumberButton(8),
createNumberButton(9),
createOperatorButton("/")
},
iup.hbox{
createNumberButton(4),
createNumberButton(5),
createNumberButton(6),
createOperatorButton("*")
},
iup.hbox{
createNumberButton(1),
createNumberButton(2),
createNumberButton(3),
createOperatorButton("-")
},
iup.hbox{
createNumberButton(0),
iup.button{
title = ".",
size = "40x40",
action = function()
local display = iup.GetHandle("display")
if not display.value:find("%.") then
updateDisplay(".")
end
end
},
equalsButton,
createOperatorButton("+")
},
iup.hbox{
clearButton
},
margin = "10x10",
gap = "5"
}
-- Create main window
local window = iup.dialog{
layout,
title = "Calculator",
size = "250x300",
resize = "NO"
}
-- Show the window and run the main loop
window:show()
iup.MainLoop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment