Table[number] returning nil?

I’m trying to make a system where you spin for something and theres different rarities. So I wrote this code to get a random instance in a random rarity to then send it back to the client to show them. This is the code:

local function getRarity()
	local random = math.random(1,100)
	if random == 1 then
		return "Legendary"
	elseif random > 1 and random < 31 then
		return "Rare"
	elseif random > 31 then
		return "Common"

local function Length(rarity)
	local counter = 0 
	for _, v in pairs(rarity) do
		counter =counter + 1
	return counter

replicatedStorage.SummonTower.OnServerInvoke = function(player)
	if player then
		local chosenRarity = getRarity()
		local rarityTable = towers[chosenRarity]
		local length = Length(rarityTable)
		local random = math.random(1,length)
		return rarityTable[random]

However, rarityTable[random] and rarityTable[1] both return nil. For anyone wondering, this is what the table looks like

local TowerShop = {
		["Common"] = {
			["CCTV-Man"] = {
				["Name"] = "CCTV-Man",
				["ImageAsset"] = "",
			["Speakerman"] = {
				["Name"] = "Speakerman",
				["ImageAsset"] = '',
			["TV-Man"] = {
				["Name"] = "TV-Man",
				["ImageAsset"] = "",

Any help is appreciated, thanks!

1 Like

This is because they are not indexed as numbers, they are indexed as strings

and since these are both numbers it will return nil, if you wanted to get the first one it would look something like this:


also in this if the number is 31 it returns nothing

Your not using a table, you are using a dictionary. They require special treatment when iterating and indexing.

How else would I index the random number in the dictionary then?

Take a look at:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.