Best way to find value in table?

I know that table have method “find”, but why I can’t find index with this method?
P.s: I really don’t want use “for” iterator

local Table = {[1] = {["Name"] = "pet",["Index"] = 3},[2] = {["Name"] = "cat",["Index"] = 4}}
	
	print(table.find(Table,{["Name"] = "pet",["Index"] = 3})) -- nil

the way i use is just loop through the table with a for pairs loop and compare the values with the desired value until a match is found

I don’t like this way because of speed and code readable

I don’t think you are using table.find() correctly. And furthermore, table.find() is only used on Linear Searches.

In your case it isn’t working because tables (and dictionaries) are passed by reference rather than value.

What’s probably happening is the dictionary in the table and the dictionary in the table.find are seen as 2 completely different dictionaries and thus will never be found unless you get the dictionary directly from the table.

Whereas values such as strings, numbers, etc, are passed by value, so even if you don’t have a direct reference it’ll still work

So your only choice is to iterate using an in pairs loop and see if all the stuff match. If you’re going to be using it a lot, put it in a function

At the end of this article, it details this pass by reference thing I’m mentioning

2 Likes

the speed isnt effected searches all work the same granted the table is unsorted (its just about randomly stumbling on the value most common way being linear)