Module:Gtable

From solab
Jump to navigation Jump to search

function fromCSV (s)

 s = s .. ','        -- ending comma
 local t = {}        -- table to collect fields
 local fieldstart = 1
 repeat
   -- next field is quoted? (start with `"'?)
   if string.find(s, '^"', fieldstart) then
     local a, c
     local i  = fieldstart
     repeat
       -- find closing quote
       a, i, c = string.find(s, '"("?)', i+1)
     until c ~= '"'    -- quote not followed by quote?
     if not i then error('unmatched "') end
     local f = string.sub(s, fieldstart+1, i-1)
     table.insert(t, (string.gsub(f, '""', '"')))
     fieldstart = string.find(s, ',', i) + 1
   else                -- unquoted; find next comma
     local nexti = string.find(s, ',', fieldstart)
     table.insert(t, string.sub(s, fieldstart, nexti-1))
     fieldstart = nexti + 1
   end
 until fieldstart > string.len(s)
 return t

end


function table.val_to_str ( v )

 if "string" == type( v ) then
   v = string.gsub( v, "\n", "\\n" )
   if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
     return "'" .. v .. "'"
   end
   return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
 else
   return "table" == type( v ) and table.tostring( v ) or
     tostring( v )
 end

end

function table.key_to_str ( k )

 if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
   return k
 else
   return "[" .. table.val_to_str( k ) .. "]"
 end

end

function table.tostring( tbl )

 local result, done = {}, {}
 for k, v in ipairs( tbl ) do
   table.insert( result, table.val_to_str( v ) )
   done[ k ] = true
 end
 for k, v in pairs( tbl ) do
   if not done[ k ] then
     table.insert( result,
       table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
   end
 end
 return "{" .. table.concat( result, "," ) .. "}"

end