Minetest provides four different random sources, each with its own merits. Modders must choose wisely unless they can let the engine do the random for them (e.g. randomly picking a sound or a texture for particles).
Not restricted by mod security, these functions are available to both SSMs and CSMs:
Seed the random. Minetest already does this for you using the system time.
Important
|
Do not seed the random
Do not seed the random to turn it into a deterministic random source as other mods may expect it to be "non-deterministic". Conversely, do not rely on the random to have any particular seed either; other mods & the engine may have seeded it (using the system time) to be "non-deterministic". The problem with If you need ---
-- Use the random to generate a seed for the random; preferable over using system time,
-- as the latter may be deterministic
local seed = ... -- some fixed seed
local reseed = math.random(2^31-1)
math.randomseed(seed) -- temporarily make the random "deterministic"
-- ... do something using `math.random` ...
math.randomseed(reseed)
--- |
Get a random number. Very versatile; allows getting floats between 0
and 1
or integers in a range.
Note
|
The random numbers between 0 and 1 do not provide a full 52-bit mantissa
full of entropy; they usually have around 32 bits of entropy.
|
Warning
|
When using this to obtain integers,
make sure that both the upper & lower bound
as well as their difference are within the C int range -
otherwise you may get overflows & errors.
|
Warning
|
This is not portable; different builds on different platforms will produce different random numbers.
PUC Lua 5.1 builds use a system-provided random generator.
LuaJIT builds use LuaJIT’s PRNG implementation.
Do not use math.random in mapgen, for example.
|
Tip
|
Use math.random as your go-to versatile "non-deterministic" random source.
|
A seedable 32-bit signed integer pseudo-random number generator.
Constructs a PcgRandom
instance with the given seed,
which should be an integer within 32-bit bounds.
If min
and max
are both omitted,
they default to -2^31
(-2147483648
)
and 2^31 - 1
(2147483647
) respectively.
Warning
|
No successful use of this function is documented. Consider implementing your own normal distribution instead. |
min
and max
are required; they need to be integers.
Rough approximation of a normal distribution with a mean of (max - min) / 2
and a variance of (((max - min + 1) ^ 2) - 1) / (12 * num_trials)
.
num_trials
defaults to 6
. The more trials, the better the approximation.
The return value is a float.
A seedable 16-bit unsigned integer pseudo-random number generator.
"Uses a well-known LCG algorithm introduced by K&R."
Perhaps the lowest-quality random generator of all.
System-provided cryptographically secure random: An attacker should not be able to predict the generated sequence of random numbers. Use this when generating cryptographic keys or tokens.
Not necessarily available in all builds and on all platforms.
Constructor: Returns a SecureRandom object or nil
if no secure random source is available.
Tip
|
Use assert(SecureRandom(), "no secure random available") to error if no secure random source is available.
|
---
collectgarbage"stop" -- we don't want GC heuristics to interfere
local n = 1e8 — number of runs local function bench(name, constructor, invokation) local func = assert(loadstring[[ local r = %s for _ = 1, %d do %s end ]]):format(constructor, n, invokation) local t = minetest.get_us_time() func() print(name, (minetest.get_us_time() - t) / n, "µs/call") end
bench("Lua", "nil", "math.random()") bench("PCG", "PcgRandom(42)", "r:next()") bench("K&R", "PseudoRandom(42)", "r:next()") bench("Secure", "assert(SecureRandom())", "r:next_bytes()") ---
Example output:
---
Lua 0.00385002 µs/call
PCG 0.05579729 µs/call
K&R 0.05859349 µs/call
Secure 0.11211887 µs/call
---
Random Source |
Performance |
Bytes of entropy |
Seedability |
Versatility |
Distribution |
Security |
Portability |
|
very good (1x) |
up to 4 |
global seed; seeded by default |
very good |
no guarantees, but usually decent enough |
not cryptographically secure |
varies by platform |
|
okay (~14x) |
up to 4 |
per-instance seed |
very good |
good, decent guarantees |
not cryptographically secure |
always the same |
|
okay (~15x) |
1 to 2 |
per-instance seed |
outright sucks |
okay-ish |
not cryptographically secure |
always the same |
Note: The performance comparison is a bit of an apples-to-oranges comparison for multiple reasons:
-
The different generators make different guarantees regarding the randomness;
-
The different generators generate different numbers of bytes per invocation - the default was arbitrarily chosen; Secure random in particular is able to generate plenty of bytes (up to 2048) with one call.
The benchmark still suffices to draw basic conclusions though,
especially for the common case where a random source is simply used once
(e.g. math.random() < 0.5
).