Unfortunately the LÖVE version of Lua does not support direct bit manipulation and thus cannot be used to reasonably implement a good PRNG, thus one should be bundled.
Here is a Public Domain version of 32-bit xorshift in ISO C99 written by me:
Code: Select all
#include <stdint.h>
// PRNG state type
typedef struct { uint32_t x; uint32_t y; } RandomState;
// Current PRNG state
static RandomState State = {2282008U, 362436069U};
// Seeds the RNG
void RandomSeed(uint32_t seed)
{
State.x = seed;
}
// Returns a random unsigned integer
uint32_t RandomUint32(void)
{
State.x = 69069U * State.x + 123U;
State.y ^= State.y << 13U;
State.y ^= State.y >> 17U;
State.y ^= State.y << 5U;
return State.x + State.y;
}
// Returns a random double [0, 1) interval
double RandomDouble(void)
{
return RandomUint32() * (1.0 / 4294967296.0);
}
// Returns a random integer [0, n) interval
int32_t RandomMod(int32_t n)
{
return RandomDouble() * n;
}
// Returns a random integer [lb, ub] interval
int32_t Random(int32_t lb, int32_t ub)
{
return lb + (int32_t)(RandomDouble() * (ub - lb + 1));
}
// Demo
#include <time.h>
#include <stdio.h>
int main(void)
{
RandomSeed(time(NULL));
for (int i = 0; i < 20; ++i)
printf("%d\n", Random(1,3));
return 0;
}
I do not think it is necessary to implement more than one RNG (as someone suggested elsewhere). LÖVE is not Java or C++ and hopefully never will be. More than one PRNG would be bloat for a platform like this IMO. Even if the binary size impact would be fairly minimal API bloat is a problem in itself.
You don't have to use xorshift but please do not rely on the platform's random for LÖVE's random functions.
Oh, and please add functions to get/set the PRNG state. They are useful for many things. With xorshift those functions are trivial and easy to understand because the state is just two integers.