Module:ParseCSV

From Against the Storm Official Wiki
Revision as of 16:30, 10 June 2023 by Aeredor (talk | contribs) (Created so we can upload the CSV data (like into Module:GoodsCSV and others) and parse it automatically)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:ParseCSV/doc

--- Module for parsing CSV data into a Lua table.
-- @module ParseCSV
local ParseCSV = {}



--- Parses the CSV data and returns the header and rows as a Lua table.
-- @tparam string csvString The CSV data to be parsed.
-- @treturn table The header of the CSV data.
-- @treturn table The rows of the CSV data.
function ParseCSV.parseCSV(csvString)

    -- Check for an end-of-file comma
    if csvString:sub(-1) == ',' then
        csvString = csvString:sub(1, -2) -- Remove the trailing comma
    end
	
    local header = nil
    local rows = {}

    -- Separate the csv data into lines/rows by gmatch'ing on carriage returns 
	-- and/or newlines
    for line in csvString:gmatch("[^\r\n]+") do
        
		-- the first line will be the header, after we build it, everything else
		-- goes into the rows table
		if not header then
		
			-- we started with nil, so replace nil with a blank table
            header = {}

			-- Separate the rows into fields by gmatch'ing on commas
			for field in line:gmatch("[^,]+") do
				-- append the last-matched field (value) to the header table
				table.insert(header, field)
			end
			
			-- there is only one row in the header table, so we don't need to do
			-- anything else
			
		else
			-- build each line separately as a new table
            local row = {}
			
            for field in line:gmatch("[^,]+") do
				-- append the last-matched field (value) to the row table
                table.insert(row, field)
            end
			
			--append the constructed row to the rows table
            table.insert(rows, row)
        end
		
    end -- for each line

    -- Return the header and the rows data table
    return header, rows
	
end -- parseCSV function



return ParseCSV