csv2array.nut 795 B

123456789101112131415161718192021222324252627
  1. function fromCSV (s){
  2. local t = []; // table to collect fields
  3. local fieldstart = 0;
  4. local slen = s.len();
  5. do {
  6. // next field is quoted? (start with `"'?)
  7. if (s[fieldstart] == '"') {
  8. local i = s.find_close_quote(fieldstart+1);
  9. if (i<0) throw("unmatched \"");
  10. local f = s.slice(fieldstart+1, i);
  11. //print(f);
  12. t.push(f.replace("\"\"", "\""));
  13. local nextc = s.find(",", i);
  14. if(!nextc) nextc=slen-1;
  15. fieldstart = nextc + 1;
  16. }
  17. else // unquoted; find next comma
  18. {
  19. local nexti = s.find(",", fieldstart);
  20. if(!nexti) nexti = slen-1;
  21. //print("nn", s.slice(fieldstart, nexti))
  22. t.push(s.slice(fieldstart, nexti));
  23. fieldstart = nexti + 1;
  24. }
  25. } while(fieldstart < slen);
  26. return t;
  27. }