I started writing a response awhile ago but decided to come back because this question interested me so I took a look into it.
Anyway, you’re able to do this with recursion. I had fun writing this:
local tbl = {
Apple = 3;
Banana = {
foo = "E";
test = {
lol = "F";
};
};
};
local hierarchy = {} -- this is what we are going to store the hierarchy in
local function getHierarchy(value, tbl, attempt, level)
local level = level or 1 -- this determines the index of the hierarchy table
local found
for i,v in pairs(tbl) do
if type(v) ~= 'table' and v == value then -- if v isn't a table and v is equal to the value then we can set the idnex to the value'
hierarchy[level] = i
return true
elseif type(v) == 'table' then -- if the v is a table then
found = getHierarchy(value, v, attempt, level + 1) -- call the functiom with the index as the last index plus 1, pass the current table
if found then
hierarchy[level] = i -- if it's found, set the index to i
return found -- return the found value, assuming this is calling itself (we don't really have any way to know)
end
end
end
end
local found = getHierarchy('F', tbl)
print(hierarchy) -- [1] = 'Banana'; [2] = 'test'; [3] = 'lol'
You can do this as much as you want, with any level.
local tbl = { -- this is the base
Apple = 3;
Banana = {
foo = "E";
test = {
lol = "F";
};
moreTest = {
wow = {
this = {
can = {
go = {
really = {
really = {
really = {
andIMean = {
REALLY = {
far = {
down = {
because = {
of = {
our = {
good = {
friend = {
recursion = ':)'
}
};
look = {
it = {
even = {
works = {
with = {
multiple = {
tables = ':O'
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
};
moreMoreTest = {};
};
};
--...
local found = getHierarchy(':O', tbl)
--[[
▼ {
[1] = "Banana",
[2] = "moreTest",
[3] = "wow",
[4] = "this",
[5] = "can",
[6] = "go",
[7] = "really",
[8] = "really",
[9] = "really",
[10] = "andIMean",
[11] = "REALLY",
[12] = "far",
[13] = "down",
[14] = "because",
[15] = "of",
[16] = "our",
[17] = "look",
[18] = "it",
[19] = "even",
[20] = "works",
[21] = "with",
[22] = "multiple",
[23] = "tables"
} - Edit
]]
--
local found = getHierarchy(':)', tbl)
print(hierarchy)
--[[ ▼ {
[1] = "Banana",
[2] = "moreTest",
[3] = "wow",
[4] = "this",
[5] = "can",
[6] = "go",
[7] = "really",
[8] = "really",
[9] = "really",
[10] = "andIMean",
[11] = "REALLY",
[12] = "far",
[13] = "down",
[14] = "because",
[15] = "of",
[16] = "our",
[17] = "good",
[18] = "friend",
[19] = "recursion"
} - Edit
]]