diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1998-12-30 15:22:17 -0200 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1998-12-30 15:22:17 -0200 |
commit | 05d89b5c05bdf3be8f6fd3c6d195672f1e10d13e (patch) | |
tree | 9025a07825656795795f089449cdb98eb3b6f4d6 /lmathlib.c | |
parent | fe5c41fb8a0e1d4f130437b22667bf699851b17a (diff) | |
download | lua-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.c | 24 |
1 files changed, 15 insertions, 9 deletions
@@ -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 | ||
156 | static void math_random (void) | 156 | static 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 | ||