🎓 A1Learner
🔍
0 of 49 lessons completed

Lua Chaining DSLs

A chaining DSL is a small language where each step returns the same table. The steps join with colons into one chain that builds one result.

Each step returns the same table

Each add step stores one word. The final list shows all three words in chain order.

local maker = { words = {} }
function maker:add(word)
  table.insert(self.words, word)
  return self
end
maker:add("one"):add("two"):add("three")
print(table.concat(maker.words, "-"))

Steps can set different fields

One step sets the size. Two steps add toppings, and the printed line shows both kinds of step.

local order = { size = "?", toppings = {} }
function order:setSize(s)
  self.size = s
  return self
end
function order:addTopping(t)
  table.insert(self.toppings, t)
  return self
end
order:setSize("large"):addTopping("cheese"):addTopping("tomato")
print(order.size .. " with " .. table.concat(order.toppings, " and "))

A final step can return the built result

The add steps store path pieces. The build step joins them into one path string.

local path = { parts = {} }
function path:add(p)
  table.insert(self.parts, p)
  return self
end
function path:build()
  return "/" .. table.concat(self.parts, "/")
end
path:add("home"):add("tea"):add("menu")
print(path:build())

Example

local sandwich = { bread = "", fillings = {} }
function sandwich:setBread(bread)
  self.bread = bread
  return self
end
function sandwich:addFilling(filling)
  table.insert(self.fillings, filling)
  return self
end
function sandwich:describe()
  return self.bread .. " sandwich with " .. table.concat(self.fillings, " and ")
end
sandwich:setBread("rye"):addFilling("cheese"):addFilling("lettuce")
print(sandwich:describe())

Key points

  • Chaining DSL: a style where method calls join together on one table.
  • Step: one method call that adds a piece to the result and returns the table.
  • Chain: several steps written in a row, each acting on the same table.
  • Self: the table a method acts on, passed automatically with colon calls.
  • Result: the table or value the chain has built when the steps finish.

In this example, the sandwich table starts empty. The setBread step stores the bread and returns the table, then each addFilling step stores one filling and returns the table. The describe step joins the bread and the fillings into one sentence.

Note

a chain that returns a different table at a step would break the chain, so each step must return the same table.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

In a chaining DSL, what must each step return so the next step can follow it?