Patterns Instead of Regex
Lesson 28 of 48 in Coddy's Lua for GDScript Developers course.
Godot offers RegEx for regular expressions. Lua's built-in string matching uses a smaller pattern language with different syntax. For an ASCII inventory line, ^([a-z]+)=([0-9]+)$ works in both examples, capturing the label and digits. The anchors require the entire line to match. Lua string.match returns the captures directly, or nil on failure; Godot returns a RegExMatch object whose captured groups are read with get_string. Convert the captured digits before displaying their numeric value to remove leading zeroes. Do not assume that every Godot regular expression has a direct Lua-pattern translation.
GDScript 4
extends SceneTree
func _init():
var regex = RegEx.new()
regex.compile("^([a-z]+)=([0-9]+)$")
var found = regex.search("potion=007")
if found != null:
print(found.get_string(1) + ":" + str(int(found.get_string(2))))
else:
print("invalid")
quit()Lua 5.1
local name, digits = string.match("potion=007", "^([a-z]+)=([0-9]+)$")
if name then
print(name .. ":" .. tonumber(digits))
else
print("invalid")
endPorting trap
Lua patterns use %d for a digit class, not the regex escape \d. The explicit ASCII class [0-9] avoids that syntax difference here.
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 GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules3Iteration and Flow
Ranges to Numeric forwhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsPatterns Instead of RegexScripts to requireError Results and pcallRecap: Validate a BatchPractice on your own: Online Lua compiler