Getting a CSV list file into an array

Hi all,

I’ve just started out and I’m having a blast! But I have one thing I’m struggling with.

A have a CSV file (comma separated values) which hold 2500 integer numbers, representing a 50 x 50 grid - it’s for a tilemap of sorts. I want to get this CSV file into my iPhone app as a Corona array.

The file looks like this:

1,5,3,1,4,5,…,5,8,
1,6,2,4,6,8,…,9,6,


1,7,5,2,6,7,…,2,3

Without the dots of course. Basically the file holds 50 lines of text, with each line consisting of 50 numbers and a comma in between. Each line ends with a comma, except for the last one, but I can add a comma here manually to make things easier. I may also assume that the CSV file will always hold 2500 numbers.

Now, how do I get this into Corona??? I’ve looked at the file functions, and I’ve looked at the string functions, and I’m sure that parsing a string must be a good starting point, but I’m very confused by all the %g %a string.gsub pattern thingies and such… I come from another programming background which confuses me here :slight_smile:

Any pointers or help would be greatly appreciated!

Thanks,
Thomas [import]uid: 70134 topic_id: 12760 reply_id: 312760[/import]

this will work,
[lua]local path = system.pathForFile( “test.csv”, system.ResourceDirectory )
local file = io.open( path, “r” )

local table = {}

local contents
if file then – nil if no file found
contents = file:read( “*a” )
io.close( file )
end
print(contents)
local k = 1
local j = string.len(contents)
while j > 0 do
i = string.find(contents,",")
if i~= nil then
table[#table + 1] = string.sub(contents,k,i-1)
print(table[#table])
contents = string.sub(contents,i+1,j)
j = string.len(contents)
else
table[#table + 1] = string.sub(contents,k,j)
print(table[#table])
j = 0
end
end[/lua]
[edit]
no need to put comma at last
[import]uid: 12482 topic_id: 12760 reply_id: 46807[/import]