Numbers Tutorial

lua-users home

Internal representation

Some languages support one or more of the following number types by default:

In the interest of simplicity Lua supports only one type of number, floating point numbers. By default these are double precision floating point numbers, but Lua can easily be recompiled to support single precision floating point numbers should you so desire. If you are unfamiliar with floating point it may be advantageous for you to read about FloatingPoint numbers.

The main thing to remember is that if you use numbers with fractional parts (or division), they may have rounding error, since they are stored in a limited amount of space. Also numbers that are short or don't have infinitely repeating patterns in decimal may have them in binary, so don't assume that any fractional number is "safe". The main things to remember are not to use the == operator with fractional numbers (since it checks for perfect equality), and to write your code so that rounding error can't build up to large amounts over time.

If your numbers are integers (with no fractional part), and they don't reach 2^53, then all this isn't an issue.

Using numbers

We can use the Lua interactive command line prompt as a calculator by prefixing an expression by =, e.g.,

Lua 5.1  Copyright (C) 1994-2006, PUC-Rio
> = 1
> = 1 + 2
> = 3.1415927
> = 5 / 6
We can enter numbers and evaluate simple calculations. Lua can also understand exponent types for expressing numbers in the form <value> * 10 ^ <exponent>
> = 1.2345e6
> = 543.21E8
> = 2.56e-4
We can assign numbers to variables and do arithmetic:
> width = 7.5
> height = 12.7
> = width * height
> depth = 2.8
> area = width * height
> volume = area * depth
> print(area, volume)
95.25   266.7

The math library

Lua is equipped with a math library (see section 5.6 of the Reference Manual [1]). The functions provided are as follows:

math.abs     math.acos    math.asin       math.atan    math.atan2
math.ceil    math.cos     math.cosh       math.deg     math.exp
math.floor   math.fmod    math.frexp      math.ldexp   math.log
math.log10   math.max     math.min        math.modf    math.pow
math.rad     math.random  math.randomseed math.sin     math.sinh
math.sqrt    math.tan     math.tanh
We'll try a few of the functions and variables as an example.
> = math.sqrt(101)
> = math.pi
> = math.sin( math.pi/3 )
Read the MathLibraryTutorial for more details.


You can convert strings to numbers using the function tonumber(). This takes a string argument and returns a number.

> = tonumber("123") + 25
> x = tonumber("123.456e5")
> print(x)


Lua will automatically convert string and number types to the correct format in order to perform calculations. For example, if you try to apply an arithmetic operation to a string, Lua will try to convert that string to a number first, otherwise the operation will not work. If the string cannot be converted to a number an error is raised. This automatic conversion of types is called coercion.

> = 100 + "7"
> = "1000" + 234
> = "hello" + 234
stdin:1: attempt to perform arithmetic on a string value
stack traceback:
        stdin:1: in main chunk
        [C]: ?
> = 234 + "1000"
You can see where a string can be converted to number, the calculation succeeds. The string "hello" cannot be converted to a number and so an error occurs. In statically typed languages (e.g. C) this would cause an error as you cannot assign a value to a variable of an incompatible type. This works in Lua because it is dynamically typed.

A notable exception: comparison operators (== ~= < > <= >=) do not coerce their arguments. The (in)equality operators consider a number to be not equal to its string representation (or any non-number type in fact). Ordered comparison operators throw an error when you feed them different types.

> = 100 == "100"
> = 100 ~= "hello"
> = 100 ~= {}
> = 100 == tonumber("100")
> = 100 <= "100"
stdin:1: attempt to compare number with string
stack traceback:
        stdin:1: in main chunk
        [C]: ?
For performance reasons you should avoid relying on automatic coercion too much. Make sure that all numbers in performance sensitive computations (especially in inner loops) are of the proper type.
RecentChanges · preferences
edit · history
Last edited May 25, 2013 9:32 pm GMT (diff)