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

[Help!] Button to exchange Money for Levels using [DataStore] .Any way to fix this script?

I'm trying to make a button where it exchanges the players 100 Money for 1 Level. The error is Callbacks cannot yield USING DATASTORE If someone could give me advice I would appreciate it!

local LevelStore = game:GetService("DataStoreService"):GetDataStore("LevelStorageNEW")
local MoneyStore = game:GetService("DataStoreService"):GetDataStore("MoneyStorageNEW")
local Player = game.Players.LocalPlayer

script.Parent.MouseButton1Click:Connect(function()
	local key = "user_" .. Player.userId
	local key2 = "user_" .. Player.userId
	MoneyStore:UpdateAsync(key, function(oldValue)
		local newValue = oldValue or 0
		newValue = newValue - 100
	LevelStore:UpdateAsync(key2, function(oldValue2)
		local newValue2 = oldValue2 or 0
		newValue2 = newValue2 + 1
		return newValue
		end)
	end)
end)

1 answer

UpdateAsync does not allow you to use anything that yields within it's function, and that's why you get that error. That also includes other Datastore calls.

You need rearrange your end statements so they are one after the other and not one within the other.

local LevelStore = game:GetService("DataStoreService"):GetDataStore("LevelStorageNEW")
local MoneyStore = game:GetService("DataStoreService"):GetDataStore("MoneyStorageNEW")
local Player = game.Players.LocalPlayer

script.Parent.MouseButton1Click:Connect(function()
    local key = "user_" .. Player.userId
    local key2 = "user_" .. Player.userId
    MoneyStore:UpdateAsync(key, function(oldValue)
        local newValue = oldValue or 0
        newValue = newValue - 100
    end)
    LevelStore:UpdateAsync(key2, function(oldValue2)
        local newValue2 = oldValue2 or 0
        newValue2 = newValue2 + 1
        return newValue
    end)
end)

However, using UpdateAsync is pointless here as you are updating player data, something SetAsync will do just fine as there is no risk a different server will change it.

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