简体   繁体   English

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

[英]Lua - parse from text file and store values with different length

I am a beginner in programming with Lua, and I am stuck with reading a text file and trying to store this in an array. 我是使用Lua进行编程的初学者,但我一直坚持阅读文本文件并将其存储在数组中。 I know there already exists a topic like this, but I was wondering how I should store lines with different amount of numbers. 我知道已经有一个这样的主题,但是我想知道如何存储不同数量的行。 eg: in the textfile: 例如:在文本文件中:

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

How do I make an array from this? 我该如何做一个数组? The only solutions I find are with identical amount of numbers. 我发现的唯一解决方案是使用相同数量的数字。

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

Supposing you want the resulting lua-table (not array) to look like: 假设您希望生成的lua表 (而非数组)看起来像:

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

then you'd do: 然后您将执行以下操作:

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

You could parse the file character by character. 您可以逐个字符地解析文件。 When a char is a number, add it to a buffer string. 当char是数字时,将其添加到缓冲区字符串中。 When it's a space, add the buffer string to an array, and convert it to a number. 如果是空格,则将缓冲区字符串添加到数组,然后将其转换为数字。 If it's a newline, do the same as with a space, but also switch to the next array. 如果是换行符,请执行与空格相同的操作,但还要切换到下一个数组。

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 

You can see the output by doing 您可以通过以下方式查看输出

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

Which shows 这表现了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM