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.
This commit is contained in:
Roberto Ierusalimschy
2023-03-20 16:13:17 -03:00
parent 8c064fdc23
commit 5a04f1851e
9 changed files with 87 additions and 86 deletions

View File

@@ -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);
}