Function to Check if Element Exists in Dictionary Not Working

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 
1 Like

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

2 Likes

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 
1 Like

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?

1 Like

I’m working on a solution, give me a couple minutes.

1 Like

Take your time, you’ve been extremely helpful!

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

It should work if it doesn’t let me know

1 Like

Thank you so much, this worked!

1 Like