Can I make this math.random code shorter?

I have a math.random code that gives you a random number:

local theRanNum = math.random(1,5)

if theRanNum == 1 then
print("You got 1!!")
end

if theRanNum == 2 then
print("You got 2!!")
end

if theRanNum == 3 then
print("You got 3!!!")
end

if theRanNum == 4 then
print("You got 4!!!!")
end

if theRanNum == 5 then
print("You got 5!!!!!")
end

Is there anyway I can make this shorter so I don’t have to type out every single number?

Any kind of help is appreciated.

2 Likes
local theRanNum = math.random(1,5)

print("You got "..theRanNum.."!!")
8 Likes

Thanks, I didn’t realise that.

If you wanted to do more than print, and maybe something for each number you could involve an array of functions and then you could pull the function out of the array and all it.

I’d also recommend that you use the Random datatype, it has it’s own seed per object and has mutliple functions.

For example:

local FunctionsArray = {
    function()
        print("You got 1!")
    end,
    function()
        print("You got 2!")
    end
}

local Rand = Random.new()
local RandomNumber = Rand:NextInteger(1, 2)
local RandomFunction = FunctionsArray[RandomNumber]
RandomFunction()

Random datatype is psuedo-random, which means it can be predictable. In most cases math.random is better

Both math.random and the Random datatype are psuedo-random, they can never achieve full randomness.

Take a look at this small test I did a few months ago:


As you can see, they’re both as random as each other.