2017-08-02 4 views
1

私は、luaの親リストポインタからツリーを構築するメソッドを持っています。なぜluaクラスメソッドに引数を渡すとnillを取得する

機能1(ノードを作成):特に 私はこのLUAテーブルは2つの機能とともに

parents = {2,3,13,5,12,7,11,9,10,11,12,13,14,0} 

持ち

function create_node(parent, i, created, root) 
    if created[i] ~= nil then 
     return 
    end 
    print(i) 
-- print(parent) 
-- Create a new node and set created[i] 
    local new_node = Tree() 
    new_node.idx = i 
    created[i] = new_node 


-- If 'i' is root, change root pointer and return 
    if parent[i] == 0 then 
     root[1] = created[i] -- root[1] denotes root of the tree 

     return 
    end 

-- If parent is not created, then create parent first 
    if created[parent[i]] == nil then 
     create_node(parent, parent[i], created, root) 
    end 
    print(i) 

-- Find parent pointer 
    local p = created[parent[i]] 
    print (p) 

    if #p.children <=2 then 
     print(p.idx) 
     print(created[i].idx) 
     p.add_child(created[i]) 
    end 

end 

機能2は、(ツリーを作成します再帰的に): 私はtesに1つのループを停止しました私はp.add_child(created[i])呼び出すとき

local Tree = torch.class('Tree') 

function Tree:__init() 
    self.parent = nil 
    self.num_children = 0 
    self.children = {} 
end 

function Tree:add_child(c) 

    print(c) 
    c.parent = self 
    self.num_children = self.num_children + 1 
    self.children[self.num_children] = c 
end 

すべてが正常に動作しますが、:すなわち1-2-3-13-14

function read_postorder_parent_tree(parents) 
    n = #parents 

-- Create and array created[] to keep track 
-- of created nodes, initialize all entries as None 
    created = {} 

    root = {} 
    for i=1, 1 do 
     create_node(parents, i, created, root) 
    end 
    return root[1] 
end 

create_note方法はTreeクラスの下に使用を根絶するために、葉から最初のパストン引数はnilなぜですか? (なぜcnilですか?)私はすでにcreated[i]pnilではないことを確認しました。私はこれをどうやって解決できるのですか?

これは私が取得エラーです:

./Tree.lua:16: attempt to index local 'c' (a nil value) 
stack traceback: 
    ./Tree.lua:16: in function 'add_child' 
    main.lua:120: in function 'create_node' 
    main.lua:109: in function 'create_node' 
    main.lua:109: in function 'create_node' 
    main.lua:109: in function 'create_node' 
    main.lua:134: in function 'read_postorder_parent_tree' 
    main.lua:153: in function 'main' 
    main.lua:160: in main chunk 
    [C]: in function 'dofile' 
    ...3rto/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk 
    [C]: at 0x00405d50 
+0

実際のエラーメッセージが表示されますが、あなたの解釈ではありません。 – Piglet

+0

@ピグレット私はそれを投稿する – sdrabb

答えて

3

あなたはオブジェクト指向の方法で関数を定義した場合、あなたはまた、同じ方法でそれを呼び出す必要があります。

function Tree:add_child(c) 

これは、コロン演算子を使用してオブジェクト指向の方法で関数を宣言する。あなたはそれが何を意味するかを理解するために、それは次のように書き換えることができます:あなたが見ることができるように

Tree.add_child = function(self, c) 

、暗黙のselfパラメータは、関数がコールされたオブジェクトを反映するために作成されます。ただし、標準的な方法を経由して関数を呼び出す:

p.add_child(created[i]) 

今、あなたはあなたが本当にやったことselfとしてではなく、その後、もちろんゼロであることを起こるc、としてパスcreated[i]だったことがわかります。このような機能を呼び出すための標準的な方法は、コロン演算子経由でもある:

p:add_child(created[i]) 

これは、暗黙のうちに実際の関数へselfとしてpを渡し、そして今p実引数が含まれています。

関連する問題