Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislovecnm/2381999 to your computer and use it in GitHub Desktop.
Save chrislovecnm/2381999 to your computer and use it in GitHub Desktop.
Lua Random Number Generation
// taken from http://snes9x-rr.googlecode.com/svn/trunk/snes9x-151/lua-engine.cpp
// http://snes9x-rr.googlecode.com/svn/trunk/snes9x-151/SFMT/SFMT.c
// same as math.random, but uses SFMT instead of C rand()
// FIXME: this function doesn't care multi-instance,
// original math.random either though (Lua 5.1)
static int sfmt_random (lua_State *L) {
lua_Number r = (lua_Number) genrand_real2();
switch (lua_gettop(L)) { // check number of arguments
case 0: { // no arguments
lua_pushnumber(L, r); // Number between 0 and 1
break;
}
case 1: { // only upper limit
int u = luaL_checkint(L, 1);
luaL_argcheck(L, 1<=u, 1, "interval is empty");
lua_pushnumber(L, floor(r*u)+1); // int between 1 and `u'
break;
}
case 2: { // lower and upper limits
int l = luaL_checkint(L, 1);
int u = luaL_checkint(L, 2);
luaL_argcheck(L, l<=u, 2, "interval is empty");
lua_pushnumber(L, floor(r*(u-l+1))+l); // int between `l' and `u'
break;
}
default: return luaL_error(L, "wrong number of arguments");
}
return 1;
}
// same as math.randomseed, but uses SFMT instead of C srand()
// FIXME: this function doesn't care multi-instance,
// original math.randomseed either though (Lua 5.1)
static int sfmt_randomseed (lua_State *L) {
init_gen_rand(luaL_checkint(L, 1));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment