It’s because what you’re storing is a Dictionary Table, which doesn’t have an ordered index. Imagine this, if we had a simple table with just numbers like so:
local simpleTableWithJustNumbers = { 10, 20, 500, 300, 2 }
This with the indexes (visual purposes only) would look like this.
local simpleTableWithJustNumbers = {
[1] = 10,
[2] = 20,
[3] = 500,
[4] = 300,
[5] = 2
}
And if we used a for loop with ipairs, this would iterate in order (from index 1 to 5). This comes to the issue with your code, this is how you would visualise your table.
local petTable = {
["Bunny"] = 20,
["Dog"] = 60,
["Cat"] = 100,
}
There’s no way to numerically order this, how does the program know how to organise this? It doesn’t. So a work around for this is to store these properties in tables, like so (this is another visual example of what it would look like to the program):
local petTable = {
[1] = {
PetName = "Bunny",
Rarity = 20
},
[2] = {
PetName = "Dog",
Rarity = 60
},
[3] = {
PetName = "Cat",
Rarity = 100
}
}
Now the program knows how to iterate through them (order being Bunny, Dog and Cat). In that case, this is your updated code, I hope this helped you.
local petTable = {
{
PetName = "Bunny",
Rarity = 20
},
{
PetName = "Dog",
Rarity = 60
},
{
PetName = "Cat",
Rarity = 100
}
}
for i, v in ipairs(petTable) do
print(rng)
if rng <= v.Rarity then
print(v.Rarity )
selectedRarity = v.Rarity
local pet
if v.Rarity == 20 then
pet = "Bunny"
costCheck(plr, pet)
elseif v.Rarity == 60 then
pet = "Dog"
costCheck(plr, pet)
elseif v.Rarity == 100 then
pet = "Cat"
costCheck(plr, pet)
end
print(pet)
break
end
rng -= v.Rarity
end