[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: math.random() when lua_Number is int
- From: Graham Wilson <graham@...>
- Date: Tue, 6 Sep 2005 21:56:50 -0500
math.random() doesn't return anything useful when lua_Number is int. I
think it makes sense for at least the one and two argument versions to
return something useful, and the attached patch attempts to do this.
--
gram
diff -Naur lua-5.0.2.orig/src/lib/lmathlib.c lua-5.0.2/src/lib/lmathlib.c
--- lua-5.0.2.orig/src/lib/lmathlib.c 2003-03-11 06:30:37.000000000 -0600
+++ lua-5.0.2/src/lib/lmathlib.c 2005-08-29 14:00:18.000000000 -0500
@@ -170,23 +170,23 @@
static int math_random (lua_State *L) {
/* the `%' avoids the (rare) case of r==1, and is needed also because on
some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
- lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
+ int r = rand()%RAND_MAX;
switch (lua_gettop(L)) { /* check number of arguments */
case 0: { /* no arguments */
- lua_pushnumber(L, r); /* Number between 0 and 1 */
+ lua_pushnumber(L, (lua_Number)r / (lua_Number)RAND_MAX); /* 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, (int)floor(r*u)+1); /* int between 1 and `u' */
+ lua_pushnumber(L, (int)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, (int)floor(r*(u-l+1))+l); /* int between `l' and `u' */
+ lua_pushnumber(L, (int)floor(r%(u-l+1))+l); /* int between `l' and `u' */
break;
}
default: return luaL_error(L, "wrong number of arguments");