Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local CsvLookup = advancedMacros.inherit()
- local function readHeader( file )
- assert( file, "File handle missing")
- local line = file.readLine()
- local out = {}
- local i = 1
- for a in line:gmatch("[^,]+") do
- out[a] = i
- out[i] = a
- i = i+1
- end
- return out
- end
- local function isQuote(x)
- return x=='"' or x=='"'
- end
- local function xnor(a, b)
- return a and b or not a and not b
- end
- local _new = CsvLookup.new
- function CsvLookup:new( fileName , ...)
- local obj = _new( self )
- assert(filesystem.exists(filename), "Could not find the file!")
- obj.file = filesystem.open(fileName,"r")
- obj.header = readHeader( obj.file )
- obj.data = {}
- return obj
- end
- function CsvLookup:indexFor( propName )
- if not self.file then
- self.file = filesystem.open(fileName,"r")
- self.header = readHeader( obj.file )
- end
- local k = self.header[propName]
- assert( k , "property '"..propName.."' is not defined in the header")
- self.data = {}
- lineNum = 1
- while self.file.available() > 0 do
- local line = self.file.readLine()
- local i = 1
- local x;
- local values = {}
- local t =""
- for a in line:gmatch("[^,]+") do
- if i == k then
- x = a
- else
- --log(self.header[i])
- --log(values)
- t = t..a
- end
- if xnor(isQuote(t:sub(1,1)), isQuote(t:sub(#t, #t))) then
- if i~=k then values[self.header[i]] = t end
- t = ""
- i = i+1
- end
- end
- if #t>0 then error("Unfinished quote on line "..lineNum..":&6"..line) end
- self.data[x] = values
- lineNum = lineNum+1
- end
- self.file.close()
- self.file = nil
- end
- function CsvLookup:find( x )
- return self.data[ x ]
- end
- return CsvLookup
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement