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

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

问题描述

我正在寻找一种替代方法来在 Lua 中获取一个介于最小和最大数之间的随机数,而不使用 math.random().有什么办法吗?它不一定是一个简单的方法.

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 安装或手动获取.

Install with luarocks or get it manually.

$ luarocks install randbytes

需要模块或文件.

$ lua
> randbytes = require 'randbytes'

然后抓取一些字节.

> 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.

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

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