lua-users home
lua-l archive

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

Another interesting iterator is this:

  -- generate substrings (bad name...)
  function gensub (s, p)
    local i=1
    return function ()
      local res = {strfind(s, p, i)}
      if res[1] == nil then return nil end
      tremove(res, 1)               -- remove 1st result from strfind,
      i = tremove(res, 1) + 1       -- remove 2nd result,
      return unpack(res)            -- and return only the captures

Then you can transform gsub loops into for loops:

  s = "peter paul mary"

  for w in gensub(s, "(%w+)") do print(w) end

-- Roberto