Hello, guys, I recently encountered an error I believe might be a bug, or I'm missing something stupid. When I have a script print: math.random(7), I always get 7...So much for random. I considered that with ROBLOX's updates they may have changed it to where a minimum value is required so I did try print: math.random(1,7). And still ALWAYS get "7". Thanks in advance for ANY help.
Update. No matter what the "random-range" is. I am still constantly getting the highest possible value.
Update 2 Solved. Turns out adding a small waiting period before the function runs fixed the issue.
Number sequence?
Like XAXA's link in his comment references, this is all dealing with a function
called math.randomseed
. This functions allows you to set the random number generator sequence
of your script environment.
If you're getting the same number over and over again right when your game starts at the exact same time as the last, this is using the same seed over and over again (allegedly).
Seed?
A seed is pretty simple to understand; you could think of it just as a seed for a flower. Different flower seeds grow different flowers. In this case, different number seeds produce different sequences of random numbers.
Implementing this in your code
It's probably ideal when working with math.random
, to assign a new random seed at the beginning of your script IF you plan to be working with it as soon as the game launches. If you're using math.random for effects of something, or when a user inputs something, you probably won't have to worry about creating a new seed.
So, what 'seed' should I use?
So here's the thing, obviously to have a different number sequence every time, you'd need a different random seed every time. How can this be done?- Isn't this impossible without using math.random? Not really. All we have to do is think of something that constantly
changes, and will never be the same no matter what. Sound familiar? We can use time for this (specifically, tick
).
Tick is a function that returns the current UNIX time, and is perfect for setting the new random seed for your script. Here's an example:
math.randomseed(tick()) -- Tick as our new seed print(math.random(7)) -- New random number sequence
Try this code, and if you have any problems or questions, just leave a comment and I'll get to it.