lua-users home
lua-l archive

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


Mike,

There is an issue with math.random in LJ2.

Lua 5.1. Manual explicitly says that math.random calls ANSI C rand() function:

        This function is an interface to the simple pseudo-random
generator function rand provided by ANSI C.

Since math.random() calls rand(), it should affect ANSI C random
generator state. That is, if you call math.random() from Lua and then
call rand() from C you'll get different results than if you don't call
Lua code.

A friend of mine had a nasty debugging session after transition to LJ2
from Lua, trying to figure out what's happened with his code, and why
math.random() no longer affects C random.

I know that LJ2 has its own random and math.random() calls it. I even
think that it is good. But still, in my opinion, it is a deviation
from the current Lua language standard.

What to do with this problem:

1. At the very least, LJ2 docs should explicitly mention this incompatibility.
2. LJ2 may provide a compile-time option to select which math.random
implementation to use. (Lua's implementation is really small and will
not be a burden.)
3. Leave math.random() as it was in Lua, rename LJ2's math.random to
jit.random(). User will say math.random = jit.random as needed.

Thanks,
Alexander.

P.S. That being said, I believe that math.random definition is an
issue of the manual, and it should be rephrased as "generator function
*similar to* rand, provided by ANSI C". Otherwise it is not possible
to write a fully compliant implementation when ANSI C is inaccessible.
Nevertheless, Lua 5.1. math.random() is defined as it is now and we
have to cope with this.