Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to use Data Stores?

How do I exactly use Data Stores. The wiki makes no sense to me. Could anyone give a small explaination?

1 answer

DataStoreService, as you know, is a service that stores data in data stores. A data store can be created or referenced using the GetDataStore method.

local dataStoreService = game:GetService("DataStoreService");
local myDataStore = dataStoreService:GetDataStore("Stored");

Data is stored in key-value pairs, like a table. You can get a value you stored by key using the GetAsync method of the data store.

local cash = myDataStore:GetAsync("Cash");
if cash == nil then -- If Cash was never saved to the data store
	print("No cash saved!");
else -- Otherwise
	print(cash); -- Print the value
end

To save a value, you use SaveAsync:

myDataStore:SetAsync("Cash", 100); -- Save 100 to the Cash key of the data store

If you want to do something with the old value you can use UpdateAsync as it gives you the value of the key and whatever you return from the callback function (the second argument in UpdateAsync) will be what the key is set to:

myDataStore:UpdateAsync("Cash", function(currentCash)
	if currentCash == nil then -- If there was no cash saved
		return 100; -- Save 100 cash
	else -- Otherwise
		return currentCash + 100; -- Save how much cash there was before plus 100
	end
end);

But there is another method that you may find useful: IncrementAsync. Take our addition of cash for example, instead of using UpdateAsync to add 100, you can use IncrementAsync;

myDataStore:IncrementAsync("Cash", 100); -- Add 100 to our current cash

2 comments

0

How do you know that cash is there. Don't i put it in leaderstats?

0

Well, no that's your job. I just showed you how you can save the value of that IntValue (in example) to data store. Cash is actually the key you use to save it so you know what to load.

This discussion is preserved as it was. New answers, comments, and votes are closed.