How to make a global data store

Hello, I am wondering how to make a data store where it tracks global stuff like the amount of one pet owned in a game or the total currency of everybody etc. How would I go about doing this and what all do I need to know about the limitations and implimentation?

local DataStore = game:GetService("DataStoreService"):GetDataStore("Data") -- Creates a new DataStore

I know how to make a datastore lol, im talking about like for example if you want for there to only be 100,000 of a certain item in an economy, how can you track the current amount?

1 Like

Add the current amount to a datastore.

It’s similar to setting the player’s data, except you have to use GlobalDataStore and not GetDataStore. So probably every time the player leaves, you have to check their old data, get the difference, and then add that to the GlobalDataStore.

local function UpdateGlobalDataStore(pets: number, cash: number)
    -- why update async because it allows us to access the old data without
    -- using get async, also this is what the documentation recommends 
    GlobalStore:UpdateAsync(globalKey, function(oldData)
        if not oldData then
            return {
                Pets = if pets >= 0 then pets else 0,
                Cash = if cash >= 0 then cash else 0,
            }
        end

        local petsSum = oldData.Pets + pets
        local cashSum = oldData.Cash + cash

        oldData.Pets = if petsSum >= 0 then petsSum else 0
        oldData.Cash = if cashSum >= 0 then cashSum else 0

        return oldData
    end)
end
PlayerStore:UpdateAsync(playerKey, function(oldData)
    if not oldData then return currentData

    local petsDifference = currentData.Pets - oldData.Pets
    local cashDifference = currentData.Cash - oldData.Cash

    UpdateGlobalDataStore(petsDifference, cashDifference)
end)

Not sure if it works.

1 Like