🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Declarative DSLs

A declarative DSL is a description written as data, not as steps of code. It says what should exist, and an interpreter decides how to show it.

A description lists fields in order

The form description holds two fields. The interpreter prints their labels in description order.

local form = {
  { label = "Name", kind = "text" },
  { label = "Age", kind = "number" },
}
local labels = {}
for i, field in ipairs(form) do
  labels[i] = field.label
end
print(table.concat(labels, ", "))

A flag can mark a field required

The first field carries a required flag and the second does not. Only the first line gains the required note.

local form = {
  { label = "Name", required = true },
  { label = "Nickname", required = false },
}
local lines = {}
for i, field in ipairs(form) do
  if field.required then
    lines[i] = field.label .. " (required)"
  else
    lines[i] = field.label
  end
end
print(table.concat(lines, "\n"))

Each field also names its kind

Both fields name a kind. The interpreter prints each label beside its kind.

local form = {
  { label = "Email", kind = "text" },
  { label = "Age", kind = "number" },
}
local lines = {}
for i, field in ipairs(form) do
  lines[i] = field.label .. ": " .. field.kind
end
print(table.concat(lines, "\n"))

Example

local form = {
  { label = "Name", kind = "text", required = true },
  { label = "Email", kind = "text", required = true },
  { label = "Age", kind = "number", required = false },
  { label = "City", kind = "text", required = false },
}
local lines = {}
for i, field in ipairs(form) do
  local line = i .. ". " .. field.label .. " - " .. field.kind
  if field.required then
    line = line .. " (required)"
  end
  lines[i] = line
end
print(table.concat(lines, "\n"))

Key points

  • Declarative: describing what should exist instead of listing steps to build it.
  • Description: a table of fields, where each field names one piece of the result.
  • Interpreter: a function that walks the description and lists its fields in order.
  • Field: one entry in the description, with a label and a kind.
  • Kind: a word that says what sort of field it is, such as text or number.

In this example, the form table describes four fields in order. The loop builds one numbered line per field from its label and kind. Required fields gain a note, and the printed list shows the whole form in description order.

Note

changing the description changes the result without changing the interpreter.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What is a declarative description?