Skip to content

Commit 339c0d0

Browse files
committed
Work in progress
1 parent 5208a97 commit 339c0d0

1 file changed

Lines changed: 7 additions & 8 deletions

File tree

_posts/2025-08-02-replacing-lua-s-math-random-module-with-the-xorshift-algorithm.md

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@ Anyway, I ended up replacing Lua’s implementation with the one below, because
2626
```cpp
2727
static std::array<uint64_t, 2> prng_state;
2828

29-
void seed(const uint64_t a, uint64_t b) {
30-
if (a == 0 && b == 0) b = 1;
31-
prng_state[0] = a;
32-
prng_state[1] = b;
29+
void seed(uint64_t value) {
30+
constexpr uint64_t mix = 0xdeadbeefcafebabeULL;
31+
if (value == 0) value = 1;
32+
prng_state[0] = value;
33+
prng_state[1] = value ^ mix;
3334
}
3435

3536
uint64_t xorshift128plus() {
@@ -56,8 +57,7 @@ lua_Integer xorshift_random_int(const lua_Integer low, const lua_Integer high) {
5657
}
5758

5859
const auto now = std::chrono::high_resolution_clock::now().time_since_epoch().count();
59-
const auto seed_val = static_cast<uint64_t>(now);
60-
seed(seed_val, seed_val ^ 0xdeadbeefcafebabeULL);
60+
seed(static_cast<uint64_t>(now));
6161

6262
lua["math"]["random"] = sol::overload(
6363
[]() -> double {
@@ -72,7 +72,6 @@ lua["math"]["random"] = sol::overload(
7272
);
7373

7474
lua["math"]["randomseed"] = [](lua_Integer seed_value) {
75-
const uint64_t s = static_cast<uint64_t>(seed_value);
76-
seed(s, s ^ 0xdeadbeefcafebabeULL);
75+
seed(static_cast<uint64_t>(seed_value));
7776
};
7877
```

0 commit comments

Comments
 (0)