为什么将参数传递给lua类方法得到nill

时间:2017-08-02 10:51:23

标签: lua parameter-passing

我有一个方法,可以从lua中的父列表指针构建一个Tree。 特别是我有 lua表

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

1 个答案:

答案 0 :(得分: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])

这隐含地将p作为self传递给实际函数,现在p将包含实际参数。