Scripting Weekly Leaderboards

How would I go about creating leaderboards that just take into account the last 7 days of playing?

In the past, I used an OrderedDataStore for leaderboards that spanned the entire history of the game. But if I want to restrict things to just the last 7 days, I am not sure how to do that since there is no timestamp or query capabilities in an OrderedDataStore.

3 Likes

At present I do not believe this is possible. You could alternatively have leaderboards which reset every week by setting the scope parameter of the ordered datastore to be something which changes once a week.

Since there is no limit on the number of datastore you can create… you could just make a new leaderboard each week just iterate up every 7 days.

IE :GetOrderedDataStore(“1”)
:GetOrderedDataStore(“2”)
:GetOrderedDataStore(“3”)
:GetOrderedDataStore(“4”)

1 Like

To expand upon what others have already mentioned, it might be better to make leaderboards that last up to the end of the week. That way you can do things such as weekly prizes. To make weekly leaderboards, you would first need to figure out what week you’re in, which you can do with os.time()

local WEEK_LENGTH = 60*60*24*7 -- week length in seconds
local WEEK_NUMBER = math.floor(os.time()/WEEK_LENGTH) -- current week as a number

Now that you know your week number, you can make an OrderedDataStore key using that number.

local EXAMPLE_KEY = "WeeklyLeaderboard"..tostring(WEEK_NUMBER)

Now when you want to make changes to your OrderedDataStore you generate this key and then use it to load and write to the current week’s leaderboard.

Hello As8D :eyes:

13 Likes

While this is a bit different from what you want (at any time you want to find the records updated within the last 7 days), what I do for one of my projects is to generate an unique identifier for each week, starting monday - when that happens, I just switch to that new OrderedDataStore, and let it fill up through the next 7 days, until which the os.time() timestamp will find the next week’s identifier to use.

local function getWeekId() -- returns the amount of days since the epoch, clamped to Monday.
	local dateInfo = os.date("!*t", os.time())
	return (os.time({year = dateInfo.year, month = dateInfo.month, day = dateInfo.day, hour = 0}) - ((dateInfo.wday - 2) % 7) * DAY) / DAY
end

Here’s a little utility snippet - hey Zome :eyes:

3 Likes

Great suggestion, thank you.

What do you do when the year rolls over, and then the week number repeats? For example, I don’t want to include last year’s week 1, with this year’s week 1 results.

His system does that automatically, the week number is how many weeks have passed since UNIX time starts (1st of january 1970), so its always an incremental number. The number of the 1st week of January 2019 will be 52 more than the 1st week of January 2018.

6 Likes