Datastore2 not working

Why does datastore2 not work for me? datastore2 doesnt save when player leaves the server and I tried 2 whole days fixing and I cant fix it

local function SaveData(plr)
	local MainDataStore = Datas2("MainDataStore-Test222", plr)
	local Stats = plr:WaitForChild("Stat")
	local Cash = Stats.Cash.Value
	local Multi = Stats.Multiplier.Value
	local Rebirth = Stats.Rebirth.Value

	local defaultTab = {
		Cash,
		Multi,
		Rebirth,
	}
	
MainDataStore:Set(defaultTab)
print(MainDataStore:GetTable(output))
end

if not game:GetService("RunService"):IsStudio() then
	game:BindToClose(function()
		for i, v in pairs(game.Players:GetChildren()) do
			SaveData(v)
		end
	end)
end

What about insted of BindToClose use game.Players.PlayerRemoving

I can’t answer your question properly due to the lack of code being shown. I’m not sure where the Stat Instance is being created from, which could also be a problem.

However I’m able to tell you that you should use the built in combined function as such:

Datastore2.Combine("MasteryKey", "Cash", "Rebirths", "Multiplier")

The MasteryKey is in the name, essentially, a master key which contains all the ‘data’.

I’d also like to remind you that you shouldn’t use other sources to save data except the built in :Set() function.

Instead of setting player.leaderstats.Cash.Value = n ( Or where ever you change the value of ‘Cash’ ) you should use Datastore2("Cash", player):Set(n). And if you only want to increment the amount then you can use Datastore2("Cash", player):Increment(n).

You can use this:

datastore2.Combine("MasteryKey-1915", "Cash")

local function PlayerAdded(player: Player)
	local cashStore = datastore2("Cash", player)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local cash = Instance.new("NumberValue")
	cash.Name = "Cash"
	cash.Value = cashStore:Get(0) -- the 0 inside is just a default value if the player doesn't have any data.
	cash.Parent = leaderstats
	
	cashStore:OnUpdate(function(newValue)
		cash = newValue
	end)
end

players.PlayerAdded:Connect(PlayerAdded)

To simply listen for when a player joins. Then create a leaderstats folder and the ‘Cash’ NumberValue. And then update the ‘Cash’ NumberValue’ whenever the actual cash amount changes.

A function to add some money to the player is as such:

local function AddMoney(player: Player, amount: number)
	datastore2("Cash", player):Increment(amount, 0) -- the 0 is just a default value if the player has no cash/data.
end

I’d also like to mention that you don’t need to use :Set() when the player leaves. Datastore2 automatically saves the player’s data.

Hope this helps in some way.

the thing is i cannot use that way because im storing my values with string because of another module im using to make numbers go further than 1e308

Don’t use :Set() here, just use :GetTable(defaultTab). The argument is the default table if you have no data.