Updating a table in a for loop

I’m creating an Inventory where it updates its own children every time something is added into it. The problem with my current code is that when a child is added to the inventory, it reiterates through the whole again, essentially cloning the loop, and duplicating an item when clicked.

local Table = script.Parent.Frame

local function loop()
	for i, v in pairs(Table:GetChildren()) do
		if v:IsA("ImageButton") then
			v.MouseButton1Click:Connect(function()
				print(v) -- prints +1 times every time a child is added
			end)
		end
	end
end

Table.ChildAdded:Connect(function()
	loop()
end)

loop() -- This is here to make sure you can interact with the Table

I’ve tried to find an idea on how to solve this, hence the title being the idea I have, but any help and guidance is appreciated.

I’ll rewrite the code to make it easier instead of explaining step-by-step on how to fix this problem.

local Table = script.Parent.Frame

local function buttonFunction(v)
	print(v)
end

local function add(v)
	if v:IsA("ImageButton") then
		v.MouseButton1Click:Connect(function()
			buttonFunction(v)
		end)
	end
end

local function init()
	for _, v in Table:GetChildren() do
		add(v)
	end
end

init() -- This is here to make sure you can interact with the Table

Table.ChildAdded:Connect(add) --When something is added, it will be interacted with instead of going through the whole loop

Why don’t you do something like this instead?

local Table = script.Parent.Frame

Table.ChildAdded:Connect(function(child)
	if child:IsA("ImageButton") then
		child.MouseButton1Click:Connect(function()
			print(child)
		end)
	end
end)

What you’re doing will end up being really inefficient and costly. Every time you pick up a new item, every single item is being given another signal.

Both replies pretty much worked the same way, thank you!

Yes, but I think you and I also forgot to point out that creating a lengthy function for the child.MouseButton1Click is also quite costly, but in memory. I recommend creating a function that can handle all of the buttons the same.

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