Read file line by line to array

Sorry, I'm still learning about lua. Could you please correct me, why the data from the file will not read line by line?

this is my example data in points.txt file :

lexxo:30:1
rey:40:2
lion:40:2
prince:50:3
royal:50:3

so when i got on top it's a 2d array (table)

player = {{(name),(points),(which var point earned on index)},
          {(...),(...),(...)}};

so the problem is that I am trying to execute a loop to print all the data in a file. it just prints only the last line. so I wanted to print all of them

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
+4
source share
2 answers

player_data has an index of 1 always, because you do not add elements to it, you add them to line_points, for which #line_points is 5, so use it.

This is what you wanted:

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

Conclusion:

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 assignemnt, 3.

+2

player_data , line_points; #player_data ( 1) player_data line_points.

, - 1:

table.insert(player_data, {playername, playerpoint, playeridpoint})

1 t[#t+1]= , () .

+3

Source: https://habr.com/ru/post/1660037/


All Articles