Lua的string.find无法找到一行中的最后一个单词。

4

这是书籍《Lua编程》中的一个案例。以下是代码,我的问题是为什么它无法获取行的最后一个单词?

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
2个回答

4
在这一行中:
local s,e=string.find(line,"%w+ ",pos)
--                             ^

在模式"%w+ "中有一个空格,因此它匹配一个单词后跟一个空格。当您输入例如word1 word2 word3并按下Enter时,word3后面没有空格。

在书本的例子中没有空格:

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

1

非常抱歉,我“复活”了这个问题,但我认为我有一个更好的解决方案。

不要使用你的allwords函数,你可以这样做:

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

这个函数

gmatch("%S+")

返回字符串中的所有单词。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接