4

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
mynameistechno
  • 3,526
  • 1
  • 37
  • 32
hkk
  • 45
  • 5

2 Answers2

4

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)
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

Sorry for, uh, "resurrecting" this question, but I think I have a better solution.

Instead of using your allwords function, could you not just do this:

for word in io.read():gmatch("%S+") do
   print(word)
end

The function

gmatch("%S+")

returns all the words in a string.

warspyking
  • 3,045
  • 4
  • 20
  • 37