Last active
August 29, 2015 14:05
-
-
Save nsf/e217ad789e3c89f46d5b to your computer and use it in GitHub Desktop.
Lua line iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- 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