0% found this document useful (0 votes)
23 views57 pages

Programming in Lua 4th Edition Roberto Ierusalimschy download

The document provides information about the 4th edition of 'Programming in Lua' by Roberto Ierusalimschy, detailing its contents and structure, including chapters on basics, real programming, Lua-isms, and the C API. It also includes links to various other programming-related ebooks available for download. The document appears to be a promotional or informational piece related to Lua programming resources.

Uploaded by

saugatfjera
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
0% found this document useful (0 votes)
23 views57 pages

Programming in Lua 4th Edition Roberto Ierusalimschy download

The document provides information about the 4th edition of 'Programming in Lua' by Roberto Ierusalimschy, detailing its contents and structure, including chapters on basics, real programming, Lua-isms, and the C API. It also includes links to various other programming-related ebooks available for download. The document appears to be a promotional or informational piece related to Lua programming resources.

Uploaded by

saugatfjera
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/ 57

Programming in Lua 4th Edition Roberto

Ierusalimschy pdf download

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

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Lua Programming Gems Luiz Henrique De Figueiredo

https://ebookname.com/product/lua-programming-gems-luiz-henrique-
de-figueiredo/

Programming in C 4th Edition Stephen G. Kochan

https://ebookname.com/product/programming-in-c-4th-edition-
stephen-g-kochan/

Programming Python 4th Edition Mark Lutz

https://ebookname.com/product/programming-python-4th-edition-
mark-lutz/

Getting Straight A s A Student s Guide to Success 1st


Edition Richard Palmer

https://ebookname.com/product/getting-straight-a-s-a-student-s-
guide-to-success-1st-edition-richard-palmer/
Translational Neuroscience Applications in Psychiatry
Neurology and Neurodevelopmental Disorders 1st Edition
Dr James E. Barrett

https://ebookname.com/product/translational-neuroscience-
applications-in-psychiatry-neurology-and-neurodevelopmental-
disorders-1st-edition-dr-james-e-barrett/

Fighter s Fact Book 2 Street Fighting Essentials No 2


1st Edition Loren W. Christensen

https://ebookname.com/product/fighter-s-fact-book-2-street-
fighting-essentials-no-2-1st-edition-loren-w-christensen/

The Tensions between Culture and Human Rights


Emancipatory Social Work and Afrocentricity in a Global
World 1st Edition Vishanthie Sewpaul

https://ebookname.com/product/the-tensions-between-culture-and-
human-rights-emancipatory-social-work-and-afrocentricity-in-a-
global-world-1st-edition-vishanthie-sewpaul/

The Falklands War 1982 Duncan Anderson

https://ebookname.com/product/the-falklands-war-1982-duncan-
anderson/

Philosophy Rhetoric and the End of Knowledge A New


Beginning for Science and Technology Studies 2nd
Edition Steve Fuller

https://ebookname.com/product/philosophy-rhetoric-and-the-end-of-
knowledge-a-new-beginning-for-science-and-technology-studies-2nd-
edition-steve-fuller/
Truth Light Brief Explanations M. R. Bawa Muhaiyaddeen

https://ebookname.com/product/truth-light-brief-explanations-m-r-
bawa-muhaiyaddeen/
Last update: Sat Mar 18 22:00:08 GMT 2017 (build 21)
Programming in Lua, Fourth Edition
Roberto Ierusalimschy
Programming in Lua, Fourth Edition
Roberto Ierusalimschy
Copyright © 2016, 2003 Roberto Ierusalimschy

Feisty Duck Digital


Book Distribution
www.feistyduck.com

Licensed for the exclusive use of:


Eric Taylor <[email protected]>
Table of 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

iii
Programming in Lua, Fourth Edition

repeat ..................................................................................................... 59
Numerical for ........................................................................................... 60
Generic for .............................................................................................. 60
break, return, and goto ..................................................................................... 61
II. Real Programming ......................................................................................................... 65
9. Closures ............................................................................................................... 68
Functions as First-Class Values ............................................................................ 68
Non-Global Functions ........................................................................................ 69
Lexical Scoping ................................................................................................ 71
A Taste of Functional Programming ..................................................................... 74
10. Pattern Matching .................................................................................................. 77
The Pattern-Matching Functions ........................................................................... 77
The function string.find ...................................................................... 77
The function string.match .................................................................... 77
The function string.gsub ...................................................................... 78
The function string.gmatch .................................................................. 78
Patterns ............................................................................................................ 78
Captures ........................................................................................................... 82
Replacements .................................................................................................... 83
URL encoding .......................................................................................... 84
Tab expansion ........................................................................................... 86
Tricks of the Trade ............................................................................................ 86
11. Interlude: Most Frequent Words ............................................................................. 90
12. Date and Time ..................................................................................................... 92
The Function os.time ..................................................................................... 92
The Function os.date ..................................................................................... 93
Date–Time Manipulation .................................................................................... 95
13. Bits and Bytes ..................................................................................................... 97
Bitwise Operators .............................................................................................. 97
Unsigned Integers .............................................................................................. 97
Packing and Unpacking Binary Data ..................................................................... 99
Binary files ..................................................................................................... 101
14. Data Structures ................................................................................................... 104
Arrays ............................................................................................................ 104
Matrices and Multi-Dimensional Arrays ............................................................... 105
Linked Lists .................................................................................................... 107
Queues and Double-Ended Queues ..................................................................... 107
Reverse Tables ................................................................................................ 108
Sets and Bags ................................................................................................. 109
String Buffers .................................................................................................. 110
Graphs ........................................................................................................... 111
15. Data Files and Serialization .................................................................................. 114
Data Files ....................................................................................................... 114
Serialization .................................................................................................... 116
Saving tables without cycles ...................................................................... 118
Saving tables with cycles .......................................................................... 119
16. Compilation, Execution, and Errors ....................................................................... 122
Compilation .................................................................................................... 122
Precompiled Code ............................................................................................ 125
Errors ............................................................................................................. 126
Error Handling and Exceptions .......................................................................... 127
Error Messages and Tracebacks .......................................................................... 128
17. Modules and Packages ........................................................................................ 131
The Function require .................................................................................... 132

iv
Programming in Lua, Fourth Edition

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

v
Programming in Lua, Fourth Edition

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

vi
List of Figures
2.1. The eight-queen program .............................................................................................. 13
7.1. A program to sort a file ............................................................................................... 52
8.1. An example of a state machine with goto ........................................................................ 62
8.2. A maze game ............................................................................................................. 63
8.3. A strange (and invalid) use of a goto .............................................................................. 64
9.1. Union, intersection, and difference of regions ................................................................... 75
9.2. Drawing a region in a PBM file ..................................................................................... 75
11.1. Word-frequency program ............................................................................................ 91
12.1. Directives for function os.date ................................................................................. 94
13.1. Unsigned division ...................................................................................................... 98
13.2. Dumping the dump program ...................................................................................... 102
14.1. Multiplication of sparse matrices ................................................................................ 106
14.2. A double-ended queue .............................................................................................. 108
14.3. Reading a graph from a file ....................................................................................... 112
14.4. Finding a path between two nodes .............................................................................. 112
15.1. Quoting arbitrary literal strings ................................................................................... 117
15.2. Serializing tables without cycles ................................................................................. 118
15.3. Saving tables with cycles .......................................................................................... 120
16.1. Example of output from luac -l .............................................................................. 125
16.2. String repetition ....................................................................................................... 130
17.1. A homemade package.searchpath ...................................................................... 134
17.2. A simple module for complex numbers ........................................................................ 136
17.3. Module with export list ............................................................................................. 137
18.1. Iterator to traverse all words from the standard input ...................................................... 143
19.1. Auxiliary definitions for the Markov program ............................................................... 150
19.2. The Markov program ................................................................................................ 151
20.1. A simple module for sets .......................................................................................... 153
20.2. Tracking table accesses ............................................................................................. 159
21.1. the Account class .................................................................................................. 165
21.2. An implementation of multiple inheritance ................................................................... 167
21.3. Accounts using a dual representation ........................................................................... 171
22.1. The function setfield ........................................................................................... 174
22.2. Checking global-variable declaration ........................................................................... 176
23.1. Constant-function factory with memorization ................................................................ 187
23.2. Running a function at every GC cycle ......................................................................... 190
23.3. Finalizers and memory .............................................................................................. 192
24.1. Producer–consumer with filters ................................................................................... 198
24.2. A function to generate permutations ............................................................................ 199
24.3. An ugly implementation of the asynchronous I/O library ................................................. 201
24.4. Reversing a file in event-driven fashion ....................................................................... 202
24.5. Running synchronous code on top of the asynchronous library ......................................... 203
25.1. Getting the value of a variable ................................................................................... 208
25.2. Hook for counting number of calls .............................................................................. 211
25.3. Getting the name of a function ................................................................................... 212
25.4. A naive sandbox with hooks ...................................................................................... 213
25.5. Controlling memory use ............................................................................................ 214
25.6. Using hooks to bar calls to unauthorized functions ......................................................... 215
26.1. Function to download a Web page .............................................................................. 218
26.2. The dispatcher ......................................................................................................... 219
26.3. Dispatcher using select ......................................................................................... 220
27.1. A bare-bones stand-alone Lua interpreter ..................................................................... 224

vii
Programming in Lua, Fourth Edition

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

viii
About the Book
When Waldemar, Luiz, and I started the development of Lua, back in 1993, we could hardly imagine that
it would spread as it did. Started as an in-house language for two specific projects, currently Lua is widely
used in all areas that can benefit from a simple, extensible, portable, and efficient scripting language, such
as embedded systems, mobile devices, the Internet of Things, and, of course, games.

We designed Lua, from the beginning, to be integrated with software written in C/C++ and other con-
ventional languages. This integration brings many benefits. Lua is a small and simple language, partly
because it does not try to do what C is already good for, such as sheer performance and interface with
third-party software. Lua relies on C for these tasks. What Lua does offer is what C is not good for: a good
distance from the hardware, dynamic structures, no redundancies, and ease of testing and debugging. For
these goals, Lua has a safe environment, automatic memory management, and good facilities for handling
strings and other kinds of data with dynamic size.

Part of the power of Lua comes from its libraries. This is not by chance. After all, one of the main strengths
of Lua is its extensibility. Many features contribute to this strength. Dynamic typing allows a great degree
of polymorphism. Automatic memory management simplifies interfaces, because there is no need to de-
cide who is responsible for allocating and deallocating memory or how to handle overflows. First-class
functions allow a high degree of parameterization, making functions more versatile.

More than an extensible language, Lua is also a glue language. Lua supports a component-based approach
to software development, where we create an application by gluing together existing high-level compo-
nents. These components are written in a compiled, statically-typed language, such as C or C++; Lua is
the glue that we use to compose and connect these components. Usually, the components (or objects)
represent more concrete, low-level concepts (such as widgets and data structures) that are not subject to
many changes during program development, and that take the bulk of the CPU time of the final program.
Lua gives the final shape of the application, which will probably change a lot during the life cycle of the
product. We can use Lua not only to glue components, but also to adapt and reshape them, and to create
completely new components.

Of course, Lua is not the only scripting language around. There are other languages that you can use for
more or less the same purposes. Nevertheless, Lua offers a set of features that makes it your best choice
for many tasks and gives it a unique profile:

Extensibility: Lua's extensibility is so remarkable that many people regard Lua not as a language,
but as a kit for building domain-specific languages. We designed Lua from scratch
to be extended, both through Lua code and through external C code. As a proof
of concept, Lua implements most of its own basic functionality through external
libraries. It is really easy to interface Lua with external languages like C/C++, Java,
C#, and Python.

Simplicity: Lua is a simple and small language. It has few (but powerful) concepts. This sim-
plicity makes Lua easy to learn and contributes to its small size. (Its Linux 64-bit
executable, including all standard libraries, has 220 KB.)

Efficiency: Lua has a quite efficient implementation. Independent benchmarks show Lua as
one of the fastest languages in the realm of scripting languages.

Portability: When we talk about portability, we are talking about running Lua on all platforms
we have ever heard about: all flavors of UNIX (Linux, FreeBSD, etc.) Windows,
Android, iOS, OS X, IBM mainframes, game consoles (PlayStation, Xbox, Wii,
etc.), microcontrollers (Arduino, etc.), and many more. The source code for each
of these platforms is virtually the same. Lua does not use conditional compilation

ix
About the Book

to adapt its code to different machines; instead, it sticks to the standard ISO (ANSI)
C. This way, you do not usually need to adapt it to a new environment: if you have
an ISO C compiler, you just have to compile Lua, out of the box.

Audience
This book does not assume any prior knowledge of Lua or any specific programming language —except
for its last part, which discusses the Lua API with C. However, it assumes the knowledge of some basic
programming concepts, in particular variables and assignment, control structures, functions and parame-
ters, recursion, streams and files, and basic data structures.

Lua users typically fall into three broad groups: those that use Lua already embedded in an application
program, those that use Lua stand alone, and those that use Lua and C together. This book has much to
offer to all these groups.

Many people use Lua embedded in an application program, such as Adobe Lightroom, Nmap, or World
of Warcraft. These applications use Lua's C API to register new functions, to create new types, and to
change the behavior of some language operations, configuring Lua for their specific domains. Often, the
users of such applications do not even know that Lua is an independent language adapted for a particular
domain. For instance, many developers of plug-ins for Lightroom do not know about other uses of the
language; Nmap users tend to think of Lua as the language of the Nmap Scripting Engine; many players
of World of Warcraft regard Lua as a language exclusive to that game. Despite these different worlds, the
core language is still the same, and the programming techniques you will learn here apply everywhere.

Lua is useful also as a stand-alone language, not only for text processing and one-shot little programs,
but for medium-to-large projects, too. For such uses, the main functionality of Lua comes from libraries.
The standard libraries, for instance, offer pattern matching and other functions for string handling. As Lua
has improved its support for libraries, there has been a proliferation of external packages. LuaRocks, a
deployment and management system for Lua modules, passed one thousand modules in 2015, covering
all sorts of domains.

Finally, there are those programmers that work on the other side of the bench, writing applications that
use Lua as a C library. Those people will program more in C than in Lua, although they need a good
understanding of Lua to create interfaces that are simple, easy to use, and well integrated with the language.

Book Structure
This edition adds new material and examples in many areas, including sandboxing, coroutines, date and
time manipulation, in addition to the new material related to version 5.3: integers, bitwise operations,
unsigned integers, etc.

More importantly, this edition marks a major restructuring of the text. Instead of organizing the material
around the language (e.g., with separate chapters for each library), I tried to organize the material around
common themes in programming. That organization allows the book to better follow an order of increasing
complexity, with simple themes coming first. That order came from experience teaching courses about
the language; in particular, I think this new organization fits the book better as a didactic resource for
courses involving Lua.

As the previous editions, this one is organized in four parts, each with around nine chapters. However,
the parts have a quite new character.

The first part covers the basics of the language (and it is fittingly named The Basics). It is organized around
the main types of values in Lua: numbers, strings, tables, and functions. It also covers basic I/O and gives
an overview of the syntax of the language.

x
About the Book

The second part, called Real Programming, covers more advanced topics that you can expect to find in
other similar languages, such as closures, pattern matching, date and time manipulation, data structures,
modules, and error handling.

The third part is called Lua-isms. As the name implies, it covers aspects of Lua that are particularly dif-
ferent from other languages, such as metatables and its uses, environments, weak tables, coroutines, and
reflection. These are also the more advanced aspects of the language.

Finally, as in previous editions, the last part of the book covers the API between Lua and C, for those that
use C to get the full power of Lua. The flavor of that part is necessarily quite different from the rest of
the book. There, we will be programming in C, not in Lua; therefore, we will be wearing a different hat.
For some readers, the discussion of the C API may be of marginal interest; for others, it may be the most
relevant part of this book.

Along all parts, we focus on different language constructs and use numerous examples and exercises to
show how to use them for practical tasks. We also have a few interludes among the chapters. Each interlude
presents a short but complete program in Lua, which gives a more holistic view of the language.

Other Resources
The reference manual is a must for anyone who wants to really learn a language. This book does not replace
the Lua reference manual; quite the opposite, it complements the manual. The manual only describes Lua.
It shows neither examples nor a rationale for the constructs of the language. On the other hand, it describes
the whole language; this book skips over seldom-used dark corners of Lua. Moreover, the manual is the
authoritative document about Lua. Wherever this book disagrees with the manual, trust the manual. To get
the manual and more information about Lua, visit the Lua site at http://www.lua.org.

You can also find useful information at the Lua users' site, kept by the community of users at http://
lua-users.org. Among other resources, it offers a tutorial, a list of third-party packages and docu-
mentation, and an archive of the official Lua mailing list.

This book describes Lua 5.3, although most of its contents also apply to previous versions and probably
to future versions as well. All differences between Lua 5.3 and older Lua 5 versions are clearly marked in
the text. If you are using a more recent version (released after the book), check the corresponding manual
for differences between versions.

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.

xi
About the Book

Several code fragments in the book, mainly in the initial chapters, should be entered in interactive mode.
In that case, I use a notation showing the Lua prompt ("> ") in each line:

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

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

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

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.

xii
About the Book

Finally, I must express my deep gratitude to Noemi Rodriguez, for all kinds of help (technical and non-
technical) and for illumining my life.

xiii
Part I. The Basics
Table of Contents
1. Getting Started ................................................................................................................ 4
Chunks ...................................................................................................................... 4
Some Lexical Conventions ........................................................................................... 6
Global Variables ......................................................................................................... 7
Types and Values ........................................................................................................ 7
Nil .................................................................................................................... 8
Booleans ............................................................................................................ 8
The Stand-Alone Interpreter .......................................................................................... 9
2. Interlude: The Eight-Queen Puzzle .................................................................................... 12
3. Numbers ....................................................................................................................... 15
Numerals .................................................................................................................. 15
Arithmetic Operators .................................................................................................. 16
Relational Operators .................................................................................................. 17
The Mathematical Library ........................................................................................... 18
Random-number generator .................................................................................. 18
Rounding functions ............................................................................................ 18
Representation Limits ................................................................................................. 19
Conversions .............................................................................................................. 21
Precedence ............................................................................................................... 22
Lua Before Integers ................................................................................................... 22
4. Strings ......................................................................................................................... 24
Literal strings ............................................................................................................ 24
Long strings ............................................................................................................. 25
Coercions ................................................................................................................. 26
The String Library ..................................................................................................... 27
Unicode ................................................................................................................... 29
5. Tables .......................................................................................................................... 33
Table Indices ............................................................................................................ 33
Table Constructors ..................................................................................................... 35
Arrays, Lists, and Sequences ....................................................................................... 36
Table Traversal ......................................................................................................... 38
Safe Navigation ......................................................................................................... 38
The Table Library ..................................................................................................... 39
6. Functions ...................................................................................................................... 42
Multiple Results ........................................................................................................ 43
Variadic Functions ..................................................................................................... 45
The function table.unpack .................................................................................... 47
Proper Tail Calls ....................................................................................................... 48
7. The External World ........................................................................................................ 50
The Simple I/O Model ............................................................................................... 50
The Complete I/O Model ............................................................................................ 53
Other Operations on Files ........................................................................................... 54
Other System Calls .................................................................................................... 55
Running system commands ................................................................................. 55
8. Filling some Gaps .......................................................................................................... 57
Local Variables and Blocks ......................................................................................... 57
Control Structures ...................................................................................................... 58
if then else ....................................................................................................... 58
while ............................................................................................................... 59
repeat ............................................................................................................. 59
Numerical for ................................................................................................... 60

2
The Basics

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
Random documents with unrelated
content Scribd suggests to you:
dark and nearly lost many of my trek oxen, in their
eagerness to get at the water, which is twenty feet from the
surface. They were supplied by sending my boys down with
buckets, by that means filling a hole dug out for the oxen to
drink.

These pits are fifty miles north of Kakaman’s drift, and


twenty-five miles on is Swaat Modder, in the bed of the
Hygap river, the road passing along its bed between sand-
cliffs 150 feet in height. Between these two watering-places
the Back river enters the Hygap; the sand in its bed is
mostly composed of ruby sand, which I believe would make
a fine red glass.

At Swaat Modder the right side of the river has cliffs 100
feet in height; the left bank has sand-dunes, where I found
several flint borers, many of them in a finished state, for
making holes in the shell of the ostrich egg to form beads.
Under these cliffs, in an old Bushman cave, I built a stone
house, where we remained six weeks waiting for the rains.
All this country is under the Koranna chief Puffadder, and
his people are spread over the country in small kraals. The
road still continues north, past other pits in limestone at
Bloomfontein, and at Kebeum, springbok, etc.; Abequas
pits, a large Koranna kraal; then passes over sand-dunes
for thirty miles, and arrives at Anoerogas, where there is
another Kaffir station, also a store kept by a Mr Redman, of
whom I bought some tobacco for five bags of gunpowder,
and a medicine-chest, and a variety of goods I was much in
want of. A captain of the Bundelswaarts is here, to give
notice to the Bastards to clear out. Coal abounds in this
part, garnets are found in all the river-beds, and in many
parts mixed up in the sand of the desert. Lions are so
plentiful here that it is dangerous to leave the waggon
without your rifle. A Koranna man was killed and eaten last
night, a short distance from the waggon. This station is 180
miles north from Kakaman’s drift, on the Orange river, and
three miles south of Hogskin vlei; here the roads divide.
One goes to the salt-pan, another to Meer station, a third to
Quassam on to Damaraland, a fourth past Knaas, in a
north-north-west direction to Ovampoland, and a fifth turns
south-west, and leads to Barth, where the Bundelswaarts
people live, besides others to different parts of the desert.

The other portion of the Kalahara takes in the southern part


from the Orange river to the Molapo river, 190 miles to the
north, and from the Hygap river to the Langberg range of
mountains, which is the eastern boundary of the desert,
100 miles in width. The lower portion, near the Orange
river, is better adapted for farming, as there is good grass,
and the karroo bush, upon which sheep and bucks get fat. I
purchased of Klass Lucas, the chief, living at his large kraal
on the banks of the Orange, near Orleans drift, a large
Africander sheep, for 2 lbs. of gunpowder. It weighed,
without the tail, 62 lbs., and the tail produced 12 lbs. of
pure fat.
Between this station and sixty miles to the north, called
Blue Busk Kalk, there is a fine fountain and large vlei, with
a stone kopje on the north side, where the rocks stand out
in grotesque forms of granite formation; there are in the
intermediate distance several very peculiar granite koptjies;
they average about 200 feet in height and 600 feet in
circumference at the base, large masses of huge rocks,
piled one upon another, and without any vegetation; the
country round is perfectly level; they have the appearance
of ruined pyramids; the highest I measured was 275 feet.

The mountain, called Scheurberg, is another peculiar range,


with its many pointed peaks, with wood in the valleys and
kloof; fifty miles in length and twelve in width, a road
passing through the centre, a great resort of lions, wolves,
and other beasts of prey. The continuation of the Orange
river up from the junction of the Hygap is particularly
picturesque, and in many places fearfully bold and rugged,
with lofty and almost perpendicular cliffs, with fine timber,
beautiful bushes, tree-ferns, and other subtropical plants,
which add much to the landscape.

It was at the point of the Langberg, close to the river, where


the berg seems split up into several magnificent hills,
between which and the river is almost a level but thickly
wooded space of several hundred yards in width, where we
came to outspan, for the purpose of making a new tent to
my waggon. My driver happened to capsize it into a sluit
two days before, and, to complete my misfortune, I lost
four of my best trek oxen in the river by sinking in the mud.
The next day one died of the melt sickness, and I had to
shoot another from lung-sickness.

The willow trees along the bank gave us plenty of wood,


and in two days the tent was completed. Mr Staple, who
was with me, suggested we should make a boat of wicker-
work, after our Welsh coracles, which we soon completed,
by small branches being bent the proper shape, with cross-
pieces, each tied very carefully together, forming a strong
and firm framework, over which we stretched two raw
bullock-hides, well sewn together, and when dry painted it
red,—two seats, two paddles, a mast, and lug-sail; the
length was seven feet, and twenty inches deep, in shape
like half an egg cut through lengthways. This little work
occupied us a week. When perfectly dry we took it down to
the river to launch it, not thinking of its lightness. As soon
as it was floated I brought it close to the rock, and put one
foot into the boat, and then made a spring in, when I was
no sooner in than I was out on the other side into the water,
a regular header—fortunately it was deep water. However,
on landing, I took off my clothes to dry on the rocks, and
Staples got some Koranna girls who were sitting on the
bank watching our work, to bring some stones to put in as
ballast, which took some time, as few were to be found.
I was better prepared for the second trial, being without
clothes, but this time our boat was perfectly steady, and no
wonder, for we had at least 200 lbs. of stones in the bottom
as ballast. A fine breeze was blowing up-river, which was
nearly a mile wide: fixing our little mast and lug, we started
on our first voyage, steering by a paddle. This being the
first boat that ever floated on the Orange river, I consider it
worthy of recording. Our little craft acted splendidly. The
astonishment of the Bushmen, Korannas, and the blood
Kaffirs living on the bank, who came down to see the white
man’s floating-house, was amusing; they shouted with
delight as we sailed away up-stream; the women in
particular were the loudest in their admiration. After
spending some hours sailing up and down, exploring on the
islands, shooting ducks and geese, we returned to our
handing and carried our boat to camp, after taking out the
ballast. As we were in a lovely spot, well sheltered by trees,
and only a short distance from several small kraals, where
we could obtain milk, we determined to remain some time
to explore the neighbourhood, shoot and fish, and enjoy
this wild, independent, and delightful free and easy life.

There were several families of blood Kaffirs who had


permanently established themselves on the banks of this
river. They originally came from the Cape Colony; the men
were perfectly naked, and the women also, with the
exception of a piece of skin round the loins, which was of
very little service as a covering; the Korannas and Bushmen
the same. In the evening we had two fires, one for us and
one for our boys, having two waggons, a cart, and many
oxen and sheep to look after. We had eight servants,
composed of Hottentots, Korannas, Bushmen, and a Cape
half-caste; consequently, when we were all assembled
round the fires, with the addition of our neighbours, who
never failed to visit us at feeding-time to come in for
snacks, we formed a large gathering of as romantic and
unique a party as could well be collected at any picnic. The
ladies present were of all colours, from yellow to black;
many of them well-formed and good-looking, others were of
every type of ugliness.

The Kaffirs were models of symmetry, and a much superior


class to the others. Having an unlimited supply of wood, our
fires lighted up the trees, bush, and many of the near rocks,
leaving the lofty mountains in shadow, looking black and
grim against the sky,—a grand picture for a Turner. I made
an attempt to portray it on canvas, but my humble efforts
could not do justice to this beautiful and wild scene.

So enjoyable was this mode of life, what with sketching,


exploring, fishing, and shooting, besides the daily sail on
the river, visiting the islands, and the opposite shore,
geologising and reading under the overhanging trees as the
boat floated quietly with the gentle current, I determined to
waste three or four months on its banks, as I was following
the river down for 300 miles, which would occupy that time
to thoroughly enjoy it, and give me ample opportunity of
indulging in this wild and free life. The boat was fastened on
to the back of my waggon, when treking down by the river.
When outspanned, it was taken down to the water,
sometimes crossing over to the Colony side to visit the
blood Kaffirs, to obtain milk and purchase the large
Africander sheep. The people would come down to see
where we came from, and when they saw the boat and us
getting into it and paddling away with our two sheep, their
shouts of astonishment were amusing.

When travelling, it was always in the morning for a couple


of hours; that was our day’s work, the rest being employed
in various ways as described. At one outspan, close to a
small Koranna village, we as usual took the boat down to
the river that we might, in mid-stream, enjoy our daily
swim, and crossed over to some Kaffirs. They were entirely
naked, nothing whatever to cover them; the women
brought us some thick milk. They had heard that some
white men were coming down, and told us that the
Korannas intended to stop us, and not allow us to proceed.
On returning to the waggons, we found several of those
people sitting round our fires, evidently come to overhaul
us, but they were very civil; they had been getting out what
information they could from our boys.

Forewarned is being forearmed; we looked up our rifles and


ammunition, to be ready for any surprise, as we intended to
fight our way down stream if opposed. But there was no
sign of opposition on their part. They were much amused at
a sketch I had been making of them as they were sitting
round the fire in their half-naked state. They each wanted
me to take them individually. Many I did, for practice, and
to embellish my journal, for we do not meet with such
picturesque groups every day. I therefore made the best
use of my opportunity. Both sexes are great swimmers, and
would follow me some distance. As I sailed from the shore,
I took one or two out occasionally in the boat to help me in
fishing and other work, when my own people were out
hunting up game to keep my larder full. So that, from being
shy at first, they became almost too friendly, which, under
existing circumstances, I permitted. Their primitive mode of
living is very simple. They marry at twelve years of age, if
living together as long as it suits them is called marriage.
No divorce courts are needed in these parts.

Our next trek was to avoid the high mountains which


terminated on the river-bank in enormous cliffs. We
therefore had to go round through the gorges and over
steep and stony hills—no roads in this wild country—and
outspanned for the night close to a mountain stream
surrounded by lofty hills, covered with bush. As night
advanced, the different wild animals began to move about;
the red cat, a kind of panther, the wolf-jackals, and
porcupine were very plentiful. At night when the camp-fires
have burnt nearly out, and all the boys are rolled up in their
blankets fast asleep, every sound is distinctly heard. The
mountains contained many leopards, and they are very
dangerous, and will not hesitate to attack if you are alone.

These hills were the home of the wild Bushmen, who war on
all living things. They differ from other Bushmen; they are
of a reddish-black colour, and stand four feet four inches in
height. They live in the caves amongst most inaccessible
parts of these mountains. They use the bow and arrow. Few
are now left, as far as we know, for they never show
themselves, and keep as much away from mankind as the
beast of the forest.

Travelling on through mountain passes, we arrived at a


native station where the chief, Klas Lucas, lived, who
claimed all the country north, to the Kuruman river, which is
a wild district, having several isolated hills, and being scarce
of water, particularly towards the Kuruman and Molapo
rivers. Large pans are distributed over this waste, but water
is seldom found in them, except in the rainy season, from
January to May. Large herds of game, and also the ostrich,
are occasionally to be seen, but are difficult to approach, as
they are constantly being hunted by the Korannas,
Bushmen, and Griquas, living at the kraals near the Hygap
and Orange rivers, and along the mountains of Scheurberg.
Limestone and granite are the only rocks to be found over
this extensive region.

The Kalahara, to the north of the Molapo, up to a short


distance of Lake N’gami, the Langberg range of mountains
continues northwards in broken and detached hills through
a wild country, unfrequented, except by native hunters, who
visit it from the Bechuana side on the east, and those living
in the desert and the Bastards at Meer. The ostrich is less
hunted here, and consequently more plentiful. Lions seem
to have it all their own way, for they are more numerous
here than in any part I have seen; not only at night, but in
broad day, they make an attack on your oxen. One full-
grown male lion seized one of my black oxen, not 300 yards
from the waggon, in some low bush at mid-day. Our
attention was called to the bellowing of the ox and the rush
of the others towards us. The lion was on the ox, having
seized him by the back of the neck; one hind-foot of the
lion had torn open the flank, and the other across the back,
when the ox dropped. In a few minutes I was at his side
with my double-barrel rifle, and sent two bullets into his
heart, when he rolled on the ground quite dead. The ox had
to be shot also, for his bowels were protruding from his
side; he was one of my best oxen. We saw several others a
short distance off, but they disappeared after a few shots
were fired at them. As we treked over the veldt, we came
upon several remains of game on the ground, which the
lions had killed and eaten.

There are many beautiful plants and flowers in these parts.


We were frequently crossed by border tribes who go in to
hunt, but they do not remain. They may be seen
occasionally in small parties traversing the desert, with one
or two pack-oxen loaded with dried game and such feathers
as they may have obtained by the rifle or stolen from the
Bushmen they may have surprised. If they catch a
Bushman, they conclude he has feathers,—if not with him,
he has them hid in the sand. They take from him what he
has, and then, to make him give up what they believe he
has concealed, they torture the poor wretch by putting a
finger or a toe in the fire until the pain is so groat he tells
where he has hidden them. If he has none, they believe he
is telling them false, and go to such extremes, that they will
burn the hand or foot until they are consumed, believing
the victim is obstinate and will not tell where they are.

I have a Bushman I engaged to look after the waggon with


one foot entirely burnt off, and a Bush boy with four fingers
of the right hand served in the same way. The man came to
me and asked to be employed, and said he would show me
the waters. He brought his two daughters with him; their
mother was dead. The girls’ ages, as well as I could guess,
were fourteen and sixteen. I employed them on various
duties about the waggons, and found them very willing to
learn. I had now a large family to provide for; my own eight
boys and seventeen Bushmen, including six women and
girls, which was a great help, as they took me to watering-
places unknown to hunters, and were my guides to places I
should not otherwise have visited. I found if you treat these
people well, they are willing to assist in any way. They are a
very small race, seldom exceeding four feet ten inches in
height. When old, which is at the age of forty, they are very
ugly. Their food consists of game, which they kill with their
bows and arrows, eggs, roots, mice, locusts, insects, frogs,
land-turtle, and anything they may pick up.

When I was in the desert in 1872, I had one of the chief


Bushmen captains engaged with many of his people to hunt
for me. Hearing of the atrocities committed on these
Bushmen by the border tribes, I told him to collect a few of
the injured ones, and bring them to my waggon, that I
might see them. In a week he collected fourteen, all, more
or less, having lost a hand or fingers, a foot or a greater
part of it. One Bushman had a red-hot iron ramrod forced
through his body under the arm-pit and it came out on the
other side. I saw the skeleton a few days after it occurred.
Some are shot down, and the children stolen and taken for
slaves. They are also tied to stakes and burnt to death, and
I was taken to the places where these crimes had been
committed, and saw the remains and the site of the fire.
Having satisfied myself as to the correctness of all these
statements from personal inspection and from more than
fifty Bushmen who told me of others equally horrible, all of
which I noted in my journal, I was frequently importuned by
these people to become their chief, which I declined. I was
then asked to write to the Great Mother (the Queen) to
solicit Her Majesty’s protection, and take them over as her
children. This, I saw, was impracticable. I then told the chief
head-men to call all the Bushman families together near at
hand, at a drift where I had had the bad luck to get my
waggon capsized, and where there was plenty of water, and
to meet me there at the full moon a fortnight hence.

True to the appointment, seventy-seven of the head-men


and their families were there, forming a large camp, and as
quiet and orderly as any assemblage of people could be. I
took down the probable number there would be within a
radius of seventy miles, from Klasson, the chief spokesman,
which numbered 3986.

They stated, if the Great Mother could not be written to,


would I write to the Great Chief at the Cape? This I agreed
to, and told them I would write out a petition which they
would sign, and I would forward it with a letter explaining
the circumstances under which it was sent to his Excellency
Sir Henry Barkly, detailing the atrocities, and praying to be
taken under English protection, which was in due course
forwarded, and some months afterwards I received a reply
from his Excellency, stating “he had received the petition
and my letter, but as the Kalahara desert was so far
removed from the Cape Colony, he could not see how it
could be done at present, but at some future time it might
be considered.” And from that time these peacefully-
disposed people have been left to the tender mercy of the
border tribes. His Excellency, it appears, did not know that
the Kalahara desert joined the northern border of the Cape
Colony, which shows how little interest was taken to
ascertain the true position of the country from which the
petition was forwarded.

The country to the west of this region up to Damaraland,


200 miles, up to the mountain regions of that country and
Great Namaqualand, is undulating, with vast stretches of
wood and open plains; isolated hills of granite and
limestone in other portions. One extensive district was
covered with water-worn pebbles, garnets, agates, and
other beautiful stones, also large broken pieces of stone of
a rich crimson colour. When broken small cubes of iron
pyrites like gold are embedded. The grain is very fine, and it
would make splendid vases, cups, plates, or any other
ornaments.

I had been foolish enough to collect specimens of every


kind of stone, until my waggon became so full and heavy
that I had to throw them away. I made a collection of 3000
agates of every variety of colour and shape, which had to
be abandoned. Many cairns or graves are seen with heavy
stones surrounding them.

Not far from them are several ancient stone huts, built upon
a small hill, that must have belonged to a former race, and
close to a dried-up river. Some of the stones are six feet in
length, two feet wide, and one and a half thick. They were
placed on end and covered in. None of them would hold
more than four persons. They are in small clusters of seven
and eight together, and some less. They were covered in
with large stones, that have long since fallen. No account
can be obtained of them from the Bushmen. Their huts are
a few sticks stuck up with grass thrown over.
Several fresh Bushmen and women came to my camp this
morning. Some of the young girls were very good-looking,
and with a profusion of native ornaments upon them made
entirely of ostrich eggs. A perfect set comprised a tiara,
three inches in width, for the head; a broad necklace, six
bracelets on each arm, and eight anklets or bangles to each
leg, and finally, a rope of beads of sufficient length to go
round the loins twice and fastened in front with a piece of
rimpey. These constituted the entire dress of one of the
girls. She looked like a young African queen, and it had the
effect of making her look half pretty.

I bought two sets for six yards of print each. I think there
cannot be less than 8000 beads in each set, between each
bead a piece of leather of the same size, which becomes
black, so that they look like black and white beads, which
has a good effect upon their black skin. They were delighted
with the exchange. When disrobed of their ornaments, they
threw the print over their shoulders like a mantle. The
ornament had the appearance of having been handed down
from generation to generation. At Narukus, on the Nosop
river, I came upon a family of Bushmen, ten in number, of a
different type to those I had in my service, evidently a
lower caste. They have no forehead; the wool on their
heads comes close down to the eyes, and the head falling
back like a baboon; projecting mouth, small nose, a sort of
hair or wool all over the chest, arms, and legs; their eyes
are small and restless, watching every movement that is
going on; the tallest man did not exceed four feet four;
their skin was of a reddish-brown. A few old skins, broken
ostrich eggs, and bows and arrows, seemed all they
possessed of worldly goods.

They would have decamped and hid in the bush, but I sent
some of my Bushmen and brought them back. I asked my
own boys, if they were their brothers, meaning of the same
race; they repudiated the idea, and said they were monkeys
not men, and told me there were very few ever seen, it was
very seldom they ever came upon any; they eat carrion.
They are evidently a distinct race from the Masara Bushmen
who are largely distributed over the desert. One of the
women had a baby not much bigger than a half-grown
kitten; all of them were destitute of clothing.

The country through which the Oup and Nosop pass, in


many places is very pretty and picturesque. At a fountain
on the branch of the Oup, I remained several days to hunt,
to supply so many people with food.

24th February, 1872. A terrific thunderstorm broke over us


soon after midnight, and continued until six this morning,
striking and splitting up some large trees a short distance
from our camp, and it rent into three a large rock which
stood out alone from the base of the hill. The country was
swamped with water, the oxen at one time standing half
knee-deep in it. My escort of Bushmen and their families for
once in their lives had a good shower-bath. The baboons
also in the hills must have felt its effects, for they could be
heard far and near, with their half-human grunts.

My Bushman with the stump foot told me he could


understand the baboon language, when, they are frightened
or hungry, or are to meet together to defend themselves
against an enemy, or to meet to play, and he knew well
what they said and could talk to them. The old ones beat
the young baboons with sticks if they do anything wrong,
such as stealing the food from others. The Bushman’s
language has a great many grunts in it similar to these
animals.
I find there are four types of Bushmen in this desert; the
lowest is the one already described with no forehead and
half wool and hair on their bodies and legs. The second is
the wild Bushmen, who live in the mountains near the
Orange river, also mentioned, who war on all men, but they
are of good form, without hair. The third is the Masara Bush
family, also of good proportions and of gentle dispositions,
inoffensive and harmless, ready to help or do anything, and
they make good servants. It was this tribe I had with me in
my wanderings. The two girls I took in charge made good
cooks, washed the clothes, and mended them. The fourth is
much taller and well-formed, great rascals, who cannot be
trusted with anything; they inhabit the eastern portion of
the desert, and down by Langberg. A similar tribe were
those Sir Walter Currie drove out of the colony, some of
whom I fell in with at Quassam under Coche Africanda. The
Bushmen of the northern Kalahara are much the same as
the Masara, every one of them quite distinct from the
Drakensberg Bushmen, whose form and colour differ
entirely from the others, which I believe to be a distinct
race, and which I described in the first chapter.

One amusing circumstance I omitted to mention in


connection with one of these wild Bushman boys, when at
Swaart-Modder in the Hygap river, where we had built a
stone house under the cliff to keep our goods during our
stay there. A young Bush boy came in the evening to the
camp and made himself comfortable by the fire. After some
time my boys asked him where he came from, but he would
give no reply. At last they got from him that he had run
away from his people, because his mother had burnt his
fingers for stealing, and he came to get something to eat.
This was his second visit, and as he had been well fed
before, he came again, but managed at the same time to
steal some of my boys’ food. On this evening, we had a
young man from the colony to drive the cart and look after
the boys, and as our stone house was infested with large
mice, this young Hancock was catching them in an iron pot,
and throwing them out amongst the boys for amusement.
As one by one, up to seven, were thrown, this Bush boy
picked them up, put them into the red-hot ashes to cook,
and, when half-done, ate them as they were. Thinking he
must be awfully hungry, I told my cook to put on a pot and
cook some Boer meal, which is wheat ground but unsifted;
two pints of this were cooked in water, and when ready it
was set before him and soon disposed of.

After all the people were asleep, he stole the food they had
left, and in the middle of the night, sucked three of my
goats dry. The following morning he was not to be found,
and for nearly a month we did not see him again; when we
had travelled 100 miles north, and were outspanned, he
presented himself again, as if it were his first visit. We
found out he had lived in the bush, existing on a wild water-
melon, called shama or kongive, and had kept us in sight as
we travelled. I tried to tame him, but it was of no use; his
age was about eleven years. He kept with us off and on for
three months, then disappeared altogether; the lions would
not let him remain long, without making a meal of him.

We were now travelling through a very pretty part of the


desert, open glades and timber trees, lofty pyramidal hills,
partly covered with bush, fine grass, with white feathery
tops, no inhabitants; a wild and picturesque region, crossing
open plains, then gentle rises with low bush; in the
distance, mountains with their lofty peaks fading away into
nothing. The perfect calm and silence that pervades
everything around, the variety of game quietly grazing in all
directions, the very loneliness of my position, being many
hundred miles from any white man, surrounded only by my
own Bushmen, and those who accompany me, living in all
their natural innocence as their forefathers lived in
prehistoric ages, add immensely to the pleasure one feels in
viewing a scene so novel and so seldom to be enjoyed.

The country as we approach Damaraland becomes more


wild and broken, lofty mountains come into view as we
advance westward. We were nightly visited by lions and
wolves, which kept us constantly on the watch, and our
fires kept lighted. It is an anxious time, particularly when in
the stillness of the night we hear their roar at no great
distance, in answer to others far away. The roar of a lion in
the still evening can be heard miles away.

One morning about eleven o’clock, as we were outspanned


in an open plain about 300 yards from a small pool of water,
our oxen, horse, and a few goats grazing on the opposite
side of the waggons, several of my boys asleep, the
Bushmen and the women cooking some flesh in the hot
embers, we saw seven lions leisurely walking up to the
water. After drinking, they went to a small rise, bare of
grass and sandy, and commenced playing, some lying
down, others jumping over them, growling in their deep
bass voice, acting the same as cats at play. This lasted
twenty minutes, when they as leisurely walked away, taking
no notice of us whatever. If I had fired and wounded any,
they might have come at us, which would have been
dangerous to our oxen, by dispersing. When an ox or a
horse smells a lion, they will bolt away anywhere, and some
might have been lost, therefore we left them alone and
enjoyed so unusual a sight, watching the movements of
these beautiful but dangerous kings of the forest, in their
wild and natural state in the wilds of Africa.

The Kalahara, that portion, on the borders of Damara and


Ovampolands for 300 miles, becomes much more densely
wooded and hilly. Some of the mountains attain a height of
8000 feet, in which lead, copper, iron, and coal, also
limestone, both white and dark grey, crop up everywhere.
Granite forms the hills. The Black and White Nosop and the
Elephant river, and their several branches, drain all this
region. The country is very dry, rain seldom falls, and when
it does, it comes down with a rush, which soon passes
away; but the vegetation is excellent, fine timber and thick
bush predominate over this vast but little inhabited country.
The road from Walfish Bay on the west coast passes
through, in an easterly direction, to Lake N’gami, Zambese,
Ba-Mangwato, and other territories on the east. The road is
difficult to travel for want of water, but when the country is
more opened up, means will be found for procuring it by
well-sinking and pumps, to make it as easy to travel as any
part of Africa. There are several permanent watering-places
now along this route. In the dry season it is three and four
days’ trek between them, but as it is limestone nearly all
the way, water can be procured by digging wells. The
country is subject to drought, more particularly in the
southern portion of the desert, consequently there is more
game to be found in the northern region. Elephants are
seen in troops of two or three hundred, also the zebra, and
the various antelopes, giraffes, rhinoceros, wild boar, and
others.

The country is very favourable for rearing cattle; large


numbers of horses are yearly taken through the desert from
the Orange River Free State to Damaraland, and exchanged
for Damara oxen, which are found to make the best trek
oxen, having small hoofs and being nimble on their feet;
they are compact and strong. Another advantage is that
they are bred on sour grass; when they arrive in the colony,
it is sweet, which improves their condition.

April 30th.—At Hoab, a lovely, calm morning, after a heavy


rain last night, at a vlei; there are several large ones in this
open grass country that contain water at this time of year,
being the rainy season. This station is on the desert-track
from the lake to Ovampoland.

Outspanned under a large tree; boys employed skinning a


koodoo, killed early this morning by one of my Bushmen
guides with his poisoned arrow. The arrow-head is of bone,
very small, the shaft two feet in length, and the bow two
feet six inches. The shaft, close to the head for four inches,
is covered over with their poison, which, in penetrating the
flesh, paralyses the animal; the flesh killed in this manner is
very good, and has no bad effect on those who partake of
it. Several Bush people have come to our camp begging for
food; they look poor and miserable, their only covering
being a few pieces of ragged skins thrown over their
shoulders. Several of the grown-up boys and girls had not
even that to cover them. They are complete wanderers in
the desert; no home or fixed abode, but live on roots,
berries, insects, and anything they may by chance shoot: I
gave them some flesh, and a fire to cook it.
The hot winds, which are very oppressive, come in waves,
and are very enervating, more particularly in the dry
season, when they dry up everything. The wood-work of the
waggons shrinks to such an extent, that the wheels are
kept together by ropes of raw hide bound round them; and
your own system becomes so dried-up, that the natural
functions of your body partly cease to act; to remedy this,
fat is absolutely necessary, and nature craves after it. You
will see the desire after fat in the native tribes, not only to
grease their skin, to protect it from the sun, but to use as
medicine.

When treking, some days afterwards, we were overtaken by


one of those gigantic whirlwinds so common in all tropical
countries. We were entirely enveloped in it; everything that
is loose in the way of clothes is carried up hundreds of
yards. One of my boys had his hat taken by the current,
and it fell nearly a quarter of a mile from where he lost it.
Many of these whirlwinds may be seen at one time passing
over the desert.

At this outspan, late in the afternoon, sitting on my camp-


stool where my boys were skinning a buffalo I had shot, I
saw in the distance a Bushman coming. When near enough
to distinguish, I saw it was a Bush girl, tall and well-made,
and for a wonder quite fat; she was marked over every part
of her body—face, legs, and arms—with white stripes, like
the stripes of the zebra, and had nothing else on. She came
up, holding out an old piece of leopard-skin. My Bushman
spoke to her, but could get no answer. I gave her some
tobacco, when, dropping the skin, she walked to the fire
and sat down. We gave her a piece of cooked meat,
thinking she might be hungry, which she took, and after
remaining some ten minutes, got up and walked away in
the same direction she came; but no word could we get
from her. She was even strange to my Bushman. It was a
strange visit, and a strange mode of decorating herself. The
only other occasion on which I fell in with Bushmen so
marked was more to the cast, nearly 300 miles, when
nearly a dozen came to my waggon, to tell me I had that
day ridden over a grave where a few days before they had
buried one of their people. The stripes may have something
to do with death, but the Bushmen I have spoken to know
nothing of such custom.

One of the vleis, which was full of water, appeared to be full


of frogs, from the noise they made at night; going down,
next morning, I found several small ones, having a peculiar
appearance. Catching one, which was very narrow in its
body compared to its length, and having a short tail, I
concluded at once from its general shape that it was half-
lizard and half-frog. It had all the action of the frog in its
long leaps, without any attempt at running; all the others
were of the same form, and with tails. I brought it to the
waggon to take its measure, viz. from front of head to
commencement of tail one and a half inch, length of tail
three-quarters of an inch, beautifully marked with green
and light-yellow spots. Not having any means of preserving
it, I took it back to the vlei, where there were hundreds
sitting on the bank; as I neared them they jumped into the
water and disappeared. The Bushman brought in to-day
several ostrich eggs, quite fresh from the nest, which we
had cooked in our large iron pots, mixed with a little flour—
a kind of omelet; one is sufficient for three persons. The
Bushman took me to a nest that the old birds had been
sitting on for some time; there were eighteen in the centre,
and fourteen on the outside, formed into a circle round
them, which are kept for food for the young birds, which
lasts them a few days when hatched; the hen bird then
takes and teaches the chicks to eat grass.
Thursday, 18th.—Our camp was visited by a party of traders
and Korannas on their way from Meer down South—the
chief Puffadder, old Mr Ryland, from Kopie’s farm and Low
Blaat, four waggons, and a lot of cattle, horses, and sheep.
They remained the afternoon and night, and started early
the next day for Kebeum. They told me a trader on the
border of Great Namaqualand, going down to Walfish Bay,
had been shot, and his waggon and everything seized by
the Gobabis Hottentots for plunder, and that the country
was in a fearful state of tribal wars. I told them of my little
affair with the Bushman Hottentot at Quassam; they said I
was most fortunate to escape as I did, particularly with all
my belongings, as they are noted as a nest of thieves, and
have robbed traders of everything.

I left them for Abequis pita, which are in limestone; it is a


Koranna station, under the chief Puffadder. The country is
open and flat; the grass in many places was up to my chin
with white feathery flowers; at a distance it looks like snow.
The road is very good for waggon travelling, and around
Springbok fountain the scenery is very pretty. At Abequis
pits the Korannas have many huts, and seem to be doing
well; they have flocks of goats, and a few Africander sheep.
They brought me some very good feathers, which I took in
exchange for powder and caps; many of them have the old
flint gun, which would be a curiosity now in England.

The winters here are warm; it is now mid-winter,


thermometer in the shade 68 degrees. The men wear old
leather trousers, which constitute their dress, the women an
old blanket thrown over the left shoulder, and brought
round and held in front by the hand. Overmodesty is not a
failing with them. They were very civil, supplied my people
with goats’ milk, and I gave them what they much needed,
tobacco, as the women are great smokers. Dozens of them
will sit or be lying round my fire, having only two or three
bone pipes between them, each taking a few puffs and
passing it on to the next, until all have had a turn; then
they begin again, the old ones keeping a pipe to
themselves. My maids, Topsey and Nina, the daughters of
my Piet, knew these people, therefore I got on very well,
Piet also lived once with them. The country towards the
south and west was a level plain as far as the eye could
see.

The next morning after the second day, started to the


northwards; we passed a large vlei on the left, six miles
from the Koranna station, which is the commencement of
the sand-dunes. The dunes are small until sixteen miles of
country are passed, then they assume great proportions. A
mile to the left is another vlei, where we filled our water-
casks and gave the oxen water, and remained the night, to
have a clear day to pass over them. There were three
Griquas’ waggons outspanned, each waggon was full of
women and children, each Jack had his Jill, and each a
baby, plenty of little naked children of both sexes. They told
me they were on the trek to the Orange river. These people
are always quiet and civil, they exchanged a fat sheep for
some tobacco. All the country, including the sand-dunes, is
limestone with sand above, and full of low bush, many large
and small land-shells are mixed up in the sand.

July 17th.—The Griquas left early in the morning, and we


started to cross the sand-dunes. A fearful road, their sides
are about at an angle of thirty, and every time we ascend
one, we have to put two spans of twenty-eight oxen in, to
pull one waggon up at a time, which causes much delay
shifting them backwards and forwards, as each dune rises
from 150 to 200 feet in height, with deep sand in the road,
the wheels sinking nine inches into it. After struggling over
these for five hours, the oxen were done up, and we
outspanned for the day at another large dry vlei, but on the
bank a small spring of water was issuing, sufficient for the
oxen and ourselves, a grand discovery, as we did not expect
to find any until we had got clear of this heavy road. A short
distance from the water were several families of Bushmen,
sitting round a large fire; some of them had most
extraordinary figures, thin calfless legs, prominent chests
and abdomen, altogether different from the other Bushmen
of the desert, and the colour of their skin was much lighter.
A thin band of leather round their loins, and a skin over
their shoulders was their only covering; long bundles of
skins rolled up with several spears were lying on the
ground. The food they live on in a great measure gives
them this peculiar formation. They had the short bow and
arrow, and quivers made of skins, full of arrows, cleverly
made with bone heads, all smeared with poison. They
appear to be half-Bushman, half-Koranna.

I started the next morning, and after toiling for several


hours, rested, and again went on, crossing those lofty
ridges until dark, outspanned for the night in a deep hollow,
where there was plenty of good grass, and trees, and dead
wood for fire. Our trek this day was about eight miles; two
great fires were made, and our little party of twenty-six all
told, made themselves comfortable over their supper, and
at ten all were fast asleep. But we did not get much rest,
the lions kept round the camp making a great noise, and
being surrounded by these hills and thick bush, we were the
greater part of the night obliged to keep a sharp look-out
that none of our animals were taken. Early the next
morning I took my rifle and mounted one of these sand-
dunes before inspanning, and found from the base to the
summit registered 204 feet. But what a sight when I looked
round; as far as the eye could see, nothing but these
immense sand-dunes in every direction, here and there
open patches of yellow sand and bush, a wild, rugged, and
howling wilderness, that appeared interminable, the fit
abode for savage man and more savage beast, and here we
find them, man in primitive nature, as low a type as the
world can produce, little removed from the beast, for it is
here I have met those wild men which I have described
elsewhere; they are partly covered with short woolly hair,
and have no forehead, the scant wool reaching the eyes.
They are rarely now seen, even by the Bushmen of the
desert, as they have repeatedly told me, and here they may
find a home for many years to come, for no other living
man will fix his residence in such a region of desolation,—

“A wilderness howling and drear,


Forsaken by man from famine or fear.”

Pringle.

On our trek we started many head of game, which are


easily killed by the Bushman arrow, and with these and the
many wild fruits they manage to exist. It has taken four
days to cross this wild and hilly region which extends over
an area as far as I have explored it, fifty miles from east to
west, and nearly forty north to south: the home of the
leopard and a legion of wild tiger-cats, that are spotted or
striped,—their skins make beautiful karosses. On leaving
these dunes we come upon a level plain of limestone, which
we have ten miles to cross, where there are several
watering-places, fountains they may be called, and enter
sand-dunes again for some fifteen miles, and then come
upon a bush country, with gentle rises and low wooded bills
with isolated conical hills of granite. Close to the hills, I
outspanned near a swamp; the noise from the bull-frog
kept us from sleep. They are monsters, a foot across the
back and quite black. The Bushmen eat them; they would
form a fine dish for our French neighbours.
The weather is very fine, like an English spring day,
everything seems springing into life. Clouds begin to collect
on the horizon, and the sunsets are most brilliant, purple
and gold, forming celestial landscapes of the most gorgeous
hues. There are many ostriches to be seen on the flats, but
the country is so full of holes, partly covered with grass,
that it is dangerous to follow them. Far and wide in every
direction the character of the country is the same, which we
pass through up to Meer, the Bastard station.

We passed several small Bushmen kraals; the women and


children as we approached hid themselves in the bush, but
when they found we were friendly, and giving presents to
the men, they came forward. At one we remained a few
days to buy feathers, during the time my Bushmen and the
girls soon made friends with them, and dancing went on in
their fashion every evening. These women daub their faces
and bodies with black stripes, which they consider
ornamental. Their natural colour is half black, consequently
these stripes show out prominently; they are a mild, timid
race, very good-natured, willing to do anything, and, if left
alone by the border tribes and the Bastards, their lives
would be happy; their wants are few and easily supplied,
clothes they do not require, the climate at all seasons of the
year is seldom colder than our English summer, and, as
these children of the desert are constantly shifting their
locations, huts are not required, or only of the most
primitive kind, a few sticks stuck in the ground, and the
long grass thrown over them. This is a portion of the central
part of the Kalahara.

When we arrived at Meer, all the people were out ostrich-


hunting close round the village, a great excitement, the
birds running in all directions, and the Bastards after them
on their horses; they managed to shoot seven; the others,
about fifty, made their escape.
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!

ebookname.com

You might also like