Help with finding how much a value increased with OnUpdate (DataStore2)

Hello Developers!!

I am working with Datastore 2 to make a script for the total income of something (for example if you earn 5 dollars and spend 3 dollars, your total income is 5 dollars)

I am trying to find out how much a value increased from its previous value using OnUpdate, but I am only able to retrieve the new value and I don’t know how to get the old value for the subtraction part of finding the increase.

Here is my current code:

timeStore:OnUpdate(function(new)
	leaderstats:WaitForChild("Time").Value = new
		
	coroutine.wrap(function()
		if new > 0 then
			local oldval -- Part I am stuck on
			local calculatedVal = oldval - new
			topStore:Increment(calculatedVal )
		end
	end)()
end)

Thank you! :slight_smile:

EDIT: More code can be provided if necessary.

timeStore:OnUpdate(function(new)
	leaderstats:WaitForChild("Time").Value = new
		
	coroutine.wrap(coroutine.create(function()) -- Add a coroutine.create() before the function
		if new > 0 then
			local oldval -- Part I am stuck on
			local calculatedVal = oldval - new
			topStore:Increment(calculatedVal )
		end
	end)() -- The two Brackets () will error 
end)

[/quote]

oldval is nil, you can’t put oldval - new

timeStore:OnUpdate(function(new)

	
coroutine.wrap(function()
	if new > 0 then
		local oldval = leaderstats:WaitForChild("Time").Value

        leaderstats:WaitForChild("Time").Value = new

		local calculatedVal = oldval - new
		topStore:Increment(calculatedVal )
	end
end)()
end)

This should work, I haven’t tested it since I’m on mobile.

I left oldval empty because I didn’t know how to get oldval

The coroutine was working for me at the start, I don’t think that was the problem. Sorry i didnt clarify that in the post :slight_smile:

1 Like

Hi, this worked with a bit of tweaking. Thank you so much!

1 Like