私は Lua を使ったプログラミングの初心者で、テキスト ファイルを読み込んで、これを配列に保存しようとしています。このようなトピックが既に存在することは知っていますが、異なる数の行をどのように格納するべきか疑問に思っていました。例: テキストファイル内:
1 5 6 7
2 3
2 9 8 1 4 2 4
これから配列を作成するにはどうすればよいですか? 私が見つけた唯一の解決策は、同じ量の数字を使用することです。
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}
結果の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
ファイルを文字ごとに解析できます。char が数値の場合、それをバッファー文字列に追加します。スペースの場合は、バッファ文字列を配列に追加し、数値に変換します。改行の場合は、スペースの場合と同じですが、次の配列に切り替えます。