给定一个带有一些空行的多行字符串,如何迭代Lua中的行,包括空行? local s = "foo\nbar\n\njim"for line in magiclines(s) do print( line=="" and "(blank)" or line)end-- foo-- bar-- (blank)-- jim 此代码不包含空行:
local s = "foo\nbar\n\njim" for line in magiclines(s) do print( line=="" and "(blank)" or line) end --> foo --> bar --> (blank) --> jim
此代码不包含空行:
for line in string.gmatch(s,'[^\r\n]+') do print(line) end --> foo --> bar --> jim
此代码包含额外的虚假空白行:
for line in string.gmatch(s,"[^\r\n]*") do print( line=="" and "(blank)" or line) end --> foo --> (blank) --> bar --> (blank) --> (blank) --> jim --> (blank)试试这个:
function magiclines(s) if s:sub(-1)~="\n" then s=s.."\n" end return s:gmatch("(.-)\n") end