We use cookies on this site to enhance your user experience

Data Store Game Config

Data Store Game Config

Sep 05 2018, 1:30 PM PST

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()