将CSV文件读入哈希表中

你好,我是一个 Lua 初学者,正在尝试逐行循环遍历 CSV。我希望将从 CSV 读取的每行存储在哈希表中。实验代码的当前状态如下:-

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!

ParseCSVLine 是来自 http://lua-users.org/wiki/LuaCsv。但问题在于将值赋给 myfields[v]。查看各种文档后,发现可以在 [] 中使用的语法相当奇怪,而且 Lua 不允许在此处使用符号。如何构造新表 myfields?

原文链接 https://stackoverflow.com/questions/4661577

点赞
stackoverflow用户189205
stackoverflow用户189205

将下面翻译成中文并且保留原本的 markdown 格式,

问题分析:赋值语句给表赋值没有问题。问题在于打印表内容时:您使用 ipairs,实际上应该使用 pairsipairs 用于迭代数组(键为连续的数字1,2,3等的表格),而 pairs 可用于检索任何表的键/值对,如:

for k,v in pairs(myfields) do print(k,v) end
2011-01-11 19:16:39