What you’ve got here is not a standard table - it’s a dictionary. Dictionaries with string keys cannot be referenced with numbers because they do not have a specific order, regardless of whether in your code they do appear to be in a logical order.
For example, to reference the first index in your dictionary, you’d do Rarities["Common"]
, not Rarities[1]
, because items in dictionaries are referenced by keys rather than number positions.
There is a way to use numbers to reference the values of each dictionary key, but there’s no guarantee it’ll be in order. I wouldn’t recommend the following method if you’re relying on the order being the same every time, but it will allow you to reference the values with numbers whilst keeping the original format as a dictionary with string keys. The getValues()
function simply returns a table with number indices.
local Rarities = {
Common = { title = "Common", rarity = 550 };
Rare = { title = "Rare", rarity = 320 };
Epic = { title = "Epic", rarity = 120 };
Legendary = { title = "Legendary", rarity = 30 };
Mythic = { title = "Mythic", rarity = 5 };
}
local function getValues(dict: { [string]: any }): { any }
local values = {}
for _,v in Rarities do
table.insert(values, v)
end
return values
end
local rarityValues = getValues(Rarities)
local common = rarityValues[1] -- but Common might not always be the first index...
For your particular case, and since you’re already storing the titles of the rarities inside the actual values, you could get around the issue by just using a numbered array instead. For that, you’d just change the keys of your dictionary to numbers. If there’s a reason why you’d need to loop through the rarities in order using ipairs
or anything like that, you’ll want to do the following anyway:
local Rarities = {
[1] = { title = "Common", rarity = 550 };
[2] = { title = "Rare", rarity = 320 };
[3] = { title = "Epic", rarity = 120 };
[4] = { title = "Legendary", rarity = 30 };
[5] = { title = "Mythic", rarity = 5 };
}
For more information on understanding dictionaries, check out:
Intro to Dictionaries | Documentation - Roblox Creator Hub