Crafting system for my game is confusing

Oh boy, enjoy trying to read through this headache of a post! :sweat_smile:

So, I have been trying to make a crafting system for about 3 hours now, and I am finally resorting to the developer forums…

Basically, how it works is that the players inventory is stored in a table:

You can add items:
image

And also remove items:
image
(excuse any errors in this code snippet, i just changed it a bit for testing and im not 100% sure if it works yet, changes will be reverted)

And this all works fine! But trouble really began when I tried making crafting…

I tried looping through each item in the recipe, and then put the name of each item in the players inventory in a list, and then checked to see if the name was the same, and then checked the amount the player had in their inventory and compared that with the amount needed.

This did not work, because whenever i broke the loop it just didnt work for some reason? Probably bad code but I can’t be bothered to spend another 15 hours looking for the problem.

So, could anybody tell me the REAL way to do this? I have looked through many dev forum posts with nothing that I could use for my specific crafting system. Also, don’t just say “Compare the tables” or whatever. Please explain what you mean when you say something like that.

Thank you!

I would first add a method, following your method naming/parameter pattern, HasInvItemitem(player: string, item: string, count: number?): boolean. In short, this method would just check if the player’s inventory has the given item – if count is provided, it should return true if the # of items is greater or equal to count, otherwise return false. This is just a handy utility function that you’ll probably use in a bunch of other spots with an inventory system.

For crafting, we’ll first just have an example recipe.

local bookRecipe = {
	Paper = 4,
	Leather = 2,
	Ink = 1,
}

Now, we will check if the player has each item.

for item, amount in bookRecipe do
	if not functions.HasInvItem(player, item, amount) then
		return -- Immediately stop code execution since we're missing a necessary item.
	end
end

If we don’t have the needed items, then we’ll stop code execution now with a return statement. Otherwise, we’ll continue.

We’ve established we have the needed items, so now let’s remove them from the inventory and add our crafted item.

for item, amount in bookRecipe do
	functions.RemoveInvItem(item, amount, player)
end
functions.AddInvItem("Book", 1, player)

And, just like that, we’re done. We could easily condense this code into its own function at this point, but that’s mostly up to you to decide how you’d like to approach that. If you’d like some help with that too, I can definitely provide some ideas.

thank you! I was actually able to use a different method, but this one seems better. Will probably rewrite my code to follow your method.