Search code examples
recursionluapseudocode

Recursive search with Lua objects


In Lua, I have a tree relationship structure between objects where an object can have multiple children, but only one parent object, i.e.

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

If I want to know obj6's 'distant' parents instead of just the immediate parent obj5, how can I achieve that? I just need a list of parents two or more levels above the current object, and the API I'm working with only has a obj.parent property.

Pseudo-code would also be helpful to get me in the right direction.


Solution

  • Well, if your api supports .parent, can't you do something like the following? I'm rusty with Lua but this should offer a start.

    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