Skip to content

CSV

The CSV Parser library provides functions to parse CSV (Comma-Separated Values) data and manipulate CSV-like tables in Lua.

Functions

csv.parse(csvString, delimiter)

Parses a CSV string into a Lua table.

  • csvString: A string containing CSV data.
  • delimiter: (optional) The delimiter character. Defaults to ,.

Returns a table of tables, where each inner table represents a row in the CSV.

local csvData = "Name,Age,City\nAlice,30,New York\nBob,25,Los Angeles"
local parsed = csv.parse(csvData)

csv.stringify(table, delimiter)

Converts a Lua table to a CSV string.

  • table: A table of tables representing CSV data.
  • delimiter: (optional) The delimiter character. Defaults to ','.

Returns a string in CSV format.

local data = {
    {"Name", "Age", "City"},
    {"Alice", "30", "New York"},
    {"Bob", "25", "Los Angeles"}
}
local csvString = csv.stringify(data)

csv.getField(csvTable, row, col)

Retrieves a specific field from a parsed CSV table.

  • csvTable: A table returned by csv.parse.
  • row: The row index (1-based).
  • col: The column index (1-based).

Returns the value at the specified row and column.

local value = csv.getField(parsed, 2, 1)  -- Gets "Alice"

csv.getRow(csvTable, row)

Retrieves an entire row from a parsed CSV table.

  • csvTable: A table returned by csv.parse.
  • row: The row index (1-based).

Returns a table representing the specified row.

local row = csv.getRow(parsed, 2)  -- Gets {"Alice", "30", "New York"}

Examples

Parsing CSV Data

local csvData = "Name,Age,City\nAlice,30,New York\nBob,25,Los Angeles"
local parsed = csv.parse(csvData)

for i, row in ipairs(parsed) do
    print("Row " .. i .. ":")
    for j, value in ipairs(row) do
        print("  Column " .. j .. ": " .. value)
    end
end

Creating and Stringifying CSV Data

local data = {
    {"Name", "Age", "City"},
    {"Alice", "30", "New York"},
    {"Bob", "25", "Los Angeles"}
}

local csvString = csv.stringify(data)
print(csvString)

Using Custom Delimiter

local tsvData = "Name\tAge\tCity\nAlice\t30\tNew York\nBob\t25\tLos Angeles"
local parsed = csv.parse(tsvData, '\t')

local tsvString = csv.stringify(parsed, '\t')
print(tsvString)

Accessing Specific Fields

local csvData = "Name,Age,City\nAlice,30,New York\nBob,25,Los Angeles"
local parsed = csv.parse(csvData)

local name = csv.getField(parsed, 2, 1)  -- Gets "Alice"
local age = csv.getField(parsed, 2, 2)   -- Gets "30"
print(name .. " is " .. age .. " years old")

local bobRow = csv.getRow(parsed, 3)
print(bobRow[1] .. " lives in " .. bobRow[3])