Scribunto: An Introduction/Numbers

In the last chapter we learned how to use the debug console, and how to display text from a module on a normal wiki page. The module we wrote to display the text used quite a few new concepts, and you may be feeling a little confused after reading it. However, please don't panic just yet; in part two of this book we will learn all the concepts necessary to understand that module, and more. Until we have covered all the concepts used in the module that we wrote, we will concentrate on using the debug console, which allows us to write simpler programs.

So, without further ado, let's get started on learning some basic Lua concepts. First, we will cover something that is likely very familiar to you: the use of numbers.

Inputting numbers
The syntax for inputting numbers in Lua is very simple. In fact, there is no special syntax; all you do is type the number in. Try the following example in the debug console:

The debug console should print the same numbers as the ones you typed. Now, let's see what happens if we add some zeroes:

Even though we input 002 and 2.0, the output is still 2. This is because Lua interprets the value of the number; it doesn't remember the exact characters that you type.

To insert a negative number, just prefix it with a hyphen.

Calculation
Now, let's do some calculations. Lua can do any calculation that your pocket calculator can, and quite a few that it can't. To make calculations, Lua uses arithmetic operators. This is just a complicated way of saying "symbols that you do arithmetic with". For example, addition is performed with the  operator.

Similarly, subtraction, multiplication and division are performed with the,   and   operators, respectively.

The result of  may surprise some readers, as in some other programming languages this same code produces "3", and to get a result of "3.3333333333333" you need to write something like. However, in Lua there is no distinction between  and.

It is also possible to find the remainder after division by using the modulo (or mod) operator,.

This example means, "Divide 17 by 5 and output what is left over." 17 doesn't divide by 5 exactly; the next highest number that divides exactly by 5 is 15. The difference between 17 and 15 is 2, so this is what Lua outputs.

The modulo operator has many applications. For example, you can find whether a number is odd or even by using.

If you use  with an odd number, it will give a result of 1, and if you use it with an even number, it will give a result of 0.

The final operator that we will introduce here is, which is used to make calculations with exponents (or powers). For example,  means "2 to the power 3", or.