diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2019-07-17 16:00:24 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2019-07-17 16:00:24 -0300 |
commit | 4eefef07ab1c136f901d816822c79336fa89336d (patch) | |
tree | ce2232ba8a09287899af1ac07af0c902800bfae6 /lmathlib.c | |
parent | 9c28ed05c95cb6854d917ac3e3ed7be9ae109480 (diff) | |
download | lua-4eefef07ab1c136f901d816822c79336fa89336d.tar.gz lua-4eefef07ab1c136f901d816822c79336fa89336d.tar.bz2 lua-4eefef07ab1c136f901d816822c79336fa89336d.zip |
'math.randomseed()' returns the seeds it used
A call to 'math.randomseed()' returns the two components of the seed
it set, so that they can be used to set that same seed again.
Diffstat (limited to 'lmathlib.c')
-rw-r--r-- | lmathlib.c | 9 |
1 files changed, 7 insertions, 2 deletions
@@ -605,20 +605,24 @@ static void setseed (Rand64 *state, lua_Unsigned n1, lua_Unsigned n2) { | |||
605 | static void randseed (lua_State *L, RanState *state) { | 605 | static void randseed (lua_State *L, RanState *state) { |
606 | lua_Unsigned seed1 = (lua_Unsigned)time(NULL); | 606 | lua_Unsigned seed1 = (lua_Unsigned)time(NULL); |
607 | lua_Unsigned seed2 = (lua_Unsigned)(size_t)L; | 607 | lua_Unsigned seed2 = (lua_Unsigned)(size_t)L; |
608 | lua_pushinteger(L, seed1); | ||
609 | lua_pushinteger(L, seed2); | ||
608 | setseed(state->s, seed1, seed2); | 610 | setseed(state->s, seed1, seed2); |
609 | } | 611 | } |
610 | 612 | ||
611 | 613 | ||
612 | static int math_randomseed (lua_State *L) { | 614 | static int math_randomseed (lua_State *L) { |
613 | RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); | 615 | RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); |
614 | if (lua_isnone(L, 1)) | 616 | if (lua_isnone(L, 1)) { |
615 | randseed(L, state); | 617 | randseed(L, state); |
618 | return 2; /* return seeds */ | ||
619 | } | ||
616 | else { | 620 | else { |
617 | lua_Integer n1 = luaL_checkinteger(L, 1); | 621 | lua_Integer n1 = luaL_checkinteger(L, 1); |
618 | lua_Integer n2 = luaL_optinteger(L, 2, 0); | 622 | lua_Integer n2 = luaL_optinteger(L, 2, 0); |
619 | setseed(state->s, n1, n2); | 623 | setseed(state->s, n1, n2); |
624 | return 0; | ||
620 | } | 625 | } |
621 | return 0; | ||
622 | } | 626 | } |
623 | 627 | ||
624 | 628 | ||
@@ -635,6 +639,7 @@ static const luaL_Reg randfuncs[] = { | |||
635 | static void setrandfunc (lua_State *L) { | 639 | static void setrandfunc (lua_State *L) { |
636 | RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0); | 640 | RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0); |
637 | randseed(L, state); /* initialize with a "random" seed */ | 641 | randseed(L, state); /* initialize with a "random" seed */ |
642 | lua_pop(L, 2); /* remove pushed seeds */ | ||
638 | luaL_setfuncs(L, randfuncs, 1); | 643 | luaL_setfuncs(L, randfuncs, 1); |
639 | } | 644 | } |
640 | 645 | ||