lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 11/7/06, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> Counting matches instead of replacements IMHO is simpler to understand
> and use. It also provides an easy way to count how many times a given
> pattern occur in a string.
>
> path= "/many/nested/directories"
> _,n= path:gsub("/",{})  -- n counts "/" chars

I do agree that it is simpler, and that is the main reason we chose it.
But I am not sure it is "better". You can use other options for this
code, like

  _,n= path:gsub("/","")

On the other hand, counting only replacements allow some interesting
tricky counts:

  -- count number of reserved words in string
  _,n = string.gsub(s, "%w", {[while] = true, [for] = true, ...})


-- Roberto

Indeed, counting replacements is more powerful than counting mere matches.
BTW, is "+" missing from the search pattern? I think it should be

_,n = string.gsub(s, "%w+", {[while] = true, [for] = true, ...})

--Leo--