Random Numbers in Lua

Here’s the translation of the Go code to Lua, with explanations in Markdown format suitable for Hugo:

Lua’s math.random function provides pseudorandom number generation.

-- For example, math.random(100) returns a random integer n,
-- 1 <= n <= 100.
print(math.random(100), ",", math.random(100))
print()

-- math.random() returns a float f,
-- 0.0 <= f < 1.0.
print(math.random())

-- This can be used to generate random floats in
-- other ranges, for example 5.0 <= f' < 10.0.
print((math.random() * 5) + 5, ",", (math.random() * 5) + 5)
print()

-- If you want a known seed, use math.randomseed.
-- This sets a fixed seed for the random number generator.
math.randomseed(42)
print(math.random(100), ",", math.random(100))
print()

-- Using the same seed will produce the same sequence of random numbers.
math.randomseed(42)
print(math.random(100), ",", math.random(100))
print()

Some of the generated numbers may be different when you run the sample.

$ lua random-numbers.lua
42,78
0.7728531138485
5.1130238712206,7.5666729574614
37,58
37,58

See the Lua manual for references on other random quantities that Lua can provide.

In Lua, the math.random function is used for generating random numbers. It can be called in different ways:

  1. math.random(): Returns a float between 0 and 1.
  2. math.random(n): Returns an integer between 1 and n.
  3. math.random(m, n): Returns an integer between m and n.

The math.randomseed function is used to set a seed for the random number generator. Using the same seed will produce the same sequence of random numbers, which is useful for reproducible results.

Unlike Go, Lua doesn’t have built-in support for different random number generation algorithms like PCG. If you need more advanced random number generation, you might need to use external libraries or implement the algorithms yourself.