Help with loop not breaking

So I was working on a rhythm game with a friend, and we (mostly my friend) made this script to detect input, and it should work fine, except for one tiny problem, that being a break statement is causing an error on line 51 for some reason. The break is inside of a loop, so it shouldn’t give off an error.


Local script inside of StarterCharacterScripts:

local UIS = game:GetService("UserInputService")
local Camera = workspace.CurrentCamera
local IsPlaying = false
local SpawnNote = game.ReplicatedStorage.Remotes.SpawnNote
local InputF = game.ReplicatedStorage.Remotes.InputF
local SelectedPlayArea
local ShouldBreak
local Keybinds = {Enum.KeyCode.D,Enum.KeyCode.F,Enum.KeyCode.J,Enum.KeyCode.K}
local RunService = game:GetService("RunService")

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.G and IsPlaying == false then
		
		
		for i,v in pairs(game.Workspace.GameAreas:GetChildren()) do
			if v.InUse.Value == false then
				SelectedPlayArea = v
				SelectedPlayArea.InUse.Value = true
				break
			end
		end
		Camera.CameraType = "Scriptable"
		Camera.CameraSubject = SelectedPlayArea.View
		Camera.CFrame = SelectedPlayArea.View.CFrame - Vector3.new(0,0,10)
		IsPlaying = true
		UIS.InputBegan:Connect(function(input)
			if input.KeyCode == Enum.KeyCode.Q then
				SpawnNote:InvokeServer(SelectedPlayArea,1,30)
			end
		end)
	end
end)




UIS.InputBegan:Connect(function(input,Typing)
	if Typing == false and SelectedPlayArea then
		if table.find(Keybinds,input.KeyCode) then
			while true do
				
				
				InputF:InvokeServer(table.find(Keybinds,input.KeyCode),SelectedPlayArea,"Start")
				
				UIS.InputEnded:Connect(function(input,e)
					
					if e == false and SelectedPlayArea then
						
						if table.find(Keybinds,input.KeyCode) then
							InputF:InvokeServer(table.find(Keybinds,input.KeyCode),SelectedPlayArea,"End")
							break -- this is the line that is causing the errror.
						end
					end
						
				end)
				
				
				wait(0.1)
			end
			
		end
		
	end
end)

Image of the error:

image

We have tried a few different things to try to get this to work, but has nothing has worked so far, so any help is appreciated!

Have you tried replacing the true in your loop with a variable?

local state = true

while state do
     print("hello")
     state = false
end

This is only an example, and it should only print once.

1 Like

You’re getting that error because the break statement is not executing in a while loop; it’s in the function hooked into UIS.InputEnded:Connect(). Currently, your while loop is only connecting the function to InputEnded… but it’s not executing it at that time.

1 Like

Thank you, that fixed the bug we were having, I will try to use that more!