Trying to create a Loot Table using a Module Script

Hi there, I’m new to the forum and I am still learning how to script, so please be descriptive with your answers. :grinning:

I’m trying to use a Script to access all parts of my ModuleScript. I’m attempting to make a sort of loot table using weight. The script is in ServerScriptService, and I need to get a random item from my module script in ServerStorage.

This is my ModuleScript as of now.


From my script, I want to look at all of the items in this ModuleScript (I plan to add more), and pick a random one using the spawnWeight as a weight in the loot table.
I would prefer to use a ModuleScript as a basis for the loot table so all the items will be organized in a convenient place, rather than in a script that does other unrelated things.

I have looked around the Dev Forum for a solution which meets my needs, but haven’t found much. Many have suggested using ReplicatedStorage, but I don’t think it would fully solve the problem.
I can provide any other details that can help with solving the problem if needed.
Any help, suggestions, or changes would be appreciated! :slightly_smiling_face:

First, you should be aware that you added 2 commas after Knife in your table, which may be part of the problem.

Anyway, see if this helps:

local module = {}
module.Items = {
    --I'm slightly reformatting your table,
    --but you can do it the same way
    --as before if you want
    ["Sword"] = { index = {1}, spawnWeight = {20}}
    ["Knife"] = { index = {2}, spawnWeight = {50}}

return module
-- your other script

local function size(tabl)
    local count = 0
    for i,v in pairs(tabl) do
        count += 1
    return count
local module = require(game.ServerScriptService.ModuleScript)

local function selectnewitem()
    local number = math.random(1, size(module.Items))
    for i,v in pairs (module.Items) do
        If v.Index[1] == number then
            return i,v
local itemname,iteminfo = selectnewitem()

I’m not quite sure what you meant by this, please explain more.

1 Like

I’d recommend setting up your loot table preset to look something more like so:

	Sword = 20;
	Knife = 50;

With that, we can make a simple weighted chance function to randomly select an item from the loot table:

function GetRandomItem(lootTbl)
	local pool = {}
	for item,weight in pairs(lootTbl) do
		for i = 1,weight do

	return pool[math.random(#pool)]

Hope this helps!


Thank you both @iGiDgames and @AskForHeaven for your help. I was able to solve the problem. I had to change up several things and mix things from both of your concepts (and from some of my own), but I eventually solved the problem with your help. Heaven’s weighted random item function was a big help.
Thank you! :grinning:

1 Like

Ah so that’s what he meant by pool. Should have figured. Your method is super smart btw.