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

Why is the code no saving or loading is working right?

Asked by 5 years ago
Edited 5 years ago

``local currencyName = "Coins"

local DataStore = game:GetService("DataStoreService"):GetDataStore("DataStore")

game.Players.PlayerAdded:Connect(function(player)

local folder = Instance.new("Folder")
folder.Name = "leaderstats"
folder.Parent = player

local currency = Instance.new("IntValue")
currency.Name = currencyName
currency.Parent = folder

local ID = currencyName.."-"..player.UserId
local savedData = nil

pcall(function()
    local savedData = DataStore:GetAsync(ID)
end)

if savedData ~= nil then
    currency.Value = savedData
else
    currency.Value = 10
    print("New")
end

end)

game.Players.PlayerRemoving:Connect(function(player)

local ID = currencyName.."-"..player.UserId

DataStore:SetAsync(ID,player.leaderstats[currencyName].Value)

end)

game:BindToClose(function()

for i, player in pairs(game.Players:GetPlayers())do

    if player then 

        player:Kick("this game is shutting down")
    end
end

wait(5)

end)

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

Make sure to accept this answer if it solved your problem!

Question

Why is the code no saving or loading is working right?

Problem

In your pcall statement you define a new function. Inside that function you define a new variable savedData. The local keyword creates a variable in the current scope. You're currently creating the variable inside the scope of the anonymous function you passed to pcall.

Solution

Simply remove the local from the savedData declaration inside the pcall.

Example Code

local savedData = nil

pcall(function()
    savedData = DataStore:GetAsync(ID)
end)

Extra Resources

http://lua-users.org/wiki/ScopeTutorial

0
It is not working it should be able to work right? Staven2u 2 — 5y
Ad

Answer this question