Search code examples
stringcountluacpu-wordread-write

How to count the amount of words in a text file in Lua


I was wanting to ask what the steps are to creating a Lua program that would count the amount of words in a .txt file? I'm only familiar with how to count characters and not strings.


Solution

  • A sequence of nonspace characters is a good approximation to what a word is.

    In that case, this simple code counts the words in a string s:

    _,n = s:gsub("%S+","")
    print(n)
    

    This works because gsub returns the number of substitutions made as a second result. This count is rarely used, and sometimes even a minor annoyance, but in this case it's exactly what is needed.