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"
	end
end

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

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

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"] = "http://www.roblox.com/asset/?id=13749054780",
			},
			["Speakerman"] = {
				["Name"] = "Speakerman",
				["ImageAsset"] = 'http://www.roblox.com/asset/?id=13749300689',
			},
			["TV-Man"] = {
				["Name"] = "TV-Man",
				["ImageAsset"] = "http://www.roblox.com/asset/?id=13767180458",
			},
	},
	
	}

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:

rarityTable['CCTV-Man']

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.