开发者

reading a csv into a hash

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 ParseC开发者_如何转开发SVLine 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 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜