SetAsync isnt working

I am trying to save data in my game, but it seems to not be working.

local DatastoreService = game:GetService("DataStoreService")

local DEVMODE = true

local coinsStore
local buttonsAmountStore

if DEVMODE then
	coinsStore = DatastoreService:GetDataStore("dev", "coins")
	buttonsAmountStore = DatastoreService:GetDataStore("dev", "buttonsAmount")
end

local function setDatastore(player, store, data)
	local success, result 
	repeat
	success, result = pcall(function()
		store:SetAsync(player.UserId, data)
	end)
	until success
	--[[
	if not success then
		setDatastore(player, store, data)
	end
	]]--
end

local function loadDatastores(player)
	local coins
	local buttonsAmount
	
	local success, result = pcall(function()
		coins = coinsStore:GetAsync(player.UserId)
		buttonsAmount = buttonsAmountStore:GetAsync(player.UserId)
	end)
	
	if not success then
		player:Kick("Loading the game failed, rejoin or contact the devs!")
	elseif coins == nil and buttonsAmount == nil then
		coins = 0
		buttonsAmount = 0
		setDatastore(player, coinsStore, 0)
		setDatastore(player, buttonsAmountStore, 0)
	elseif coins == nil then
		coins = 0
		setDatastore(player, coinsStore, 0)
	elseif buttonsAmount == 0 then
		buttonsAmountStore = 0
		setDatastore(player, buttonsAmountStore, 0)
	end
	return {
	["coins"] = coins,
	["buttonsAmount"] = buttonsAmount
	}
end

In studio, I get the error

 ServerScriptService.DatastoreHandler:48: Script timeout: exhausted allowed execution time

I assume the issue is in my setDatastore function but im not sure why.

By the way, this is being run when the player joins, and if they have no data, I am trying to set their datastore data. This function is not being used for saving player data upon them leaving. I have studio API access enabled.

I am fairly new to posting topics, so please leave feedback if needed.

Your looping this way too much, you need to give the script time to execute the :SetAsync. Also there are limits to how often you can set it, and you should set up a max fail amount. Heres what I would do:

local function setDatastore(player, store, data)
	local success, result
    local FailCount = 0

	repeat
	success, result = pcall(function()
		store:SetAsync(player.UserId, data)
	end)
    task.wait(0.1) -- You need this so you aren't looping quickly

    if not success then
       FailCount += 1
    end

	until success or FailCount >= 5
	
	if FailCount >= 5 then
		error("Data could not be set; "..result)
	end
	
end

Edit: Setted up fail count

For more information, Please see this roblox doc about server limits on datastore requests

1 Like

you aren’t putting a wait in between each repeat, so it’s basically like having a while loop without a wait.

1 Like

Thank you everyone, these worked!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.