100% found this document useful (2 votes)
44 views55 pages

[FREE PDF sample] Programming in Lua 4th Edition Roberto Ierusalimschy ebooks

Ierusalimschy

Uploaded by

joploeless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
44 views55 pages

[FREE PDF sample] Programming in Lua 4th Edition Roberto Ierusalimschy ebooks

Ierusalimschy

Uploaded by

joploeless
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Programming in Lua 4th Edition Roberto


Ierusalimschy

https://textbookfull.com/product/programming-in-lua-4th-
edition-roberto-ierusalimschy/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Lua Programming The Ultimate Beginner s Guide to Learn Lua


Step by Step 3rd Edition Claudia Alves

https://textbookfull.com/product/lua-programming-the-ultimate-
beginner-s-guide-to-learn-lua-step-by-step-3rd-edition-claudia-alves/

textboxfull.com

Advanced Apex Programming in Salesforce 4th Edition Dan


Appleman

https://textbookfull.com/product/advanced-apex-programming-in-
salesforce-4th-edition-dan-appleman/

textboxfull.com

Programming PHP 4th Edition Peter Macintyre

https://textbookfull.com/product/programming-php-4th-edition-peter-
macintyre/

textboxfull.com

Programming WCF Services 4th Edition Juval Löwy

https://textbookfull.com/product/programming-wcf-services-4th-edition-
juval-lowy/

textboxfull.com
Scripting Farming Simulator with Lua: Unlocking the
Virtual Fields: A Comprehensive Guide to Farming Simulator
Scripting with Lua 1st Edition Zander Brumbaugh
https://textbookfull.com/product/scripting-farming-simulator-with-lua-
unlocking-the-virtual-fields-a-comprehensive-guide-to-farming-
simulator-scripting-with-lua-1st-edition-zander-brumbaugh/
textboxfull.com

Fear and Uncertainty in Europe Roberto Belloni

https://textbookfull.com/product/fear-and-uncertainty-in-europe-
roberto-belloni/

textboxfull.com

Computer Programming and Utilization, 4e 4th Edition E.


Balagurusamy

https://textbookfull.com/product/computer-programming-and-
utilization-4e-4th-edition-e-balagurusamy/

textboxfull.com

Programmable Logic Controllers Hardware and Programming


4th Edition Max Rabiee

https://textbookfull.com/product/programmable-logic-controllers-
hardware-and-programming-4th-edition-max-rabiee/

textboxfull.com

Clinical Interventions in Systemic Couple and Family


Therapy Roberto Pereira

https://textbookfull.com/product/clinical-interventions-in-systemic-
couple-and-family-therapy-roberto-pereira/

textboxfull.com
Programming in Lua, Fourth Edition
Roberto Ierusalimschy
Copyright © 2016, 2003 Roberto Ierusalimschy

Feisty Duck Digital


Book Distribution
www.feistyduck.com

Licensed for the exclusive use of:


Eric Taylor <[email protected]>
Contents
About the Book ................................................................................................................. ix
I. The Basics ...................................................................................................................... 1
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
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
Renaming a module ................................................................................. 133
Path searching ......................................................................................... 133
Searchers ................................................................................................ 135
The Basic Approach for Writing Modules in Lua .................................................. 135
Submodules and Packages ................................................................................. 137
III. Lua-isms ................................................................................................................... 139
18. Iterators and the Generic for ................................................................................ 142
Iterators and Closures ....................................................................................... 142
The Semantics of the Generic for ....................................................................... 143
Stateless Iterators ............................................................................................. 145
Traversing Tables in Order ................................................................................ 146
True Iterators .................................................................................................. 147
19. Interlude: Markov Chain Algorithm ....................................................................... 149
20. Metatables and Metamethods ................................................................................ 152
Arithmetic Metamethods ................................................................................... 152
Relational Metamethods .................................................................................... 155
Library-Defined Metamethods ............................................................................ 155
Table-Access Metamethods ............................................................................... 156
The __index metamethod ....................................................................... 156
The __newindex metamethod ................................................................. 157
Tables with default values ......................................................................... 158
Tracking table accesses ............................................................................. 159
Read-only tables ...................................................................................... 160
21. Object-Oriented Programming .............................................................................. 162
Classes ........................................................................................................... 163
Inheritance ...................................................................................................... 165
Multiple Inheritance ......................................................................................... 166
Privacy ........................................................................................................... 168
The Single-Method Approach ............................................................................ 170
Dual Representation ......................................................................................... 170
22. The Environment ................................................................................................ 173
Global Variables with Dynamic Names ............................................................... 173
Global-Variable Declarations ............................................................................. 174
Non-Global Environments ................................................................................. 176
Using _ENV .................................................................................................... 177
Environments and Modules ............................................................................... 180
_ENV and load .............................................................................................. 181
23. Garbage ............................................................................................................ 183
Weak Tables ................................................................................................... 183
Memorize Functions ......................................................................................... 184
Object Attributes ............................................................................................. 185
Revisiting Tables with Default Values ................................................................. 186
Ephemeron Tables ........................................................................................... 187
Finalizers ........................................................................................................ 188
The Garbage Collector ...................................................................................... 190
Controlling the Pace of Collection ...................................................................... 191
24. Coroutines ......................................................................................................... 194
Coroutine Basics .............................................................................................. 194
Who Is the Boss? ............................................................................................ 196
Coroutines as Iterators ...................................................................................... 198
Event-Driven Programming ............................................................................... 200
25. Reflection .......................................................................................................... 205
Introspective Facilities ...................................................................................... 205
Accessing local variables .......................................................................... 207
Accessing non-local variables .................................................................... 208
Accessing other coroutines ........................................................................ 209
Hooks ............................................................................................................ 210
Profiles .......................................................................................................... 211
Sandboxing ..................................................................................................... 212
26. Interlude: Multithreading with Coroutines ............................................................... 217
IV. The C API ................................................................................................................ 221
27. An Overview of the C API .................................................................................. 223
A First Example .............................................................................................. 223
The Stack ....................................................................................................... 225
Pushing elements ..................................................................................... 226
Querying elements ................................................................................... 227
Other stack operations .............................................................................. 229
Error Handling with the C API .......................................................................... 231
Error handling in application code .............................................................. 232
Error handling in library code .................................................................... 232
Memory Allocation .......................................................................................... 233
28. Extending Your Application ................................................................................. 236
The Basics ...................................................................................................... 236
Table Manipulation .......................................................................................... 237
Some short cuts ....................................................................................... 240
Calling Lua Functions ...................................................................................... 241
A Generic Call Function ................................................................................... 242
29. Calling C from Lua ............................................................................................ 247
C Functions .................................................................................................... 247
Continuations .................................................................................................. 249
C Modules ...................................................................................................... 251
30. Techniques for Writing C Functions ...................................................................... 254
Array Manipulation .......................................................................................... 254
String Manipulation .......................................................................................... 255
Storing State in C Functions .............................................................................. 258
The registry ............................................................................................ 258
Upvalues ................................................................................................ 260
Shared upvalues ....................................................................................... 263
31. User-Defined Types in C ..................................................................................... 265
Userdata ......................................................................................................... 265
Metatables ...................................................................................................... 268
Object-Oriented Access ..................................................................................... 270
Array Access .................................................................................................. 271
Light Userdata ................................................................................................. 272
32. Managing Resources ........................................................................................... 274
A Directory Iterator .......................................................................................... 274
An XML Parser ............................................................................................... 277
33. Threads and States .............................................................................................. 286
Multiple Threads ............................................................................................. 286
Lua States ...................................................................................................... 289
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
27.2. Dumping the stack ................................................................................................... 229
27.3. Example of stack manipulation ................................................................................... 231
28.1. Getting user information from a configuration file ......................................................... 236
28.2. A particular getcolorfield implementation ............................................................ 238
28.3. Colors as strings or tables ......................................................................................... 240
28.4. Calling a Lua function from C ................................................................................... 242
28.5. A generic call function .............................................................................................. 243
28.6. Pushing arguments for the generic call function ............................................................. 244
28.7. Retrieving results for the generic call function ............................................................... 245
29.1. A function to read a directory .................................................................................... 249
29.2. Implementation of pcall with continuations ............................................................... 251
30.1. The function map in C ............................................................................................. 255
30.2. Splitting a string ...................................................................................................... 256
30.3. The function string.upper ................................................................................... 257
30.4. A simplified implementation for table.concat ........................................................ 258
30.5. An implementation of tuples ...................................................................................... 262
31.1. Manipulating a Boolean array .................................................................................... 266
31.2. Extra code for the Boolean array library ...................................................................... 267
31.3. New versions for setarray/getarray .................................................................... 269
31.4. New initialization code for the Bit Array library ............................................................ 272
32.1. The dir.open factory function ................................................................................ 275
32.2. Other functions for the dir library ............................................................................. 276
32.3. Function to create XML parser objects ........................................................................ 280
32.4. Function to parse an XML fragment ............................................................................ 281
32.5. Handler for character data ......................................................................................... 282
32.6. Handler for end elements .......................................................................................... 282
32.7. Handler for start elements ......................................................................................... 283
32.8. Method to close an XML parser ................................................................................. 283
32.9. Initialization code for the lxp library .......................................................................... 284
33.1. Function to search for a process waiting for a channel .................................................... 291
33.2. Function to add a process to a waiting list .................................................................... 291
33.3. Functions to send and receive messages ....................................................................... 292
33.4. Function to create new processes ................................................................................ 293
33.5. Body for new threads ............................................................................................... 294
33.6. Extra functions for the lproc module ........................................................................ 295
33.7. Registering libraries to be opened on demand ............................................................... 296
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
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.
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.

A Few Typographical Conventions


The book encloses "literal strings" between double quotes and single characters, such as a,
between single quotes. Strings that are used as patterns are also enclosed between single quotes, like
'[%w_]*'. The book uses a typewriter font both for chunks of code and for identifiers. For reserved
words, it uses a boldface font. Larger chunks of code are shown in display style:

-- program "Hello World"


print("Hello World") --> Hello World

The notation --> shows the output of a statement or the result of an expression:

print(10) --> 10
13 + 3 --> 16

Because a double hyphen (--) starts a comment in Lua, there is no problem if you include these annotations
in your code.
Several code fragments in the book, mainly in the initial chapters, should be entered in interactive mode.
In that case, I use a notation showing the Lua prompt ("> ") in each line:

> 3 + 5 --> 8
> math.sin(2.3) --> 0.74570521217672

In Lua 5.2 and older versions, to print the result of an expression in interactive mode, you must precede
the expression with an equals sign:

> = 3 + 5 --> 8
> a = 25
> = a --> 25

For compatibility, Lua 5.3 still accepts this equal sign.

Finally, the book uses the notation <--> to indicate that something is equivalent to something else:

this <--> that

Running the Examples


You will need a Lua interpreter to run the examples in this book. Ideally, you should use Lua 5.3, but most
of the examples run on older versions without modifications.

The Lua site (http://www.lua.org) keeps the source code for the interpreter. If you have a C 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.
Finally, I must express my deep gratitude to Noemi Rodriguez, for all kinds of help (technical and non-
technical) and for illumining my life.
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

Generic for ...................................................................................................... 60


break, return, and goto ............................................................................................. 61

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:

-- 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))

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

In older versions, we need to precede these expressions with an equals sign:

% lua5.2
Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
> a = 15
> = a^2 --> 225

For compatibility, Lua 5.3 still accepts these equals signs.

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:

function norm (x, y)


return math.sqrt(x^2 + y^2)
end

function twice (x)


return 2.0 * x
end

Then, in interactive mode, we can type this code:

> dofile("lib1.lua") -- load our library


> n = norm(3.4, 1.0)
> twice(n) --> 7.0880180586677

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

in interactive mode. After saving a modification in our program, we execute dofile("prog.lua")


in the Lua console to load the new code; then we can exercise the new code, calling its functions and
printing the results.

Some Lexical Conventions


Identifiers (or names) in Lua can be any string of letters, digits, and underscores, not beginning with a
digit; for instance

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.

The following words are reserved; we cannot use them as identifiers:

and break do else elseif


end false for function goto
if in local nil not
or repeat return then true
until while

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)
--]]

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 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

a = 1 b = a * 2 -- ugly, but valid

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:

> b --> nil


> b = 10
> b --> 10

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.

Types and Values


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
function type gives the type name of any given value:

> type(nil) --> nil


> type(true) --> boolean
> type(10.4 * 3) --> number
> type("Hello world") --> string
> type(io.stdin) --> userdata
> type(print) --> function
> type(type) --> function
> type({}) --> table
> 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.

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:

> type(a) --> nil ('a' is not initialized)


> a = 10
> type(a) --> number
> a = "a string!!"
> type(a) --> string
> a = nil
> type(a) --> nil

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:

> 4 and 5 --> 5


> nil and 13 --> nil
> false and 13 --> false
> 0 or 5 --> 0
> false or "hi" --> "hi"
> nil or false --> false

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.

A useful Lua idiom is x = x or v, which is equivalent to

if not x then x = v end

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.

The not operator always gives a Boolean value:

> not nil --> true


> not false --> true
> not 0 --> false
> not not 1 --> true
> not not nil --> false

The Stand-Alone Interpreter


The stand-alone interpreter (also called lua.c due to its source file or simply lua due to its executable)
is a small program that allows the direct use of Lua. This section presents its main options.

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

(assuming that the stand-alone interpreter is located at /usr/local/bin), or

#!/usr/bin/env lua

then we can call the script directly, without explicitly calling the Lua interpreter.

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 the 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

(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.

% lua -i -llib -e "x = 10"

If we write an expression in interactive mode, Lua prints its value:

> math.sin(3) --> 0.14112000805987


> a = 30
> a --> 30

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:

> io.flush() --> true


> io.flush();

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:

% 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).

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.4: Which of the following strings are valid identifiers?

___ _end End end until? nil NULL one-step

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?

Exercise 1.7: 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 expression?

Exercise 1.8: Write a simple script that prints its own name without knowing it in advance.

11
Chapter 2. Interlude: The Eight-Queen
Puzzle
In this chapter we make a short interlude to present a simple but complete program in Lua that solves the
eight-queen puzzle: its goal is to position eight queens in a chessboard in such a way that no queen can
attack another one.

The code here does not use anything specific to Lua; we should be able to translate the code to several
other languages with only cosmetic changes. The idea is to present the general flavor of Lua, in particular
how the Lua syntax looks like, without going into details. We will cover all missing details in subsequent
chapters.

A first step to solving the eight-queen puzzle is to note that any valid solution must have exactly one queen
in each row. Therefore, we can represent potential solutions with a simple array of eight numbers, one for
each row; each number tells at which column is the queen at that row. For instance, the array {3, 7, 2,
1, 8, 6, 5, 4} means that the queens are in the squares (1,3), (2,7), (3,2), (4,1), (5,8), (6,6), (7,5),
and (8,4). (By the way, this is not a valid solution; for instance, the queen in square (3,2) can attack the
one in square (4,1).) Note that any valid solution must be a permutation of the integers 1 to 8, as a valid
solution also must have exactly one queen in each column.

The complete program is in Figure 2.1, “The eight-queen program”.

12
Interlude: The Eight-Queen Puzzle

Figure 2.1. The eight-queen program


N = 8 -- board size

-- check whether position (n,c) is free from attacks


function isplaceok (a, n, c)
for i = 1, n - 1 do -- for each queen already placed
if (a[i] == c) or -- same column?
(a[i] - i == c - n) or -- same diagonal?
(a[i] + i == c + n) then -- same diagonal?
return false -- place can be attacked
end
end
return true -- no attacks; place is OK
end

-- print a board
function printsolution (a)
for i = 1, N do -- for each row
for j = 1, N do -- and for each column
-- write "X" or "-" plus a space
io.write(a[i] == j and "X" or "-", " ")
end
io.write("\n")
end
io.write("\n")
end

-- add to board 'a' all queens from 'n' to 'N'


function addqueen (a, n)
if n > N then -- all queens have been placed?
printsolution(a)
else -- try to place n-th queen
for c = 1, N do
if isplaceok(a, n, c) then
a[n] = c -- place n-th queen at column 'c'
addqueen(a, n + 1)
end
end
end
end

-- run the program


addqueen({}, 1)

The first function is isplaceok, which checks whether a given position on a board is free from attacks
from previously placed queens. More specifically, it checks whether putting the n-th queen in column c
will conflict with any of the previous n-1 queens already set in the array a. Remember that, by represen-
tation, two queens cannot be in the same row, so isplaceok checks whether there are no queens in the
same column or in the same diagonals of the new position.

Next we have the function printsolution, which prints a board. It simply traverses the entire board,
printing an X at positions with a queen and a - at other positions, without any fancy graphics. (Note its
use of the and–or idiom to select the character to print at each position.) Each result will look like this:

13
Interlude: The Eight-Queen Puzzle

X - - - - - - -
- - - - X - - -
- - - - - - - X
- - - - - X - -
- - X - - - - -
- - - - - - X -
- X - - - - - -
- - - X - - - -

The last function, addqueen, is the core of the program. It tries to place all queens larger than or equal
to n in the board. It uses backtracking to search for valid solutions. First, it checks whether the solution
is complete and, if so, prints that solution. Otherwise, it loops through all columns for the n-th queen; for
each column that is free from attacks, the program places the queen there and recursively tries to place
the following queens.

Finally, the main body simply calls addqueen on an empty solution.

Exercises
Exercise 2.1: Modify the eight-queen program so that it stops after printing the first solution.

Exercise 2.2: An alternative implementation for the eight-queen problem would be to generate all possible
permutations of 1 to 8 and, for each permutation, to check whether it is valid. Change the program to use
this approach. How does the performance of the new program compare with the old one? (Hint: compare
the total number of permutations with the number of times that the original program calls the function
isplaceok.)

14
Chapter 3. Numbers
Until version 5.2, Lua represented all numbers using double-precision floating-point format. Starting with
version 5.3, Lua uses two alternative representations for numbers: 64-bit integer numbers, called simply
integers, and double-precision floating-point numbers, called simply floats. (Note that, in this book, the
term “float” does not imply single precision.) For restricted platforms, we can compile Lua 5.3 as Small
Lua, which uses 32-bit integers and single-precision floats.1

The introduction of integers is the hallmark of Lua 5.3, its main difference against previous versions of Lua.
Nevertheless, this change created few incompatibilities, because double-precision floating-point numbers
can represent integers exactly up to 253. Most of the material we will present here is valid for Lua 5.2 and
older versions, too. In the end of this chapter I will discuss in more detail the incompatibilities.

Numerals
We can write numeric constants with an optional decimal part plus an optional decimal exponent, like
these examples:

> 4 --> 4
> 0.4 --> 0.4
> 4.57e-3 --> 0.00457
> 0.3e12 --> 300000000000.0
> 5E+20 --> 5e+20

Numerals with a decimal point or an exponent are considered floats; otherwise, they are treated as integers.

Both integer and float values have type "number":

> type(3) --> number


> type(3.5) --> number
> type(3.0) --> number

They have the same type because, more often than not, they are interchangeable. Moreover, integers and
floats with the same value compare as equal in Lua:

> 1 == 1.0 --> true


> -3 == -3.0 --> true
> 0.2e3 == 200 --> true

In the rare occasions when we need to distinguish between floats and integers, we can use math.type:

> math.type(3) --> integer


> math.type(3.0) --> float

Moreover, Lua 5.3 shows them differently:

> 3 --> 3
> 3.0 --> 3.0
> 1000 --> 1000
> 1e3 --> 1000.0

Like many other programming languages, Lua supports hexadecimal constants, by prefixing them with
0x. Unlike many other programming languages, Lua supports also floating-point hexadecimal constants,
1
We create Small Lua from the same source files of Standard Lua, compiling them with the macro LUA_32BITS defined. Except for the sizes for
number representations, Small Lua is identical to Standard Lua.

15
Numbers

which can have a fractional part and a binary exponent, prefixed by p or P.2 The following examples
illustrate this format:

> 0xff --> 255


> 0x1A3 --> 419
> 0x0.2 --> 0.125
> 0x1p-1 --> 0.5
> 0xa.bp2 --> 42.75

Lua can write numbers in this format using string.format with the %a option:

> string.format("%a", 419) --> 0x1.a3p+8


> string.format("%a", 0.1) --> 0x1.999999999999ap-4

Although not very friendly to humans, this format preserves the full precision of any float value, and the
conversion is faster than with decimals.

Arithmetic Operators
Lua presents the usual set of arithmetic operators: addition, subtraction, multiplication, division, and nega-
tion (unary minus). It also supports floor division, modulo, and exponentiation.

One of the main guidelines for the introduction of integers in Lua 5.3 was that “the programmer may
choose to mostly ignore the difference between integers and floats or to assume complete control over the
representation of each number.”3 Therefore, any arithmetic operator should give the same result when
working on integers and when working on reals.

The addition of two integers is always an integer. The same is true for subtraction, multiplication, and
negation. For those operations, it does not matter whether the operands are integers or floats with integral
values (except in case of overflows, which we will discuss in the section called “Representation Limits”);
the result is the same in both cases:

> 13 + 15 --> 28
> 13.0 + 15.0 --> 28.0

If both operands are integers, the operation gives an integer result; otherwise, the operation results in a
float. In case of mixed operands, Lua converts the integer one to a float before the operation:

> 13.0 + 25 --> 38.0


> -(3 * 6.0) --> -18.0

Division does not follow that rule, because the division of two integers does not need to be an integer.
(In mathematical terms, we say that the integers are not closed under division.) To avoid different results
between division of integers and divisions of floats, division always operates on floats and gives float
results:

> 3.0 / 2.0 --> 1.5


> 3 / 2 --> 1.5

For integer division, Lua 5.3 introduced a new operator, called floor division and denoted by //. As
its name implies, floor division always rounds the quotient towards minus infinity, ensuring an integral
result for all operands. With this definition, this operation can follow the same rule of the other arithmetic
operators: if both operands are integers, the result is an integer; otherwise, the result is a float (with an
integral value):
2
This feature was introduced in Lua 5.2.
3
From the Lua 5.3 Reference Manual.

16
Numbers

> 3 // 2 --> 1
> 3.0 // 2 --> 1.0
> 6 // 2 --> 3
> 6.0 // 2.0 --> 3.0
> -9 // 2 --> -5
> 1.5 // 0.5 --> 3.0

The following equation defines the modulo operator:

a % b == a - ((a // b) * b)

Integral operands ensure integral results, so this operator also follows the rule of other arithmetic opera-
tions: if both operands are integers, the result is an integer; otherwise, the result is a float.

For integer operands, modulo has the usual meaning, with the result always having the same sign as the
second argument. In particular, for any given positive constant K, the result of the expression x % K
is always in the range [0,K-1], even when x is negative. For instance, i % 2 always results in 0 or 1,
for any integer i.

For real operands, modulo has some unexpected uses. For instance, x - x % 0.01 is x with exactly
two decimal digits, and x - x % 0.001 is x with exactly three decimal digits:

> x = math.pi
> x - x%0.01 --> 3.14
> x - x%0.001 --> 3.141

As another example of the use of the modulo operator, suppose we want to check whether a vehicle turning
a given angle will start to backtrack. If the angle is in degrees, we can use the following formula:

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#).

Lua also offers an exponentiation operator, denoted by a caret (^). Like division, it always operates on
floats. (Integers are not closed under exponentiation; for instance, 2-2 is not an integer.) We can write
x^0.5 to compute the square root of x and x^(1/3) to compute its cubic root.

Relational Operators
Lua provides the following relational operators:

17
Exploring the Variety of Random
Documents with Different Content
CHAPTER VI.
THE NIGHT BEFORE.

Full of dissatisfaction I wandered into the shed and loitered


aimlessly about. As I stood there Jason came clattering homeward,
his coat collar turned up and his curly head bowed to the deluge.
“So you got home before me?” he said, shaking himself and
squeezing his cap out as he spoke.
“Yes; we came straight.”
“It was lovely in the meads, wasn’t it?” said he, with an odd glance
at me.
“It’s been lovely all this May,” said I.
“And that means a fat churchyard. Old Rottengoose says: ‘A cold
May and windy makes a full barn and findy.’ A queer one, old Peg is.
She’d die if she cast a woolen before the first of June. I wonder what
she’d think of sitting under a hedge in a northeaster?”
I started a little and shot a look askance at my brother. Could he
have seen us? But his next words reassured me.
“Or of falling asleep in the shade, as I did, till the rain on my face
woke me up.”
“Then you didn’t see us pass——” I began and stopped.
“See what? I saw nothing but my eyelids and the sky through ’em.”
I gave a sigh of relief. My feelings toward Zyp were boyish and
bashful and innocent enough, heaven knows; but in the shadow of
my rough past they were beginning to glimmer out so strange and
sweet that the merest suspicion of their incurring publicity filled me
with a shame-faced terror of ridicule that was agony.
Freed from this dread, I fell into an extreme of garrulity that landed
me in a quagmire of discomfiture.
After I had thus talked for a while, rather disconnectedly, he
interrupted me.
“Renny,” he said, “you’re pretty fond of the girl, aren’t you?”
I heard him with a little shock of surprise.
“Not that I care,” he went on, airily, “except for your sake, old boy.”
“What do you mean?” I said.
“We’re up to a thing or two, aren’t we?” said he, “but she’s fifty
tricks to our one.”
“She has her good points, Jason.”
“Oh, yes; lots of them. So many that it hardly seems worth while
noticing her setting you up against me.”
“She’s never done anything of the sort!” I cried, hotly.
“Hasn’t she? Well, that’s all right, and we can be chums again. I
only wanted to warn you against putting faith in a chit that can wear
a new face easier than her dress, to you, or Modred, or—or any
one.”
“Modred!” I cried, in astonishment.
“Oh, don’t suppose,” he said, “that you’re sole lord of her heart.”
“I never did suppose it,” I answered, thickly. “Why should I? She’s
free to fancy whom she likes”—but my heart sunk within me.
“Yes; that’s the way to look at it,” he said. “You wouldn’t think she
could find much to admire in that fatty, now, would you?”
“How do you know she does?”
“I do know—that’s enough.”
“Well, isn’t he a sort of brother to her?” I said—with a courageous
effort—“as we all are.”
“Of course. That’s it.”
“And I don’t know what you mean by ‘any one’ else.”
“Don’t you?” He laughed and flung away a stone he had been idly
playing with. “Well, I meant Modred, or—or any one else.”
“Who else?”
“Dad, say—or Dr. Crackenthorpe.”
“Oh, you’re an idiot!” I cried; “I won’t talk to you”—and I left him
and ran indoors.
But he had driven the sting home and the poison already worked
furiously in me. How can I explain why? It was true, what he had
said, every word of it. She had set me against him, Jason—not in
words, but by a tacit conviction of him as one who had of his own act
bared his soul momentarily, and revealed a sinister brand across it
hitherto unguessed at.
Well, this was the first waking from the boyish dream, and should I
ever dream it again? I had said we were all in a manner her brothers,
and that she was free to smile on whom she chose. What a pitiful
handful of dust for all eyes but my own! I felt the passion of longing
for her single love surge in me as I spoke. I had never till that
moment dreamed of combating another for possession of it. She had
seemed mine by right of fortune’s gift from the first, nor had she by
her behavior appeared to question the right. We had confidences,
discussions, little secrets together, which none but we might share
in. We walked and talked and leaned toward one another, with a
sense of mutual understanding that was pathetic, I am sure—at least
as to my share in it—in God’s eyes.
And now to find that all the time she was on like secret terms with
Modred—with Jason, too, perhaps, judging by his sidelong
innuendoes, though it made my heart sick to think that she could
play so double faced a game between me and one whom she
professed to hate and despise.
What a drama of dolls it was! And how soon the drama was to turn
into a tragedy!
I went indoors and upstairs to the room which Jason and I shared
and flung myself on the bed. Then I was properly shocked and
horrified to find that my cheeks were suddenly wet with tears—a
humiliating discovery for a tough-sinewed young barbarian to make.
What an admirable sight, indeed! Renalt Trender, sniffing and
snuffling for a girl’s favor!
Pride, however, is everywhere indigenous, and this came to my
assistance. If the minx played sham with me I would meet her with
her own tactics and affect indifference. What a triumphant picture
this:
Zyp—“Why have you been different to me of late, Renny? Aren’t
you fond of me now?”
Renny—“My good little Zyp, the fact is I have tired a bit of the
novelty. It has been my first experience of the society of a girl, you
know, and very pleasant while it lasted; but I confess to a little
longing for a resumption of the old independence and freedom.
Perhaps some day again we will walk and converse together as of
old.”
Atop of this imaginary question and answer rose a smugly
anguishing picture of Zyp flushed and in tears (my imagination
insisted on these in bucketsful, to out-flood my own temporary
weakness); of Zyp hurt and sorrowing, but always striving by every
means in her power to win back my lost favor.
Alas, poor little clown! I fear it is just those who have the fancy to
conjure up such pictures who suffer most cruelly from the non-
realization of the hopes of youth. Braced to the test, however, and
not knowing myself in weak armor, I came down to supper that
evening prickling all through with resolve.
Jason was in the room alone, as I entered, and was walking
feverishly up and down.
“Hist!” he said, softly, seizing me by the arm; “come here and look
for yourself.”
He dragged me to the little square window, which was open. It
looked out at the back, and beneath was the railed platform before
mentioned.
I knew that I was urged to act the spy, and yet—so demoralizing is
jealousy—like a dog I went. Softly we craned our necks through the
opening and looked down. Trees all about here bordered the river
banks, so as to make the rear of our mill quite secret and secluded.
She, Zyp, was standing on the platform with her arm round
Modred’s neck. She seemed trying to coax something from him
which he was reluctant to part with. As he evaded her efforts I saw
what it was—the little round yellow object I had noticed in his hand
earlier in the afternoon.
“Darling,” she said, in a subdued voice, “do let me have it.”
He laughed and looked at her loutishly.
“You know the condition, Zyp.”
“I have let you kiss me over and over again.”
“But you haven’t kissed me yet.”
She stamped her foot. “Nor ever shall!” she cried.
“Then here goes,” he said, and slipped it into his pocket.
At that she rushed at him and wound her arms about him like a
young panther.
“Shall I tear you with my teeth?” she said, but instead she
smoothed his face with one hand disengaged and murmured to him:
“Modred, dear, you got it for me, you know; you said so.”
“And precious frightened I was, Zyp.”
“Well, it is mine, isn’t it?”
“If you give me the kiss.”
My father’s step on the stairs brought our heads in with a clatter.
We heard them scuttle into the house, and a moment later they
appeared in the room. Modred’s face was flushed and bore a heavy,
embarrassed expression, but Zyp looked quite cool and self-
possessed.
I took no notice of her during the meal, but talked, daring in my
misery, to my father, who condescended to answer me now and
again, and I could see that she wondered at me.
Supper over, I hurried to my room, and shutting myself in, went
and sat by the window and gave my tormented soul to the night. Had
I never met Zyp, I doubt if I should ever in my manhood have
realized what the grown-up, I think, seldom do, the amount of torture
and wrong the young heart may endure without bursting—with no
hope of sympathy, moreover, except that half-amused tolerant form
of it which the old think it sufficient to extend to youth’s elastic
grievances.
By and by Jason stole in. For some little time he sat upon his bed,
silent; then he said in a soft voice:
“Let’s cry quits, Renny. I think I’ve paid you out for that little
accident of the meads.”
“I hate you!” I said, quietly, and indeed it seemed to me that his
cruelty deserved no better a reward.
He laughed, and was silent again, and presently began to undress
for bed, whistling softly all the time.
I took no notice of him; but long after when he was breathing
peacefully asleep, I laid my own aching head, tired with misery, on
the pillow, and tried to follow his example. I was not to succeed until
faint daylight came through the casement and the birds were
twittering outside—was never, indeed, to know sleep in its innocence
again.
CHAPTER VII.
THE POOL OF DEATH.

Morning brought a pitcher of comfort with it on its gossamer wings.


Who, at 17, can wake from restoring sleep to find the June sun on
his face and elect to breakfast on bitter wormwood, with the
appetizing fry of good country bacon caressing his nostrils through
every chink of the boards? Indeed, I was not born to hate, or to any
decided vice or virtue, but was of those who, taking a middle course,
are kicked to the wall or into the gutter as the Fates have a fancy.
I was friendly with myself, with Jason—almost with Zyp, who had
so bedeviled me. After all, I thought, the measure of her regard for
me might be more in a winning friendliness than in embraces such
as she had bestowed upon Modred.
Therefore I dressed in good heart, chatting amiably with Jason,
who, I could not help noticing, was at some pains to study me
curiously.
Such reactionary spirits are the heritage of youth. They decline
with the day. My particular relapse happened, maybe, ungenerously
early, for it was at breakfast I noticed the first tremulous vibrations of
Zyp’s war trumpet. Clearly she had guessed the reason of the
change in my manner toward her yesterday evening and was bent
upon disabusing my mind of the presumptuous supposition that I
held any monopoly whatsoever of her better regard. To this end she
showered exaggerated attentions upon Modred and my father—even
Jason coming in for his share. She had little digs at my silence and
boorishness that hugely delighted the others. She slipped a corner of
fat bacon into my tea and spilled salt over my bread and jam, and all
the time I had to bear my suffering with a stoic heart and echo the
merriment, which I did in such sardonic fashion as to call down fresh
banter for my confusion. At our worst, it must be confessed, we were
not a circle with a refined sense of humor. But when we rose, and
Zyp brushed rudely by me with a pert toss of her head, I felt indeed
as if life no longer held anything worth the striving after.
I walked out into the yard to be alone, but Jason followed me.
Some tenderness for old comradeship sake stirred in him
momentarily, I think, for his blue eyes were good as they met mine.
“What an ass you are, Renny,” he said; “to make such a to-do
about the rubbish!”
“I don’t know what you mean,” I said, in miserable resentment. “I’m
making no to-do about anything.”
My chest felt like a stone, and I could have struck him or any one.
“Oh, I can see,” said he.
“See what you like,” I replied, furiously, “but don’t bother me with it.
I’ve nothing to do with your fancies.”
“Oh, very well,” he said, coolly; “I don’t want to interfere, I’m sure.”
I bounced past him and strode out of the yard. My blood was
humming in my veins; the sunny street looked all glazed with a
shining gray. I walked on and on, scarcely knowing whither I went.
Presently I climbed St. Catherine’s hill and flung myself down on the
summit. Below me, a quarter of a mile away, the old city lay in the
hollow cup of its down. Who, of all its 17,000 souls, could ever stir
my pulses as the little stranger from the distant shadowy forest
could? We had no forests round Winton. Perhaps if we had the spirit
of the trees would have colored my life, too, so that I might have
scorned “the blind bow-god’s butt shaft.”
No doubt I was young to make such capital out of a little boyish
disappointment. Do you think so? Then to you I must not appeal. Oh,
my friend! We are not all jack-o’-lanterns at 17, and the fire of
unrequited affection may burn fiercer in the pure air of youth than in
the vitiated atmosphere of manhood. Anyhow believe me that to me
my misery was very real and dreadful. Think only, you who have
plucked the fruit and found it bitter—you whose disenchantment of
life did not begin till life itself was waning—what it must be to feel
hopeless at that tender age.
All day long I lay on the hill or wandered about the neighboring
downs, and it was not till the shadows of the trees were stretching
that I made up my mind to return and face out the inevitable.
I was parched and feverish, and the prospect of a plunge in the
river on my way home came to me with a little lonely thrill as of
solace to my unhappiness.
There was a deep pool at a bend of the stream, not far from where
Zyp and I had sat yesterday afternoon (was it only yesterday?) which
we three were much in the habit of frequenting on warm evenings;
and thither I bent my steps. This part of the water lay very private
and solitary, and was only to be reached by trespassing from the
road through a pretty thick-set blackthorn hedge—a necessity to its
enjoyment which, I need not say, was an attraction to us.
As I wriggled through our individual “run” in the hedge and,
emerging on the other side, raised my face, I saw that a naked figure
was already seated by the side of the running pool, which I was not
long in identifying as Modred’s.
I hesitated. What reason had I for hobnobbing with mine enemy,
as, in the bitterness of my heart, I called him? I could not as yet
speak to him naturally, I felt, or meet him without resentment. Where
was the object in complicating matters? I turned, on the thought, to
go, and again hesitated. Should he see me before I had made my
escape, would he not attribute it to embarrassment on my part and
crow triumphant over my discomfiture? Ah, why did I not act on my
first impulse? Why, why? The deeps of perdition must resound with
that forlorn little word.
When a second time the good resolve came to me, it was too late.
He rose and saw me and, under his shading hand, even at that
distance, I could mark the silent grin of mockery on his face. I walked
deliberately toward him, my hands in my pockets, my cap shading
my eyes.
“Aren’t you coming to bathe?” he said, when I drew near. “It’ll cool
your temper.”
I could have struck him, but I answered nothing and only began to
undress.
“Where have you been all day? We were wondering, Zyp and I, as
we lay in the meadow out there.”
Still I answered nothing, but I knew that my hands trembled as I
pulled off my coat and waistcoat.
He stood watching me a little while in silence, then said: “You
seem to have lost your tongue, old Renny. Has it followed your heart
because Zyp talks for two?”
I sprung up, but he eluded me and, with a hateful laugh, leaped on
the moment into the deep center of the pool. A horrible tightness
came round my throat. Half-undressed as I was I plunged after him
all mad with passion. He rose near me, and seeing the fury of my
face, dived again, and I followed. It took but an instant, and my life
was wrecked. We met among the weeds at the bottom, and he
jumped from me. As he rose I clutched him by one foot, and swiftly
passed a great sinew of weed three or four times around his ankle. It
held like a grapnel and would hold; for, though he was a fair
swimmer, he was always frighted and nervous in the face of little
difficulties. Then swerving away, I rose again, with laboring lungs, to
the surface.
Barely had my drenched eyes found the daylight again, when the
hideous enormity of my crime broke into my brain like the toll of a
death bell. The water near me was heaving slightly and some welling
bubbles swayed to the surface. They were the drowning gasps of my
brother—my own brother, whom I was murdering.
I gave a thin, wretched scream and sunk again into the deep hole
beneath me. He was jerking convulsively, and his hands clutched
vainly at his feet and slipped away in a dying manner. I tore at the
weed to unwind it—only to twist it into new fetters. I pulled frantically
at its roots. I felt that I should go mad if it did not yield. In a moment it
came away in my hands and I shot upward, struggling. But the other
poor body followed me sluggishly, and I seized it by the hair, with all
my heart gone crazy, and towed it ashore.
His face, I thought, looked fallen away already and was no longer
loutish or malicious. It seemed just a white, pathetic thing freed from
suffering—and I would have given my life—ay, and my love—ten
times over to see the same expression come back to it it had worn
as it turned to me before he dived.
I fell on my knees beside him and broke into a passion of tears. I
kissed, with no shame but a murderer’s, the wet forehead, and beat
and pressed, in a futile agony too terrible for words, the limp
unresisting hand against my breast. It seemed that he must wake if I
implored him so frantically. But he lay quiet, with closed eyes, and
the water ran from his white skin in trickling jerks and pauses.
In the midst of my useless anguish some words of Jason’s
recurred to me, and, seizing my coat for a pillow to his forehead, I
turned him, with a shuddering horror of his limpness, upon his face.
A great gush of water came with a rumble from his mouth, but he did
not stir; and there I stood looking down upon him, my hand to my
forehead, my mad eyes staring as Cain’s must have stared when he
wrought the deed of terror.
And I was Cain—I who yesterday was a boy of loving impulses, I
think; whose blackest crime might be some petty rebellion against
the lesser proprieties; who had even hugged himself upon living on a
loftier plane than this poor silenced victim of his brutality.
As the deadly earnest of my deed came home to my stunned
mind, I had no thought of escape. I would face it out, confess and
die. My father’s agony—for he loved us in his way, I believe; Jason’s
condemnation; Zyp’s hatred; my own shame and torture—I put them
all on one side to get full view of that black crossbeam and rope that
I felt to be the only medicine for my sick and haunted soul.
As I stood, the sound of wheels on the road beyond woke me to
some necessity of action. Stumbling, as in a nightmare; not feeling
my feet, but only the mechanical spring of motion, I hurried to the
hedge side and looked over.
A carter with a tilt wagon was urging his tired team homeward.
“Help!” I cried. “Oh, come and help me!” And my voice seemed to
me to issue from under the tilt of the wagon.
He “woa’d” up his horses, raised his hat from his forehead,
wrinkled with hot weariness, and came toward me, his whip over his
shoulder.
“What’s toward?” said he.
“My brother!” I gasped. “We were bathing together and he’s
drowned.”
The man’s boorish face lighted up like a farthing rushlight. Here
was something horribly sordid enough for all the excitement he was
worth. It would sweeten many a pot of swipes for the week to come.
“Wheer be the body?” said he, eagerly.
“Over yonder, on the grass. Oh, won’t you help me to carry it
home?”
He looked at the hedge critically.
“Go, you,” he said, “and drag ’en hither. We’ll gat ’en over hedge
together.”
I ran back to where it lay. It had collapsed a little to one side, and
for an instant my breath caught in a wild thrill of hope that he had
moved of himself. But the waxen hue of the face in the gathering
dusk killed my emotion on its very issuing.
A strange loathing of the thing, lying so unresponsive, had in my
race backward and forward sprung upon me, but before it could gain
the mastery I had seized it under the arm-pits and was half-dragging,
half-carrying it toward the road.
I was at the hedge before I knew it, and the red face of the carter
was peering curiously down at the white heap beneath.
“Harned ’en up,” he said. “My, but it’s cold. Easy, now. Take the
toes of ’en. Thart’s it—woa!” and he had it in his strong arms and
shuffling heavily to the rear of his wagon, jerked back the flap of the
tilt with his elbow and slid the body like a package into the interior.
“Get your coat, man,” he cried, “and coom away.”
I had forgotten in the terror of it all my own half-dressed state, for I
had stripped only to my underclothes, and my boots were still on my
feet. Mechanically I returned to the riverside, and hastily donning my
coat and trousers, snatched up the other’s tumbled garments and
ran back to the road.
CHAPTER VIII.
THE WAKING.

The carter was holding the curtain back and critically


apostrophizing the thing within.
“Ay, he be sound enough. Reckon nought but the last trump’ll
waken yon. Now, youngster, where may you live?”
I told him.
“Sure,” he said, “the old crazed mill?” Then I thought he muttered:
“Well, ’tis one vermin the less,” but I was not sure and nothing
mattered—nothing.
He asked me if I would like to ride with it inside. The mere
suggestion was terror to me, and I stammered out that I would rather
walk, for I had tried my best already and had given up hope.
So we set off slowly through the dumb, haunted twilight. Thoughts
would not come to me in any definite form. I imagined the cathedral
bells were ringing, till I found it was only a jangling in my brain,
discordant and unearthly. People came toward us who on nearing
were resolved into distorted rags of mist; voices croaked with
laughter, and they were only the swung branches of trees.
Suddenly I heard an exclamation—real enough this time—and
saw the carter run to the head of his team and stop them.
“Woa, then!” he cried, in a frightened voice; and then with terrified
impatience: “Coom hither, marn; I tell ’ee. Don’t ’ee stand theer
gawking at the air. Dang it, the ghost walks!” He stamped his heavy
foot, seeing me motionless; then cried again: “Take thee foul burden
out o’ the wain and dang me for a fool ever to have meddled wi’t!”
A gush of wondrous hope flooded my breast. I tore to the rear of
the wagon, dashed back the curtain—and there was Modred sitting
up and swaying feebly from side to side.
I leaped; I caught him in my arms; my breath came in laughter and
sobs. “Oh, Modred, Modred!” I cried. “I didn’t mean it—it wasn’t me—
I’m not like that!” and then I broke down and wept long and
convulsively, though I would never let him out of my clutch.
“Where am I?” he said, faintly; “oh, it hurts so. Every vein in my
body is bursting with pain.”
At this I beat under my hysterical outburst and set to rubbing him
all over in frantic eagerness. It seemed to ease him a little and I
blessed him that he lay passively against me and did not offer to
push me away. Poor fellow, he was far too weak as yet for any
resistance.
Presently I heard the carter bawl in tremulous tones: “Art gone, the
two of ’ee?”
“Come here,” I called back, with a tearful laugh. “He’s better; he’s
recovered!”
The fellow came round gingerly and stood a little distance off.
“Eh?” he said, dubiously.
“See for yourself!” I cried. “He wasn’t drowned after all. He’s come
round!”
The man spat viciously in the road and came sullenly forward. He
was defrauded of an excitement and he felt the injury grievously.
“You young varmint!” he growled. “Them’s your tricks for to get a
free lift.”
“Nonsense!” I said, buoyantly; “you yourself thought him dead.
Carry us on to the mill and I’ll promise you a proper skinful of liquor.”
He was crabbed and undecided, but presently he went forward
and whipped up his horses with a surly oath. As the wagon pitched,
Modred opened his eyes, which he had shut, and looked up at me.
“Are you feeling better, old boy?” I said, tenderly.
“The pain isn’t so bad, but I’m tired to death,” said he.
“Rest, and don’t talk. You’ll be stronger in a bit.”
He closed his eyes again and I tried to shield him as much as I
could from the jolting. I had already wrapped him up warm in some
old sacks that were heaped in a corner of the wagon. So all the way
home I held him, counting his every breath, loving him as I had never
done before.
It was dark when we reached the mill and I laid him gently back
and leaped down.
“Dad! Dad!” I shouted, running down the yard and into the house;
but he was already standing at the head of the stairs, with a candle
in his hand.
“Modred’s had an accident!” I cried, in a subdued voice—I could
not keep the lie back. It seemed so dreadful at the outset to confess
and stand aside condemned—while others helped. Jason and Zyp
came out on the landing and my father ran down the stairs hurriedly.
“What’s that?” he said—“Modred!”
“He got caught in the weeds and was nearly drowned, but he’s
getting better.”
“Where is he?” He seized me by the arm as he spoke, and
dragged me to the mill door. I could feel the pulses in his finger tips
through my coat.
“He’s in a wain outside, and I promised the man a long drink for
bringing us home.”
“There’s a full bottle in the cupboard—bring it down,” shouted my
father to Jason. Then he hurried to the wagon and lifted out the
breathing figure and looked into its face. After all, it was his
youngest.
“Not much harm, perhaps,” said he. “Run and tell them to heat
some water and the blankets.”
While I was finding old Peg and explaining and giving the order,
they carried him upstairs. I did not dare follow them, but, the reaction
over, leaned, feeling sick and faint, in the passage outside the little
kitchen. Perhaps even now he was telling them, and I dreaded more
than I can describe the sentence which a first look at any one of their
faces might confirm.
Presently old Peg came out to me with a can of boiling water and
flung an armful of warm blankets over my shoulder.
“There’s for you, Renalt,” she cried in her thin, rusty voice; then
muttered, clawing her hips like a monkey: “’Tis flying in the Lord’s
face o’ Providence, to me a old woman; like as restoring a froze
snake on the hearth.”
I had no heart for retort, but sped from the sinister old witch with
my burden. I saw Zyp and Jason in the living-room as I passed, but,
though they called to me, I ran on and upstairs to the door of
Modred’s room, which was next ours.
My father came out to my knock and took the things from me.
“Now,” said he, “I want nobody here but myself and Dr.
Crackenthorpe. Go you and fetch him, if he’s to be found.”
Happy to be employed in any useful service, I hurried away on my
errand. The door of the sitting-room was shut, at which I was glad.
Very little respite gave me fresh lease of hope.
The doctor’s home was close by, in a straggling street of old
buildings that ran off our end of the High street, and the doctor
himself was, I was told, within.
I found him seated in a musty little parlor, with some ugly casts of
murderers’ heads facing him from the top of a varnished bookcase.
“Ah, my friend!” he screeched, cracking his knuckles; “those
interest you, eh? Well, perhaps I shall have the pleasure of adding
your picture to them some day.”
An irrepressible shudder took me and he laughed, not knowing the
reason of it.
“Now, what’s your business?” said he.
I told him.
“Eh,” he said, and bent forward and looked at me narrowly. “Near
drowned, eh? Why, what were you doing, you young limb?”
“I went after him,” I answered, faintly, “but I couldn’t get the weeds
loose.”
“Dressed, too?” he said, for the sop of my underclothes had come
through the upper, and nothing escaped his hawk’s eye; “why, you’re
a hero, upon my word.”
He bade me begone after that and he would follow immediately.
And I returned to the mill, and, softly climbing the stairs, shut myself
into my room and sat upon the edge of the bed listening—listening
for every breath and sound in the old eerie house. I heard the doctor
come up the stairs and enter the room next door. I heard the low
murmur of voices and strained my ears to gather what was said, but
could not make out a word. And the darkness grew into my soul and
shut out all the old light of happy reason. Should I ever feel innocent
again? And would Modred, satisfied with his knowledge of the
dreadful heritage of remorse I had laid up for myself, forego his right
to denounce me and to forever make me an outcast and alone? I
hardly dared to hope it, yet clung with a strenuous longing to thought
of his mercy.
It may have been hours I sat there. I do not know. I had heard
footsteps go up and down the stairs many times. And then a silence
fell. What was the meaning of it? Was it possible that life had only
rallied in him momentarily, like the flame of a dying candle and had
suddenly sunk for good and all into endless darkness? Had he told?
Why did no one come near me? I could stand it no longer.
As I sprung to my feet I heard a footstep again on the stairs and
Jason walked into the room and shut the door. He took no notice of
me, but began to undress.
“Jason!” I cried, and the agony in my voice I could not repress.
“How is he? Has he spoken? Oh, don’t keep me in this torture.”
“What torture?” said my brother, looking at me with a cold,
unresponsive eye. “Why should you be upset more than the rest of
us? He’s asleep all right, and not to be bothered with any questions.”
Thank God! Oh, thank God! I took no notice of his looks or tone,
for I was absorbed in great gratitude to heaven that my worst fears
were idle ones.
“Where’s dad?” I said.
“Drinking downstairs with the doctor. They’ll make high revel of it, I
expect.”
He was already in bed; but I sat on and on in the darkness. I had
only one thought—one longing to wait till Jason was fast in slumber,
and then to creep to Modred’s side and implore his forgiveness.
Presently the deep, regular breathing of my brother announced to
me the termination of my vigil. With my heart beating in a suffocating
manner, I stole to the door, opened it and stood outside that of
Modred’s room. I listened a moment. A humming noise of garrulous
voices below was the only sound that broke the silence of the house.
Softly I turned the handle and softly crept into the room. There was
light in it, for on the wash-hand stand a rush candle burned dimly in
an old lanthorn.
He gave a start, for he was lying awake in his bed, then half-rose
on his elbow and looked at me with frightened eyes.
“Don’t come near,” he whispered. “What do you want? You aren’t
going to try to kill me again?”
I gave a little strangled, agonized cry, and, dropping on my knees
where I stood, stretched out my arms to him imploringly.
“Oh, Modred, don’t! Don’t! You can’t think I meant it! It was only a
horrible impulse. I was mad, and I nearly drowned myself directly
afterward in saving you.”
The fright went from his face and something like its familiar look
returned to it.
“Are you sorry?” he said.
“Sorry? Oh, I will do anything you like if you will only believe me.”
“Come here, Renny,” he said, “and stand by me. I want to see you
better.”
I obeyed humbly—lovingly.
“You want me to forgive you?”
“If you could, Modred—if you only could.”
“And not to peach?”
I hung my head in shame and the tears were in my eyes again.
“Well, I’ll agree, on one condition.”
“Make any you like, Modred. I’ll swear to keep it; I’ll never forget
it.”
“Zyp’s it,” he said, looking away from me.
“Yes,” I said, gently, with a prescience of what was coming.
“You’ll have to give her up for good and all—keep out of her way;
let her know somehow you’re sick of her. And keep Jason out of the
way. You and he were chums enough before she came.”
“I swear for myself, and to do what I can with Jason,” I said, dully.
What did it matter? One way or another the buoyant light of
existence was shut to me for good and all.
“It’s the only way,” said Modred, and he gave me a look that I dare
not call crafty. “After all, it isn’t much,” he said, “considering what you
did to me, and she seems to be getting tired of you—now, doesn’t
she?”
“Yes,” I said in a low voice.
“Then, that’s settled. And now let me be, for I feel as if I can sleep.
Hand me my breeches first, though. There’s something in the pocket
I want.”
“Shall I get it out for you, old boy?”
“No, no!” he answered, hurriedly. “Give them to me, can’t you?”
I did as he wanted and crept from the room. What did it matter?
Zyp had already cast me off, but for the evil deed I was respited. A
moment ago the girl had seemed as nothing, set in the scale against
my brother’s forgiveness. Could it be the true, loving spirit of
forgiveness that could make such a condition? Hush! I must not think
that thought. What did it matter?
I did not go back to my room, but sat on a stair at the head of the
downward flight, with a strange, stunned feeling. Below the voices
went on spasmodically—now a long murmur—now a snatch of song
—now an angry phrase. By and by, I think, I must have fallen into a
sort of stupor, for I seemed to wake all at once to a thunderous
uproar.
I started to my feet. Magnified as all sounds are in the moment of
recovered consciousness, there was yet noise enough below to
convince me that a violent quarrel between the two men was toward.
I heard my father’s voice in bitter denunciation.
“You’ve been hawking over my quarry this long while. I’ll tear the
truth out of your long throat! Give me back my cameo—where is it?”
“A fig for your cameo!” cried the other in a shrill voice, “and I tell
you this is the first I’ve heard of it.”
“You’ve been watching me, you fiend, you! Dogging me—haunting
me! I’ll have no more o’t! I’m not to be bribed or threatened or
coaxed any more; least of all thieved from. Where is it?”
“You aren’t, aren’t you?” screeched the doctor. “You leave me here
and I fall asleep. You’re away and you come storming back that I’ve
robbed you. It’s a trap, by thunder, but you won’t catch me in it!”
“I believe you’re lying!” cried my father. His voice seemed strained
with passion. But the other answered him now much more coolly.
“Believe what you like, my friend. It’s beneath my dignity to
contradict you again; but take this for certain—if you slander me in
public, I’ll ruin you!”
Then silence fell and I waited to hear no more. I stole to my room
and crept to bed. I had never changed my drenched clothes and the
deadly chill of my limbs was beginning to overcome the frost in my
heart.
It seemed hours before the horrible coldness relaxed, and then
straightway a parching fever scorched me as if I lay against a
furnace. I heard sounds and dull footsteps and the ghostly creaking
of stairs, but did not know if they were real or only incidents in my
half-delirium.
At last as day was breaking I fell into a heavy, exhausted sleep. It
merged into a dream of my younger brother. We walked together as
we had done as little children, my arm around his neck. “Zenny,” he
said, like a baby paraphrasing Zyp’s words, “what’s ’ove dat ’ey talk
about?” I could have told him in the gushing of my heart, but in a
moment he ran from me and faded.
I gave a cry and woke, and Jason was standing over me, with a
white, scared face.
“Get up!” he whispered; “Modred’s dead!”
CHAPTER IX.
THE FACE ON THE PILLOW.

Often the first shock of some unexpected mental blow shakes from
the soul, not its corresponding emotion, but that emotion’s exact
antithesis. Thus, when Jason spoke I laughed. I could not on the
moment believe that such hideous retribution was demanded of my
already writhed and repentant conscience, and it seemed to me that
he must be jesting in very ugly fashion.
Perhaps he looked astonished; anyhow he said:
“You needn’t make a joke of it. Are you awake? Modred’s dead, I
tell you.”
I sprung from the bed; I clutched him and pulled him to and fro.
“Tell me you lie—you lie—you lie!” I cried.
He did not. I could see it in his face. There and then the drought of
Tophet withered and constricted my life. I was branded and doomed
forevermore; a thing to shudder at and avoid.
“I will dress and come!” I said, relaxing from my hold on him, and
turned away and began to hurry on my clothes. I had not felt so set
in quietness since the morning of two days past. I could even think
calmly and balance the pros and cons of my future behavior.
Each man must be his own judge, his own plaintiff, his own
defendant—an atom of self-contained equity. By his own ruling in
matters of right and wrong he must abide, suffer his own
punishments, enjoy his own rewards. He is a lonely organism, in
whom only himself took an interest, and as such he must be content
to endure with calmness the misinterpretations of aliens.
Modred had forgiven me. Whatever was the condition, whatever
the deed, it was too late now to convince me that no justification
existed for my rebellion against fate.
My elder, my only brother now, watched me in silence as I
dressed.
“Where is he?” I said, when I had finished.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like