How do I find a value in a table that has a table for each value?

I don’t know how to explain it in words so hopefully this will explain it a little better. If anyone can help, please do, thanks!

local t = {
   [1] = {value1A, value1B},
   [2] = {value2A, value2B},
   [3] = {value3A, value3B},
   [4] = {value4A, value4B},
}

print(table.find(t, value3B)) --This prints nil

1 Like

You can’t use table.find directly on a nested table like t . The function table.find is designed for flat arrays, and it won’t work as expected on tables with nested structures. You will need to do it like that:

local t = {
   [1] = value1A,
   [2] = value1B,
   [3] = value2A,
   [4] = value2B,
   [5] = value3A,
   [6] = value3B,
   [7] = value4A,
   [8] = value4B,
}

print(table.find(t, value3B)) -- 6

In your case, where t is a table of tables, you’ll need to iterate through the outer table and then check each inner table for the value you’re looking for. Here’s how you can achieve this:

local function ScanTableToFindIndexByValue(array, value)
	for i = 1, #array do
		local content = array[i]
		local index = table.find(array, value)
		if index then
			return i, index
		end
	end
end

local i, index = ScanTableToFindIndexByValue(t, value3B)

print(i, index) -- 3, 2
print(t[i][index])

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.