4

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Nolin M.
  • 387
  • 1
  • 11

1 Answers1

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