Programming in Lua 4th Edition Roberto Ierusalimschy download
Programming in Lua 4th Edition Roberto Ierusalimschy download
https://ebookname.com/product/programming-in-lua-4th-edition-
roberto-ierusalimschy/
https://ebookname.com/product/lua-programming-gems-luiz-henrique-
de-figueiredo/
https://ebookname.com/product/programming-in-c-4th-edition-
stephen-g-kochan/
https://ebookname.com/product/programming-python-4th-edition-
mark-lutz/
https://ebookname.com/product/getting-straight-a-s-a-student-s-
guide-to-success-1st-edition-richard-palmer/
Translational Neuroscience Applications in Psychiatry
Neurology and Neurodevelopmental Disorders 1st Edition
Dr James E. Barrett
https://ebookname.com/product/translational-neuroscience-
applications-in-psychiatry-neurology-and-neurodevelopmental-
disorders-1st-edition-dr-james-e-barrett/
https://ebookname.com/product/fighter-s-fact-book-2-street-
fighting-essentials-no-2-1st-edition-loren-w-christensen/
https://ebookname.com/product/the-tensions-between-culture-and-
human-rights-emancipatory-social-work-and-afrocentricity-in-a-
global-world-1st-edition-vishanthie-sewpaul/
https://ebookname.com/product/the-falklands-war-1982-duncan-
anderson/
https://ebookname.com/product/philosophy-rhetoric-and-the-end-of-
knowledge-a-new-beginning-for-science-and-technology-studies-2nd-
edition-steve-fuller/
Truth Light Brief Explanations M. R. Bawa Muhaiyaddeen
https://ebookname.com/product/truth-light-brief-explanations-m-r-
bawa-muhaiyaddeen/
Last update: Sat Mar 18 22:00:08 GMT 2017 (build 21)
Programming in Lua, Fourth Edition
Roberto Ierusalimschy
Programming in Lua, Fourth Edition
Roberto Ierusalimschy
Copyright © 2016, 2003 Roberto Ierusalimschy
iii
Programming in Lua, Fourth Edition
repeat ..................................................................................................... 59
Numerical for ........................................................................................... 60
Generic for .............................................................................................. 60
break, return, and goto ..................................................................................... 61
II. Real Programming ......................................................................................................... 65
9. Closures ............................................................................................................... 68
Functions as First-Class Values ............................................................................ 68
Non-Global Functions ........................................................................................ 69
Lexical Scoping ................................................................................................ 71
A Taste of Functional Programming ..................................................................... 74
10. Pattern Matching .................................................................................................. 77
The Pattern-Matching Functions ........................................................................... 77
The function string.find ...................................................................... 77
The function string.match .................................................................... 77
The function string.gsub ...................................................................... 78
The function string.gmatch .................................................................. 78
Patterns ............................................................................................................ 78
Captures ........................................................................................................... 82
Replacements .................................................................................................... 83
URL encoding .......................................................................................... 84
Tab expansion ........................................................................................... 86
Tricks of the Trade ............................................................................................ 86
11. Interlude: Most Frequent Words ............................................................................. 90
12. Date and Time ..................................................................................................... 92
The Function os.time ..................................................................................... 92
The Function os.date ..................................................................................... 93
Date–Time Manipulation .................................................................................... 95
13. Bits and Bytes ..................................................................................................... 97
Bitwise Operators .............................................................................................. 97
Unsigned Integers .............................................................................................. 97
Packing and Unpacking Binary Data ..................................................................... 99
Binary files ..................................................................................................... 101
14. Data Structures ................................................................................................... 104
Arrays ............................................................................................................ 104
Matrices and Multi-Dimensional Arrays ............................................................... 105
Linked Lists .................................................................................................... 107
Queues and Double-Ended Queues ..................................................................... 107
Reverse Tables ................................................................................................ 108
Sets and Bags ................................................................................................. 109
String Buffers .................................................................................................. 110
Graphs ........................................................................................................... 111
15. Data Files and Serialization .................................................................................. 114
Data Files ....................................................................................................... 114
Serialization .................................................................................................... 116
Saving tables without cycles ...................................................................... 118
Saving tables with cycles .......................................................................... 119
16. Compilation, Execution, and Errors ....................................................................... 122
Compilation .................................................................................................... 122
Precompiled Code ............................................................................................ 125
Errors ............................................................................................................. 126
Error Handling and Exceptions .......................................................................... 127
Error Messages and Tracebacks .......................................................................... 128
17. Modules and Packages ........................................................................................ 131
The Function require .................................................................................... 132
iv
Programming in Lua, Fourth Edition
v
Programming in Lua, Fourth Edition
vi
List of Figures
2.1. The eight-queen program .............................................................................................. 13
7.1. A program to sort a file ............................................................................................... 52
8.1. An example of a state machine with goto ........................................................................ 62
8.2. A maze game ............................................................................................................. 63
8.3. A strange (and invalid) use of a goto .............................................................................. 64
9.1. Union, intersection, and difference of regions ................................................................... 75
9.2. Drawing a region in a PBM file ..................................................................................... 75
11.1. Word-frequency program ............................................................................................ 91
12.1. Directives for function os.date ................................................................................. 94
13.1. Unsigned division ...................................................................................................... 98
13.2. Dumping the dump program ...................................................................................... 102
14.1. Multiplication of sparse matrices ................................................................................ 106
14.2. A double-ended queue .............................................................................................. 108
14.3. Reading a graph from a file ....................................................................................... 112
14.4. Finding a path between two nodes .............................................................................. 112
15.1. Quoting arbitrary literal strings ................................................................................... 117
15.2. Serializing tables without cycles ................................................................................. 118
15.3. Saving tables with cycles .......................................................................................... 120
16.1. Example of output from luac -l .............................................................................. 125
16.2. String repetition ....................................................................................................... 130
17.1. A homemade package.searchpath ...................................................................... 134
17.2. A simple module for complex numbers ........................................................................ 136
17.3. Module with export list ............................................................................................. 137
18.1. Iterator to traverse all words from the standard input ...................................................... 143
19.1. Auxiliary definitions for the Markov program ............................................................... 150
19.2. The Markov program ................................................................................................ 151
20.1. A simple module for sets .......................................................................................... 153
20.2. Tracking table accesses ............................................................................................. 159
21.1. the Account class .................................................................................................. 165
21.2. An implementation of multiple inheritance ................................................................... 167
21.3. Accounts using a dual representation ........................................................................... 171
22.1. The function setfield ........................................................................................... 174
22.2. Checking global-variable declaration ........................................................................... 176
23.1. Constant-function factory with memorization ................................................................ 187
23.2. Running a function at every GC cycle ......................................................................... 190
23.3. Finalizers and memory .............................................................................................. 192
24.1. Producer–consumer with filters ................................................................................... 198
24.2. A function to generate permutations ............................................................................ 199
24.3. An ugly implementation of the asynchronous I/O library ................................................. 201
24.4. Reversing a file in event-driven fashion ....................................................................... 202
24.5. Running synchronous code on top of the asynchronous library ......................................... 203
25.1. Getting the value of a variable ................................................................................... 208
25.2. Hook for counting number of calls .............................................................................. 211
25.3. Getting the name of a function ................................................................................... 212
25.4. A naive sandbox with hooks ...................................................................................... 213
25.5. Controlling memory use ............................................................................................ 214
25.6. Using hooks to bar calls to unauthorized functions ......................................................... 215
26.1. Function to download a Web page .............................................................................. 218
26.2. The dispatcher ......................................................................................................... 219
26.3. Dispatcher using select ......................................................................................... 220
27.1. A bare-bones stand-alone Lua interpreter ..................................................................... 224
vii
Programming in Lua, Fourth Edition
viii
About the Book
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 con-
ventional 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 de-
cide 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 compo-
nents. 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:
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 external languages like C/C++, Java,
C#, and Python.
Simplicity: Lua is a simple and small language. It has few (but powerful) concepts. This sim-
plicity makes Lua easy to learn and contributes to its small size. (Its Linux 64-bit
executable, including all standard libraries, has 220 KB.)
Efficiency: Lua has a quite efficient implementation. Independent benchmarks show Lua as
one of the fastest languages in the realm of scripting languages.
Portability: 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
ix
About the Book
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.
Audience
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 parame-
ters, 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.
Book Structure
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.
x
About the Book
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 dif-
ferent 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.
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, 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 docu-
mentation, 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 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.
xi
About the Book
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
Finally, the book uses the notation <--> to indicate that something is equivalent to something else:
The Lua site (http://www.lua.org) keeps the source code for the interpreter. If you have a C com-
piler 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 precom-
piled 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.)
Acknowledgments
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 sug-
gestions 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.
xii
About the Book
Finally, I must express my deep gratitude to Noemi Rodriguez, for all kinds of help (technical and non-
technical) and for illumining my life.
xiii
Part I. The Basics
Table of Contents
1. Getting Started ................................................................................................................ 4
Chunks ...................................................................................................................... 4
Some Lexical Conventions ........................................................................................... 6
Global Variables ......................................................................................................... 7
Types and Values ........................................................................................................ 7
Nil .................................................................................................................... 8
Booleans ............................................................................................................ 8
The Stand-Alone Interpreter .......................................................................................... 9
2. Interlude: The Eight-Queen Puzzle .................................................................................... 12
3. Numbers ....................................................................................................................... 15
Numerals .................................................................................................................. 15
Arithmetic Operators .................................................................................................. 16
Relational Operators .................................................................................................. 17
The Mathematical Library ........................................................................................... 18
Random-number generator .................................................................................. 18
Rounding functions ............................................................................................ 18
Representation Limits ................................................................................................. 19
Conversions .............................................................................................................. 21
Precedence ............................................................................................................... 22
Lua Before Integers ................................................................................................... 22
4. Strings ......................................................................................................................... 24
Literal strings ............................................................................................................ 24
Long strings ............................................................................................................. 25
Coercions ................................................................................................................. 26
The String Library ..................................................................................................... 27
Unicode ................................................................................................................... 29
5. Tables .......................................................................................................................... 33
Table Indices ............................................................................................................ 33
Table Constructors ..................................................................................................... 35
Arrays, Lists, and Sequences ....................................................................................... 36
Table Traversal ......................................................................................................... 38
Safe Navigation ......................................................................................................... 38
The Table Library ..................................................................................................... 39
6. Functions ...................................................................................................................... 42
Multiple Results ........................................................................................................ 43
Variadic Functions ..................................................................................................... 45
The function table.unpack .................................................................................... 47
Proper Tail Calls ....................................................................................................... 48
7. The External World ........................................................................................................ 50
The Simple I/O Model ............................................................................................... 50
The Complete I/O Model ............................................................................................ 53
Other Operations on Files ........................................................................................... 54
Other System Calls .................................................................................................... 55
Running system commands ................................................................................. 55
8. Filling some Gaps .......................................................................................................... 57
Local Variables and Blocks ......................................................................................... 57
Control Structures ...................................................................................................... 58
if then else ....................................................................................................... 58
while ............................................................................................................... 59
repeat ............................................................................................................. 59
Numerical for ................................................................................................... 60
2
The Basics
3
Chapter 1. Getting Started
To keep with 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.3— 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:
print("enter a number:")
a = io.read("*n") -- reads a number
print(fact(a))
Chunks
We call each piece of code that Lua executes, such as a file or a single line in interactive mode, a chunk.
A chunk is simply a sequence of commands (or statements).
A chunk can be as simple as a single statement, such as in the “Hello World” example, or it can be composed
of a mix of statements and function definitions (which are actually assignments, as we will see later), such
as the factorial example. A chunk can be as large as we wish. Because Lua is used also as a data-description
language, chunks with several megabytes are not uncommon. The Lua interpreter has no problems at all
with large chunks.
Instead of writing your program to a file, you can run the stand-alone interpreter in interactive mode. If
you call lua without any arguments, you will get its prompt:
% lua
Lua 5.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
>
Thereafter, each command that you type (such as print "Hello World") executes immediately after
you enter it. To exit the interactive mode and the interpreter, just type the end-of-file control character
(ctrl-D in POSIX, ctrl-Z in Windows), or call the function os.exit, from the Operating System
library —you have to type os.exit().
Starting in version 5.3, we can enter expressions directly in the interactive mode, and Lua will print their
values:
4
Getting Started
% lua
Lua 5.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> math.pi / 4 --> 0.78539816339745
> a = 15
> a^2 --> 225
> a + 2 --> 17
% lua5.2
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> a = 15
> = a^2 --> 225
To run that code as a chunk (not in interactive mode), we must enclose the expressions inside calls to
print:
print(math.pi / 4)
a = 15
print(a^2)
print(a + 2)
Lua usually interprets each line that we type in interactive mode as a complete chunk or expression. How-
ever, if it detects that the line is not complete, it waits for more input, until it has a complete chunk. This
way, we can enter a multi-line definition, such as the factorial function, directly in interactive mode. How-
ever, it is usually more convenient to put such definitions in a file and then call Lua to run the file.
We can use the -i option to instruct Lua to start an interactive session after running a given chunk:
% lua -i prog
A command line like this one will run the chunk in the file prog and then prompt 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 function dofile, which immediately executes a file. For instance,
suppose we have a file lib1.lua with the following code:
The function dofile is useful also when we are testing a piece of code. We can work with two windows:
one is a text editor with our program (in a file prog.lua, say) and the other is a console running Lua
5
Getting Started
i j i10 _ij
aSomewhatLongName _INPUT
You should avoid identifiers starting with an underscore followed by one or more upper-case letters (e.g.,
_VERSION); they are reserved for special uses in Lua. Usually, I reserve the identifier _ (a single under-
score) for dummy variables.
Lua is case-sensitive: and is a reserved word, but And and AND are two different identifiers.
A comment starts anywhere with two consecutive hyphens (--) and runs until the end of the line. Lua
also offers long comments, which start with two hyphens followed by two opening square brackets and
run until the first occurrence of two consecutive closing square brackets, like here:1
--[[A multi-line
long comment
]]
A common trick that we use to comment out a piece of code is to enclose the code between --[[ and
--]], like here:
--[[
print(10) -- no action (commented out)
--]]
---[[
print(10) --> 10
--]]
In the first example, the --[[ in the first line starts a long comment, and the two hyphens in the last line
are 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.
Lua needs no separator between consecutive statements, but we can use a semicolon if we wish. Line
breaks play no role in Lua's syntax; for instance, the following four chunks are all valid and equivalent:
1
Long comments can be more complex than that, as we will see in the section called “Long strings”.
6
Getting Started
a = 1
b = a * 2
a = 1;
b = a * 2;
a = 1; b = a * 2
My personal convention is to use semicolons only when I write two or more statements in the same line
(which I hardly do).
Global Variables
Global variables do not need declarations; we simply use them. It is not an error to access a non-initialized
variable; we just get the value nil as the result:
If we assign nil to a global variable, Lua behaves as if we have never used the variable:
> b = nil
> b --> nil
Lua does not differentiate a non-initialized variable from one that we assigned nil. After the assignment,
Lua can eventually reclaim the memory used by the variable.
There are eight basic types in Lua: nil, Boolean, number, string, userdata, function, thread, and table. The
function type gives the type name of any given value:
The last line will result in "string" no matter the value of X, because the result of type is always
a string.
The userdata type allows arbitrary C data to be stored in Lua variables. It has no predefined operations in
Lua, except assignment and equality test. Userdata are used to represent new types created by an application
program or a library written in C; for instance, the standard I/O library uses them to represent open files.
We will discuss more about userdata later, when we get to the C API.
7
Getting Started
Variables have no predefined types; any variable can contain values of any type:
Usually, when we 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.
We will discuss now the simple types nil and Boolean. In the following chapters, we will discuss in detail
the types number (Chapter 3, Numbers), string (Chapter 4, Strings), table (Chapter 5, Tables), and function
(Chapter 6, Functions). We will explain the thread type in Chapter 24, Coroutines, where we discuss
coroutines.
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 we can assign nil to a global variable to delete it.
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 con-
dition. 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 write “false” to mean any false value, that is, the Boolean false or nil. When
I mean specifically the Boolean value, I will write “false”. The same holds for “true” and “true”.
Lua supports a conventional set of logical operators: and, or, and not. Like control structures, all logical
operators consider both the Boolean false and nil as false, and anything else as true. The result of the and
operator is its first operand if that operand is false; otherwise, the result is its second operand. The result
of the or operator is its first operand if it is not false; otherwise, the result is its second operand:
Both and and or use short-circuit evaluation, that is, they evaluate their second operand only when nec-
essary. Short-circuit evaluation ensures that expressions like (i ~= 0 and a/i > b) do not cause
run-time errors: Lua will not try to evaluate a / i when i is zero.
8
Getting Started
That is, it sets x to a default value v when x is not set (provided that x is not set to false).
Another useful idiom is ((a and b) or c) or simply (a and b or c) (given that and has a
higher precedence than or). It is equivalent to the C expression a ? b : c, provided that b is not false.
For instance, we can select the maximum of two numbers x and y with the expression (x > y) and x
or y. When x > y, the first expression of the and is true, so the and results in its second operand (x),
which is always true (because it is a number), and then the or expression results in the value of its first
operand, x. When x > y is false, the and expression is false and so the or results in its second operand, y.
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 POSIX systems. If we start our script with something like
#!/usr/local/bin/lua
#!/usr/bin/env lua
then we can call the script directly, without explicitly calling the Lua interpreter.
Everything is optional. As we have seen already, when we call lua without arguments the interpreter
enters the interactive mode.
The -e option allows us to enter code directly into the command line, like here:
(POSIX systems need the double quotes to stop the shell from interpreting the parentheses.)
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.
9
Getting Started
(Remember, this feature came with Lua 5.3. In older versions, we must precede the expressions with equals
signs.) To avoid this print, we can finish the line with a semicolon:
The semicolon makes the line syntactically invalid as an expression, but still valid as a command.
Before running its arguments, the interpreter looks for an environment variable named LUA_INIT_5_3
or else, if there is no such variable, LUA_INIT. If there is one of these variables and its content is @file-
name, then the interpreter runs the given file. If LUA_INIT_5_3 (or LUA_INIT) is defined but it does
not start with an at-sign, 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 through the predefined global variable arg. In a call like % lua
script a b c, the interpreter creates the table arg with all the command-line arguments, before
running any code. 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:
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).
A script can also retrieve its arguments through a vararg expression. In the main body of a script, the
expression ... (three dots) results in the arguments to the script. (We will discuss vararg expressions in
the section called “Variadic Functions”.)
Exercises
Exercise 1.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?
Exercise 1.3: Can you name other languages that use "--" for comments?
Exercise 1.5: What is the value of the expression type(nil) == nil? (You can use Lua to check
your answer.) Can you explain this result?
10
Getting Started
Exercise 1.6: How can you check whether a value is a Boolean without using the function type?
Are the parentheses necessary? Would you recommend their use in that expression?
Exercise 1.8: Write a simple script that prints its own name without knowing it in advance.
11
Random documents with unrelated
content Scribd suggests to you:
dark and nearly lost many of my trek oxen, in their
eagerness to get at the water, which is twenty feet from the
surface. They were supplied by sending my boys down with
buckets, by that means filling a hole dug out for the oxen to
drink.
At Swaat Modder the right side of the river has cliffs 100
feet in height; the left bank has sand-dunes, where I found
several flint borers, many of them in a finished state, for
making holes in the shell of the ostrich egg to form beads.
Under these cliffs, in an old Bushman cave, I built a stone
house, where we remained six weeks waiting for the rains.
All this country is under the Koranna chief Puffadder, and
his people are spread over the country in small kraals. The
road still continues north, past other pits in limestone at
Bloomfontein, and at Kebeum, springbok, etc.; Abequas
pits, a large Koranna kraal; then passes over sand-dunes
for thirty miles, and arrives at Anoerogas, where there is
another Kaffir station, also a store kept by a Mr Redman, of
whom I bought some tobacco for five bags of gunpowder,
and a medicine-chest, and a variety of goods I was much in
want of. A captain of the Bundelswaarts is here, to give
notice to the Bastards to clear out. Coal abounds in this
part, garnets are found in all the river-beds, and in many
parts mixed up in the sand of the desert. Lions are so
plentiful here that it is dangerous to leave the waggon
without your rifle. A Koranna man was killed and eaten last
night, a short distance from the waggon. This station is 180
miles north from Kakaman’s drift, on the Orange river, and
three miles south of Hogskin vlei; here the roads divide.
One goes to the salt-pan, another to Meer station, a third to
Quassam on to Damaraland, a fourth past Knaas, in a
north-north-west direction to Ovampoland, and a fifth turns
south-west, and leads to Barth, where the Bundelswaarts
people live, besides others to different parts of the desert.
These hills were the home of the wild Bushmen, who war on
all living things. They differ from other Bushmen; they are
of a reddish-black colour, and stand four feet four inches in
height. They live in the caves amongst most inaccessible
parts of these mountains. They use the bow and arrow. Few
are now left, as far as we know, for they never show
themselves, and keep as much away from mankind as the
beast of the forest.
Not far from them are several ancient stone huts, built upon
a small hill, that must have belonged to a former race, and
close to a dried-up river. Some of the stones are six feet in
length, two feet wide, and one and a half thick. They were
placed on end and covered in. None of them would hold
more than four persons. They are in small clusters of seven
and eight together, and some less. They were covered in
with large stones, that have long since fallen. No account
can be obtained of them from the Bushmen. Their huts are
a few sticks stuck up with grass thrown over.
Several fresh Bushmen and women came to my camp this
morning. Some of the young girls were very good-looking,
and with a profusion of native ornaments upon them made
entirely of ostrich eggs. A perfect set comprised a tiara,
three inches in width, for the head; a broad necklace, six
bracelets on each arm, and eight anklets or bangles to each
leg, and finally, a rope of beads of sufficient length to go
round the loins twice and fastened in front with a piece of
rimpey. These constituted the entire dress of one of the
girls. She looked like a young African queen, and it had the
effect of making her look half pretty.
I bought two sets for six yards of print each. I think there
cannot be less than 8000 beads in each set, between each
bead a piece of leather of the same size, which becomes
black, so that they look like black and white beads, which
has a good effect upon their black skin. They were delighted
with the exchange. When disrobed of their ornaments, they
threw the print over their shoulders like a mantle. The
ornament had the appearance of having been handed down
from generation to generation. At Narukus, on the Nosop
river, I came upon a family of Bushmen, ten in number, of a
different type to those I had in my service, evidently a
lower caste. They have no forehead; the wool on their
heads comes close down to the eyes, and the head falling
back like a baboon; projecting mouth, small nose, a sort of
hair or wool all over the chest, arms, and legs; their eyes
are small and restless, watching every movement that is
going on; the tallest man did not exceed four feet four;
their skin was of a reddish-brown. A few old skins, broken
ostrich eggs, and bows and arrows, seemed all they
possessed of worldly goods.
They would have decamped and hid in the bush, but I sent
some of my Bushmen and brought them back. I asked my
own boys, if they were their brothers, meaning of the same
race; they repudiated the idea, and said they were monkeys
not men, and told me there were very few ever seen, it was
very seldom they ever came upon any; they eat carrion.
They are evidently a distinct race from the Masara Bushmen
who are largely distributed over the desert. One of the
women had a baby not much bigger than a half-grown
kitten; all of them were destitute of clothing.
After all the people were asleep, he stole the food they had
left, and in the middle of the night, sucked three of my
goats dry. The following morning he was not to be found,
and for nearly a month we did not see him again; when we
had travelled 100 miles north, and were outspanned, he
presented himself again, as if it were his first visit. We
found out he had lived in the bush, existing on a wild water-
melon, called shama or kongive, and had kept us in sight as
we travelled. I tried to tame him, but it was of no use; his
age was about eleven years. He kept with us off and on for
three months, then disappeared altogether; the lions would
not let him remain long, without making a meal of him.
Pringle.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com