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.
How to count the amount of words in a text file in Lua
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.
© 2022 - 2024 — McMap. All rights reserved.
string.gfind
has been renamedstring.gmatch
since then. – Hwahwanstring.gfind
– Originality