Advertisement
fuxoft

Lua random number generator

Nov 4th, 2013
835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.05 KB | None | 0 0
  1. #!/usr/bin/env lua
  2.  
  3. --Lua random # generator module
  4. --Seeded using any string
  5. --Requires Lua 5.2 (bit32 library)
  6.  
  7. local _M={}
  8. _M.new = function(seed)
  9.     seed = tostring(seed) .. "#*]"
  10.     assert(#seed >= 4, "Seed too short")
  11.     local seeds = {0xdeadbeef,0x67898765,0xfacecafe,#seed}
  12.     for i = 1, #seed do
  13.         local chr = string.byte(seed:sub(i))
  14.         for s = 1, 4 do
  15.             if s > 1 then
  16.                 for s2 = 1, s-1 do
  17.                     seeds[s]=seeds[s] + seeds[s2]
  18.                 end
  19.             end
  20.             seeds[s] = bit32.lrotate((seeds[s]+chr), (seeds[s] + chr) % 8 + 5)
  21.         end
  22.     end
  23.     local w,x,y,z = seeds[4],seeds[3],seeds[2],seeds[1]
  24.     if(w+x+y+z == 0) then
  25.         w,x,y,z = 0xdeadbeef,0xfacecafe,0x12345678,999
  26.     end
  27.     local fun = function(arg)
  28.         local t = bit32.bxor(x, bit32.lshift(x,11))
  29.         x,y,z = y,z,w
  30.         w = bit32.bxor(w, bit32.rshift(w,19), t, bit32.rshift(t,8))
  31.         if arg == "bin" then
  32.             return w,x,y,z
  33.         end
  34.         local float = bit32.rshift(w,1) / 0x80000000 --31bit float
  35.         if not arg then
  36.             return float
  37.         end
  38.         return math.floor(float * arg) + 1
  39.     end
  40.     --fun()
  41.     return fun
  42. end
  43. return _M
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement