Here is a solution using LPEG:
local lpeg = require "lpeg"
local lpegmatch = lpeg.match
local P, C = lpeg.P, lpeg.C
local iterlines
do
local eol = P"\r\n" + P"\n\r" + P"\n" + P"\r"
local line = (1 - eol)^0
iterlines = function (str, f)
local lines = ((line / f) * eol)^0 * (line / f)
return lpegmatch (lines, str)
end
end
What you get is a function that can be used instead of an iterator. Its first argument is the line you want to repeat, the second is the action for each match:
--- print each line
iterlines ("foo\nbar\n\njim\n\r\r\nbaz\rfoo\n\nbuzz\n\n\n\n", print)
--- count lines while printf
local n = 0
iterlines ("foo\nbar\nbaz", function (line)
n = n + 1
io.write (string.format ("[%2d][%s]\n", n, line))
end)
source
share