lua-users home
lua-l archive

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


On Sun, Feb 27, 2011 at 4: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'}
>

"hide escaped quotes - hide quoted spaces - split - reveal hidden
quotes and spaces in elements":

function argify(s)
  local out = {}
  -- see http://www.lua.org/pil/20.4.html for encode/decode
  string.gsub(
         string.gsub(s, "\\(.)", function (x)
              return string.format("\\%03d", string.byte(x))
            end),
         "[\"]([^\"]*)[\"]",
         function(m) return m:gsub(" ", "\\032") end):
             gsub("([^%s]+)%s*", function(m)
                 table.insert(out, (m:gsub("\\(%d%d%d)",
                    function (d) return string.char(d) end)))
                 end)
  return out
end

cheers,
andrew