2015-02-11 33 views
3

這是Lua書籍編程中的一個案例。代碼被遵循,我的問題是爲什麼它不能得到該行的最後一句話?Lua string.find在一行中找不到最後一個字

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 

回答

4

在這一行:

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

有一個在圖案"%w+ "一個空白,所以一個字後跟一個空格匹配。輸入時,例如word1 word2 word3並按輸入word3後面沒有空格。

有書中的例子中,沒有空白:

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

對不起,我,嗯,「復活」這個問題,但我想我有一個更好的解決方案。

而不是使用您的allwords功能,你能不能只是這樣做:

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

功能

gmatch("%S+") 

返回在一個字符串的話。

相關問題