I decided to write a mt19937 implementation in Lua after I`ve seen this thread.

[lua]

local k_MTLength = 624

local k_BitMask32 = 0x00000000ffffffff

local k_BitPow31 = bit.lshift(1, 31)

local function printhex(d)

print(string.format("%08x", d))

end

local function mul(a, b, maxBits)

```
local res = 0
local negative = (a < 0 and b > 0) or (a > 0 and b < 0)
a = math.abs(a)
b = math.abs(b)
for i = 0, maxBits - 1 do
local mask = bit.lshift(1, i)
local bitV = bit.band(b, mask)
if bitV > 0 then
res = res + (bit.lshift(a, i))
end
end
if negative then
res = bit.bnot(res) + 1
end
return res
```

end

local function add(a, b, maxBits)

```
local res = 0
local c = 0
for i = 0, maxBits - 1 do
local mask = bit.lshift(1, i)
local b1 = bit.rshift(bit.band(a, mask), i)
local b2 = bit.rshift(bit.band(b, mask), i)
local v = bit.bxor(bit.bxor(b1, b2), c)
c = bit.bor(bit.bor(bit.band(b2, c), bit.band(b1, b2), bit.band(b1, c)))
res = bit.bor(res, bit.lshift(v, i))
end
return res
```

end

local mt19937_meta = {}

function mt19937_meta:init(seed)

```
self.KeyTable = {}
self.KeyTable[0] = 0
self.State = 0
self:seed(seed)
```

end

function mt19937_meta:seed(seed)

```
self.KeyTable[0] = seed
self.State = 0
for i = 1, k_MTLength - 1 do
local shift = bit.rshift(self.KeyTable[i - 1], 30)
local xored = bit.bxor(self.KeyTable[i - 1], shift)
local entry = add(mul(1812433253, xored, 32), i, 32)
self.KeyTable* = entry
end
```

end

function mt19937_meta:get(min, max)

```
min = min or 0
max = max or 0xFFFFFFFF
if self.State == 0 then
for i = 0, k_MTLength - 1 do
local y = add(
bit.band(self.KeyTable*, k_BitPow31),
bit.band(self.KeyTable[(i + 1) % k_MTLength], k_BitPow31 - 1),
32)
self.KeyTable* = bit.bxor(self.KeyTable[(i + 397) % k_MTLength], bit.rshift(y, 1));
if y % 2 > 0 then
self.KeyTable* = bit.bxor(self.KeyTable*, 2567483615)
end
end
end
local res = self.KeyTable[self.State]
res = bit.bxor(res, bit.rshift(res, 11))
res = bit.bxor(res, bit.band(bit.lshift(res, 7), 0x000000009D2C5680))
res = bit.bxor(res, bit.band(bit.lshift(res, 15), 0x00000000EFC60000))
res = bit.bxor(res, bit.rshift(res, 18))
self.State = (self.State + 1) % k_MTLength
return min + ((res % max) - min)
```

end

mt19937_meta.__index = mt19937_meta

function mt19937(seed)

```
seed = seed or 0
local new = {}
setmetatable(new, mt19937_meta)
new:init(seed)
return new
```

end

[/lua]

The performance isn’t perfect due the manual add/mul, I had to account the overflow of uint32_t in order to have a deterministic implementation that would work along with the default implementation.

[lua]

local mt = mt19937(os.clock())

for i = 0, 10 do

print(mt:get(0, 10))

end

[/lua]

It should give some good results, see blow:

```
8
4
6
0
8
9
9
2
7
0
6
```