Lua(Lapis)的随机数生成器即使使用随机种子,返回的结果仍然相同。

首先,我使用了以下函数:

math.randomseed(os.time())

使用以下函数进行检查:

function makeString(l)
        if l < 1 then return nil end
        local s = ""
        for i = 0, l do
            n = math.random(0, 61)--61
            n0 = 0
            if n < 10 then n0 = n + 48
            elseif n < 36 then n0 = n - 10 + 65
            else n0 = n - 36 + 97 end
                s = s .. string.char(n0)
        end
        return s
end

如果我使用此函数:

app:match("/tttt", function()
  local ss = ""
   for i=1,10 do ss = ss .. makeString(30) .. "\n" end
  return ss
end)

我会收到不错的不同值。

如果我使用:

app:match("/ttt", function()
  return makeString(30)
end)

和 JavaScript jQuery: :

  $("#button5").click(function(){
   var ss = ""
   for(var i = 0; i < 10; i++)
    {
        $("#div1").load("/ttt", function() {
        ss = ss + $(this).text()
  alert(ss);
});
    }
    $("#div1").text(ss);
  });

我每秒收到相同的随机字符串。 如何解决?我尝试创建不同的随机数据数据库,但我收到了相同的字符串!这只是我写的一个示例,但是填充数据库会产生相同的结果!@#%%

有没有什么好的想法来解决这个问题?

点赞
用户1979882
用户1979882

我发现这是 Lua 的一个“特性”,使用秒生成伪随机数。请使用此链接阅读更多:http://lua-users.org/wiki/MathLibraryTutorial

但可以帮助的解决方案是使用 /dev/urandom

描述链接: http://lua-users.org/lists/lua-l/2008-05/msg00498.html

以我的案例为例:

local frandom = io.open("/dev/urandom", "rb")
local makeString
makeString = function(l)

        local d = frandom:read(4)
        math.randomseed(d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))

        if l < 1 then return nil end
        local s = ""
        for i = 0, l do
            local n = math.random(0, 61)
            n0 = 0
            if n < 10 then n0 = n + 48
            elseif n < 36 then n0 = n - 10 + 65
            else n0 = n - 36 + 97 end
                s = s .. string.char(n0)
        end
        return s
end
2014-11-17 16:17:25