Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I Loop Save with DataStore?

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

 
game.Players.PlayerAdded:connect(function(player)
wait(3)
	local key = "user_" .. player.userId    --we want to give 50 points to users each time they visit
	DataStore:UpdateAsync(key, function(oldValue)
		local newValue = oldValue or 300 --oldValue might be nil
		

local label = player.PlayerGui.TimeLeft.Frame.TimeLeftLabel
local ready = player.PlayerGui.TimeLeft.Frame.Ready.ReadyToVisit

while true do
if ready.Value == false then
label.Visible = true
repeat
print("repeat")
newValue = newValue - 1
print(newValue)
label.Text = newValue
wait(0.1) --60
--return newValue
until newValue == 0 or ready.Value == true
label.Visible = false
ready.Value = true
end
wait(5)	 --60
end
		
		return newValue
	end)
end)

This script is suppose to be a timer that goes down, and when you leave the time left saves. How could I keep the timer going and save the time at the same time?

An example of what I want to happen:

Bob enters the game for the first time.
The timer is set at 300.
Bob stays in the game for 160.
Bob leaves.
*When Bob enters, the timer starts at 140*

1 answer

✓ Accepted answer

ONLY the saving bit;

local timerStart = 300
local joinTimes = {}
Game["Players"]["PlayerAdded"]:connect(
    function(Player)
        joinTimes[Player] = os.time()
    end
)

Game["Players"]["PlayerRemoving"]:connect(
    function(Player)
         data:UpdateAsync(tostring(Player["userId"]),  
             function(previousValue)
                 previousValue = previousValue or timerStart
                 return previousValue - (os.time() - joinTimes[Player])
             end
    end
)

4 comments

2

If this isn't what you wanted, please inform me and I will edit my answer.

0

Please do not refrence your services like that, use :FindService or :GetService.

1

There's nothing wrong with referencing a Service directly. Game["Players"] is the same as Game.Players. If someone is bright enough to change the name of the service, they're probably bright enough to fix scripts referencing it.

0

I think I understand the script but could you 'implement it'? If you can't I THINK I can try something else.

This discussion is preserved as it was. New answers, comments, and votes are closed.