How do I check if a folder has a certain item?

I want to check if a folder has a specific item. How would I do that?

I’ve tried doing this:

for i, item in ipairs(inventory:GetChildren("Sword"))do
	if item.Name == "Sword" then
		itemOwned = true
	else 
		itemOwned = false

end

In this code sample the folder is saved in a variable named inventory and I’m trying to check if there is a tool named “Sword” in that folder.

This code sample doesn’t work because it gives the error of “attempt to call nil value”. If someone knows a post that has the answer to this question can you link it to me because I cannot find a post that does. If there is no post that answers that question does anyone know the answer to the question?

1 Like

Do :FindFirstChild() to see if it’s true

1 Like

You could use FindFirstChild() it will either return the item or nil. I would recommend searching it up if you’re unfamiliar with it.

Example Code

local Sword = inventory:FindFirstChild("Sword")
if Sword then--If the sword exists
      itemOwned = true
else
      itemOwned = false
end

You can just use :FindFirstChild(name) to search for a child in any object. Replace ‘name’ with the string Name of the object you want to find. It gets a bit more complicated if you have multiple items named the same thing parented to one object.

local hasSword = inventory:FindFirstChild("Sword")