lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Tue, 8 Jun 2004, Brennan Leathers wrote:

> >It can be useful, in many cases, to have multiple pseudo-random generator
> >objects which can be used, saved and restored independently. We have made
> >a bind of c++ MersenneTwister pseudo-random generator to Lua for our work.
> >  
> >
> Hi,
> I would like to have the wrapper for the MT function. I've been wanting 
> to do one myself, but I'm fairly new to lua. Although I am not sure why 
> c++ is needed when the MT is a C function and a random number "object" 
> can easily be done in pure lua. Still, no big deal :) I just avoid c++ 
> when I can.


C++ is used because we want more than one MT generator at the same time.  
Different threads can use their own generator with no interferences. If
this feature is not needed, a much simpler bind can be implemented and
only C is needed (of course, MT objects could be done in C without C++

A (stupid and) tiny example of usage:

mt1 = random(seed1)
mt2 = random() -- seed is optional
table = mt2:shuffle(100) -- create a random permutation of indices:
mt3 = mt2 -- the are the same c++ object
mt4 = mt2:clone() -- no longer the same c++ object
state = mt2:save() -- state is a lua table of numbers
mt2:load(state) -- restore

The code (.tgz approx. 10kbytes) can be obtained at:

I think the garbage collection has some bugs to be fixed (we use reference 
counting and lua GC).

I will delete this file maybe in a few weeks...

Best regards,
Salva E.

> not to annoy anyone, but ruby and python both use the Mersenne Twister 
> as their default, preferred random number generator. Tcl has it 
> available as an extension. The MT really is becoming the standard 
> replacement for C std lib's rand() (which is slow and known to repeat 
> itself). so IMO the MT function (it's really quite small) should be 
> considered for addition to lua's standard math lib.
> The code is available here:
> Its only shortcoming is that the authors say it is not secure for 
> cryptography (in which case you'd want to use openssl's random number 
> functions anyway).
> anyways, in the mean time, can you post the code for your wrapper to the 
> Web or send if the attachment is small? Thanks.
> regards,
> Brennan