Parsing with Lua Patterns
Lesson 28 of 48 in Coddy's Lua for C Developers course.
C parsing often walks a character buffer, checking delimiters and tracking where a conversion stopped. The example uses strspn to recognize lowercase ASCII letters and digits, then verifies the end of the string. Lua patterns express the same structure compactly. Parentheses capture substrings, + requires at least one character, and the anchors require the entire input to match. Successful captures are strings; use tonumber before numeric calculations. A failed match returns nil. The examples print the captured digit text without converting it.
C
#include <stddef.h>
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "pen=12";
size_t letters = strspn(text, "abcdefghijklmnopqrstuvwxyz");
if (letters > 0 && text[letters] == '=') {
const char *digits = text + letters + 1;
size_t count = strspn(digits, "0123456789");
if (count > 0 && digits[count] == '\0') {
puts(digits);
return 0;
}
}
puts("invalid");
return 0;
}Lua
local name, digits = ("pen=12"):match("^([a-z]+)=([0-9]+)$")
if name then
print(digits)
else
print("invalid")
endPorting trap
Lua patterns are not C formatted-input strings or full regular expressions. Use [0-9] for this explicit ASCII contract, check both anchors, and reject failed matches before attempting arithmetic on a capture.
Challenge
EasyInput is one line. Accept exactly one or more lowercase ASCII letters, an equals sign, and one or more digits. Return name:number with leading numeric zeroes removed, or invalid for any malformed line.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules3Iteration and Flow
Numeric for and Limitswhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsParsing with Lua PatternsModules and requireStatus Codes to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler