This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


18 – The Mathematical Library

In this chapter (and in the other chapters about the standard libraries), my purpose is not to give the complete specification of each function, but to show you what kind of functionality the library can provide. I may omit some subtle options or behaviors for clarity of exposition. The main idea is to spark your curiosity, which can then be satisfied by the reference manual.

The math library comprises a standard set of mathematical functions, such as trigonometric functions (sin, cos, tan, asin, acos, etc.), exponentiation and logarithms (exp, log, log10), rounding functions (floor, ceil), max, min, plus a variable pi. The mathematical library also defines the operator `^´ to work as the exponentiation operator.

All trigonometric functions work in radians. (Until Lua 4.0, they worked in degrees.) You can use the functions deg and rad to convert between degrees and radians. If you want to work in degrees, you can redefine the trigonometric functions:

    local sin, asin, ... = math.sin, math.asin, ...
    local deg, rad = math.deg, math.rad
    math.sin = function (x) return sin(rad(x)) end
    math.asin = function (x) return deg(asin(x)) end
    ...

The math.random function generates pseudo-random numbers. We can call it in three ways. When we call it without arguments, it returns a pseudo-random real number with uniform distribution in the interval [0,1). When we call it with only one argument, an integer n, it returns an integer pseudo-random number x such that 1 <= x <= n. For instance, you can simulate the result of a die with random(6). Finally, we can call random with two integer arguments, l and u, to get a pseudo-random integer x such that l <= x <= u.

You can set a seed for the pseudo-random generator with the randomseed function; its only numeric argument is the seed. Usually, when a program starts, it initializes the generator with a fixed seed. That means that, every time you run your program, it generates the same sequence of pseudo-random numbers. For debugging, that is a nice property; but in a game, you will have the same scenario over and over. A common trick to solve this problem is to use the current time as a seed:

    math.randomseed(os.time())
(The os.time function returns a number that represents the current time, usually as the number of seconds since some epoch.)