So I'm writing an inventory ModuleScript that saves a table to the player's UserID through a datastore, to do this, I've loosely followed the Roblox Developer Hub tutorial.
local DS = game:GetService("DataStoreService")
local Store = DS:GetDataStore("Datastore")
local AUTOSAVE_INTERVAL = 10
local SessionData = {}
local PlayerInventoryManager = {}
function PlayerInventoryManager:ChangeInventory(player, item, value)
local UserID = "Player_" .. player.UserId
assert(typeof(SessionData[UserID][item]) == typeof(value), "ChangeInventory error: data types do not match")
if typeof(SessionData[UserID][item]) == "number" then
SessionData[UserID][item] = SessionData[UserID][item] + value
else
SessionData[UserID][item] = value
end
end
local function SetupPlayerData(player)
local UserID = "Player_" .. player.UserId
local Data = Store:GetAsync(UserID)
if Data then
SessionData = Data
for i, v in next, SessionData do
print(i, v)
end
else
SessionData[UserID] = {Stone = 0}
for i, v in next, SessionData do
print(i, v)
end
warn("No data found for " .. UserID)
end
end
local function savePlayerData(UserID)
if SessionData[UserID] then
Store:SetAsync(UserID, SessionData[UserID])
end
end
local function saveOnExit(player)
local UserID = "Player_" .. player.UserId
savePlayerData(UserID)
end
local function autoSave()
while wait(AUTOSAVE_INTERVAL) do
for UserID, data in pairs(SessionData) do
savePlayerData(UserID)
end
end
end
spawn(autoSave)
game.Players.PlayerAdded:Connect(SetupPlayerData)
game.Players.PlayerRemoving:Connect(saveOnExit)
return PlayerInventoryManager
I want scripts to be able to access SessionData so it can add and remove data before being copied to PlayerInventoryManager and saved, so I wrote this Script in ServerScriptService:
game.Players.PlayerAdded:Connect(function(player)
local module = require(script.Parent.ModuleScript)
local item = "testsss"
local value = 1
wait(1)
module:ChangeInventory(player, item, value)
end)
However after this, I get the error ServerScriptService.ModuleScript:9: attempt to index nil with 'testsss'.
Does anyone know how to fix this, and/or point me in the direction of how to properly use ModuleScripts for saving player data?
