How to take tables as argument in function

So, I was trying to compare elements of tables with each other in this function

function isTableSimilar(table1,table2)
local Subset = false
if #table1>#table2 then local BigTable= table1; local SmallTable = table2 else local BigTable = table2; local SmallTable = table1 end
for _,v in pairs(SmallTable) do
for _,s in pairs(BigTable) do

if v == s then Subset = true; break end

       end
if Subset == true then break
end
 Return Subset
end

But Error is arguments are nill value whenever I enter any table. How to do?

1 Like

Can you please show us how you are calling the function?

local table = {"a","b","c"}
local Table = {"a","d"}

if isTableSimilar(table,Table) then print("done") end

Probs not related to the issue, but avoid renaming built in functions (i.e. table)

Directly after function isTableSimilar(table1,table2), can you please output table1 and table2?

theres many issues with that script, this task can be done easily.

Then you have 2 tables, one bigger than the other, and you want to find if theres a value inside the smaller table that exist in the bigger table too and return it?

-- 2 tables with random values, the only one shared is "apple"
local tableA = {"apple", "pera", "guayaba", "melon"}
local tableB = {"another fruit", "fruit in spanish", "apple"}

-- Function to find value in bigger table
function isTableSimilar(table1,table2)
	local BigTable
	local SmallTable
	
	if #table1 > #table2 then
		BigTable = table1
		SmallTable = table2
	else
		BigTable = table2;
		SmallTable = table1
	end
	
	for _, v in pairs(SmallTable) do
		if table.find(BigTable, v) then
			return v	
		end
	end
end

-- Calling the table checker function
local result = isTableSimilar(tableA, tableB)
-- the result
warn(result)
2 Likes

Defining local variables inside function solved the problem just like in your code. This works too.

function isTableSimilar(table1,table2)
	local Subset = false
	local BigTable
	local SmallTable
	
	if #table1>#table2 then 
		 BigTable = table1;
	     SmallTable = table2;
	else
		local BigTable = table2;
		local SmallTable = table1
		
		end
	
	for _,v in pairs(SmallTable) do
		for _,s in pairs(BigTable) do

			if v == s then Subset = true; return Subset end

			end
	end
	return Subset
	end
1 Like

Obviously the main issue was defining variables inside the if statement, where cannot be reached by the rest of the code.
I was pointing that nesting loops inside loops for an easy task is not needed

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