Lua - 从文本文件解析并存储不同长度的值

我是 Lua 编程的初学者,在阅读文本文件并尝试将其存储在数组中方面遇到了问题。我知道已经存在这样的主题,但我想知道如何存储具有不同数量数字的行。例如:在文本文件中:

1 5 6 7
2 3
2 9 8 1 4 2 4

我该如何从中制作一个数组?我发现的唯一解决方案是具有相同数量的数字。

点赞
用户1190388
用户1190388

假设您想要生成的 lua-table(而不是数组)看起来像这样:

mytable = { 1, 5, 6, 7, 2, 3, 2, 9, 8, 1, 4, 2, 4 }

那么您需要执行以下代码:

local t, fHandle = {}, io.open( "filename", "r+" )
for line in fHandle:read("*l") do
    line:gmatch( "(%S+)", function(x) table.insert( t, x ) end )
end
2013-05-19 23:37:22
用户1576117
用户1576117

你可以逐个字符解析文件。当一个字符是数字时,将其添加到缓冲字符串中。当它是一个空格时,将缓冲字符串添加到一个数组中,并将其转换为数字。如果它是一个换行符,则与空格相同,但同时切换到下一个数组。

2013-05-19 23:38:48
用户1847592
用户1847592
local tt = {}
for line in io.lines(filename) do
   local t = {}
   for num in line:gmatch'[-.%d]+' do
      table.insert(t, tonumber(num))
   end
   if #t > 0 then
      table.insert(tt, t)
   end
end
local tt = {}
-- 从文件中逐行读取
for line in io.lines(filename) do
   local t = {}
   -- 通过正则表达式匹配数字,将数字转换成 tonumber 类型并加入 t 表中
   for num in line:gmatch'[-.%d]+' do
      table.insert(t, tonumber(num))
   end
   -- 如果 t 表不为空,将其加入 tt 表中
   if #t > 0 then
      table.insert(tt, t)
   end
end
2013-05-19 23:40:22
用户2303714
用户2303714
t = {}
index = 1
for line in io.lines('file.txt') do
    t[index] = {} -- 初始化一个二维数组
    for match in string.gmatch(line,"%d+") do -- 匹配所有数字
        t[index][ #t[index] + 1 ] = tonumber(match) -- 将数字添加到数组中
    end
    index = index + 1 -- 下一行
end

你可以通过下面的代码查看输出

for _,row in ipairs(t) do
    print("{"..table.concat(row,',').."}")
end

这将展示

{1,5,6,7}
{2,3}
{2,9,8,1,4,2,4}
2013-05-20 02:19:45