Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to Make a Comparison of Two Tables To Get the Same Table as a Result?

Hello I wanted to make a craft system, but noticed that the problem is that my code does not work as it should

local Table = { "Apple" , "?" , "Apple"}
local Recipes = {
	ThreeApple = {
		"Apple";
		"Apple";
		"Apple";
	}
}
local function FindItemGivenRecipet()
	local CraftingItems = Table
	for k,v in pairs(Recipes) do
		local Compare = true;
		for i = 1 ,#v do
			if v[i] ~= CraftingItems[i] then
				Compare = false;
				break;
			end
			if Compare then
				return k;
			end
		end
	end
end
local g = FindItemGivenRecipet()
print(g)

If these two values match, the rest are ignored and returned, or maybe even return the wrong table that you need, I need the function to return only when all values match. You can offer your versions how to do it.

1 comment

0

There may be no understanding because I'm in a hurry

1 answer

✓ Accepted answer

Your problem is you put the second if statement wrong place

for k,v in pairs(Recipes) do
	local Compare = true; -- the Compare
	for i = 1 ,#v do
		if v[i] ~= CraftingItems[i] then -- the first if statement will past because v[i] == CraftingItems[i] so Compare is still true
			Compare = false; 
			break;
		end
		if Compare then -- Compare is true so the function will return the value k
			return k;
		end
	end
end

The solution is check the Compare after the loop done:

for k,v in pairs(Recipes) do
	local Compare = true;
	for i = 1 ,#v do
		if v[i] ~= CraftingItems[i] then -- Compare will be false because CraftingItems[2] is "?"
			Compare = false; 
			break;
		end
	end
end

if Compare then -- Compare is false so the function won't return
	return k;
end

Hope it helped :D

1 comment

1

I checked and it works well, thanks, I will be more careful with the algorithms in my scripts

This discussion is preserved as it was. New answers, comments, and votes are closed.