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 Johann ''Myrkraverk'' Oskarsson once stated:
> On 3/6/2023 7:10 AM, Sean Conner wrote:
> >
> >You can also tighten up p.instruction to read:
> >
> >	p.instruction = lpeg.R("az","AZ")^1
> 
> Thank you.  

  You're welcome.

> All of that works -- and has for weeks -- but now I have
> another question, that wasn't immediately obvious from the manual
> either.
> 
> When I use lpeg.Ct() to create a table of parsed objects, can I put
> arbitrary Lua values in the table?  More specifically, if I want to
> have the LPEG parser put the numeric value of lpeg.R( "09" ) matches,
> is that doable?  We can leave aside the issue of matches that don't fit
> in a Lua number for the moment; I'm pretty sure it's easy enough to
> handle.

  Yes, and there are a few ways of doing so.

  The first (I'm eluding the leading "lpeg." as it clutters up the example):

	pattern1 = Ct(C(R"09"^1"))
	x = pattern1:match("123")

will return the following table:

	{ 123 }

However, we can also do:

	pattern2 = Ct(Cg(R"09"^1,'result'))
	y = pattern2:match("456")

will return the following table:

	{ result = 456 }

  Here's a slightly larger example that will parse data like:

	<id> [ <count> ] LF

where if the number is missing, it's assumed to be 1, then we can do like:

        SP      = P" "
        LF      = P"\n"
        id      = R"az"^1
        num     = R"09" / tonumber
        record  = Ct(
                      Cg(Cc(1),'count') -- default count
                    * Cg(id,'id') 
                    * (SP * Cg(num,'count'))^-1 -- optional
                ) * LF
        records = Ct(record^1) -- at least one record

	x = records:match "alpha\nbeta 4\n"

	x =
	{
	  [1] =
	  {
	    count = 1.000000,
	    id = "alpha",
	  },
	  [2] =
	  {
	    count = 4.000000,
	    id = "beta",
	  },
	}

  If you remove the line with 'default count' on it, then the first element
of the array will only have the id field, and count will be missing.  

  I hope this example helps some.

  -spc