在Lua中获取随机数的其他方法 [英] Other ways to get a random number in Lua

查看:836
本文介绍了在Lua中获取随机数的其他方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种不使用math.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.

推荐答案

就像注释所暗示的那样,在类似Unix的系统上,您可以从/dev/random/dev/urandom中读取字节,并从它们中创建一个随机数.

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


作为对此答案的扩展,并且很有趣,我编写了一个非常小的模块, randbytes ,以便将来的读者可以轻松地使用/dev/random/dev/urandom接口.这是一个快速的总结.


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.

使用 luarocks 进行安装,或获取需要模块或文件.

$ lua
> randbytes = require 'randbytes'

然后抓取一些字节.

> print (randbytes (8))

到目前为止,我已经清理并包含了上面显示的非常简单的生成算法,用于生成基本随机数.

For now, I've cleaned up and included the very simple generation algorithm show 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.

这篇关于在Lua中获取随机数的其他方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆