How to count words in a variable

Posted by Rene on Tue 03 Oct 2017 12:48 AM — 2 posts, 15,172 views.

#0
I want to count words in a variable to know how many words it contains, I assume it can be done by matching white spaces, assuming the variable is called 'vnum', how would I do that?

Also, how can I break up each word in 'vnum' into a separate value in an array? meaning if 'vnum' is how are you today, the array would be vnum = {"how", "are", "you", "today"}
Thanks!
Australia Forum Administrator #1
You can use string.gmatch, like this:


for w in string.gmatch ("nick takes a stroll", "%a+") do
  print (w)
end -- for


By altering the regular expression (ie. "%a+") you can change what you define a "word" to be (eg. does it include numbers?)

Having done that you can count things (eg, add one to a counter instead of printing).

Similarly you could insert each word into an array.


http://www.gammon.com.au/scripts/doc.php?lua=string.gmatch