I'm looking for an alternative way to get a random number in Lua that is between a minimum and a maximum number without using math.random()
. Is there any way? It doesn't have to be a simple method.
Asked
Active
Viewed 2,129 times
4
-
Why is `math.random` unsuitable? Have you tried searching for `lua random` online? – Etan Reisner Jun 26 '15 at 21:15
-
Perhaps you should give reason why you want to avoid random. Do you miss entropy ? – Marged Jun 26 '15 at 21:15
-
4If you're running in Linux or Mac OS X, you can read bytes from `/dev/random` or`/dev/urandom`. – lhf Jun 26 '15 at 21:17
-
math.random() is not unsuitable, I am just wondering if there are other ways to get random numbers. – Nolin M. Jun 26 '15 at 21:18
1 Answers
6
Like the comments have hinted at, on Unix-like systems you can read bytes from /dev/random
or /dev/urandom
, and create a random number from them.
urand = assert (io.open ('/dev/urandom', 'rb'))
rand = assert (io.open ('/dev/random', 'rb'))
function RNG (b, m, r)
b = b or 4
m = m or 256
r = r or urand
local n, s = 0, r:read (b)
for i = 1, s:len () do
n = m * n + s:byte (i)
end
return n
end
As an extension to this answer, and for fun, I've authored a very tiny module, randbytes
, so that future readers may play around with the /dev/random
and /dev/urandom
interfaces in a simple manner. Here's a quick run down.
Install with luarocks
or get it manually.
$ luarocks install randbytes
Require the module, or file.
$ lua
> randbytes = require 'randbytes'
And then grab some bytes.
> print (randbytes (8))
For now, I've cleaned up and included the very simple generation algorithm shown above, for generating basic random numbers.
> print (randbytes:urandom (16))
You can build on top of the basic interface to implement your own algorithms. Read the documentation for a full list of methods, and settings.

Oka
- 23,367
- 6
- 42
- 53