Removing an unconditioned loop

How would I be able to remove the unconditioned loop from the following run script?

My concern with the while loop is that it requires a wait to prevent it crashing resulting in the script not stopping you running immediately. It is almost unnoticeable in this example, however I also know that using wait is a bad habit to fall into especially on more critical scripts.

Code
local UserInputService = game:GetService("UserInputService")

local KeyLShift = Enum.KeyCode.LeftShift
local KeyRShift = Enum.KeyCode.RightShift
local ShiftHeld

function InputStart(InputObject) -- A key has been pressed 
	if InputObject.KeyCode == KeyLShift or InputObject.KeyCode == KeyRShift then
		ShiftHeld = true
		while ShiftHeld == true do
			game.Players.LocalPlayer.Character:WaitForChild("Humanoid").WalkSpeed = 300 -- Runspeed
			wait()
		end
	end
	ShiftHeld = false
end

UserInputService.InputBegan:Connect(InputStart)

Run.rbxl (17.7 KB)

1 Like

You don’t need a loop at all here. Just set the WalkSpeed to 300 once, and set it back to normal when you set ShiftHeld to false.

3 Likes

With that aside, you can use break to stop/remove a loop. At least that looks like what you were asking originally so… correct me if I’m wrong!

1 Like

No, because the script wouldn’t know if shift had been let go. By adding another function onKeyRelease solves all of the problems.

1 Like