[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: String argification
- From: Duncan Cross <duncan.cross@...>
- Date: Sun, 27 Feb 2011 15:49:17 +0000
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'}
>
> ...?
>
> I've had a look at the wiki, as this is a fairly stock problem, but
> don't see anything.
>
Probably not especially cunning, but this is my attempt:
--
function argify(str)
local output = {}
local i = 1 -- current position
local m -- temporary match value
while i <= #str do
i, m = str:match('%s*()(%S)', i)
if not m then -- trailing whitespace
break
end
if m == [["]] then
local j = i + 1
repeat
m, j = str:match('(\\?)"()', j)
if not m then
error('argify: mismatched quote', 2)
end
until (#m == 0)
output[#output+1] = str:sub(i+1,j-2):gsub('\\"', '"')
i = j
else
output[#output+1], i = str:match('(%S+)()', i)
end
end
return output
end
--
-Duncan