How can I list the inventory item number order without skipping?

I’m in the middle of a first person game, and I got a bug where I used item limiters and the order of the numbers of the items was skipped. How do I get the items to go into the inventory in order? For your information, the script is like this. Is the script a bad code? I’d appreciate your help

local limit = 3


function updateTools()


	local backpack = game.Players.LocalPlayer:WaitForChild("Backpack")
	local char = script.Parent


	local tools = {}

	for i, child in pairs(char:GetChildren()) do
		if child:IsA("Tool") then table.insert(tools, child) end
	end

	for i, tool in pairs(backpack:GetChildren()) do
		table.insert(tools, tool)
	end	


	for i, tool in pairs(tools) do
		
		if i > limit then tool:Destroy() end
	end
end



local backpack = game.Players.LocalPlayer:WaitForChild("Backpack")

backpack.DescendantAdded:Connect(updateTools)
backpack.DescendantRemoving:Connect(updateTools)

workspace.DescendantAdded:Connect(updateTools)
workspace.DescendantRemoving:Connect(updateTools)
1 Like