For i, v only working one value at a time

i have made a script that is supposed to check for a part in different folders. however, it only checks for one value until it is done checking before moving to the next one. i would like to have each value be checked simultaneously

local function zoneCheck(givenZone)

--finding part in the zone folder--
task.wait(1)
local attempts = 1
repeat
	local part = givenZone:FindFirstChildWhichIsA("Part")
	if not part then
		warn("No part found in zone folder "..givenZone.Name..", Attempts: "..attempts)
		attempts += 1
		task.wait(1)
	end
until part
print("found part for folder "..givenZone.Name.." in "..attempts.." attempt(s)")

end

for i,v in ipairs(ZonesFolder:GetChildren()) do
for j, w in ipairs(v:GetChildren()) do
zoneCheck(w)
end
end

i found out how to make it work, i used task.spawn() to run it

You should look into task.defer and when to use it instead of task.spawn (most cases)

local function zoneCheck(givenZone)
	--finding part in the zone folder--
	task.wait(1)
	local attempts = 1
	repeat
	local part = givenZone:FindFirstChildWhichIsA("Part")
	if not part then
		warn("No part found in zone folder "..givenZone.Name..", Attempts: "..attempts)
		attempts += 1
		task.wait(1)
	end
	until part
	print("found part for folder "..givenZone.Name.." in "..attempts.." attempt(s)")
end

for i,v in ipairs(ZonesFolder:GetChildren()) do
	for j, w in ipairs(v:GetChildren()) do
		zoneCheck(w)
	end
end

I know this had already been solved, but I would like to suggest some improvements to the code:

local maxAttempts = 20 -- Maximum amount of attempts before exiting out

local function zoneCheck(givenZone)
	local part = nil
	for attempts = 1, maxAttempts do -- Rather than using a repeat ... until loop, let's exit out after an X amount of attempts
		task.wait(1)
		part = givenZone:FindFirstChildWhichIsA("Part")
		if part ~= nil then
			break
		else
			warn("No part found in zone folder "..givenZone.Name..", Attempts: "..attempts)
		end
	end
	if part ~= nil then
		print("found part for folder", givenZone.Name, "in", attempts, "attempt(s)")
	else
		print("failed to find part for folder", givenZone.Name, "within", maxAttempts, "amount of attempts!")
	end
end

zoneCheck = coroutine.wrap(zoneCheck) -- Let's wrap the function as a coroutine. This will prevent yielding the scope that it will run under.

for i,v in ipairs(ZonesFolder:GetChildren()) do
	for j, w in ipairs(v:GetChildren()) do
		zoneCheck(w)
	end
end

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