Immediate Download Programming in Lua 3rd Edition Roberto Ierusalimschy Ebooks 2024
Immediate Download Programming in Lua 3rd Edition Roberto Ierusalimschy Ebooks 2024
com
https://ebookfinal.com/download/programming-in-lua-3rd-
edition-roberto-ierusalimschy/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookfinal.com/download/programming-in-lua-2nd-edition-
roberto-ierusalimschy/
ebookfinal.com
https://ebookfinal.com/download/beginning-lua-programming-1st-edition-
jung/
ebookfinal.com
https://ebookfinal.com/download/love-for-lua-game-programming-1st-
edition-akinlaja/
ebookfinal.com
https://ebookfinal.com/download/beginning-linux-programming-3rd-
edition-neil-matthew/
ebookfinal.com
CNC programming handbook a comprehensive guide to
practical CNC programming 3rd ed Edition Smid
https://ebookfinal.com/download/cnc-programming-handbook-a-
comprehensive-guide-to-practical-cnc-programming-3rd-ed-edition-smid/
ebookfinal.com
https://ebookfinal.com/download/android-programming-tutorials-3rd-
edition-mark-l-murphy/
ebookfinal.com
https://ebookfinal.com/download/practical-programming-for-strength-
training-3rd-edition-rippetoe/
ebookfinal.com
https://ebookfinal.com/download/beginning-programming-for-dummies-3rd-
ed-edition-wallace-wang/
ebookfinal.com
https://ebookfinal.com/download/programming-languages-principles-and-
practices-3rd-edition-kenneth-c-louden/
ebookfinal.com
Programming in Lua
Third Edition
Programming in Lua
Third Edition
Roberto Ierusalimschy
PUC-Rio, Brazil
Lua.org
Rio de Janeiro
ProgramminginLua,ThirdEdition
by Roberto Ierusalimschy
ISBN 978-85-903798-5-0
Book cover by Luiza Novaes. Lua logo design by Alexandre Nako. Typeset by
the author using LATEX.
Although the author used his best efforts preparing this book, he assumes no
responsibility for errors or omissions, or for any damage that may result from
the use of the information presented here. All product names mentioned in this
book are trademarks of their respective owners.
CIP–BibliotecadoDepartamentodeInformática,PUC-Rio
Ierusalimschy, Roberto
I22 Programming in Lua / Roberto Ierusalimschy. – 3th ed.
– Rio de Janeiro, 2013.
xviii, 348 p. : 25 cm.
Includes index.
ISBN 978-85-903798-5-0
1. Lua (Programming language). I. Title.
005.133 – dc20
Preface xiii
I The Language 1
1 Getting Started 3
1.1 Chunks 4
1.2 Some Lexical Conventions 5
1.3 Global Variables 6
1.4 The Stand-Alone Interpreter 6
Exercises 8
3 Expressions 21
3.1 Arithmetic Operators 21
3.2 Relational Operators 22
3.3 Logical Operators 23
3.4 Concatenation 23
3.5 The Length Operator 24
3.6 Precedence 25
3.7 Table Constructors 26
Exercises 28
vii
viii Contents
4 Statements 29
4.1 Assignment 29
4.2 Local Variables and Blocks 30
4.3 Control Structures 32
4.4 break, return, and goto 36
Exercises 38
5 Functions 41
5.1 Multiple Results 42
5.2 Variadic Functions 46
5.3 Named Arguments 48
Exercises 49
9 Coroutines 83
9.1 Coroutine Basics 83
9.2 Pipes and Filters 86
9.3 Coroutines as Iterators 89
9.4 Non-Preemptive Multithreading 91
Exercises 95
ix
10 Complete Examples 97
10.1 The Eight-Queen Puzzle 97
10.2 Most Frequent Words 99
10.3 Markov Chain Algorithm 101
Exercises 102
Index 339
Preface
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, 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 tiny and simple language, partly because it does not try to
do what C is already good for, such as sheer performance, low-level operations,
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 con-
tribute 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. Higher-order functions and anonymous 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 ap-
plication 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 compo-
nents (or objects) represent more concrete, low-level concepts (such as widgets
and data structures) that are not subject to many changes during program de-
velopment, 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 dur-
ing the life cycle of the product. However, unlike other glue technologies, Lua
is a full-fledged language as well. Therefore, we can use Lua not only to glue
xiii
xiv Preface
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:
Extensibility: 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 C/C++, and Lua has been used integrated with several
other languages as well, such as Fortran, Java, Smalltalk, Ada, C#, and
even with other scripting languages, such as Perl and Python.
Simplicity: 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 complete distribution (source code, manual, plus binaries
for some platforms) fits comfortably in a floppy disk.
Efficiency: Lua has a quite efficient implementation. Independent benchmarks
show Lua as one of the fastest languages in the realm of scripting lan-
guages.
Portability: When we talk about portability, we are talking about running Lua
on all platforms we have ever heard about: all flavors of UNIX and Win-
dows, PlayStation, Xbox, Mac OS X and iOS, Android, Kindle Fire, NOOK,
Haiku, QUALCOMM Brew, IBM mainframes, RISC OS, Symbian OS, Rab-
bit processors, Raspberry Pi, Arduino, 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 ANSI (ISO) C. This way, you do not usually need to adapt it
to a new environment: if you have an ANSI C compiler, you just have to
compile Lua, out of the box.
Audience
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.
Many people use Lua embedded in an application program, such as Adobe
Lightroom, Nmap, or World of Warcraft. These applications use the Lua–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. Fre-
quently, the users of such applications do not even know that Lua is an inde-
pendent language adapted for a particular domain. For instance, many devel-
opers of plug-ins for Lightroom do not know about other uses of the language;
xv
Nmap users tend to think of Lua as the language of the Nmap Scripting Engine;
players of World of Warcraft may regard Lua as a language exclusive to that
game.
Lua is useful also as a stand-alone language, not only for text-processing and
one-shot little programs, but increasingly for medium-to-large projects, too. For
such uses, the main functionality of Lua comes from libraries. The standard
libraries, for instance, offer basic pattern matching and other functions for
string handling. As Lua improves its support for libraries, there has been a
proliferation of external packages. Lua Rocks, a deployment and management
system for Lua modules, currently features more than 150 packages.
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 book has much to offer to all these people. The first part covers the
language itself, showing how we can explore all its potential. We focus on
different language constructs and use numerous examples and exercises to show
how to use them for practical tasks. Some chapters in this part cover basic
concepts, such as control structures, while others cover topics more advanced,
such as iterators and coroutines.
The second part is entirely devoted to tables, the sole data structure in Lua.
Its chapters discuss data structures, persistence, packages, and object-oriented
programming. There we will unveil the real power of the language.
The third part presents the standard libraries. This part is particularly
useful for those that use Lua as a stand-alone language, although many other
applications also incorporate all or part of the standard libraries. This part
devotes one chapter to each standard library: the mathematical library, the
bitwise library, the table library, the string library, the I/O library, the operating
system library, and the debug library.
Finally, 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 this 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.
Nevertheless, I clearly marked the differences from Lua 5.1, so you can use the
book for that version too.
Second, and more important, I have added exercises to all chapters of the
book. These exercises range from simple questions about the language to full
small-size projects. Several exercises illustrate important aspects of program-
ming in Lua and are as important as the examples to expand your toolbox of
useful techniques.
As we did with the first and second editions of Programming in Lua, we self-
published this third edition. Despite the limited marketing, this avenue brings
several benefits: we have total control over the book contents; we keep the full
rights to offer the book in other forms; we have freedom to choose when to release
another edition; and we can ensure that the book does not go out of print.
Other Resources
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, they
complement each other. 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.2, although most of its contents also apply to
Lua 5.1 and Lua 5.0. The few differences between Lua 5.2 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 occasional differ-
ences between versions. If you are using a version older than 5.2, this is a good
time to consider an upgrade.
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 programs. Finally, the book uses the
notation <--> to indicate that something is equivalent to something else:
Acknowledgments
It is almost 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,
and Norman Ramsey provided invaluable suggestions and useful insights for
diverse editions of this book.
Luiza Novaes, head of the Arts & Design Department at PUC-Rio, managed
to find some time in her busy schedule to create an ideal cover for this edition.
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.
xviii Preface
The Language
Getting Started
1
To keep with the tradition, our first program in Lua just prints “Hello World”:
print("Hello World")
If you are using the stand-alone Lua interpreter, all you have to do to run your
first program is to call the interpreter — usually named lua or lua5.2 — with the
name of the text file that contains your program. If you save the above program
in a file hello.lua, the following command should run it:
% lua hello.lua
As a more complex example, the next program defines a function to compute
the factorial of a given number, asks the user for a number, and prints its
factorial:
-- defines a factorial function
function fact (n)
if n == 0 then
return 1
else
return n * fact(n-1)
end
end
print("enter a number:")
a = io.read("*n") -- reads a number
print(fact(a))
3
4 Chapter 1 Getting Started
1.1 Chunks
Each piece of code that Lua executes, such as a file or a single line in interac-
tive mode, is called a chunk. A chunk is simply a sequence of commands (or
statements).
Lua needs no separator between consecutive statements, but you can use
a semicolon if you wish. My personal convention is to use semicolons only to
separate two or more statements written in the same line. Line breaks play no
role in Lua’s syntax; for instance, the following four chunks are all valid and
equivalent:
a = 1
b = a*2
a = 1;
b = a*2;
a = 1; b = a*2
a = 1 b = a*2 -- ugly, but valid
A command line like this one will run the chunk in file prog and then prompt you
for interaction. This is especially useful for debugging and manual testing. At
the end of this chapter, we will see other options for the stand-alone interpreter.
Another way to run chunks is with the dofile function, which immediately
executes a file. For instance, suppose you have a file lib1.lua with the following
code:
function norm (x, y)
return (x^2 + y^2)^0.5
end
function twice (x)
return 2*x
end
Then, in interactive mode, you can type
> dofile("lib1.lua") -- load your library
> n = norm(3.4, 1.0)
> print(twice(n)) --> 7.0880180586677
The dofile function is useful also when you are testing a piece of code. You
can work with two windows: one is a text editor with your program (in a file
prog.lua, say) and the other is a console running Lua in interactive mode. After
saving a modification in your program, you execute dofile("prog.lua") in the
Lua console to load the new code; then you can exercise the new code, calling its
functions and printing the results.
Lua is case-sensitive: and is a reserved word, but And and AND are two other
different identifiers.
A comment starts anywhere with a double hyphen (--) and runs until the
end of the line. Lua also offers block comments, which start with --[[ and run
until the next ]].1 A common trick to comment out a piece of code is to enclose
the code between --[[ and --]], like here:
--[[
print(10) -- no action (commented out)
--]]
To reactivate the code, we add a single hyphen to the first line:
---[[
print(10) --> 10
--]]
In the first example, the --[[ in the first line starts a block comment, and
the double hyphen in the last line is still inside that comment. In the second
example, the sequence ---[[ starts an ordinary, single-line comment, so that
the first and the last lines become independent comments. In this case, the
print is outside comments.
When the interpreter loads a file, it ignores its first line if this line starts
with a hash (‘#’). This feature allows the use of Lua as a script interpreter in
UNIX systems. If you start your script with something like
#!/usr/local/bin/lua
(assuming that the stand-alone interpreter is located at /usr/local/bin), or
#!/usr/bin/env lua
then you can call the script directly, without explicitly calling the Lua inter-
preter.
The usage of lua is
lua [options] [script [args]]
Everything is optional. As we have seen already, when we call lua without
arguments the interpreter enters in interactive mode.
The -e option allows us to enter code directly into the command line, like
here:
% lua -e "print(math.sin(12))" --> -0.53657291800043
(UNIX needs the double quotes to stop the shell from interpreting the parenthe-
ses.)
The -l option loads a library. As we saw previously, -i enters interactive
mode after running the other arguments. Therefore, the next call will load the
lib library, then execute the assignment x = 10, and finally present a prompt for
interaction.
% lua -i -llib -e "x = 10"
In interactive mode, you can print the value of any expression by writing a
line that starts with an equal sign followed by the expression:
> = math.sin(3) --> 0.14112000805987
> a = 30
> = a --> 30
This feature helps to use Lua as a calculator.
Before running its arguments, the interpreter looks for an environment vari-
able named LUA_INIT_5_2 or else, if there is no such variable, LUA_INIT. If there
is one of these variables and its content is @filename, then the interpreter runs
the given file. If LUA_INIT_5_2 (or LUA_INIT) is defined but it does not start
with ‘@’, then the interpreter assumes that it contains Lua code and runs it.
LUA_INIT gives us great power when configuring the stand-alone interpreter,
because we have the full power of Lua in the configuration. We can preload
packages, change the path, define our own functions, rename or delete functions,
and so on.
A script can retrieve its arguments in the predefined global variable arg.
In a call like % lua script a b c, the interpreter creates the table arg with all
8 Chapter 1 Getting Started
the command-line arguments, before running the script. The script name goes
into index 0, its first argument (“a” in the example) goes to index 1, and so on.
Preceding options go to negative indices, as they appear before the script. For
instance, consider this call:
% lua -e "sin=math.sin" script a b
The interpreter collects the arguments as follows:
arg[-3] = "lua"
arg[-2] = "-e"
arg[-1] = "sin=math.sin"
arg[0] = "script"
arg[1] = "a"
arg[2] = "b"
More often than not, a script uses only the positive indices (arg[1] and arg[2],
in the example).
Since Lua 5.1, a script can also retrieve its arguments through a vararg ex-
pression. In the main body of a script, the expression ... (three dots) results in
the arguments to the script. (We will discuss vararg expressions in Section 5.2.)
Exercises
Exercise1.1: Run the factorial example. What happens to your program if you
enter a negative number? Modify the example to avoid this problem.
Exercise 1.2: Run the twice example, both by loading the file with the -l
option and with dofile. Which way do you prefer?
Exercise1.3: Can you name other languages that use -- for comments?
Exercise1.4: Which of the following strings are valid identifiers?
Exercise1.5: Write a simple script that prints its own name without knowing
it in advance.
Types and Values
2
Lua is a dynamically typed language. There are no type definitions in the
language; each value carries its own type.
There are eight basic types in Lua: nil, boolean, number, string, userdata,
function, thread, and table. The type function gives the type name of any given
value:
print(type("Hello world")) --> string
print(type(10.4*3)) --> number
print(type(print)) --> function
print(type(type)) --> function
print(type(true)) --> boolean
print(type(nil)) --> nil
print(type(type(X))) --> string
The last line will result in “string” no matter the value of X, because the result
of type is always a string.
Variables have no predefined types; any variable can contain values of any
type:
9
10 Chapter 2 Types and Values
Notice the last two lines: functions are first-class values in Lua; so, we can
manipulate them like any other value. (We will see more about this facility in
Chapter 6.)
Usually, when you use a single variable for different types, the result is
messy code. However, sometimes the judicious use of this facility is helpful,
for instance in the use of nil to differentiate a normal return value from an
abnormal condition.
2.1 Nil
Nil is a type with a single value, nil, whose main property is to be different from
any other value. Lua uses nil as a kind of non-value, to represent the absence
of a useful value. As we have seen, a global variable has a nil value by default,
before its first assignment, and you can assign nil to a global variable to delete
it.
2.2 Booleans
The boolean type has two values, false and true, which represent the traditional
boolean values. However, booleans do not hold a monopoly of condition values:
in Lua, any value can represent a condition. Conditional tests (e.g., conditions in
control structures) consider both the boolean false and nil as false and anything
else as true. In particular, Lua considers both zero and the empty string as true
in conditional tests.
Throughout this book, I will type “false” to mean any false value, that is, the
boolean false or nil. When I mean specifically the boolean value, I will type
“false”. The same holds for “true” and “true”.
2.3 Numbers
The number type represents real (double-precision floating-point) numbers. Lua
has no integer type.
Some people fear that even a simple increment or comparison can go weird
with floating-point numbers. Reality, however, is not like that. Virtually all plat-
forms nowadays follow the IEEE 754 standard for floating-point representation.
Following this standard, the only possible source of errors is a representation er-
ror, which happens when a number cannot be exactly represented. An operation
rounds its result only if that result has no exact representation. Any operation
with a result that has an exact representation must give that exact result.
The fact is that any integer up to 253 (approximately 1016 ) has an exact
representation as a double-precision floating-point number. When you use a
double to represent an integer, there is no rounding error at all, unless the
2.4 Strings 11
number has an absolute value greater than 253 . In particular, a Lua number
can represent any 32-bit integer without rounding problems.
Of course, fractional numbers can have representation errors. The situation
here is not different from what happens with pen and paper. If we want to
write 1/7 in decimal, we will have to stop somewhere. If we use ten digits
to represent a number, 1/7 becomes rounded to 0.142857142. If we compute
1/7 * 7 using ten digits, the result will be 0.999999994, which is different from 1.
Moreover, numbers that have a finite representation in decimal can have an
infinite representation in binary. For instance, 12.7 - 20 + 7.3 is not exactly zero
when computed with doubles, because both 12.7 and 7.3 do not have an exact
finite representation in binary (see Exercise 2.3).
Before we go on, remember: integers do have exact representations and
therefore do not have rounding errors.
Most modern CPUs do floating-point arithmetic as fast as (or even faster
than) integer arithmetic. Nevertheless, it is easy to compile Lua so that it
uses another type for numbers, such as longs or single-precision floats. This
is particularly useful for platforms without hardware support for floating point,
such as embedded systems. See file luaconf.h in the distribution for details.
We can write numeric constants with an optional decimal part, plus an
optional decimal exponent. Examples of valid numeric constants are:
4 0.4 4.57e-3 0.3e12 5E+20
Moreover, we can also write hexadecimal constants, prefixing them with 0x.
Since Lua 5.2, hexadecimal constants can also have a fractional part and a
binary exponent (prefixed by ‘p’ or ‘P’), as in the following examples:
0xff (255) 0x1A3 (419) 0x0.2 (0.125) 0x1p-1 (0.5)
0xa.bp2 (42.75)
(For each constant, we added its decimal representation in parentheses.)
2.4 Strings
Strings in Lua have the usual meaning: a sequence of characters. Lua is
eight-bit clean and its strings can contain characters with any numeric code,
including embedded zeros. This means that you can store any binary data into
a string. You can also store Unicode strings in any representation (UTF-8, UTF-
16, etc.). The standard string library that comes with Lua offers no explicit
support for those representations. Nevertheless, we can handle UTF-8 strings
quite reasonably, as we will discuss in Section 21.7.
Strings in Lua are immutable values. You cannot change a character inside
a string, as you can in C; instead, you create a new string with the desired
modifications, as in the next example:
a = "one string"
b = string.gsub(a, "one", "another") -- change string parts
print(a) --> one string
print(b) --> another string
12 Chapter 2 Types and Values
Strings in Lua are subject to automatic memory management, like all other
Lua objects (tables, functions, etc.). This means that you do not have to worry
about allocation and deallocation of strings; Lua handles this for you. A string
can contain a single letter or an entire book. Programs that manipulate strings
with 100K or 1M characters are not unusual in Lua.
You can get the length of a string using the prefix operator ‘#’ (called the
length operator):
a = "hello"
print(#a) --> 5
print(#"good\0bye") --> 8
Literal strings
We can delimit literal strings by matching single or double quotes:
a = "a line"
b = 'another line'
They are equivalent; the only difference is that inside each kind of quote you can
use the other quote without escapes.
As a matter of style, most programmers always use the same kind of quotes
for the same kind of strings, where the “kinds” of strings depend on the program.
For instance, a library that manipulates XML may reserve single-quoted strings
for XML fragments, because those fragments often contain double quotes.
Strings in Lua can contain the following C-like escape sequences:
\a bell
\b back space
\f form feed
\n newline
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\" double quote
\' single quote
We can specify a character in a string also by its numeric value through the
escape sequences \ddd and \x\hh, where ddd is a sequence of up to three dec-
imal digits and hh is a sequence of exactly two hexadecimal digits. As a some-
what complex example, the two literals "alo\n123\"" and '\97lo\10\04923"'
have the same value, in a system using ASCII: 97 is the ASCII code for ‘a’, 10 is
the code for newline, and 49 is the code for the digit ‘1’. (In this example we must
write 49 with three digits, as \049, because it is followed by another digit; other-
wise Lua would read the number as 492.) We can also write that same string as
'\x61\x6c\x6f\x0a\x31\x32\x33\x22', representing each character by its hex-
adecimal code.
Long strings
We can delimit literal strings also by matching double square brackets, as we
do with long comments. Literals in this bracketed form can run for several
lines and do not interpret escape sequences. Moreover, this form ignores the
first character of the string when this character is a newline. This form is
especially convenient for writing strings that contain large pieces of code, as
in the following example:
page = [[
<html>
<head>
<title>An HTML Page</title>
</head>
<body>
<a href="http://www.lua.org">Lua</a>
</body>
</html>
]]
write(page)
contain arbitrary characters, it is not a good idea to use them in your code: you
may have problems with your text editor; moreover, end-of-line sequences like
“\r\n” may change to “\n” when read. Instead, it is better to code arbitrary bi-
nary data using numeric escape sequences, either in decimal or in hexadecimal,
such as “\x13\x01\xA1\xBB”. However, this poses a problem for long strings,
because they would result in quite long lines.
For those situations, Lua 5.2 offers the escape sequence \z: it skips all
subsequent characters in the string until the first non-space character. The next
example illustrates its use:
data = "\x00\x01\x02\x03\x04\x05\x06\x07\z
\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"
The \z at the end of the first line skips the following end-of-line and the inden-
tation of the next line, so that the byte \x07 is directly followed by \x08 in the
resulting string.
Coercions
Lua provides automatic conversions between numbers and strings at run time.
Any numeric operation applied to a string tries to convert the string to a number:
print("10" + 1) --> 11
print("10 + 1") --> 10 + 1
print("-5.3e-10"*"2") --> -1.06e-09
print("hello" + 1) -- ERROR (cannot convert "hello")
Lua applies such coercions not only in arithmetic operators, but also in other
places that expect a number, such as the argument to math.sin.
Conversely, whenever Lua finds a number where it expects a string, it con-
verts the number to a string:
(The .. is the string concatenation operator in Lua. When you write it right
after a numeral, you must separate them with a space; otherwise, Lua thinks
that the first dot is a decimal point.)
Today we are not sure that these automatic coercions were a good idea in
the design of Lua. As a rule, it is better not to count on them. They are handy
in a few places, but add complexity both to the language and to programs that
use them. After all, strings and numbers are different things, despite these
conversions. A comparison like 10 == "10" is false, because 10 is a number and
“10” is a string.
If you need to convert a string to a number explicitly, you can use the function
tonumber, which returns nil if the string does not denote a proper number:
2.5 Tables 15
2.5 Tables
The table type implements associative arrays. An associative array is an array
that can be indexed not only with numbers, but also with strings or any other
value of the language, except nil.
Tables are the main (in fact, the only) data structuring mechanism in Lua,
and a powerful one. We use tables to represent ordinary arrays, sets, records,
and other data structures in a simple, uniform, and efficient way. Lua uses
tables to represent packages and objects as well. When we write io.read, we
think about “the read function from the io module”. For Lua, this expression
means “index the table io using the string read as the key”.
Tables in Lua are neither values nor variables; they are objects. If you are
familiar with arrays in Java or Scheme, then you have a fair idea of what I
mean. You may think of a table as a dynamically allocated object; your program
manipulates only references (or pointers) to them. Lua never does hidden copies
or creation of new tables behind the scenes. Moreover, you do not have to declare
a table in Lua; in fact, there is no way to declare one. You create tables by means
of a constructor expression, which in its simplest form is written as {}:
a = {} -- create a table and store its reference in 'a'
k = "x"
a[k] = 10 -- new entry, with key="x" and value=10
a[20] = "great" -- new entry, with key=20 and value="great"
print(a["x"]) --> 10
k = 20
print(a[k]) --> "great"
a["x"] = a["x"] + 1 -- increments entry "x"
print(a["x"]) --> 11
A table is always anonymous. There is no fixed relationship between a
variable that holds a table and the table itself:
16 Chapter 2 Types and Values
a = {}
a["x"] = 10
b = a -- 'b' refers to the same table as 'a'
print(b["x"]) --> 10
b["x"] = 20
print(a["x"]) --> 20
a = nil -- only 'b' still refers to the table
b = nil -- no references left to the table
When a program has no more references to a table, Lua’s garbage collector will
eventually delete the table and reuse its memory.
Each table can store values with different types of indices, and it grows as
needed to accommodate new entries:
a = {} -- empty table
-- create 1000 new entries
for i = 1, 1000 do a[i] = i*2 end
print(a[9]) --> 18
a["x"] = 10
print(a["x"]) --> 10
print(a["y"]) --> nil
Note the last line: like global variables, table fields evaluate to nil when not
initialized. Also like global variables, you can assign nil to a table field to delete
it. This is not a coincidence: Lua stores global variables in ordinary tables. We
will discuss this subject further in Chapter 14.
To represent records, you use the field name as an index. Lua supports this
representation by providing a.name as syntactic sugar for a["name"]. Therefore,
we could write the last lines of the previous example in a cleaner manner as
follows:
a.x = 10 -- same as a["x"] = 10
print(a.x) -- same as print(a["x"])
print(a.y) -- same as print(a["y"])
For Lua, the two forms are equivalent and can be intermixed freely. For a human
reader, however, each form may signal a different intention. The dot notation
clearly shows that we are using the table as a record, where we have some set of
fixed, predefined keys. The string notation gives the idea that the table can have
any string as a key, and that for some reason we are manipulating that specific
key.
A common mistake for beginners is to confuse a.x with a[x]. The first form
represents a["x"], that is, a table indexed by the string “x”. The second form is
a table indexed by the value of the variable x. See the difference:
a = {}
x = "y"
a[x] = 10 -- put 10 in field "y"
print(a[x]) --> 10 -- value of field "y"
print(a.x) --> nil -- value of field "x" (undefined)
print(a.y) --> 10 -- value of field "y"
2.5 Tables 17
You can introduce subtle bugs in your program if you do not pay attention to this
point.
2.6 Functions
Functions are first-class values in Lua: programs can store functions in vari-
ables, pass functions as arguments to other functions, and return functions as
results. Such facilities give great flexibility to the language; a program can re-
define a function to add new functionality, or simply erase a function to create
a secure environment when running a piece of untrusted code (such as code re-
ceived through a network). Moreover, Lua offers good support for functional
programming, including nested functions with proper lexical scoping; just wait
until Chapter 6. Finally, first-class functions play a key role in Lua’s object-
oriented facilities, as we will see in Chapter 16.
Lua can call functions written in Lua and functions written in C. Typically,
we resort to C functions both to achieve better performance and to access facili-
ties not easily accessible directly from Lua, such as operating-system facilities.
All the standard libraries in Lua are written in C. They comprise functions for
string manipulation, table manipulation, I/O, access to basic operating system
facilities, mathematical functions, and debugging.
We will discuss Lua functions in Chapter 5 and C functions in Chapter 27.
Exercises
Exercise 2.1: What is the value of the expression type(nil) == nil? (You can
use Lua to check your answer.) Can you explain this result?
Exercise 2.2: Which of the following are valid numerals? What are their
values?
.0e12 .e12 0.0e 0x12 0xABFG 0xA FFFF 0xFFFFFFFF
0x 0x1P10 0.1e1 0x0.1p1
Exercise 2.3: The number 12.7 is equal to the fraction 127/10, where the
denominator is a power of ten. Can you express it as a common fraction where
the denominator is a power of two? What about the number 5.5?
Exercises 19
Exercise 2.4: How can you embed the following piece of XML as a string in
Lua?
<![CDATA[
Hello world
]]>
Show at least two different ways.
Exercise 2.5: Suppose you need to format a long sequence of arbitrary bytes
as a string literal in Lua. How would you do it? Consider issues like readability,
maximum line length, and performance.
Exercise2.6: Assume the following code:
a = {}; a.a = a
What would be the value of a.a.a.a? Is any a in that sequence somehow
different from the others?
Now, add the next line to the previous code:
a.a.a.a = 3
What would be the value of a.a.a.a now?
Expressions
3
Expressions denote values. Expressions in Lua include the numeric constants
and string literals, variables, unary and binary operations, and function calls.
Expressions include also the unconventional function definitions and table con-
structors.
a % b == a - math.floor(a/b)*b
For integer operands, it has the usual meaning, with the result always having
the same sign as the second argument. For real operands, it has some extra
uses. For instance, x%1 is the fractional part of x, and so x - x%1 is its integer
part. Similarly, x - x%0.01 is x with exactly two decimal digits:
x = math.pi
print(x - x%0.01) --> 3.14
As another example of the use of the modulo operator, suppose you want to
check whether a vehicle turning a given angle will start to backtrack. If the
angle is given in degrees, you can use the following formula:
21
22 Chapter 3 Expressions
local tolerance = 10
function isturnback (angle)
angle = angle % 360
return (math.abs(angle - 180) < tolerance)
end
This definition works even for negative angles:
print(isturnback(-180)) --> true
If we want to work with radians instead of degrees, we simply change the
constants in our function:
local tolerance = 0.17
function isturnback (angle)
angle = angle % (2*math.pi)
return (math.abs(angle - math.pi) < tolerance)
end
The operation angle % (2*math.pi) is all we need to normalize any angle to a
value in the interval [0, 2π).
3.4 Concatenation
Lua denotes the string concatenation operator by .. (two dots). If any operand
is a number, Lua converts this number to a string. (Some languages use the ‘+’
operator for concatenation, but 3+5 is different from 3 .. 5.)
24 Chapter 3 Expressions
a[10000] = nil
What is the list length now? Should it be 9999, because the program deleted
the last element? Or maybe still 10000, as the program only changed the last
element to nil? Or should the length collapse to 1?
Another common proposal is to make the # operator return the total number
of elements in the table. This semantics is clear and well defined, but not useful
at all. Consider all previous examples and think how useful would be such
operator for real algorithms over lists or arrays.
Yet more troubling are nils at the end of the list. What should be the length
of the following list?
3.6 Precedence
Operator precedence in Lua follows the table below, from the higher to the lower
priority:
^
not # - (unary)
* / %
+ -
..
< > <= >= ~= ==
and
or
All binary operators are left associative, except for ‘^’ (exponentiation) and ‘..’
(concatenation), which are right associative. Therefore, the following expres-
sions on the left are equivalent to those on the right:
a+i < b/2+1 <--> (a+i) < ((b/2)+1)
5+x^2*8 <--> 5+((x^2)*8)
a < y and y <= z <--> (a < y) and (y <= z)
-x^2 <--> -(x^2)
x^y^z <--> x^(y^z)
26 Chapter 3 Expressions
Lua also offers a special syntax to initialize a table record-like, as in the next
example:
a = {x=10, y=20}
The original expression, however, is faster, because Lua creates the table already
with the right size.
No matter what constructor we use to create a table, we can always add fields
to and remove fields from the result:
w = {x=0, y=0, label="console"}
x = {math.sin(0), math.sin(1), math.sin(2)}
w[1] = "another field" -- add key 1 to table 'w'
x.f = w -- add key "f" to table 'x'
print(w["x"]) --> 0
print(w[1]) --> another field
print(x.f[1]) --> another field
w.x = nil -- remove field "x"
However, as I just mentioned, creating a table with a proper constructor is more
efficient, besides being more elegant.
We can mix record-style and list-style initializations in the same constructor:
3.7 Table Constructors 27
polyline = {color="blue",
thickness=2,
npoints=4,
{x=0, y=0}, -- polyline[1]
{x=-10, y=0}, -- polyline[2]
{x=-10, y=1}, -- polyline[3]
{x=0, y=1} -- polyline[4]
}
The above example also illustrates how we can nest constructors to represent
more complex data structures. Each of the elements polyline[i] is a table
representing a record:
Those two constructor forms have their limitations. For instance, you cannot
initialize fields with negative indices, nor with string indices that are not proper
identifiers. For such needs, there is another, more general, format. In this
format, we explicitly write the index to be initialized as an expression, between
square brackets:
i = 20; s = "-"
a = {[i+0] = s, [i+1] = s..s, [i+2] = s..s..s}
This syntax is more cumbersome, but more flexible too: both the list-style and
the record-style forms are special cases of this more general syntax. The con-
structor {x = 0, y = 0} is equivalent to {["x"] = 0, ["y"] = 0}, and the constructor
{"r", "g", "b"} is equivalent to {[1] = "r", [2] = "g", [3] = "b"}.
You can always put a comma after the last entry. These trailing commas are
optional, but are always valid:
This flexibility frees programs that generate Lua constructors from the need to
handle the last element as a special case.
Finally, you can always use a semicolon instead of a comma in a constructor.
I usually reserve semicolons to delimit different sections in a constructor, for
instance to separate its list part from its record part:
Exercises
Exercise3.1: What will the following program print?
for i = -10, 10 do
print(i, i % 3)
end
Exercise3.2: What is the result of the expression 2^3^4? What about 2^-3^4?
Exercise3.3: We can represent a polynomial an xn + an−1 xn−1 + . . .+ a1 x1 + a0
in Lua as a list of its coefficients, such as {a0 , a1 , ..., an }.
Write a function that receives a polynomial (represented as a table) and a
value for x and returns the polynomial value.
Exercise3.4: Can you write the function from the previous item so that it uses
at most n additions and n multiplications (and no exponentiations)?
Exercise 3.5: How can you check whether a value is a boolean without using
the type function?
Exercise3.6: Consider the following expression:
(x and y and (not z)) or ((not y) and x)
Are the parentheses necessary? Would you recommend their use in that expres-
sion?
Exercise3.7: What will the following script print? Explain.
sunday = "monday"; monday = "sunday"
t = {sunday = "monday", [sunday] = monday}
print(t.sunday, t[sunday], t[t.sunday])
Exercise 3.8: Suppose that you want to create a table that associates each
escape sequence for strings (see Section 2.4) with its meaning. How could you
write a constructor for that table?
Statements
4
Lua supports an almost conventional set of statements, similar to those in C
or Pascal. The conventional statements include assignment, control structures,
and procedure calls. Lua also supports some not so conventional statements,
such as multiple assignments and local variable declarations.
4.1 Assignment
Assignment is the basic means of changing the value of a variable or a table
field:
a = "hello" .. "world"
t.n = t.n + 1
Lua allows multiple assignment, which assigns a list of values to a list of
variables in one step. Both lists have their elements separated by commas. For
instance, in the assignment
a, b = 10, 2*x
29
30 Chapter 4 Statements
Lua always adjusts the number of values to the number of variables: when
the list of values is shorter than the list of variables, the extra variables receive
nil as their values; when the list of values is longer, the extra values are silently
discarded:
a, b, c = 0, 1
print(a, b, c) --> 0 1 nil
a, b = a+1, b+1, b+2 -- value of b+2 is ignored
print(a, b) --> 1 2
a, b, c = 0
print(a, b, c) --> 0 nil nil
The last assignment in the above example shows a common mistake. To initial-
ize a set of variables, you must provide a value for each one:
a, b, c = 0, 0, 0
print(a, b, c) --> 0 0 0
Actually, most of the previous examples are somewhat artificial. I seldom
use multiple assignment simply to write several unrelated assignments in one
line. In particular, a multiple assignment is not faster than its equivalent
single assignments. Nevertheless, often we really need multiple assignment. We
already saw an example, to swap two values. A more frequent use is to collect
multiple returns from function calls. As we will discuss in detail in Section 5.1,
a function call can return multiple values. In such cases, a single expression can
supply the values for several variables. For instance, in the assignment a,b=f()
the call to f returns two results: a gets the first and b gets the second.
if i > 20 then
local x -- local to the "then" body
x = 20
print(x + 2) -- (would print 22 if test succeeded)
else
print(x) --> 10 (the global one)
end
print(x) --> 10 (the global one)
Beware that this example will not work as expected if you enter it in interactive
mode. In interactive mode, each line is a chunk by itself (unless it is not
a complete command). As soon as you enter the second line of the example
(local i = 1), Lua runs it and starts a new chunk in the next line. By then, the
local declaration is already out of scope. To solve this problem, we can delimit
the whole block explicitly, bracketing it with the keywords do–end. Once you
enter the do, the command completes only at the corresponding end, so Lua
does not execute each line by itself.
These do blocks are useful also when you need finer control over the scope of
some local variables:
do
local a2 = 2*a
local d = (b^2 - 4*a*c)^(1/2)
x1 = (-b + d)/a2
x2 = (-b - d)/a2
end -- scope of 'a2' and 'd' ends here
print(x1, x2)
It is good programming style to use local variables whenever possible. Local
variables help you avoid cluttering the global environment with unnecessary
names. Moreover, the access to local variables is faster than to global ones.
Finally, a local variable vanishes as soon as its scope ends, allowing the garbage
collector to release its value.
Lua handles local-variable declarations as statements. As such, you can
write local declarations anywhere you can write a statement. The scope of
the declared variables begins after the declaration and goes until the end of
the block. Each declaration can include an initial assignment, which works the
same way as a conventional assignment: extra values are thrown away; extra
variables get nil. If a declaration has no initial assignment, it initializes all its
variables with nil:
local a, b = 1, 10
if a < b then
print(a) --> 1
local a -- '= nil' is implicit
print(a) --> nil
end -- ends the block started at 'then'
print(a, b) --> 1 10
Exploring the Variety of Random
Documents with Different Content
highest but one of the ten grades or
ranks of chiefs. ↑
4 A royal progress in olden time was
known by its predominating red
insignia. ↑
5 Moa, trunk-fish (Ostracion
camurum). ↑
6 The recurrence of the names
Olopana and Luukia, and the flood
incident, prominent in the history of
Moikeha (Vol. iv, page 156 of these
Memoirs), again illustrates the free use
by the bards of popular characters and
plots for repetition in their stories. ↑
[Contents]
CHAPTER I. MOKUNA I.
RELATING TO NO KALAEPUNI.
KALAEPUNI.
Kalanipo and Kamaelekapu were O Kalanipo ka makuakane, o
the father and mother of Kamaelekapu ka wahine, o
Kalaepuni and Kalaehina. Kalaepuni ka mua o Kalaehina
Kalaepuni was the elder and ka muli, a o Holualoa i Kona,
Kalaehina was the younger. Hawaii, ka aina; o
They were born and raised in Keawenuiaumi ke ’lii o Hawaii ia
Holualoa, Kona, during the reign wa e noho ana. No Kalaepuni.
of Keawenuiaumi, king of He keiki kolohe loa ia a me ka
Hawaii. Regarding Kalaepuni: he makau ole, eono ona mau
was a very mischievous boy and makahiki, hoomaka oia e pepehi
one who was without fear. At the i kona poe hoa paani; mai laila
age of six he was able to whip all ka pii ana o kona ikaika a hiki i
his playmates and his strength ka iwakalua o kona mau
developed from that time on until makahiki. Lilo ae la o Kalaepuni i
he reached the age of twenty mea kaulana ma Hawaii a puni,
years, at which time Kalaepuni manao iho la ia e pepehi i na
became famous 1 over the whole keiki alii a pau loa o Hawaii, mai
of Hawaii for his great strength. ka mea nunui a ka mea liilii loa,
At twenty he determined to kill all a ka mea e omo ana i ka waiu.
the young chiefs of Hawaii, 2 [201]A o Keawenuiaumi hoi, aole
those who were of very high ona manao e pepehi, no ka mea
blood as well as those of low ua kokoke mai kona wa
blood, both big and small, even elemakule; nolaila, waiho wale
the mere sucklings. In his plan to kona manao ia Keawenuiaumi.
[200]kill all the chiefs he did not Aka, ua komo ka makau o
intend to kill Keawenuiaumi, Keawenuiaumi ia Kalaepuni, a
because, as he reasoned, manao iho la e mahuka mai na
Keawenuiaumi was already well maka aku o Kalaepuni.
on in years. But Keawenuiaumi 3
was afraid of Kalaepuni and he
made his plans to escape and to
get out from the presence of
Kalaepuni.
After they had been fishing for A pau ka lawaia ana, hoi aku la
some time they returned and lakou a pae ka waa ma
landed their canoe at Honaunau Honaunau, e ku ana he kumu
where a large kou tree was kou nui i laila, o ka nui o ua kou
standing. This was a very large la, ekolu kanaka e apo me na
tree requiring three men to span lima, alaila, puni kona kino.
its girth. Kalaepuni, however, Lalau iho la o Kalaepuni i ke
took hold of the tree and pulled it kumu kou a huhuki ae la, ua like
up by the roots 5 as though it was me ka mauu opala ia ia, ka
but a blade of grass, so maunu a uaua ole ke huhuki ae.
resistless was it. After pulling up Alaila, waiho iho la ia i kana
the tree he again boasted, olelo kaena, penei: “E hoolilo
saying: “I am going to turn my ana au i o’u mau lima i ko’i kua
hands into an axe for the cutting waa no Hilo.”
down of trees for canoes in Hilo.”
[Contents]
Legend of Kapakohana. Kaao no Kapakohana.