I’m trying to make a DataStore method in which I set the new instance’s properties not based on number-based indexing, but on the name of the instance. This way, I can set the instance’s properties without having to manually assign a number to each value of each instance. I want it to be done automatically in case I ever need to save and load more instances.
Here is the part of the code where I assign the instance values and save the data (for clarity’s sake, note that this is only meant to be a proof of concept):
local ds = game:GetService("DataStoreService"):GetDataStore("TestDataStore")
vals = {}
game.Players.PlayerRemoving:Connect(function(player)
for _, v in ipairs(workspace.Baseplate:GetChildren()) do
if v:IsA("ValueBase") then
vals[v.Name .. "-Name"] = v.Name
vals[v.Name .. "-Value"] = v.Value
end
end
ds:SetAsync(player.UserId, vals)
end)
For further reference, here is what “vals” looks like when printed:
How would I go about reading this data and assigning the properties accordingly?
If you would only store one value for that ValueBase, wouldn’t it be better if you just kept the key as the name and the value as the Value.
Something like:
{
["FirstValue"] = false
}
Or with multiple values, you can make another dictionary.
I should have specified that for this test, I’m creating new BoolValues based on the ones in the Baseplate. Obviously, these values need a name that matches the appropriate value.
game.Players.PlayerAdded:Connect(function(player)
local data = ds:GetAsync(player.UserId)
local f= Instance.new("Folder")
f.Name = "Values"
f.Parent = workspace
for _, v in pairs(data) do
local n = Instance.new("BoolValue")
n.Name = "NameHere"
n.Value = data[n.Name]
n.Parent = fold
end
end)
You are using the name to access the value. The name comes from the data in the datastore. The value is also part of that data.
Using my solution, the table has the key as its name and the value as its value. Therefore, you can name the BoolValue using the key, then set the value using value
game.Players.PlayerAdded:Connect(function(player)
local data = ds:GetAsync(player.UserId)
local f= Instance.new("Folder")
f.Name = "Values"
f.Parent = workspace
for key, val in pairs(data) do
local n = Instance.new("BoolValue")
n.Name = key
n.Value = val
n.Parent = fold
end
end)