functions.lua 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. minerdream.has_value = function(tab, val)
  2. -- test if val is in tab
  3. for index, value in ipairs(tab) do
  4. if value == val then
  5. return true
  6. end
  7. end
  8. return false
  9. end
  10. local has_value=minerdream.has_value
  11. -- read table "infile" where in "def" is defined, which cols are numbers and which belongs to a group
  12. minerdream.import_csv = function(infile,def)
  13. local file = io.open(infile, "r")
  14. local outdata = {}
  15. -- reading header with column names
  16. local splitchar=","
  17. if def.seperator then
  18. splitchar=def.seperator
  19. end
  20. local header = file:read():gsub("\r",""):split(splitchar,true)
  21. -- read each line, split in separat fields and stores in array
  22. -- by header the value is stored as numeric, in the group environment or as text
  23. for line in file:lines() do
  24. local attribs = line:gsub("\r",""):split(splitchar,true)
  25. local nrow={groups={}}
  26. for i,d in ipairs(attribs) do
  27. if d ~= "" then
  28. local th=header[i]
  29. local dsaved = false
  30. if def.col_num then
  31. if has_value(def.col_num,th) then
  32. nrow[th] = tonumber(d)
  33. dsaved = true
  34. end
  35. end
  36. if def.groups_num then
  37. if has_value(def.groups_num,th) then
  38. nrow.groups[th]=tonumber(d)
  39. dsaved = true
  40. end
  41. end
  42. if not dsaved then
  43. nrow[th]=d
  44. end
  45. end
  46. end
  47. if nrow.name then
  48. outdata[nrow.name] = nrow
  49. else
  50. outdata[#outdata+1] = nrow
  51. end
  52. end
  53. file:close()
  54. return outdata
  55. end