Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
Alex111 Avatar asked Feb 11 '23 15:02

Alex111


1 Answers

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.

like image 192
lhf Avatar answered Feb 13 '23 11:02

lhf