lua-users home
lua-l archive

Re: Code Request: CSV parser written in Lua

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


Follows my code for this task (I had it already). CSV is not an easy task 
for Lua, mostly because of the '""' rule (a "" inside quotes is a single 
quote, but outside quotes this is simply the empty string). It would be 
much simpler if it used a conventional escape mechanism (such as '\"'). 
 function fromCSV (s)
 s = s..',' -- ending comma
 local t = {n=0} -- table to collect fields
 local fieldstart = 1
 repeat
 if strfind(s, '^"', fieldstart) then -- quoted field?
 local a, c
 local i = fieldstart
 repeat
 a, i, c = strfind(s, '"("?)', i+1) -- find closing quote
 until c ~= '"' -- repeat if quote is followed by quote
 if not i then error('unmatched "') end
 tinsert(t, gsub(strsub(s, fieldstart+1, i-1), '""', '"'))
 fieldstart = strfind(s, ',', i) + 1
 else -- unquoted; find next comma
 local nexti = strfind(s, ',', fieldstart)
 tinsert(t, strsub(s, fieldstart, nexti-1))
 fieldstart = nexti+1
 end
 until fieldstart > strlen(s)
 return t
 end
-- Roberto

AltStyle によって変換されたページ (->オリジナル) /