Hello, I am needing support on something I am having issues with. I am wanting to add more data into a table which is in a DataStore and then saving that new table with the new data in it. So when a Player purchases a vehicle it will insert that vehicle name into the table and the previous purchased vehicles will still be in that table.
I believe you use table.insert()
but have no idea how to use it in this scenario.
Perhaps this? :
table.insert(data, "Vehicle 2")
local success,errormessage = pcall(function()
old = vehicleDataStore:SetAsync(player.UserId, {
data
})
end)
To insert string into table which DataStore will read, you will need just to have a string and use function table.insert(table, value)
as you have mentioned earlier. Table is basically a table which value will be inserted and for value to insert could be: numbers, strings, booleans and etc.
-- Two tables because it will be comfortable to work in these.
local data = {
strings = {}
}
-- We're storing a value into one variable, which assigned as string and we will insert this into table "data".
local vehicle = "Vehicle 1"
table.insert(data.strings, vehicle)
After table.insert(table, value)
have been called, you can print contains of data.strings table by iterating them!
local data = {
strings = {}
}
local vehicle = "Vehicle 0"
table.insert(data.strings, vehicle)
for _, value in pairs(data.strings) do
if value then
print("Strings table contained a value: "..value)
end
end
Expected output will be: Strings table contained a value: Vehicle 0
From this how would I put it into a DataStore?
local Players = game:GetService('Players')
local DSS = game:GetService('DataStoreService')
local VehicleStorage = DSS:GetDataStore("VehicleDatabase")
local data = {
strings = {}
}
local vehicle = "Vehicle 1"
game.Players.PlayerAdded:Connect(function(player)
local response
local success,errormessage = pcall(function()
response = VehicleStorage:GetAsync(player.UserId)
end)
if success then
if response then
print("Found Data: "..table.concat(response.strings))
else
table.insert(data.strings, vehicle)
local success,errormessage = pcall(function()
VehicleStorage:SetAsync(player.UserId, data)
end)
end
else
print("There was an error while getting data")
warn(errormessage)
end
end)
game:GetService('ReplicatedStorage').RemoteEvent.OnServerEvent:Connect(function(player)
local newVehicle = "Vehicle 0"
local response
local success,errormessage = pcall(function()
response = VehicleStorage:GetAsync(player.UserId)
end)
if success then
if response then
for _, value in pairs(response.strings) do
if value then
print("Strings table contained a value: "..value)
local data1 = {
strings = {
value,
newVehicle
}
}
local success,errormessage = pcall(function()
VehicleStorage:UpdateAsync(player.UserId, data1)
end)
if success then
print("Successfully added purchased car.")
end
end
end
end
end
end)