How could I use less if statements for this code?

The issue is that I want rng to decide what the multi will be, it can be 2, 5, 10, I have thought of using tables, dictionaries, but I couldn’t figure out how exactly to do it using those, 3 if statements are not a big problem but I’m thinking of what if there were 100 different variations, and it would be useful to know for other things too.

local function GivePoint(Points)
	local Multi = 1
	
	local LuckNumber1 = math.random(1,5)
	local LuckNumber2 = math.random(1,25)
	local LuckNumber3 = math.random(1,100)

	if LuckNumber1 == 5 then
		Multi = 2
	end
	if LuckNumber2 == 25 then
		Multi = 5
	end	
	if LuckNumber3 == 100 then
		Multi = 10	
	end
		
	
	
	print(Multi)
	Points.Value = Points.Value + 1 * Multi
	
	
end

I’m not going to even lie, that’s like the best way to write it, though if you were to make 100 of those if-then statements it does become messy but for now I think its fine honestly. Nice and Simple.

Useless because LuckNumber1 is not LuckNumber2 and is also not LuckNumber3

1 Like

True, I was thinking they were the same variable, my bad.

Using tables with this requires a slightly different approach.
What we need to store will be both the chance for the luck number to be rolled, and the multiplier it will give.
So our table should look something like this:

--// You dont actually need the keys "luck1, luck2..", etc. It's just to make it easier to read
local LuckTable = {
	Luck1 = {
		Chance = 1/5;
		Multiplier = 2;
	};
	
	Luck2 = {
		Chance = 1/25;
		Multiplier = 5;
	};
	
	Luck3 = {
		Chance = 1/100;
		Multiplier = 10
	}
};

Then we can make our code iterate over every single table inside of the luck table and automatically determine whether or not we should set the multiplier to it.

local function GivePoint(Points: NumberValue? | IntValue?)
	local CurrentMultiplier = 1 
	
	for _, ChanceTable: {Chance: number, Multiplier: number} in LuckTable do
		local Rand = math.random(0, 100000)/100000 --Using this to get a random float (1 >= x >= 0).
		if ChanceTable.Chance > Rand and ChanceTable.Multiplier > CurrentMultiplier then
			CurrentMultiplier = ChanceTable.Multiplier -- Only set this multiplier if the new multiplier is higher than the old one.
		end
	end
	
	Points.Value = Points.Value + 1 * CurrentMultiplier
	return CurrentMultiplier
end
2 Likes