Weird loop behaviour [SOLVED]

Hello,

So i want to make a store shelf, and when its refilled, shop items appear on it to the specific amount.

But before i do most of the code, i wanted to test a loop which will create items and put it on the shelf, and how i did it is that there’s 2 folders where the first one is the items that are invisible which the other folder has visible items. But i ran into a problem.

The problem is, it did work normally but, there weren’t exactly the amount of items i wanted to, i wanted 15, i tried putting print and it did print 15 times but there was only 12-14 items on the shelf. Sometimes though, it did get 15 items on the shelf.

I have looked for solutions around the devforum but couldn’t find exactly what i need.

Here’s the code.

local folder = workspace.NotInserted:GetChildren()

for i = 1, 15 do
   print("inserted")
   local randomitem = folder[math.random(1, #folder)]
   randomitem.Parent = workspace.Inserted
   randomitem.Transparency = 0
   randomitem.CanCollide = true
end 

Any help would be appreciated.

define the children that are left in the “notinserted” folder per iteration, if you only define it once then it will also reference the children that have already been inserted.

I think it should look like this:

local folder = workspace.NotInserted:GetChildren()

for i = 1, 15 do
   print("inserted")
   folder = workspace.NotInserted:GetChildren()
   local randomitem = folder[math.random(1, #folder)]
   randomitem.Parent = workspace.Inserted
   randomitem.Transparency = 0
   randomitem.CanCollide = true
end

Just by defining the children in the loop

This is kinda late, but now the problem is fixed, Thank you @RatiusRat and @Gaming_Natan123, i appreciate the help!

local folder = workspace.NotInserted:GetChildren()

for i = 1, 15 do
	print("inserted")
	if #folder == 0 then break end --prevent error
	local randomitem = table.remove(folder, math.random(#folder))
	randomitem.Parent = workspace.Inserted
	randomitem.Transparency = 0
	randomitem.CanCollide = true
end