The demo folder only had a toy todo list, which did not show that a non-trivial application can be written in Lua and shipped as a single compiled binary. This adds LuaSheet: a tokenizer, a formula parser, a lazy evaluator with cycle detection, range-aware builtin functions, ASCII/CSV rendering and a benchmark, all driven by a CLI entry point. Everything stays plain Lua under Demo/: no C++ change is needed to build or run it.
95 lines
2.2 KiB
Lua
95 lines
2.2 KiB
Lua
-- Shared formatting helpers: cell labels, number rendering, padding.
|
|
-- Used by the parser, the engine, the renderer and the command line app.
|
|
local M = {}
|
|
|
|
-- 1 -> "A", 26 -> "Z", 27 -> "AA", 703 -> "AAA"
|
|
function M.column_label(index)
|
|
local label = ""
|
|
local n = index
|
|
while n > 0 do
|
|
local remainder = (n - 1) % 26
|
|
label = string.char(65 + remainder) .. label
|
|
n = (n - 1 - remainder) // 26
|
|
end
|
|
return label
|
|
end
|
|
|
|
function M.column_index(letters)
|
|
local text = string.upper(letters)
|
|
if text == "" then
|
|
error("empty column name", 0)
|
|
end
|
|
local index = 0
|
|
for i = 1, #text do
|
|
local b = string.byte(text, i)
|
|
if b < 65 or b > 90 then
|
|
error("bad column name: " .. letters, 0)
|
|
end
|
|
index = index * 26 + (b - 64)
|
|
end
|
|
return index
|
|
end
|
|
|
|
-- Spreadsheet-ish number rendering: integers stay integers, floats lose
|
|
-- floating point noise (0.30000000000000004 -> "0.3").
|
|
function M.number(value)
|
|
if math.type(value) == "integer" then
|
|
return tostring(value)
|
|
end
|
|
local text = string.format("%.10g", value)
|
|
if text == "-0" then
|
|
text = "0"
|
|
end
|
|
return text
|
|
end
|
|
|
|
function M.value(value)
|
|
local kind = type(value)
|
|
if kind == "nil" then
|
|
return ""
|
|
elseif kind == "number" then
|
|
return M.number(value)
|
|
elseif kind == "boolean" then
|
|
if value then
|
|
return "TRUE"
|
|
end
|
|
return "FALSE"
|
|
elseif kind == "string" then
|
|
return value
|
|
elseif kind == "table" and value.__range then
|
|
local parts = {}
|
|
for i = 1, #value.values do
|
|
parts[#parts + 1] = M.value(value.values[i])
|
|
end
|
|
return table.concat(parts, " ")
|
|
end
|
|
return tostring(value)
|
|
end
|
|
|
|
function M.pad(text, width, right)
|
|
local length = #text
|
|
if length >= width then
|
|
return text
|
|
end
|
|
local fill = string.rep(" ", width - length)
|
|
if right then
|
|
return fill .. text
|
|
end
|
|
return text .. fill
|
|
end
|
|
|
|
-- Keeps a cell readable in a fixed width column instead of blowing it up.
|
|
function M.fit(text, width)
|
|
if #text <= width then
|
|
return text
|
|
end
|
|
return string.sub(text, 1, width - 1) .. "~"
|
|
end
|
|
|
|
function M.percent(ratio, digits)
|
|
local pattern = "%." .. tostring(digits or 1) .. "f%%"
|
|
return string.format(pattern, ratio * 100)
|
|
end
|
|
|
|
return M
|