Given a multiline string with some blank lines, how can I iterate over lines in Lua including the blank lines?
local s = "foo\nbar\n\njim"
for line in magiclines(s) do
print( line=="" and "(blank)" or line)
end
--> foo
--> bar
--> (blank)
--> jim
This code does not include blank lines:
for line in string.gmatch(s,'[^\r\n]+') do print(line) end
--> foo
--> bar
--> jim
This code includes extra spurious blank lines:
for line in string.gmatch(s,"[^\r\n]*") do
print( line=="" and "(blank)" or line)
end
--> foo
--> (blank)
--> bar
--> (blank)
--> (blank)
--> jim
--> (blank)
Try this:
function magiclines(s)
if s:sub(-1)~="\n" then s=s.."\n" end
return s:gmatch("(.-)\n")
end