Tutorial: sorting StringValue leaderstats in any order

I recently ran into the problem of sorting the player list with a leaderstats folder that uses StringValues. This is because I added custom abbreviation for the numbers. Example:

image

As you can see it sorts by the value of the string, not the value of the number. I evidently am not the first to face this problem: Leaderstat sort order

However, it is actually not impossible to sort strings in leaderstats. We can do this by using zero-width space unicodes. This is because the zero-width space unicode has a higher sorting value than all numbers. So, you can type these unicode characters with U+200B. Alternatively, I found a site that allows you to copy these unicodes: zerowidthspace.me.

So to sort, the more zero-width spaces I put before the string, the higher priority they have in the list. This is the result after implementing the zero-width spaces. Player1 has one zero-width space before their Cash string. Player2 has no zero-width spaces before their Cash string.

image

This is the code I used in my game:

local zeroWidthSpace = '​'

local function UpdateLeaderboardStats()
	local statInfos = {}
	
	-- Each playerDataManager holds the player's data such as money
	-- Each also holds the player's money string value
	-- So we compile a list of each string value and its associated money
	for _, playerDataManager in playerDataManagers do
		if playerDataManager._playerData then
			table.insert(statInfos, {
				
				Money = playerDataManager._playerData.Money,
				MoneyStringValue = playerDataManager._moneyStringValue
				
			})
		end
	end
	
	-- Now we sort the list by money least to greatest
	table.sort(statInfos, function(statInfo1, statInfo2)
		return statInfo1.Money < statInfo2.Money
	end)
	
	-- Now we update each string value
	for index, statInfo in statInfos do
		-- Repeat the zero-width space depending on their position in the list
		-- And then add the abbreviated money value on the end
		statInfo.MoneyStringValue.Value = `{zeroWidthSpace:rep(index - 1)}{Abbreviate(statInfo.Money)}`
	end
end

For anyone who has the same issue, hope this helps.

Edit: added comments

5 Likes

Heyy this is actually really cool! But I would recommend you to explain your code a bit. I mean I do understand it but lets compensate for the non scripters here yknow?

3 Likes

why do this when num vals already abbreviate for you

3 Likes

Roblox’s leaderstats abbreviations are slightly different. For example the number 1234 by default displays as 1,234. For my abbreviations, it displays as 1.2K. I did this because personally it may be distracting seeing all those numbers constantly change on the player list.

There may also be cases where you do not want any abbreviations, or maybe want to sort with other strings that are not supposed to be numbers.

2 Likes