2016-05-30 52 views
0

我有一个文件中的文本 “A.TXT”:读取文件中的文本和存储在阵列2D

1 2 3 
4 5 6 
7 8 9 

现在我想将它存储在阵列2D:

阵列= {{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 

但它没有成功。 有人建议我做一个方法吗?

回答

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 
+0

这正是我期待的。非常感谢你! – ledien

+0

不客气!如果你喜欢我的回答,善良,接受它:) – pschulz

+2

你可以使用'for line in io.lines(“a.txt”)do'。 – lhf