应该是:
--space
local a = 1
你不会得到第一个空格,因为 Lua 长字符串会丢弃第一个换行符。
您的问题是您在"[^\n]+" 上的匹配匹配至少一个 字符,该字符不是换行符。空行不匹配(换行符之间没有字符),因此不会显示。
现在您可以将其更改为 "[^\n]*",如下所示:
for Paragraph in string.gmatch(code,"[^\n]*") do
print("Line=", Paragraph)
for Word in string.gmatch(Paragraph, "[^ ]+") do
print ("Word=", Word)
end
end
但这有一个不同的问题:
Line= local a = 1
Word= local
Word= a
Word= =
Word= 1
Line=
Line=
Line= local b = 2
Word= local
Word= b
Word= =
Word= 2
Line=
Line=
空行出现两次!
一个方便的函数遍历一个字符串,一次一行,是这样的:
function getlines (str)
local pos = 0
-- the for loop calls this for every iteration
-- returning nil terminates the loop
local function iterator (s)
if not pos then
return nil
end -- end of string, exit loop
local oldpos = pos + 1 -- step past previous newline
pos = string.find (s, "\n", oldpos) -- find next newline
if not pos then -- no more newlines, return rest of string
return string.sub (s, oldpos)
end -- no newline
return string.sub (s, oldpos, pos - 1)
end -- iterator
return iterator, str
end -- getlines
处理空行。现在您可以像这样编写代码(假设上面的函数在您的代码之前):
for Paragraph in getlines (code) do
print("Line=", Paragraph)
for Word in string.gmatch(Paragraph, "[^ ]+") do
print ("Word=", Word)
end
end
输出:
Line= local a = 1
Word= local
Word= a
Word= =
Word= 1
Line=
Line= local b = 2
Word= local
Word= b
Word= =
Word= 2
Line=
制作一个 Lua 模块
你可以把函数getlines变成一个Lua模块,像这样:
getlines.lua
function getlines (str)
local pos = 0
-- the for loop calls this for every iteration
-- returning nil terminates the loop
local function iterator (s)
if not pos then
return nil
end -- end of string, exit loop
local oldpos = pos + 1 -- step past previous newline
pos = string.find (s, "\n", oldpos) -- find next newline
if not pos then -- no more newlines, return rest of string
return string.sub (s, oldpos)
end -- no newline
return string.sub (s, oldpos, pos - 1)
end -- iterator
return iterator, str
end -- getlines
return getlines
现在你所要做的就是“要求”它:
require "getlines"
for Paragraph in getlines (code) do
print("Line=", Paragraph)
for Word in string.gmatch(Paragraph, "[^ ]+") do
print ("Word=", Word)
end
end