How would I add Values to int values inside data stores?

I tried to do this for a while, just a simple Integer inside a data store.

local datastore = game:GetService("DataStoreService"):GetDataStore("Datalol")
local data = datastore:GetAsync("1")
local Players = game:GetService("Players")

print(data)

Players.PlayerAdded:Connect(function(plr)
	while wait(2) do
		data = data + 1
	end
end)

Players.PlayerRemoving:Connect(function(player)
	datastore:UpdateAsync("1", function()
		return data
	end)
end)

I have attempted to do it with the code but didn’t succed, it’s my first time coding this.

1 Like

Could you tell me the use for this? It seems pretty useless unless you want to just try how to do datastores.

Just playing around with data stores nothing much.

What exactly is the error you are having with this script?

local data = datastore:GetAsync("1")

This is ‘nil’ if the ‘DataStore’ key isn’t defined resulting in an error at the data = data + 1 line.

local data = datastore:GetAsync("1") or 0 --Default value.
1 Like

there are a few problems with your script

when you do local data = datastore:GetAsync("1")
this is getting a value from the key 1

now lets say you have 10 servers running on your game

each server will load a value from the 1 key depending on what the value was in the datastore at the time so it might be nil for some servers it might be a different value for other servers depending on when that server started

then when a player leaves the game the server will write the value to the 1 key but this value will be different on each server

another problem you have is that your while wait(2) do loop with contiune to run forever even after the player has left the game

so here is how to do it

local players = game:GetService("Players")
local dataStoreService = game:GetService("DataStoreService")
local dataStore = dataStoreService:GetDataStore("Datalol")
local data = 0

-- every 2 seconds add 1 to data for each player that is online
while true do
	data += #players:GetPlayers()
	task.wait(2)
end

-- when the server closes add data to key 1 in the datastore
-- WARNING all servers are only allowed to write to key 1 once every 6 seconds
-- so if you shutdown all the servers at the same time it might fail to save all servers data
game:BindToClose(function()
	datastore:UpdateAsync("1", function(value)
		return (value or 0) + data
	end)
end)

you might also want to read this Data Stores | Roblox Creator Documentation

here is a video i made that shows how to read and write player data using intvalues, numbervalues, boolvalues, stringvalues