Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other ways to get a random number in Lua

Tags:

random

lua

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.

like image 205
Nolin M. Avatar asked Oct 26 '25 02:10

Nolin M.


1 Answers

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.

like image 62
Oka Avatar answered Oct 29 '25 08:10

Oka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!