For loop iterates multiple times in table, only needs to once

Attempting a list of equipped items on a player, but I noticed an issue where multiple amounts of the same item will end up being created in the ‘equipped’ list.

I isolated the code used to create the GUI for the inventory, and I’m assuming the issue is that using the for loop iterates through each 'item inside the ‘inventory’ module I have and performs the ‘panel’ creation no matter what checks I do.

I’m not entirely sure how I can iterate through each item in my ‘inventory’ module ONCE and be able to properly check if there’s an existing ‘equipped item’ GUI to prevent all of this. I attempted to use next (not even sure if it’s applicable for this issue) and because of what I’m iterating through, it complained about string values, so that’s not gonna work… No idea what to do.

for _,item in pairs(inventory:GetTable(inv)) do
		if item.Equipped then
			print("found equipped item, check if in eqlist")
			for _,panel in eqitemlist:GetChildren() do
				print("checking")
				if panel:IsA("Frame") and panel.id.Value == item.ID then
					print(panel.id.Value)
					print(item.ID)
					print("item is equipped and in list, do nothing")
				elseif panel:IsA("Frame") and panel.id.Value ~= item.ID then
					print("item equipped, not in list, add now")
					itempanel = eqitemtemp.item:Clone()
					itempanel.Parent = eqitemlist
					itempanel.Name = item.Name
					itempanel.itemname.Text = item.Name
					--itempanel.itemamt.Text = item.Amount
					itempanel.itemimg.Image = item.Image
					itempanel.id.Value = item.ID
					itempanel.Visible = true
				else
					itempanel = eqitemtemp.item:Clone()
					itempanel.Parent = eqitemlist
					itempanel.Name = item.Name
					itempanel.itemname.Text = item.Name
					--itempanel.itemamt.Text = item.Amount
					itempanel.itemimg.Image = item.Image
					itempanel.id.Value = item.ID
					itempanel.Visible = true
				end
			end
		elseif not item.Equipped then
			for _,panel in eqitemlist:GetChildren() do
				if panel:IsA("Frame") and panel.id.Value == item.ID then
					print("destroy!")
					panel:Destroy()
				end
			end
		end
	end

You have multiple loops nested. Use the break statement.

Thank you! I assumed some other things if I used break but this did the trick flawlessly lol

1 Like

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