Use gmatch with a simple pattern when you need to count repeated matches.

repeated matches `gmatch` continues after each match and stops when no more matches are found.

Count Matches

text
count_matches.lua
Replay: real traced execution (multi-file project)
local text = "one two one"
local count = 0

for _ in string.gmatch(text, "one") do
  count = count + 1
end

print("text=" .. text)
print("count=" .. count)
local text = "two two one"
local count = 0

for _ in string.gmatch(text, "one") do
  count = count + 1
end

print("text=" .. text)
print("count=" .. count)
local text = "one"
local count = 0

for _ in string.gmatch(text, "one") do
  count = count + 1
end

print("text=" .. text)
print("count=" .. count)
  1. text ← one two one, count ← 0

    1local text→ one two one = "one two one" --@text="two two one", "one"2local count→ 0 = 0
  2. count ← 1

    pass 1 of 2
    4for _one in string.gmatch(textone two one, "one") do5  count→ 1 = count + 16end
  3. count ← 2

    pass 2 of 2
    4for _one in string.gmatch(textone two one, "one") do5  count→ 2 = count + 16end
  4. print("text=" .. text)

    8print("text=" .. textone two one)9print("count=" .. count2)
    outputtext=one two one
    count=2
  1. text ← two two one, count ← 0

    1local text→ two two one = "two two one"2local count→ 0 = 0
  2. count ← 1

    4for _one in string.gmatch(texttwo two one, "one") do5  count→ 1 = count + 16end
  3. print("text=" .. text)

    8print("text=" .. texttwo two one)9print("count=" .. count1)
    outputtext=two two one
    count=1
  1. text ← one, count ← 0

    1local text→ one = "one"2local count→ 0 = 0
  2. count ← 1

    4for _one in string.gmatch(textone, "one") do5  count→ 1 = count + 16end
  3. print("text=" .. text)

    8print("text=" .. textone)9print("count=" .. count1)
    outputtext=one
    count=1