Hello. I have a module script with some rarities and their weight for a weighted odd system but I’m getting an error when I try and use that table. I tried a table in the same script and it didn’t error.
I dont know how I forgot to add the error, my bad lmao
local Rarites = require(game.ReplicatedStorage.Rarites)
function RollRarity()
local rollTable = {}
for _, data in ipairs(Rarites) do
for i = 1, data.weight, 1 do
table.insert(rollTable, data)
end
end
local roll = math.random(1, #rollTable)
return roll
end
Module script:
local Rarites = {
['Basic'] ={
weight = 30,
multi = 1,
};
['Common'] ={
weight = 10,
multi = 1,
};
['Uncommon'] ={
weight = 5,
multi = 1,
};
['Rare'] ={
weight = 1,
multi = 1,
};
['Legendary'] ={
weight = 0.66,
multi = 1,
};
}
return Rarites
Does the code actually work in practice? You said its an error, but in the image is a warning and I don’t see why it wouldn’t work in a module if it does when it’s in the same script.
The table Rarites is not an array in nature, it’s a dictionary. Arrays start from index 1 and go up to x, whereas dictionaries are saved in specified key/value form. Because of this, using ipairs makes no sense, because ipairs expects the table to be in array form. If you are trying to loop through all of the rarit[i]es, you should use pairs instead.
This is because Rarities is an a dictionary, meaning each value is assigned to a key, not a number. ipairs returns an iterator function that uses an incremented number to search through the array, but since this is a dictionary with no numerical entries, it cannot loop through it. Instead, you should use pairs, since it works indiscriminantly to the type of index and simply loops through the table.
This is also why pairs is seperate from ipairs, because pairs returns an iterator function that doesn’t go through the table in a numerical order, just in the way the contents are in the table.
To make things clear, the difference is that pairs doesn’t necessarily respect the order of an array, and ipairs does. This doesn’t work in this case, because Rarites is a dictionary and pairs just loops through all items without respect of the order, which doesn’t exist for a dictionary. Also pretty sure rarites should be rarities.