xref: /freebsd/contrib/lua/src/lmathlib.c (revision 3068d706eabe99f930fb01d3cbfd74ff1f0eb5a2)
1 /*
2 ** $Id: lmathlib.c $
3 ** Standard mathematical library
4 ** See Copyright Notice in lua.h
5 */
6 
7 #define lmathlib_c
8 #define LUA_LIB
9 
10 #include "lprefix.h"
11 
12 
13 #include <float.h>
14 #include <limits.h>
15 #include <math.h>
16 #include <stdlib.h>
17 #include <time.h>
18 
19 #include "lua.h"
20 
21 #include "lauxlib.h"
22 #include "lualib.h"
23 
24 
25 #undef PI
26 #define PI	(l_mathop(3.141592653589793238462643383279502884))
27 
28 
math_abs(lua_State * L)29 static int math_abs (lua_State *L) {
30   if (lua_isinteger(L, 1)) {
31     lua_Integer n = lua_tointeger(L, 1);
32     if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n);
33     lua_pushinteger(L, n);
34   }
35   else
36     lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
37   return 1;
38 }
39 
math_sin(lua_State * L)40 static int math_sin (lua_State *L) {
41   lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));
42   return 1;
43 }
44 
math_cos(lua_State * L)45 static int math_cos (lua_State *L) {
46   lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
47   return 1;
48 }
49 
math_tan(lua_State * L)50 static int math_tan (lua_State *L) {
51   lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
52   return 1;
53 }
54 
math_asin(lua_State * L)55 static int math_asin (lua_State *L) {
56   lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
57   return 1;
58 }
59 
math_acos(lua_State * L)60 static int math_acos (lua_State *L) {
61   lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));
62   return 1;
63 }
64 
math_atan(lua_State * L)65 static int math_atan (lua_State *L) {
66   lua_Number y = luaL_checknumber(L, 1);
67   lua_Number x = luaL_optnumber(L, 2, 1);
68   lua_pushnumber(L, l_mathop(atan2)(y, x));
69   return 1;
70 }
71 
72 
math_toint(lua_State * L)73 static int math_toint (lua_State *L) {
74   int valid;
75   lua_Integer n = lua_tointegerx(L, 1, &valid);
76   if (l_likely(valid))
77     lua_pushinteger(L, n);
78   else {
79     luaL_checkany(L, 1);
80     luaL_pushfail(L);  /* value is not convertible to integer */
81   }
82   return 1;
83 }
84 
85 
pushnumint(lua_State * L,lua_Number d)86 static void pushnumint (lua_State *L, lua_Number d) {
87   lua_Integer n;
88   if (lua_numbertointeger(d, &n))  /* does 'd' fit in an integer? */
89     lua_pushinteger(L, n);  /* result is integer */
90   else
91     lua_pushnumber(L, d);  /* result is float */
92 }
93 
94 
math_floor(lua_State * L)95 static int math_floor (lua_State *L) {
96   if (lua_isinteger(L, 1))
97     lua_settop(L, 1);  /* integer is its own floor */
98   else {
99     lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
100     pushnumint(L, d);
101   }
102   return 1;
103 }
104 
105 
math_ceil(lua_State * L)106 static int math_ceil (lua_State *L) {
107   if (lua_isinteger(L, 1))
108     lua_settop(L, 1);  /* integer is its own ceil */
109   else {
110     lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
111     pushnumint(L, d);
112   }
113   return 1;
114 }
115 
116 
math_fmod(lua_State * L)117 static int math_fmod (lua_State *L) {
118   if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
119     lua_Integer d = lua_tointeger(L, 2);
120     if ((lua_Unsigned)d + 1u <= 1u) {  /* special cases: -1 or 0 */
121       luaL_argcheck(L, d != 0, 2, "zero");
122       lua_pushinteger(L, 0);  /* avoid overflow with 0x80000... / -1 */
123     }
124     else
125       lua_pushinteger(L, lua_tointeger(L, 1) % d);
126   }
127   else
128     lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
129                                      luaL_checknumber(L, 2)));
130   return 1;
131 }
132 
133 
134 /*
135 ** next function does not use 'modf', avoiding problems with 'double*'
136 ** (which is not compatible with 'float*') when lua_Number is not
137 ** 'double'.
138 */
math_modf(lua_State * L)139 static int math_modf (lua_State *L) {
140   if (lua_isinteger(L ,1)) {
141     lua_settop(L, 1);  /* number is its own integer part */
142     lua_pushnumber(L, 0);  /* no fractional part */
143   }
144   else {
145     lua_Number n = luaL_checknumber(L, 1);
146     /* integer part (rounds toward zero) */
147     lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
148     pushnumint(L, ip);
149     /* fractional part (test needed for inf/-inf) */
150     lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
151   }
152   return 2;
153 }
154 
155 
math_sqrt(lua_State * L)156 static int math_sqrt (lua_State *L) {
157   lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
158   return 1;
159 }
160 
161 
math_ult(lua_State * L)162 static int math_ult (lua_State *L) {
163   lua_Integer a = luaL_checkinteger(L, 1);
164   lua_Integer b = luaL_checkinteger(L, 2);
165   lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
166   return 1;
167 }
168 
math_log(lua_State * L)169 static int math_log (lua_State *L) {
170   lua_Number x = luaL_checknumber(L, 1);
171   lua_Number res;
172   if (lua_isnoneornil(L, 2))
173     res = l_mathop(log)(x);
174   else {
175     lua_Number base = luaL_checknumber(L, 2);
176 #if !defined(LUA_USE_C89)
177     if (base == l_mathop(2.0))
178       res = l_mathop(log2)(x);
179     else
180 #endif
181     if (base == l_mathop(10.0))
182       res = l_mathop(log10)(x);
183     else
184       res = l_mathop(log)(x)/l_mathop(log)(base);
185   }
186   lua_pushnumber(L, res);
187   return 1;
188 }
189 
math_exp(lua_State * L)190 static int math_exp (lua_State *L) {
191   lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
192   return 1;
193 }
194 
math_deg(lua_State * L)195 static int math_deg (lua_State *L) {
196   lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
197   return 1;
198 }
199 
math_rad(lua_State * L)200 static int math_rad (lua_State *L) {
201   lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
202   return 1;
203 }
204 
205 
math_min(lua_State * L)206 static int math_min (lua_State *L) {
207   int n = lua_gettop(L);  /* number of arguments */
208   int imin = 1;  /* index of current minimum value */
209   int i;
210   luaL_argcheck(L, n >= 1, 1, "value expected");
211   for (i = 2; i <= n; i++) {
212     if (lua_compare(L, i, imin, LUA_OPLT))
213       imin = i;
214   }
215   lua_pushvalue(L, imin);
216   return 1;
217 }
218 
219 
math_max(lua_State * L)220 static int math_max (lua_State *L) {
221   int n = lua_gettop(L);  /* number of arguments */
222   int imax = 1;  /* index of current maximum value */
223   int i;
224   luaL_argcheck(L, n >= 1, 1, "value expected");
225   for (i = 2; i <= n; i++) {
226     if (lua_compare(L, imax, i, LUA_OPLT))
227       imax = i;
228   }
229   lua_pushvalue(L, imax);
230   return 1;
231 }
232 
233 
math_type(lua_State * L)234 static int math_type (lua_State *L) {
235   if (lua_type(L, 1) == LUA_TNUMBER)
236     lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float");
237   else {
238     luaL_checkany(L, 1);
239     luaL_pushfail(L);
240   }
241   return 1;
242 }
243 
244 
245 
246 /*
247 ** {==================================================================
248 ** Pseudo-Random Number Generator based on 'xoshiro256**'.
249 ** ===================================================================
250 */
251 
252 /*
253 ** This code uses lots of shifts. ANSI C does not allow shifts greater
254 ** than or equal to the width of the type being shifted, so some shifts
255 ** are written in convoluted ways to match that restriction. For
256 ** preprocessor tests, it assumes a width of 32 bits, so the maximum
257 ** shift there is 31 bits.
258 */
259 
260 
261 /* number of binary digits in the mantissa of a float */
262 #define FIGS	l_floatatt(MANT_DIG)
263 
264 #if FIGS > 64
265 /* there are only 64 random bits; use them all */
266 #undef FIGS
267 #define FIGS	64
268 #endif
269 
270 
271 /*
272 ** LUA_RAND32 forces the use of 32-bit integers in the implementation
273 ** of the PRN generator (mainly for testing).
274 */
275 #if !defined(LUA_RAND32) && !defined(Rand64)
276 
277 /* try to find an integer type with at least 64 bits */
278 
279 #if ((ULONG_MAX >> 31) >> 31) >= 3
280 
281 /* 'long' has at least 64 bits */
282 #define Rand64		unsigned long
283 #define SRand64		long
284 
285 #elif !defined(LUA_USE_C89) && defined(LLONG_MAX)
286 
287 /* there is a 'long long' type (which must have at least 64 bits) */
288 #define Rand64		unsigned long long
289 #define SRand64		long long
290 
291 #elif ((LUA_MAXUNSIGNED >> 31) >> 31) >= 3
292 
293 /* 'lua_Unsigned' has at least 64 bits */
294 #define Rand64		lua_Unsigned
295 #define SRand64		lua_Integer
296 
297 #endif
298 
299 #endif
300 
301 
302 #if defined(Rand64)  /* { */
303 
304 /*
305 ** Standard implementation, using 64-bit integers.
306 ** If 'Rand64' has more than 64 bits, the extra bits do not interfere
307 ** with the 64 initial bits, except in a right shift. Moreover, the
308 ** final result has to discard the extra bits.
309 */
310 
311 /* avoid using extra bits when needed */
312 #define trim64(x)	((x) & 0xffffffffffffffffu)
313 
314 
315 /* rotate left 'x' by 'n' bits */
rotl(Rand64 x,int n)316 static Rand64 rotl (Rand64 x, int n) {
317   return (x << n) | (trim64(x) >> (64 - n));
318 }
319 
nextrand(Rand64 * state)320 static Rand64 nextrand (Rand64 *state) {
321   Rand64 state0 = state[0];
322   Rand64 state1 = state[1];
323   Rand64 state2 = state[2] ^ state0;
324   Rand64 state3 = state[3] ^ state1;
325   Rand64 res = rotl(state1 * 5, 7) * 9;
326   state[0] = state0 ^ state3;
327   state[1] = state1 ^ state2;
328   state[2] = state2 ^ (state1 << 17);
329   state[3] = rotl(state3, 45);
330   return res;
331 }
332 
333 
334 /*
335 ** Convert bits from a random integer into a float in the
336 ** interval [0,1), getting the higher FIG bits from the
337 ** random unsigned integer and converting that to a float.
338 ** Some old Microsoft compilers cannot cast an unsigned long
339 ** to a floating-point number, so we use a signed long as an
340 ** intermediary. When lua_Number is float or double, the shift ensures
341 ** that 'sx' is non negative; in that case, a good compiler will remove
342 ** the correction.
343 */
344 
345 /* must throw out the extra (64 - FIGS) bits */
346 #define shift64_FIG	(64 - FIGS)
347 
348 /* 2^(-FIGS) == 2^-1 / 2^(FIGS-1) */
349 #define scaleFIG	(l_mathop(0.5) / ((Rand64)1 << (FIGS - 1)))
350 
I2d(Rand64 x)351 static lua_Number I2d (Rand64 x) {
352   SRand64 sx = (SRand64)(trim64(x) >> shift64_FIG);
353   lua_Number res = (lua_Number)(sx) * scaleFIG;
354   if (sx < 0)
355     res += l_mathop(1.0);  /* correct the two's complement if negative */
356   lua_assert(0 <= res && res < 1);
357   return res;
358 }
359 
360 /* convert a 'Rand64' to a 'lua_Unsigned' */
361 #define I2UInt(x)	((lua_Unsigned)trim64(x))
362 
363 /* convert a 'lua_Unsigned' to a 'Rand64' */
364 #define Int2I(x)	((Rand64)(x))
365 
366 
367 #else	/* no 'Rand64'   }{ */
368 
369 /* get an integer with at least 32 bits */
370 #if LUAI_IS32INT
371 typedef unsigned int lu_int32;
372 #else
373 typedef unsigned long lu_int32;
374 #endif
375 
376 
377 /*
378 ** Use two 32-bit integers to represent a 64-bit quantity.
379 */
380 typedef struct Rand64 {
381   lu_int32 h;  /* higher half */
382   lu_int32 l;  /* lower half */
383 } Rand64;
384 
385 
386 /*
387 ** If 'lu_int32' has more than 32 bits, the extra bits do not interfere
388 ** with the 32 initial bits, except in a right shift and comparisons.
389 ** Moreover, the final result has to discard the extra bits.
390 */
391 
392 /* avoid using extra bits when needed */
393 #define trim32(x)	((x) & 0xffffffffu)
394 
395 
396 /*
397 ** basic operations on 'Rand64' values
398 */
399 
400 /* build a new Rand64 value */
packI(lu_int32 h,lu_int32 l)401 static Rand64 packI (lu_int32 h, lu_int32 l) {
402   Rand64 result;
403   result.h = h;
404   result.l = l;
405   return result;
406 }
407 
408 /* return i << n */
Ishl(Rand64 i,int n)409 static Rand64 Ishl (Rand64 i, int n) {
410   lua_assert(n > 0 && n < 32);
411   return packI((i.h << n) | (trim32(i.l) >> (32 - n)), i.l << n);
412 }
413 
414 /* i1 ^= i2 */
Ixor(Rand64 * i1,Rand64 i2)415 static void Ixor (Rand64 *i1, Rand64 i2) {
416   i1->h ^= i2.h;
417   i1->l ^= i2.l;
418 }
419 
420 /* return i1 + i2 */
Iadd(Rand64 i1,Rand64 i2)421 static Rand64 Iadd (Rand64 i1, Rand64 i2) {
422   Rand64 result = packI(i1.h + i2.h, i1.l + i2.l);
423   if (trim32(result.l) < trim32(i1.l))  /* carry? */
424     result.h++;
425   return result;
426 }
427 
428 /* return i * 5 */
times5(Rand64 i)429 static Rand64 times5 (Rand64 i) {
430   return Iadd(Ishl(i, 2), i);  /* i * 5 == (i << 2) + i */
431 }
432 
433 /* return i * 9 */
times9(Rand64 i)434 static Rand64 times9 (Rand64 i) {
435   return Iadd(Ishl(i, 3), i);  /* i * 9 == (i << 3) + i */
436 }
437 
438 /* return 'i' rotated left 'n' bits */
rotl(Rand64 i,int n)439 static Rand64 rotl (Rand64 i, int n) {
440   lua_assert(n > 0 && n < 32);
441   return packI((i.h << n) | (trim32(i.l) >> (32 - n)),
442                (trim32(i.h) >> (32 - n)) | (i.l << n));
443 }
444 
445 /* for offsets larger than 32, rotate right by 64 - offset */
rotl1(Rand64 i,int n)446 static Rand64 rotl1 (Rand64 i, int n) {
447   lua_assert(n > 32 && n < 64);
448   n = 64 - n;
449   return packI((trim32(i.h) >> n) | (i.l << (32 - n)),
450                (i.h << (32 - n)) | (trim32(i.l) >> n));
451 }
452 
453 /*
454 ** implementation of 'xoshiro256**' algorithm on 'Rand64' values
455 */
nextrand(Rand64 * state)456 static Rand64 nextrand (Rand64 *state) {
457   Rand64 res = times9(rotl(times5(state[1]), 7));
458   Rand64 t = Ishl(state[1], 17);
459   Ixor(&state[2], state[0]);
460   Ixor(&state[3], state[1]);
461   Ixor(&state[1], state[2]);
462   Ixor(&state[0], state[3]);
463   Ixor(&state[2], t);
464   state[3] = rotl1(state[3], 45);
465   return res;
466 }
467 
468 
469 /*
470 ** Converts a 'Rand64' into a float.
471 */
472 
473 /* an unsigned 1 with proper type */
474 #define UONE		((lu_int32)1)
475 
476 
477 #if FIGS <= 32
478 
479 /* 2^(-FIGS) */
480 #define scaleFIG       (l_mathop(0.5) / (UONE << (FIGS - 1)))
481 
482 /*
483 ** get up to 32 bits from higher half, shifting right to
484 ** throw out the extra bits.
485 */
I2d(Rand64 x)486 static lua_Number I2d (Rand64 x) {
487   lua_Number h = (lua_Number)(trim32(x.h) >> (32 - FIGS));
488   return h * scaleFIG;
489 }
490 
491 #else	/* 32 < FIGS <= 64 */
492 
493 /* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */
494 #define scaleFIG  \
495     (l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33)))
496 
497 /*
498 ** use FIGS - 32 bits from lower half, throwing out the other
499 ** (32 - (FIGS - 32)) = (64 - FIGS) bits
500 */
501 #define shiftLOW	(64 - FIGS)
502 
503 /*
504 ** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32)
505 */
506 #define shiftHI		((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0))
507 
508 
I2d(Rand64 x)509 static lua_Number I2d (Rand64 x) {
510   lua_Number h = (lua_Number)trim32(x.h) * shiftHI;
511   lua_Number l = (lua_Number)(trim32(x.l) >> shiftLOW);
512   return (h + l) * scaleFIG;
513 }
514 
515 #endif
516 
517 
518 /* convert a 'Rand64' to a 'lua_Unsigned' */
I2UInt(Rand64 x)519 static lua_Unsigned I2UInt (Rand64 x) {
520   return (((lua_Unsigned)trim32(x.h) << 31) << 1) | (lua_Unsigned)trim32(x.l);
521 }
522 
523 /* convert a 'lua_Unsigned' to a 'Rand64' */
Int2I(lua_Unsigned n)524 static Rand64 Int2I (lua_Unsigned n) {
525   return packI((lu_int32)((n >> 31) >> 1), (lu_int32)n);
526 }
527 
528 #endif  /* } */
529 
530 
531 /*
532 ** A state uses four 'Rand64' values.
533 */
534 typedef struct {
535   Rand64 s[4];
536 } RanState;
537 
538 
539 /*
540 ** Project the random integer 'ran' into the interval [0, n].
541 ** Because 'ran' has 2^B possible values, the projection can only be
542 ** uniform when the size of the interval is a power of 2 (exact
543 ** division). Otherwise, to get a uniform projection into [0, n], we
544 ** first compute 'lim', the smallest Mersenne number not smaller than
545 ** 'n'. We then project 'ran' into the interval [0, lim].  If the result
546 ** is inside [0, n], we are done. Otherwise, we try with another 'ran',
547 ** until we have a result inside the interval.
548 */
project(lua_Unsigned ran,lua_Unsigned n,RanState * state)549 static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
550                              RanState *state) {
551   if ((n & (n + 1)) == 0)  /* is 'n + 1' a power of 2? */
552     return ran & n;  /* no bias */
553   else {
554     lua_Unsigned lim = n;
555     /* compute the smallest (2^b - 1) not smaller than 'n' */
556     lim |= (lim >> 1);
557     lim |= (lim >> 2);
558     lim |= (lim >> 4);
559     lim |= (lim >> 8);
560     lim |= (lim >> 16);
561 #if (LUA_MAXUNSIGNED >> 31) >= 3
562     lim |= (lim >> 32);  /* integer type has more than 32 bits */
563 #endif
564     lua_assert((lim & (lim + 1)) == 0  /* 'lim + 1' is a power of 2, */
565       && lim >= n  /* not smaller than 'n', */
566       && (lim >> 1) < n);  /* and it is the smallest one */
567     while ((ran &= lim) > n)  /* project 'ran' into [0..lim] */
568       ran = I2UInt(nextrand(state->s));  /* not inside [0..n]? try again */
569     return ran;
570   }
571 }
572 
573 
math_random(lua_State * L)574 static int math_random (lua_State *L) {
575   lua_Integer low, up;
576   lua_Unsigned p;
577   RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
578   Rand64 rv = nextrand(state->s);  /* next pseudo-random value */
579   switch (lua_gettop(L)) {  /* check number of arguments */
580     case 0: {  /* no arguments */
581       lua_pushnumber(L, I2d(rv));  /* float between 0 and 1 */
582       return 1;
583     }
584     case 1: {  /* only upper limit */
585       low = 1;
586       up = luaL_checkinteger(L, 1);
587       if (up == 0) {  /* single 0 as argument? */
588         lua_pushinteger(L, I2UInt(rv));  /* full random integer */
589         return 1;
590       }
591       break;
592     }
593     case 2: {  /* lower and upper limits */
594       low = luaL_checkinteger(L, 1);
595       up = luaL_checkinteger(L, 2);
596       break;
597     }
598     default: return luaL_error(L, "wrong number of arguments");
599   }
600   /* random integer in the interval [low, up] */
601   luaL_argcheck(L, low <= up, 1, "interval is empty");
602   /* project random integer into the interval [0, up - low] */
603   p = project(I2UInt(rv), (lua_Unsigned)up - (lua_Unsigned)low, state);
604   lua_pushinteger(L, p + (lua_Unsigned)low);
605   return 1;
606 }
607 
608 
setseed(lua_State * L,Rand64 * state,lua_Unsigned n1,lua_Unsigned n2)609 static void setseed (lua_State *L, Rand64 *state,
610                      lua_Unsigned n1, lua_Unsigned n2) {
611   int i;
612   state[0] = Int2I(n1);
613   state[1] = Int2I(0xff);  /* avoid a zero state */
614   state[2] = Int2I(n2);
615   state[3] = Int2I(0);
616   for (i = 0; i < 16; i++)
617     nextrand(state);  /* discard initial values to "spread" seed */
618   lua_pushinteger(L, n1);
619   lua_pushinteger(L, n2);
620 }
621 
622 
623 /*
624 ** Set a "random" seed. To get some randomness, use the current time
625 ** and the address of 'L' (in case the machine does address space layout
626 ** randomization).
627 */
randseed(lua_State * L,RanState * state)628 static void randseed (lua_State *L, RanState *state) {
629   lua_Unsigned seed1 = (lua_Unsigned)time(NULL);
630   lua_Unsigned seed2 = (lua_Unsigned)(size_t)L;
631   setseed(L, state->s, seed1, seed2);
632 }
633 
634 
math_randomseed(lua_State * L)635 static int math_randomseed (lua_State *L) {
636   RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
637   if (lua_isnone(L, 1)) {
638     randseed(L, state);
639   }
640   else {
641     lua_Integer n1 = luaL_checkinteger(L, 1);
642     lua_Integer n2 = luaL_optinteger(L, 2, 0);
643     setseed(L, state->s, n1, n2);
644   }
645   return 2;  /* return seeds */
646 }
647 
648 
649 static const luaL_Reg randfuncs[] = {
650   {"random", math_random},
651   {"randomseed", math_randomseed},
652   {NULL, NULL}
653 };
654 
655 
656 /*
657 ** Register the random functions and initialize their state.
658 */
setrandfunc(lua_State * L)659 static void setrandfunc (lua_State *L) {
660   RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0);
661   randseed(L, state);  /* initialize with a "random" seed */
662   lua_pop(L, 2);  /* remove pushed seeds */
663   luaL_setfuncs(L, randfuncs, 1);
664 }
665 
666 /* }================================================================== */
667 
668 
669 /*
670 ** {==================================================================
671 ** Deprecated functions (for compatibility only)
672 ** ===================================================================
673 */
674 #if defined(LUA_COMPAT_MATHLIB)
675 
math_cosh(lua_State * L)676 static int math_cosh (lua_State *L) {
677   lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
678   return 1;
679 }
680 
math_sinh(lua_State * L)681 static int math_sinh (lua_State *L) {
682   lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
683   return 1;
684 }
685 
math_tanh(lua_State * L)686 static int math_tanh (lua_State *L) {
687   lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
688   return 1;
689 }
690 
math_pow(lua_State * L)691 static int math_pow (lua_State *L) {
692   lua_Number x = luaL_checknumber(L, 1);
693   lua_Number y = luaL_checknumber(L, 2);
694   lua_pushnumber(L, l_mathop(pow)(x, y));
695   return 1;
696 }
697 
math_frexp(lua_State * L)698 static int math_frexp (lua_State *L) {
699   int e;
700   lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
701   lua_pushinteger(L, e);
702   return 2;
703 }
704 
math_ldexp(lua_State * L)705 static int math_ldexp (lua_State *L) {
706   lua_Number x = luaL_checknumber(L, 1);
707   int ep = (int)luaL_checkinteger(L, 2);
708   lua_pushnumber(L, l_mathop(ldexp)(x, ep));
709   return 1;
710 }
711 
math_log10(lua_State * L)712 static int math_log10 (lua_State *L) {
713   lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
714   return 1;
715 }
716 
717 #endif
718 /* }================================================================== */
719 
720 
721 
722 static const luaL_Reg mathlib[] = {
723   {"abs",   math_abs},
724   {"acos",  math_acos},
725   {"asin",  math_asin},
726   {"atan",  math_atan},
727   {"ceil",  math_ceil},
728   {"cos",   math_cos},
729   {"deg",   math_deg},
730   {"exp",   math_exp},
731   {"tointeger", math_toint},
732   {"floor", math_floor},
733   {"fmod",   math_fmod},
734   {"ult",   math_ult},
735   {"log",   math_log},
736   {"max",   math_max},
737   {"min",   math_min},
738   {"modf",   math_modf},
739   {"rad",   math_rad},
740   {"sin",   math_sin},
741   {"sqrt",  math_sqrt},
742   {"tan",   math_tan},
743   {"type", math_type},
744 #if defined(LUA_COMPAT_MATHLIB)
745   {"atan2", math_atan},
746   {"cosh",   math_cosh},
747   {"sinh",   math_sinh},
748   {"tanh",   math_tanh},
749   {"pow",   math_pow},
750   {"frexp", math_frexp},
751   {"ldexp", math_ldexp},
752   {"log10", math_log10},
753 #endif
754   /* placeholders */
755   {"random", NULL},
756   {"randomseed", NULL},
757   {"pi", NULL},
758   {"huge", NULL},
759   {"maxinteger", NULL},
760   {"mininteger", NULL},
761   {NULL, NULL}
762 };
763 
764 
765 /*
766 ** Open math library
767 */
luaopen_math(lua_State * L)768 LUAMOD_API int luaopen_math (lua_State *L) {
769   luaL_newlib(L, mathlib);
770   lua_pushnumber(L, PI);
771   lua_setfield(L, -2, "pi");
772   lua_pushnumber(L, (lua_Number)HUGE_VAL);
773   lua_setfield(L, -2, "huge");
774   lua_pushinteger(L, LUA_MAXINTEGER);
775   lua_setfield(L, -2, "maxinteger");
776   lua_pushinteger(L, LUA_MININTEGER);
777   lua_setfield(L, -2, "mininteger");
778   setrandfunc(L);
779   return 1;
780 }
781 
782