I want to be able to have a dictionary and be able to save it and load it. All tutorials on datastores are for single values.
I have tried editing other scripts and searching everywhere but I just don’t understand it. Any explanation would be helpful.
So say you have a dictionary of data here from a player. It’s indexed in your datastore with the player’s user id, which is stored in the variable userId
:
{
Money = 50
Experience = 100
}
you want to change their data so that their Experience
equals 10,000
, because they just paid for VIP.
You would have to retrieve your data from the datastore first, using DataStore:GetAsync
:
local dictionary
repeat
local success = false
success, dictionary = pcall(DataStore.GetAsync, DataStore, userId)
until success == true
You will then have the dictionary in hand, for you to edit! So, let’s change that value:
dictionary.Experience = 10000
Once you are done editing this table, you can just save it using DataStore:SetAsync
:
repeat
local success = pcall(DataStore.SetAsync, DataStore, userId, dictionary)
until success == true
After this, your VIP player will get this information from the datastore and notice that he now has 10,000 experience.
Please ask more questions if you have them, because this explanation is not really all too complete.
1 Like
What would be the best way to access the datastore though another script?
You would access it the same way you would from your first script. You would get the same data and datastore no matter where you get it from, as long as they get it at the same time and it wasn’t changed between accessing and saving the data:
In one script:
local DataStore = DataStoreService:GetDataStore(scope, name)
-- just imagine good coding practice here
success1, dictionary1 = pcall(DataStore.GetAsync, DataStore, userId)
In another script:
-- spoiler, I copied and pasted it
local DataStore = DataStoreService:GetDataStore(scope, name)
success2, dictionary2 = pcall(DataStore.GetAsync, DataStore, userId)
If you were to compare both dictionaries, they would have the same values:
print(dictionary1.Money == dictionary2.Money) --> true!
print(dictionary1.Experience == dictionary2.Experience) --> true!
Accessing datastores from multiple scripts wouldn’t be recommended though, it is best to try and stay as independent of the datastore as possible and accessing the data only when you need to. Usually, you would just save the dictionary in a module and load/update it from there:
local DataStoreModule = require(path.to.DataStoreModule)
local playerMoney = DataStoreModule[userId].Money -- or something like that
If you use a module though, make sure to destroy the data when the player leaves so that memory doesn’t build up!
2 Likes