Reputation: 93
sorry i am still learning about lua. could you correct me, why the data from file wont read line by line ?
this is my example data in file points.txt :
lexxo:30:1
rey:40:2
lion:40:2
prince:50:3
royal:50:3
so when i got from above is the 2d array(table)
player = {{(name),(points),(which var point earned on index)},
{(...),(...),(...)}};
so the problem is, when i try to loop for printing all of data in file. it just print only the lastest line. so what i wanted 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
Upvotes: 5
Views: 7557
Reputation: 2810
player_data have index of 1 always, because you dont add items to it you add them to line_points which's #line_points is 5, so use it instead.
Is that 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
Output:
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
Update:
After changing player_data assignemnt in first loop to single table, it count always will be 3.
Upvotes: 5
Reputation: 39380
You're overriding player_data
with a new record every time, and the collection is kept in line_points
; however, when printing, your loop goes up to #player_data
(which is gonna be 1) and accesses player_data
instead of line_points
.
You probably wanted to do something like that1:
table.insert(player_data, {playername, playerpoint, playeridpoint})
1 The t[#t+1]=
idiom would also work, just use the correct table and note (get rid of) the double brackets in your code.
Upvotes: 3