【问题标题】:Lua - parse from text file and store values with different lengthLua - 从文本文件中解析并存储不同长度的值
【发布时间】:2013-05-14 11:26:55
【问题描述】:

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

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

如何从中创建一个数组?我找到的唯一解决方案是使用相同数量的数字。

【问题讨论】:

    标签: arrays parsing text lua


    【解决方案1】:
    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
    

    【讨论】:

    • 非常感谢!这为我省去了很多麻烦!
    【解决方案2】:

    假设您希望生成的 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
    

    【讨论】:

      【解决方案3】:

      您可以逐个字符地解析文件。当 char 是数字时,将其添加到缓冲区字符串中。如果是空格,则将缓冲区字符串添加到数组中,并将其转换为数字。如果是换行符,和空格一样,但也要切换到下一个数组。

      【讨论】:

        【解决方案4】:
        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}
        

        【讨论】:

        • 文件中的空行(即末尾)怎么办?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-24
        • 1970-01-01
        • 2015-10-13
        • 2016-08-06
        相关资源
        最近更新 更多