Hello. I am trying to make a script to return a random object inside of a dictionary influenced by a “Rarity” value inside of the object (sorry if this is badly explained).
I’ve tried a function I found to find something in a table, I’ve used table.find and tried using a number index (obviously doesn’t work) and I have no other ideas.
local ChosenItem = nil
for i, v in pairs (Dictionary) do
local Rarity = v.Rarity
if math.random(1, Rarity) == 1 then
ChosenItem = i
end
end
print(ChosenItem)
Thanks. I know this is a stupid question, but would this have bias towards the items at the beginning of the table since it runs through them in order?
Actually quite the opposite, it would favor items at the end since it would cycle through them and they would end up setting the ChosenItem value last, whereas the first ones are being overwritten
oh yeah, didn’t think about that lol. Is there a way to run through everything without bias? I’m sorry I’m asking so many questions but I want to make the rarities as accurate as I can.
The only, slightly inconvenient, way of doing this that I have found (there could be others) would be adding every single rarity together and doing a math.random(1, totalrarities) and assigning ranges to each rarity, so in the end items with 1 rarity would be the rarest, and high numbers would be common. That might’ve been a little confusing explanation but here’s some code to back it up if you want to use this method:
local Dictionary = {
["Item1"] = {
["Rarity"] = 15,
},
["Item2"] = {
["Rarity"] = 10,
},
["Item3"] = {
["Rarity"] = 1,
}
}
local RarityDictionary = {}
local CurrentHighestRarity = 0
for i, v in pairs(Dictionary) do
RarityDictionary[i] = {
["Min"] = CurrentHighestRarity+1,
["Max"] = CurrentHighestRarity+(v.Rarity + 1)
}
CurrentHighestRarity = (v.Rarity + 1)
end
local ChosenItemRarity = math.random(1,CurrentHighestRarity)
local ChosenItem = nil
for i, v in pairs(RarityDictionary) do
if ChosenItemRarity <= v.Max and ChosenItemRarity >= v.Min then
ChosenItem = i
end
end
I tested this, but it’s only returning four different items out of a much larger list.
Edit: I’ve tested both methods, and they are both only returning a few of the possible items, despite returning a wide rarity range.
There are around 23 items in the list, but it only prints these. 15 is the most common out of the plates. Not sure if this is important, but some plates have the same rarity number.