How to use "table.find" to find dictionary elements in a array?

I have this array with a dictionary inside:

a = { {[“q1”]=1, [“q2”]=2}, {[“q1”]=3, [“q2”]=4} }


Using table.find, how can I find an inner dictionary element, like ["q1"] = 3 ?

1 Like

someone please correct me if I’m wrong, but if I remember right you can only use table.find for the value not the index/key


I don’t think you can, but it’s easy to write your own function to do it (if you want to achieve the same functionality as table.find and return the index of the key). Otherwise, you don’t need to do this.

a = {
	{["q1"]=1, ["q2"]=2}, 
	{["q1"]=3, ["q2"]=4}

function find(tab, val)
	local i = 1;
	for k, v in pairs(tab) do
		if k == val then
			return i; 
		i += 1;
	return nil

print(find(a[1], 'q2'))

table.find is Array specific, as in it can only search for value matches at a numerical index, and return said index, or nil if there is no Value that corresponds.

local t = {
  ["String"] = "Another string!"
  table.find(t, "Another string"),
  table.find(t, "String")

You can simply use Table[Key] as a conditional to find if a dictionary key has a value.

local Temp = PetAssets[SearchTerm] -- If this value is needed later (if it exists,) reference it.
if Temp then -- and following that, you can use its reference as a conditional.
  Temp = Temp:Clone()
  table.insert(PetsTemp, Temp)
  table.insert(InvalidPets, SearchTerm)

EDIT: Added an example snippet.
EDIT 2: Added example for the alternative.


I presume it’s possible by if a[1]["q1"] == 1.

Think of it as using FindFirstChild but with a recursive function (basically FindFirstDescendant, but that’s not an API).

You would use this information to devise a similar function but for tables:

local find -- Make it referencable withing function
find = function(originalTable, findIndex) -- Defining the function
    for index, wrappedTable in pairs(originalTable) do -- Looping through table
        if index == findIndex then -- Checking if it's found
            return wrappedTable -- Returns the value of the index
        if type(wrappedTable) == "table" then -- If it isn't found, and the value is a table then loop through the table
            return recursive(wrappedTable, findIndex) -- Cycle repeats

print(find(a, "q1")) -- 1

You don’t need a function to search by key though.

Yes, I know I can search for dictionary elements within an array using a loop.
My only question was whether it is possible to save code using only table.find in this specific case.
Since it’s not possible, the answer is:

In this case, you can’t. :point_left:

Thanks for all the answers and tips.

1 Like