Lesson 2 - Database

Databases saves the progress of the game imagine that theres no database in a game that you have 10k points and if you leave all your progress will be GONE.

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

local DataStore = DataStoreService:GetDataStore("PlayerData_V1")

local DataService = {}
local PlayerData = {}

local DEFAULT_DATA = {
	Cash = 100,
	Level = 1
}

-- Load data
function DataService:Load(player)
	local data

	local success, err = pcall(function()
		data = DataStore:GetAsync(player.UserId)
	end)

	if success and data then
		PlayerData[player.UserId] = data
	else
		PlayerData[player.UserId] = table.clone(DEFAULT_DATA)
	end

	return PlayerData[player.UserId]
end

-- Get data
function DataService:Get(player)
	return PlayerData[player.UserId]
end

-- Save data
function DataService:Save(player)
	local data = PlayerData[player.UserId]
	if not data then return end

	local success, err = pcall(function()
		DataStore:SetAsync(player.UserId, data)
	end)

	if not success then
		warn("Failed to save data for", player.Name, err)
	end
end

-- Cleanup
function DataService:Remove(player)
	self:Save(player)
	PlayerData[player.UserId] = nil
end

return DataService

  
← Back