Hello. I was trying to figure out how to store, save, and load data with a table. I can’t seem to figure it out.
Here is the script:
local dss = game:GetService("DataStoreService")
local ds = dss:GetDataStore("UserSettings")
local settingvalues = { -- all value names should be the same as the name of the frames
-- Graphics ---------------------------
PerfMode = false,
Shadows = true,
Time = "Day",
Weather = "Clear",
-- Interface --------------------------
Speedmeter = false,
Unit = "Imperial"
-- Others -----------------------------
}
local function setSetting(key, value)
settingvalues[key] = value
end
local players = game:GetService("Players")
for _, values in pairs(players:GetDescendants()) do
if values:IsA("BoolValue") then
values.Changed:Connect(function()
setSetting(values.Parent.Name, values.Value)
end)
elseif values:IsA("StringValue") then
values.Changed:Connect(function()
setSetting(values.Parent.Name, values.Value)
end)
end
end
How would I store, save, and load data using the table?
Firstly, since this is probably a server script, the value change signals would not fire if they are changed on the client. You would have to have a Remote Event that sends the server the data whenever the client interacts with the settings UI.
On the server, you would have a queue of data that is to be saved. Every 15 seconds the data is saved for all players that are in the queue and then their queue status is set to nil. Also if the player leaves the game, any data in the queue should save to. But don’t forget if when the server shuts down (game:BindToClose())(which may be unexpected), the queue should once save all the data.
Nothing here is actually setting that table to the data. On player removing, or intermittently, you need to save this table to a key, and then load it again when you join. For example:
game.Players.PlayerRemoving:Connect(function(player)
ds:SetAsync(player.UserId, settingvalues)
end)
game.Players.PlayerAdded:Connect(function(player)
local data = ds:GetAsync(player.UserId) -- you now have the data you saved, do what you want with this from here
end)
Also, I imagine you would want the settingsvalues to be unique for every player so you would need to make a version for each player like this:
local defautlvalues = {
-- Graphics ---------------------------
PerfMode = false,
Shadows = true,
Time = "Day",
Weather = "Clear",
-- Interface --------------------------
Speedmeter = false,
Unit = "Imperial"
-- Others -----------------------------
}
local settingvalues = {}
game.Players.PlayerAdded:Connect(function(player)
local data = ds:GetAsync(player.UserId)
settingvalues[player] = data or defautlvalues -- set to the saved value, or if no saved value, the default
end)
local function setSetting(player, key, value)
settingvalues[player][key] = value -- now you would instead set this to the player's own settings, otherwise players can alter eachothers settings
end