From fb6a20845fed68f1fc3bb5722bb1f5f7f9469d95 Mon Sep 17 00:00:00 2001 From: amelia squires Date: Mon, 29 Jun 2026 08:01:17 -0500 Subject: 'better' rng --- src/math.c | 18 ++++++++++++++++-- src/reg.c | 2 -- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/math.c b/src/math.c index 75cd578..e7cd1bb 100644 --- a/src/math.c +++ b/src/math.c @@ -15,6 +15,8 @@ end #include "math.h" #include "stdint.h" #include +#include +#include uint64_t gcd(uint64_t a, uint64_t b){ if(b == 0) return a; @@ -47,18 +49,30 @@ int l_lcm(lua_State* L){ return 1; } +thread_local uint16_t seedv[3] = {0, 0, 0}; + int l_random(lua_State* L){ + if(seedv[0] + seedv[1] + seedv[2] == 0){ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + uint64_t seed = (ts.tv_sec << 32) | ts.tv_nsec; + + seedv[0] = seed; + seedv[1] = seed >> 16; + seedv[2] = seed >> 32; + } + size_t min = 1; switch(lua_gettop(L)){ case 2: min = lua_tointeger(L, 1); lua_remove(L, 1); case 1: - lua_pushinteger(L, (rand() % (lua_tointeger(L, 1) - min + 1)) + min); + lua_pushinteger(L, (erand48(seedv) * (lua_tointeger(L, 1) - min + 1)) + min); break; case 0: default: - lua_pushnumber(L, (double)rand() / (double)RAND_MAX); + lua_pushnumber(L, erand48(seedv)); } return 1; diff --git a/src/reg.c b/src/reg.c index c57cdf7..b90e03d 100644 --- a/src/reg.c +++ b/src/reg.c @@ -8,7 +8,6 @@ #include "test.h" #include "config.h" #include "lullaby.h" -#include #define open_common(name, config)\ int luaopen_lullaby_##name (lua_State* L){\ @@ -39,7 +38,6 @@ lua_settable(L, T); int luaopen_lullaby(lua_State* L) { - srand(time(NULL)); lua_newtable(L); int top = lua_gettop(L); -- cgit v1.2.3