Hello, title basically says it all. I have this code that is meant to print true, but is not working. "hi" gets printed but the function returns false. I think this is because it is returning out of the loop and not the function, so I tried Code 2 and it still didn’t work.
Code 1
local tbl = {
["hi"] = {
["1"] = 2,
["2"] = 3
};
["3"] = {
["3"] = "eae"
};
}
local function TblDescendantExists(Tbl, Descendant)
for _, Value in pairs(Tbl) do
if (Descendant == Value) then
print("hi")
return true
elseif (typeof(Value) == "table" and Descendant ~= Value) then
TblDescendantExists(Value, Descendant)
end
end
return false
end
print(TblDescendantExists(tbl, "eae"))
Code 2
local function TblDescendantExists(Tbl, Descendant)
local ToReturn
for _, Value in pairs(Tbl) do
if (Descendant == Value) then
print("hi")
ToReturn = true
break
elseif (typeof(Value) == "table" and Descendant ~= Value) then
TblDescendantExists(Value, Descendant)
end
end
return ToReturn
end
you have a recursive function so when “hi” gets printed and then returns true on the next line it returns it to the function when it was called in the elseif
Oh, I didn’t think of this! Thank you! I did this and it worked!
local function TblDescendantExists(Tbl, Descendant)
for _, Value in pairs(Tbl) do
if (Descendant == Value) then
print("hi")
return true
elseif (typeof(Value) == "table" and Descendant ~= Value) then
return TblDescendantExists(Value, Descendant)
end
end
return false
end
Hi again, I ran into an issue where this wouldn’t work if there are multiple tables inside of a table, because it would only return the search of the first table it looked through. Do you know a way around this?
Ok I think I’ve figured it out, it’s by no means efficient and if you have a better way of structuring your code you probably should.
The only way to guarantee whether a table with an indefinite number of sub tables has a value within, is to iterate through ever single one until a value is found. (basically it’s not efficient and could be slow for big datastructure, and you probably shouldn’t run it often (e.g. renderstepped))
anyway here's the code
local function recursiveCheck(table,value) -- > [bool]
for k,v in pairs(table)do
if v == value then
return true
end
if type(v) == "table" then
local var = recursiveCheck(v,value)
if var == true then
return var
else
continue
end
end
end
return false
end
print(recursiveCheck(nice_table,"nice value")) -- replace nice_table with your table and nice_value with value