Roberto ierusalimschy. programming in lua. second edition

Programming ROBERTO IERUSALIMSCHY
in
Lua
2nd
edition
Lua.org
Last update: Wed Jan 13 12:07:33 UTC 2010
Programming in Lua

Programming in Lua
Second Edition
Roberto Ierusalimschy
PUC-Rio, Brazil
Lua.org
Rio de Janeiro
Property of Ian Bloss
Programming in Lua, Second Edition
by Roberto Ierusalimschy
ISBN 85-903798-2-5
Copyright c 2006, 2003 by Roberto Ierusalimschy. All rights reserved.
The author can be contacted at roberto@lua.org.
Book cover and illustrations by Dimaquina. Lua logo design by Alexandre Nako.
Typesetting by the author using LTEX. A
Although the author used his best efforts preparing this book, he assumes no
responsibility for errors or omissions, or for any damage that may result from
the use of the information presented here. All product names mentioned in this
book are trademarks of their respective owners.
́
CIP – Biblioteca do Departamento de Informatica, PUC-Rio
Ierusalimschy, Roberto
I22 Programming in Lua / Roberto Ierusalimschy. – 2nd ed.
– Rio de Janeiro, 2006.
xviii, 308 p. : 25 cm.
Includes index.
ISBN 85-903798-2-5
1. Lua (Programming language). I. Title.
005.133 – dc20

to Ida, Noemi, and Ana Lucia

Contents
Preface xiii
I The Language 1
1 Getting Started 3
1.1 Chunks 4
1.2 Some Lexical Conventions 5
1.3 Global Variables 6
1.4 The Stand-Alone Interpreter 7
2 Types and Values 9
2.1 Nil 10
2.2 Booleans 10
2.3 Numbers 10
2.4 Strings 11
2.5 Tables 13
2.6 Functions 17
2.7 Userdata and Threads 17
3 Expressions 19
3.1 Arithmetic Operators 19
3.2 Relational Operators 20
3.3 Logical Operators 21
3.4 Concatenation 22
3.5 Precedence 22
3.6 Table Constructors 22
vii

viii Contents
4 Statements 27
4.1 Assignment 27
4.2 Local Variables and Blocks 28
4.3 Control Structures 30
4.4 break and return 34
5 Functions 35
5.1 Multiple Results 36
5.2 Variable Number of Arguments 39
5.3 Named Arguments 42
6 More About Functions 45
6.1 Closures 47
6.2 Non-Global Functions 50
6.3 Proper Tail Calls 52
7 Iterators and the Generic for 55
7.1 Iterators and Closures 55
7.2 The Semantics of the Generic for 57
7.3 Stateless Iterators 58
7.4 Iterators with Complex State 60
7.5 True Iterators 61
8 Compilation, Execution, and Errors 63
8.1 Compilation 63
8.2 C Code 67
8.3 Errors 67
8.4 Error Handling and Exceptions 69
8.5 Error Messages and Tracebacks 70
9 Coroutines 73
9.1 Coroutine Basics 73
9.2 Pipes and Filters 76
9.3 Coroutines as Iterators 79
9.4 Non-Preemptive Multithreading 81
10 Complete Examples 87
10.1 Data Description 87
10.2 Markov Chain Algorithm 91
II Tables and Objects 95
11 Data Structures 97
11.1 Arrays 97

ix
11.2 Matrices and Multi-Dimensional Arrays 98
11.3 Linked Lists 100
11.4 Queues and Double Queues 100
11.5 Sets and Bags 101
11.6 String Buffers 103
11.7 Graphs 104
12 Data Files and Persistence 107
12.1 Data Files 107
12.2 Serialization 109
13 Metatables and Metamethods 117
13.1 Arithmetic Metamethods 118
13.2 Relational Metamethods 120
13.