Lua Table DSLs
A table DSL is a small language written as nested Lua tables. Keys name the parts of a thing, and values name its settings.
A table can describe one thing
The description holds a title and a price. The interpreter turns those two settings into one sentence.
local card = { title = "Tea", price = 3 }
local function describe(c)
return c.title .. " costs " .. c.price
end
print(describe(card))Nested tables describe parts inside parts
Each part is its own small table. The interpreter reads one setting from each part.
local page = { header = { text = "Welcome" }, body = { text = "Fresh tea daily" } }
local function render(p)
return p.header.text .. " | " .. p.body.text
end
print(render(page))A list keeps the parts in order
The interpreter walks the list from first to last. The joined names show that order.
local steps = { { name = "heat" }, { name = "pour" }, { name = "serve" } }
local parts = {}
for i, step in ipairs(steps) do
parts[i] = step.name
end
print(table.concat(parts, " -> "))Example
local report = {
title = "Sales",
sections = {
{ heading = "Morning", value = 12 },
{ heading = "Evening", value = 20 },
},
}
local lines = { report.title }
local total = 0
for i, section in ipairs(report.sections) do
lines[#lines + 1] = section.heading .. ": " .. section.value
total = total + section.value
end
lines[#lines + 1] = "Total: " .. total
print(table.concat(lines, "\n"))Key points
- Table DSL: nested tables describe a thing instead of giving step by step instructions.
- Part: a key in the description that names one piece of the thing.
- Setting: a value in the description that says how one part should appear.
- Interpreter: a function that walks a description and turns it into output.
- Order: a list inside the description keeps the parts in a fixed order.
In this example, the report table holds a title and a list of sections. The loop adds one line per section and adds each value to the total. The last line prints the total, so the printed report proves the interpreter read every section.
Note
Lua tables hold both the description and the settings, so no extra language is needed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does an interpreter do with a table DSL description?