2016-11-07 19 views
4

죄송합니다. 아직 lua에 대해 배우고 있습니다. 당신이 날 고칠 수 있니, 왜 파일로부터의 데이터가 한 줄씩 읽지 않겠습니까? 내가 위에서 왔을 때배열별로 파일을 한 줄씩 읽음

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

때문에 2 차원 배열 인 (테이블)

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

그렇게 문제가 :

파일 points.txt 내 예제 데이터입니다 나는 파일의 모든 데이터를 인쇄하기 위해 반복을 시도합니다. 가장 최근의 행만 인쇄합니다. 그래서 내가 그들 모두를 인쇄 원하는 것을

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 

답변

2

player_data는 에 항목을 추가하지 않기 때문에 항상에 #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 assignemnt을 변경 한 후,이 3

+0

될 것입니다 항상 계산이다 내가 싶었어 :). 그러나 그것은 인쇄 제로 가치입니다. 예를 들어,이'print (line_points [1] [2])' – Han

+1

nvm을 넣을 때 ** line_points [#line_points + 1] = player_data **를 ** replace **로 수정하려고 생각했습니다. * line_playerachiement [# line_playerachievement + 1] = {line : match ('([^ :] +) : (% d +) : (% d +)')}'. 나는 왜 플레이어 데이터 배열이 작동하지 않을지 전혀 몰랐다. 그래서 플레이어 데이터를 제거하고 for 루프를 식별하기로 결정했습니다. – Han

3

당신은 새로운 레코드마다 player_data을 무시하고 있으며, 컬렉션 line_points에 보관됩니다; 그러나 인쇄 할 때 루프가 최대 #player_data (1이 됨)이되고 line_points 대신 player_data에 액세스합니다.

당신은 아마 그런 일 1하고 싶어 :

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

1t[#t+1]= 관용구는 일을 바로 사용할 것을 올바른 테이블과 주 (제거) 더블 대괄호를 코드에 넣으십시오.