For loop not running the in the correct way

Hello developers! I’m currently working on a horror backrooms game on roblox, now I’m working on a items system, I’ve used a way that uses tagged parts to be the spawns.

I’ve also made a system that pickups random models to be the “Item”, now the problem is, I’m using a system that places all spawn in a table and them, in a for loop, it try uses the spawn, if it was used or not, the script will remove this spawn from the table.

Everything is working fine, I have just a problem that the for loop in my script doesn’t run in the correct way.

The for loop is supposted to run the amount of instances that are tagged with “Spawn” (17 Instances), but, for some reason, it just runs 9 times! Idk what to do.

I would be grateful if anyone could help

Here’s the script:

local items = {
	"Almond",
	"Almond",
	"Almond",
	"Flashlight",
}

local UsableSpawns = {
	
}

local CS = game:GetService("CollectionService")
local Spawns = CS:GetTagged("Spawns")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local itemsFolder = ReplicatedStorage.Items

for i, v in pairs(Spawns) do
	table.insert(UsableSpawns, v)
end



local function selectItem()
	print(#UsableSpawns)
for i, v in pairs(UsableSpawns) do
	local item = items[math.random(1,#items)]
	local itemClone = itemsFolder:FindFirstChild(item):Clone()
local chances = math.random(1,6)
if chances == 1 and table.find(UsableSpawns, v) and v.Parent.Parent.Parent == workspace then
	print("An Item was spawned! ".. itemClone.Name, itemClone.Parent)
	itemClone.Parent = v.Parent.Parent
	itemClone.PrimaryPart.CFrame = v.CFrame
end
	table.remove(UsableSpawns, table.find(UsableSpawns, v))
	print(#UsableSpawns,i, v)
	task.wait()
end
end
	
	selectItem()

Here’s the output (Ignore errors, this bug does not print errors):

Captura de tela 2024-10-16 114735
Captura de tela 2024-10-16 114742

Sorrry for bad english, for more informations just ask me

just quickly looking over your script, the problem is that you loop trough a table while removing items from it

you can easily overcome this with a while loop instead

while #UsableSpawns > 0 do
local spawn = UsableSpawns[1]
[...]
table.remove(UsableSpawns, 1)
end
1 Like

I need to get the “v” from the for loop

Also, where do I put this? In the first or the second loop?

local spawn = UsableSpawns[1]

Would be your “v”

And you do not put this in any loop. Its a loop by itself

Oh, I think I’ve understanded it

Thank you so much, it worked!

Captura de tela 2024-10-16 121930

1 Like

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