One problem with Shmuel's solution quoted above is that it
treats the first of the above two strings as four lines, the
last being empty. If you want to treat both of them as
three lines, you need to do something like this:
if string.sub(Str, -1) ~= "\n" then
-- The last line doesn't have an EOL; give it one:
Str = Str .. "\n"
end
for Line in Str:gmatch("([^\n]*)\n") do
print("line: <" .. Line .. ">")
end
or this (doesn't side-effect Str):
local MissingEol = false
if string.sub(Str, -1) ~= "\n" then
-- The last line doesn't have an EOL; give it one:
MissingEol = true
end
for Line in (MissingEol and Str .. "\n" or Str):gmatch("([^\n]*)\n") do
print("line: " .. Line)
end
This is impossible to do with just a single pattern and no
additional checks, but using string.sub avoids a linear scan
of the string. (In other words, don't use Str:match("\n$").)