Advertisement
TheIncgi

CSV Lookup

Nov 11th, 2019
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.73 KB | None | 0 0
  1. local CsvLookup = advancedMacros.inherit()
  2.  
  3. local function readHeader( file )
  4.   assert( file, "File handle missing")
  5.   local line = file.readLine()
  6.   local out = {}
  7.   local i = 1
  8.   for a in line:gmatch("[^,]+") do
  9.     out[a] = i
  10.     out[i] = a
  11.     i = i+1
  12.   end
  13.   return out
  14. end
  15.  
  16. local function isQuote(x)
  17.   return x=='"' or x=='"'
  18. end
  19.  
  20. local function xnor(a, b)
  21.   return a and b or not a and not b
  22. end
  23.  
  24. local _new = CsvLookup.new
  25. function CsvLookup:new( fileName , ...)
  26.   local obj = _new( self )
  27.   assert(filesystem.exists(filename), "Could not find the file!")
  28.   obj.file = filesystem.open(fileName,"r")
  29.   obj.header = readHeader( obj.file )
  30.   obj.data = {}
  31.   return obj
  32. end
  33.  
  34. function CsvLookup:indexFor( propName )
  35.   if not self.file then
  36.     self.file = filesystem.open(fileName,"r")
  37.     self.header = readHeader( obj.file )
  38.   end
  39.   local k = self.header[propName]
  40.   assert( k , "property '"..propName.."' is not defined in the header")
  41.   self.data = {}
  42.   lineNum = 1
  43.   while self.file.available() > 0 do
  44.     local line = self.file.readLine()
  45.     local i = 1
  46.  
  47.     local x;
  48.     local values = {}
  49.     local t =""
  50.     for a in line:gmatch("[^,]+") do
  51.       if i == k then
  52.         x = a
  53.       else
  54.         --log(self.header[i])
  55.         --log(values)
  56.         t = t..a
  57.       end
  58.       if xnor(isQuote(t:sub(1,1)), isQuote(t:sub(#t, #t)))  then
  59.         if i~=k then values[self.header[i]] = t end
  60.         t = ""
  61.         i = i+1
  62.       end
  63.     end
  64.     if #t>0 then error("Unfinished quote on line "..lineNum..":&6"..line) end
  65.     self.data[x] = values
  66.     lineNum = lineNum+1
  67.   end
  68.   self.file.close()
  69.   self.file = nil
  70. end
  71.  
  72.  
  73. function CsvLookup:find( x )
  74.   return self.data[ x ]
  75. end
  76.  
  77. return CsvLookup
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement