lua-users home
lua-l archive

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


Hi,

I'm using LPeg to convert a string into a Lua table with named key-value pairs
for the various fields. Basically it goes something like this:
  
the code

  space = P" "^0
  token = (R"az")^1 
  header = Ct(Cg(token, "first") * space * Cg(token, "second"))

converts

   "foo bar"

to the Lua table

   { first = "foo", second = "bar" }

In addition to the 'first' and 'second' parts, I would also like to
capture the whole string into a separate table entry, so the result
would be something like

   { first = "foo", second = "bar", org = "foo bar" }

or maybe
   
   { org = "foo bar", parts = { first = "foo", bar = "bar" } }

My first naive approach was to nest the Cg calls like

   header = Ct(Cg(Cg(token, "first") * space * Cg(token, "second"), "org"))

but this fails because the outer Cg "org" seems to overrule the inner Cg's.


Is there a way to make LPeg behave like this ?

Thank you,

Ico



Rationale: The real code is for parsing SIP messages into a Lua data structure.
For example, the SIP 'From' header

   From: "Alice noddle" <sip:alice@atlanta.com>;tag=1928301774

gets parsed into the table

  headers = {
    ...,
    4 = {
      "name" = "From", 
      "value" = {
        "host" = "atlanta.com", 
        "display_name" = "Alice noddle", 
        "user" = "alice", 
        "param" = {
          1 = {
            "key" = "tag", 
            "value" = "1928301774"
          } 
        } 
      } 
    },
    ...
  }

The problem is that apart from the picked-apart header fields, I also need to
store the complete header in its original form for other uses. Of course I can
parse the messages two times using two different parses - one for the details
and one for the complete headers - but it would be nice to get things done in
one parser of course.

Thank you,

Ico

-- 
:wq
^X^Cy^K^X^C^C^C^C