Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How does generating random numbers in this script work?

Asked by
tanzane 100
8 years ago
while wait(math.random(5)) do
    script.Parent:Play()
end

OK.

This is my script I have in my game. Basically what it is suppose to do is randomly play thunder in my game. I just don't want the thunder to be at the exact same time each time so I tried doing math.random and I got everything figured out, but how does the parentheses work?

I assumed if you put a number in the parentheses it'll choose a random number for 1-whatever number you chose. In my case I have five so thunder would play 1-5 seconds each time , right?

3 answers

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

Yes. math.random has three ways to be used:

  • math.random(low, high) low and high must be integers, and it will return a random integer between low and high (inclusive)
  • math.random(high), the same thing as math.random(1, high).
  • math.random(), returns a random number (not integer) between 0 and 1 (including 0, not including 1)

Thus math.random(5) will either be 1, 2, 3, 4, or 5.

If you wanted to have a continuous range of numbers, e.g., 4.3, 4.45, 4.973234 also being options, you could use something like

wait( 1 + math.random() * 4 )

to be any number (not just 1, 2, 3, 4, 5) between 1 and 5.

Ad
Log in to vote
0
Answered by 8 years ago

To get better random numbers, I would recommend using a seed value derived from os time, and then taking off a few of the values - here is a function I use to consistently get random numbers from Lua - otherwise you may end up getting the same numbers all the time, in the same order, when you call the math.random function.

local function randomnum (minimum,maximum)


              math.randomseed(os.time())

            local r = math.random(minimum,maximum)
             r = math.random(minimum,maximum)
             r = math.random(minimum,maximum)

            return r

    end
Log in to vote
-2
Answered by
Scootakip 299 Moderation Voter
8 years ago

Yep! That should work the way you want it to! However if it doesn't then try this:

while true do
wait(math.random(5)) do
script.Parent:Play()
end
0
His will work. But this one won't. CodingEvolution 490 — 8y

Answer this question