在 Lua 中将 .csv 文件转换为二维 table

Convert a .csv file into a 2D table in Lua

如标题所示,我想知道如何将 Lua 中的 .csv 文件转换为 2D table。

例如,假设我有一个如下所示的 .csv 文件:

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0
0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0
0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0
0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0
0,0,-1,-1,-1,-1,-1,-1,0,0,0,0,-1,-1,-1,-1,-1,-1,0,0
0,0,0,-1,-1,-1,-1,0,0,0,0,0,0,-1,-1,-1,-1,0,0,0
0,0,0,0,-1,-1,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

我如何将它转换成这样的东西?

local example_table = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,0,-1,-1,-1,-1,-1,-1,0,0,0,0,-1,-1,-1,-1,-1,-1,0,0},
{0,0,0,-1,-1,-1,-1,0,0,0,0,0,0,-1,-1,-1,-1,0,0,0},
{0,0,0,0,-1,-1,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}

非常感谢您的帮助。

1。不要小看 CSV。

如果您需要它的通用性,请获取合适的 CSV 解析库。如果您自己进行解析,您将错过许多 可能 发生的特殊情况,因此只有 suitable 用于您知道数据并且会注意到是否发生某些事情的情况错了。

2。更改文件

如果你想要等效的 Lua 代码 作为输出,假设你在 Lua 中进行解析,你可以这样做:

local input = get_input_somehow() -- probably using io.open, etc.

local output =
"local example_table = {\n"
..
input:gmatch("[^\n]*", function(line)
   return "{" .. line .. "};"
end)
..
"\n}"

save_output_somehow(output) -- Probably just write to a new file

3。将 CSV 解析为 table

如果您想将 CSV 文件直接读入 Lua table,您可以这样做:

local input = get_input_somehow() -- probably using io.open, etc.

local output = {}
input:gmatch("[^\n]", function(line)
   local row = {}
   table.insert(output, row)
   line:gmatch("[^,]", function(item)
      table.insert(row, tonumber(item))
   end)
end)

do_something_with(output) -- Whatever you need your data for