Is there a more efficient way of writing this?

Is there a more efficient way of writing the following code?
Thanks.
Winky.

local moving = true

while true do
	while not moving do
		
	end

	while moving do
	    wait()
	end
end
1 Like
3 Likes

How can I apply that to this situation? I added the

while not moving do
    wait()
end

Is there any other way I can tidy the code up?

What are you trying to accomplish with this code?

What does it look like?
Run a piece of code when a player is moving, stop it when they aren’t.

No, the code you wrote definitely does not look like that. It looks like an infinite loop with more steps :slight_smile:

edit: To do what you just described, see Humanoid | Documentation - Roblox Creator Hub

edit 2: Or better Humanoid | Documentation - Roblox Creator Hub

game.Workspace.Player.Humanoid.Running:Connect(function(speed)
    if speed > 0 then
        print("Player is running")
    else
        print("Player has stopped")
    end
end)
1 Like

As mentioned in the post @sjr04 shared a good way to avoid the repeat wait() trap could be to set up a bindable event and wait for it to fire. Then wherever in the script you’d normally change the flag variable, just fire the event instead.

while (true) do
	print("waiting for moving")
	movingStartedEvent:Wait()
	print("moving")
	movingStoppedEvent:Wait()
	print("stopped moving")
end
1 Like