对不起,我还在学习lua。你能不能纠正我,为什么文件中的数据不能逐行读取?
这是我的示例数据文件points.txt:
lexxo:30:1
rey:40:2
lion:40:2
prince:50:3
royal:50:3
所以当我从上面得到2d数组(table)
player = {{(name),(points),(which var point earned on index)},
{(...),(...),(...)}};
所以问题是,当我尝试循环打印文件中的所有数据。它只打印最后一行。所以我想把它们全部打印出来
line_points = {}
player_data = {{}}
local rfile = io.open("points.txt", "r")
for line in rfile:lines() do
playername, playerpoint, playeridpoint = line:match("^(.-):(%d+):(%d+)$")
player_data = {{playername, playerpoint, playeridpoint}}
line_points[#line_points + 1] = player_data
end
for i = 1, #player_data do
player_checkname = player_data[i][1] -- Get Player Name From Array for checking further
player_checkpnt = player_data[i][3] -- Get Player ID Point From Array for checking further
print(i..". Name: "..player_data[i][1].." Point: ".. player_data[i][2] .. " ID: " .. player_data[i][3]);
end
player_data有索引1总是,因为你不添加项目到它你添加它们到line_points的#line_points是5,所以使用它代替。
这是你想要的吗?
line_points = {}
player_data = {{}} --I think you can delete it at all...
--Because it is rewriting each time.
local rfile = io.open("points.txt", "r")
for line in rfile:lines() do
playername, playerpoint, playeridpoint = line:match("^(.-):(%d+):(%d+)$")
player_data = {playername, playerpoint, playeridpoint}
--I also remover double table here ^^^^^^^^^^^^^^^^^^^
line_points[#line_points + 1] = player_data
end
--Here i checked counts
--print('#pd='..#player_data)
--print('#lp='..#line_points)
--After it i decided to use line_points instead of player_data
for i = 1, #line_points do
player_checkname = line_points[i][1] -- Get Player Name From Array for checking further
player_checkpnt = line_points[i][3] -- Get Player ID Point From Array for checking further
print(i..". Name: "..line_points[i][1].." Point: ".. line_points[i][2] .. " ID: " .. line_points[i][3]);
end
输出:1. Name: lexxo Point: 30 ID: 1
2. Name: rey Point: 40 ID: 2
3. Name: lion Point: 40 ID: 2
4. Name: prince Point: 50 ID: 3
5. Name: royal Point: 50 ID: 3
:
将player_data在第一个循环中的赋值更改为单个表后,它的计数将始终为3。
每次用新记录重写player_data
,并且集合保存在line_points
中;然而,在打印时,循环上升到#player_data
(它将是1)并访问player_data
而不是line_points
。
你可能想做这样的事情1:
table.insert(player_data, {playername, playerpoint, playeridpoint})
1 t[#t+1]=
习语也可以工作,只是使用正确的表并注意(去掉)代码中的双括号。