2012-10-15 92 views
2

我試圖從文件x y z座標讀取到一個3d數組中。但它似乎並沒有工作。使用LUA讀取和解析文件

文件位於同一文件夾中.lua腳本

-9649.481 666.4141 117.3444 
-9475.624 563.4871 116.0533 
-9338.459 432.295 137.4043 

function lines_from(file) 
    if not file_exists(file) then return {} end 
    for line in io.lines(file) do 
    tokens = {}; 
    itr = 1; 
    for token in string.gmatch(line, "[^%s]+") do 
     tokens[ itr ] = token; 
     itr = itr + 1; 
    end 

    x = tokens[1]; 
    y = tokens[2]; 
    z = tokens[3]; 
    g_lines_from[g_lines_fromCount] = { x, y, z }; 
    g_lines_fromCount = g_lines_fromCount + 1; 

    end 

end 

function AddAll() 
    for i = 1, g_lines_from, 1 do 
     x, y, z = g_lines_from[i]; 
     ListBoxEntry.Create(g_lbWaypoints, "X: " .. math.floor(x) .. ", Y: " .. math.floor(y) .. ", Z: " .. math.floor(z)); 
    end 
end 

function OnAddWaypointClicked(eventID, button) 
    local file = "mine1-75.txt"; 
    lines_from(file); 
    AddAll(); 
end; 
+1

那麼會發生什麼?你期望得到什麼,你究竟得到了什麼?你有什麼試圖自己調試它? –

+0

您的程序可以優化** LOT **。 – hjpotter92

回答

1

請嘗試以下功能:

function readwaypoints(filename, numberofwaypoints) 
    local file = io.open(filename) 
    local waypoints = {} 
    for n = 1, numberofwaypoints do 
    local x, y, z 
    x = file:read('*n') 
    y = file:read('*n') 
    z = file:read('*n') 
    waypoints[#waypoints+1] = {['x'] = x, ['y'] = y, ['z'] = z} 
    end 
    file:close() 
    return waypoints 
end 

它需要一個文件名和行的數文件。對於你的例子文件,它應該返回一個這樣的表:

{[1] = {x = -9649.481, y = 666.4141, z = 117.3444}, 
[2] = {x = -9475.624, y = 563.4871, z = 116.0533}, 
[3] = {x = -9338.459, y = 432.295, z = 137.4043}}