Lua/Introduction

Lua can be used both as a scripting/programming language on its own, and as an integrated scripting language for other platforms. This lesson focuses on using Lua with the interpreter available from Lua.org. See the next lesson to learn how to use Lua for scripting MediaWiki Scribunto/Lua extension templates now available on Wikiversity.

Prerequisites
The Lua interpreter, which can be downloaded from the official Lua website. The package includes the Lua compiler and a few sample scripts.

Lua command line interpreter
The command line Lua interpreter is a nifty tool if you need to quickly test some code. It executes lines of code as soon as you hit the Return key, and blocks of code (such as conditional statements and loops) after you complete them (with the  keyword).

If you have Lua installed, you can start the terminal and run  to start the interpreter. If not, you can download and install it, use the repl.it Lua emulator in the browser or the Lua demo.

Here is an example session:

The first line uses the function print to output the string "Hello, world!". Numbers and booleans may also be output using print. The interpreter acknowledges code blocks with an extra '>' at the prompt.

When done, hit Ctrl-D (EOF) to close the interpreter.

Executing and compiling programs
While entering commands at the command line prompt is suitable for testing, it is not for executing scripts. Scripts are usually saved in files with the  file extension. To execute a script, the filename is passed as an argument to the interpreter. For example:

You can compile your scripts using, the Lua compiler.

This will output the bytecode to a file named. Use the -o argument to change this:

Variables
The rest of the lesson will simply list the code—it is up to you to try it in the interpreter or save it in a file and execute it.

Lua is a dynamically-typed language. Variables don't have types, only values have types. This means that a variable can be set to a value of a type, and then to a value of another type. Consider this:

Output: 15 Hello

This has advantages and disadvantages. It allows for different types of values to be used easily, but also means that unexpected types may be used, causing errors.

Value types
The following basic types are available in Lua:


 * boolean: Can be true or false
 * number: A real number (floating-point precision)
 * string: A string of characters, such as "Hello, world!".
 * function: Functions are first-class values in Lua (more on this later).
 * userdata: C objects passed to Lua (more on this later).
 * thread: Lua coroutines (more on this later).
 * table: Tables are flexible data structures (more on this later).
 * nil: Type of the value nil. nil represents the absence of a value