19

I'm trying to count the number of times that " --" occurs in a string.

So for instance, it occurs twice here 'a --b --c'

I tried the following, but it gives me 4 instead of 2, any idea why?

argv='a --b --c'
count = 0
for i in string.gfind(argv, " --") do
   count = count + 1
end
print(count)
Yaroslav Bulatov
  • 57,332
  • 22
  • 139
  • 197

3 Answers3

38

you can actually do this as a one-liner using string.gsub:

local _, count = string.gsub(argv, " %-%-", "")
print(count)

no looping required!

Not recommended for large inputs, because the function returns the processed input to the _ variable, and will hold onto the memory until the variable is destroyed.

Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49
  • 8
    Instead of using a dummy variable, [select](https://www.lua.org/manual/5.3/manual.html#pdf-select) can discard the first returned value, the string with substitutions, which reduces the memory footprint. – WD40 Mar 23 '18 at 17:30
17

This snippet could be helpful, based on response of Mike Corcoran & optimisation suggestion of WD40

function count(base, pattern)
    return select(2, string.gsub(base, pattern, ""))
end

print(count('Hello World', 'l'))
Abhishek Kumar
  • 171
  • 2
  • 4
12

The - character has special meaning in patterns, used for a non-greedy repetition.

You need to escape it, i.e. use the pattern " %-%-".

interjay
  • 107,303
  • 21
  • 270
  • 254