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

How do I save a DataStore in a :BindToClose() function? [Solved]

Asked by 3 years ago
Edited by JesseSong 3 years ago

This question has been solved by the original poster.

Hello developers, I'm unsure how to save data in :BindToClose(). I've tried ways such as:

game:BindToClose(function()
    local Player = game:GetService("Players"):GetPlayers()
    local playerid = "Player_"..Player.UserId
    local data = Player.leaderstats.deaths.Value

    local success, errormessage = pcall(function()
        HisDataStore:SetAsync(playerid, data)
    end)

    if success then
        print("Data has been successfully saved!")
    else
        print("Data has not been saved, negative!")
        warn(errormessage)
    end
end) 

I've tried this way but doesn't work. Gives the error 'attempt to concatenate string with nil' on the line local playerid = "Player_"..Player.UserId

I can see the mistake but I am rather confused how to fix it.

0
TIP: When a question is solved by you, it's good to write [Solved] or [Answered] at the front or end of the question, so that it won't be marked as unanswered. JesseSong 3916 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago

I found out the answer. I used a for loop to iterate the players.

Code:

game:BindToClose(function()
    local Player = game:GetService("Players")
    for _, players in pairs(Player:GetPlayers()) do
        local playerid = "Player_"..players.UserId
        local data = players.leaderstats.deaths.Value

        local success, errormessage = pcall(function()
            HisDataStore:SetAsync(playerid, data)
        end)

        if success then
            print("Data has been successfully saved in studio!")
        else
            print("Data has not been saved, negative!")
            warn(errormessage)
        end
    end
end)
Ad

Answer this question