Find values in two tables

So I have two tables, let’s assume their values.

local table1 = {'value1', 'value2', 'value4'}
local table2 = {'value1', 'value2', 'value3', 'value4'}

How would I check if a value is missing from one of the tables (in this case, value3 is missing from table1)?

You could first, get the size of each table, whichever has the higher count should be iterated. Once in iteration (forloop), you want to use table.find(tablewearentiterating, currentiterationvalue) and whenever that returns false, do something (keep track of the missing values?). This is just an idea, I’m not sure what your actual data is going to look like and if this is viable.

There may be a built in method for comparing tables that I am not aware of.

This is the code that I came up with, and I think it works.

local function getBiggerTable(table1, table2)
	if typeof(table1) ~= 'table' or typeof(table2) ~= 'table' then
		return nil
	end
	local table1L = table.maxn(table1)
	local table2L = table.maxn(table2)
	if table1L > table2L then
		return table1
	elseif table2L > table1L then
		return table2
	end
end

local function getSmallerTable(table1, table2)
	if typeof(table1) ~= 'table' or typeof(table2) ~= 'table' then
		return nil
	end
	local table1L = table.maxn(table1)
	local table2L = table.maxn(table2)
	if table1L < table2L then
		return table1
	elseif table2L < table1L then
		return table2
	end
end

local table1Test = {'value1', 'value2', 'value4', 'value6'} --table1
local table2Test = {'value1', 'value2', 'value3', 'value4', 'value5', 'value6'} --table2


local table1TL = table.maxn(table1Test)
local table2TL = table.maxn(table2Test)
if table1TL ~= table2TL then
	local biggerTable = getBiggerTable(table1Test, table2Test)
	local smallerTable = getSmallerTable(table1Test, table2Test)
	local missingValues = {}
	for n, value in pairs(biggerTable) do
		if not table.find(smallerTable, value) then
			table.insert(missingValues, value)
		end
	end
	print(missingValues)
end

If you have any suggestions, feel free to reply. I have a tendency to use table.maxn(table) rather than #table.

Those functions work (though overly complicated imo) but did you solve your original question?

How would I check if a value is missing from one of the tables (in this case, value3 is missing from table1)?

If so, great!

How would you simplify the functions?

Depending on your use case, you can simply compare the tables with a simple if statement if you only need to see if they are of the same length (and not which actual values differ from each table)

if #table1 == #table2 then

end

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