100% found this document useful (11 votes)
41 views

(Ebook) Programming in Lua by Roberto Ierusalimschy ISBN 9788590379867, 8590379868 2024 scribd download

The document provides information about the ebook 'Programming in Lua' by Roberto Ierusalimschy, including its ISBN numbers and download links. It also lists various other Lua programming ebooks available on the website ebooknice.com. The content of 'Programming in Lua' covers a wide range of topics related to the Lua programming language, including basics, data structures, and advanced programming techniques.

Uploaded by

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

(Ebook) Programming in Lua by Roberto Ierusalimschy ISBN 9788590379867, 8590379868 2024 scribd download

The document provides information about the ebook 'Programming in Lua' by Roberto Ierusalimschy, including its ISBN numbers and download links. It also lists various other Lua programming ebooks available on the website ebooknice.com. The content of 'Programming in Lua' covers a wide range of topics related to the Lua programming language, including basics, data structures, and advanced programming techniques.

Uploaded by

dinosrodrisp
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/ 65

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Programming in Lua by Roberto


Ierusalimschy ISBN 9788590379867, 8590379868

https://ebooknice.com/product/programming-in-lua-5894730

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Programming in Lua by Roberto Ierusalimschy ISBN


9788590379867, 8590379868

https://ebooknice.com/product/programming-in-lua-5894730

ebooknice.com

(Ebook) Programming in Lua by Roberto Ierusalimschy ISBN


9788590379867, 8590379868

https://ebooknice.com/product/programming-in-lua-42896558

ebooknice.com

(Ebook) Programming in Lua by Roberto Ierusalimschy ISBN


9788590379829, 8590379825

https://ebooknice.com/product/programming-in-lua-1669624

ebooknice.com

(Ebook) Programming in Lua by Roberto Ierusalimschy ISBN


9788590379850, 859037985X

https://ebooknice.com/product/programming-in-lua-4415838

ebooknice.com
(Ebook) Lua Programming Gems by Luiz Henrique de
Figueiredo, Waldemar Celes, Roberto Ierusalimschy ISBN
9788590379843, 8590379841
https://ebooknice.com/product/lua-programming-gems-6618486

ebooknice.com

(Ebook) Lua Programming: The Ultimate Beginner's Guide to


Learn Lua Step by Step by Claudia Alves; Alexander
Aronowitz
https://ebooknice.com/product/lua-programming-the-ultimate-beginner-s-
guide-to-learn-lua-step-by-step-23284136

ebooknice.com

(Ebook) Beginning Lua Programming by Jung, Kurt ISBN


9780470069172, 0470069171

https://ebooknice.com/product/beginning-lua-programming-55199762

ebooknice.com

(Ebook) Lua Programming: The Ultimate Beginner's Guide to


Learn Lua Step by Step by Claudia Alves & Alexander
Aronowitz [Alves, Claudia]
https://ebooknice.com/product/lua-programming-the-ultimate-beginner-s-
guide-to-learn-lua-step-by-step-30354828

ebooknice.com

(Ebook) LÖVE for Lua Game Programming by Akinlaja, Darmie


ISBN 9781782161608, 1782161600

https://ebooknice.com/product/love-for-lua-game-programming-43150088

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

Feisty Duck Digital


Book Distribution
www.feistyduck.com

Licensed for the exclusive use of:


Eric Taylor <[email protected]>
Contents
About the Book ................................................................................................................. ix
I. The Basics ...................................................................................................................... 1
1. Getting Started ........................................................................................................ 4
Chunks .............................................................................................................. 4
Some Lexical Conventions ................................................................................... 6
Global Variables ................................................................................................. 7
Types and Values ................................................................................................ 7
Nil ............................................................................................................ 8
Booleans .................................................................................................... 8
The Stand-Alone Interpreter .................................................................................. 9
2. Interlude: The Eight-Queen Puzzle ............................................................................ 12
3. Numbers ............................................................................................................... 15
Numerals .......................................................................................................... 15
Arithmetic Operators .......................................................................................... 16
Relational Operators .......................................................................................... 17
The Mathematical Library ................................................................................... 18
Random-number generator .......................................................................... 18
Rounding functions .................................................................................... 18
Representation Limits ......................................................................................... 19
Conversions ...................................................................................................... 21
Precedence ....................................................................................................... 22
Lua Before Integers ........................................................................................... 22
4. Strings ................................................................................................................. 24
Literal strings .................................................................................................... 24
Long strings ..................................................................................................... 25
Coercions ......................................................................................................... 26
The String Library ............................................................................................. 27
Unicode ........................................................................................................... 29
5. Tables .................................................................................................................. 33
Table Indices .................................................................................................... 33
Table Constructors ............................................................................................. 35
Arrays, Lists, and Sequences ............................................................................... 36
Table Traversal ................................................................................................. 38
Safe Navigation ................................................................................................. 38
The Table Library ............................................................................................. 39
6. Functions .............................................................................................................. 42
Multiple Results ................................................................................................ 43
Variadic Functions ............................................................................................. 45
The function table.unpack ............................................................................ 47
Proper Tail Calls ............................................................................................... 48
7. The External World ................................................................................................ 50
The Simple I/O Model ....................................................................................... 50
The Complete I/O Model .................................................................................... 53
Other Operations on Files ................................................................................... 54
Other System Calls ............................................................................................ 55
Running system commands ......................................................................... 55
8. Filling some Gaps .................................................................................................. 57
Local Variables and Blocks ................................................................................. 57
Control Structures .............................................................................................. 58
if then else ............................................................................................... 58
while ....................................................................................................... 59
repeat ..................................................................................................... 59
Numerical for ........................................................................................... 60
Generic for .............................................................................................. 60
break, return, and goto ..................................................................................... 61
II. Real Programming ......................................................................................................... 65
9. Closures ............................................................................................................... 68
Functions as First-Class Values ............................................................................ 68
Non-Global Functions ........................................................................................ 69
Lexical Scoping ................................................................................................ 71
A Taste of Functional Programming ..................................................................... 74
10. Pattern Matching .................................................................................................. 77
The Pattern-Matching Functions ........................................................................... 77
The function string.find ...................................................................... 77
The function string.match .................................................................... 77
The function string.gsub ...................................................................... 78
The function string.gmatch .................................................................. 78
Patterns ............................................................................................................ 78
Captures ........................................................................................................... 82
Replacements .................................................................................................... 83
URL encoding .......................................................................................... 84
Tab expansion ........................................................................................... 86
Tricks of the Trade ............................................................................................ 86
11. Interlude: Most Frequent Words ............................................................................. 90
12. Date and Time ..................................................................................................... 92
The Function os.time ..................................................................................... 92
The Function os.date ..................................................................................... 93
Date–Time Manipulation .................................................................................... 95
13. Bits and Bytes ..................................................................................................... 97
Bitwise Operators .............................................................................................. 97
Unsigned Integers .............................................................................................. 97
Packing and Unpacking Binary Data ..................................................................... 99
Binary files ..................................................................................................... 101
14. Data Structures ................................................................................................... 104
Arrays ............................................................................................................ 104
Matrices and Multi-Dimensional Arrays ............................................................... 105
Linked Lists .................................................................................................... 107
Queues and Double-Ended Queues ..................................................................... 107
Reverse Tables ................................................................................................ 108
Sets and Bags ................................................................................................. 109
String Buffers .................................................................................................. 110
Graphs ........................................................................................................... 111
15. Data Files and Serialization .................................................................................. 114
Data Files ....................................................................................................... 114
Serialization .................................................................................................... 116
Saving tables without cycles ...................................................................... 118
Saving tables with cycles .......................................................................... 119
16. Compilation, Execution, and Errors ....................................................................... 122
Compilation .................................................................................................... 122
Precompiled Code ............................................................................................ 125
Errors ............................................................................................................. 126
Error Handling and Exceptions .......................................................................... 127
Error Messages and Tracebacks .......................................................................... 128
17. Modules and Packages ........................................................................................ 131
The Function require .................................................................................... 132
Renaming a module ................................................................................. 133
Path searching ......................................................................................... 133
Searchers ................................................................................................ 135
The Basic Approach for Writing Modules in Lua .................................................. 135
Submodules and Packages ................................................................................. 137
III. Lua-isms ................................................................................................................... 139
18. Iterators and the Generic for ................................................................................ 142
Iterators and Closures ....................................................................................... 142
The Semantics of the Generic for ....................................................................... 143
Stateless Iterators ............................................................................................. 145
Traversing Tables in Order ................................................................................ 146
True Iterators .................................................................................................. 147
19. Interlude: Markov Chain Algorithm ....................................................................... 149
20. Metatables and Metamethods ................................................................................ 152
Arithmetic Metamethods ................................................................................... 152
Relational Metamethods .................................................................................... 155
Library-Defined Metamethods ............................................................................ 155
Table-Access Metamethods ............................................................................... 156
The __index metamethod ....................................................................... 156
The __newindex metamethod ................................................................. 157
Tables with default values ......................................................................... 158
Tracking table accesses ............................................................................. 159
Read-only tables ...................................................................................... 160
21. Object-Oriented Programming .............................................................................. 162
Classes ........................................................................................................... 163
Inheritance ...................................................................................................... 165
Multiple Inheritance ......................................................................................... 166
Privacy ........................................................................................................... 168
The Single-Method Approach ............................................................................ 170
Dual Representation ......................................................................................... 170
22. The Environment ................................................................................................ 173
Global Variables with Dynamic Names ............................................................... 173
Global-Variable Declarations ............................................................................. 174
Non-Global Environments ................................................................................. 176
Using _ENV .................................................................................................... 177
Environments and Modules ............................................................................... 180
_ENV and load .............................................................................................. 181
23. Garbage ............................................................................................................ 183
Weak Tables ................................................................................................... 183
Memorize Functions ......................................................................................... 184
Object Attributes ............................................................................................. 185
Revisiting Tables with Default Values ................................................................. 186
Ephemeron Tables ........................................................................................... 187
Finalizers ........................................................................................................ 188
The Garbage Collector ...................................................................................... 190
Controlling the Pace of Collection ...................................................................... 191
24. Coroutines ......................................................................................................... 194
Coroutine Basics .............................................................................................. 194
Who Is the Boss? ............................................................................................ 196
Coroutines as Iterators ...................................................................................... 198
Event-Driven Programming ............................................................................... 200
25. Reflection .......................................................................................................... 205
Introspective Facilities ...................................................................................... 205
Accessing local variables .......................................................................... 207
Accessing non-local variables .................................................................... 208
Accessing other coroutines ........................................................................ 209
Hooks ............................................................................................................ 210
Profiles .......................................................................................................... 211
Sandboxing ..................................................................................................... 212
26. Interlude: Multithreading with Coroutines ............................................................... 217
IV. The C API ................................................................................................................ 221
27. An Overview of the C API .................................................................................. 223
A First Example .............................................................................................. 223
The Stack ....................................................................................................... 225
Pushing elements ..................................................................................... 226
Querying elements ................................................................................... 227
Other stack operations .............................................................................. 229
Error Handling with the C API .......................................................................... 231
Error handling in application code .............................................................. 232
Error handling in library code .................................................................... 232
Memory Allocation .......................................................................................... 233
28. Extending Your Application ................................................................................. 236
The Basics ...................................................................................................... 236
Table Manipulation .......................................................................................... 237
Some short cuts ....................................................................................... 240
Calling Lua Functions ...................................................................................... 241
A Generic Call Function ................................................................................... 242
29. Calling C from Lua ............................................................................................ 247
C Functions .................................................................................................... 247
Continuations .................................................................................................. 249
C Modules ...................................................................................................... 251
30. Techniques for Writing C Functions ...................................................................... 254
Array Manipulation .......................................................................................... 254
String Manipulation .......................................................................................... 255
Storing State in C Functions .............................................................................. 258
The registry ............................................................................................ 258
Upvalues ................................................................................................ 260
Shared upvalues ....................................................................................... 263
31. User-Defined Types in C ..................................................................................... 265
Userdata ......................................................................................................... 265
Metatables ...................................................................................................... 268
Object-Oriented Access ..................................................................................... 270
Array Access .................................................................................................. 271
Light Userdata ................................................................................................. 272
32. Managing Resources ........................................................................................... 274
A Directory Iterator .......................................................................................... 274
An XML Parser ............................................................................................... 277
33. Threads and States .............................................................................................. 286
Multiple Threads ............................................................................................. 286
Lua States ...................................................................................................... 289
List of Figures
2.1. The eight-queen program .............................................................................................. 13
7.1. A program to sort a file ............................................................................................... 52
8.1. An example of a state machine with goto ........................................................................ 62
8.2. A maze game ............................................................................................................. 63
8.3. A strange (and invalid) use of a goto .............................................................................. 64
9.1. Union, intersection, and difference of regions ................................................................... 75
9.2. Drawing a region in a PBM file ..................................................................................... 75
11.1. Word-frequency program ............................................................................................ 91
12.1. Directives for function os.date ................................................................................. 94
13.1. Unsigned division ...................................................................................................... 98
13.2. Dumping the dump program ...................................................................................... 102
14.1. Multiplication of sparse matrices ................................................................................ 106
14.2. A double-ended queue .............................................................................................. 108
14.3. Reading a graph from a file ....................................................................................... 112
14.4. Finding a path between two nodes .............................................................................. 112
15.1. Quoting arbitrary literal strings ................................................................................... 117
15.2. Serializing tables without cycles ................................................................................. 118
15.3. Saving tables with cycles .......................................................................................... 120
16.1. Example of output from luac -l .............................................................................. 125
16.2. String repetition ....................................................................................................... 130
17.1. A homemade package.searchpath ...................................................................... 134
17.2. A simple module for complex numbers ........................................................................ 136
17.3. Module with export list ............................................................................................. 137
18.1. Iterator to traverse all words from the standard input ...................................................... 143
19.1. Auxiliary definitions for the Markov program ............................................................... 150
19.2. The Markov program ................................................................................................ 151
20.1. A simple module for sets .......................................................................................... 153
20.2. Tracking table accesses ............................................................................................. 159
21.1. the Account class .................................................................................................. 165
21.2. An implementation of multiple inheritance ................................................................... 167
21.3. Accounts using a dual representation ........................................................................... 171
22.1. The function setfield ........................................................................................... 174
22.2. Checking global-variable declaration ........................................................................... 176
23.1. Constant-function factory with memorization ................................................................ 187
23.2. Running a function at every GC cycle ......................................................................... 190
23.3. Finalizers and memory .............................................................................................. 192
24.1. Producer–consumer with filters ................................................................................... 198
24.2. A function to generate permutations ............................................................................ 199
24.3. An ugly implementation of the asynchronous I/O library ................................................. 201
24.4. Reversing a file in event-driven fashion ....................................................................... 202
24.5. Running synchronous code on top of the asynchronous library ......................................... 203
25.1. Getting the value of a variable ................................................................................... 208
25.2. Hook for counting number of calls .............................................................................. 211
25.3. Getting the name of a function ................................................................................... 212
25.4. A naive sandbox with hooks ...................................................................................... 213
25.5. Controlling memory use ............................................................................................ 214
25.6. Using hooks to bar calls to unauthorized functions ......................................................... 215
26.1. Function to download a Web page .............................................................................. 218
26.2. The dispatcher ......................................................................................................... 219
26.3. Dispatcher using select ......................................................................................... 220
27.1. A bare-bones stand-alone Lua interpreter ..................................................................... 224
27.2. Dumping the stack ................................................................................................... 229
27.3. Example of stack manipulation ................................................................................... 231
28.1. Getting user information from a configuration file ......................................................... 236
28.2. A particular getcolorfield implementation ............................................................ 238
28.3. Colors as strings or tables ......................................................................................... 240
28.4. Calling a Lua function from C ................................................................................... 242
28.5. A generic call function .............................................................................................. 243
28.6. Pushing arguments for the generic call function ............................................................. 244
28.7. Retrieving results for the generic call function ............................................................... 245
29.1. A function to read a directory .................................................................................... 249
29.2. Implementation of pcall with continuations ............................................................... 251
30.1. The function map in C ............................................................................................. 255
30.2. Splitting a string ...................................................................................................... 256
30.3. The function string.upper ................................................................................... 257
30.4. A simplified implementation for table.concat ........................................................ 258
30.5. An implementation of tuples ...................................................................................... 262
31.1. Manipulating a Boolean array .................................................................................... 266
31.2. Extra code for the Boolean array library ...................................................................... 267
31.3. New versions for setarray/getarray .................................................................... 269
31.4. New initialization code for the Bit Array library ............................................................ 272
32.1. The dir.open factory function ................................................................................ 275
32.2. Other functions for the dir library ............................................................................. 276
32.3. Function to create XML parser objects ........................................................................ 280
32.4. Function to parse an XML fragment ............................................................................ 281
32.5. Handler for character data ......................................................................................... 282
32.6. Handler for end elements .......................................................................................... 282
32.7. Handler for start elements ......................................................................................... 283
32.8. Method to close an XML parser ................................................................................. 283
32.9. Initialization code for the lxp library .......................................................................... 284
33.1. Function to search for a process waiting for a channel .................................................... 291
33.2. Function to add a process to a waiting list .................................................................... 291
33.3. Functions to send and receive messages ....................................................................... 292
33.4. Function to create new processes ................................................................................ 293
33.5. Body for new threads ............................................................................................... 294
33.6. Extra functions for the lproc module ........................................................................ 295
33.7. Registering libraries to be opened on demand ............................................................... 296
About the Book
When Waldemar, Luiz, and I started the development of Lua, back in 1993, we could hardly imagine that
it would spread as it did. Started as an in-house language for two specific projects, currently Lua is widely
used in all areas that can benefit from a simple, extensible, portable, and efficient scripting language, such
as embedded systems, mobile devices, the Internet of Things, and, of course, games.

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

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

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

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

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

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

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

Portability: When we talk about portability, we are talking about running Lua on all platforms
we have ever heard about: all flavors of UNIX (Linux, FreeBSD, etc.) Windows,
Android, iOS, OS X, IBM mainframes, game consoles (PlayStation, Xbox, Wii,
etc.), microcontrollers (Arduino, etc.), and many more. The source code for each
of these platforms is virtually the same. Lua does not use conditional compilation
to adapt its code to different machines; instead, it sticks to the standard ISO (ANSI)
C. This way, you do not usually need to adapt it to a new environment: if you have
an ISO C compiler, you just have to compile Lua, out of the box.

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

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

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

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

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

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

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

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

The first part covers the basics of the language (and it is fittingly named The Basics). It is organized around
the main types of values in Lua: numbers, strings, tables, and functions. It also covers basic I/O and gives
an overview of the syntax of the language.
The second part, called Real Programming, covers more advanced topics that you can expect to find in
other similar languages, such as closures, pattern matching, date and time manipulation, data structures,
modules, and error handling.

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

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

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

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

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

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

A Few Typographical Conventions


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

-- program "Hello World"


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

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

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

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

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

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

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

For compatibility, Lua 5.3 still accepts this equal sign.

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

this <--> that

Running the Examples


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

The Lua site (http://www.lua.org) keeps the source code for the interpreter. If you have a C com-
piler and a working knowledge of how to compile C code in your machine, you should try to install Lua
from its source code; it is really easy. The Lua Binaries site (search for luabinaries) offers precom-
piled Lua interpreters for most major platforms. If you use Linux or another UNIX-like system, you may
check the repository of your distribution; several distributions already offer a package with Lua.

There are several Integrated Development Environments (IDEs) for Lua. Again, you can easily find them
with a basic search. (Nevertheless, I am an old timer. I still prefer a command-line interface in a window
and a text editor in another, specially for the initial learning steps.)

Acknowledgments
It is more than ten years since I published the first edition of this book. Several friends and institutions
have helped me along this journey.

As always, Luiz Henrique de Figueiredo and Waldemar Celes, Lua coauthors, offered all kinds of help.
André Carregal, Asko Kauppi, Brett Kapilik, Diego Nehab, Edwin Moragas, Fernando Jefferson, Gavin
Wraith, John D. Ramsdell, Norman Ramsey, Reuben Thomas, and Robert Day provided invaluable sug-
gestions and useful insights for diverse editions of this book. Luiza Novaes provided key support for the
cover design.

Lightning Source, Inc. proved a reliable and efficient option for printing and distributing the book. Without
them, the option of self-publishing the book would not be an option.

Tecgraf, headed by Marcelo Gattass, housed the Lua project from its birth in 1993 until 2005, and continues
to help the project in several ways.

I also would like to thank the Pontifical Catholic University of Rio de Janeiro (PUC-Rio) and the Brazilian
National Research Council (CNPq) for their continuous support to my work. In particular, the Lua project
would be impossible without the environment that I have at PUC-Rio.
Finally, I must express my deep gratitude to Noemi Rodriguez, for all kinds of help (technical and non-
technical) and for illumining my life.
Part I. The Basics
Table of Contents
1. Getting Started ................................................................................................................ 4
Chunks ...................................................................................................................... 4
Some Lexical Conventions ........................................................................................... 6
Global Variables ......................................................................................................... 7
Types and Values ........................................................................................................ 7
Nil .................................................................................................................... 8
Booleans ............................................................................................................ 8
The Stand-Alone Interpreter .......................................................................................... 9
2. Interlude: The Eight-Queen Puzzle .................................................................................... 12
3. Numbers ....................................................................................................................... 15
Numerals .................................................................................................................. 15
Arithmetic Operators .................................................................................................. 16
Relational Operators .................................................................................................. 17
The Mathematical Library ........................................................................................... 18
Random-number generator .................................................................................. 18
Rounding functions ............................................................................................ 18
Representation Limits ................................................................................................. 19
Conversions .............................................................................................................. 21
Precedence ............................................................................................................... 22
Lua Before Integers ................................................................................................... 22
4. Strings ......................................................................................................................... 24
Literal strings ............................................................................................................ 24
Long strings ............................................................................................................. 25
Coercions ................................................................................................................. 26
The String Library ..................................................................................................... 27
Unicode ................................................................................................................... 29
5. Tables .......................................................................................................................... 33
Table Indices ............................................................................................................ 33
Table Constructors ..................................................................................................... 35
Arrays, Lists, and Sequences ....................................................................................... 36
Table Traversal ......................................................................................................... 38
Safe Navigation ......................................................................................................... 38
The Table Library ..................................................................................................... 39
6. Functions ...................................................................................................................... 42
Multiple Results ........................................................................................................ 43
Variadic Functions ..................................................................................................... 45
The function table.unpack .................................................................................... 47
Proper Tail Calls ....................................................................................................... 48
7. The External World ........................................................................................................ 50
The Simple I/O Model ............................................................................................... 50
The Complete I/O Model ............................................................................................ 53
Other Operations on Files ........................................................................................... 54
Other System Calls .................................................................................................... 55
Running system commands ................................................................................. 55
8. Filling some Gaps .......................................................................................................... 57
Local Variables and Blocks ......................................................................................... 57
Control Structures ...................................................................................................... 58
if then else ....................................................................................................... 58
while ............................................................................................................... 59
repeat ............................................................................................................. 59
Numerical for ................................................................................................... 60

2
The Basics

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


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

3
Chapter 1. Getting Started
To keep with tradition, our first program in Lua just prints "Hello World":

print("Hello World")

If you are using the stand-alone Lua interpreter, all you have to do to run your first program is to call the
interpreter —usually named lua or lua5.3— with the name of the text file that contains your program.
If you save the above program in a file hello.lua, the following command should run it:

% lua hello.lua

As a more complex example, the next program defines a function to compute the factorial of a given
number, asks the user for a number, and prints its factorial:

-- defines a factorial function


function fact (n)
if n == 0 then
return 1
else
return n * fact(n - 1)
end
end

print("enter a number:")
a = io.read("*n") -- reads a number
print(fact(a))

Chunks
We call each piece of code that Lua executes, such as a file or a single line in interactive mode, a chunk.
A chunk is simply a sequence of commands (or statements).

A chunk can be as simple as a single statement, such as in the “Hello World” example, or it can be composed
of a mix of statements and function definitions (which are actually assignments, as we will see later), such
as the factorial example. A chunk can be as large as we wish. Because Lua is used also as a data-description
language, chunks with several megabytes are not uncommon. The Lua interpreter has no problems at all
with large chunks.

Instead of writing your program to a file, you can run the stand-alone interpreter in interactive mode. If
you call lua without any arguments, you will get its prompt:

% lua
Lua 5.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
>

Thereafter, each command that you type (such as print "Hello World") executes immediately after
you enter it. To exit the interactive mode and the interpreter, just type the end-of-file control character
(ctrl-D in POSIX, ctrl-Z in Windows), or call the function os.exit, from the Operating System
library —you have to type os.exit().

Starting in version 5.3, we can enter expressions directly in the interactive mode, and Lua will print their
values:

4
Getting Started

% lua
Lua 5.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> math.pi / 4 --> 0.78539816339745
> a = 15
> a^2 --> 225
> a + 2 --> 17

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

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

For compatibility, Lua 5.3 still accepts these equals signs.

To run that code as a chunk (not in interactive mode), we must enclose the expressions inside calls to
print:

print(math.pi / 4)
a = 15
print(a^2)
print(a + 2)

Lua usually interprets each line that we type in interactive mode as a complete chunk or expression. How-
ever, if it detects that the line is not complete, it waits for more input, until it has a complete chunk. This
way, we can enter a multi-line definition, such as the factorial function, directly in interactive mode. How-
ever, it is usually more convenient to put such definitions in a file and then call Lua to run the file.

We can use the -i option to instruct Lua to start an interactive session after running a given chunk:

% lua -i prog

A command line like this one will run the chunk in the file prog and then prompt for interaction. This is
especially useful for debugging and manual testing. At the end of this chapter, we will see other options
for the stand-alone interpreter.

Another way to run chunks is with the function dofile, which immediately executes a file. For instance,
suppose we have a file lib1.lua with the following code:

function norm (x, y)


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

function twice (x)


return 2.0 * x
end

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

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


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

The function dofile is useful also when we are testing a piece of code. We can work with two windows:
one is a text editor with our program (in a file prog.lua, say) and the other is a console running Lua

5
Getting Started

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


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

Some Lexical Conventions


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

i j i10 _ij
aSomewhatLongName _INPUT

You should avoid identifiers starting with an underscore followed by one or more upper-case letters (e.g.,
_VERSION); they are reserved for special uses in Lua. Usually, I reserve the identifier _ (a single under-
score) for dummy variables.

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

and break do else elseif


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

Lua is case-sensitive: and is a reserved word, but And and AND are two different identifiers.

A comment starts anywhere with two consecutive hyphens (--) and runs until the end of the line. Lua
also offers long comments, which start with two hyphens followed by two opening square brackets and
run until the first occurrence of two consecutive closing square brackets, like here:1

--[[A multi-line
long comment
]]

A common trick that we use to comment out a piece of code is to enclose the code between --[[ and
--]], like here:

--[[
print(10) -- no action (commented out)
--]]

To reactivate the code, we add a single hyphen to the first line:

---[[
print(10) --> 10
--]]

In the first example, the --[[ in the first line starts a long comment, and the two hyphens in the last line
are still inside that comment. In the second example, the sequence ---[[ starts an ordinary, single-line
comment, so that the first and the last lines become independent comments. In this case, the print is
outside comments.

Lua needs no separator between consecutive statements, but we can use a semicolon if we wish. Line
breaks play no role in Lua's syntax; for instance, the following four chunks are all valid and equivalent:
1
Long comments can be more complex than that, as we will see in the section called “Long strings”.

6
Getting Started

a = 1
b = a * 2

a = 1;
b = a * 2;

a = 1; b = a * 2

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

My personal convention is to use semicolons only when I write two or more statements in the same line
(which I hardly do).

Global Variables
Global variables do not need declarations; we simply use them. It is not an error to access a non-initialized
variable; we just get the value nil as the result:

> b --> nil


> b = 10
> b --> 10

If we assign nil to a global variable, Lua behaves as if we have never used the variable:

> b = nil
> b --> nil

Lua does not differentiate a non-initialized variable from one that we assigned nil. After the assignment,
Lua can eventually reclaim the memory used by the variable.

Types and Values


Lua is a dynamically-typed language. There are no type definitions in the language; each value carries
its own type.

There are eight basic types in Lua: nil, Boolean, number, string, userdata, function, thread, and table. The
function type gives the type name of any given value:

> type(nil) --> nil


> type(true) --> boolean
> type(10.4 * 3) --> number
> type("Hello world") --> string
> type(io.stdin) --> userdata
> type(print) --> function
> type(type) --> function
> type({}) --> table
> type(type(X)) --> string

The last line will result in "string" no matter the value of X, because the result of type is always
a string.

The userdata type allows arbitrary C data to be stored in Lua variables. It has no predefined operations in
Lua, except assignment and equality test. Userdata are used to represent new types created by an application
program or a library written in C; for instance, the standard I/O library uses them to represent open files.
We will discuss more about userdata later, when we get to the C API.

7
Getting Started

Variables have no predefined types; any variable can contain values of any type:

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


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

Usually, when we use a single variable for different types, the result is messy code. However, sometimes
the judicious use of this facility is helpful, for instance in the use of nil to differentiate a normal return
value from an abnormal condition.

We will discuss now the simple types nil and Boolean. In the following chapters, we will discuss in detail
the types number (Chapter 3, Numbers), string (Chapter 4, Strings), table (Chapter 5, Tables), and function
(Chapter 6, Functions). We will explain the thread type in Chapter 24, Coroutines, where we discuss
coroutines.

Nil
Nil is a type with a single value, nil, whose main property is to be different from any other value. Lua uses
nil as a kind of non-value, to represent the absence of a useful value. As we have seen, a global variable
has a nil value by default, before its first assignment, and we can assign nil to a global variable to delete it.

Booleans
The Boolean type has two values, @false{} and @true{}, which represent the traditional Boolean values.
However, Booleans do not hold a monopoly of condition values: in Lua, any value can represent a con-
dition. Conditional tests (e.g., conditions in control structures) consider both the Boolean false and nil
as false and anything else as true. In particular, Lua considers both zero and the empty string as true in
conditional tests.

Throughout this book, I will write “false” to mean any false value, that is, the Boolean false or nil. When
I mean specifically the Boolean value, I will write “false”. The same holds for “true” and “true”.

Lua supports a conventional set of logical operators: and, or, and not. Like control structures, all logical
operators consider both the Boolean false and nil as false, and anything else as true. The result of the and
operator is its first operand if that operand is false; otherwise, the result is its second operand. The result
of the or operator is its first operand if it is not false; otherwise, the result is its second operand:

> 4 and 5 --> 5


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

Both and and or use short-circuit evaluation, that is, they evaluate their second operand only when nec-
essary. Short-circuit evaluation ensures that expressions like (i ~= 0 and a/i > b) do not cause
run-time errors: Lua will not try to evaluate a / i when i is zero.

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

if not x then x = v end

8
Getting Started

That is, it sets x to a default value v when x is not set (provided that x is not set to false).

Another useful idiom is ((a and b) or c) or simply (a and b or c) (given that and has a
higher precedence than or). It is equivalent to the C expression a ? b : c, provided that b is not false.
For instance, we can select the maximum of two numbers x and y with the expression (x > y) and x
or y. When x > y, the first expression of the and is true, so the and results in its second operand (x),
which is always true (because it is a number), and then the or expression results in the value of its first
operand, x. When x > y is false, the and expression is false and so the or results in its second operand, y.

The not operator always gives a Boolean value:

> not nil --> true


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

The Stand-Alone Interpreter


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

When the interpreter loads a file, it ignores its first line if this line starts with a hash (#). This feature allows
the use of Lua as a script interpreter in POSIX systems. If we start our script with something like

#!/usr/local/bin/lua

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

#!/usr/bin/env lua

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

The usage of lua is

lua [options] [script [args]]

Everything is optional. As we have seen already, when we call lua without arguments the interpreter
enters the interactive mode.

The -e option allows us to enter code directly into the command line, like here:

% lua -e "print(math.sin(12))" --> -0.53657291800043

(POSIX systems need the double quotes to stop the shell from interpreting the parentheses.)

The -l option loads a library. As we saw previously, -i enters interactive mode after running the other
arguments. Therefore, the next call will load the lib library, then execute the assignment x = 10, and
finally present a prompt for interaction.

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

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

> math.sin(3) --> 0.14112000805987


> a = 30
> a --> 30

9
Getting Started

(Remember, this feature came with Lua 5.3. In older versions, we must precede the expressions with equals
signs.) To avoid this print, we can finish the line with a semicolon:

> io.flush() --> true


> io.flush();

The semicolon makes the line syntactically invalid as an expression, but still valid as a command.

Before running its arguments, the interpreter looks for an environment variable named LUA_INIT_5_3
or else, if there is no such variable, LUA_INIT. If there is one of these variables and its content is @file-
name, then the interpreter runs the given file. If LUA_INIT_5_3 (or LUA_INIT) is defined but it does
not start with an at-sign, then the interpreter assumes that it contains Lua code and runs it. LUA_INIT
gives us great power when configuring the stand-alone interpreter, because we have the full power of
Lua in the configuration. We can preload packages, change the path, define our own functions, rename
or delete functions, and so on.

A script can retrieve its arguments through the predefined global variable arg. In a call like % lua
script a b c, the interpreter creates the table arg with all the command-line arguments, before
running any code. The script name goes into index 0; its first argument ("a" in the example) goes to
index 1, and so on. Preceding options go to negative indices, as they appear before the script. For instance,
consider this call:

% lua -e "sin=math.sin" script a b

The interpreter collects the arguments as follows:

arg[-3] = "lua"
arg[-2] = "-e"
arg[-1] = "sin=math.sin"
arg[0] = "script"
arg[1] = "a"
arg[2] = "b"

More often than not, a script uses only the positive indices (arg[1] and arg[2], in the example).

A script can also retrieve its arguments through a vararg expression. In the main body of a script, the
expression ... (three dots) results in the arguments to the script. (We will discuss vararg expressions in
the section called “Variadic Functions”.)

Exercises
Exercise 1.1: Run the factorial example. What happens to your program if you enter a negative number?
Modify the example to avoid this problem.

Exercise 1.2: Run the twice example, both by loading the file with the -l option and with dofile.
Which way do you prefer?

Exercise 1.3: Can you name other languages that use "--" for comments?

Exercise 1.4: Which of the following strings are valid identifiers?

___ _end End end until? nil NULL one-step

Exercise 1.5: What is the value of the expression type(nil) == nil? (You can use Lua to check
your answer.) Can you explain this result?

10
Getting Started

Exercise 1.6: How can you check whether a value is a Boolean without using the function type?

Exercise 1.7: Consider the following expression:

(x and y and (not z)) or ((not y) and x)

Are the parentheses necessary? Would you recommend their use in that expression?

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

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

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

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

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

12
Interlude: The Eight-Queen Puzzle

Figure 2.1. The eight-queen program


N = 8 -- board size

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


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

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

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


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

-- run the program


addqueen({}, 1)

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

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

13
Interlude: The Eight-Queen Puzzle

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

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

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

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

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

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

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

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

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

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

Both integer and float values have type "number":

> type(3) --> number


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

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

> 1 == 1.0 --> true


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

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

> math.type(3) --> integer


> math.type(3.0) --> float

Moreover, Lua 5.3 shows them differently:

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

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

15
Numbers

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

> 0xff --> 255


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

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

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


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

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

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

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

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

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

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

> 13.0 + 25 --> 38.0


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

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

> 3.0 / 2.0 --> 1.5


> 3 / 2 --> 1.5

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

16
Numbers

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

The following equation defines the modulo operator:

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

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

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

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

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

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

local tolerance = 10
function isturnback (angle)
angle = angle % 360
return (math.abs(angle - 180) < tolerance)
end

This definition works even for negative angles:

print(isturnback(-180)) --> true

If we want to work with radians instead of degrees, we simply change the constants in our function:

local tolerance = 0.17


function isturnback (angle)
angle = angle % (2*math.pi)
return (math.abs(angle - math.pi) < tolerance)
end

The operation angle % (2 * math.pi) is all we need to normalize any angle to a value in the
interval [0, 2#).

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

Relational Operators
Lua provides the following relational operators:

17
Exploring the Variety of Random
Documents with Different Content
Habiendo tocado á turno de concurso las vacantes de Barcelona y
Zaragoza, vacilé algún tiempo en mi elección. Mi primer pensamiento
fué trasladarme á la capital aragonesa. Hacia ella me arrastraban el
amor de la tierra, los recuerdos de la juventud y el afecto á la
familia. Pero enfrente de estos sentimientos prevalecieron
consideraciones de orden honestamente utilitario. Para el hombre
votado á una idea y resuelto á rendirle toda su actividad, las
ciudades grandes son preferibles á las pequeñas. En éstas, las
gentes se conocen demasiado, ó demasiado pronto, para vivir en
santa calma. Y el tiempo se va en halagar á los amigos y combatir á
los adversarios. Importa notar, además, que por aquellos tiempos el
claustro de mi venerada Alma mater, á causa de dos ó tres
desequilibrados, ardía en rencillas y antagonismos impropios del
decoro de la toga. No faltan, por desgracia, temperamentos
malévolos en las grandes poblaciones universitarias; pero aquí las
toxinas humanas, diluídas por la distancia, pierden ó atenúan
notablemente sus efectos.
Temeroso, pues, de que mis fuerzas se disiparan en vanas y
dolorosas frotaciones, resolví al fin, contra el consejo de mi familia,
trasladarme á la ciudad condal. Y acerté en mis presunciones,
porque en Barcelona encontré no sólo el sereno ambiente
indispensable á mis trabajos, sino facilidades que no hubiera hallado
en Zaragoza para organizar un bien provisto laboratorio y publicar
folletos ilustrados con profusión de litografías y fotograbados.
Precisamente, durante los primeros años pasados en la ciudad
condal, aparecieron las más importantes de mis comunicaciones
científicas.
Preocupado, como siempre, de no turbar la ecuación entre los
gastos y los ingresos, me instalé modestamente en una casa barata
de la calle de la Riera Alta, próxima al Hospital de Santa Cruz,
donde, por entonces, estaba la Facultad de Medicina. Ulteriormente,
y contando ya con otros emolumentos (los proporcionados por
algunos médicos deseosos de ampliar en mi laboratorio sus
conocimientos histológicos y bacteriológicos), me mudé á la calle del
Bruch, á cierta casa nueva y relativamente lujosa. En ella dispuse de
una hermosa sala donde instalar el laboratorio y de un jardín anejo,
muy apropiado para conservar los animales en curso de
experimentación.
Allí recibieron enseñanza micrográfica, entre otros jóvenes de
mérito, Durán y Ventosa, hijo del ex ministro Durán y Bas; Pí y
Gilbert, que hizo brillantes oposiciones á cátedras de Histología y
publicó algún trabajo en mi Revista; el malogrado Gil Saltor[31],
futuro profesor de Histología en Zaragoza y de Patología externa en
Barcelona; Bofill, que llegó á ser, andando el tiempo, un buen
naturalista; Sala Pons, que publicó años después algunas
investigaciones interesantes sobre la estructura del cerebro de las
aves y la médula espinal de los batracios, etc.
Dada la proverbial cortesía catalana, huelga decir que en mis
compañeros de Facultad hallé sentimientos de consideración y
respeto. Pasa el catalán por ser un tanto brusco y excesivamente
reservado con los forasteros; pero le adornan dos cualidades
preciosas: siente y practica fervorosamente la doble virtud del
trabajo y de la economía; y acaso por esto mismo, evita rencillas y
cominerías y respeta religiosamente el tiempo de los demás.
Entre los comprofesores con quienes me ligaron lazos de afecto
sincero, recuerdo á nuestro excelente decano el Dr. Juan Rull,
profesor de Obstetricia; al simpático doctor Campá, que acababa de
trasladarse desde la Universidad de Valencia; á Batlles, catedrático
de Anatomía, orador colorista y afluentísimo; al anciano y
benemérito Silóniz, un andaluz á quien treinta años de permanencia
en Barcelona no habían quitado el gracioso acento gaditano; á Coll y
Pujol, enclenque y valetudinario entonces, pero que ha alcanzado los
setenta sin jubilarse; á Pí, maestro de Patología general, una de las
cabezas más reflexivas y equilibradas de la Facultad; á Giné y
Partagás, orador brioso y publicista fecundo y agudo; á Valentí,
profesor de Medicina legal, expositor sutil, pero algo desconcertante
y paradójico; al Dr. Morales, prestigioso cirujano andaluz, á quien los
barceloneses llamaban el moro triste, por su aspecto de Boabdil
destronado; á Robert, clínico eminente, luchador de palabra precisa
é intencionada, que, andando el tiempo, debía sorprendernos á
todos dirigiendo el nacionalismo catalán y proclamando urbi et orbi,
un poco á la ligera (no era antropólogo, ni había leído á Olóriz y
Aranzadi), la tesis de la superioridad del cráneo catalán sobre el
castellano; opinión desinteresada, pues además de gozar de un
cráneo pequeño, aunque bien amueblado, había nacido en Méjico y
ostentaba un apellido francés; en fin, al simpático Bonet, quien,
gracias á su viveza y habilísima política, llegó á rector de la
Universidad, á senador y hasta á barón de Bonet, etc., etc.
¡Lástima que tan lucido elenco de maestros desarrollara sus
funciones en el vetusto y ruinoso Hospital de Santa Cruz, en donde
si no faltaban enfermos y facilidades, por tanto, para la enseñanza
clínica, se carecía del indispensable local para cátedras y
laboratorios! Por lo que á mí respecta, hízose lo posible para
organizar la enseñanza micrográfica. Gracias á la benevolencia del
Dr. Rull, conseguí una sala, relativamente capaz, destinada á las
manipulaciones y demostraciones de Histología y Bacteriología,
amén de un buen microscopio Zeiss y de algunas estufas de
esterilización y vegetación. Contando con alumnos poco numerosos,
pero muy aplicados y formales, pude, no obstante la pequeñez del
laboratorio, dar una enseñanza práctica harto más eficaz que la
actualmente dada en Madrid, donde la masa trepidante de
trescientos alumnos turba el buen orden del aula y esteriliza las
iniciativas pedagógicas mejor encaminadas.
Novato todavía en los estudios de Anatomía patológica, tomé á
empeño adquirir conocimientos positivos en esta rama de la
Medicina, haciendo autopsias é iniciándome en los secretos de la
patología experimental. Por fortuna, los cadáveres abundaban en el
Hospital de Santa Cruz. Pasábame diariamente algunas horas en la
sala de disección: recogía tumores; exploraba infecciones; cultivaba
microbios y, sobre la base de algunas piezas interesantes, llevaba
adelante mis estudios sobre el sistema nervioso del hombre. Casi
todas las figuras relativas á la inflamación, degeneraciones, tumores
é infecciones, incluídos en la primera edición de mi Manual de
Anatomía patológica general[32] son copias de preparaciones
efectuadas con aquel rico material necrópsico, al que se añadieron
algunos tumores é infecciones proporcionados por Profesores de
otros hospitales ó por los veterinarios municipales. La ejecución de
estos trabajos y la redacción del citado libro fueron la principal tarea
del año 1887 y comienzos del 88.
Dejo expresado en otro lugar que el hombre de laboratorio, ajeno
á la política y al ejercicio profesional, nada frecuentador de casinos y
teatros, necesita, para no llegar al enquistamiento intelectual ó caer
en la estrafalariez, del oreo confortador de la tertulia. Es preciso que
llegue hasta él, simplificado y elaborado por el ajeno ingenio, algo
de lo que en el mundo pasa. Ocioso es notar que tales reuniones,
para ser amenas y educadoras, deben comprender temperamentos
mentales diversos y especialistas diferentes. Sólo los ricos, es decir,
los escuetamente capitalistas, y las malas personas serán
cuidadosamente eliminados; porque si los últimos causan disgustos,
los primeros disgustan del ideal, que es harto peor. La buena peña
supone atinado reparto de papeles. Un comensal tratará de política;
otro de negocios; aquél comentará, leve y graciosamente, los
sucesos locales ó nacionales; el de más allá se entusiasmará con la
literatura ó con el arte; alguien cultivará la nota cómica; hasta la voz
grave de un defensor celoso del orden social, y del consabido
consorcio entre el altar y el trono, se oirá con gusto de vez en
cuando; mas para el hombre de laboratorio, los más útiles y
sugestivos contertulios serán sus colegas de otras Facultades, los
capaces de comentar sin pedantería las últimas revelaciones de las
respectivas ciencias.
Sin responder enteramente á este ideal, la tertulia del Café de
Pelayo (trasladada después á la Pajarera de la Plaza de Cataluña),
donde fuí presentado en los primeros meses de 1887, me resultó
singularmente grata y provechosa. Preponderaban, y ello era bueno,
los Catedráticos de la Facultad de Ciencias; pero figuraban también
políticos, literatos, médicos y hombres de negocios. Recuerdo, entre
otros: al amigo Lozano, Catedrático de Física; á Castro Pulido,
Profesor de Cosmografía y pulcro y fácil conversador; á Villafañé
(recién llegado de Valencia), carácter atrabiliario, defensor de una
estrafalaria teoría filosófica sobre el átomo pensante, con que nos
dió tremendas tabarras; á Domenech, un buen Catedrático de
Geometría, arquitecto, catalanista ferviente y partidario, en último
término[33], de la anexión á Francia (solía decir que Cataluña estaba
llamada á ser la Bélgica del Sud); á V. García de la Cruz, Profesor de
Química, bonísima persona y talento clarísimo, del cual hablaré
luego; á Solsona, médico locuaz y zaragatero que abusaba de los
específicos y de los autobombos periodísticos; á Soriano, Catedrático
de latín y activo periodista; á Schwarz, Profesor de Historia
(entonces auxiliar), orador fogoso, prototipo del vir bonus dicendi
peritus, que llegó á Concejal, Alcalde y no sé si á Diputado á Cortes;
á Sedó (yerno), fabricante de tejidos, persona lista y diestra en
negocios; á Pablo Calvell, abogado con fábrica, dotado de finísimo
ingenio satírico, fértil en ocurrencias agudas y oportunísimas[34], etc.
Á esta peña agregáronse más adelante B. Bonet, entonces boticario
en Gracia, hoy Profesor en la Facultad de Farmacia de Madrid, y mi
paisano Odón de Buen, naturalista de mucho mérito, y en fin, otras
muchas personas borradas de mi memoria.
Juzgo excesivamente egoísta aquel dicho antiguo, desaprobado
por Cicerón, «que se debe amar como quien ha de aborrecer»; pero
estimo prudente para salvaguardar la santa libertad, no extremar el
trato amistoso hasta esa embarazosa intimidad que merma nuestro
tiempo, se entromete en caseros asuntos y coarta gustos é
iniciativas. De esta discreta reserva, hice, sin embargo, excepción en
favor de Victorino García de la Cruz, uno de los más asiduos y
agradables comensales de la referida peña. De ideas filosóficas no
siempre armónicas con las mías, coincidíamos en muchos gustos y
tendencias: igual despreocupación del dinero; el mismo culto hacia
el arte, y en su defecto, hacia la fotografía; parecida aflicción
patriótica al reconocer nuestro decaimiento científico; igual
entusiasmo, en fin, por la investigación original y el renacimiento
intelectual de España.
Durante varios años de íntimo trato, fué Victorino el único
confidente de mis proyectos. Comunicábale á diario el estado de mis
trabajos, los obstáculos que me detenían, así como mis caras
ilusiones y esperanzas. Al principio, me oía con extrañeza, casi con
incredulidad. Patriota sincero, la desesperanza había ganado su
espíritu y paralizado sus fuerzas. Mas al fin mis predicaciones
obraron en él una especie de contagio. Y siguiendo mi ejemplo,
acabó por escoger en el dominio de la física, que cultivó siempre con
amor, algunos temas de estudio, baratos, es decir, accesibles á los
mezquinos medios con que contaba. Años después, recordando mis
alentadoras exhortaciones, solía decir que sin mi estímulo no
hubieran aparecido nunca sus interesantes descubrimientos sobre
Las leyes de los líquidos turbios y gases nebulosos, y otras
conquistas científicas de positivo valor.
En el curso de estas memorias hemos de ver á menudo
acreditado el dicho de Cisneros: «Fray Ejemplo es el mejor
predicador.»
¡Pobre Victorino! Era un talento reflexivo y penetrante, un
trabajador infatigable y probo. Murió, joven aún, años después,
cuando, trasladado á la Corte, había conseguido, por sus
indiscutibles méritos, un sillón en la Real Academia de Ciencias y
alcanzado bien cimentada notoriedad. Y cayó víctima de una virtud,
como otros caen víctimas del vicio. Su virtud consistió en adaptarse
austera y resignadamente á la pobreza, habitando con su bastante
numerosa familia en casas baratas, sórdidas, emplazadas en barrios
malsanos, atenido estrictamente á la paga de Profesor que, por
aquellos tiempos, constituía mera ración de entretenimiento. En
virtud de esta penuria, que transcendía naturalmente á sus medios
de investigación y de información bibliográfica, le ocurrió más de
una vez perder las ventajas de la prioridad, hallando la solución de
difíciles problemas, poco después de esclarecidos en Revistas
alemanas, que él desconocía, por sabios de primera fuerza. Así y
todo, su obra original es copiosa é importante. En fin, Victorino
profesaba, en materia de higiene, ideas demasiado personales, y por
tanto, demasiado peligrosas. De esta debilidad, que tanto contribuyó
á precipitar la muerte del querido compañero, trataré más adelante.
Volviendo al relato de mis trabajos, consignaré que, adelantada
mi labor preparatoria en Anatomía patológica, proseguí con inusitado
ardor las investigaciones acerca del sistema nervioso. El método de
Golgi comenzaba á ser fecundo en mis manos.
Y llegó el año 1888, mi año cumbre, mi año de fortuna. Porque
durante este año, que se levanta en mi memoria con arreboles de
aurora, surgieron al fin aquellos descubrimientos interesantes,
ansiosamente esperados y codiciados. Sin ellos, habría yo vegetado
tristemente en una Universidad provinciana, sin pasar, en el orden
científico, de la categoría de jornalero detallista, más ó menos
estimable. Por ellos, llegué á sentir el acre halago de la celebridad;
mi humilde apellido, pronunciado á la alemana (Cayal), traspasó las
fronteras; en fin, mis ideas, divulgadas entre los sabios,
discutiéronse con calor. Desde entonces, el tajo de la ciencia contó
con un obrero más.
¿Cómo fué ello? Perdonará el lector si, á un acontecimiento tan
decisivo para mi carrera, consagro aquí algunos comentarios y
amplificaciones. Declaro desde luego que la nueva verdad,
laboriosamente buscada y tan esquiva durante dos años de vanos
tanteos, surgió de repente en mi espíritu como una revelación. Las
leyes que rigen la morfología y las conexiones de las células
nerviosas en la substancia gris, patentes primeramente en mis
estudios del cerebelo, confirmáronse en todos los órganos
sucesivamente explorados. Séame lícito formularlas desde luego:
1.ª Las ramificaciones colaterales y terminales de todo cilindro-eje
acaban en la substancia gris, no mediante red difusa, según
defendían Gerlach y Golgi con la mayoría de los neurólogos, sino
mediante arborizaciones libres, dispuestas en variedad de formas
(cestas ó nidos pericelulares, ramas trepadoras, etc.).
2.ª Estas ramificaciones se aplican íntimamente al cuerpo y
dendritas de las células nerviosas, estableciéndose un contacto ó
articulación entre el protoplasma receptor y los últimos ramúsculos
axónicos.
De las referidas leyes anatómicas despréndense dos corolarios
fisiológicos:
3.ª Puesto que al cuerpo y dendritas de las neuronas se aplican
estrechamente las últimas raicillas de los cilindros-ejes, es preciso
admitir que el soma y las expansiones protoplásmicas participan en
la cadena de conducción, es decir, que reciben y propagan el
impulso nervioso, contrariamente á la opinión de Golgi, para quien
dichos segmentos celulares desempeñarían un papel meramente
nutritivo.
4.ª Excluída la continuidad substancial entre célula y célula, se
impone la opinión de que el impulso nervioso se transmite por
contacto, como en las articulaciones de los conductores eléctricos, ó
por una suerte de inducción, como en los carretes de igual nombre.
Las referidas leyes, puro resultado inductivo del análisis
estructural del cerebelo, fueron confirmadas después en todos los
órganos nerviosos explorados (retina, bulbo olfatorio, ganglios
sensitivos y simpáticos, cerebro, médula espinal, bulbo raquídeo,
etc.). Ulteriores trabajos nuestros y ajenos (de Kölliker, Retzius, van
Gehuchten, His, Edinger, v. Lenhossék, Athias, Lugaro, P. Ramón, Cl.
Sala, etc.), revelaron que las referidas normas estructurales y
fisiológicas se aplicaban, también, sin violencia, al sistema nervioso
de vertebrados é invertebrados. Según ocurre con todas las
concepciones legítimas, la mía fué consolidándose y ganando
progresivamente en dignidad conforme se acrecía el círculo de la
exploración comprobatoria.
Pero en mi afán de condensar en breves proposiciones lo esencial
de los resultados obtenidos, no he contestado aún á la interrogación
formulada en párrafos anteriores.
¿Cómo fueron las referidas leyes descubiertas? ¿Por qué mi labor,
atenida durante dos años á la modesta confirmación de las
conquistas de Deiters, Ranvier, Krause, Kölliker y, sobre todo, de
Golgi, adquirió de repente vuelo y originalidad sorprendentes?
Quiero ser franco con el lector. Á mis éxitos de entonces
contribuyeron, sin duda, algunos perfeccionamientos del método
cromo-argéntico, singularmente la modificación designada proceder
de doble impregnación[35]; pero el resorte principal, la causa
verdaderamente eficiente, consistió —¡quién lo dijera!— en haber
aplicado á la resolución del problema de la substancia gris los
dictados del más vulgar sentido común. En vez de atacar al toro por
las astas, según la frase vulgar, yo me permití algunos rodeos
estratégicos. Pero esto exige una amplificación.
Dejo consignado en el capítulo anterior, y repetido hace un
momento, que el gran enigma de la organización del cerebro se cifra
en averiguar el modo de terminarse las ramificaciones nerviosas y de
enlazarse recíprocamente las neuronas. Reproduciendo un símil ya
mencionado, tratábase de inquirir cómo rematan las raíces y las
ramas de esos árboles de la substancia gris, de esa selva tan densa
que, por refinamiento de complicación, carece de vacíos, de suerte
que los troncos, ramas y hojas se tocan por todas partes.
Dos medios ocurren para individualizar convenientemente los
elementos de este bosque inextricable. El más natural y sencillo al
parecer, pero en realidad el más difícil, consiste en explorar
intrépidamente la selva adulta, limpiando el terreno de arbustos y
plantas parásitas, y aislando, en fin, cada especie arbórea, tanto de
sus parásitos como de sus congéneres. Tal es el recurso, aplicado en
Neurología por la mayoría de los autores, desde la época de Stilling,
Deiters y Schültze (disociación mecánica y química) hasta la de
Weigert y Golgi, en que el aislamiento de cada forma celular ó de
cada fibra se conseguía ópticamente, es decir, por desaparición ó
incoloración de la mayoría de los factores integrantes de la
substancia gris. Mas semejante táctica, á la que Golgi y Weigert
debieron notables descubrimientos, resulta poco apropiada á la
dilucidación del problema propuesto, á causa de la enorme longitud
y extraordinaria frondosidad del ramaje nervioso, que
inevitablemente aparece mutilado y casi indescifrable en cada corte.
El segundo camino ofrecido á la razón constituye lo que, en
términos biológicos, se designa método ontogénico ó embriológico.
Puesto que la selva adulta resulta impenetrable é indefinible, ¿por
qué no recurrir al estudio del bosque joven, como si dijéramos, en
estado de vivero? Tal fué la sencillísima idea inspiradora de mis
reiterados ensayos del método argéntico en los embriones de ave y
de mamífero. Escogiendo bien la fase evolutiva, ó más claro,
aplicando el método antes de la aparición en los axones de la vaina
medular (obstáculo casi infranqueable á la reacción), las células
nerviosas, relativamente pequeñas, destacan íntegras dentro de
cada corte; las ramificaciones terminales del cilindro-eje dibújanse
clarísimas y perfectamente libres; los nidos pericelulares, esto es, las
articulaciones interneuronales, aparecen sencillas, adquiriendo
gradualmente intrincamiento y extensión; en suma, surge ante
nuestros ojos, con admirable claridad y precisión, el plan
fundamental de la composición histológica de la substancia gris. Para
colmo de fortuna, la reacción cromo-argéntica, incompleta y azarosa
en el adulto, proporciona en los embriones coloraciones espléndidas,
singularmente extensas y constantes.
¿Cómo —se dirá— tratándose de cosa tan vulgar, no dieron en
ella los sabios? Ciertamente, el recurso debió ocurrir á muchos. Años
después tuve noticia de que el mismo Golgi había ya aplicado su
método á los embriones y animales jóvenes y obtenido algún
resultado excelente; pero no insistió en sus probaturas, ni presumió
quizás que, por semejante camino, pudiera adelantarse en la
dilucidación del problema estructural de los centros. Tan poca
importancia debió conceder á tales ensayos que, en su obra magna
antes citada, las observaciones consignadas refiérense
exclusivamente al sistema nervioso adulto del hombre y mamíferos.
De cualquier modo, mi fácil éxito comprueba una vez más que las
ideas no se muestran fecundas con quien las sugiere ó las aplica por
primera vez, sino con los tenaces que las sienten con vehemencia y
en cuya virtualidad ponen toda su fe y todo su amor. Bajo este
aspecto, bien puede afirmarse que las conquistas científicas son
creaciones de la voluntad y ofrendas de la pasión.
Consciente de haber encontrado una dirección fecunda, procuré
aprovecharme de ella, consagrándome al trabajo, no ya con ahinco,
sino con furia. Al compás de los nuevos hechos en mis
preparaciones, las ideas bullían y se atropellaban en mi espíritu. Una
fiebre de publicidad me devoraba. Á fin de exteriorizar mis
pensamientos, servíme al principio de cierta Revista médica
profesional, la Gaceta Médica Catalana. Pero en rápido crescendo la
marea ideal y la impaciencia por publicar, este cauce me resultaba
estrecho. Contrariábame mucho la lentitud de la imprenta y la tiranía
de las fechas. Para sacudir de una vez tales trabas, decidí publicar
por mi cuenta una nueva Revista, la Revista trimestral de Histología
normal y patológica. El primer cuaderno vió la luz en Mayo de 1888
y el segundo apareció en el mes de Agosto del mismo año.
Naturalmente, todos los artículos, en número de seis, brotaron de mi
pluma. De mis manos salieron también las seis tablas litográficas
anejas. Razones económicas obligáronme á no tirar, por entonces,
en junto, más de 60 ejemplares, destinados casi enteramente á los
sabios extranjeros.
Excusado es decir que la vorágine de publicidad absorbió
enteramente mis ingresos ordinarios y extraordinarios. Ante aquella
racha asoladora de gastos, mi pobre mujer, atareada con la cría y
vigilancia de cinco diablillos (durante el primer año de mi estancia en
Barcelona me nació un hijo más), resolvió pasarse sin criada.
Adivinaba, sin duda, en mi cerebro, la gestación de algo insólito y
decisivo para el porvenir de la familia, y evitó, discreta y
abnegadamente, todo conato de competencia y de envidia entre los
hijos de la carne y las criaturas del espíritu.
CAPÍTULO VI
Algunos detalles tocantes á mis trabajos de 1888. —
Las cestas del cerebelo, el axon de los granos y
las fibras musgosas y trepadoras. — Valor decisivo
de estos encuentros para la resolución del
problema de la conexión intercelular. — Teoría
reticular de Gerlach y de Golgi. — Los atisbos
geniales de His y Forel. — Confirmación en la
retina y lóbulo óptico de las leyes conectivas
inducidas del análisis del cerebelo. — Plan
estructural de la médula espinal. — Averiguación
del modo de terminar en los centros los nervios
sensitivos y sensoriales. — Otros trabajos menos
importantes.

onsignadas en el capítulo precedente, en síntesis abreviada, las


conclusiones más generales de mis estudios en los centros
nerviosos durante los años 1888 y 1889, séame lícito entrar
ahora en la exposición somera, y lo más clara posible, de los
hallazgos más interesantes. Estos hallazgos refiérense al cerebelo de
las aves y mamíferos, á la retina, á la médula espinal y al lóbulo
óptico de las aves.
Cerebelo.—Mis estudios sobre la estructura de este centro
nervioso iniciáronse en las aves jóvenes y adultas; siguieron luego
los referentes al cerebelo de los mamíferos. Dos Memorias, amén de
algunas comunicaciones preventivas, consagramos, desde 1888 á
1889, á este fecundo tema.

Fig. 1.—Corte transversal de una lámina cerebelosa. Figura semiesquemática.— A y


B, células estrelladas de la capa molecular (células de cesta), cuyo axon (a)
genera nidos terminales en torno de las células de Purkinje (C); b, axon de estos
últimos corpúsculos.

En la primera, publicada en Mayo de 1888[36], constan ya los


principales hechos sobre que se fundan las leyes anatomo-
fisiológicas enunciadas en el capítulo precedente. En efecto; con
ocasión del análisis del axon de las células estrelladas pequeñas de
la capa molecular del cerebelo, se describe por primera vez el modo
real de terminación de las fibras nerviosas en la substancia gris,
problema sobre el cual sólo poseíamos soluciones hipotéticas. De
esta interesante observación, comprobada después por numerosos
autores (Kölliker, van Gehuchten, Retzius, Edinger, v. Lenhossék,
Athias, etc.), damos copia en la figura 1, C, correspondiente al
cerebelo de los mamíferos. Nótese cómo el cilindro-eje de las
referidas células estrelladas pequeñas marcha desde luego en
dirección transversal á la circunvolución cerebelosa, describiendo un
curso arciforme, y emitiendo numerosas ramas colaterales,
caracterizadas por la propiedad de espesarse progresivamente. En
fin, tanto el remate de la expansión funcional como sus numerosas
proyecciones descendentes, se resuelven en ciertos flecos ó borlas
terminales, íntimamente aplicadas al cuerpo de las células de
Purkinje, en torno de las cuales generan á modo de nido ó cesta
complicados.
Digno de mencionarse es también, por su valor teórico, el
encuentro en la capa de los granos de un tipo especial de fibra
centrípeta, bautizada con el nombre de fibra musgosa, la cual
exhibe, tanto en su cabo final como en sus ramas colaterales (fig. 2,
a), ciertas eflorescencias ó rosáceas, de apéndices cortos, tuberosos,
libremente terminados. Ulteriores observaciones nuestras pusieron
de manifiesto que semejantes excrecencias entran en estrecha
articulación con las arborizaciones digitiformes de los granos,
arborizaciones descritas también por primera vez, dicho sea de
pasada, en la comunicación aludida.
En fin, en el citado trabajo se llama asimismo la atención de los
sabios acerca de la existencia en derredor de las dendritas de los
corpúsculos de Purkinje y, en general, de toda prolongación
protoplásmica, de una especie de vello de finísimos y cortos
apéndices (espinas peridendríticas), confirmadas y estudiadas
después por numerosos autores.
La segunda comunicación relativa al cerebelo, publicada en
Agosto de 1888[37], contiene dos hechos capitales:
a) El descubrimiento del axon delicadísimo de los granos (células
pequeñísimas de la zona segunda de la corteza cerebelosa)[38], el
cual, según mostramos en la figura 2, d, c, asciende á la capa
molecular, donde, á diversas alturas para cada célula, se divide en
ángulo recto, produciendo dos sutilísimas ramas orientadas en
opuesto sentido (figura 2, e). Estas larguísimas proyecciones, que
llamé fibras paralelas, á causa de marchar paralelamente en el
sentido de la circunvolución cerebelosa, y por tanto, en dirección
normal al ramaje de las células de Purkinje, aparecen en cantidad
formidable, rellenan todos los intersticios de la zona molecular y, tras
largo é indiviso trayecto, acaban en los extremos de cada lámina.
Tan general es su existencia y uniforme su disposición, que se las
encuentra casi con los mismos caracteres en toda la serie de los
vertebrados, desde el pez hasta el hombre. Constituyen, pues, un
factor importante del centro cerebeloso.
b) El otro afortunado encuentro es el de las fibras trepadoras (fig.
3, c). Estos robustos conductores emanan de los ganglios de la
protuberancia; invaden el eje blanco central de las láminas
cerebelosas; cruzan, sin ramificarse, la capa de los granos; asaltan
después el plano de las células de Purkinje, y costean, en fin, el
soma y tallo principal de estos elementos, á los cuales se adaptan
estrechamente. Arribadas al nivel de los primeros brazos del citado
tronco dendrítico, descompónense en plexos paralelos serpenteantes
que ascienden á lo largo de las ramas protoplásmicas, á cuyo
contorno se aplican, al modo de la hiedra ó de las lianas al tallo de
los árboles (fig. 3, a).
Fig. 2.—Corte longitudinal de una circunvolución cerebelosa.— A, capa molecular; B,
capa de las células de Purkinje; C, capa de los granos; D, substancia blanca; a,
rosáceas de las fibras musgosas; b, soma de las células de Purkinje; c, fibrillas
paralelas; d, granos con su axon ascendente; e, división de este axon. (Figura
semiesquemática).

Tan afortunado hallazgo, uno de los más bellos con que me


agasajó el azar en aquella época fecunda, significaba la prueba
terminante de la transmisión de los impulsos nerviosos por contacto.
Así lo reconocieron sabios insignes al comprobar, años después, mi
descripción de las fibras musgosas y trepadoras.
Fig. 3.—Trozo de un corte transversal de una circunvolución.— A, capa molecular; B,
capa de los granos; C, células de Purkinje; a, arborización trepadora; b, axon de
Purkinje; c, cilindro-eje llegado de la substancia blanca y ramificado sobre las
dendritas de las células de Purkinje.

Al dar cuenta de la labor del trienio de 1891 á 1894, añadiré otros


encuentros de menos importancia concernientes á la corteza
cerebelosa. Para alivio del lector poco familiarizado con estas
materias, reproducimos aquí una figura donde se presenta, de modo
esquemático, el estado de nuestros conocimientos sobre el cerebelo
después de mis observaciones de 1888 y 1889. Este esquema (fig.
4) fué compuesto para ilustrar unas conferencias pronunciadas más
tarde (1894) ante la Academia de Ciencias Médicas de Cataluña. Del
éxito inesperado de estas lecciones, que se tradujeron
inmediatamente al francés, inglés y alemán, diré algo más adelante.
Fig. 4.—Corte transversal semiesquemático de una circunvolución cerebelosa de
mamífero.— A, zona molecular; B, zona de los granos; C, zona de la substancia
blanca; a, célula de Purkinje vista de plano; b, células estrelladas pequeñas de la
zona molecular; d, arborizaciones finales descendentes que rodean las células de
Purkinje; e, células estrelladas superficiales; g, granos con sus cilindros-ejes
ascendentes bifurcados en i; h, fibras musgosas; j, célula neuróglica de penacho;
n, fibras trepadoras; m, célula neuróglica de la zona de los granos; f, células
estrelladas grandes de la zona de los granos.

Las conclusiones de mis investigaciones acerca del cerebelo


contradecían rudamente las ideas, á la sazón reinantes, sobre la fina
anatomía de la substancia gris. Claro es que mis puntos de vista
eran harto revolucionarios para ser fácilmente admitidos. Mas por
esta vez abrigaba la certidumbre de no haberme equivocado;
porque, en realidad, las leyes enunciadas venían á ser la expresión
ingenua de los hechos, sin mezcla alguna de subjetivismo. No se
trataba ahora de una hipótesis más, sino de una inducción legítima
con todas las garantías lógicas apetecibles, según reconocieron más
tarde insignes histólogos y neurólogos. Estaba yo demasiado
escarmentado por el error cometido al interpretar temerariamente la
estructura del tejido muscular, para proceder de ligero ó dejarme
seducir por una mera concepción teórica, propia ó ajena.
Á fin de que el lector siga fácilmente el curso de mis trabajos y
excuse el tono polémico de algunos de mis futuros escritos, conviene
exponer aquí, en breves términos, las opiniones reinantes por
entonces entre los sabios sobre la constitución íntima de la
substancia gris.
Dos hipótesis principales se disputaban el campo de la ciencia: la
del retículo, defendida por casi todos los neurólogos; la de la libre
terminación, insinuada tímidamente por dos solitarios, His y Forel,
sin eco en las escuelas.
La hipótesis de la red era el formidable enemigo. Note el lector,
que también aquí, á semejanza de lo ocurrido en la fibra muscular
estriada, nos salía al paso el prejuicio del retículo; sin embargo, en
esta ocasión la supuesta rejilla difusa no era intracelular, sino
intercelular. Creada por Gerlach, sostenida después por Meynert y
otros neurólogos célebres, durante una época en que la penuria
metodológica excusaba las aventuras de la fantasía, la teoría
reticular recibió, al fin, de Golgi una forma arquitectónica nueva y
atrayente, y hasta cierta apariencia de apoyo en los hechos de
observación.
Para el sabio de Pavía, la substancia gris constituye el punto de
encuentro y fusión de todas las fibras aferentes y eferentes de los
centros nerviosos, así como de los axones de los elementos
autóctonos. Á este retículo, continuo y de formidable riqueza fibrilar,
concurrirían los siguientes factores: 1.º, las ramificaciones terminales
de los cilindros-ejes sensitivos ó simplemente aferentes de otros
centros nerviosos; 2.º, las ramas colaterales del axon de ciertos
elementos grandes, designados por Golgi células motrices (grandes
pirámides cerebrales, células de Purkinje del cerebelo, etc.) y que yo
bauticé, para no prejuzgar su fisiologismo, elementos de axon largo;
y 3.º, las arborizaciones terminales del cilindro-eje de otras células
nerviosas, consideradas arbitrariamente como sensitivas (Golgi) y
que yo califiqué células de axon corto.
Á diferencia de Gerlach, según el cual cooperarían también en la
construcción del retículo difuso las últimas proyecciones del ramaje
protoplásmico neuronal, Golgi redujo los componentes del mismo á
las ramificaciones nerviosas. Para que el lector, ajeno á esta clase de
asuntos, pueda comprender fácilmente las hipótesis reticulares de
Gerlach y de Golgi, reproducimos esquemáticamente la manera
según la cual los referidos sabios concebían las comunicaciones
anatomo-fisiológicas entre las raíces motrices y sensitivas de la
médula espinal (fig. 5, C y fig. 9, I).
Fig. 5.—Esquema de la estructura de la substancia gris de la médula espinal, según
los autores de la época pregolgiana.— A, raíces anteriores; B, raíz posterior; C,
red intersticial de la substancia gris; D, surco anterior de la médula; E, cordón de
Goll; F, cordón de Burdach; H, célula motriz; I, vía piramidal cruzada; G, columna
de Clarke; J, ganglio sensitivo.

Dejamos expresado que la capacidad sugestiva de ciertas


fórmulas, extremadamente esquemáticas, depende de su
comodidad. Admitido el supuesto de la red, nada más fácil que el
estudio objetivo de un grupo de neuronas ó del comportamiento
terminal de un manojo de conductores; redúcese todo á dar por
averiguado que, las últimas raicillas nerviosas, previas algunas
dicotomías, se pierden y desvanecen en la consabida red intersticial;
en esa especie de piélago fisiológico insondable, en el cual, por un
lado, desembocarían las corrientes arribadas de los órganos
sensoriales, y de donde brotarían, por otro, á modo de ríos surgidos
de alpinos lagos, los conductores motores ó centrífugos. Comodín
admirable, porque dispensa de todo esfuerzo analítico encaminado á
determinar en cada caso el itinerario seguido al través de la
substancia gris por el impulso nervioso. Con razón se ha dicho que la
hipótesis reticular, en fuerza de pretender explicarlo todo llana y
sencillamente, no explica absolutamente nada; y lo que es más
grave, embaraza y casi hace superfluas las futuras pesquisas
tocantes á la organización íntima de los centros. Sólo á fuerza de
habilidades, de inconsecuencias, de subterfugios, podía la susodicha
concepción (por lo demás, defendida casi exclusivamente por Golgi y
sus discípulos inmediatos) adaptarse á las exigencias de la fisiología,
cuya doctrina de los reflejos, actos instintivos, localizaciones
funcionales del cerebro, etc., demandan imperiosamente el
señalamiento de vías ó cauces de conducción, perfectamente
circunscritos, al través del eje cerebro-raquídeo.
Enfrente de la teoría de las redes militaban solamente, según
dejamos dicho, dos observadores de gran mérito, His y Forel,
quienes, con reservas y prudencias excusables por la carencia de
hechos precisos de observación, anunciaron (1887) la posibilidad de
que las expansiones de las células nerviosas se terminaran
libremente en la substancia gris. Consecuencia natural de tal modo
de ver era la transmisión por contacto de los impulsos nerviosos. Así,
Forel, vista la imposibilidad de sorprender anastomosis evidentes en
el seno de la substancia gris, daba por probable que las expansiones
neuronales se tocaban entre sí, á semejanza de las frondas ó copas
en el bosque. En cuanto al ilustre profesor de Leipzig, procediendo
por generalización (1886), conjeturaba que, pues las arborizaciones
nerviosas (entonces bien conocidas) de la placa motriz acaban
libremente, según es notorio, entrando en contacto con la materia
estriada, estimaba lógico admitir igual disposición terminal para los
conductores distribuídos y ramificados en los centros cerebro-
raquídeos.
Mas al discurrir de esta suerte, His y Forel no abandonaban la
esfera de las hipótesis. Imposible resultaba, sin descender al terreno
del análisis estructural, refutar á Golgi, quien, á las tímidas
alegaciones teóricas de aquellos sabios, contraponía aparatoso
alegato de observaciones concienzudas. Para resolver
definitivamente la cuestión, precisaba presentar neta, exacta é
indiscutiblemente las últimas ramificaciones de los cilindros-ejes
centrales, no vistas por nadie, y determinar además entre qué
factores celulares se efectúa el imaginado contacto. Porque admitir
vagamente el hecho de la transmisión mediata ó articulación
interneuronal, sin señalar con precisión entre qué apéndices
celulares se produce, resulta casi tan cómodamente peligroso como
la socorrida teoría reticular. Supongamos, por ejemplo: según parece
deducirse de las manifestaciones de Forel, que el susodicho contacto
afecta carácter difuso, verificándose entre dendritas pertenecientes á
vecinas neuronas, ó entre ramificaciones axónicas de diverso origen,
ó, en fin, entre apéndices protoplásmicos y raicillas nerviosas
terminales. La consecuencia fatal, indeclinable de tal supuesto será
la indeterminación de los cauces de la vibración nerviosa, y, en el
fondo, la reedición, bajo nueva forma, de la teoría reticular, de esa
especie de panteísmo protoplásmico, tan grato á los comodones de
la observación como contrario á los postulados de la neurogenia, de
la fisiología y de la anatomía patológica. Afirmar que todo se
comunica con todo, vale tanto como declarar la absoluta
incognoscibilidad del órgano del alma.
Nuestra obra consistió, precisamente, en prestar base objetiva á
los geniales pero vagos atisbos de His y Forel. Con el encuentro
afortunado de las cestas terminales y de las fibras trepadoras,
demostramos que el contacto no se verifica entre dendritas solas, ni
entre arborizaciones nerviosas, sino entre éstas, de una parte, y el
soma y prolongaciones protoplásmicas neuronales, de otra; que, en
fin, una célula contrae, á menudo, conexiones con arborizaciones
nerviosas de diversa procedencia, y que, recíprocamente, cada axon
admite contacto, mediante colaterales y ramas terminales, con
diferentes tipos de neuronas; no obstante lo cual, quedan
reservadas en la substancia gris vías bien deslindadas de
conducción, de acuerdo con las exigencias de la fisiología y la
patología nerviosas.
Dejamos dicho que las concepciones legítimas se reconocen en
que, en vez de perder, ganan y se robustecen ante las nuevas
observaciones. Tal le ocurrió á la ley de la transmisión por contacto,
sometida al contraste del análisis estructural de la retina y centros
ópticos.
Retina.—Fué en la retina de las aves donde iniciamos esta labor
de contraste. Ocioso é inoportuno fuera, después de las
consideraciones precedentes, entrar aquí en detalles descriptivos.
Bástenos señalar sucintamente los nuevos hechos contenidos en la
aludida comunicación[39].
a) Demostración de que los conos y bastones se terminan libremente al
nivel de la capa plexiforme externa, articulándose con el penacho exterior de
las células bipolares (fig. 6).
b) Descubrimiento, debajo de la capa plexiforme externa, de unos
elementos especiales en forma de brocha y provistos de dendritas
ascendentes repartidas en dicha zona (fig. 6, h).
c) Hallazgo de las fibras centrífugas de la retina, es decir, de una categoría
especial de fibras del nervio óptico, que, después de cruzar la zona
plexiforme interna, acaban por una arborización varicosa y libre entre los
espongioblastos. Este hecho interesante, que ha servido de base, entre otras
concepciones fecundas, á la teoría de los nervo-nervorum de Duval, fué
confirmado por Dogiel, quien lo había negado en un principio (fig. 8, b, c, d,
e).
d) Descubrimiento, simultáneamente con Dogiel (Anatomischen Anzeiger,
Mayo de 1888), de la maza de Landolt, en las células bipolares de las aves y
de las colaterales de las expansiones descendentes de éstas (fig. 7, A).
e) Descripción de muchos tipos morfológicos nuevos de espongioblastos
(células nerviosas exentas de axon).
Fig. 6.—Capas de los granos externos y plexiforme externa de la retina de las aves.—
a, b, d, variedades de conos; c, bastones; h, células horizontales.

f) Demostración de varios pisos de arborización nerviosa en la zona


plexiforme interna, revelando que, á estos niveles, las dendritas de las
células ganglionares se relacionan, por contacto, con la ramificación
descendente y ramas colaterales de las bipolares, y no mediante red difusa,
según había descrito Tartuferi en la retina de los mamíferos (fig. 7, A, B).
g) Exposición de muchos detalles morfológicos de las fibras de Müller de
las aves.

En las figuras 6, 7 y 8 mostramos esquemáticamente lo más


esencial de mis hallazgos en la retina. Nótese, sobre todo, cómo las
tres series de neuronas (conos y bastones, bipolares y gangliónicas)
se articulan, según dos planos concéntricos.
Husos musculares.—De cierto alcance para la fisiología
muscular resulta también un pequeño trabajo aparecido en el mismo
número de la Revista de Histología, y titulado Terminaciones
nerviosas en los husos musculares de la rana[40].
Fig. 7.—Esquema donde se muestran las conexiones entre las diversas neuronas de
la retina de las aves y la marcha del impulso nervioso— A, células bipolares.

En esta comunicación, basada en las revelaciones del método de


Ehrlich al azul de metileno, se hace notar:
a) La existencia en los husos de Kühne de los batracios y reptiles (fibras
musculares pequeñas portadoras de un órgano nervioso terminal específico
y, al parecer, sensitivo, pero de significación dudosa por entonces) de dos
clases de arborizaciones nerviosas: una, la ya conocida por los autores,
continuada con fibras gruesas; otra ú otras, no descritas, más finas, situadas
en las regiones alejadas de la tumefacción fusiforme.
b) En vista de que una de las terminaciones es enteramente idéntica á la
de las placas motrices ordinarias, y que la otra posee caracteres en un todo
semejantes á los observados en los órganos músculo-tendinosos de Golgi,
califícase la arborización pequeña de motriz, y la extensa ó específica de
sensitiva. La excitación de este último aparato terminal, durante la
contracción de los músculos, suscitaría, al llegar al cerebro, la percepción del
estado de contracción de los músculos (sentido muscular de que hablan los
fisiólogos).

Fig. 8.—Algunos tipos de células gangliónicas (B, C) de la retina de las aves; e, b, d,


f, arborización final de las fibras centrífugas.

Parecidos hechos fueron posteriormente comunicados por Ruffini, Huber y


de Witt, Dogiel, Sherrington, etc., quienes adoptaron también, aunque sin
conocerla, nuestra interpretación fisiológica. Opinión semejante defendió
asimismo, en igual fecha que nosotros, Kerschner (Anat. Anzeiger, 1.º de
Mayo de 1888), aunque sin precisar detalles ni dar figuras de la doble
terminación.

En fin, para poner remate á esta pesada reseña acerca de la labor


de 1888, citemos aún dos artículos, de menos enjundia que los
precedentes.
El primero, concerniente á la textura de la fibra muscular del
corazón[41], contenía, entre otros hechos, los siguientes:
a) Demostración, en torno de las fibras cardíacas, de un verdadero
sarcolema, más fino que el de las células estriadas comunes. (Confirmado
muchos años después por Hoche, Ebner, Heidenhain, Marceau, etc.).
b) Indicación de que las llamadas placas ó escaleras de cemento
intercalar de las células cardíacas corresponden á las líneas de Krause, y
ofrecen una situación infrasarcolemática.
El segundo artículo versaba sobre las células y tubos nerviosos
del lóbulo cerebral eléctrico del torpedo[42], donde el tamaño colosal
de los elementos presta singulares facilidades al análisis. Á favor de
la disociación y del método de Boveri (mezcla de ácido ósmico y
nitrato de plata), se pusieron de manifiesto los siguientes hechos:
a) Existencia de positivas estrangulaciones en los tubos conductores de un
centro nervioso, las cuales habían sido negadas por Ranvier y sólo
mencionadas en la substancia blanca de la médula espinal por Tourneaux y
Le Goff.
b) Presencia de un anillo de cemento en el punto del axon en que se inicia
la mielina, y de dos anillos al nivel de las estrangulaciones del tubo medular.
c) Ausencia de anastomosis de las ramificaciones protoplásmicas de las
células, disposición que confirmaba los resultados del método de Golgi.
d) Aparición, en torno del cuerpo de las neuronas, de una fina cubierta.
Esta particularidad sólo muchos años después fué ratificada por los autores.

Hasta aquí, lo publicado en 1888.


Médula espinal.—Durante el año 1889, mi actividad continuó
vigorosa y despierta, aplicándose á diversos temas neurológicos; sin
embargo, concentróse especialmente en el estudio de la médula
espinal de aves y mamíferos.
Al abordar este asunto, cuya obscuridad conocía bien por haberla
padecido muchas veces al explicar, como profesor de Anatomía, la
organización del eje raquídeo, movióme, en primer término, el
propósito de dilucidar en lo posible el arduo problema de la
terminación de las raíces posteriores ó sensitivas. Y aunque, después
de mis exploraciones acerca del cerebelo, resultaba presumible que
semejantes arborizaciones siguieran también la ley del contacto
pericelular, era indispensable confirmar de visu esta concordancia,
averiguar con precisión el itinerario real de las fibras sensitivas al
través de la substancia gris, y señalar, en fin, las neuronas con ellas
relacionadas.
Antes de puntualizar mis observaciones, no estará de más
recordar brevemente al lector el estado de nuestros conocimientos
acerca de la organización á la médula espinal allá por los años de
1880 á 1889.
Ciertamente, los experimentos de la fisiología y los datos
recolectados por la anatomía patológica humana y comparada,
asistida del método de las degeneraciones secundarias (Waller, Türk,
Charcot, Bouchard, Lowenthal, Münzer) ó del de las atrofias de
Gudden y Forel, habían logrado fijar el carácter motor ó sensitivo de
muchos nervios, localizar grosso modo el núcleo de origen de los
centrífugos y de terminación de los centrípetos, y diferenciar, en fin,
en el espesor de los cordones, vías ó categorías separadas de fibras
de idéntica conducción (vía piramidal ó de los movimientos
voluntarios, vía cerebelosa ascendente, cordón de Goll formado por
fibras sensitivas centrales, etc.). Por su parte, el análisis macro-
microscópico había alcanzado algunos éxitos positivos, deslindando
en la substancia gris, aparte esas grandes provincias llamadas astas
anterior y posterior, ciertos territorios de peculiar estructura, tales
como: las pléyades celulares motrices del asta ventral, la substancia
gris central, la columna vesiculosa de Clarke, la substancia de
Rolando, las comisuras blanca ó anterior y gris ó posterior, etc. Se
sabía igualmente, ó más bien se adivinaba —porque demostración
fehaciente del hecho no existía— que los tubos de la substancia
blanca están en continuación con axones de neuronas emplazadas
en la substancia gris, los cuales, después de un curso longitudinal
más ó menos largo, retornaban al territorio de las astas, donde
primeramente se congregan en haces de varia dirección, para
dispersarse al fin en plexo difuso y enmarañado.
Pero acerca de los puntos principales de la histología del eje
medular raquídeo, esto es, sobre el problema del origen y
terminación de las fibras arribadas de los cordones, el origen de las
comisuras y, en suma, la disposición final de las fibras exógenas ó
sensitivas, los neurólogos sólo exponían conjeturas frecuentemente
obscuras, á veces contradictorias y en todo caso incomprobables. En
realidad, la histología de dicho centro nervioso ofrecía sólo un dato
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!

ebooknice.com

You might also like