How to access a Dictionary in roblox

Here’s My Code:

local Items = require(game:GetService("ReplicatedStorage"):WaitForChild("Items"))

function module:GetRandomItem(Player)
	local Rarity = RandomRarityFunc.PickRandom()
	--Just Returns a Random Rarity like "Common", "Uncommon", "Epic", etc

	local function Length(Table)
		local Counter = 0
		for i, v in pairs(Table) do
			Counter = Counter + 1
		end
		return Counter
	end
	
	local ItemsOfRarity = {}
	
	for i = 1, Length(Items) do
		print(Items)
		if Items[i].Rarity == Rarity then
			table.insert(ItemsOfRarity, Items[i])
		end
	end		
        local RandNum = math.random(1, #ItemsOfRarity)
	
	local Data = {}
	table.insert(Data, ItemsOfRarity[RandNum])
	table.insert(Data, Rarity)
	
	return Data
end

I am a New Developer (Exp:11 Months) and I am making a Random Item Giving System based on Rarity. This is a small part of that code inside a Module Script. For some reason this Code Dosen’t Work.

Item[1] shows nil when trying to print.

Btw, here’s how the Items module looks like. Its Unfinished

You’re using string indexes inside your items module ([“Banana Peel”] = …), and trying to access it with number indexes, instead of doing for i = 1, Length(Items) do, you will want to do

for itemName, itemData in pairs(Items) do
	if itemData.Rarity == Rarity then
		table.insert(ItemsOfRarity, itemData)
	end
end

I wanted to return the key as a string to use it in another script but this code is returning a table. I was using a code very similar to this one and somehow it was returning strings not tables.

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