High-quality PRNG for MTA:SA Lua 5.1, seeded from MariaDB's CSPRNG.
Replaces the weak built-in math.random (32-bit LCG) with a xorshift128 generator (period 2^128 - 1), seeded from MariaDB's RANDOM_BYTES() which sources entropy from OpenSSL's RAND_bytes.
The database is only touched once during seeding. All subsequent calls are pure Lua bitwise math — fast enough for real-time use like table shuffling.
- Copy
random.luainto your MTA:SA resource - Add it to your
meta.xml:
<script src="random.lua" type="server" />-- Seed once using your existing DB connection
local db = dbConnect("mysql", "dbname=mydb;host=127.0.0.1", "user", "pass")
random.seed(db)
-- Use it
local roll = random.int(1, 100)
local coin = random.bool()
local deck = {}
for i = 1, 52 do deck[i] = i end
random.shuffle(deck)| Function | Description |
|---|---|
random.seed(connection) |
Seed the PRNG from MariaDB's CSPRNG. Pass your dbConnect handle. Returns boolean. |
| Function | Description |
|---|---|
random.raw32() |
Raw 32-bit unsigned integer [0, 2^32 - 1]. |
random.int(min, max) |
Integer in [min, max], no modulo bias. Supports ranges up to 2^53. |
random.float() |
Float in [0, 1) with 32-bit precision. |
random.float53() |
Float in [0, 1) with 53-bit precision (full double mantissa). |
random.bool(pTrue?) |
Random boolean. Optional pTrue sets probability of true (default 0.5). |
| Function | Description |
|---|---|
random.hex128() |
128-bit random as a 32-character hex string. |
random.uuid() |
RFC 4122 UUID v4. |
| Function | Description |
|---|---|
random.shuffle(t) |
In-place Fisher-Yates shuffle. Returns the same table. |
random.choice(t) |
Pick a random element from an array. |
random.sample(t, n) |
Pick n unique elements (no repeats). Returns a new array. |
random.weighted(items, weights) |
Weighted random selection. |
math.random |
random.lua |
|
|---|---|---|
| Algorithm | C rand() LCG |
xorshift128 |
| State | 32-bit | 128-bit |
| Period | ~2^32 | 2^128 - 1 |
| Seed source | os.time() (predictable) |
MariaDB RANDOM_BYTES() (OpenSSL CSPRNG) |
| Modulo bias | Yes | No (rejection sampling) |
| Performance | ~1 multiply + add | ~4 XORs + shifts |
Seeding once is sufficient for most use cases. If you want periodic re-seeding:
setTimer(function() random.seed(db) end, 600000, 0) -- every 10 minutesThis is not a cryptographic PRNG. The seed comes from a CSPRNG, but xorshift128 itself is not suitable for cryptographic purposes (key generation, authentication tokens that must resist state recovery, etc.). For game logic, shuffling, loot drops, and similar use cases it is more than adequate.
This project is licensed under the GNU General Public License v3.0. See the LICENSE file for details.
teamxpr.com | Generated by Claude Opus 4.6 (Anthropic)