Script returning less values than expected?

I’ve got a script that checks if tools with the same names as values in the table exist, and then prints the result. However, the result is printing one less than the amount that’s in the table.

When there are 1 items left, it prints one,
2 prints 2,
3 prints 3,
4 prints 3,
5 prints 4.

How can i make this… Not like that?

local players = game:GetService("Players")
local player = players.LocalPlayer

local backpack = player.Backpack

local craftingParts = {"SMG Receiver", "SMG Mag", "SMG Grip", "SMG Barrel", "SMG Stock"}

local function checkTable()
	local itemCount = 0
	for i, tool in ipairs(craftingParts) do
		if backpack:FindFirstChild(tool) then
			itemCount = itemCount + 1
		elseif player.Character:FindFirstChild(tool) then
			itemCount = itemCount + 1
		end
	end
	return itemCount
end

local result = checkTable()
print(result)

try printing the itemCount variable inside the for loop to see what it’s doing in there then check the returned result after.

1 Like

Ah, The problem seems to be that the itemCount sets to 0, probably from the “Local itemCount = 0”

18:17:39.148  0  -  Client - CraftingSystem:29
18:17:39.148  1  -  Client - CraftingSystem:29
18:17:39.148  2  -  Client - CraftingSystem:29
18:17:39.148  3  -  Client - CraftingSystem:29
18:17:39.148  4  -  Client - CraftingSystem:29

Fixing it brings it back up to the table value.

However, I’ve also tried to make it so it also destroys the tools once the script runs, to also see what’s happening, And it always leaves the ‘SMG Reciever’ Tool out.

local function removeItems()
	for i, tools in ipairs(craftingParts) do
		if backpack:FindFirstChild(tools) then
			local tool = backpack:FindFirstChild(tools)
			tool:Destroy()
		elseif player.Character:FindFirstChild(tools) then
			local tool = backpack:FindFirstChild(tools)
			tool:Destroy()
		end
	end
end

local result = checkTable()
	if result == #craftingParts then
		print("WIN")
		removeItems()
	end

Ah, Wait i may have found the solution! Hold on a minute till i confirm i actually fixed it lol

Yup. Fixed, Thank ya for that, laddy!

1 Like

No need to give my post the Solution, it was just a troubleshooting step. Put your post as the solution so people can read it instead of mine. :upside_down_face:

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