lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


This is a perfect example for a coroutine iterator (see chapter 9.3):

The version below looks more contrived but is >10% faster on my system (in lua 5.0.2)

local function allmatches(pattern)
  local lines, linestate, line
  local words, wordstate

  return function(_, word)
    if word then
      word = words(wordstate, word)
    else
      lines, linestate, line = io.lines()
    end

    while not word do
      line = lines(linestate, line)
      if not line then break end
      words, wordstate, word = string.gfind(line, pattern)
      word = words(wordstate, word)
    end

    return word
  end
end


Maybe the linestate/wordstate variables are redundant (didn't check) but it would be cheating to leave them out (and make an assumption on the implementation of io.lines and string.gfind).

--
Wim