0
votes

Hello I am a lua beginner and am trying to loop through a CSV one line at a time. I would like to store each line read from the CSV in a hash table. The current state of the experimental code is as follows:-

local fp = assert(io.open ("fields.csv"))
local line=fp:read()
local headers=ParseCSVLine(line,",") 
-- for i,v in ipairs(headers) do print(i,v) end    -- this print outs the CSV header nicely


-- now read the next line from the file and store in a hash
local line=fp:read()
local cols=ParseCSVLine(line,",")
local myfields={}
for i,v in ipairs(headers) do
   -- print( v,cols[i])                            -- this print out the contents nicely
   myfields[v]=cols[i]                             ------ this is where things go bad -----
   end
for i,v in ipairs(myfields) do print(i,v) end      ------ this print nothing!

The ParseCSVLine is from the http://lua-users.org/wiki/LuaCsv. However the issue is the assignment to myfields[v]. Looking at the various docs the syntax of what is allowed within the [] is rather odd and it appears Lua does not allow the use of a symbol here. How do construct my new table in myfields?

1
I was not aware I had! I seem to remember I did unclick the 'star' thingy below the question, as this certainly was not my favorite question. At the time your answer was very helpful. Thanks.ferg

1 Answers

3
votes

The assignment to the table looks fine. The problem is when printing the table contents: You used ipairs where you should have used pairs. ipairs is used when iterating over an array (a table where the keys are the sequential numbers 1,2,3,...), and pairs can be used over any table to retrieve the key/value pairs, like this:

for k,v in pairs(myfields) do print(k,v) end