和Lua递归搜索对象

问题描述:

在Lua中,我有对象,其中一个对象可以有多个孩子之间的关系的树结构,但只有一个父对象,即和Lua递归搜索对象

OBJ --- OBJ1 --- obj2的--- objd3 --- obj4 --- obj5 --- obj6

如果我想知道obj6的'远处'父母而不是直接父亲obj5,我该如何实现这一点?我只需要一个父级列表,当前对象的两个或多个级别,我正在使用的API只有一个obj.parent属性。

伪代码也将有助于让我走向正确的方向。

+1

你尝试过什么?你似乎知道你必须做一个递归搜索,所以,这样做。 –

那么,如果你的API支持.parent,难道你不能做类似以下的事情吗?我对Lua生疏,但这应该提供一个开始。

local function GetAncestors(child) 

    local ancestors = {}; 

    if child.parent then 
     local i = 0; 
     ancestors[0] = child.parent; 
     while ancestors[i].parent do 
      ancestors[i + 1] = ancestors[i].parent; 
      i = i + 1; 
     end 
    end 

    return ancestors; 

end 
+0

非常感谢这正是我想要做的。 :) – aethys

+0

顺便说一句,这应该让你所需的'父母名单',从中你可以排除任何一代你想要的。就像我说的,如果我在这里有一些逻辑/语法问题,请告诉我。 – canon

+0

没有评论的投票是不好的味道imo。 – canon

obj.parent    -- immediate parent (obj5) 
obj.parent.parent  -- parent's parent (obj4) 
obj.parent.parent.parent -- parent's parent's parent (obj3) 

于是就等等?

如果你想避免试图引用一个不存在的父母,我认为你可以这样做:

function getAncestor(obj, depth) 
    if not obj.parent then 
     return nil 
    elseif depth > 1 then 
     return getAncestor(obj.parent, depth-1) 
    end 
    return obj.parent 
end 


-- get parent 
obj = getAncestor(obj6) 

-- get great great grandparent 
obj = getAncestor(obj6, 3)