This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Grim Reaper's profile picture

CSV Splitter (Comma Separated Value)

Started by Grim Reaper, 10 September 2012 - 06:47 AM
Grim Reaper #1
Posted 10 September 2012 - 08:47 AM
I don't usually release junk scripts, or any for that matter, but I thought someone might use this.

This API, or function rather, takes a comma separated value string in the with compensation of 1 space past the comma, and returns each value in a table.

Example:

os.loadAPI( "csv" )


local t = {}
local sCSV = "1, 2, 3,4,test!"

t = csv.SplitCSV_ToTable( sCSV )


for index,value in ipairs( t ) do
  print( value )
end


-- OUTPUT --
1
2
3
4
test!
----------------

Here is the code:
Spoiler


-- Written and developed by PaymentOption --

function SplitCSV_ToTable( sCSV )
-- There is a first comma and then a last.
local tValues = {}
local nLastComma_Pos_Dupe = 1
local nLastComma_Pos = 1
local nValueLength = 0 -- This will be the difference in comma positions.

local bFirstRun = true
local bEndOfString = false
local cEndCharacter = string.sub( sCSV, string.len( sCSV ), string.len( sCSV ) ) -- Get the last character in the list.

while not bEndOfString do
nLastComma_Pos_Dupe = nLastComma_Pos
-- test,test
nLastComma_Pos = string.find( sCSV, ",", nLastComma_Pos+1, string.len( sCSV ) )

if nLastComma_Pos ~= nil then
nValueLength = nLastComma_Pos - nLastComma_Pos_Dupe

if bFirstRun then
-- Handle a single space.
if string.sub( sCSV, 1, 1 ) == " " then
tValues[1] = string.sub( sCSV, 2, nValueLength )
else
tValues[1] = string.sub( sCSV, 1, nValueLength )
end

bFirstRun = false
else
-- Handle a single space.
if string.sub( sCSV, nLastComma_Pos_Dupe+1, nLastComma_Pos_Dupe+1 ) == " " then
tValues[#tValues+1] = string.sub( sCSV, nLastComma_Pos_Dupe+2, nValueLength + nLastComma_Pos_Dupe-1 )
else
tValues[#tValues+1] = string.sub( sCSV, nLastComma_Pos_Dupe+1, nValueLength + nLastComma_Pos_Dupe-1 )
end
end
else
-- Get the last character.
if string.sub( sCSV, nLastComma_Pos_Dupe+1, nLastComma_Pos_Dupe+1 ) == " " then
tValues[#tValues+1] = string.sub( sCSV, nLastComma_Pos_Dupe+2, string.len( sCSV ) )
else
tValues[#tValues+1] = string.sub( sCSV, nLastComma_Pos_Dupe+1, string.len( sCSV ) )
end

bEndOfString = true
return tValues
end
end
end
Sorry for the shitty indentations, but you can't really paste code into the forums with indentations…

Pastebin link: http://pastebin.com/8A5kEQdc

Hope this helps someone out there.

Warm regards,
Payment
Xtansia #2
Posted 10 September 2012 - 11:30 AM
Don't want to rain on your parade or anything but just a little improvement, It also can handle any number of spaces/tabs before after the comma:
function csvToTable(s)
  local tab = {}
  for match in string.gmatch(s, "[ t]*([^,]+)") do tab[#tab + 1] = match end
  return tab
end