lua-users home
lua-l archive

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


In message <AANLkTik+YwMPNiPJfmuSBRD4NvOOynxkEX5ZsCOnr76y@mail.gmail.com> you wrote:

> On Sun, Feb 27, 2011 at 3:07 PM, David Given <dg@cowlark.com> wrote:
> > Does anyone have a cunning piece of pure-Lua code for argifying a
> > string? That is, turning this:
> >
> >        foo bar "baz bloo \"fnord" wibble
> >
> > into this:
> >
> >        {'foo', 'bar', 'baz bloo "fnord', 'wibble'}

Here is an lpeg solution. Excuse small dialectal differences (RiscLua):

require "lpeg"
do
 local the = \(kind,x)
  local fmt,y = "expecting %s but got %s",type(x)
  assert(y==kind,fmt:format(kind,y))
  => x end
 local match,P,C,Ct in lpeg
 local sp,quote,esc = P [[ ]],P [["]],P [[\"]]
 local strip = \(s) => s:gsub([[\"]],[["]]) end
 local word = C((1-sp-quote)^1)
 local quoted = quote*C((esc + (1 - quote))^1)*quote
 local item = (quoted/strip)+word
 local pat = Ct(item*((sp^1)*item)^0)
 argify = \(str) => the("table",pat:match(str)) end
end
-- 
Gavin Wraith (gavin@wra1th.plus.com)
Home page: http://www.wra1th.plus.com/