Files
LeonOS/data/computercraft/lua/rom/programs/calc.lua
Leonmmcoset 47b8b5cd2c feat: 添加计算器程序并更新版本至0.2.7
添加新的计算器程序calc.lua,包含完整的计算功能和界面
移除shell.lua中的错误窗口功能,改为直接输出错误信息
更新installer.lua和bios.lua中的版本号至0.2.7
添加calc命令的自动补全功能
2025-09-01 20:49:38 +08:00

89 lines
2.3 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

-- Calculator program calc.lua
local term = require("term")
local keys = require("keys")
local colors = require("colors")
-- Function to draw top bar
local function drawTopBar()
-- Get terminal size
local w, h = term.getSize()
-- Save cursor position
local cx, cy = term.getCursorPos()
-- Set top bar color
term.setTextColor(colors.yellow)
term.setBackgroundColor(colors.blue)
-- Move to top-left corner
term.setCursorPos(1, 1)
-- Draw top bar with centered title
local title = " LeonOS Calculator "
local padding = math.floor((w - #title) / 2)
term.write(string.rep(" ", padding) .. title .. string.rep(" ", padding))
-- Reset colors
term.setTextColor(colors.white)
term.setBackgroundColor(colors.black)
-- Restore cursor position
term.setCursorPos(cx, cy)
end
-- Clear screen and show UI
term.clear()
drawTopBar()
-- Move cursor to below top bar and show instructions
term.setCursorPos(1, 3)
print("Enter an expression, press Enter to calculate (type 'q' to quit)")
print("Supports +, -, *, /, ^(exponent), %(modulus), and parentheses")
print("---------------------------")
while true do
-- Show prompt
io.write("> ")
local input = io.read()
-- Check for exit
if input == "q" or input == "quit" then
break
end
-- Check for clear screen
if input == "clear" then
term.clear()
drawTopBar()
-- Move cursor to below top bar and show instructions
term.setCursorPos(1, 3)
print("Enter an expression, press Enter to calculate (type 'q' to quit)")
print("Supports +, -, *, /, ^(exponent), %(modulus), and parentheses")
print("---------------------------")
goto continue
end
-- Calculate expression
local success, result = pcall(function()
-- Replace Chinese parentheses with English ones
input = input:gsub("", "("):gsub("", ")")
-- Safely execute expression
local func = load("return " .. input)
if func then
return func()
else
error("Invalid expression")
end
end)
-- Show result
if success then
print("Result: " .. result)
else
print("Error: " .. tostring(result))
end
::continue::
end
print("Calculator has exited")