Introduction to Lua
From Wikiversity
Contents |
[edit] 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 Return, and blocks of code (such as if statements and loops) after you complete them (with an "end").
Fire up a terminal and start up the interpreter (just type "lua" on *nix machines, you may have to CD to the directory on Windows machines). Here is an example session:
Lua 5.1.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio
> print("Hello, World!")
Hello, World!
> print(5+7)
12
> if true then
>> print(true)
>> end
true
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.
[edit] Executing and Compiling Scripts
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 .lua extension. To execute a script, the filename is passed as an argument to the interpreter. For example:
lua myscript.lua
You can compile your scripts using luac, the Lua compiler.
luac inputfile
This will output the bytecode to a file named luac.out. Use the -o argument to change this:
luac -o outputfile inputfile
[edit] 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 the values have types. Consider this:
a = 15
print(a)
a = "Hello"
print(a)
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.
[edit] 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 is essentially a non-existent value.