lua-users home
lua-l archive

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


On Tue, Jun 21, 2011 at 12:04:29PM +0200, Peter Cawley wrote:
> 
> There is one slightly cheeky way to embed Lua patterns in LPeg:
> 
> local function adjust(_, x, ...)
>   if x then
>     return x + 1, ...
>   end
> end
> local function patternToLPeg(p)
>   p = "^".. p:gsub("$$", "$%%$")
>   return require"lpeg".Cmt(0, function(s, i) return
> adjust(string.find(s, p, i)) end)
> end
> 
I just learned something more about LPeg!

Trying out your idea got me to a sore point: Lua patterns are by default
not anchored, LPeg patterns are. 

~~~
> p1="%g+"
> p2="%G*(%g+)"     -- equivalent in Lua to p1 but needlessly complex
> line="   word   "
> return string.match(line,p1)
word
> return (patternToLPeg(p1)/"%1"):match(line)
nil
> return string.match(line,p2)
word
> return (patternToLPeg(p2)/"%1"):match(line)
word
~~~

Dirk