The format is odd im aware, but the goal is to try and obtain lets say
Randomvalue6, through a function i am creating. The isssueee is im stuck.
I tried making a recursion function where when it found a table it would check inside it however itll stop at that first table.
The problem with this is, randomvalue 6 is in table2, the recursion function will stop in table 1 / table 4 and wont go further cuz thats where the function led it to.
My goal is to make it finish within each table and continue to the next, but i feel like im missing something.
I know there’s likely easier ways to go about this like just typing each path
but the ideal goal is a function that i can call to just obtain the value i want on demand.
Worth noting, its a large amount of information so… if someone is aware how hefty this could get on performance aswell with some alternative answers would also be appreciated.
You can have function with takes in 2 number one being the number of the table and the other being the index of the random value. Both the numbers will be referred to as index1 and index. Then you can acquire the randomnumber by doing tablename[index].index1
This function should do what you’re asking for I think, let me know if there’s something missing. It should account for recursive tables and such
local function deepFindKey(targetKey, t)
local looked = {}
local function look(t)
if t[targetKey] then
return t[targetKey]
end
if looked[t] then -- recursive table check
return
end
looked[t] = true
for _, value in t do
if type(value) == 'table' then
local ret = look(value)
if ret then
return ret
end
end
end
return nil
end
return look(t)
end
Tests
local t = {
table1 = {
table3 = {
randomvalue = 1;
randomvalue2 = 2;
};
table4 = {
randomvalue3 = 3;
randomvalue4 = 4;
}
};
table2 = {
table5 = {
randomvalue5 = 5;
randomvalue6 = 6;
};
table6 = {
randomvalue7 = 7;
randomvalue8 = 8;
}
}
}
t.table3 = t.table2
local function deepFindKey(targetKey, t)
local looked = {}
local function look(t)
if t[targetKey] then
return t[targetKey]
end
if looked[t] then -- recursive table check
return
end
looked[t] = true
for _, value in t do
if type(value) == 'table' then
local ret = look(value)
if ret then
return ret
end
end
end
return nil
end
return look(t)
end
print(deepFindKey('randomvalue7', t)) --> 7
print(deepFindKey('table6', t)) --> { randomvalue7 = 7; randomvalue8 = 8 }
print(deepFindKey('thisKeyDoesNotExist', t)) --> nil
Ah i ended up making something similar. unfortunately, I realized performance wise this wasn’t ideal for a lot of mass data editing so I’m doing a bit of a different thing now. This functions very useful though especially for people looking for a more reliable recursive search.