lua-users home
lua-l archive

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


> I'm trying to implement line parsing in Lua.
> Line syntax is similar to shell one, where double quotes protect words in
> them to be splitted.
> 
> <word> [<word> <"word with spaces"> ...]
> 
> I want to parse the line into Lua table where fields are line words.
> For example:
> 
> cmd first-arg "second arg" 3
> 
> should be converted into table t
> t.1 = 'cmd' t.2 = 'first-arg', t.3='second arg', t.4='3'
> 
	You can substitute spaces between a pair of `"' by another character
then split the string using spaces as separators and reconstructing the
original spaces:

function parse (s)
    local t = {}
    s = gsub(s,'"([^"]*)"',function(str) return gsub(str,' ','\1') end)
    s = gsub(s,'(%S+)', function (str)
        local s=gsub(str,'\1',' ')
        tinsert(%t,s)
    end)
    return t
end

	Tomas