使用 Lua 对象的递归搜索



在Lua中,我在对象之间有一个树关系结构,其中对象可以有多个子对象,但只有一个父对象,即

obj---obj1---obj2---objd3---obj4---obj5---obj6

如果我想了解 obj6 的"远亲"父母,而不仅仅是直接父 obj5,我该如何实现?我只需要一个比当前对象高两个或更多级别的父级列表,而我正在使用的 API 只有一个 obj.parent 属性。

伪代码也有助于我朝着正确的方向前进。

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)

好吧,如果你的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

最新更新