[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: extension to string.gmatch (structural regular expressions)
- From: Norman Ramsey <nr@...>
- Date: Thu, 03 Jan 2008 16:40:08 -0500
 > Here's a first attempt at a splitting gmatch: [quoted below]
Not bad but I think you return the extra position matched by the
final ().  Mostly harmless.
You can also ditch the coroutines and simply do
    return function() return aux(gm()) end
Norman
 > function string.gmatchsplit(text, pattern)
 >     local gm = text:gmatch("()" .. pattern .. "()")
 >     local start = 1
 >     local function aux(...)
 >         if start == nil then
 >             return nil
 >         end
 >         local caps = select('#', ...)
 >         if caps == 0 then
 >             local finalpart = text:sub(start)
 >             start = nil
 >             return finalpart
 >         end
 >         local stop = (...) - 1
 >         local before = text:sub(start,stop)
 >         start = select(caps, ...)
 >         return before, select(2, ...)
 >     end
 >     return coroutine.wrap(
 >         function()
 >             while true do
 >                 coroutine.yield( aux(gm()) )
 >             end
 >         end
 >     )
 > end
 > 
 > for part in string.gmatchsplit("one<delim>two<delim>three", "<delim>") do
 >    print(part)
 > end