[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Matching a fixed number of repetitions in LPeG
- From: Patrick Donnelly <batrick@...>
- Date: Tue, 19 Jun 2012 15:21:28 -0400
On Tue, Jun 19, 2012 at 3:04 PM, Hinrik Örn Sigurðsson
<hinrik.sig@gmail.com> wrote:
> I need to match a fixed number of repetitions of a pattern, so I tried
> the multiply_pattern() function listed in
> http://lua-users.org/wiki/LpegRecipes. However, for me it never
> matches. I also tried the function listed in the referenced blog post,
> with the same result. Has LPeG changed significantly since this was
> written, or am I using it wrong? Here is the code I'm using:
>
> function multiply_pattern(item, count)
> return lpeg.Cmt(lpeg.P(true), function(s, i)
> local set, offset = {}, i
> for j = 1, count do
> set[j], offset = lpeg.match(item * lpeg.Cp(), s, offset)
> if not offset then
> return false
> end
> end
> return offset, set
> end)
> end
>
> print(lpeg.match(lpeg.C(multiply_pattern('a', 2)), 'aa')) --> nil
I think you're overthinking this (you shouldn't need match-time captures). Try:
function power (patt, n)
local p = lpeg.P(true)
for i = 1, n do
p = p * patt
end
return p
end
> print(lpeg.match(lpeg.C(power('a', 2)), 'aa'))
aa
As is usual for a power function, you can achieve logarithmic time if
that optimization is needed.
--
- Patrick Donnelly