我的'randomString'函数不断返回相同的结果 [英] My 'randomString' function keeps returning the same result

查看:95
本文介绍了我的'randomString'函数不断返回相同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

randomString.lua

randomString.lua

----------------------------------------------------------------------------
-- File: randomString.lua
-- Author: Don Draper
-- 
-- This is the Lua implementation of my simple 'randomString' function
-- which I previous wrote in PAWN.
----------------------------------------------------------------------------

randomString = {}

local randomCharset = {
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
}

function randomString.generate(length)
    local currentString = ""
    for index = 1, length do
        currentString = currentString .. randomCharset[math.random(1, #randomCharset)]
    end
    return currentString
end

Test.lua

require("randomString")

print(randomString.generate(16))
io.read()

这是我最初用PAWN编程语言编写的"randomString"函数,我想我应该将其实现到Lua来生成一些密码盐.但是,每当我调用我的移植函数时,无论何时我第一次运行该程序,它总是会返回相同的输出.

So here is my 'randomString' function which I originally wrote in the PAWN programming language, I thought I would implement it to Lua to generate some password salts. However whenever I call my ported function it always returns the same output whenever I first run the program.

以这段代码为例.

for i = 0, 100 do
    print(randomString.generate(16))
end

它将始终生成相同的随机字符串列表.谁能解释为什么?预先感谢!

It will always generate the same list of random strings. Can anyone please explain why? Thanks in advance!

推荐答案

math.random生成一个伪随机数字序列,该序列是类似于实际随机序列的确定性序列.除非您使用math.random生成的序列将始终相同. > math.randomseed .

math.random generates a sequence of pseudorandom numbers, that is a deterministic sequence that will resemble an actual random sequence. The sequence generated by math.random will be always the same, unless you use math.randomseed.

对于每个您调用math.randomseed的可能值,math.random都会生成一个不同的伪随机序列.

For every possible value with which you call math.randomseed, math.random will generate a different pseudorandom sequence.

例如,尝试此操作,您将看到不同的顺序:

Try this, for example, and you will see a different sequence:

math.randomseed( 7654321 )
for i = 0, 100 do
    print(randomString.generate(16))
end

如果您想要一个真正的随机序列,则应该在开始生成之前为randomseed提供一个真正的随机数.

If you want a truly random sequence you should feed randomseed with a true random number before starting the generation.

这篇关于我的'randomString'函数不断返回相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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