From 5a49998c2ceaa229d69d39bad55ababc16f5dbde Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Mon, 3 Nov 2025 19:27:27 +0100 Subject: [PATCH] Add a toCSV to go along with the fromCSV --- processor/processor.go | 44 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/processor/processor.go b/processor/processor.go index d284e36..33f4f3f 100644 --- a/processor/processor.go +++ b/processor/processor.go @@ -223,7 +223,7 @@ end --- --- Returns: --- - A table (array) of rows; each row is a table (array) of string fields. -function parseCSV(csv) +function fromCSV(csv) local rows = {} local fields = {} local field = {} @@ -305,6 +305,45 @@ function parseCSV(csv) return rows end +--- Converts a table of rows back to CSV text format (RFC 4180 compliant). +--- +--- Requirements: +--- - Input is a table (array) of rows, where each row is a table (array) of field values. +--- - Field values are converted to strings using tostring(). +--- - Fields are quoted if they contain commas, newlines, or double quotes. +--- - Double quotes inside quoted fields are doubled (""). +--- - Fields are joined with commas; rows are joined with newlines. +--- +--- @param rows table Array of rows, where each row is an array of field values. +--- @return string CSV-formatted text. +function toCSV(rows) + local rowStrings = {} + + for _, row in ipairs(rows) do + local fieldStrings = {} + + for _, field in ipairs(row) do + local fieldStr = tostring(field) + local needsQuoting = false + + if fieldStr:find(',') or fieldStr:find('\n') or fieldStr:find('\r') or fieldStr:find('"') then + needsQuoting = true + end + + if needsQuoting then + fieldStr = fieldStr:gsub('"', '""') + fieldStr = '"' .. fieldStr .. '"' + end + + table.insert(fieldStrings, fieldStr) + end + + table.insert(rowStrings, table.concat(fieldStrings, ',')) + end + + return table.concat(rowStrings, '\n') +end + -- String to number conversion helper function num(str) return tonumber(str) or 0 @@ -629,7 +668,8 @@ STRING FUNCTIONS: format(s, ...) - Formats string using Lua string.format trim(s) - Removes leading/trailing whitespace strsplit(inputstr, sep) - Splits string by separator (default: whitespace) - parseCSV(csv) - Parses CSV text into rows of fields + fromCSV(csv) - Parses CSV text into rows of fields + toCSV(rows) - Converts table of rows to CSV text format num(str) - Converts string to number (returns 0 if invalid) str(num) - Converts number to string is_number(str) - Returns true if string is numeric