Iterating multi-dimensional data-structures of an unknown depth is a perfect problem for recursion. Recursion is the process of recursively (repeatedly) calling a function from within itself. One thing to note, though: function calls allocate stack memory, and the stack space is constant. This means we can’t utilize recursion forever. There is no base-case (the condition where recursion is stopped) you can set for this type of problem, so you’ll have to stray away from using this solution on large data structures:
local function findDeep<T>(container: {}, target: T): T?
for key, value in container do
if value == target then
return key, container
elseif type(value) == "table" then
return findDeep(value, target)
end
end
end
The algorithm above is known as Depth-First Search (DFS). This algorithm works in-order, diving into the first and deepest layer of the data-structure. It will work its way back up until the first layer has been fully combed, then proceed to the next layer