Reputation: 87
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
Upvotes: 2
Views: 452
Reputation: 2263
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).
Upvotes: 2