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?
The assignment to the table looks fine. The problem is when printing the table contents: You used
ipairswhere you should have usedpairs.ipairsis used when iterating over an array (a table where the keys are the sequential numbers 1,2,3,…), andpairscan be used over any table to retrieve the key/value pairs, like this: