您的代码中存在一些错误。首先打开文件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
这正是我期待的。非常感谢你! – ledien
不客气!如果你喜欢我的回答,善良,接受它:) – pschulz
你可以使用'for line in io.lines(“a.txt”)do'。 – lhf