Hello everyone, I am making a system in which any server script can call the function _G.LoadDataStore(key) and get the table saved in there. And if they call _G.SaveDataStore(key,data) they can save the data in the selected key. Would this script work?
local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerStats") _G.LoadDataStore = function(key) local SavedValues = DataStore:GetAsync(key) if SavedValues then return SavedValues else return "NoData" end end _G.SaveDataStore = function(key, data) DataStore:SetAsync(key, data) end
Another script:
local DataToSave = {50, 30, 60} _G.SaveDataStore("player_1234, DataToSave)
Would the data save?
Another Script:
local LoadedData = _G.LoadDataStore("player_1234") print(LoadedData[1])
Would the data in the first position in the table of that datastore displayed inside the console?
The best way to go about doing this is using a module script.
So this is how you can set up the module script:
local module = {} local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerStats") function module.LoadData(key) local SavedValues = DataStore:GetAsync(key) if SavedValues then return SavedValues else return "NoData" end end function module.SaveData(key, data) DataStore:SetAsync(key, data) end return module
Now that your module script is set up, all you need to do is call require from any other script, and then you will be able to call the functions that you set up in this script.
Script example:
local sss = game:GetService("ServerScriptService") local moduleScript = require(sss.Script) -- assuming the module script is under serverscriptservice and is called 'script' -- loading data local data = moduleScript.LoadData(key) -- saving data moduleScript.SaveData(key, data)
Hope this helped!
Note: When saving data, use the player's userId as the key, and not their name, because users are able to change their names