Weird behaviour with DataStore2:Increment()

Hello,

In my game I use the following code:

function UpdateCoins(Player, Delta, purchased)
    purchased = purchased or false
    local CoinsDB = DataStore2(CoinsKey, Player)
    local CoinsBefore = CoinsDB:Get(0)
    
    local ActualDelta = Delta
    if MarketplaceService:UserOwnsGamePassAsync(Player.UserId, 9217590) and purchased == false and Delta > 0 then
        ActualDelta *= 2

    end
    ActualDelta = math.ceil(ActualDelta)
    CoinsDB:Increment(ActualDelta,0)
    local Coins = CoinsDB:Get(0)
    
    if Coins < 0 then
        local ErrorTable = {
            ["PlayerName"] = Player.Name;
            ["CoinsBefore"] = CoinsBefore;
            ["Delta"] = Delta;
            ["ActualDelta"] = ActualDelta;
            ["CalculatedDelta"] = Coins-CoinsBefore;
            ["Coins"] = Coins;
            ["Purchased"] = purchased;
        }
        local ErrorString = "Coins got <0 for "..Player.Name..". "..CoinsBefore..","..Delta..","..ActualDelta..","..Coins..","..tostring(purchased)
        warn(ErrorString)
        AnalyticsService:FireLogEvent(Player,Enum.AnalyticsLogLevel.Error, "CoinsGotBelow0", {}, ErrorTable)
    end
    
    SetCoins:FireClient(Player,Coins, ActualDelta)
end

Before I run this function, it always checks if the coins of the player are > Delta if Delta > 0. However, the coins still get set up, and the values in the ErrorTable are sometimes:
afbeelding
afbeelding
Does anyone see how the CalculatedDelta is not equal to the ActualDelta? I don’t have any clue, but it really affects my game. Thank you in advance.

The increment in your code is outside the if-condition, so it’ll increment even with a negative delta. All your if-condition currently does is increment the double amount of delta if it’s positive.

Yeah, that is the intended behaviour: The if-condition checks if the player owns a x2 coins-gamepass and therefore double the amount of coins when you receive coins (but not when you buy something - a negative delta means you are buying something)

Ah I see, very weird how CoinsBefore + ActualDelta don’t match with Coins after like in the image.

Is there perhaps some other function influencing Coins?

In your ErrorTable you are calculating CalculatedDelta by doing Coins - CoinsBefore. For each image this calculation means:

  • First Image: (-75) - 125 = -200
  • Second Image: (-149) - 321 = -470

Both are correct and in line with the images you sent. ActualDelta on the other hand is being set to Delta and maybe being multiplied by two, depending on if the user owns the gamepass and Delta is above 0 (which for both tests it wasn’t).

Somehow your CoinsDB is being incremented twice based on the results you are getting.