While true do and if statements

Hello, I’m trying to achieve a script where when I press a button it will scroll through images in a loop, and then when I click the button again it will stop the loop. I came across a problem while coding where I have an if statement and I want to tie it into a while true do statement but I’m not sure how to approach it. Could be the fact that it’s 3 am and hard to think of anything but I don’t know.

Code Example:

local UserInput = game:GetService("UserInputService")

local OpenKey = Enum.KeyCode.P

local Frm = script.Parent

local IsOpen = true

local function onInput(input)
	if input.KeyCode == OpenKey then
		if IsOpen then
				while true do
				for i, v in pairs(Images) do
					vh.Image = v
					task.wait(0.1)
				end
			end		
		else
                --Disable while true do
		end
		IsOpen = not IsOpen
	end
end

UserInput.InputBegan:Connect(onInput)

It would be amazing if someone could tell me how to tie this together and disable it after you press the button or lead me to articles to help me with it.

Thank you,
Thothboy

Why don’t you type:

local function onInput(input)
	if input.KeyCode == OpenKey then
		if IsOpen then
				while IsOpen == true do --while the IsOpen variable is true it should repeat that
				for i, v in pairs(Images) do
					vh.Image = v
					task.wait(0.1)
				end
			end		
		else
		end
		IsOpen = not IsOpen
	end
end

Instead of it always running you can just say while the variable is true it should repeat.
I didn’t test the script out because I don’t have access to roblox studio right now.

Or you could use break. You can find more information on break online.

1 Like

Thank you, a good idea that I tried but it doesn’t work it will continue running through the loop not allowing me to click the button for the else statement. I figured out the solution though which was to put the while true statement on the outside and just manually activate it from the function like this:

local function onInput(input)
	if input.KeyCode == openKey then
		if isOpen then
			vhGUI.Enabled = true

		else
			vhGUI.Enabled = false
		end
		isOpen = not isOpen
	end
end

UserInput.InputBegan:Connect(onInput)

while true do
	for i, v in pairs(StaticImages) do
		vhs.Image = v
		task.wait(0.1)
	end
end	

Thank you for the help though.

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