Skip to content

Instantly share code, notes, and snippets.

@nsf
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save nsf/e217ad789e3c89f46d5b to your computer and use it in GitHub Desktop.

Select an option

Save nsf/e217ad789e3c89f46d5b to your computer and use it in GitHub Desktop.
Lua line iterator
-- Iterate over all lines in `text`, use it like this (handles only
-- plain "\n", not "\r\n"):
-- for line_num, line in Lines(text) do
-- -- line_num - number of the line, starting from 1
-- -- line - contents of the line without "\n"
-- end
local function Lines(text)
local function next_line(state)
local text, begin, line_n = state[1], state[2], state[3]
if begin < 0 then
return nil
end
state[3] = line_n + 1
local b, e = text:find("\n", begin, true)
if b then
state[2] = e+1
return line_n, text:sub(begin, e-1)
else
state[2] = -1
return line_n, text:sub(begin)
end
end
local state = {text, 1, 1}
return next_line, state
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment