Error with requiring a table from a module script

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
image

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
1 Like

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.

2 Likes

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.

1 Like

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.

2 Likes

Didn’t see this, you beat me to it… :neutral_face:

1 Like

Thanks that fixed the error. Do you have any knowledge on weighted odds because I think i might need to redo this function.

1 Like

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