Learn Lua · Data formats · Lesson 2 of 4

CSV

Spreadsheets export CSV: rows of fields separated by commas. csv.parse gives a list of rows, each a list of text fields. Quotes are handled, so a comma inside quotes stays part of the field:

LUA
local rows = csv.parse('name,qty\nFlyer,250\n"Card, square",10\n')
#rows        --> 3
rows[1][1]   --> "name"
rows[3][1]   --> "Card, square"

Every field is text: use tonumber to work with numbers. The first row is often a header naming the columns.

What your code receives

Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.

LUA
input = { text = "name,qty\nFlyer,250\n\"Card, square\",10\n" }

Steps

  1. Return count: how many rows there are after the header row.
  2. Add names: the first field of each row after the header, in order.
  3. Add total: the second fields of those rows added up as numbers.
Show a hint

Loop from the second row: for i = 2, #rows do … end. tonumber gives nil for a field that isn't a number, so give it a fallback: (tonumber(rows[i][2]) or 0).