typestar

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

  1. gmatch iterates every match; captures unpack in the loop.
  2. match pulls the first capture out directly.
  3. gsub rewrites and reports how many times.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Patterns & errors, step 20 of 27 in Language basics.

← Previous Next →

Patterns in other languages