[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: math.random() when lua_Number is int
- From: Lisa Parratt <lisa@...>
- Date: Thu, 08 Sep 2005 12:07:21 +0100
Lisa Parratt wrote:
I vaguely remember having got around this problem in a manner that
works with both reals and integers - I'll look it up when I get to work.
This is the version I'm using, based on the Lua 5.0 random function:
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);
switch (lua_gettop(L)) { /* check number of arguments */
case 0: { /* no arguments */
lua_pushnumber(L, (lua_Number)(((int)r) / 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, (lua_Number)((int)(((int)r) / (int)((RAND_MAX
/ (u-1))))+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, (lua_Number)((int)(((int)r) / (int)((RAND_MAX
/ (u-l))))+l)); /* int between 'l' and `u' */
break;
}
default: return luaL_error(L, "wrong number of arguments");
}
return 1;
}
--
Lisa
http://www.thecommune.org.uk/~lisa/