From 5a04f1851e0d42b4bcbb0af103490bc964e985aa Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Mon, 20 Mar 2023 16:13:17 -0300 Subject: New function 'luaL_makeseed' This function unifies code from 'lua_newstate', 'math.randomseed', and 'table.sort' that tries to create a value with a minimum level of randomness. --- lmathlib.c | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) (limited to 'lmathlib.c') diff --git a/lmathlib.c b/lmathlib.c index d0b1e1e5..f13cae4a 100644 --- a/lmathlib.c +++ b/lmathlib.c @@ -603,28 +603,18 @@ static void setseed (lua_State *L, Rand64 *state, } -/* -** Set a "random" seed. To get some randomness, use the current time -** and the address of 'L' (in case the machine does address space layout -** randomization). -*/ -static void randseed (lua_State *L, RanState *state) { - lua_Unsigned seed1 = (lua_Unsigned)time(NULL); - lua_Unsigned seed2 = (lua_Unsigned)(size_t)L; - setseed(L, state->s, seed1, seed2); -} - - static int math_randomseed (lua_State *L) { RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1)); + lua_Unsigned n1, n2; if (lua_isnone(L, 1)) { - randseed(L, state); + n1 = luaL_makeseed(L); + n2 = I2UInt(state->s[0]); } else { - lua_Integer n1 = luaL_checkinteger(L, 1); - lua_Integer n2 = luaL_optinteger(L, 2, 0); - setseed(L, state->s, n1, n2); + n1 = luaL_checkinteger(L, 1); + n2 = luaL_optinteger(L, 2, 0); } + setseed(L, state->s, n1, n2); return 2; /* return seeds */ } @@ -641,7 +631,7 @@ static const luaL_Reg randfuncs[] = { */ static void setrandfunc (lua_State *L) { RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0); - randseed(L, state); /* initialize with a "random" seed */ + setseed(L, state->s, luaL_makeseed(L), 0); /* initialize with random seed */ lua_pop(L, 2); /* remove pushed seeds */ luaL_setfuncs(L, randfuncs, 1); } -- cgit v1.2.3-55-g6feb