Indexing Table of Datastores

Hey Devs,

I am trying to create a display in my game that picks random players within the top 100 of each Stat that I have chosen, however, I am not sure of how to begin with the ground-code for this system.

Here is my current code:

Summary
local ds = game:GetService("DataStoreService")

-- Leaderboards 
local FollowerLeaderboard = ds:GetOrderedDataStore("FollowerLeaderboard")
local LikeLeaderboard = ds:GetOrderedDataStore("LikeLeaderboard")
local MinutesLeaderboard = ds:GetOrderedDataStore("MinutesLeaderboard")
local RefreshLeaderboard = ds:GetOrderedDataStore("RefreshLeaderboard")

-- Creats table of Leaderboard Variables to choose randomly later
local leadersTable = {}
table.insert(leadersTable, 1, FollowerLeaderboard)
table.insert(leadersTable, 2, LikeLeaderboard)
table.insert(leadersTable, 3, MinutesLeaderboard)
table.insert(leadersTable, 4, RefreshLeaderboard)

local function change()
	
	local good, info = pcall(function()
		
		print(leadersTable)
		
		local randomboard = math.random(1,#leadersTable)
		local data = randomboard:GetSortedAsync(false,100)
		local page = data:GetCurrentPage()
		
		local player = math.random(1,#page)
		print(player)
		
	end)
	
	if not good then
		print(info)
	end
	
end

I am getting the error:
Workspace.Megetron.MegatronHandler:23: attempt to index number with 'GetSortedAsync'

Specifically, I want the code to choose a random leaderboard from the leadersTable, receive the information of that leaderboard inside of change, and then choose a random player on that leaderboard to have their stats displayed in game.

I am not very skilled as I have not worked with them much, but I know that my local randomboard = math.random(1,#leadersTable) is responsible for my current error, as randomboard is only the number of the selected value.

How can I get the value of the selected random board?

You have to index the table with that index.

local randomboard = leadersTable[math.random(1, #leadersTable)]
2 Likes

That worked!

So I assuming that I will have to do the same thing for local player = math.random(1,#page)?

Yes, you would have to do the same thing for that:

local player = page[math.random(1, #page)]
1 Like