So I made a Datastore system in a module.
there are 4 functions:
save, get, init (initialize), and getdatastore
HOW IT WORKS
So basically, how it works, is that the server initializes the datastore (sets everything from the datastore into a table called DataTable).
Later, when the server gets the datastore info, they change values in the datastore table returned by the Get function.
When the Save function is called, it saves everything from the datastore table onto the actual datastore.
When the player joins again, it does the cycle again.
Feel free to ask questions if this is unclear.
The Problem
Whenever the server calls the Get function, the DataTable is somehow nil???
Here’s the code:
local Data = {}
local DataStoreService = game:GetService("DataStoreService")
local Modules = game.ServerStorage.ServerModules
local Settings = game.ServerStorage.ServerSettings
local DataTable = {}
Data.GetDatastore = function(player)
return DataStoreService:GetDataStore(require(game.ServerStorage.ServerSettings.MainSettings).DatastoreVersion)
end
Data.Init = function(player)
local FinalData
local Key = player.UserId .. "'s Data"
local data = Data.GetDatastore(player)
local s, err = pcall(function() FinalData = data:GetAsync(Key) end)
if s then
if player.DisplayName ~= player.Name then
print("✅ " .. player.DisplayName .. "(@" .. player.Name .. ")'s data was successfully retrieved!")
else
print("✅ " .. player.Name .. "'s data was successfully retrieved!")
end
else
if player.DisplayName ~= player.Name then
warn("(MAJOR ERROR) ❌ " .. player.DisplayName .. "(@" .. player.Name .. ")'s data was not able to be retrived!")
else
warn("(MAJOR ERROR) ❌ " .. player.Name .. "'s data was not able to be retrieved!")
end
warn("Error message: " .. err)
player:Kick("Your data was not able to be retrieved! You have been kicked to prevent data loss. (Roblox's datastores might be down...)")
end
local NewPlayer = (FinalData == nil)
if NewPlayer then
print("New player!")
data:SetAsync(Key, require(Settings.DefaultData))
DataTable[player.UserId] = require(Settings.DefaultData)
return true
end
DataTable[player.UserId] = Data.GetDatastore(player):GetAsync(Key)
end
Data.Save = function(player)
local FinalData
local Key = player.UserId .. "'s Data"
local data = Data.GetDatastore(player)
local s, err = pcall(function() data:UpdateAsync(Key, function() return DataTable[player.UserId] end) end)
if s then
return true, DataTable[player.UserId]
else
if player.DisplayName ~= player.Name then
warn("(MAJOR ERROR) ❌ " .. player.DisplayName .. "(@" .. player.Name .. ")'s data was not able to be saved!")
else
warn("(MAJOR ERROR) ❌ " .. player.Name .. "'s data was not able to be saved!")
end
warn("Error message: " .. err)
game.ReplicatedStorage.Communication.AddNotification:FireClient(player, "Your data was not able to be saved! Error message: " .. err, 10)
return false
end
end
Data.Get = function(player)
return DataTable[player.UserId]
end
return Data