Random number generator in Lua.

Posted by Arnumor on Wed 07 Jul 2010 11:34 PM — 6 posts, 25,016 views.

#0
Okay, so I want to make a script that Ic an use for either aliases or triggers that generales a randomized, five-digit number ranging between 11111 and 99999. What's the syntax for that?

I think it'd use the math.random function, but I always have trouble figuring out how to type it in Lua when I read about a functino in the manual.

I'm not a skilled programmer, so try to make it as easy for me to understand as possible, please. :)
USA #1
The first thing you want to do is "seed" the random number generator. Long story short, it'll always produce the same sequence of numbers if you don't set the seed. A common and easy seed is the current time. You can do this with:

math.randomseed(os.time())


After that, you use math.random() to get a random number. For the range you want, you'd use:

math.random(11111, 99999)


As you can see, the first parameter is the lowest number, and the second is the highest number.
Amended on Wed 07 Jul 2010 11:40 PM by Twisol
#2
Okay, but I need to know just how to use it in the script, too. I took a shot at it, but got back an error. Let's just say for simplicity's sake that I want to make my character say the randomly-generated number. What would the LUA syntax be?

Say in this case is straightforward; "say {text}", where I want {text} to be the number.

Australia Forum Administrator #3
It is always nice to see the error message.

Anyway, something like this:


Send ("say " .. math.random(11111, 99999) )

USA #4
Explanation: That takes the result of math.random, concatenates it to "say " (so you get, for example, "say 42"), and passes that new string to Send(). The '..' operator is the string concatenation operator.
Amended on Thu 08 Jul 2010 02:47 AM by Twisol
#5
Thanks a ton fellas, I appreciate it. I'll give it a shot and see how it works out for me.