Is there a more efficient way to use math.random?

Hey! I am still a learning scripter and I seek answers for my question. Is there a more efficient way to use math.random? that might sound confusing, but here’s my example:

local randomNumber = math.random(1,2)

if randomNumber == 1 then
-- code 
end

if randomNumber == 2 then
-- code
end

-- is there a more efficient way of like going through the outcomes?
1 Like

I wouldn’t replace math.random() with anything else but I know you can do something with math.min and math.max Why would you need another way of using math.random anyways?

Sorry if my wording was tough to understand, I was talking about the outcomes, not line 1. So is there an easier way of going through the outcomes?

this bit above :arrow_double_up:

I know since there is 2 outcomes I can just do else.

You could combine the two if statements into a single if/elseif or if/else statement, like so:

if randomNumber == 1 then
    --code
elseif randomNumber == 2 then
    --code
end

Or, simply:

if randomNumber == 1 then
    --code
else
    --code
end
3 Likes

There might be another way of doing it but I find this method the best. You could also make a table with the values that math.random generates then check from there.
The way you wrote it is neat and it’s what I would use.

2 Likes

Yes, but is there a way like that with even more numbers?

EDIT; nvm

1 Like

If there are more number you can use the symbol > or < or <= or >=.

1 Like

Without a use case, you can’t get a proper answer to this question. The most efficient way to use math.random is to use it at all. Efficiency is now extending towards the system you’re putting math.random in, which is more important to analyse.

What’s your use case? What are you doing? An if statement can easily be better in one case and in another, may be worse or not even necessary at all. A use case is important to have for questions like this. If you don’t have one, then knowing what you’re trying to do is confusing and you end up with just a generalised this-or-that solution.