When Waldemar, Luiz, and I started the development of Lua, back in 1993, we could hardly imagine that it would spread as it did. Started as an in-house language for two specific projects, currently Lua is widely used in all areas that can benefit from a simple, extensible, portable, and efficient scripting language, such as embedded systems, mobile devices, the Internet of Things, and, of course, games.
We designed Lua, from the beginning, to be integrated with software written in C/C++ and other conventional languages. This integration brings many benefits. Lua is a small and simple language, partly because it does not try to do what C is already good for, such as sheer performance and interface with third-party software. Lua relies on C for these tasks. What Lua does offer is what C is not good for: a good distance from the hardware, dynamic structures, no redundancies, and ease of testing and debugging. For these goals, Lua has a safe environment, automatic memory management, and good facilities for handling strings and other kinds of data with dynamic size.
Part of the power of Lua comes from its libraries. This is not by chance. After all, one of the main strengths of Lua is its extensibility. Many features contribute to this strength. Dynamic typing allows a great degree of polymorphism. Automatic memory management simplifies interfaces, because there is no need to decide who is responsible for allocating and deallocating memory or how to handle overflows. First-class functions allow a high degree of parameterization, making functions more versatile.
More than an extensible language, Lua is also a glue language. Lua supports a component-based approach to software development, where we create an application by gluing together existing high-level components. These components are written in a compiled, statically-typed language, such as C or C++; Lua is the glue that we use to compose and connect these components. Usually, the components (or objects) represent more concrete, low-level concepts (such as widgets and data structures) that are not subject to many changes during program development, and that take the bulk of the CPU time of the final program. Lua gives the final shape of the application, which will probably change a lot during the life cycle of the product. We can use Lua not only to glue components, but also to adapt and reshape them, and to create completely new components.
Of course, Lua is not the only scripting language around. There are other languages that you can use for more or less the same purposes. Nevertheless, Lua offers a set of features that makes it your best choice for many tasks and gives it a unique profile:
Lua’s extensibility is so remarkable that many people regard Lua not as a language, but as a kit for building domain-specific languages. We designed Lua from scratch to be extended, both through Lua code and through external C code. As a proof of concept, Lua implements most of its own basic functionality through external libraries. It is really easy to interface Lua with external languages like C/C++, Java, C#, and Python.
Lua is a simple and small language. It has few (but powerful) concepts. This simplicity makes Lua easy to learn and contributes to its small size. (Its Linux 64-bit executable, including all standard libraries, has 220 KB.)
Lua has a quite efficient implementation. Independent benchmarks show Lua as one of the fastest languages in the realm of scripting languages.
When we talk about portability, we are talking about running Lua on all platforms we have ever heard about: all flavors of UNIX (Linux, FreeBSD, etc.) Windows, Android, iOS, OS X, IBM mainframes, game consoles (PlayStation, Xbox, Wii, etc.), microcontrollers (Arduino, etc.), and many more. The source code for each of these platforms is virtually the same. Lua does not use conditional compilation to adapt its code to different machines; instead, it sticks to the standard ISO (ANSI) C. This way, you do not usually need to adapt it to a new environment: if you have an ISO C compiler, you just have to compile Lua, out of the box.
This book does not assume any prior knowledge of Lua or any specific programming language —except for its last part, which discusses the Lua API with C. However, it assumes the knowledge of some basic programming concepts, in particular variables and assignment, control structures, functions and parameters, recursion, streams and files, and basic data structures.
Lua users typically fall into three broad groups: those that use Lua already embedded in an application program, those that use Lua stand alone, and those that use Lua and C together. This book has much to offer to all these groups.
Many people use Lua embedded in an application program, such as Adobe Lightroom, Nmap, or World of Warcraft. These applications use Lua’s C API to register new functions, to create new types, and to change the behavior of some language operations, configuring Lua for their specific domains. Often, the users of such applications do not even know that Lua is an independent language adapted for a particular domain. For instance, many developers of plug-ins for Lightroom do not know about other uses of the language; Nmap users tend to think of Lua as the language of the Nmap Scripting Engine; many players of World of Warcraft regard Lua as a language exclusive to that game. Despite these different worlds, the core language is still the same, and the programming techniques you will learn here apply everywhere.
Lua is useful also as a stand-alone language, not only for text processing and one-shot little programs, but for medium-to-large projects, too. For such uses, the main functionality of Lua comes from libraries. The standard libraries, for instance, offer pattern matching and other functions for string handling. As Lua has improved its support for libraries, there has been a proliferation of external packages. LuaRocks, a deployment and management system for Lua modules, passed one thousand modules in 2015, covering all sorts of domains.
Finally, there are those programmers that work on the other side of the bench, writing applications that use Lua as a C library. Those people will program more in C than in Lua, although they need a good understanding of Lua to create interfaces that are simple, easy to use, and well integrated with the language.
This edition adds new material and examples in many areas, including sandboxing, coroutines, date and time manipulation, in addition to the new material related to version 5.3: integers, bitwise operations, unsigned integers, etc.
More importantly, this edition marks a major restructuring of the text. Instead of organizing the material around the language (e.g., with separate chapters for each library), I tried to organize the material around common themes in programming. That organization allows the book to better follow an order of increasing complexity, with simple themes coming first. That order came from experience teaching courses about the language; in particular, I think this new organization fits the book better as a didactic resource for courses involving Lua.
As the previous editions, this one is organized in four parts, each with around nine chapters. However, the parts have a quite new character.
The first part covers the basics of the language (and it is fittingly named The Basics). It is organized around the main types of values in Lua: numbers, strings, tables, and functions. It also covers basic I/O and gives an overview of the syntax of the language.
The second part, called Real Programming, covers more advanced topics that you can expect to find in other similar languages, such as closures, pattern matching, date and time manipulation, data structures, modules, and error handling.
The third part is called Lua-isms. As the name implies, it covers aspects of Lua that are particularly different from other languages, such as metatables and its uses, environments, weak tables, coroutines, and reflection. These are also the more advanced aspects of the language.
Finally, as in previous editions, the last part of the book covers the API between Lua and C, for those that use C to get the full power of Lua. The flavor of that part is necessarily quite different from the rest of the book. There, we will be programming in C, not in Lua; therefore, we will be wearing a different hat. For some readers, the discussion of the C API may be of marginal interest; for others, it may be the most relevant part of this book.
Along all parts, we focus on different language constructs and use numerous examples and exercises to show how to use them for practical tasks. We also have a few interludes among the chapters. Each interlude presents a short but complete program in Lua, which gives a more holistic view of the language.
The reference manual is a must
for anyone who wants to really learn a language.
This book does not replace the Lua reference manual;
quite the opposite, it complements the manual.
The manual only describes Lua.
It shows neither examples nor a rationale for the constructs
of the language.
On the other hand, it describes the whole language;
this book skips over seldom-used dark corners of Lua.
Moreover, the manual is the authoritative document about Lua.
Wherever this book disagrees with the manual,
trust the manual.
To get the manual and more information about Lua,
visit the Lua site at http://www.lua.org
.
You can also find useful information at the Lua users’ site,
kept by the community of users
at http://lua-users.org
.
Among other resources,
it offers a tutorial,
a list of third-party packages and documentation,
and an archive of the official Lua mailing list.
This book describes Lua 5.3, although most of its contents also apply to previous versions and probably to future versions as well. All differences between Lua 5.3 and older Lua 5 versions are clearly marked in the text. If you are using a more recent version (released after the book), check the corresponding manual for differences between versions.
The book encloses "literal strings"
between double quotes
and single characters, such as a
, between single quotes.
Strings that are used as patterns
are also enclosed between single quotes,
like ’[%w_]*
’.
The book uses a typewriter font
both for chunks of code
and for identifiers.
For reserved words, it uses a boldface font.
Larger chunks of code are shown in display style:
-- program "Hello World" print("Hello World") --> Hello World
The notation -->
shows the output of a statement or
the result of an expression:
print(10) --> 10 13 + 3 --> 16
Because a double hyphen (--
) starts a comment in Lua,
there is no problem if you include
these annotations in your code.
Several code fragments in the book,
mainly in the initial chapters,
should be entered in interactive mode.
In that case,
I use a notation showing the Lua prompt ("> "
) in each line:
> 3 + 5 --> 8 > math.sin(2.3) --> 0.74570521217672
In Lua 5.2 and older versions, to print the result of an expression in interactive mode, you must precede the expression with an equals sign:
> = 3 + 5 --> 8 > a = 25 > = a --> 25
For compatibility, Lua 5.3 still accepts this equal sign.
Finally, the book uses the notation <-->
to indicate that something is equivalent to something else:
this <--> that
You will need a Lua interpreter to run the examples in this book. Ideally, you should use Lua 5.3, but most of the examples run on older versions without modifications.
The Lua site (http://www.lua.org
) keeps
the source code for the interpreter.
If you have a C compiler
and a working knowledge of how to compile C code
in your machine,
you should try to install Lua from its source code;
it is really easy.
The Lua Binaries site (search for luabinaries
)
offers precompiled Lua interpreters for most major platforms.
If you use Linux or another UNIX-like system,
you may check the repository of your distribution;
several distributions already offer a package with Lua.
There are several Integrated Development Environments (IDEs) for Lua. Again, you can easily find them with a basic search. (Nevertheless, I am an old timer. I still prefer a command-line interface in a window and a text editor in another, specially for the initial learning steps.)
It is more than ten years since I published the first edition of this book. Several friends and institutions have helped me along this journey.
As always, Luiz Henrique de Figueiredo and Waldemar Celes, Lua coauthors, offered all kinds of help. André Carregal, Asko Kauppi, Brett Kapilik, Diego Nehab, Edwin Moragas, Fernando Jefferson, Gavin Wraith, John D. Ramsdell, Norman Ramsey, Reuben Thomas, and Robert Day provided invaluable suggestions and useful insights for diverse editions of this book. Luiza Novaes provided key support for the cover design.
Lightning Source, Inc. proved a reliable and efficient option for printing and distributing the book. Without them, the option of self-publishing the book would not be an option.
Tecgraf, headed by Marcelo Gattass, housed the Lua project from its birth in 1993 until 2005, and continues to help the project in several ways.
I also would like to thank the Pontifical Catholic University of Rio de Janeiro (PUC-Rio) and the Brazilian National Research Council (CNPq) for their continuous support to my work. In particular, the Lua project would be impossible without the environment that I have at PUC-Rio.
Finally, I must express my deep gratitude to Noemi Rodriguez, for all kinds of help (technical and non-technical) and for illumining my life.
Personal copy of Eric Taylor <jdslkgjf.iapgjflksfg@yandex.com>