lua-users home
lua-l archive

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




On Thu, Sep 15, 2016 at 8:47 AM, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:


The manual says about 'Cmt':

   Unlike all other captures, this one is evaluated immediately when a
   match occurs. It forces the immediate evaluation of all its nested
   captures and then calls function.

This is the only capture that specifies *when* (and *if*) it runs. It
is the only one where you can count on side effects.

-- Roberto


I found a use for this property which is worth sharing:

local function Csp (patt)
return lpeg.Cp() 
* lpeg.Cmt(patt, function() return true end) 
* lpeg.Cp() 
* lpeg.Carg(1)  / spanner
end

This captures the index before and after a given value. Carg(1) is a second reference to the string being parsed by match(), spanner() creates and returns a table containing the captured substring and the indices as t.val, t.first, and t.last, respectively.

cheers,
-Sam.