2014-11-15 17 views
0

起初,我用這個:的Lua(青金石)隨機值返回相同的結果,即使使用randomseed

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, :

​​

我收到相同的隨機字符串每隔一秒。 如何解決它?我試圖用不同的隨機數據創建數據庫,但我收到相同的字符串!這只是我寫的例子,但填寫數據庫給出了相同的結果!@#%%

任何想法解決它?

+0

在真正使用幫助之前是否會彈出一些隨機數字?請參閱[此問題](http://stackoverflow.com/questions/18199844/lua-math-random-not-working/18199908#18199908)。 –

+0

不,它沒有幫助。結果相同。據我瞭解,如果我嘗試在1秒內檢索隨機數據,則會出現此錯誤。 – Vyacheslav

回答

0

我發現這是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 
相關問題