Han*_*Han 5 lua lua-table luafilesystem
抱歉,我仍在学习lua。您能纠正我吗,为什么文件中的数据无法逐行读取?
这是我在points.txt文件中的示例数据:
lexxo:30:1
rey:40:2
lion:40:2
prince:50:3
royal:50:3
Run Code Online (Sandbox Code Playgroud)
所以当我从上面得到的是二维数组(表)
player = {{(name),(points),(which var point earned on index)},
{(...),(...),(...)}};
Run Code Online (Sandbox Code Playgroud)
所以问题是,当我尝试循环打印文件中的所有数据时。它只打印最后一行。所以我想要打印所有的
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
更新:
将第一个循环中的player_data allocateemnt更改为单表后,它的计数始终为3。