Scripts skips for loop problem

Something weirds happening in my script. I’m trying to make a sell function for my towers so it will first loop through the tower and check what it’s wort and then destroy it, but if I don’t put a wait before the destroy which is placed after the loop then it errors:

local sellPrice = 0
	
	sellPrice += mainModule.Towers[tower.Name].Price
	
	for i,v in pairs(mainModule.Towers[tower.Name].Upgrades) do
		if tower.Upgrade.Value >= i then -- Upgrade is not a valid member of tower
			sellPrice += v.Price
		end
	end
	
	task.wait(5) -- when I put the wait it doesn't error
	
	tower:Destroy()

so it skips to the destroy part before finishing the loop, I printed it.

6 Likes