Search code examples
stringlualua-patterns

Lua string.find can't find the last word in a line


It's a case in the book programming in Lua. The code is followed, my question is why it can't get the last word of the line?

function allwords()
   local line=io.read()
   local pos=1
   return function ()
      while line do
         local s,e=string.find(line,"%w+ ",pos)
         if s then
            pos=e+1
            return string.sub(line,s,e)   
         else
            line=io.read()
            pos=1
         end
      end
      return nil
   end
end

for word in allwords() do
   print(word)
end

Solution

  • In this line:

    local s,e=string.find(line,"%w+ ",pos)
    --                             ^
    

    There is a whitespace in the pattern "%w+ ", so it matches a word followed by a whitespace. When you input, e.g, word1 word2 word3 and press Enter, word3 has no whitespace following it.

    There is no whitespace in the example of the book:

    local s, e = string.find(line, "%w+", pos)