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 Andrew Gierth once stated:
> >>>>> "Sean" == Sean Conner <sean@conman.org> writes:
>
>  Sean> I'd like the output to be:
>
>  Sean> foo -t application/x-foo /tmp/bar.foo   false
>  Sean> bar -t application/x-bar        true
>
> My solution:
>
> local lpeg = require "lpeg"
>
> local P,R = lpeg.P, lpeg.R
> local Carg,Cc,C,Cg,Ct,Cs = lpeg.Carg, lpeg.Cc, lpeg.C, lpeg.Cg, lpeg.Ct, lpeg.Cs
>
> local char = P"%s" * Carg(1) * Cg(Cc(true),'noredirect')
>            + P"%t" * Carg(2)
>            + C(P"%")  -- I'm guessing a P"%%" * Cc"%" is missing here
>            + C((R" ~" - P"%")^1)
>
> local cmd  = Ct( char^1 )
>
> t = cmd:match("foo -t %t %s",1,"/tmp/bar.foo","application/x-foo")
> print(table.concat(t), not t.noredirect)
> t = cmd:match("bar -t %t",   1,"/tmp/foo.bar","application/x-bar")
> print(table.concat(t), not t.noredirect)

  That's a nice solution and it lends itself to an easy way to support
redirection if required:

        t = cmd:match(cmdstring,1,filename,type)
        if not t.noredirect then
          table.insert(t,string.format("< %s",filename))
        end
        print(table.concat(t),not t.noredirect)

  The only change I'd make is to remove the double negation aspect of it.

        local char = P"%s" * Carg(1) * Cg(Cc(false),'redirect')
                   + ...
        local cmd = Ct(Cg(Cc(true),'redirect') * char^1)

  Unless that too, is technically undefined per the LPeg spec (I hope
not---I use that idiom [1] quite often).

  -spc (Because I was taught don't use no double negatives ... )

[1]     Of setting a table field to a defined value before parsing the rest
        of the string.