0

I tried doing this by myself, and all I figured out was how to split the string into several lines:

local line = "Hello my name is Name"
for token in string.gmatch(line, "[^%s]+") do
   print(token)
end

This would result in:

Hello  
my  
name  
is  
Name

Which is not what I need. Any suggestions?

1 Answers1

0

If you want to retain every non whitespace token, you could just add each match to an array:

t = {}
line = "Hello my name is Name"
i = 1
for token in string.gmatch(line, "%S+") do
    t[i] = token
    print(t[i])
    i = i + 1
end

Note that the print output here is the same as the code snippet you already have, but the above code actually saves each separate token in an array.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • @lhf Good suggestions, I have edited my answer. – Tim Biegeleisen Mar 23 '21 at 13:16
  • Sorry for the nitpicking. When there are no words in the string, the value of `i` after the loop is 1, but should be 0, in case you want to use `i`. So, start with ì=0` and increment before assigning to `t[i]`. – lhf Mar 23 '21 at 13:19