roblox how to make a leaderboard code example

Example 1: how to make a leaderstats script

function onPlayerEntered(newPlayer)
	wait(.5)
	local stats = Instance.new("IntValue")
	stats.Name = "leaderstats"

	local score = Instance.new("IntValue")
	
	score.Name = "Cash" -- Change "Cash" with Your Leaderstats Name
	score.Value = 0

	score.Parent = stats	
	stats.Parent = newPlayer
end

game.Players.ChildAdded:connect(onPlayerEntered)

Example 2: global leaderboard roblox

local DataStoreService = game:GetService("DataStoreService")
local PointsODS = DataStoreService:GetOrderedDataStore("Points") 
 
local function printTopTenPlayers()
	local isAscending = false
	local pageSize = 10
	local pages = PointsODS:GetSortedAsync(isAscending, pageSize)
	local topTen = pages:GetCurrentPage()
 
	-- The data in 'topTen' is stored with the index being the index on the page
	-- For each item, 'data.key' is the key in the OrderedDataStore and 'data.value' is the value
	for rank, data in ipairs(topTen) do
		local name = data.key
		local points = data.value
		print(data.key .. " is ranked #" .. rank .. " with " .. data.value .. "points")
	end
 
	-- Potentially load the next page...
	--pages:AdvanceToNextPageAsync()
end
 
-- Create some data
PointsODS:SetAsync("Alex", 55)
PointsODS:SetAsync("Charley", 32)
PointsODS:SetAsync("Sydney", 68)
 
-- Display the top ten players
printTopTenPlayers()