Preventing Multiple Loops from Starting

For this example, I have a fishing system in my game. The flow is like this:

Player Clicks on Fishing Spot → Sends Request to Server → Server Begins Fishing Loop

The loop is like this

function Player:beginFishing()
	self.state = States.Fishing
		while (self.state == States.Fishing) do
			-- Catch fish

The problem: If the user stops fishing (their state goes from Fishing to None) and then clicks on the fishing spot again within the time that wait(X) is yielding, another loop will spawn because the first loop has a wait in it before the while loop’s condition is checked again.

So when the while loop checks again, the user is set to Fishing state again. So both loops keep running.

I have a lot of skills that use a loop system like this. So I am looking for suggestions on a scalable method to handle this issue.

Use an attribute or other variable to track if the player is currently fishing.

1 Like

No need for that, that isn’t the issue. The issue is a race condition of the first loop yielding and beginFishing being called again.

This issue has been resolved by an outside person on a Discord called CodeSupport anyways. The race condition is resolved by using a jobID that stores the current action has a random integer. After the yield of task.wait the job ID is currently checked against the cached one when the loop begin.

1 Like