我是Lua編程的初學者,而且我堅持閱讀文本文件並試圖將其存儲在數組中。我知道那裏已經有一個這樣的話題,但我想知道如何存儲不同數量的行。例如:在文本文件中:Lua - 從不同長度的文本文件和商店值進行解析
1 5 6 7
2 3
2 9 8 1 4 2 4
如何從此創建數組?我發現唯一的解決方案是數量相同。
我是Lua編程的初學者,而且我堅持閱讀文本文件並試圖將其存儲在數組中。我知道那裏已經有一個這樣的話題,但我想知道如何存儲不同數量的行。例如:在文本文件中:Lua - 從不同長度的文本文件和商店值進行解析
1 5 6 7
2 3
2 9 8 1 4 2 4
如何從此創建數組?我發現唯一的解決方案是數量相同。
假如你希望得到的LUA表(不陣列)的樣子:
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
您可以通過文字解析文件的字符。當char是一個數字時,將其添加到緩衝區字符串中。當它是一個空格時,將緩衝區字符串添加到數組中,並將其轉換爲數字。如果是換行符,請按空格操作,但也切換到下一個數組。
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
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}
文件中的空行(即最後)如何? –
非常感謝您!這節省了我很多麻煩! – zer