读取文件文本并存储在数组2d中

时间:2016-05-30 15:31:12

标签: lua

我有一个文件文本" a.txt" :

1 2 3
4 5 6
7 8 9

现在我想将它存储在数组2d中:

array = {{1,2,3} {4,5,6} {7,8,9}} 我试着:

array ={}
file = io.open("a.txt","r")
io.input(file)
i=0
for line in io.lines() do
   array[i]=line
   i=i+1
end

但它并没有成功。 有没有人建议我这样做?

1 个答案:

答案 0 :(得分:3)

您的代码中存在一些错误。首先打开文件a.txt,然后将其设置为标准输入。你不需要open()。但我建议使用文件上的lines()迭代器打开文件并对其进行操作:

array = {}
file = io.open("a.txt","r")
i = 0
for line in file:lines() do
   array[i]=line
   i=i+1
end

此外,使用您的方法,您不会获得您希望的数组({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }),而是包含字符串作为元素的数组: { "1 2 3", "4 5 6", "7 8 9" }。 要获得后者,您必须解析您已阅读的字符串。一种简单的方法是将string.match与捕获一起使用:

array ={}
file = io.open("a.txt","r")
for line in file:lines() do
    -- extract exactly three integers:
    local t = { string.match(line, "(%d+) (%d+) (%d+)")) }
    table.insert(array, t) -- append row
end

https://www.lua.org/manual/5.3/manual.html#pdf-string.match。对于每一行的任意数量的整数(或其他数字),您可以与string.gmatch()一起使用循环:

array ={}
file = io.open("a.txt","r")
for line in file:lines() do
    local t = {} 
    for num in string.gmatch(line, "(%d+)") do
        table.insert(t, num)
    end
    table.insert(array, t)
end