2

I'm trying to design a game in lua (This is my first shot). And now I'm stuck with the math.random and math.randomseed() functions. I had gone through the math library, but it even confused me more. I want to randomize 3 functions (means I want 3 functions to be called randomly). How do I do this with math.random() function?

Also, which random function is better and safe to use? the math.random() or math.randomseed() ?

Help please

1 Answer 1

2

First - clarification. Function random.randomseed() initializes random number generator. It means that you should call it somewhere in start of your program, typically before first random.random() call.

Now, to solve your problem and call three functions randomly, you have to use numbers generated with random.random() to call these functions (numbers are from 0 to 1). This is one way to do it:

local function first()
    …
end
local function second()
    …
end
local function third()
    …
end

random.randomseed(os.time()) -- initialize random number generator with time

local number = random.random()
if number < 0.3333 then
    first()
elseif number < 0.6666 then
    second()
else
    third()

Now, you can do it in a loop, so that your functions will be called multiple times. You can also change probabilities (in the code above, in the long run, frequency of calling first() will be similar to second() and third()). If you need to call one of the funcitons more often, just adjust the numbers in if conditions).

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah! :) I figured out calling functions randomly yesterday night. And thank you for clarification. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.