Parsing with Lua Patterns
Lesson 28 of 48 in Coddy's Lua for Go Developers course.
Go regexp uses regular expressions and returns a slice of submatches or nil for no match. Lua patterns are a smaller language using percent classes and returning captures directly. Anchor the accepted grammar and check failure before reading captured values. Do not copy regular-expression escapes or features into a Lua pattern unchanged.
Go
package main
import ("fmt"; "regexp")
func main(){
m:=regexp.MustCompile(`^([a-z]+)=([0-9]+)$`).FindStringSubmatch("pen=12"); fmt.Println(m[2])
}
Lua
local name, digits = ("pen=12"):match("^([a-z]+)=([0-9]+)$")
if name then
print(digits)
else
print("invalid")
endPorting trap
Use Lua pattern syntax and handle nil when matching fails.
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 Go 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