feat(demo): add a spreadsheet engine written in Lua

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.
This commit is contained in:
BlackAngelTV committed 2026-11-18 09:19:32 +01:00
1 parent 4bf42d9179
commit e71907ea86
9 files changed
+1950

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
-- LuaSheet : un tableur en console, 100% Lua, compilé en un binaire unique.
--
-- ./build/luacpp run Demo/luasheet.lua classeur Budget (défaut)
-- ./build/luacpp run Demo/luasheet.lua ventes second classeur
-- ./build/luacpp run Demo/luasheet.lua errors feuille d'erreurs
-- ./build/luacpp run Demo/luasheet.lua formula "=SUM(1,2,3)*2"
-- ./build/luacpp run Demo/luasheet.lua csv
-- ./build/luacpp run Demo/luasheet.lua bench 200
-- ./build/luacpp run Demo/luasheet.lua test
local sheet_module = require("sheet.sheet")
local render = require("sheet.render")
local workbooks = require("sheet.workbooks")
local tests = require("sheet.tests")
local builtins = require("sheet.builtins")
local format = require("sheet.format")
local M = {}
local argv = arg or {}
local command = argv[1] or "demo"
local function echo(line)
print(line or "")
end
local function banner(title)
echo(string.rep("=", 64))
echo(title)
echo(string.rep("=", 64))
end
local function demo()
local sheet = sheet_module.from_text(workbooks.budget, "Budget 2026")
banner("LuaSheet - classeur Budget 2026")
echo("")
local rendered = render.render(sheet)
echo(rendered)
echo("")
echo(string.format(
"%d cellules, %d evaluations, %d erreurs",
sheet:count(), sheet.stats.eval, sheet.stats.errors
))
echo("")
echo("--- inspecteur de formules ---")
local inspected = { "D4", "C11", "D11", "B13", "C16", "B18" }
for i = 1, #inspected do
local key = inspected[i]
echo(string.format(" %-4s %-22s -> %s", key, sheet:raw(key) or "", sheet:display(key)))
end
echo("")
echo("--- repartition des charges (B4:B9) ---")
local posts = {
{ "Loyer", "B4" }, { "Courses", "B5" }, { "Transport", "B6" },
{ "Energie", "B7" }, { "Loisirs", "B8" }, { "Epargne", "B9" },
}
local total = 0
for i = 1, #posts do
local value = sheet:value(posts[i][2])
if type(value) == "number" then
total = total + value
end
end
for i = 1, #posts do
local value = sheet:value(posts[i][2])
local label = posts[i][1]
local ratio = 0
if total > 0 then
ratio = value / total
end
echo(string.format(
" %-10s %6s %s %5s",
label, format.number(value), render.bar(value, total, 24), format.percent(ratio, 1)
))
end
echo("")
echo("--- indicateurs ---")
local revenue = sheet:value("B12") or 0
local remaining = sheet:value("B13") or 0
local remaining_ratio = 0
if revenue ~= 0 then
remaining_ratio = remaining / revenue
end
local savings = sheet:value("B21") or 0
echo(" charges mensuelles : " .. sheet:display("B11"))
echo(" reste a vivre : " .. sheet:display("B13") .. " (" .. format.percent(remaining_ratio, 1) .. " des revenus)")
echo(" epargne annuelle : " .. sheet:display("B15"))
echo(" objectif epargne : " .. sheet:display("B16") .. " -> " .. sheet:display("C16"))
echo(" part de l'epargne : " .. format.percent(savings, 1))
local found = sheet:errors()
if #found > 0 then
echo("")
echo("--- erreurs ---")
for i = 1, #found do
echo(string.format(" %-4s %-16s %s", found[i].key, found[i].text, found[i].err))
end
end
return 0
end
local function ventes()
local sheet = sheet_module.from_text(workbooks.ventes, "Ventes")
banner("LuaSheet - classeur Ventes")
echo("")
echo(render.render(sheet))
echo("")
echo("vue formules :")
echo(render.render(sheet, { show_formulas = true }))
return 0
end
local function show_errors()
local sheet = sheet_module.from_text(workbooks.errors, "Erreurs")
banner("LuaSheet - feuille d'erreurs (volontaires)")
echo("")
echo(render.render(sheet))
echo("")
local found = sheet:errors()
echo(string.format("%d cellules en erreur :", #found))
for i = 1, #found do
local entry = found[i]
echo(string.format(" %-4s %-14s %-10s %s", entry.key, entry.err, entry.text, entry.detail or ""))
end
return 0
end
local function formula(text)
if text == nil or text == "" then
echo('usage : luasheet formula "=SUM(1,2,3)*2"')
return 2
end
local sheet = sheet_module.new("formula")
sheet:set("A1", "120")
sheet:set("A2", "80")
sheet:set("A3", "Lua")
sheet:set("A4", "=A1+A2")
if string.sub(text, 1, 1) == "=" then
text = string.sub(text, 2)
end
sheet:set("B1", "=" .. text)
echo(string.format("A1=120 A2=80 A3=\"Lua\" A4=A1+A2=%s", sheet:display("A4")))
echo(string.format("%s -> %s", text, sheet:display("B1")))
local found = sheet:errors()
for i = 1, #found do
if found[i].key == "B1" and found[i].detail ~= nil then
echo("detail : " .. found[i].detail)
end
end
return 0
end
local function csv()
local sheet = sheet_module.from_text(workbooks.budget, "Budget 2026")
echo(render.csv(sheet))
return 0
end
local function bench(argument)
local rows = tonumber(argument) or 300
if rows < 1 then
rows = 1
end
local sheet = sheet_module.new("bench")
for row = 1, rows do
for column = 1, 7 do
sheet:set(format.column_label(column) .. row, tostring((row * column) % 97))
end
sheet:set("H" .. row, string.format("=SUM(A%d:G%d)", row, row))
end
sheet:set("I1", string.format("=SUM(H1:H%d)", rows))
local best = 0
local last = 0
for pass = 1, 3 do
sheet:invalidate()
local started = os.clock()
local total = sheet:value("I1")
local elapsed = os.clock() - started
last = total
if pass == 1 or elapsed < best then
best = elapsed
end
echo(string.format(
" passe %d : %6.1f ms (%d evaluations, total I1 = %s)",
pass, elapsed * 1000, sheet.stats.eval, format.number(total)
))
end
local cells = rows * 8 + 1
local rate = 0
if best > 0 then
rate = cells / best
end
echo("")
echo(string.format(" %d lignes x 8 colonnes = %d cellules", rows, cells))
echo(string.format(" meilleure passe : %.1f ms -> environ %d cellules/s", best * 1000, math.floor(rate)))
echo(string.format(" total recalcule : %s", format.number(last)))
return 0
end
local function run_tests()
banner("LuaSheet - tests internes")
local summary = tests.run()
echo("")
echo(string.format(" %d tests OK, %d echec(s)", summary.passed, summary.failed))
if summary.failed > 0 then
echo("")
for i = 1, #summary.failures do
echo(" FAIL " .. summary.failures[i])
end
return 1
end
return 0
end
local function usage()
banner("LuaSheet - tableur en Lua compilé par luacpp")
echo("")
echo(" luasheet demo classeur Budget 2026 (défaut)")
echo(" luasheet ventes second classeur (texte, IF, &)")
echo(" luasheet errors feuille d'erreurs (#DIV/0!, #CYCLE!, ...)")
echo(' luasheet formula "=..." évalue une formule')
echo(" luasheet csv exporte le classeur Budget en CSV")
echo(" luasheet bench [lignes] mesure le recalcul (défaut : 300 lignes)")
echo(" luasheet test lance les tests internes")
echo(" luasheet help cette aide")
echo("")
echo("Opérateurs : + - * / % ^ & = <> < > <= >=")
echo("Références : A1, $A$1, plages A1:B4")
echo("Fonctions : " .. table.concat(builtins.names(), " "))
echo("")
echo("Exemple : luacpp run Demo/luasheet.lua formula \"=SUM(1,2,3)*2\"")
return 0
end
local commands = {
demo = demo,
ventes = ventes,
errors = show_errors,
formula = formula,
csv = csv,
bench = bench,
test = run_tests,
help = usage,
["--help"] = usage,
["-h"] = usage,
}
local handler = commands[command]
if handler == nil then
echo("commande inconnue : " .. command)
usage()
os.exit(2)
end
os.exit(handler(argv[2]) or 0)
+382
View File
@@ -0,0 +1,382 @@
-- Built-in spreadsheet functions.
-- Every function receives the already evaluated arguments; ranges arrive as
-- { __range = true, values = { ... } } and are flattened by the helpers below.
local format = require("sheet.format")
local M = {}
local function fail(code)
error(code, 0)
end
local function flatten(args)
local out = {}
for i = 1, #args do
local argument = args[i]
if type(argument) == "table" and argument.__range then
for j = 1, #argument.values do
out[#out + 1] = argument.values[j]
end
else
out[#out + 1] = argument
end
end
return out
end
-- Numbers only: text inside a range is ignored, like a spreadsheet does.
local function numeric_values(args)
local values = flatten(args)
local out = {}
for i = 1, #values do
local value = values[i]
if type(value) == "number" then
out[#out + 1] = value
elseif type(value) == "string" then
local number = tonumber(value)
if number then
out[#out + 1] = number
end
end
end
return out
end
local function number_arg(value)
if type(value) == "number" then
return value
end
if type(value) == "string" then
local number = tonumber(value)
if number then
return number
end
end
if type(value) == "boolean" then
if value then
return 1
end
return 0
end
fail("#VALUE!")
end
local function text_arg(value)
local kind = type(value)
if kind == "string" then
return value
end
if kind == "number" then
return format.number(value)
end
if kind == "boolean" then
if value then
return "TRUE"
end
return "FALSE"
end
fail("#VALUE!")
end
local function boolean_arg(value)
local kind = type(value)
if kind == "boolean" then
return value
end
if kind == "number" then
return value ~= 0
end
if kind == "string" then
local lower = string.lower(value)
if lower == "true" or lower == "oui" or lower == "vrai" then
return true
end
if lower == "false" or lower == "non" or lower == "faux" or lower == "" then
return false
end
end
fail("#VALUE!")
end
local function sum(args)
local values = numeric_values(args)
local total = 0
for i = 1, #values do
total = total + values[i]
end
return total
end
local function product(args)
local values = numeric_values(args)
local total = 1
for i = 1, #values do
total = total * values[i]
end
return total
end
local function average(args)
local values = numeric_values(args)
if #values == 0 then
fail("#DIV/0!")
end
local total = 0
for i = 1, #values do
total = total + values[i]
end
return total / #values
end
local function minimum(args)
local values = numeric_values(args)
if #values == 0 then
return 0
end
local best = values[1]
for i = 2, #values do
if values[i] < best then
best = values[i]
end
end
return best
end
local function maximum(args)
local values = numeric_values(args)
if #values == 0 then
return 0
end
local best = values[1]
for i = 2, #values do
if values[i] > best then
best = values[i]
end
end
return best
end
local function count(args)
return #numeric_values(args)
end
local function count_non_empty(args)
local values = flatten(args)
local total = 0
for i = 1, #values do
if values[i] ~= nil then
total = total + 1
end
end
return total
end
local function median(args)
local values = numeric_values(args)
if #values == 0 then
fail("#DIV/0!")
end
table.sort(values)
local middle = (#values + 1) // 2
if #values % 2 == 1 then
return values[middle]
end
return (values[middle] + values[middle + 1]) / 2
end
local function choose(args)
if boolean_arg(args[1]) then
if args[2] == nil then
return true
end
return args[2]
end
if args[3] == nil then
return false
end
return args[3]
end
local function all_of(args)
local values = flatten(args)
for i = 1, #values do
if not boolean_arg(values[i]) then
return false
end
end
return true
end
local function any_of(args)
local values = flatten(args)
for i = 1, #values do
if boolean_arg(values[i]) then
return true
end
end
return false
end
local function not_of(args)
return not boolean_arg(args[1])
end
local function round(args)
local value = number_arg(args[1])
local digits = 0
if args[2] ~= nil then
digits = number_arg(args[2])
end
local multiplier = 10 ^ digits
local scaled = value * multiplier
local rounded
if scaled >= 0 then
rounded = math.floor(scaled + 0.5)
else
rounded = math.ceil(scaled - 0.5)
end
if digits == 0 then
return rounded
end
return rounded / multiplier
end
local function absolute(args)
return math.abs(number_arg(args[1]))
end
local function square_root(args)
local value = number_arg(args[1])
if value < 0 then
fail("#VALUE!")
end
return math.sqrt(value)
end
local function integer_part(args)
return math.floor(number_arg(args[1]))
end
local function modulo(args)
local left = number_arg(args[1])
local right = number_arg(args[2])
if right == 0 then
fail("#DIV/0!")
end
return left % right
end
local function power(args)
return number_arg(args[1]) ^ number_arg(args[2])
end
local function concat(args)
local values = flatten(args)
local parts = {}
for i = 1, #values do
parts[#parts + 1] = format.value(values[i])
end
return table.concat(parts)
end
local function length(args)
return #text_arg(args[1])
end
local function upper(args)
return string.upper(text_arg(args[1]))
end
local function lower(args)
return string.lower(text_arg(args[1]))
end
local function left(args)
local text = text_arg(args[1])
local amount = number_arg(args[2])
if amount < 0 then
fail("#VALUE!")
end
return string.sub(text, 1, amount)
end
local function right(args)
local text = text_arg(args[1])
local amount = number_arg(args[2])
if amount < 0 then
fail("#VALUE!")
end
if amount >= #text then
return text
end
return string.sub(text, #text - amount + 1)
end
local function trim(args)
local text = text_arg(args[1])
return string.match(text, "^%s*(.-)%s*$")
end
-- name, minimum arguments, maximum arguments (-1 = unlimited), implementation
local definitions = {
{ "SUM", 1, -1, sum },
{ "PRODUCT", 1, -1, product },
{ "AVG", 1, -1, average },
{ "MIN", 1, -1, minimum },
{ "MAX", 1, -1, maximum },
{ "COUNT", 1, -1, count },
{ "COUNTA", 1, -1, count_non_empty },
{ "MEDIAN", 1, -1, median },
{ "IF", 2, 3, choose },
{ "AND", 1, -1, all_of },
{ "OR", 1, -1, any_of },
{ "NOT", 1, 1, not_of },
{ "ROUND", 1, 2, round },
{ "ABS", 1, 1, absolute },
{ "SQRT", 1, 1, square_root },
{ "INT", 1, 1, integer_part },
{ "MOD", 2, 2, modulo },
{ "POWER", 2, 2, power },
{ "CONCAT", 1, -1, concat },
{ "LEN", 1, 1, length },
{ "UPPER", 1, 1, upper },
{ "LOWER", 1, 1, lower },
{ "LEFT", 2, 2, left },
{ "RIGHT", 2, 2, right },
{ "TRIM", 1, 1, trim },
}
local by_name = {}
local names = {}
for i = 1, #definitions do
local definition = definitions[i]
by_name[definition[1]] = { min = definition[2], max = definition[3], fn = definition[4] }
names[#names + 1] = definition[1]
end
function M.call(name, args)
local builtin = by_name[name]
if builtin == nil then
fail("#NAME?")
end
local received = #args
if received < builtin.min or (builtin.max >= 0 and received > builtin.max) then
fail("#VALUE!")
end
return builtin.fn(args)
end
function M.exists(name)
return by_name[string.upper(name)] ~= nil
end
function M.names()
local copy = {}
for i = 1, #names do
copy[i] = names[i]
end
table.sort(copy)
return copy
end
return M
+94
View File
@@ -0,0 +1,94 @@
-- 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
+164
View File
@@ -0,0 +1,164 @@
-- Tokenizer for spreadsheet formulas.
--
-- =SUM(A1:B4) * 2 >= IF(C1 <> "", "ok", "non")
--
-- Tokens are { kind = "num"|"str"|"ref"|"ident"|"op"|"punct"|"eof",
-- value = ..., pos = <1-based column> }.
local M = {}
local byte = string.byte
local sub = string.sub
local format = string.format
local function byte_at(text, index)
return byte(text, index) or 0
end
local function is_alpha(b)
return (b >= 65 and b <= 90) or (b >= 97 and b <= 122) or b == 95
end
local function is_digit(b)
return b >= 48 and b <= 57
end
local function is_alnum(b)
return is_alpha(b) or is_digit(b)
end
local TWO_CHAR = { ["<="] = true, [">="] = true, ["<>"] = true, ["!="] = true }
local ONE_CHAR = {
["+"] = true, ["-"] = true, ["*"] = true, ["/"] = true, ["%"] = true,
["^"] = true, ["&"] = true, ["="] = true, ["<"] = true, [">"] = true,
}
local function token(kind, value, pos)
return { kind = kind, value = value, pos = pos }
end
function M.tokenize(text)
local tokens = {}
local i = 1
local n = #text
while i <= n do
local c = sub(text, i, i)
local b = byte_at(text, i)
if b == 32 or b == 9 or b == 10 or b == 13 then
i = i + 1
elseif is_digit(b) or (c == "." and is_digit(byte_at(text, i + 1))) then
local start = i
while is_digit(byte_at(text, i)) do
i = i + 1
end
if byte_at(text, i) == 46 then
i = i + 1
while is_digit(byte_at(text, i)) do
i = i + 1
end
end
local exponent = byte_at(text, i)
if exponent == 101 or exponent == 69 then
local save = i
i = i + 1
local sign = byte_at(text, i)
if sign == 43 or sign == 45 then
i = i + 1
end
if is_digit(byte_at(text, i)) then
while is_digit(byte_at(text, i)) do
i = i + 1
end
else
i = save
end
end
local literal = sub(text, start, i - 1)
tokens[#tokens + 1] = token("num", tonumber(literal), start)
elseif c == '"' or c == "'" then
local quote = c
local start = i
i = i + 1
local parts = {}
local closed = false
while i <= n do
local ch = sub(text, i, i)
if ch == "\\" then
local escaped = sub(text, i + 1, i + 1)
if escaped == "n" then
parts[#parts + 1] = "\n"
elseif escaped == "t" then
parts[#parts + 1] = "\t"
elseif escaped == "\\" then
parts[#parts + 1] = "\\"
elseif escaped == '"' then
parts[#parts + 1] = '"'
elseif escaped == "'" then
parts[#parts + 1] = "'"
elseif escaped == "" then
error(format("unterminated string at %d", start), 0)
else
parts[#parts + 1] = escaped
end
i = i + 2
elseif ch == quote then
closed = true
i = i + 1
break
else
parts[#parts + 1] = ch
i = i + 1
end
end
if not closed then
error(format("unterminated string at %d", start), 0)
end
tokens[#tokens + 1] = token("str", table.concat(parts), start)
elseif is_alpha(b) or c == "$" then
local start = i
i = i + 1
while i <= n do
local next_byte = byte_at(text, i)
if is_alnum(next_byte) or next_byte == 36 then
i = i + 1
else
break
end
end
local word = sub(text, start, i - 1)
local letters, digits = string.match(word, "^%$?([A-Za-z]+)%$?(%d+)$")
if letters then
tokens[#tokens + 1] = token("ref", {
text = word,
letters = letters,
row = tonumber(digits),
}, start)
else
tokens[#tokens + 1] = token("ident", word, start)
end
elseif c == "(" or c == ")" or c == "," or c == ":" then
tokens[#tokens + 1] = token("punct", c, i)
i = i + 1
else
local pair = sub(text, i, i + 1)
if TWO_CHAR[pair] then
if pair == "!=" then
pair = "<>"
end
tokens[#tokens + 1] = token("op", pair, i)
i = i + 2
elseif ONE_CHAR[c] then
tokens[#tokens + 1] = token("op", c, i)
i = i + 1
else
error(format("unexpected character %q at %d", c, i), 0)
end
end
end
tokens[#tokens + 1] = token("eof", "<eof>", n + 1)
return tokens
end
return M
+178
View File
@@ -0,0 +1,178 @@
-- Recursive descent parser for spreadsheet formulas.
-- Produces plain tables: { k = "num"|"str"|"bool"|"ref"|"range"|"un"|"bin"|"call", ... }
--
-- Precedence (low to high): comparisons, &, + -, * / %, unary -, ^
-- Unary minus binds tighter than ^ (spreadsheet style: -2^2 = 4).
local lexer = require("sheet.lexer")
local format = require("sheet.format")
local M = {}
local PREC = {
["="] = 1, ["<>"] = 1, ["<"] = 1, [">"] = 1, ["<="] = 1, [">="] = 1,
["&"] = 2,
["+"] = 3, ["-"] = 3,
["*"] = 4, ["/"] = 4, ["%"] = 4,
["^"] = 6,
}
local Parser = {}
Parser.__index = Parser
function Parser.new(tokens)
return setmetatable({ tokens = tokens, pos = 1 }, Parser)
end
function Parser:peek()
return self.tokens[self.pos]
end
function Parser:next()
local current = self.tokens[self.pos]
self.pos = self.pos + 1
return current
end
function Parser:expect_punct(value)
local current = self:peek()
if current.kind ~= "punct" or current.value ~= value then
error(string.format("expected %q at %d", value, current.pos), 0)
end
return self:next()
end
function Parser:parse_primary()
local current = self:peek()
if current.kind == "num" then
self:next()
return { k = "num", v = current.value }
end
if current.kind == "str" then
self:next()
return { k = "str", v = current.value }
end
if current.kind == "ref" then
self:next()
local column = format.column_index(current.value.letters)
local row = current.value.row
local reference = {
k = "ref",
col = column,
row = row,
key = format.column_label(column) .. row,
text = current.value.text,
}
local following = self:peek()
if following.kind == "punct" and following.value == ":" then
self:next()
local last = self:peek()
if last.kind ~= "ref" then
error(string.format("expected a cell after ':' at %d", last.pos), 0)
end
self:next()
local column2 = format.column_index(last.value.letters)
local row2 = last.value.row
return {
k = "range",
c1 = math.min(column, column2),
c2 = math.max(column, column2),
r1 = math.min(row, row2),
r2 = math.max(row, row2),
}
end
return reference
end
if current.kind == "ident" then
self:next()
local following = self:peek()
if following.kind == "punct" and following.value == "(" then
self:next()
local args = {}
local closing = self:peek()
if not (closing.kind == "punct" and closing.value == ")") then
args[#args + 1] = self:parse_expression(1)
while true do
local separator = self:peek()
if separator.kind == "punct" and separator.value == "," then
self:next()
args[#args + 1] = self:parse_expression(1)
else
break
end
end
end
self:expect_punct(")")
return { k = "call", name = string.upper(current.value), args = args }
end
local upper = string.upper(current.value)
if upper == "TRUE" then
return { k = "bool", v = true }
end
if upper == "FALSE" then
return { k = "bool", v = false }
end
error(string.format("unknown name %q at %d", current.value, current.pos), 0)
end
if current.kind == "punct" and current.value == "(" then
self:next()
local inner = self:parse_expression(1)
self:expect_punct(")")
return inner
end
error(string.format("unexpected token %q at %d", tostring(current.value), current.pos), 0)
end
function Parser:parse_unary()
local current = self:peek()
if current.kind == "op" and (current.value == "-" or current.value == "+") then
self:next()
local operand = self:parse_unary()
if current.value == "-" then
return { k = "un", op = "-", a = operand }
end
return { k = "un", op = "+", a = operand }
end
return self:parse_primary()
end
function Parser:parse_expression(minimum)
local left = self:parse_unary()
while true do
local current = self:peek()
if current.kind ~= "op" then
break
end
local precedence = PREC[current.value]
if precedence == nil or precedence < minimum then
break
end
self:next()
local next_minimum = precedence + 1
if current.value == "^" then
next_minimum = precedence
end
local right = self:parse_expression(next_minimum)
left = { k = "bin", op = current.value, a = left, b = right }
end
return left
end
-- Parses the body of a formula, i.e. without the leading '='.
function M.parse(text)
local tokens = lexer.tokenize(text)
local parser = Parser.new(tokens)
local ast = parser:parse_expression(1)
local last = parser:peek()
if last.kind ~= "eof" then
error(string.format("unexpected %q at %d", tostring(last.value), last.pos), 0)
end
return ast
end
return M
+108
View File
@@ -0,0 +1,108 @@
-- ASCII rendering of a sheet: grid, formula view, CSV export and bars.
local format = require("sheet.format")
local M = {}
local MAX_WIDTH = 24
function M.render(sheet, options)
options = options or {}
local show_formulas = options.show_formulas
local max_row, max_col = sheet:dimensions()
if max_row == 0 or max_col == 0 then
return "(feuille vide)"
end
local widths = {}
local cells = {}
local numeric = {}
for column = 1, max_col do
widths[column] = #format.column_label(column)
end
for row = 1, max_row do
cells[row] = {}
numeric[row] = {}
for column = 1, max_col do
local key = format.column_label(column) .. row
local text
if show_formulas then
text = sheet:raw(key) or ""
else
text = sheet:display(key)
end
text = format.fit(text, MAX_WIDTH)
cells[row][column] = text
if #text > widths[column] then
widths[column] = #text
end
local value = sheet:value(key)
numeric[row][column] = type(value) == "number"
end
end
local label_width = #tostring(max_row)
local lines = {}
local header = format.pad("", label_width) .. " |"
for column = 1, max_col do
header = header .. " " .. format.pad(format.column_label(column), widths[column]) .. " |"
end
lines[#lines + 1] = header
local separator = string.rep("-", label_width) .. "-+"
for column = 1, max_col do
separator = separator .. string.rep("-", widths[column] + 2) .. "+"
end
lines[#lines + 1] = separator
for row = 1, max_row do
local line = format.pad(tostring(row), label_width, true) .. " |"
for column = 1, max_col do
local text = cells[row][column]
line = line .. " " .. format.pad(text, widths[column], numeric[row][column]) .. " |"
end
lines[#lines + 1] = line
end
return table.concat(lines, "\n")
end
function M.csv(sheet)
local max_row, max_col = sheet:dimensions()
local lines = {}
for row = 1, max_row do
local fields = {}
for column = 1, max_col do
local text = sheet:display(format.column_label(column) .. row)
if string.find(text, '[,"\n]') then
local escaped = string.gsub(text, '"', '""')
text = '"' .. escaped .. '"'
end
fields[#fields + 1] = text
end
lines[#lines + 1] = table.concat(fields, ",")
end
return table.concat(lines, "\n")
end
-- Proportional bar, e.g. bar(820, 1923, 24) = "##########.............."
function M.bar(value, maximum, width)
if maximum <= 0 or width <= 0 then
return ""
end
local filled = math.floor(value / maximum * width + 0.5)
if value > 0 and filled < 1 then
filled = 1
end
if filled > width then
filled = width
end
return string.rep("#", filled) .. string.rep(".", width - filled)
end
function M.fit(text, width)
return format.fit(text, width)
end
return M
+418
View File
@@ -0,0 +1,418 @@
-- The sheet engine: cells, lazy evaluation, ranges and error values.
--
-- A cell holds either a literal (number, boolean, text) or a formula. Formula
-- values are computed on demand, memoised, and cycles are detected with a
-- "visiting" set, so A1 = B1, B1 = A1 yields #CYCLE! instead of hanging.
local parser = require("sheet.parser")
local builtins = require("sheet.builtins")
local format = require("sheet.format")
local M = {}
local Sheet = {}
Sheet.__index = Sheet
local function trim(text)
return string.match(text, "^%s*(.-)%s*$")
end
function M.new(name)
return setmetatable({
name = name or "Sheet1",
cells = {},
values = {},
visiting = {},
stats = { eval = 0, errors = 0, cycles = 0 },
}, Sheet)
end
function Sheet:invalidate()
self.values = {}
self.visiting = {}
self.stats = { eval = 0, errors = 0, cycles = 0 }
end
function Sheet:normalize(address)
local letters, digits = string.match(address, "^%s*%$?([A-Za-z]+)%$?(%d+)%s*$")
if letters == nil then
error("bad cell address: " .. tostring(address), 0)
end
local column = format.column_index(letters)
local row = tonumber(digits)
if row == nil or row < 1 then
error("bad cell address: " .. tostring(address), 0)
end
return format.column_label(column) .. row, column, row
end
function Sheet:set(address, text, number_format)
local key, column, row = self:normalize(address)
local body = trim(tostring(text or ""))
self:invalidate()
if body == "" then
self.cells[key] = nil
return key
end
local cell = { text = body, col = column, row = row, format = number_format }
if string.sub(body, 1, 1) == "=" then
cell.kind = "formula"
local ok, ast = pcall(parser.parse, string.sub(body, 2))
if ok then
cell.ast = ast
else
cell.parse_error = tostring(ast)
end
else
cell.kind = "literal"
local number = tonumber(body)
local upper = string.upper(body)
if number ~= nil then
cell.value = number
elseif upper == "TRUE" then
cell.value = true
elseif upper == "FALSE" then
cell.value = false
else
cell.value = body
end
end
self.cells[key] = cell
return key
end
function Sheet:raw(address)
local key = self:normalize(address)
local cell = self.cells[key]
if cell == nil then
return nil
end
return cell.text
end
-- Internal: evaluates a cell key, raising "#CODE" on failure.
function Sheet:evaluate(key)
local cached = self.values[key]
if cached ~= nil then
if cached.ok then
return cached.value
end
error(cached.err, 0)
end
local cell = self.cells[key]
if cell == nil then
return nil
end
if cell.kind == "literal" then
self.values[key] = { ok = true, value = cell.value }
return cell.value
end
if cell.parse_error ~= nil then
self.stats.errors = self.stats.errors + 1
self.values[key] = { ok = false, err = "#PARSE!", detail = cell.parse_error }
error("#PARSE!", 0)
end
if self.visiting[key] then
self.stats.cycles = self.stats.cycles + 1
error("#CYCLE!", 0)
end
self.visiting[key] = true
self.stats.eval = self.stats.eval + 1
local ok, result = pcall(function()
return self:run(cell.ast)
end)
self.visiting[key] = nil
if ok then
self.values[key] = { ok = true, value = result }
return result
end
local message = tostring(result)
local code = "#VALUE!"
if string.sub(message, 1, 1) == "#" then
code = message
end
self.stats.errors = self.stats.errors + 1
self.values[key] = { ok = false, err = code, detail = message }
error(code, 0)
end
function Sheet:to_number(value)
local kind = type(value)
if kind == "number" then
return value
end
if kind == "string" then
local number = tonumber(value)
if number ~= nil then
return number
end
end
if kind == "boolean" then
if value then
return 1
end
return 0
end
error("#VALUE!", 0)
end
function Sheet:compare(operator, left, right)
if type(left) == "table" or type(right) == "table" then
error("#VALUE!", 0)
end
local a = left
local b = right
local both_numbers = type(a) == "number" and type(b) == "number"
local both_booleans = type(a) == "boolean" and type(b) == "boolean"
if not both_numbers and not both_booleans then
a = format.value(a)
b = format.value(b)
end
if operator == "=" then
return a == b
elseif operator == "<>" then
return a ~= b
elseif operator == "<" then
return a < b
elseif operator == ">" then
return a > b
elseif operator == "<=" then
return a <= b
end
return a >= b
end
function Sheet:binary(operator, left_node, right_node)
if operator == "&" then
local left = format.value(self:run(left_node))
local right = format.value(self:run(right_node))
return left .. right
end
if operator == "=" or operator == "<>" or operator == "<" or operator == ">"
or operator == "<=" or operator == ">=" then
return self:compare(operator, self:run(left_node), self:run(right_node))
end
local a = self:to_number(self:run(left_node))
local b = self:to_number(self:run(right_node))
if operator == "+" then
return a + b
elseif operator == "-" then
return a - b
elseif operator == "*" then
return a * b
elseif operator == "/" then
if b == 0 then
error("#DIV/0!", 0)
end
return a / b
elseif operator == "%" then
if b == 0 then
error("#DIV/0!", 0)
end
return a % b
elseif operator == "^" then
return a ^ b
end
error("#PARSE!", 0)
end
function Sheet:run(node)
local kind = node.k
if kind == "num" or kind == "str" or kind == "bool" then
return node.v
end
if kind == "ref" then
local value = self:evaluate(node.key)
if value == nil then
return 0
end
return value
end
if kind == "range" then
local values = {}
for row = node.r1, node.r2 do
for column = node.c1, node.c2 do
local value = self:evaluate(format.column_label(column) .. row)
if value ~= nil then
values[#values + 1] = value
end
end
end
return {
__range = true,
values = values,
c1 = node.c1, c2 = node.c2, r1 = node.r1, r2 = node.r2,
}
end
if kind == "call" then
local args = {}
for i = 1, #node.args do
args[i] = self:run(node.args[i])
end
return builtins.call(node.name, args)
end
if kind == "un" then
local value = self:to_number(self:run(node.a))
if node.op == "-" then
return -value
end
return value
end
if kind == "bin" then
return self:binary(node.op, node.a, node.b)
end
error("#PARSE!", 0)
end
-- Public accessor: returns value, error_code (nil when the cell is fine).
function Sheet:value(address)
local ok, key = pcall(function()
return self:normalize(address)
end)
if not ok then
return nil, "#REF!"
end
local evaluated, result = pcall(function()
return self:evaluate(key)
end)
if evaluated then
return result, nil
end
return nil, tostring(result)
end
-- What a cell shows: formatted value, or its error code, or "" when blank.
-- A cell declared with the '%' format renders its ratio as a percentage.
function Sheet:display(address)
local value, err = self:value(address)
if err ~= nil then
return err
end
if value == nil then
return ""
end
local ok, key = pcall(function()
return self:normalize(address)
end)
local cell = nil
if ok then
cell = self.cells[key]
end
if cell ~= nil and cell.format == "percent" and type(value) == "number" then
return string.format("%.1f%%", value * 100)
end
return format.value(value)
end
function Sheet:dimensions()
local max_row = 0
local max_col = 0
for _, cell in pairs(self.cells) do
if cell.row > max_row then
max_row = cell.row
end
if cell.col > max_col then
max_col = cell.col
end
end
return max_row, max_col
end
function Sheet:count()
local total = 0
for _ in pairs(self.cells) do
total = total + 1
end
return total
end
-- Named helper (no closure): the generated C++ of a closure capturing a
-- mutated local and a generic for loop is fragile, so pcall gets plain args.
local function evaluate_entry(sheet, key)
return sheet:evaluate(key)
end
function Sheet:evaluate_all()
local keys = {}
for key in pairs(self.cells) do
table.insert(keys, key)
end
table.sort(keys)
for i = 1, #keys do
local key = keys[i]
local ok = pcall(evaluate_entry, self, key)
if not ok then
-- errors are recorded in self.values; keep walking the sheet
local recorded = self.values[key]
if recorded == nil then
self.values[key] = { ok = false, err = "#VALUE!" }
end
end
end
end
function Sheet:errors()
self:evaluate_all()
local found = {}
for key, cached in pairs(self.values) do
if not cached.ok then
local cell = self.cells[key]
found[#found + 1] = {
key = key,
err = cached.err,
detail = cached.detail,
text = cell and cell.text or "",
row = cell and cell.row or 0,
col = cell and cell.col or 0,
}
end
end
table.sort(found, function(a, b)
if a.row ~= b.row then
return a.row < b.row
end
return a.col < b.col
end)
return found
end
-- Reads a tiny worksheet format: one "A1: value" or "B4: =B3*12" per line,
-- '#' comments, blank lines ignored.
function M.from_text(text, name)
local sheet = M.new(name)
local line_number = 0
for line in string.gmatch(text .. "\n", "([^\n]*)\n") do
line_number = line_number + 1
local body = trim(line)
if body ~= "" and string.sub(body, 1, 1) ~= "#" then
local address, marker, content = string.match(body, "^([%$%a%d]+)%s*(%%?)%s*:%s*(.*)$")
if address == nil then
error(string.format("%s line %d: expected 'A1: value'", name or "sheet", line_number), 0)
end
local number_format = nil
if marker == "%" then
number_format = "percent"
end
sheet:set(address, content, number_format)
end
end
return sheet
end
return M
+214
View File
@@ -0,0 +1,214 @@
-- Self tests for the spreadsheet engine. Returns a summary table:
-- { passed = n, failed = n, failures = { "message", ... } }
local lexer = require("sheet.lexer")
local parser = require("sheet.parser")
local builtins = require("sheet.builtins")
local sheet_module = require("sheet.sheet")
local render = require("sheet.render")
local format = require("sheet.format")
local workbooks = require("sheet.workbooks")
local M = {}
-- Evaluates a single formula on a throw-away sheet and returns what the cell
-- displays (so numbers, booleans and error codes compare as strings).
local function compute(text)
local sheet = sheet_module.new("ad-hoc")
sheet:set("A1", text)
return sheet:display("A1")
end
local function sample(rows)
local sheet = sheet_module.new("case")
for i = 1, #rows do
sheet:set(rows[i][1], rows[i][2])
end
return sheet
end
function M.run()
local passed = 0
local failures = {}
local function check(name, actual, expected)
if actual == expected then
passed = passed + 1
else
failures[#failures + 1] = string.format(
"%s : attendu %s, obtenu %s",
name, tostring(expected), tostring(actual)
)
end
end
local function check_true(name, condition, detail)
if condition then
passed = passed + 1
else
failures[#failures + 1] = name .. " : " .. tostring(detail or "condition fausse")
end
end
-- addresses -----------------------------------------------------------
check("column_label(1)", format.column_label(1), "A")
check("column_label(26)", format.column_label(26), "Z")
check("column_label(27)", format.column_label(27), "AA")
check("column_label(28)", format.column_label(28), "AB")
check("column_label(702)", format.column_label(702), "ZZ")
check("column_label(703)", format.column_label(703), "AAA")
check("column_index(AA)", format.column_index("AA"), 27)
check("column_index(zz)", format.column_index("zz"), 702)
-- lexer ---------------------------------------------------------------
local tokens = lexer.tokenize("A1+2.5*$B$3")
check("lexer token count", #tokens, 6)
check("lexer first kind", tokens[1].kind, "ref")
check("lexer first text", tokens[1].value.text, "A1")
check("lexer number", tokens[3].value, 2.5)
check("lexer absolute ref", tokens[5].value.letters, "B")
local lex_ok, lex_err = pcall(lexer.tokenize, "1 @ 2")
check("lexer rejects @", lex_ok, false)
check_true("lexer error is explicit", string.find(tostring(lex_err), "unexpected") ~= nil, lex_err)
-- parser --------------------------------------------------------------
local parse_ok = pcall(parser.parse, "SUM(")
check("parser rejects unclosed call", parse_ok, false)
check("precedence add/mul", compute("=1+2*3"), "7")
check("precedence parentheses", compute("=(1+2)*3"), "9")
check("power is right assoc", compute("=2^3^2"), "512")
check("unary minus binds tight", compute("=-2^2"), "4")
check("division is float", compute("=10/4"), "2.5")
check("modulo", compute("=7%3"), "1")
check("concat operator", compute("=1&2"), "12")
check("comparison lower", compute("=2<3"), "TRUE")
check("comparison not equal", compute("=3<>3"), "FALSE")
check("string equality", compute('="a"="a"'), "TRUE")
check("string concat", compute('="a"&"b"'), "ab")
check("! = alias", compute("=1!=2"), "TRUE")
-- references and ranges ----------------------------------------------
local sheet = sample({
{ "A1", "1" }, { "A2", "2" }, { "A3", "3" }, { "A4", "texte" },
})
sheet:set("B1", "=SUM(A1:A3)")
sheet:set("B2", "=AVG(A1:A3)")
sheet:set("B3", "=COUNT(A1:A4)")
sheet:set("B4", "=MAX(A1:A4)")
sheet:set("B5", "=MIN(A1:A3)")
sheet:set("B6", "=SUM(A1:A3,B1)")
sheet:set("C1", "=$A$1*10")
sheet:set("C2", "=Z9+1")
sheet:set("C3", "=SUM(A1:A3)")
check("SUM range", sheet:display("B1"), "6")
check("AVG range", sheet:display("B2"), "2")
check("COUNT ignores text", sheet:display("B3"), "3")
check("MAX ignores text", sheet:display("B4"), "3")
check("MIN range", sheet:display("B5"), "1")
check("SUM with scalar cell", sheet:display("B6"), "12")
check("absolute reference", sheet:display("C1"), "10")
check("blank reference is zero", sheet:display("C2"), "1")
check("range order preserved", sheet:display("C3"), "6")
-- functions -----------------------------------------------------------
check("IF true", compute('=IF(1<2,"oui","non")'), "oui")
check("IF false", compute('=IF(1>2,"oui","non")'), "non")
check("ROUND digits", compute("=ROUND(3.14159,2)"), "3.14")
check("ROUND half up", compute("=ROUND(2.5,0)"), "3")
check("ROUND negative half", compute("=ROUND(-2.5,0)"), "-3")
check("ABS", compute("=ABS(-7)"), "7")
check("SQRT", compute("=SQRT(2)*SQRT(2)"), "2")
check("INT", compute("=INT(-2.5)"), "-3")
check("MOD", compute("=MOD(7,3)"), "1")
check("POWER", compute("=POWER(2,10)"), "1024")
check("MEDIAN even", compute("=MEDIAN(4,1,3,2)"), "2.5")
check("CONCAT mixed", compute('=CONCAT("a",1,TRUE)'), "a1TRUE")
check("LEN", compute('=LEN("abc")'), "3")
check("UPPER", compute('=UPPER("lua")'), "LUA")
check("LOWER", compute('=LOWER("LUA")'), "lua")
check("LEFT", compute('=LEFT("abcdef",3)'), "abc")
check("RIGHT", compute('=RIGHT("abcdef",3)'), "def")
check("TRIM", compute('=TRIM(" x ")'), "x")
check("nested calls", compute("=SUM(1,2,MAX(3,4))"), "7")
check_true("builtin registry", builtins.exists("sum") and builtins.exists("Median"), "registry incomplete")
check_true("builtin names sorted", builtins.names()[1], "ABS")
-- errors --------------------------------------------------------------
check("divide by zero", compute("=1/0"), "#DIV/0!")
check("unknown function", compute("=NOPE(1)"), "#NAME?")
check("text in arithmetic", compute('=1+"abc"'), "#VALUE!")
check("syntax error", compute("=SUM("), "#PARSE!")
check("bad operator use", compute("=1+"), "#PARSE!")
local cyclic = sample({ { "A1", "=B1" }, { "B1", "=A1" }, { "C1", "=A1" } })
check("cycle detected", cyclic:display("A1"), "#CYCLE!")
check("cycle back edge", cyclic:display("B1"), "#CYCLE!")
check("cycle propagates", cyclic:display("C1"), "#CYCLE!")
local broken = sample({ { "A1", "=1/0" }, { "B1", "=A1+1" } })
check("error propagates", broken:display("B1"), "#DIV/0!")
-- chains and caching --------------------------------------------------
local chain = sample({
{ "A1", "1" }, { "A2", "=A1+1" }, { "A3", "=A2+1" }, { "A4", "=A3+1" },
})
check("dependency chain", chain:display("A4"), "4")
check_true("evaluation counted", chain.stats.eval >= 3, "stats.eval")
chain:set("A1", "10")
check("recalc after edit", chain:display("A4"), "13")
-- rendering -----------------------------------------------------------
check("fit keeps short text", format.fit("abc", 10), "abc")
check("fit truncates", format.fit("abcdef", 4), "abc~")
check("bar full", render.bar(10, 10, 5), "#####")
check("bar half", render.bar(5, 10, 10), "#####.....")
check("bar minimum", render.bar(1, 1000, 10), "#.........")
local viewed = render.render(sheet)
check_true("render has header", string.find(viewed, "| A") ~= nil, viewed)
check_true("render has separator", string.find(viewed, "%+%-+") ~= nil, viewed)
-- csv -----------------------------------------------------------------
local csv_sheet = sample({ { "A1", "texte, avec virgule" }, { "B1", 'un "guillemet"' } })
local csv = render.csv(csv_sheet)
check_true("csv quotes comma", string.find(csv, '"texte, avec virgule"', 1, true) ~= nil, csv)
check_true("csv doubles quotes", string.find(csv, '""guillemet""', 1, true) ~= nil, csv)
-- worksheet format ----------------------------------------------------
local parsed = sheet_module.from_text("A1: 5\nB1: =A1*2\n# commentaire\n\nA2: =IF(B1>5,\"grand\",\"petit\")\n", "mini")
check("from_text literal", parsed:display("A1"), "5")
check("from_text formula", parsed:display("B1"), "10")
check("from_text if", parsed:display("A2"), "grand")
check("from_text cell count", parsed:count(), 3)
-- workbooks -----------------------------------------------------------
local budget = sheet_module.from_text(workbooks.budget, "Budget")
check("budget charges", budget:display("B11"), "1923")
check("budget annuel", budget:display("C11"), "23076")
check("budget reste", budget:display("B13"), "677")
check("budget objectif", budget:display("C16"), "atteint")
check("budget moyenne", budget:display("B18"), "320.5")
check("budget max", budget:display("B19"), "820")
check("budget count", budget:display("B20"), "6")
check("percent cell", budget:display("D4"), "42.6%")
check("percent total", budget:display("D11"), "100.0%")
check("percent savings", budget:display("B21"), "11.5%")
local ventes = sheet_module.from_text(workbooks.ventes, "Ventes")
check("ventes total", ventes:display("B9"), "44000")
check("ventes statut", ventes:display("E4"), "ok")
check("ventes etiquette", ventes:display("E9"), "total 44000 / 43000")
check("ventes best", ventes:display("B11"), "14300")
local errors_sheet = sheet_module.from_text(workbooks.errors, "Erreurs")
check("errors cycle", errors_sheet:display("A1"), "#CYCLE!")
check("errors div", errors_sheet:display("B1"), "#DIV/0!")
check("errors name", errors_sheet:display("C1"), "#NAME?")
check("errors value", errors_sheet:display("D1"), "#VALUE!")
check("errors parse", errors_sheet:display("E1"), "#PARSE!")
check("errors propagation", errors_sheet:display("F1"), "#CYCLE!")
check("errors blank ref", errors_sheet:display("G1"), "1")
check_true("errors listing", #errors_sheet:errors() >= 6, #errors_sheet:errors())
return { passed = passed, failed = #failures, failures = failures }
end
return M
+132
View File
@@ -0,0 +1,132 @@
-- Sample workbooks, kept as text in the worksheet format read by
-- sheet.from_text(): "A1: value" or "B4: =B3*12", '#' for comments.
local M = {}
M.budget = [[
# Budget 2026 : un classeur complet, calcule a la volee.
A1: Budget 2026 - foyer
A3: Poste
B3: Mensuel
C3: Annuel
D3: Part
A4: Loyer
B4: 820
C4: =B4*12
D4 %: =C4/$C$11
A5: Courses
B5: 430
C5: =B5*12
D5 %: =C5/$C$11
A6: Transport
B6: 95
C6: =B6*12
D6 %: =C6/$C$11
A7: Energie
B7: 118
C7: =B7*12
D7 %: =C7/$C$11
A8: Loisirs
B8: 160
C8: =B8*12
D8 %: =C8/$C$11
A9: Epargne
B9: 300
C9: =B9*12
D9 %: =C9/$C$11
A11: Total charges
B11: =SUM(B4:B9)
C11: =SUM(C4:C9)
D11 %: =SUM(D4:D9)
A12: Revenus net
B12: 2600
C12: =B12*12
D12 %: =B12/$B$12
A13: Reste a vivre
B13: =B12-B11
C13: =C12-C11
D13 %: =B13/B12
A15: Epargne sur 12 mois
B15: =C9
A16: Objectif epargne
B16: 3600
C16: =IF(B15>=B16,"atteint","a revoir")
A18: Moyenne par poste
B18: =ROUND(AVG(B4:B9),2)
A19: Poste le plus lourd
B19: =MAX(B4:B9)
A20: Nombre de postes
B20: =COUNT(B4:B9)
A21: Part epargne
B21 %: =B9/B12
]]
M.ventes = [[
# Ventes : texte, concatenation et comparaisons.
A1: Ventes par region
A3: Region
B3: Ventes
C3: Objectif
D3: Taux
E3: Statut
A4: Nord
B4: 12500
C4: 11000
D4 %: =B4/C4
E4: =IF(D4>=1,"ok","alerte")
A5: Sud
B5: 9800
C5: 11000
D5 %: =B5/C5
E5: =IF(D5>=1,"ok","alerte")
A6: Est
B6: 14300
C6: 12000
D6 %: =B6/C6
E6: =IF(D6>=1,"ok","alerte")
A7: Ouest
B7: 7400
C7: 9000
D7 %: =B7/C7
E7: =IF(D7>=1,"ok","alerte")
A9: Total
B9: =SUM(B4:B7)
C9: =SUM(C4:C7)
D9 %: =B9/C9
E9: =CONCAT("total ", B9, " / ", C9)
A11: Meilleure region
B11: =MAX(B4:B7)
A12: Taux median
B12 %: =ROUND(MEDIAN(D4:D7),3)
A13: Etiquette
B13: ="Taux global " & ROUND(D9,2)
]]
M.errors = [[
# Une feuille qui casse volontairement, pour montrer les codes d'erreur.
A1: =A1+1
B1: =1/0
C1: =NOPE(1)
D1: =1+"abc"
E1: =SUM(
F1: =A1+B1
G1: =Z9+1
]]
return M