Constraints
Wrap a Lua pattern in () after a param name to restrict which segment values the route will match. The pattern is anchored — the entire segment must match for the route to be selected.
Inline constraint syntax
The full form for a constrained, typed param is: :name(pattern)=type. Each part is optional except :name.
| Form | What it does |
|---|---|
:id(%d+) | Segment must match %d+ — captured as string |
:id(%d+)=number | Must match %d+, then coerced to number |
:action(%a+) | Segment must be letters only — captured as string |
:slug(%w[%w%-]+) | Alphanumeric with hyphens — captured as string |
Examples
-- digits only, raw string
app:Get("user/:id(%d+)", function(req, res)
print(req.params.id) -- "123" — string
end)
-- digits only, coerced to number
app:Get("user/:id(%d+)=number", function(req, res)
print(req.params.id) -- 123 — number
end)
-- lowercase letters only
app:Get("cmd/:action(%a+)", function(req, res)
print(req.params.action) -- "fire", "reload" | rejects "fire2"
end)
-- page number: digits, returned as integer
app:Get("page/:n(%d+)=int", function(req, res)
res:Send({ page = req.params.n })
end)
Common Lua pattern classes
| Class | Matches |
|---|---|
%d | Any digit (0–9) |
%a | Any letter (A–Z, a–z) |
%w | Any alphanumeric (letter or digit) |
%l | Lowercase letter |
%u | Uppercase letter |
%p | Punctuation |
. | Any character |
See the Lua 5.1 pattern reference for the full specification.
Non-match behaviour
When a segment does not satisfy the constraint pattern, the route is skipped entirely — it results in a 404, not a 400. The next route in priority order is tried. This is different from type coercion failure (see below).
=type conversion failed) triggers OnParamError or responds 400 automatically.Interaction with OnParamError
OnParamError is called only when a segment satisfies the Lua pattern but the =type coercion step fails. Use it to customise the error response.
app:OnParamError(function(req, res, paramName, value)
res:Status(422):Send({
error = "Cannot coerce param '" .. paramName .. "': " .. tostring(value)
})
end)
See also
← Router · Named Params | full type annotation list · Wildcards & Globs | unnamed captures · App | OnParamError handler