Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to use my module script with DataStore? [closed]

Asked by 6 years ago
Edited 6 years ago

Here is my script, I have created a module script to save and load data with DataStores. My only question is how do I access sessionData from other scripts? sessionData holds all the data for each player but I can't figure out a way to access that table from other scripts.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("playerData")


sessionData = {}

DataStore.SomeFunction = function(parameters)
        return sessionData
end

Players.PlayerAdded:Connect(function(player)
    setupPlayerData(player)
end)

Players.PlayerRemoving:Connect(function(player)
    savePlayerData(player.userId)
end)

local function autoSave()
    while wait(60) do
        for playerUserId, data in pairs(sessionData) do
            savePlayerData(playerUserId)
        end
    end
end

spawn(autoSave)


function setupPlayerData(player)
    local playerUserId = player.userId
    local success, data = pcall(function()
        return playerData:GetAsync(playerUserId)
    end)
    if success then
        if data then
            sessionData[playerUserId] = data
        else
            sessionData[playerUserId] = {Bank=5000, Cash=0, Inventory={}, Vehicles={}, Gangs={}, Messages={}}
        end
    else
        error("Cannot access data store for player!")
    end
end

function savePlayerData(playerUserId)
    if sessionData[playerUserId] then
        local success, err = pcall(function()
            playerData:SetAsync(playerUserId, sessionData[playerUserId])
        end)
        if not success then
            error("Cannot save data for player!")
        end
    end
end

Closed as Too Broad by User#19524

This question has been closed because it is too broad and is generally unanswerable. Please ask a more specific question.

Why was this question closed?