Lua Rule DSLs
A rule DSL is a small language written as a list of rules. Each rule has a test and an action, and the first rule whose test passes runs its action.
One rule tests one value
The rule tests a score of 95. Its action returns the matching label.
local rules = {
{ when = function(score) return score >= 90 end, ["then"] = function() return "gold" end },
}
local function run(score)
for _, rule in ipairs(rules) do
if rule.when(score) then
return rule["then"]()
end
end
return "none"
end
print(run(95))The first matching rule wins
Both rules could match a score of 95, but only the first fires. A score of 75 reaches the second rule.
local rules = {
{ when = function(score) return score >= 90 end, ["then"] = function() return "gold" end },
{ when = function(score) return score >= 70 end, ["then"] = function() return "silver" end },
}
local function run(score)
for _, rule in ipairs(rules) do
if rule.when(score) then
return rule["then"]()
end
end
return "none"
end
print(run(95))
print(run(75))No match gives the fallback
A score of 10 matches no rule. The run function returns the fallback instead.
local rules = {
{ when = function(score) return score >= 90 end, ["then"] = function() return "gold" end },
}
local function run(score)
for _, rule in ipairs(rules) do
if rule.when(score) then
return rule["then"]()
end
end
return "none"
end
print(run(10))Example
local rules = {
{ when = function(n) return n >= 90 end, ["then"] = function() return "A" end },
{ when = function(n) return n >= 70 end, ["then"] = function() return "B" end },
{ when = function(n) return n >= 50 end, ["then"] = function() return "C" end },
}
local function grade(n)
for _, rule in ipairs(rules) do
if rule.when(n) then
return rule["then"]()
end
end
return "F"
end
print(grade(95))
print(grade(72))
print(grade(55))
print(grade(30))Key points
- Rule: one table with a when test and a then action.
- When: a function that tests one value and answers true or false.
- Then: a function that builds the result when its rule matches.
- Order: rules run from first to last, and the first match wins.
- Fallback: the result returned when no rule matches.
In this example, the rules list holds three grade rules in order. The grade function walks the list and returns the first matching label. The four printed grades show three matches and the fallback for a score below every rule.
Note
a rule list is data the interpreter walks, so changing the order changes the result.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Rules give gold at 90 or more and silver at 70 or more, in that order. What does a score of 95 return?