Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

how to break a while loop immediately after a value changes?

local function SpawnPillars()
	while true do
		if dead == true then
			print("break")
			break
		end

		local Points = MakePillar()

		for i = 1, #Points do
			tweenPart(Points[i], 15, {Position = Points[i].Position - Vector3.new(60,0,0)}, true)
		end

		wait(waitTime)
	end
end

At the beginning of the loop I wrote an if condition to check if dead is true or not, but it only checks after the wait(waitTime) at the end, which means it only checks every 3.5 seconds. I want the loop to repeat every 3.5 seconds but I also want to break it immediately when dead is true, not after 3.5 seconds. Any solution?

2 comments

0

To answer your question on my post, I believe it will break out of the for loop, however I used that method because the for loop is placed at the end of the while true do loop, meaning that the second that for loop ends the while loop will repeat.

0

oh thanks, i just want to tell u that i found a solution so i will use my method

3 answers

While loop runs with condition, you can do like:

local function SpawnPillars()
    while not dead do -- not dead is a condition
        wait(waitTime) -- make it wait then check so it would stop right away then dead is false
      local Points = MakePillar()
        for i = 1, #Points do
            tweenPart(Points[i], 15, {Position = Points[i].Position - Vector3.new(60,0,0)}, true)
        end
    end
end

1 comment

0

that doesn't work, it's still the same. At first it checks if dead is true or not, then wait then do stuff and checks again, if dead = true and becomes false in less than the wait time the function will keep running even though the player is dead once.

so guys i found a solution, look something like this:

local function a()
if dead == false then
-- do stuff
wait(waitTime)

return a()

else
wait()
return a()
end

a()

Maybe you can use 2 while loop?

try this


local function SpawnPillars()
	spawn(function()
		while wait() do
			if dead then
				print(“break”)
				break
			end
		end
	end)

	spawn(function()
		while wait(waitTime) do
			local Points = MakePillar()

			for i=1, #Points do
				tweenPart(Points[i], 15, {Position = Points[i].Position - Vector3.new(60,0,0)}, true)
			end
		end
	end)
end

If it still delays then maybe you can try coroutine (threading)

Im still not advanced at coroutine (I don’t really undertand it) so you can check at roblox docs https://developer.roblox.com/en-us/api-reference/lua-docs/coroutine

Im gonna learn coroutine rn (You can also learn coroutine from devking on youtube)

This discussion is preserved as it was. New answers, comments, and votes are closed.