2017-08-02 28 views
1

我有一個方法從lua中的父列表指針構建樹。 特別我有此LUA表爲什麼傳遞參數到lua類方法得到nill

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

隨着兩個功能:

功能1(將產生的節點):

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(創建樹遞歸地): 我已經停止了一個循環牛逼從葉的第一路徑爲根即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類:

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 

一切工作正常,但是當我打電話p.add_child(created[i])這個說法是nil爲什麼? (爲什麼cnil?)我已經檢查過created[i]p不是nil。我如何解決這個問題和/或爲什麼會發生這種情況?

這是我的錯誤:

./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

@Piglet我張貼它 – sdrabb

回答

3

如果定義在面向對象的方式的功能,你還必須把它以同樣的方式。

function Tree:add_child(c) 

這聲明在使用冒號運算一種面向對象的方式的功能。爲了幫助你明白這意味着什麼,它可以寫成這樣:

Tree.add_child = function(self, c) 

正如你所看到的,一個隱含的self參數創建以反映函數被調用的對象。但是,您通過標準的方式調用該函數:

p.add_child(created[i]) 

現在你可以看到你真的是通created[i]self,而不是c,那當然這恰好是零。調用此函數的標準方式,也可通過冒號運算符:

p:add_child(created[i]) 

這隱含通過pself實際功能,而現在p將包含實際參數。

相關問題