Patterns in Lua
Lua's own matching: %d, %a, captures, gmatch, gsub.
-- Lua patterns: %d digits, %a letters, captures in parentheses.
local log = "found 3 gems, 45 gold, 1 idol"
for count, thing in log:gmatch("(%d+) (%a+)") do
print(thing .. " x" .. count)
end
-- match pulls one capture; gsub rewrites and counts.
local first = log:match("%d+")
print("First number: " .. first)
local shouted, hits = log:gsub("gold", "GOLD")
print(shouted)
print("Replacements: " .. hits)
How it works
gmatchiterates every match; captures unpack in the loop.matchpulls the first capture out directly.gsubrewrites and reports how many times.
Keywords and builtins used here
doendforgmatchgsubinlocalmatchprint
The run, in numbers
- Lines
- 14
- Characters to type
- 406
- Tokens
- 81
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 81 seconds.
Step 1 of 3 in Patterns & errors, step 20 of 27 in Language basics.