CSV

CSV (Comma Separated Values) is a common data format used to store and exchange tabular data between applications. HaasScript provides a ParseCsv() function that allows you to easily parse CSV data into a 2-dimensional array.

Parsing CSV Data

The ParseCsv() function takes a CSV string as its first argument, and returns a 2-dimensional array that contains the parsed data. The function also takes three optional arguments:

  • hasHeaders (default: false) – Specifies whether the CSV data includes headers in the first row. If set to true, the function will return an object with property names as headers and the corresponding values for each row.
  • columnDelimiter (default: ;) – Specifies the column delimiter used in the CSV data.
  • rowDelimiter (default: \n) – Specifies the row delimiter used in the CSV data.

Here’s an example of how to use the ParseCsv() function to parse a CSV string:

local csv = [[
Name, Age, City
John Doe, 30, New York
Jane Smith, 25, San Francisco
]]

local data = ParseCsv(csv, true)

for i, row in ipairs(data) do
    Log(string.format("Name: %s, Age: %d, City: %s", row.Name, row.Age, row.City))
end

This will output:
Name: John Doe, Age: 30, City: New York
Name: Jane Smith, Age: 25, City: San Francisco

Creating CSV

To create a CSV string, you can use a loop to iterate over your data and concatenate it into a string with commas separating each value and newline characters separating each row.

local dataArray = {
  { "name", "age", "gender" },
  { "John", 25, "Male" },
  { "Jane", 30, "Female" }
}

local csvData = ""

for i = 1, #dataArray do
  for j = 1, #dataArray[i] do
    csvData = csvData .. Parse(dataArray[i][j], StringType)
    if j < #dataArray[i] then
      csvData = csvData .. ","
    end
  end
  csvData = csvData .. "\n"
end

Log(csvData)

In this example, we’re creating a 2-dimensional array representing the same data as before, and then iterating over it to concatenate it into a CSV string. We use Parse() to convert each value to a string before concatenating it. We also check if we’re on the last column in each row so we don’t add an extra comma at the end.

Conclusion

Parsing CSV data into a 2-dimensional array is an important skill for data processing and analysis in HaasScript. The ParseCsv() function makes it easy to parse CSV data in HaasScript, and the optional arguments allow you to customize the parsing behavior to fit your needs.

Back to: HaasScript Fundamentals > Using Data