Recursion 使用Lua对象的递归搜索
在Lua中,我在对象之间有一个树关系结构,其中一个对象可以有多个子对象,但只有一个父对象,即 obj---obj1---obj2---objd3---obj4---obj5---obj6 如果我想知道obj6的“远”父母,而不仅仅是直系父母obj5,我如何才能做到这一点?我只需要在当前对象上方两个或两个以上级别的父对象列表,并且我正在使用的API只有一个obj.parent属性Recursion 使用Lua对象的递归搜索,recursion,lua,pseudocode,Recursion,Lua,Pseudocode,在Lua中,我在对象之间有一个树关系结构,其中一个对象可以有多个子对象,但只有一个父对象,即 obj---obj1---obj2---objd3---obj4---obj5---obj6 如果我想知道obj6的“远”父母,而不仅仅是直系父母obj5,我如何才能做到这一点?我只需要在当前对象上方两个或两个以上级别的父对象列表,并且我正在使用的API只有一个obj.parent属性 伪代码也将有助于我找到正确的方向。好吧,如果您的api支持.parent,您不能执行以下操作吗?我对Lua有些生疏,但
伪代码也将有助于我找到正确的方向。好吧,如果您的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
诸如此类
如果您想避免引用不存在的父对象,我想您可以这样做:
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)
你试过什么?您似乎知道必须进行递归搜索,所以,好吧,这样做。非常感谢,这正是我要做的。:)顺便说一句,这将为您提供所需的
父母列表
,您可以从中排除您想要的任何一代。就像我说的,如果我有一些逻辑/语法问题,请告诉我。
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)