How to update only a single table within a datastore?

Let’s say that when a player leaves, their health and inventory get saved in this way:

local D = game:GetService("DataStoreService"):GetDataStore("MultiplayerData")
local data = {Health = 100, Inventory = {"A","B","C"}}

game.Players.PlayerRemoving:Connect(function(player)
  local DS = nil
  local success, errorm = pcall(function()
    DS = Datastore:SetAsync(player.UserId, data)
  end)
  if not success then
    player:Kick("Error setting data: "..errorm)
  end
end)

This will save both player’s health and inventory. However, if I ever wanted to save only the player’s health, without making any changes to the inventory, how would I do it?

One way I imagined doing this to create a table containing the new health value and copy over the inventory from whatever it was previously, and then setting it into the datastore. However, I fear that doing this would be very laggy and inefficient, especially with larger tables.

Note: I would rather to not create separate datastores, one for health, one for inventory.

You can use UpdateAsync() which gets the current value or you could use GetAsync() beforehand, and then use SetAsync() with the previous value fetched from GetAsync().

1 Like

:UpdateAsync() lets you consider the current data saved before changing it.
Here is an example of how you might do this. You might want to change this to fit your game.

local D = game:GetService("DataStoreService"):GetDataStore("MultiplayerData")

local function updateData(player, key, value)
    local success, err = pcall(function()
        D:UpdateAsync(player.UserId, function(old)
            -- Check if the data does not already exist
            if (old == nil) then
                -- Set to default data
                return {Health = 100, Inventory = {"A","B","C"}}
            else
                old[key] = value
                return old
            end
        end)
    end)
    return success
end
1 Like