summaryrefslogtreecommitdiff
path: root/lmathlib.c
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>1998-12-30 15:22:17 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>1998-12-30 15:22:17 -0200
commit05d89b5c05bdf3be8f6fd3c6d195672f1e10d13e (patch)
tree9025a07825656795795f089449cdb98eb3b6f4d6 /lmathlib.c
parentfe5c41fb8a0e1d4f130437b22667bf699851b17a (diff)
downloadlua-05d89b5c05bdf3be8f6fd3c6d195672f1e10d13e.tar.gz
lua-05d89b5c05bdf3be8f6fd3c6d195672f1e10d13e.tar.bz2
lua-05d89b5c05bdf3be8f6fd3c6d195672f1e10d13e.zip
new option for function "random": random(a,b) returns a<=x<=b
Diffstat (limited to 'lmathlib.c')
-rw-r--r--lmathlib.c24
1 files changed, 15 insertions, 9 deletions
diff --git a/lmathlib.c b/lmathlib.c
index 1d99df32..63a9c1f9 100644
--- a/lmathlib.c
+++ b/lmathlib.c
@@ -1,5 +1,5 @@
1/* 1/*
2** $Id: lmathlib.c,v 1.11 1998/09/08 19:25:35 roberto Exp roberto $ 2** $Id: lmathlib.c,v 1.12 1998/12/28 13:44:54 roberto Exp roberto $
3** Lua standard mathematical library 3** Lua standard mathematical library
4** See Copyright Notice in lua.h 4** See Copyright Notice in lua.h
5*/ 5*/
@@ -153,16 +153,22 @@ static void math_max (void)
153} 153}
154 154
155 155
156static void math_random (void) 156static void math_random (void) {
157{ 157 /* the '%' is needed because on some systems (SunOS!) "rand()" may
158 /* the '%' is needed because on some systems (SunOS!) "rand()" may */ 158 return a value bigger than RAND_MAX... */
159 /* return a value bigger than RAND_MAX... */ 159 double r = (double)(rand()%RAND_MAX) / ((double)RAND_MAX+1.0);
160 double r = (double)(rand()%RAND_MAX) / (double)RAND_MAX; 160 int l = luaL_opt_int(1, 0);
161 double l = luaL_opt_number(1, 0);
162 if (l == 0) 161 if (l == 0)
163 lua_pushnumber(r); 162 lua_pushnumber(r);
164 else 163 else {
165 lua_pushnumber((int)(r*l)+1); 164 int u = luaL_opt_int(2, 0);
165 if (u == 0) {
166 u = l;
167 l = 1;
168 }
169 luaL_arg_check(l<=u, 1, "interval is empty");
170 lua_pushnumber((int)(r*(u-l+1))+l);
171 }
166} 172}
167 173
168 174