lua-users home
lua-l archive

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


It was thus said that the Great Daurnimator once stated:
> On 23 October 2017 at 14:36, Sean Conner <sean@conman.org> wrote:
> >   I'm thinking there's not anything that Lua patterns do that you can't do
> > in LPeg
> 
> I did once sit down and rewrite the lua pattern matching functions using lpeg.
> 
> If I recall correctly, the only thing I couldn't figure out was the
> `n` argument to string.gsub.

  Did you try using LPeg's patt^-n?  Where the pattern you generated is only
run up to n times?  Something along:

	function mygsub(s,luapattern,repl,n)
	  n          = n or math.huge
	  local patt = convert(luapattern,repl)
	  
	  patt = lpeg.Cs(
		   (
		     (lpeg.P(1) - patt)^0 -- skip portion that doesn't match
		     * patt               -- do that pattern
		   )^-n                   -- do it up to n times
	           * lpeg.P(1)^0          -- return rest of string if any
	  )
	  return patt:match(s)
	end

  -spc (Totally untested, not sure if it will even work, yada yada ... )