Need help rerolling table items by chance

As you may be able to tell by the title of the topic, I want to make a ‘reroll’ function which returns a table value. This I can do, however, I want to be able to tweak the chances of returning certain items and just don’t know where to start. Any suggestions would be much appreciated!

so you want to shuffle a table but there is a chance some values won’t be there?

i want to choose a single value from a table but there’s a lower chance some will be chosen than others, it’s how i’m trying to incorporate item rarity into my game

Hey, are you looking for something like this?

Code

1 Like
local ItemTable = {
    ["Item1"] = 5,
    ["Item2"] = 10,
    ["Item3"] = 15,
    ["Item4"] = 20
}

function GetItemFromTable(Table)
    local TableTotal = 0
    for i, v in pairs(Table) do
        TableTotal += v
    end
    local Number = Random.new():NextNumber(1, TableTotal)
    local Current = 0
    for i, v in pairs(Table) do
        Current += v
        if Number <= Current then
            return i
        end
    end
    return nil
end

GetItemFromTable(ItemTable)

you should at least try to write it out instead of a screenshot, also this one doesn’t need the numbers to add to 100 for it to work, the total of the numbers in the table can be anything

local MyTable = {
	['Item1'] = 25; --The item name, followed by the chance of getting it.
	['Item2'] = 25;
	['Item3'] = 25;
	['Item4'] = 25;
	
}

local function PickRandom(Table)
	local TableTotal = 0
	for i, v in pairs(table) do TableTotal += v end
	local RandomNumber = math.random(1,TableTotal) 
all of the table values added.
	local Current = 0
	for i, v in pairs(Table) do
		Current += v
		if RandomNumber <= Current then
			return i --Returns the random item that was selected
		end
	end
	return "Unable to find item."
end

PickRandom(PickRandom(MyTable)) 

Yeah, they’re pretty similar, I just used 100 instead of table total - I guess I thought it would be easier for it to be out of 100 so that it could be a percentage.
Also, I didn’t know about the text formatting, thank you for letting me know. :slightly_smiling_face:

your welcome, also yea the 100 total is probably easier to deal with, maybe if you have a lot of items then 1000