DataStore2 infinite loop problem

  1. What do you want to achieve?
    I have a value that saves your current hunger in the datastore. Every time it gets changed I want it to fire to the client to update the hunger GUI. If the value is < 0 then I set the hunger value back to 0.

  2. What is the issue?
    The problem is when I update the hunger value back to 0 if it’s < 0 is that it causes an infinite loop because I use :Set() to set it back to 0. This causes it to run the update function running the loop again.

  3. What solutions have you tried so far?
    I have tried others ways to change it but it results in the same issue.

	local CurrentHunger = Datastore("CurrentHunger", Player)
	CurrentHunger:Get(100)

	local function CurrentHungerUpdated(UpdatedHunger)				
		if CurrentHunger:Get(100) <= 0 then 
			CurrentHunger:Set(0)
			UpdatedHunger = 0 	
		end
				
		Events.UpdateGui:FireClient(Player, "CurrentHunger", UpdatedHunger, MaxHunger:Get(100))	
	end

	CurrentHunger:OnUpdate(CurrentHungerUpdated)

This isn’t related, but you shouldn’t save your hunger every time it changes, only when the player leaves.

Also, you should be handling this 100% client side, there is no reason for you to be using :FireClient() to tell the client info it can already access.

The system you have for handling this looks a bit inefficient. It would make much more sense to have a NumberValue inside the player that holds the value than constantly using :Get(), as well as you will be able to access the hunger value from the client.

Another thing, when you do

You will be able to use that NumberValue rather than checking the datastore.