Example
Leaderboard
Live leaderboard with compression, paginated fetch, and periodic push updates.
local scores = {}
app:Get("leaderboard", function(Player, Payload, req, res)
local page = tonumber(req.query.page) or 1
local limit = math.min(tonumber(req.query.limit) or 10, 50)
local sorted = {}
for userId, score in pairs(scores) do
table.insert(sorted, { userId = userId, score = score })
end
table.sort(sorted, function(a, b) return a.score > b.score end)
local start = (page - 1) * limit + 1
res:Send({ entries = { table.unpack(sorted, start, start + limit - 1) }, total = #sorted })
end, { compress = true })
app:Post("leaderboard/submit", function(Player, Payload, req, res)
local score = req.data and req.data.score
if type(score) ~= "number" then res:Status(400):Error("score required"); return end
scores[Player.UserId] = math.max(scores[Player.UserId] or 0, score)
res:Send({ best = scores[Player.UserId] })
end)
-- push top-10 update every 30 s
task.spawn(function()
while true do
task.wait(30)
local sorted = {}
for userId, score in pairs(scores) do
table.insert(sorted, { userId = userId, score = score })
end
table.sort(sorted, function(a, b) return a.score > b.score end)
app:PushAll("leaderboard.update", { table.unpack(sorted, 1, 10) })
end
end)
See also
App | compress option · Server Push · Codec | compression algorithm · Player Data | persisting scores to DataStore