MCPcopy Create free account
hub / github.com/DFHack/dfhack / math_random

Function math_random

depends/lua/src/lmathlib.c:247–274  ·  view source on GitHub ↗

** This function uses 'double' (instead of 'lua_Number') to ensure that ** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0' ** will keep full precision (ensuring that 'r' is always less than 1.0.) */

Source from the content-addressed store, hash-verified

245** will keep full precision (ensuring that 'r' is always less than 1.0.)
246*/
247static int math_random (lua_State *L) {
248 lua_Integer low, up;
249 double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0));
250 switch (lua_gettop(L)) { /* check number of arguments */
251 case 0: { /* no arguments */
252 lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */
253 return 1;
254 }
255 case 1: { /* only upper limit */
256 low = 1;
257 up = luaL_checkinteger(L, 1);
258 break;
259 }
260 case 2: { /* lower and upper limits */
261 low = luaL_checkinteger(L, 1);
262 up = luaL_checkinteger(L, 2);
263 break;
264 }
265 default: return luaL_error(L, "wrong number of arguments");
266 }
267 /* random integer in the interval [low, up] */
268 luaL_argcheck(L, low <= up, 1, "interval is empty");
269 luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
270 "interval too large");
271 r *= (double)(up - low) + 1.0;
272 lua_pushinteger(L, (lua_Integer)r + low);
273 return 1;
274}
275
276
277static int math_randomseed (lua_State *L) {

Callers

nothing calls this directly

Calls 5

lua_gettopFunction · 0.85
lua_pushnumberFunction · 0.85
luaL_checkintegerFunction · 0.85
luaL_errorFunction · 0.85
lua_pushintegerFunction · 0.85

Tested by

no test coverage detected