2016-03-28 7 views
0

ファイルからデータをテーブルに入れ、各行の最初の単語にキーを設定することができました。どのようにして、キーだけで別のファイルを読むことに基づいて、テーブル内に何を表示するのですか?あなたは、あなたのコード内のいくつかのミス持つ読み込んだファイルに基づいてテーブル情報を表示

-- see if the file exists 
function file_exists(file) 
    local f = io.open("data.txt", "rb") 
    if f then f:close() end 
    return f ~= nil 
end 

-- get all lines from a file, returns an empty 
-- list/table if the file does not exist 
function lines_from(file) 
    if not file_exists(file) then return {} end 
    lines = {} 
    for line in io.lines("data.txt") do 
    first_word = string.gmatch(line, "%a+") -- word 
    lines[first_word] = line 
    end 
    return lines 
end 

local lines = lines_from(file) 

end 

答えて

0

-- see if the file exists 
function file_exists(file) 
    local f = io.open(file, "rb") -- <-- changed "data.txt" to file 
    if f then f:close() end 
    return f ~= nil 
end 

-- get all lines from a file, returns an empty 
-- list/table if the file does not exist 
function lines_from(file) 
    if not file_exists(file) then return {} end 
    lines = {} 
    for line in io.lines(file) do -- <-- changed "data.txt" to file 
     first_word = string.match(line, "%a+") -- <-- changed gmatch to match (IMPORTANT) 
     lines[first_word] = line 
    end 
    return lines 
end 

local lines = lines_from(file) 

を、それがどのブロックに一致しませんでしたので、私は最後の最後を削除しました。 gmatchはイテレータを返します。ファンクションが一致するため、一致するgmatchが重要です。

:あなたが行テーブルの鍵を使用して、キー配列を反復処理し、別の場所では

function key_file(file) 
    if not file_exists(file) then return {} end 
    keys = {} 
    for line in io.lines(file) do 
     key = string.match(line, "%a+") 
     table.insert(keys, key) 
    end 
    return keys 
end 

:キーファイルを読みますが、アレイ状にそのエントリを保存します。あなたの質問について

local lines = lines_from("data.txt") 
local keys = key_file("keys.txt") 

for i, key in ipairs(keys) do 
    print(string.format("%d: %s", i, lines[key])) 
end 
+0

ファイルの保存場所をdata.txtとして保存する必要がありますか?私はそれが私にエラーを与えるファイルを作るとき – CorDell

+0

私はどのように最初のアウトの前に行1を追加するなど? – CorDell

+0

@CorDell:関数を使用しているので、 'lines_from(" data.txt ")'(私の最後のコード例のように)を呼び出すと仮定しました。 ルアはこれをしないでくださいが、ファイル名にnilの値を受け取り、それは動作しません。 ファイル名をluaに渡す必要があります。あなたの例では、最初のファイル名は "data.txt"です。私はちょうど "keys.txt"を取ったキーファイルのためです。しかし、あなたは確かにあなたのケースにこれを採用する必要があります。 2番目のコメント:string.formatとともにprintを使用します。私はこれを達成するために私の答えを編集しました。 – pschulz

関連する問題