PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

GetDataStore

This method returns a GlobalDataStore by name/scope. Subsequent calls to this method with the same name/scope will return the same object.

Parameters

Name Type Default Description
global

Returns

Return Type Summary

Code Samples


Data Store Game Config

This code sample uses data stores to read/write/listen to a global configuration value. It uses a defensive coding style so potential data store errors will not cause issues.

local DATA_STORE_NAME = "Config"
local DATA_STORE_SCOPE = "MyGameName"
local KEY_NEW_FEATURE = "NewFeatureEnabled"

local DataStoreService = game:GetService("DataStoreService")

local dsConfig = DataStoreService:GetDataStore(DATA_STORE_NAME, DATA_STORE_SCOPE)

local function checkFeature()
	local isFeatureEnabled
	local success, err = pcall(function()
		isFeatureEnabled = dsConfig:GetAsync(KEY_NEW_FEATURE)
	end)
	if success then
		print(KEY_NEW_FEATURE .. ": " .. tostring(isFeatureEnabled))
		if isFeatureEnabled == true then
			print("Feature is enabled!")
		elseif isFeatureEnabled == false then
			print("Feature is disabled!")
		elseif isFeatureEnabled == nil then
			print("Feature is not set!")
		else
			-- Some other value was found in this key
		end
	else
		print("Failed to load feature! Error: " .. tostring(err))
	end
	return success
end

local function onFeatureChanged(isFeatureEnabled)
	print("Feature toggled: " .. tostring(isFeatureEnabled))
end

-- Listen for changes
dsConfig:OnUpdate(KEY_NEW_FEATURE, onFeatureChanged)

local function setFeatureEnabled(isFeatureEnabled)
	local success, err = pcall(function()
		dsConfig:SetAsync(KEY_NEW_FEATURE, isFeatureEnabled)
	end) 
	return success
end

setFeatureEnabled(true)
checkFeature()

Individual Player Data Stores

This code sample features a simple way to work with per-player data stores called “Stats” and “Resources.”

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

local function onPlayerAdded(player)
	local scope = "Player_" .. player.UserId
	local playerStats = DataStoreService:GetDataStore("Stats", scope)
	local playerResources = DataStoreService:GetDataStore("Resources", scope)
	-- GetAsync()/UpdateAsync() can now be called on the 'Stats' and 'Resources' data stores
end

Players.PlayerAdded:Connect(onPlayerAdded)