aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-05-12 16:19:18 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-05-12 16:19:18 -0300
commit69b45bb4e9b08469e9fe2148d0aebf49ec54c6d2 (patch)
tree7b61d6845e6fa053cd0affc91548c65d938310c3
parent843f84f4ce64bf43d8ebe568d8d1eeae9f484caf (diff)
downloadlua-69b45bb4e9b08469e9fe2148d0aebf49ec54c6d2.tar.gz
lua-69b45bb4e9b08469e9fe2148d0aebf49ec54c6d2.tar.bz2
lua-69b45bb4e9b08469e9fe2148d0aebf49ec54c6d2.zip
changes by lhf
-rw-r--r--manual.tex1840
1 files changed, 1088 insertions, 752 deletions
diff --git a/manual.tex b/manual.tex
index 3784b4ea..7d0494e9 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,21 +1,23 @@
1% $Id: manual.tex,v 1.35 2000/04/14 17:47:55 roberto Exp roberto $ 1% $Id: manual.tex,v 1.36 2000/04/17 19:23:48 roberto Exp roberto $
2 2
3\documentclass[11pt]{article} 3\documentclass[11pt]{article}
4\usepackage{fullpage,bnf} 4\usepackage{fullpage,bnf}
5\usepackage{graphicx}
6%\usepackage{times}
5 7
6\catcode`\_=12 8\catcode`\_=12
7 9
8\newcommand{\See}[1]{Section~\ref{#1}} 10\newcommand{\See}[1]{Section~\ref{#1}}
9\newcommand{\see}[1]{(see \See{#1})} 11\newcommand{\see}[1]{(see \See{#1})}
10\newcommand{\M}[1]{\emph{#1}} 12\newcommand{\M}[1]{\rm\emph{#1}}
11\newcommand{\T}[1]{{\tt #1}} 13\newcommand{\T}[1]{{\tt #1}}
12\newcommand{\Math}[1]{$#1$} 14\newcommand{\Math}[1]{$#1$}
13\newcommand{\nil}{{\bf nil}} 15\newcommand{\nil}{{\bf nil}}
14\newcommand{\Line}{\rule{\linewidth}{.5mm}}
15\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} 16\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
16 17
17\newcommand{\Index}[1]{#1\index{#1}} 18\newcommand{\Index}[1]{#1\index{#1}}
18\newcommand{\IndexVerb}[1]{\T{#1}\index{#1}} 19\newcommand{\IndexVerb}[1]{\T{#1}\index{#1}}
20\newcommand{\IndexEmph}[1]{\emph{#1}\index{#1}}
19\newcommand{\Def}[1]{\emph{#1}\index{#1}} 21\newcommand{\Def}[1]{\emph{#1}\index{#1}}
20\newcommand{\Deffunc}[1]{\index{#1}} 22\newcommand{\Deffunc}[1]{\index{#1}}
21 23
@@ -23,75 +25,46 @@
23 25
24\newcommand{\Version}{4.0} 26\newcommand{\Version}{4.0}
25 27
28% LHF
29\renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
30\newcommand{\NOTE}{\par\noindent\emph{NOTE}: }
31
26\makeindex 32\makeindex
27 33
28\begin{document} 34\begin{document}
29 35
30\title{Reference Manual of the Programming Language Lua \Version} 36%{===============================================================
31
32\author{%
33Roberto Ierusalimschy\quad
34Luiz Henrique de Figueiredo\quad
35Waldemar Celes
36\vspace{1.0ex}\\
37\smallskip
38\small\tt lua@tecgraf.puc-rio.br
39\vspace{2.0ex}\\
40%MCC 08/95 ---
41\tecgraf\ --- Computer Science Department --- PUC-Rio
42}
43
44\date{{\small \tt\$Date: 2000/04/14 17:47:55 $ $}}
45
46\maketitle
47
48\thispagestyle{empty} 37\thispagestyle{empty}
49\pagestyle{empty} 38\pagestyle{empty}
50 39
51\begin{abstract} 40{
52\noindent 41\parindent=0pt
53Lua is a programming language originally designed for extending applications, 42\vglue1.5in
54but also frequently used as a general-purpose, stand-alone language. 43{\LARGE\bf
55Lua combines simple procedural syntax (similar to Pascal) 44The Programming Language Lua}
56with powerful data description constructs based on associative 45\hfill
57arrays and extensible semantics. 46\vskip4pt \hrule height 4pt width \hsize \vskip4pt
58Lua is dynamically typed, interpreted from opcodes, 47\hfill
59and has automatic memory management with garbage collection, 48Reference Manual for Lua version \Version
60making it ideal for configuration, scripting, and rapid prototyping. 49\\
61 50\null
62This document describes version \Version\ of the Lua programming language 51\hfill
63and the API that allows interaction between Lua programs and their 52Last revised on \today
64host C programs. 53\\
65\end{abstract} 54\vfill
66\vspace{4ex} 55\centering
67\begin{quotation} 56\includegraphics[width=0.7\textwidth]{nolabel.ps}
68\small 57\vfill
69\begin{center}{\bf Sum\'ario}\end{center} 58\vskip4pt \hrule height 2pt width \hsize
70\vspace{1ex} 59}
71\noindent
72Lua \'e uma linguagem de programa\c{c}\~ao originalmente projetada para
73extens\~ao de aplica\c{c}\~oes,
74e que \'e tamb\'em frequentemente usada como uma linguagem de
75prop\'osito geral.
76Lua combina uma sintaxe procedural simples (similar a Pascal)
77com poderosas facilidades para descri\c{c}\~ao de dados baseadas
78em tabelas associativas e uma sem\^antica estens\'{\i}vel.
79Lua tem tipagem din\^amica, \'e interpretada via opcodes,
80e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo,
81tornando-se ideal para configura\c{c}\~ao, scripting,
82e prototipagem r\'apida.
83
84Este documento descreve a vers\~ao \Version\ da linguagem de
85programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite
86a intera\c{c}\~ao entre programas Lua e programas C hospedeiros.
87\end{quotation}
88
89 60
90\newpage 61\newpage
91\begin{quotation} 62\begin{quotation}
92\parskip=10pt 63\parskip=10pt
93\noindent
94\footnotesize 64\footnotesize
65\null\vfill
66
67\noindent
95Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved. 68Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved.
96 69
97\noindent 70\noindent
@@ -127,10 +100,89 @@ Figueiredo at TeCGraf, PUC-Rio.
127 100
128\noindent 101\noindent
129This implementation contains no third-party code. 102This implementation contains no third-party code.
130\end{quotation}
131 103
104\noindent
105Copies of this manual can be obtained at
106\verb|http://www.tecgraf.puc-rio.br/lua/|.
107\end{quotation}
108%}===============================================================
132\newpage 109\newpage
133 110
111\title{Reference Manual of the Programming Language Lua \Version}
112
113\author{%
114Roberto Ierusalimschy\quad
115Luiz Henrique de Figueiredo\quad
116Waldemar Celes
117\vspace{1.0ex}\\
118\smallskip
119\small\tt lua@tecgraf.puc-rio.br
120\vspace{2.0ex}\\
121%MCC 08/95 ---
122\tecgraf\ --- Computer Science Department --- PUC-Rio
123}
124
125\date{{\small \tt\$Date: 2000/04/17 19:23:48 $ $}}
126
127\maketitle
128
129\thispagestyle{empty}
130\pagestyle{empty}
131
132\begin{abstract}
133\noindent
134Lua is a powerful, light-weight programming language
135designed for extending applications.
136Lua is also frequently used as a general-purpose, stand-alone language.
137Lua combines simple procedural syntax
138(similar to Pascal)
139with
140powerful data description constructs
141based on associative arrays and extensible semantics.
142Lua is
143dynamically typed,
144interpreted from bytecodes,
145and has automatic memory management with garbage collection,
146making it ideal for
147configuration,
148scripting,
149and
150rapid prototyping.
151
152This document describes version \Version\ of the Lua programming language
153and the API that allows interaction between Lua programs and their
154host C programs.
155\end{abstract}
156
157\def\abstractname{Resumo}
158\begin{abstract}
159\noindent
160Lua \'e uma linguagem de programa\c{c}\~ao
161poderosa e leve,
162projetada para extender aplica\c{c}\~oes.
163Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral.
164Lua combina programa\c{c}\~ao procedural
165(com sintaxe semelhante \`a de Pascal)
166com
167poderosas constru\c{c}\~oes para descri\c{c}\~ao de dados,
168baseadas em tabelas associativas e sem\^antica extens\'\i vel.
169Lua \'e
170tipada dinamicamente,
171interpretada a partir de \emph{bytecodes},
172e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo.
173Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para
174configura\c{c}\~ao,
175automa\c{c}\~ao (\emph{scripting})
176e prototipagem r\'apida.
177
178Este documento descreve a vers\~ao \Version\ da linguagem de
179programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite
180a intera\c{c}\~ao entre programas Lua e programas C hospedeiros.
181\end{abstract}
182
183\newpage
184\null
185\newpage
134\tableofcontents 186\tableofcontents
135 187
136\newpage 188\newpage
@@ -143,7 +195,7 @@ This implementation contains no third-party code.
143Lua is an extension programming language designed to support 195Lua is an extension programming language designed to support
144general procedural programming with data description 196general procedural programming with data description
145facilities. 197facilities.
146Lua is intended to be used as a light-weight, but powerful, 198Lua is intended to be used as a powerful, light-weight
147configuration language for any program that needs one. 199configuration language for any program that needs one.
148 200
149Lua is implemented as a library, written in C. 201Lua is implemented as a library, written in C.
@@ -152,8 +204,8 @@ it only works \emph{embedded} in a host client,
152called the \emph{embedding} program. 204called the \emph{embedding} program.
153This host program can invoke functions to execute a piece of 205This host program can invoke functions to execute a piece of
154code in Lua, can write and read Lua variables, 206code in Lua, can write and read Lua variables,
155and can register C functions to be called by Lua code. 207and can register C~functions to be called by Lua code.
156Through the use of C functions, Lua can be augmented to cope with 208Through the use of C~functions, Lua can be augmented to cope with
157a wide range of different domains, 209a wide range of different domains,
158thus creating customized programming languages sharing a syntactical framework. 210thus creating customized programming languages sharing a syntactical framework.
159 211
@@ -164,9 +216,28 @@ The implementation described in this manual is available
164at the following URL's: 216at the following URL's:
165\begin{verbatim} 217\begin{verbatim}
166 http://www.tecgraf.puc-rio.br/lua/ 218 http://www.tecgraf.puc-rio.br/lua/
167 ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz 219 ftp://ftp.tecgraf.puc-rio.br/pub/lua/
168\end{verbatim} 220\end{verbatim}
169 221
222Like any other reference manual,
223this document is dry in places.
224For a discussion of the decisions behind the design of Lua,
225see the papers below,
226which are available at the web site above.
227\begin{itemize}
228\item
229R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes.
230Lua---an extensible extension language.
231\emph{Software: Practice \& Experience} {\bf 26} \#6 (1996) 635--652.
232\item
233L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
234The design and implementation of a language for extending applications.
235\emph{Proceedings of XXI Brazilian Seminar on Software and Hardware} (1994) 273--283.
236\item
237L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
238Lua: an extensible embedded language.
239\emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33.
240\end{itemize}
170 241
171\section{Environment and Chunks} 242\section{Environment and Chunks}
172 243
@@ -177,7 +248,7 @@ is initialized with a call from the embedding program to
177persists until a call to \verb|lua_close|, 248persists until a call to \verb|lua_close|,
178or the end of the embedding program. 249or the end of the embedding program.
179Optionally, a user can create multiple independent global 250Optionally, a user can create multiple independent global
180environments \see{mangstate}. 251environments, and freely switch between them \see{mangstate}.
181 252
182The global environment can be manipulated by Lua code or 253The global environment can be manipulated by Lua code or
183by the embedding program, 254by the embedding program,
@@ -196,16 +267,18 @@ A chunk is simply a sequence of statements:
196\produc{chunk}{\rep{stat} \opt{ret}} 267\produc{chunk}{\rep{stat} \opt{ret}}
197\end{Produc}% 268\end{Produc}%
198Statements are described in \See{stats}. 269Statements are described in \See{stats}.
199(As usual, \rep{\emph{a}} means 0 or more \emph{a}'s, 270(The notation above is the usual extended BNF,
200\opt{\emph{a}} means an optional \emph{a} and \oneormore{\emph{a}} means 271in which
201one or more \emph{a}'s.) 272\rep{\emph{a}} means 0 or more \emph{a}'s,
273\opt{\emph{a}} means an optional \emph{a}, and
274\oneormore{\emph{a}} means one or more \emph{a}'s.)
202 275
203A chunk may be in a file or in a string inside the host program. 276A chunk may be in a file or in a string inside the host program.
204A chunk may optionally end with a \verb|return| statement \see{return}. 277A chunk may optionally end with a \verb|return| statement \see{return}.
205When a chunk is executed, first all its code is pre-compiled, 278When a chunk is executed, first all its code is pre-compiled,
206then the statements are executed in sequential order. 279and then the statements are executed in sequential order.
207All modifications a chunk effects on the global environment persist 280All modifications a chunk effects on the global environment persist
208after the chunk end. 281after the chunk ends.
209 282
210Chunks may also be pre-compiled into binary form; 283Chunks may also be pre-compiled into binary form;
211see program \IndexVerb{luac} for details. 284see program \IndexVerb{luac} for details.
@@ -216,11 +289,12 @@ Lua automatically detects the file type and acts accordingly.
216 289
217\section{\Index{Types and Tags}} \label{TypesSec} 290\section{\Index{Types and Tags}} \label{TypesSec}
218 291
219Lua is a dynamically typed language. 292Lua is a \emph{dynamically typed language}.
220Variables do not have types; only values do. 293This means that
294variables do not have types; only values do.
221Therefore, there are no type definitions in the language. 295Therefore, there are no type definitions in the language.
222All values carry their own type. 296All values carry their own type.
223Besides a type, all values also have a \Index{tag}. 297Besides a type, all values also have a \IndexEmph{tag}.
224 298
225There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, 299There are six \Index{basic types} in Lua: \Def{nil}, \Def{number},
226\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. 300\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}.
@@ -230,18 +304,18 @@ whose main property is to be different from any other value.
230while \emph{string} has the usual meaning. 304while \emph{string} has the usual meaning.
231Lua is \Index{eight-bit clean}, 305Lua is \Index{eight-bit clean},
232and so strings may contain any 8-bit character, 306and so strings may contain any 8-bit character,
233\emph{including} embedded zeros (\verb|'\0'|). 307\emph{including} embedded zeros (\verb|'\0'|) \see{lexical}.
234The \verb|type| function returns a string describing the type 308The \verb|type| function returns a string describing the type
235of a given value \see{pdf-type}. 309of a given value \see{pdf-type}.
236 310
237Functions are considered first-class values in Lua. 311Functions are considered \emph{first-class values} in Lua.
238This means that functions can be stored in variables, 312This means that functions can be stored in variables,
239passed as arguments to other functions, and returned as results. 313passed as arguments to other functions, and returned as results.
240Lua can call (and manipulate) functions written in Lua and 314Lua can call (and manipulate) functions written in Lua and
241functions written in C. 315functions written in C.
242They can be distinguished by their tags: 316The kinds of functions can be distinguished by their tags:
243all Lua functions have the same tag, 317all Lua functions have the same tag,
244and all C functions have the same tag, 318and all C~functions have the same tag,
245which is different from the tag of Lua functions. 319which is different from the tag of Lua functions.
246The \verb|tag| function returns the tag 320The \verb|tag| function returns the tag
247of a given value \see{pdf-tag}. 321of a given value \see{pdf-tag}.
@@ -263,7 +337,7 @@ Tables are the main data structuring mechanism in Lua.
263To represent \Index{records}, Lua uses the field name as an index. 337To represent \Index{records}, Lua uses the field name as an index.
264The language supports this representation by 338The language supports this representation by
265providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. 339providing \verb|a.name| as syntactic sugar for \verb|a["name"]|.
266Tables may also carry methods: 340Tables may also carry \emph{methods}:
267Because functions are first class values, 341Because functions are first class values,
268table fields may contain functions. 342table fields may contain functions.
269The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, 343The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
@@ -281,10 +355,10 @@ Tags are mainly used to select \emph{tag methods} when
281some events occur. 355some events occur.
282Tag methods are the main mechanism for extending the 356Tag methods are the main mechanism for extending the
283semantics of Lua \see{tag-method}. 357semantics of Lua \see{tag-method}.
284Each of the types \M{nil}, \M{number} and \M{string} has a different tag. 358Each of the types \M{nil}, \M{number}, and \M{string} has a different tag.
285All values of each of these types have this same pre-defined tag. 359All values of each of these types have the same pre-defined tag.
286Values of type \M{function} can have two different tags, 360Values of type \M{function} can have two different tags,
287depending on whether they are Lua functions or C functions. 361depending on whether they are Lua functions or C~functions.
288Finally, 362Finally,
289values of type \M{userdata} and \M{table} have 363values of type \M{userdata} and \M{table} have
290variable tags, assigned by the program \see{tag-method}. 364variable tags, assigned by the program \see{tag-method}.
@@ -296,40 +370,42 @@ there is the function \verb|settag| \see{pdf-newtag}.
296 370
297\section{The Language} 371\section{The Language}
298 372
299This section describes the lexis, the syntax and the semantics of Lua. 373This section describes the lexis, the syntax, and the semantics of Lua.
300 374
301 375
302\subsection{Lexical Conventions} \label{lexical} 376\subsection{Lexical Conventions} \label{lexical}
303 377
304\Index{Identifiers} in Lua can be any string of letters, 378\IndexEmph{Identifiers} in Lua can be any string of letters,
305digits, and underscores, 379digits, and underscores,
306not beginning with a digit. 380not beginning with a digit.
307The definition of letter depends on the current locale: 381This coincides with the definition of identifiers in most languages,
382except that
383the definition of letter depends on the current locale:
308Any character considered alphabetic by the current locale 384Any character considered alphabetic by the current locale
309can be used in an identifier. 385can be used in an identifier.
310The following words are reserved, and cannot be used as identifiers: 386The following words are \emph{reserved}, and cannot be used as identifiers:
311\index{reserved words} 387\index{reserved words}
312\begin{verbatim} 388\begin{verbatim}
313 and break do else 389 and break do else
314 elseif end for function 390 elseif end for function
315 if local nil not 391 if local nil not
316 or repeat return then 392 or repeat return then
317 until while 393 until while
318\end{verbatim} 394\end{verbatim}
319Lua is a case-sensitive language: 395Lua is a case-sensitive language:
320\T{and} is a reserved word, but \T{And} and \T{\'and} 396\T{and} is a reserved word, but \T{And} and \T{\'and}
321(if the locale permits) are two other different identifiers. 397(if the locale permits) are two different, valid identifiers.
322As a convention, identifiers starting with underscore followed by 398As a convention, identifiers starting with underscore followed by
323uppercase letters (such as \verb|_INPUT|) 399uppercase letters (such as \verb|_INPUT|)
324are reserved for internal variables. 400are reserved for internal variables.
325 401
326The following strings denote other \Index{tokens}: 402The following strings denote other \Index{tokens}:
327\begin{verbatim} 403\begin{verbatim}
328 ~= <= >= < > == = + - * / % 404 ~= <= >= < > == = + - * / %
329 ( ) { } [ ] ; , . .. ... 405 ( ) { } [ ] ; , . .. ...
330\end{verbatim} 406\end{verbatim}
331 407
332\Index{Literal strings} can be delimited by matching single or double quotes, 408\IndexEmph{Literal strings} can be delimited by matching single or double quotes,
333and can contain the C-like escape sequences 409and can contain the C-like escape sequences
334\verb|'\a'| (bell), 410\verb|'\a'| (bell),
335\verb|'\b'| (backspace), 411\verb|'\b'| (backspace),
@@ -341,14 +417,15 @@ and can contain the C-like escape sequences
341\verb|'\\'|, (backslash), 417\verb|'\\'|, (backslash),
342\verb|'\"'|, (double quote), 418\verb|'\"'|, (double quote),
343\verb|'\''| (single quote), 419\verb|'\''| (single quote),
344and \verb|'\\n'| (that is, a backslash followed by a real newline, 420and \verb|'\|\emph{newline}\verb|'| (that is, a backslash followed by a real newline,
345which results in a newline in the string). 421which results in a newline in the string).
346A character in a string may also be specified by its numerical value, 422A character in a string may also be specified by its numerical value,
347through the escape sequence \verb|'\ddd'|, 423through the escape sequence \verb|'\ddd'|,
348where \verb|ddd| is a sequence of up to three \emph{decimal} digits. 424where \verb|ddd| is a sequence of up to three \emph{decimal} digits.
349Strings in Lua may contain any 8-bit value, including embedded zeros. 425Strings in Lua may contain any 8-bit value, including embedded zeros,
426which can be specified as \verb|'\000'|.
350 427
351Literal strings can also be delimited by matching \verb|[[ ... ]]|. 428Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|.
352Literals in this bracketed form may run for several lines, 429Literals in this bracketed form may run for several lines,
353may contain nested \verb|[[ ... ]]| pairs, 430may contain nested \verb|[[ ... ]]| pairs,
354and do not interpret escape sequences. 431and do not interpret escape sequences.
@@ -376,29 +453,30 @@ in Unix systems \see{lua-sa}.
376and an optional decimal exponent. 453and an optional decimal exponent.
377Examples of valid numerical constants are 454Examples of valid numerical constants are
378\begin{verbatim} 455\begin{verbatim}
379 3 3.0 3.1416 314.16e-2 0.31416E1 456 3 3.0 3.1416 314.16e-2 0.31416E1
380\end{verbatim} 457\end{verbatim}
381 458
382\subsection{The \Index{Pre-processor}} \label{pre-processor} 459\subsection{The \Index{Pre-processor}} \label{pre-processor}
383 460
384All lines that start with a \verb|$| sign are handled by a pre-processor. 461All lines that start with a \verb|$| sign are handled by a pre-processor.
385The \verb|$| sign must be immediately 462The following directives are understood by the pre-processor:
386followed by one of the following directives:
387\begin{description} 463\begin{description}
388\item[\T{debug}] --- turn on debugging facilities \see{pragma}. 464\item[\T{\$debug}] --- turn on debugging facilities \see{pragma}.
389\item[\T{nodebug}] --- turn off debugging facilities \see{pragma}. 465\item[\T{\$nodebug}] --- turn off debugging facilities \see{pragma}.
390\item[\T{if \M{cond}}] --- starts a conditional part. 466\item[\T{\$if \M{cond}}] --- start a conditional part.
391If \M{cond} is false, then this part is skipped by the lexical analyzer. 467If \M{cond} is false, then this part is skipped by the lexical analyzer.
392\item[\T{ifnot \M{cond}}] --- starts a conditional part. 468\item[\T{\$ifnot \M{cond}}] --- start a conditional part.
393If \M{cond} is true, then this part is skipped by the lexical analyzer. 469If \M{cond} is true, then this part is skipped by the lexical analyzer.
394\item[\T{end}] --- ends a conditional part. 470\item[\T{\$end}] --- end a conditional part.
395\item[\T{else}] --- starts an ``else'' conditional part, 471\item[\T{\$else}] --- start an ``else'' conditional part,
396flipping the ``skip'' status. 472flipping the ``skip'' status.
397\item[\T{endinput}] --- ends the lexical parse of the file. 473\item[\T{\$endinput}] --- end the lexical parse of the chunk.
474For all purposes,
475it is as if the chunk physically ended at this point.
398\end{description} 476\end{description}
399 477
400Directives may be freely nested. 478Directives may be freely nested.
401Particularly, a \verb|$endinput| may occur inside a \verb|$if|; 479In particular, a \verb|$endinput| may occur inside a \verb|$if|;
402in that case, even the matching \verb|$end| is not parsed. 480in that case, even the matching \verb|$end| is not parsed.
403 481
404A \M{cond} part may be 482A \M{cond} part may be
@@ -418,6 +496,11 @@ Any arithmetic operation applied to a string tries to convert
418that string to a number, following the usual rules. 496that string to a number, following the usual rules.
419Conversely, whenever a number is used when a string is expected, 497Conversely, whenever a number is used when a string is expected,
420that number is converted to a string, in a reasonable format. 498that number is converted to a string, in a reasonable format.
499The format is chosen so that
500a conversion from number to string then back to number
501reproduces the original number \emph{exactly}.
502Thus,
503the conversion does not necessarily produces nice-looking text for some numbers.
421For complete control on how numbers are converted to strings, 504For complete control on how numbers are converted to strings,
422use the \verb|format| function \see{format}. 505use the \verb|format| function \see{format}.
423 506
@@ -427,15 +510,15 @@ use the \verb|format| function \see{format}.
427Functions in Lua can return many values. 510Functions in Lua can return many values.
428Because there are no type declarations, 511Because there are no type declarations,
429when a function is called 512when a function is called
430the system does not know how many values a function will return, 513the system does not know how many values the function will return,
431or how many parameters it needs. 514or how many parameters it needs.
432Therefore, sometimes, a list of values must be \emph{adjusted}, at run time, 515Therefore, sometimes, a list of values must be \emph{adjusted}, at run time,
433to a given length. 516to a given length.
434If there are more values than are needed, 517If there are more values than are needed,
435then the excess values are thrown away. 518then the excess values are thrown away.
436If there are more needs than values, 519If there are less values than are needed,
437then the list is extended with as many \nil's as needed. 520then the list is extended with as many \nil's as needed.
438Adjustment occurs in multiple assignment \see{assignment} 521This adjustment occurs in multiple assignments \see{assignment}
439and function calls \see{functioncall}. 522and function calls \see{functioncall}.
440 523
441 524
@@ -444,21 +527,22 @@ and function calls \see{functioncall}.
444Lua supports an almost conventional set of \Index{statements}, 527Lua supports an almost conventional set of \Index{statements},
445similar to those in Pascal or C. 528similar to those in Pascal or C.
446The conventional commands include 529The conventional commands include
447assignment, control structures and procedure calls. 530assignment, control structures, and procedure calls.
448Non-conventional commands include table constructors 531Non-conventional commands include table constructors
449\see{tableconstructor}, 532\see{tableconstructor}
450and local variable declarations \see{localvar}. 533and local variable declarations \see{localvar}.
451 534
452\subsubsection{Blocks} 535\subsubsection{Blocks}
453A \Index{block} is a list of statements, which are executed sequentially. 536A \Index{block} is a list of statements, which are executed sequentially.
454A statement may be have an optional label, 537A statement may be have an optional \Index{label},
538which is syntactically an identifier,
455and can be optionally followed by a semicolon: 539and can be optionally followed by a semicolon:
456\begin{Produc} 540\begin{Produc}
457\produc{block}{\opt{label} \rep{stat sc}} 541\produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}}
458\produc{sc}{\opt{\ter{;}}}
459\produc{label}{\ter{$\vert$} name \ter{$\vert$}} 542\produc{label}{\ter{$\vert$} name \ter{$\vert$}}
460\end{Produc}% 543\end{Produc}%
461For syntactic reasons, \rwd{return} and 544\NOTE
545For syntactic reasons, the \rwd{return} and
462\rwd{break} statements can only be written 546\rwd{break} statements can only be written
463as the last statement of a block. 547as the last statement of a block.
464 548
@@ -467,7 +551,7 @@ A block may be explicitly delimited:
467\produc{stat}{\rwd{do} block \rwd{end}} 551\produc{stat}{\rwd{do} block \rwd{end}}
468\end{Produc}% 552\end{Produc}%
469This is useful to control the scope of local variables \see{localvar}, 553This is useful to control the scope of local variables \see{localvar},
470and to add a \rwd{return} or a \rwd{break} statement in the middle 554and to add a \rwd{return} or \rwd{break} statement in the middle
471of another block: 555of another block:
472\begin{verbatim} 556\begin{verbatim}
473 do return end -- return is the last statement in this block 557 do return end -- return is the last statement in this block
@@ -476,7 +560,7 @@ of another block:
476\subsubsection{\Index{Assignment}} \label{assignment} 560\subsubsection{\Index{Assignment}} \label{assignment}
477The language allows \Index{multiple assignment}. 561The language allows \Index{multiple assignment}.
478Therefore, the syntax for assignment 562Therefore, the syntax for assignment
479defines a list of variables on the left side, 563defines a list of variables on the left side
480and a list of expressions on the right side. 564and a list of expressions on the right side.
481Both lists have their elements separated by commas: 565Both lists have their elements separated by commas:
482\begin{Produc} 566\begin{Produc}
@@ -486,12 +570,20 @@ Both lists have their elements separated by commas:
486This statement first evaluates all values on the right side 570This statement first evaluates all values on the right side
487and eventual indices on the left side, 571and eventual indices on the left side,
488and then makes the assignments. 572and then makes the assignments.
489Therefore, it can be used to exchange two values, as in 573So
574\begin{verbatim}
575 i = 3
576 i, a[i] = 4, 20
577\end{verbatim}
578sets \verb|a[3]| to 20, but does not affect \verb|a[4]|.
579
580Multiple assignment can be used to exchange two values, as in
490\begin{verbatim} 581\begin{verbatim}
491 x, y = y, x 582 x, y = y, x
492\end{verbatim} 583\end{verbatim}
493The two lists may have different lengths. 584
494Before the assignment, the list of values is \emph{adjusted} to 585The two lists in a multiple assignment may have different lengths.
586Before the assignment, the list of values is adjusted to
495the length of the list of variables \see{adjust}. 587the length of the list of variables \see{adjust}.
496 588
497A single name can denote a global variable, a local variable, 589A single name can denote a global variable, a local variable,
@@ -504,7 +596,7 @@ Square brackets are used to index a table:
504\produc{var}{simpleexp \ter{[} exp1 \ter{]}} 596\produc{var}{simpleexp \ter{[} exp1 \ter{]}}
505\end{Produc}% 597\end{Produc}%
506The \M{simpleexp} should result in a table value, 598The \M{simpleexp} should result in a table value,
507from where the field indexed by the expression 599from where the field indexed by the expression \M{exp1}
508value gets the assigned value. 600value gets the assigned value.
509 601
510The syntax \verb|var.NAME| is just syntactic sugar for 602The syntax \verb|var.NAME| is just syntactic sugar for
@@ -517,47 +609,50 @@ The meaning of assignments and evaluations of global variables and
517indexed variables can be changed by tag methods \see{tag-method}. 609indexed variables can be changed by tag methods \see{tag-method}.
518Actually, 610Actually,
519an assignment \verb|x = val|, where \verb|x| is a global variable, 611an assignment \verb|x = val|, where \verb|x| is a global variable,
520is equivalent to a call \verb|setglobal('x', val)|; 612is equivalent to a call \verb|setglobal("x", val)|;
521an assignment \verb|t[i] = val| is equivalent to 613an assignment \verb|t[i] = val| is equivalent to
522\verb|settable_event(t, i, val)|. 614\verb|settable_event(t,i,val)|.
523See \See{tag-method} for a complete description of these functions. 615See \See{tag-method} for a complete description of these functions.
524(Function \verb|setglobal| is pre-defined in Lua. 616(The function \verb|setglobal| is pre-defined in Lua.
525Function \T{settable\_event} is used only for explanatory purposes.) 617The function \T{settable\_event} is used only for explanatory purposes.)
526 618
527\subsubsection{Control Structures} 619\subsubsection{Control Structures}
528The \Index{condition expression} of a control structure may return any value. 620The control structures
529All values different from \nil\ are considered true; 621\index{while-do}\index{repeat-until}\index{if-then-else}%
530only \nil\ is considered false. 622\T{if}, \T{while}, and \T{repeat} have the usual meaning and
531\T{if}'s, \T{while}'s and \T{repeat}'s have the usual meaning. 623familiar syntax:
532
533\index{while-do}\index{repeat-until}\index{if-then-else}
534\begin{Produc} 624\begin{Produc}
535\produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end} \OrNL 625\produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end}}
536\rwd{repeat} block \rwd{until} exp1 \OrNL 626\produc{stat}{\rwd{repeat} block \rwd{until} exp1}
537\rwd{if} exp1 \rwd{then} block 627\produc{stat}{\rwd{if} exp1 \rwd{then} block
538 \rep{\rwd{elseif} exp1 \rwd{then} block} 628 \rep{\rwd{elseif} exp1 \rwd{then} block}
539 \opt{\rwd{else} block} \rwd{end}} 629 \opt{\rwd{else} block} \rwd{end}}
540\end{Produc} 630\end{Produc}%
631The \Index{condition expression} \M{exp1} of a control structure may return any value.
632All values different from \nil\ are considered true;
633only \nil\ is considered false.
541 634
542\index{return} 635\index{return}
543A \rwd{return} is used to return values from a function or from a chunk. 636The \rwd{return} statement is used to return values from a function or from a chunk.
544\label{return} 637\label{return}
545Because they may return more than one value, 638Because functions or chunks may return more than one value,
546the syntax for a \Index{return statement} is 639the syntax for a \Index{return statement} is
547\begin{Produc} 640\begin{Produc}
548\produc{stat}{\rwd{return} \opt{explist1}} 641\produc{stat}{\rwd{return} \opt{explist1}}
549\end{Produc} 642\end{Produc}%
550 643
551\index{break} 644\index{break}
552A \rwd{break} statement can be used to terminate the execution of a block, 645The \rwd{break} statement can be used to terminate the execution of a block,
553skipping to the next instruction after the block. 646skipping to the next statement after the block:
554\begin{Produc} 647\begin{Produc}
555\produc{stat}{\rwd{break} \opt{name}} 648\produc{stat}{\rwd{break} \opt{name}}
556\end{Produc} 649\end{Produc}%
557A \rwd{break} without a label ends the inner enclosing loop 650A \rwd{break} without a label ends the innermost enclosing loop
558(while, repeat, or for). 651(while, repeat, or for).
559A \rwd{break} with a label breaks the inner enclosing 652A \rwd{break} with a label breaks the innermost enclosing
560statement with that label. 653statement with that label.
654Thus,
655labels do not have to be unique.
561 656
562For syntactic reasons, \rwd{return} and \rwd{break} 657For syntactic reasons, \rwd{return} and \rwd{break}
563statements can only be written as the last statement of a block. 658statements can only be written as the last statement of a block.
@@ -568,35 +663,36 @@ The \rwd{for} statement has the following syntax:
568\begin{Produc} 663\begin{Produc}
569\produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} 664\produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
570 \rwd{do} block \rwd{end}} 665 \rwd{do} block \rwd{end}}
571\end{Produc} 666\end{Produc}%
572A \rwd{for} statement like 667A \rwd{for} statement like
573\begin{verbatim} 668\begin{verbatim}
574for var=e1,e2,e3 do block end 669 for var=e1,e2,e3 do block end
575\end{verbatim} 670\end{verbatim}
576is equivalent to the following code: 671is equivalent to the following code:
577\begin{verbatim} 672\begin{verbatim}
578do 673 do
579 local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) 674 local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
580 if not (var and _limit and _step) then error() end 675 if not (var and _limit and _step) then error() end
581 while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do 676 while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
582 block 677 block
583 var = var+_step 678 var = var+_step
584 end 679 end
585end 680 end
586\end{verbatim} 681\end{verbatim}
587Notice the following: 682Notice the following:
588\begin{itemize} 683\begin{itemize}\itemsep=0pt
589\item \verb|_limit| and \verb|_step| are invisible variables. 684\item \verb|_limit| and \verb|_step| are invisible variables.
590\item The behavior is undefined if you assign to \verb|var| inside 685The names are here for explanatory purposes only.
686\item The behavior is \emph{undefined} if you assign to \verb|var| inside
591the block. 687the block.
592\item If the third expression (the step) is absent, it defaults to 1. 688\item If the third expression (the step) is absent, then a step of 1 is used.
593\item Both the limit and the step are evaluated only once, 689\item Both the limit and the step are evaluated only once,
594before the loop starts. 690before the loop starts.
595\item The variable \verb|var| is local to the statement; 691\item The variable \verb|var| is local to the statement;
596you cannot use its value after the \rwd{for}. 692you cannot use its value after the \rwd{for} ends.
597\item You can use \rwd{break} to exit a \rwd{for}. 693\item You can use \rwd{break} to exit a \rwd{for}.
598If you need the value of the index, 694If you need the value of the index,
599assign it to another variable before breaking. 695then assign it to another variable before breaking.
600\end{itemize} 696\end{itemize}
601 697
602\subsubsection{Function Calls as Statements} \label{funcstat} 698\subsubsection{Function Calls as Statements} \label{funcstat}
@@ -610,8 +706,6 @@ Function calls are explained in \See{functioncall}.
610 706
611\subsubsection{Local Declarations} \label{localvar} 707\subsubsection{Local Declarations} \label{localvar}
612\Index{Local variables} may be declared anywhere inside a block. 708\Index{Local variables} may be declared anywhere inside a block.
613Their scope begins after the declaration and lasts until the
614end of the block.
615The declaration may include an initial assignment: 709The declaration may include an initial assignment:
616\begin{Produc} 710\begin{Produc}
617\produc{stat}{\rwd{local} declist \opt{init}} 711\produc{stat}{\rwd{local} declist \opt{init}}
@@ -622,6 +716,13 @@ If present, an initial assignment has the same semantics
622of a multiple assignment. 716of a multiple assignment.
623Otherwise, all variables are initialized with \nil. 717Otherwise, all variables are initialized with \nil.
624 718
719The scope of local variables begins \emph{after}
720the declaration and lasts until the end of the block.
721Thus, the code
722\verb|local print=print|
723creates a local variable called \verb|print| whose
724initial value is that of the \emph{global} variable of the same name.
725
625 726
626\subsection{\Index{Expressions}} 727\subsection{\Index{Expressions}}
627 728
@@ -630,8 +731,8 @@ The basic expressions in Lua are
630\begin{Produc} 731\begin{Produc}
631\produc{exp}{\ter{(} exp \ter{)}} 732\produc{exp}{\ter{(} exp \ter{)}}
632\produc{exp}{\rwd{nil}} 733\produc{exp}{\rwd{nil}}
633\produc{exp}{\ter{number}} 734\produc{exp}{number}
634\produc{exp}{\ter{literal}} 735\produc{exp}{literal}
635\produc{exp}{function} 736\produc{exp}{function}
636\produc{exp}{simpleexp} 737\produc{exp}{simpleexp}
637\end{Produc}% 738\end{Produc}%
@@ -639,19 +740,21 @@ The basic expressions in Lua are
639\produc{simpleexp}{var} 740\produc{simpleexp}{var}
640\produc{simpleexp}{upvalue} 741\produc{simpleexp}{upvalue}
641\produc{simpleexp}{functioncall} 742\produc{simpleexp}{functioncall}
743\produc{simpleexp}{tableconstructor}
642\end{Produc}% 744\end{Produc}%
643 745
644Numbers (numerical constants) and 746Numbers (numerical constants) and
645string literals are explained in \See{lexical}; 747literal strings are explained in \See{lexical};
646variables are explained in \See{assignment}; 748variables are explained in \See{assignment};
647upvalues are explained in \See{upvalue}; 749upvalues are explained in \See{upvalue};
648function definitions (\M{function}) are explained in \See{func-def}; 750function definitions (\M{function}) are explained in \See{func-def};
649function calls are explained in \See{functioncall}. 751function calls are explained in \See{functioncall}.
752Table constructors are explained in \See{tableconstructor}.
650 753
651An access to a global variable \verb|x| is equivalent to a 754An access to a global variable \verb|x| is equivalent to a
652call \verb|getglobal('x')|; 755call \verb|getglobal("x")|;
653an access to an indexed variable \verb|t[i]| is equivalent to 756an access to an indexed variable \verb|t[i]| is equivalent to
654a call \verb|gettable_event(t, i)|. 757a call \verb|gettable_event(t,i)|.
655See \See{tag-method} for a description of these functions. 758See \See{tag-method} for a description of these functions.
656(Function \verb|getglobal| is pre-defined in Lua. 759(Function \verb|getglobal| is pre-defined in Lua.
657Function \T{gettable\_event} is used only for explanatory purposes.) 760Function \T{gettable\_event} is used only for explanatory purposes.)
@@ -660,7 +763,7 @@ The non-terminal \M{exp1} is used to indicate that the values
660returned by an expression must be adjusted to one single value: 763returned by an expression must be adjusted to one single value:
661\begin{Produc} 764\begin{Produc}
662\produc{exp1}{exp} 765\produc{exp1}{exp}
663\end{Produc} 766\end{Produc}%
664 767
665\subsubsection{Arithmetic Operators} 768\subsubsection{Arithmetic Operators}
666Lua supports the usual \Index{arithmetic operators}: 769Lua supports the usual \Index{arithmetic operators}:
@@ -680,7 +783,7 @@ giving the expected meaning to \Index{exponentiation}
680\subsubsection{Relational Operators} 783\subsubsection{Relational Operators}
681Lua provides the following \Index{relational operators}: 784Lua provides the following \Index{relational operators}:
682\begin{verbatim} 785\begin{verbatim}
683 == ~= < > <= >= 786 == ~= < > <= >=
684\end{verbatim} 787\end{verbatim}
685All these return \nil\ as false and a value different from \nil\ as true. 788All these return \nil\ as false and a value different from \nil\ as true.
686 789
@@ -689,12 +792,13 @@ If they are different, then the result is \nil.
689Otherwise, their values are compared. 792Otherwise, their values are compared.
690Numbers and strings are compared in the usual way. 793Numbers and strings are compared in the usual way.
691Tables, userdata, and functions are compared by reference, 794Tables, userdata, and functions are compared by reference,
692that is, two tables are considered equal only if they are the same table. 795that is, two tables are considered equal only if they are the \emph{same} table.
693The operator \verb|~=| is exactly the negation of equality (\verb|==|). 796The operator \verb|~=| is exactly the negation of equality (\verb|==|).
694 797
798\NOTE
695The conversion rules of \See{coercion} 799The conversion rules of \See{coercion}
696\emph{do not} apply to equality comparisons. 800\emph{do not} apply to equality comparisons.
697Thus, \verb|"0"==0| evaluates to false, 801Thus, \verb|"0"==0| evaluates to \emph{false},
698and \verb|t[0]| and \verb|t["0"]| denote different 802and \verb|t[0]| and \verb|t["0"]| denote different
699entries in a table. 803entries in a table.
700 804
@@ -702,19 +806,19 @@ The order operators work as follows.
702If both arguments are numbers, then they are compared as such. 806If both arguments are numbers, then they are compared as such.
703Otherwise, if both arguments are strings, 807Otherwise, if both arguments are strings,
704then their values are compared using lexicographical order. 808then their values are compared using lexicographical order.
705Otherwise, the \verb|"lt"| tag method is called \see{tag-method}. 809Otherwise, the ``lt'' tag method is called \see{tag-method}.
706 810
707\subsubsection{Logical Operators} 811\subsubsection{Logical Operators}
708The \Index{logical operators} are 812The \Index{logical operators} are
709\index{and}\index{or}\index{not} 813\index{and}\index{or}\index{not}
710\begin{verbatim} 814\begin{verbatim}
711 and or not 815 and or not
712\end{verbatim} 816\end{verbatim}
713Like control structures, all logical operators 817Like control structures, all logical operators
714consider \nil\ as false and anything else as true. 818consider \nil\ as false and anything else as true.
715The operator \verb|and| returns \nil\ if its first argument is \nil; 819The conjunction operator \verb|and| returns \nil\ if its first argument is \nil;
716otherwise, it returns its second argument. 820otherwise, it returns its second argument.
717The operator \verb|or| returns its first argument 821The disjunction operator \verb|or| returns its first argument
718if it is different from \nil; 822if it is different from \nil;
719otherwise, it returns its second argument. 823otherwise, it returns its second argument.
720Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, 824Both \verb|and| and \verb|or| use \Index{short-cut evaluation},
@@ -722,17 +826,18 @@ that is,
722the second operand is evaluated only when necessary. 826the second operand is evaluated only when necessary.
723 827
724There are two useful Lua idioms with logical operators. 828There are two useful Lua idioms with logical operators.
725The first is \verb|x = x or v|, 829The first idiom is \verb|x = x or v|,
726which is equivalent to 830which is equivalent to
727\begin{verbatim} 831\begin{verbatim}
728 if x == nil then x = v end 832 if x == nil then x = v end
729\end{verbatim} 833\end{verbatim}
730i.e., it sets \verb|x| to a default value \verb|v| when 834i.e., it sets \verb|x| to a default value \verb|v| when
731\verb|x| is not set. 835\verb|x| is not set.
732The other is \verb|x = a and b or c|, 836The other idiom is \verb|x = a and b or c|,
733which is equivalent to 837which should be read as \verb|x = a and (b or c)|,
838is equivalent to
734\begin{verbatim} 839\begin{verbatim}
735 if a then x = b else x = c end 840 if a then x = b else x = c end
736\end{verbatim} 841\end{verbatim}
737provided that \verb|b| is not \nil. 842provided that \verb|b| is not \nil.
738 843
@@ -747,21 +852,23 @@ Otherwise, the ``concat'' tag method is called \see{tag-method}.
747\Index{Operator precedence} follows the table below, 852\Index{Operator precedence} follows the table below,
748from the lower to the higher priority: 853from the lower to the higher priority:
749\begin{verbatim} 854\begin{verbatim}
750 and or 855 and or
751 < > <= >= ~= == 856 < > <= >= ~= ==
752 .. 857 ..
753 + - 858 + -
754 * / 859 * /
755 not - (unary) 860 not - (unary)
756 ^ 861 ^
757\end{verbatim} 862\end{verbatim}
758All binary operators are left associative, 863All binary operators are left associative,
759except for \verb|^| (exponentiation), 864except for \verb|^| (exponentiation),
760which is right associative. 865which is right associative.
866\NOTE
761The pre-compiler may rearrange the order of evaluation of 867The pre-compiler may rearrange the order of evaluation of
762associative operators (such as \verb|..| or \verb|+|), 868associative operators (such as~\verb|..| or~\verb|+|),
763as long as these optimizations do not change normal results. 869as long as these optimizations do not change normal results.
764However, they may change some results if you define non-associative 870However, these optimizations may change some results
871if you define non-associative
765tag methods for these operators. 872tag methods for these operators.
766 873
767\subsubsection{Table Constructors} \label{tableconstructor} 874\subsubsection{Table Constructors} \label{tableconstructor}
@@ -769,15 +876,14 @@ Table \Index{constructors} are expressions that create tables;
769every time a constructor is evaluated, a new table is created. 876every time a constructor is evaluated, a new table is created.
770Constructors can be used to create empty tables, 877Constructors can be used to create empty tables,
771or to create a table and initialize some fields. 878or to create a table and initialize some fields.
772
773The general syntax for constructors is 879The general syntax for constructors is
774\begin{Produc} 880\begin{Produc}
775\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} 881\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
776\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist 882\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist
777\Or ffieldlist \ter{;} lfieldlist} 883 \Or ffieldlist \ter{;} lfieldlist}
778\produc{lfieldlist}{\opt{lfieldlist1}} 884\produc{lfieldlist}{\opt{lfieldlist1}}
779\produc{ffieldlist}{\opt{ffieldlist1}} 885\produc{ffieldlist}{\opt{ffieldlist1}}
780\end{Produc} 886\end{Produc}%
781 887
782The form \emph{lfieldlist1} is used to initialize lists: 888The form \emph{lfieldlist1} is used to initialize lists:
783\begin{Produc} 889\begin{Produc}
@@ -826,11 +932,11 @@ in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
826Both forms may have an optional trailing comma, 932Both forms may have an optional trailing comma,
827and can be used in the same constructor separated by 933and can be used in the same constructor separated by
828a semi-collon. 934a semi-collon.
829For example, all forms below are correct: 935For example, all forms below are correct.
830\begin{verbatim} 936\begin{verbatim}
831 x = {;} 937 x = {;}
832 x = {'a', 'b',} 938 x = {"a", "b",}
833 x = {type='list'; 'a', 'b'} 939 x = {type="list"; "a", "b"}
834 x = {f(0), f(1), f(2),; n=3,} 940 x = {f(0), f(1), f(2),; n=3,}
835\end{verbatim} 941\end{verbatim}
836 942
@@ -890,16 +996,17 @@ If the function is called in a place that can hold many values
890then no adjustment is made. 996then no adjustment is made.
891The only places that can hold many values 997The only places that can hold many values
892is the last (or the only) expression in an assignment, 998is the last (or the only) expression in an assignment,
893in an argument list, or in a return statement; 999in an argument list, or in a return statement.
894see examples below. 1000Here are some examples.
895\begin{verbatim} 1001\begin{verbatim}
896 f(); -- adjusted to 0 1002 f(); -- adjusted to 0
897 g(f(), x); -- f() is adjusted to 1 result 1003 g(f(), x); -- f() is adjusted to 1 result
898 g(x, f()); -- g gets x plus all values returned by f() 1004 g(x, f()); -- g gets x plus all values returned by f()
899 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) 1005 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
900 a,b,c = x, f(); -- f() is adjusted to 2 1006 a,b,c = x, f(); -- f() is adjusted to 2
901 a,b,c = f(); -- f() is adjusted to 3 1007 a,b,c = f(); -- f() is adjusted to 3
902 return f(); -- returns all values returned by f() 1008 return f(); -- returns all values returned by f()
1009 return x,y,f(); -- returns a, b, and all values returned by f()
903\end{verbatim} 1010\end{verbatim}
904 1011
905\subsubsection{\Index{Function Definitions}} \label{func-def} 1012\subsubsection{\Index{Function Definitions}} \label{func-def}
@@ -910,29 +1017,29 @@ The syntax for function definition is
910 block \rwd{end}} 1017 block \rwd{end}}
911\produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} 1018\produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)}
912 block \rwd{end}} 1019 block \rwd{end}}
913\produc{funcname}{name \Or name \ter{.} name} 1020\produc{funcname}{name \Or name \ter{.} name \Or name \ter{:} name}
914\end{Produc} 1021\end{Produc}%
915The statement 1022The statement
916\begin{verbatim} 1023\begin{verbatim}
917 function f (...) 1024 function f ()
918 ... 1025 ...
919 end 1026 end
920\end{verbatim} 1027\end{verbatim}
921is just syntactic sugar for 1028is just syntactic sugar for
922\begin{verbatim} 1029\begin{verbatim}
923 f = function (...) 1030 f = function ()
924 ... 1031 ...
925 end 1032 end
926\end{verbatim} 1033\end{verbatim}
927and 1034and the statement
928\begin{verbatim} 1035\begin{verbatim}
929 function o.f (...) 1036 function o.f ()
930 ... 1037 ...
931 end 1038 end
932\end{verbatim} 1039\end{verbatim}
933is syntactic sugar for 1040is syntactic sugar for
934\begin{verbatim} 1041\begin{verbatim}
935 o.f = function (...) 1042 o.f = function ()
936 ... 1043 ...
937 end 1044 end
938\end{verbatim} 1045\end{verbatim}
@@ -954,53 +1061,55 @@ initialized with the argument values:
954\begin{Produc} 1061\begin{Produc}
955\produc{parlist1}{\ter{\ldots}} 1062\produc{parlist1}{\ter{\ldots}}
956\produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} 1063\produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}}
957\end{Produc} 1064\end{Produc}%
958\label{vararg} 1065\label{vararg}
959When a function is called, 1066When a function is called,
960the list of \Index{arguments} is adjusted to 1067the list of \Index{arguments} is adjusted to
961the length of the list of parameters \see{adjust}, 1068the length of the list of parameters \see{adjust},
962unless the function is a \Def{vararg} function, 1069unless the function is a \Def{vararg} function,
1070which is
963indicated by the dots (\ldots) at the end of its parameter list. 1071indicated by the dots (\ldots) at the end of its parameter list.
964A vararg function does not adjust its argument list; 1072A vararg function does not adjust its argument list;
965instead, it collects any extra arguments into an implicit parameter, 1073instead, it collects all extra arguments into an implicit parameter,
966called \IndexVerb{arg}. 1074called \IndexVerb{arg}.
967This parameter is always initialized as a table, 1075The value of \verb|arg| is a table,
968with a field \verb|n| whose value is the number of extra arguments, 1076with a field~\verb|n| whose value is the number of extra arguments,
969and the extra arguments at positions 1,~2,~\ldots. 1077and the extra arguments at positions 1,~2,~\ldots,\M{n}.
970 1078
971As an example, suppose definitions like: 1079As an example, consider the following definitions:
972\begin{verbatim} 1080\begin{verbatim}
973 function f(a, b) end 1081 function f(a, b) end
974 function g(a, b, ...) end 1082 function g(a, b, ...) end
975 function r() return 1,2,3 end 1083 function r() return 1,2,3 end
976\end{verbatim} 1084\end{verbatim}
977Then, we have the following mapping from arguments to parameters: 1085Then, we have the following mapping from arguments to parameters:
978\begin{verbatim} 1086\begin{verbatim}
979 CALL PARAMETERS 1087 CALL PARAMETERS
980 1088
981 f(3) a=3, b=nil 1089 f(3) a=3, b=nil
982 f(3, 4) a=3, b=4 1090 f(3, 4) a=3, b=4
983 f(3, 4, 5) a=3, b=4 1091 f(3, 4, 5) a=3, b=4
984 f(r(), 10) a=1, b=10 1092 f(r(), 10) a=1, b=10
985 f(r()) a=1, b=2 1093 f(r()) a=1, b=2
986 1094
987 g(3) a=3, b=nil, arg={n=0} 1095 g(3) a=3, b=nil, arg={n=0}
988 g(3, 4) a=3, b=4, arg={n=0} 1096 g(3, 4) a=3, b=4, arg={n=0}
989 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} 1097 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
990 g(5, r()) a=5, b=1, arg={2, 3; n=2} 1098 g(5, r()) a=5, b=1, arg={2, 3; n=2}
991\end{verbatim} 1099\end{verbatim}
992 1100
993Results are returned using the \verb|return| statement \see{return}. 1101Results are returned using the \verb|return| statement \see{return}.
994If control reaches the end of a function without a return instruction, 1102If control reaches the end of a function
1103without encountering a \rwd{return} statement,
995then the function returns with no results. 1104then the function returns with no results.
996 1105
997There is a special syntax for defining \Index{methods}, 1106The syntax
998that is, functions that have an implicit extra parameter \IndexVerb{self}:
999\begin{Produc} 1107\begin{Produc}
1000\produc{function}{\rwd{function} name \ter{:} name \ter{(} \opt{parlist1} 1108\produc{funcname}{name \ter{:} name}
1001 \ter{)} block \rwd{end}}
1002\end{Produc}% 1109\end{Produc}%
1003Thus, a declaration like 1110is used for defining \Index{methods},
1111that is, functions that have an implicit extra parameter \IndexVerb{self}:
1112Thus, the statement
1004\begin{verbatim} 1113\begin{verbatim}
1005 function v:f (...) 1114 function v:f (...)
1006 ... 1115 ...
@@ -1022,28 +1131,31 @@ previously initialized with a table value.
1022 1131
1023A function body may refer to its own local variables 1132A function body may refer to its own local variables
1024(which include its parameters) and to global variables, 1133(which include its parameters) and to global variables,
1025as long as they are not shadowed by local 1134as long as they are not \emph{shadowed} by local
1026variables from enclosing functions. 1135variables from enclosing functions.
1027A function \emph{cannot} access a local 1136A function \emph{cannot} access a local
1028variable from an enclosing function, 1137variable from an enclosing function,
1029since such variables may no longer exist when the function is called. 1138since such variables may no longer exist when the function is called.
1030However, a function may access the \emph{value} of a local variable 1139However, a function may access the \emph{value} of a local variable
1031from an enclosing function, using \emph{upvalues}. 1140from an enclosing function, using \emph{upvalues},
1032 1141whose syntax is
1033\begin{Produc} 1142\begin{Produc}
1034\produc{upvalue}{\ter{\%} name} 1143\produc{upvalue}{\ter{\%} name}
1035\end{Produc} 1144\end{Produc}%
1036An upvalue is somewhat similar to a variable expression, 1145An upvalue is somewhat similar to a variable expression,
1037but whose value is frozen when the function wherein it 1146but whose value is \emph{frozen} when the function wherein it
1038appears is instantiated. 1147appears is instantiated.
1039The name used in an upvalue may be the name of any variable visible 1148The name used in an upvalue may be the name of any variable visible
1040at the point where the function is defined. 1149at the point where the function is defined,
1150that is
1151global variables and local variables from the immediately enclosing function.
1041 1152
1042Here are some examples: 1153Here are some examples:
1043\begin{verbatim} 1154\begin{verbatim}
1044 a,b,c = 1,2,3 -- global variables 1155 a,b,c = 1,2,3 -- global variables
1156 local d
1045 function f (x) 1157 function f (x)
1046 local b -- x and b are local to f 1158 local b -- x and b are local to f; b shadows the global b
1047 local g = function (a) 1159 local g = function (a)
1048 local y -- a and y are local to g 1160 local y -- a and y are local to g
1049 p = a -- OK, access local 'a' 1161 p = a -- OK, access local 'a'
@@ -1052,11 +1164,50 @@ Here are some examples:
1052 p = %b -- OK, access frozen value of 'b' (local to 'f') 1164 p = %b -- OK, access frozen value of 'b' (local to 'f')
1053 p = %c -- OK, access frozen value of global 'c' 1165 p = %c -- OK, access frozen value of global 'c'
1054 p = %y -- ERROR: 'y' is not visible where 'g' is defined 1166 p = %y -- ERROR: 'y' is not visible where 'g' is defined
1167 p = %d -- ERROR: 'd' is not visible where 'g' is defined
1055 end -- g 1168 end -- g
1056 end -- f 1169 end -- f
1057\end{verbatim} 1170\end{verbatim}
1058 1171
1059 1172
1173\subsection{Error Handling} \label{error}
1174
1175Because Lua is an extension language,
1176all Lua actions start from C~code in the host program
1177calling a function from the Lua library.
1178Whenever an error occurs during Lua compilation or execution,
1179the function \verb|_ERRORMESSAGE| is called \Deffunc{_ERRORMESSAGE}
1180(provided it is different from \nil),
1181and then the corresponding function from the library
1182(\verb|lua_dofile|, \verb|lua_dostring|,
1183\verb|lua_dobuffer|, or \verb|lua_callfunction|)
1184is terminated, returning an error condition.
1185
1186The only argument to \verb|_ERRORMESSAGE| is a string
1187describing the error.
1188The default definition for
1189this function calls \verb|_ALERT|, \Deffunc{_ALERT}
1190which prints the message to \verb|stderr| \see{alert}.
1191The standard I/O library redefines \verb|_ERRORMESSAGE|,
1192and uses the debug facilities \see{debugI}
1193to print some extra information,
1194such as a call stack traceback.
1195
1196To provide more information about errors,
1197Lua programs should include the compilation pragma \verb|$debug|,
1198\index{debug pragma}\label{pragma}
1199or be loaded from the host after calling \verb|lua_setdebug(1)|
1200\see{debugI}.
1201When an error occurs in a chunk compiled with this option,
1202the I/O error-message routine is able to print the number of the
1203lines where the calls (and the error) were made.
1204
1205Lua code can explicitly generate an error by calling the built-in
1206function \verb|error| \see{pdf-error}.
1207Lua code can ``catch'' an error using the built-in function
1208\verb|call| \see{pdf-call}.
1209
1210
1060\subsection{Tag Methods} \label{tag-method} 1211\subsection{Tag Methods} \label{tag-method}
1061 1212
1062Lua provides a powerful mechanism to extend its semantics, 1213Lua provides a powerful mechanism to extend its semantics,
@@ -1075,7 +1226,7 @@ Its first parameter is the tag, the second parameter is the event name
1075(a string; see below), 1226(a string; see below),
1076and the third parameter is the new method (a function), 1227and the third parameter is the new method (a function),
1077or \nil\ to restore the default behavior for the pair. 1228or \nil\ to restore the default behavior for the pair.
1078The function returns the previous tag method for that pair. 1229The \verb|settagmethod| function returns the previous tag method for that pair.
1079Another function, \IndexVerb{gettagmethod}, 1230Another function, \IndexVerb{gettagmethod},
1080receives a tag and an event name and returns the 1231receives a tag and an event name and returns the
1081current method associated with the pair. 1232current method associated with the pair.
@@ -1084,9 +1235,9 @@ Tag methods are called in the following events,
1084identified by the given names. 1235identified by the given names.
1085The semantics of tag methods is better explained by a Lua function 1236The semantics of tag methods is better explained by a Lua function
1086describing the behavior of the interpreter at each event. 1237describing the behavior of the interpreter at each event.
1087The function not only shows when a tag method is called, 1238This function not only shows when a tag method is called,
1088but also its arguments, its results, and the default behavior. 1239but also its arguments, its results, and the default behavior.
1089Please notice that the code shown here is only illustrative; 1240The code shown here is only \emph{illustrative};
1090the real behavior is hard coded in the interpreter, 1241the real behavior is hard coded in the interpreter,
1091and it is much more efficient than this simulation. 1242and it is much more efficient than this simulation.
1092All functions used in these descriptions 1243All functions used in these descriptions
@@ -1111,6 +1262,8 @@ If it also fails, then it gets a tag method from tag~0:
1111 gettagmethod(0, event) 1262 gettagmethod(0, event)
1112 end 1263 end
1113\end{verbatim} 1264\end{verbatim}
1265Using this function,
1266the tag method for the ``add' event is
1114\begin{verbatim} 1267\begin{verbatim}
1115 function add_event (op1, op2) 1268 function add_event (op1, op2)
1116 local o1, o2 = tonumber(op1), tonumber(op2) 1269 local o1, o2 = tonumber(op1), tonumber(op2)
@@ -1131,18 +1284,18 @@ If it also fails, then it gets a tag method from tag~0:
1131 1284
1132\item[``sub'':]\index{sub event} 1285\item[``sub'':]\index{sub event}
1133called when a \verb|-| operation is applied to non numerical operands. 1286called when a \verb|-| operation is applied to non numerical operands.
1134Behavior similar to the \verb|"add"| event. 1287Behavior similar to the ``add'' event.
1135 1288
1136\item[``mul'':]\index{mul event} 1289\item[``mul'':]\index{mul event}
1137called when a \verb|*| operation is applied to non numerical operands. 1290called when a \verb|*| operation is applied to non numerical operands.
1138Behavior similar to the \verb|"add"| event. 1291Behavior similar to the ``add'' event.
1139 1292
1140\item[``div'':]\index{div event} 1293\item[``div'':]\index{div event}
1141called when a \verb|/| operation is applied to non numerical operands. 1294called when a \verb|/| operation is applied to non numerical operands.
1142Behavior similar to the \verb|"add"| event. 1295Behavior similar to the ``add'' event.
1143 1296
1144\item[``pow'':]\index{pow event} 1297\item[``pow'':]\index{pow event}
1145called when a \verb|^| operation is applied. 1298called when a \verb|^| operation (exponentiation) is applied.
1146\begin{verbatim} 1299\begin{verbatim}
1147 function pow_event (op1, op2) 1300 function pow_event (op1, op2)
1148 local tm = getbinmethod(op1, op2, "pow") 1301 local tm = getbinmethod(op1, op2, "pow")
@@ -1157,7 +1310,7 @@ called when a \verb|^| operation is applied.
1157\end{verbatim} 1310\end{verbatim}
1158 1311
1159\item[``unm'':]\index{unm event} 1312\item[``unm'':]\index{unm event}
1160called when an unary \verb|-| operation is applied to a non numerical operand. 1313called when a unary \verb|-| operation is applied to a non numerical operand.
1161\begin{verbatim} 1314\begin{verbatim}
1162 function unm_event (op) 1315 function unm_event (op)
1163 local o = tonumber(op) 1316 local o = tonumber(op)
@@ -1228,12 +1381,14 @@ called when a concatenation is applied to non string operands.
1228\item[``index'':]\index{index event} 1381\item[``index'':]\index{index event}
1229called when Lua tries to retrieve the value of an index 1382called when Lua tries to retrieve the value of an index
1230not present in a table. 1383not present in a table.
1231See event \verb|"gettable"| for its semantics. 1384See event ``gettable'' for its semantics.
1232 1385
1233\item[``getglobal'':]\index{getglobal event} 1386\item[``getglobal'':]\index{getglobal event}
1234called whenever Lua needs the value of a global variable. 1387called whenever Lua needs the value of a global variable.
1235This method can only be set for \nil\ and for tags 1388This method can only be set for \nil\ and for tags
1236created by \verb|newtag|. 1389created by \verb|newtag|.
1390Note that
1391the tag is that of the \emph{current value} of the global variable.
1237\begin{verbatim} 1392\begin{verbatim}
1238 function getglobal (varname) 1393 function getglobal (varname)
1239 local value = rawgetglobal(varname) 1394 local value = rawgetglobal(varname)
@@ -1262,7 +1417,7 @@ userdata with default tags.
1262 end 1417 end
1263 end 1418 end
1264\end{verbatim} 1419\end{verbatim}
1265Notice: the function \verb|setglobal| is pre-defined in Lua \see{predefined}. 1420The function \verb|setglobal| is pre-defined in Lua \see{predefined}.
1266 1421
1267\item[``gettable'':]\index{gettable event} 1422\item[``gettable'':]\index{gettable event}
1268called whenever Lua accesses an indexed variable. 1423called whenever Lua accesses an indexed variable.
@@ -1325,9 +1480,9 @@ called when Lua tries to call a non function value.
1325\end{verbatim} 1480\end{verbatim}
1326 1481
1327\item[``gc'':]\index{gc event} 1482\item[``gc'':]\index{gc event}
1328called when Lua is ``garbage collecting'' an userdata. 1483called when Lua is ``garbage collecting'' a userdata.
1329This tag method can be set only from C, 1484This tag method can be set only from~C,
1330and cannot be set for an userdata with default tag. 1485and cannot be set for a userdata with default tag.
1331For each userdata to be collected, 1486For each userdata to be collected,
1332Lua does the equivalent of the following function: 1487Lua does the equivalent of the following function:
1333\begin{verbatim} 1488\begin{verbatim}
@@ -1345,73 +1500,39 @@ Lua does the equivalent of the call \verb|gc_event(nil)|.
1345 1500
1346 1501
1347 1502
1348\subsection{Error Handling} \label{error}
1349
1350Because Lua is an extension language,
1351all Lua actions start from C code in the host program
1352calling a function from the Lua library.
1353Whenever an error occurs during Lua compilation or execution,
1354function \verb|_ERRORMESSAGE| is called \Deffunc{_ERRORMESSAGE}
1355(provided it is different from \nil),
1356and then the corresponding function from the library
1357(\verb|lua_dofile|, \verb|lua_dostring|,
1358\verb|lua_dobuffer|, or \verb|lua_callfunction|)
1359is terminated, returning an error condition.
1360
1361The only argument to \verb|_ERRORMESSAGE| is a string
1362describing the error.
1363The default definition for
1364this function calls \verb|_ALERT|, \Deffunc{_ALERT}
1365which prints the message to \verb|stderr| \see{alert}.
1366The standard I/O library redefines \verb|_ERRORMESSAGE|,
1367and uses the debug facilities \see{debugI}
1368to print some extra information,
1369such as the call stack.
1370
1371To provide more information about errors,
1372Lua programs should include the compilation pragma \verb|$debug|.
1373\index{debug pragma}\label{pragma}
1374When an error occurs in a chunk compiled with this option,
1375the I/O error-message routine is able to print the number of the
1376lines where the calls (and the error) were made.
1377
1378Lua code can explicitly generate an error by calling the built-in
1379function \verb|error| \see{pdf-error}.
1380Lua code can ``catch'' an error using the built-in function
1381\verb|call| \see{pdf-call}.
1382
1383
1384 1503
1385\section{The Application Program Interface} 1504\section{The Application Program Interface}
1386 1505
1387This section describes the API for Lua, that is, 1506This section describes the API for Lua, that is,
1388the set of C functions available to the host program to communicate 1507the set of C~functions available to the host program to communicate
1389with the Lua library. 1508with the Lua library.
1390The API functions can be classified in the following categories: 1509The API functions can be classified into the following categories:
1391\begin{enumerate} 1510\begin{enumerate}
1392\item managing states; 1511\item managing states;
1393\item exchanging values between C and Lua; 1512\item exchanging values between C and Lua;
1394\item executing Lua code; 1513\item executing Lua code;
1395\item manipulating (reading and writing) Lua objects; 1514\item manipulating (reading and writing) Lua objects;
1396\item calling Lua functions; 1515\item calling Lua functions;
1397\item defining C functions to be called by Lua; 1516\item defining C~functions to be called by Lua;
1398\item manipulating references to Lua Objects. 1517\item manipulating references to Lua Objects.
1399\end{enumerate} 1518\end{enumerate}
1400All API functions and related types and constants 1519All API functions and related types and constants
1401are declared in the header file \verb|lua.h|. 1520are declared in the header file \verb|lua.h|.
1402 1521
1522\NOTE
1403Even when we use the term \emph{function}, 1523Even when we use the term \emph{function},
1404\emph{any facility in the API may be provided as a macro instead}. 1524\emph{any facility in the API may be provided as a macro instead}.
1405Any of such macros uses once and only once each of its arguments. 1525All such macros use each of its arguments exactly once,
1526and so do not generate hidden side-effects.
1406 1527
1407 1528
1408\subsection{States} \label{mangstate} 1529\subsection{States} \label{mangstate}
1409 1530
1410The Lua library is reentrant. 1531The Lua library is reentrant:
1411It does not have any global variable. 1532it does not have any global variable.
1412The whole state of the Lua interpreter 1533The whole state of the Lua interpreter
1413(global variables, stack, tag methods, etc) 1534(global variables, stack, tag methods, etc.)
1414is stored in a dynamic structure \Deffunc{lua_State}; 1535is stored in a dynamic structure; \Deffunc{lua_State}
1415this state must be passed as the first argument to almost 1536this state must be passed as the first argument to almost
1416every function in the library. 1537every function in the library.
1417 1538
@@ -1421,19 +1542,19 @@ This is done by calling\Deffunc{lua_newstate}
1421\begin{verbatim} 1542\begin{verbatim}
1422lua_State *lua_newstate (const char *s, ...); 1543lua_State *lua_newstate (const char *s, ...);
1423\end{verbatim} 1544\end{verbatim}
1424The arguments to this function is a list of name-value options, 1545The arguments to this function form a list of name-value options,
1425terminated with \verb|NULL|. 1546terminated with \verb|NULL|.
1426Currently, the function accepts the following options: 1547Currently, the function accepts the following options:
1427\begin{itemize} 1548\begin{itemize}
1428\item \verb|"stack"| - the stack size. 1549\item \verb|"stack"| --- the stack size.
1429Each function call needs one stack position for each local variable 1550Each function call needs one stack position for each local variable
1430and temporary variables, plus one position. 1551and temporary variables, plus one position for book-keeping.
1431The stack must also have at least ten extra positions available. 1552The stack must also have at least ten extra positions available.
1432For very small implementations, without recursive functions, 1553For very small implementations, without recursive functions,
1433a size of 100 should be enough. 1554a stack size of 100 should be enough.
1434The default is 1K. 1555The default stack size is 1024.
1435 1556
1436\item \verb|"builtin"| - the value is a boolean (0 or 1) that 1557\item \verb|"builtin"| --- the value is a boolean (0 or 1) that
1437indicates whether the predefined functions should be loaded or not. 1558indicates whether the predefined functions should be loaded or not.
1438The default is to load those functions. 1559The default is to load those functions.
1439\end{itemize} 1560\end{itemize}
@@ -1441,7 +1562,7 @@ For instance, the call
1441\begin{verbatim} 1562\begin{verbatim}
1442lua_State *L = lua_newstate(NULL); 1563lua_State *L = lua_newstate(NULL);
1443\end{verbatim} 1564\end{verbatim}
1444creates a new state with a stack of 1K positions, 1565creates a new state with a stack of 1024 positions
1445and with the predefined functions loaded; 1566and with the predefined functions loaded;
1446the call 1567the call
1447\begin{verbatim} 1568\begin{verbatim}
@@ -1455,13 +1576,18 @@ To release a state, you call
1455void lua_close (lua_State *L); 1576void lua_close (lua_State *L);
1456\end{verbatim} 1577\end{verbatim}
1457This function destroys all objects in the current Lua environment 1578This function destroys all objects in the current Lua environment
1458(calling the correspondent garbage collector tag methods), 1579(calling the corresponding garbage collection tag methods)
1459and frees all dynamic memory used by the state. 1580and frees all dynamic memory used by the state.
1460Usually, you do not need to call this function, 1581Usually, you do not need to call this function,
1461because these resources are naturally released when the program ends. 1582because all resources are naturally released when the program ends.
1583On the other hand,
1584long-running programs ---
1585like a daemon or web server, for example ---
1586might need to release states as soon as they are not needed,
1587to avoid growing too big.
1462 1588
1463With the exception of \verb|lua_newstate|, 1589With the exception of \verb|lua_newstate|,
1464all functions in the API get at its first argument a state. 1590all functions in the API need a state as their first argument.
1465However, most applications use a single state. 1591However, most applications use a single state.
1466To avoid the burden of passing this only state explicitly to all 1592To avoid the burden of passing this only state explicitly to all
1467functions, and also to keep compatibility with old versions of Lua, 1593functions, and also to keep compatibility with old versions of Lua,
@@ -1491,14 +1617,13 @@ in this case, the corresponding macro is
1491\begin{verbatim} 1617\begin{verbatim}
1492#define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0)))) 1618#define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0))))
1493\end{verbatim} 1619\end{verbatim}
1494It checks whether the global state has been initialized; 1620This code checks whether the global state has been initialized;
1495if not, it creates a new state with default settings and 1621if not, it creates a new state with default settings and
1496assigns it to \verb|lua_newstate|. 1622assigns it to \verb|lua_newstate|.
1497 1623
1498By default, those macros are all active. 1624By default, the single-state macros are all active.
1499If you will use multiple states, 1625If you need to use multiple states,
1500and therefore will want to provide the state 1626and therefore will provide the state argument explicitly in each call,
1501argument explicitly for each call,
1502you should define \IndexVerb{LUA_REENTRANT} before 1627you should define \IndexVerb{LUA_REENTRANT} before
1503including \verb|lua.h| in your code: 1628including \verb|lua.h| in your code:
1504\begin{verbatim} 1629\begin{verbatim}
@@ -1520,7 +1645,7 @@ which works like an abstract type in C that can hold any Lua value.
1520Values of type \verb|lua_Object| have no meaning outside Lua; 1645Values of type \verb|lua_Object| have no meaning outside Lua;
1521for instance, 1646for instance,
1522you cannot compare two \verb|lua_Object's| directly. 1647you cannot compare two \verb|lua_Object's| directly.
1523Instead, you should use the next function: 1648Instead, you should use the following function:
1524\Deffunc{lua_equal} 1649\Deffunc{lua_equal}
1525\begin{verbatim} 1650\begin{verbatim}
1526int lua_equal (lua_Object o1, lua_Object o2); 1651int lua_equal (lua_Object o1, lua_Object o2);
@@ -1533,21 +1658,21 @@ the following functions are available:
1533\Deffunc{lua_isfunction} 1658\Deffunc{lua_isfunction}
1534\Deffunc{lua_type} 1659\Deffunc{lua_type}
1535\begin{verbatim} 1660\begin{verbatim}
1536int lua_isnil (lua_Object object); 1661int lua_isnil (lua_Object object);
1537int lua_isnumber (lua_Object object); 1662int lua_isnumber (lua_Object object);
1538int lua_isstring (lua_Object object); 1663int lua_isstring (lua_Object object);
1539int lua_istable (lua_Object object); 1664int lua_istable (lua_Object object);
1540int lua_isfunction (lua_Object object); 1665int lua_isfunction (lua_Object object);
1541int lua_iscfunction (lua_Object object); 1666int lua_iscfunction (lua_Object object);
1542int lua_isuserdata (lua_Object object); 1667int lua_isuserdata (lua_Object object);
1543const char *lua_type (lua_Object obj); 1668const char *lua_type (lua_Object object);
1544\end{verbatim} 1669\end{verbatim}
1545The \verb|lua_is*| functions return 1 if the object is compatible 1670The \verb|lua_is*| functions return 1 if the object is compatible
1546with the given type, and 0 otherwise. 1671with the given type, and 0 otherwise.
1547The function \verb|lua_isnumber| accepts numbers and numerical strings, 1672The function \verb|lua_isnumber| accepts numbers and numerical strings,
1548\verb|lua_isstring| accepts strings and numbers \see{coercion}, 1673\verb|lua_isstring| accepts strings and numbers \see{coercion},
1549and \verb|lua_isfunction| accepts Lua functions and C functions. 1674and \verb|lua_isfunction| accepts Lua functions and C~functions.
1550To distinguish between Lua functions and C functions, 1675To distinguish between Lua functions and C~functions,
1551you should use \verb|lua_iscfunction|. 1676you should use \verb|lua_iscfunction|.
1552To distinguish between numbers and numerical strings, 1677To distinguish between numbers and numerical strings,
1553you can use \verb|lua_type|. 1678you can use \verb|lua_type|.
@@ -1557,14 +1682,14 @@ describing the type of the given object:
1557\verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|. 1682\verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|.
1558 1683
1559To get the tag of a \verb|lua_Object|, 1684To get the tag of a \verb|lua_Object|,
1560the following function is available: 1685use the following function:
1561\Deffunc{lua_tag} 1686\Deffunc{lua_tag}
1562\begin{verbatim} 1687\begin{verbatim}
1563int lua_tag (lua_Object object); 1688int lua_tag (lua_Object object);
1564\end{verbatim} 1689\end{verbatim}
1565 1690
1566To translate a value from type \verb|lua_Object| to a specific C type, 1691To translate a value from type \verb|lua_Object| to a specific C type,
1567you can use 1692you can use the following conversion functions:
1568\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} 1693\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen}
1569\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} 1694\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata}
1570\begin{verbatim} 1695\begin{verbatim}
@@ -1593,9 +1718,13 @@ Because Lua has garbage collection,
1593there is no guarantee that the pointer returned by \verb|lua_getstring| 1718there is no guarantee that the pointer returned by \verb|lua_getstring|
1594will be valid after the block ends 1719will be valid after the block ends
1595\see{GC}. 1720\see{GC}.
1721So,
1722if you need the string later on,
1723you should duplicate it with something like
1724\verb|memcpy(malloc(lua_strlen(o),lua_getstring(o)))|.
1596 1725
1597\verb|lua_getcfunction| converts a \verb|lua_Object| to a C function. 1726\verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function.
1598This \verb|lua_Object| must have type \emph{CFunction}; 1727This \verb|lua_Object| must be a C~function;
1599otherwise, \verb|lua_getcfunction| returns \verb|NULL|. 1728otherwise, \verb|lua_getcfunction| returns \verb|NULL|.
1600The type \verb|lua_CFunction| is explained in \See{LuacallC}. 1729The type \verb|lua_CFunction| is explained in \See{LuacallC}.
1601 1730
@@ -1603,27 +1732,7 @@ The type \verb|lua_CFunction| is explained in \See{LuacallC}.
1603This \verb|lua_Object| must have type \emph{userdata}; 1732This \verb|lua_Object| must have type \emph{userdata};
1604otherwise, \verb|lua_getuserdata| returns \verb|NULL|. 1733otherwise, \verb|lua_getuserdata| returns \verb|NULL|.
1605 1734
1606\subsection{Garbage Collection}\label{GC} 1735\subsection{Communication between Lua and C}\label{Lua-C-protocol}
1607Because Lua has automatic memory management and garbage collection,
1608a \verb|lua_Object| has a limited scope,
1609and is only valid inside the \emph{block} where it has been created.
1610A C function called from Lua is a block,
1611and its parameters are valid only until its end.
1612It is good programming practice to convert Lua objects to C values
1613as soon as they are available,
1614and never to store \verb|lua_Object|s in C global variables.
1615
1616A garbage collection cycle can be forced by:
1617\Deffunc{lua_collectgarbage}
1618\begin{verbatim}
1619long lua_collectgarbage (long limit);
1620\end{verbatim}
1621This function returns the number of objects collected.
1622The argument \verb|limit| makes the next cycle occur only
1623after that number of new objects have been created.
1624If \verb|limit| is 0,
1625then Lua uses an adaptive heuristics to set this limit.
1626
1627 1736
1628All communication between Lua and C is done through two 1737All communication between Lua and C is done through two
1629abstract data types, called \Def{lua2C} and \Def{C2lua}. 1738abstract data types, called \Def{lua2C} and \Def{C2lua}.
@@ -1633,8 +1742,8 @@ parameters when Lua calls C and results when C calls Lua.
1633The structure C2lua is used in the reverse direction: 1742The structure C2lua is used in the reverse direction:
1634parameters when C calls Lua and results when Lua calls C. 1743parameters when C calls Lua and results when Lua calls C.
1635 1744
1636The structure lua2C is an abstract array, 1745The structure lua2C is an \emph{abstract array}
1637which can be indexed with the function: 1746that can be indexed with the function:
1638\Deffunc{lua_lua2C} 1747\Deffunc{lua_lua2C}
1639\begin{verbatim} 1748\begin{verbatim}
1640lua_Object lua_lua2C (int number); 1749lua_Object lua_lua2C (int number);
@@ -1642,12 +1751,12 @@ lua_Object lua_lua2C (int number);
1642where \verb|number| starts with 1. 1751where \verb|number| starts with 1.
1643When called with a number larger than the array size, 1752When called with a number larger than the array size,
1644this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}. 1753this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}.
1645In this way, it is possible to write C functions that receive 1754In this way, it is possible to write C~functions that receive
1646a variable number of parameters, 1755a variable number of parameters,
1647and to call Lua functions that return a variable number of results. 1756and to call Lua functions that return a variable number of results.
1648Note that the structure lua2C cannot be directly modified by C code. 1757Note that the structure lua2C cannot be directly modified by C code.
1649 1758
1650The second structure, C2lua, is an abstract stack. 1759The structure C2lua is an \emph{abstract stack}.
1651Pushing elements into this stack 1760Pushing elements into this stack
1652is done with the following functions: 1761is done with the following functions:
1653\Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} 1762\Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring}
@@ -1670,7 +1779,7 @@ In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring|
1670make an internal copy of the given string. 1779make an internal copy of the given string.
1671Function \verb|lua_pushstring| can only be used to push proper C strings 1780Function \verb|lua_pushstring| can only be used to push proper C strings
1672(that is, strings that end with a zero and do not contain embedded zeros); 1781(that is, strings that end with a zero and do not contain embedded zeros);
1673otherwise you should use the more generic \verb|lua_pushlstring|. 1782otherwise you should use the more general \verb|lua_pushlstring|.
1674The function 1783The function
1675\Deffunc{lua_pop} 1784\Deffunc{lua_pop}
1676\begin{verbatim} 1785\begin{verbatim}
@@ -1682,10 +1791,48 @@ and pops it.
1682As a general rule, all API functions pop from the stack 1791As a general rule, all API functions pop from the stack
1683all elements they use. 1792all elements they use.
1684 1793
1794When C code calls Lua repeatedly, as in a loop,
1795objects returned by these calls can accumulate,
1796and may cause a stack overflow.
1797To avoid this,
1798nested blocks can be defined with the functions
1799\begin{verbatim}
1800void lua_beginblock (void);
1801void lua_endblock (void);
1802\end{verbatim}
1803After the end of the block,
1804all \verb|lua_Object|'s created inside it are released.
1805The use of explicit nested blocks is good programming practice
1806and is strongly encouraged.
1807
1808\subsection{Garbage Collection}\label{GC}
1809Because Lua has automatic memory management and garbage collection,
1810a \verb|lua_Object| has a limited scope,
1811and is only valid inside the \emph{block} where it has been created.
1812A C~function called from Lua is a block,
1813and its parameters are valid only until its end.
1814It is good programming practice to convert Lua objects to C values
1815as soon as they are available,
1816and never to store \verb|lua_Object|s in C global variables.
1817
1818A garbage collection cycle can be forced by:
1819\Deffunc{lua_collectgarbage}
1820\begin{verbatim}
1821long lua_collectgarbage (long limit);
1822\end{verbatim}
1823This function returns the number of objects collected.
1824The argument \verb|limit| makes the next cycle occur only
1825after that number of new objects have been created.
1826If \verb|limit| is 0,
1827then Lua uses an adaptive heuristics to set this limit.
1828
1829
1830\subsection{Userdata and Tags}\label{C-tags}
1831
1685Because userdata are objects, 1832Because userdata are objects,
1686the function \verb|lua_pushusertag| may create a new userdata. 1833the function \verb|lua_pushusertag| may create a new userdata.
1687If Lua has a userdata with the given value (\verb|void*|) and tag, 1834If Lua has a userdata with the given value (\verb|void*|) and tag,
1688that userdata is pushed. 1835then that userdata is pushed.
1689Otherwise, a new userdata is created, with the given value and tag. 1836Otherwise, a new userdata is created, with the given value and tag.
1690If this function is called with 1837If this function is called with
1691\verb|tag| equal to \verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG}, 1838\verb|tag| equal to \verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG},
@@ -1696,33 +1843,19 @@ with tag equal to 0.
1696 1843
1697Userdata can have different tags, 1844Userdata can have different tags,
1698whose semantics are only known to the host program. 1845whose semantics are only known to the host program.
1699Tags are created with the function: 1846Tags are created with the function
1700\Deffunc{lua_newtag} 1847\Deffunc{lua_newtag}
1701\begin{verbatim} 1848\begin{verbatim}
1702int lua_newtag (void); 1849int lua_newtag (void);
1703\end{verbatim} 1850\end{verbatim}
1704The function \verb|lua_settag| changes the tag of 1851The function \verb|lua_settag| changes the tag of
1705the object on the top of C2lua (and pops it); 1852the object on the top of C2lua (and pops it);
1706the object must be a userdata or a table. 1853the object must be a userdata or a table:
1707\Deffunc{lua_settag} 1854\Deffunc{lua_settag}
1708\begin{verbatim} 1855\begin{verbatim}
1709void lua_settag (int tag); 1856void lua_settag (int tag);
1710\end{verbatim} 1857\end{verbatim}
1711\verb|tag| must be a value created with \verb|lua_newtag|. 1858The given \verb|tag| must be a value created with \verb|lua_newtag|.
1712
1713When C code calls Lua repeatedly, as in a loop,
1714objects returned by these calls can accumulate,
1715and may cause a stack overflow.
1716To avoid this,
1717nested blocks can be defined with the functions:
1718\begin{verbatim}
1719void lua_beginblock (void);
1720void lua_endblock (void);
1721\end{verbatim}
1722After the end of the block,
1723all \verb|lua_Object|'s created inside it are released.
1724The use of explicit nested blocks is good programming practice
1725and is strongly encouraged.
1726 1859
1727\subsection{Executing Lua Code} 1860\subsection{Executing Lua Code}
1728A host program can execute Lua chunks written in a file or in a string 1861A host program can execute Lua chunks written in a file or in a string
@@ -1737,19 +1870,25 @@ All these functions return an error code:
17370, in case of success; non zero, in case of errors. 18700, in case of success; non zero, in case of errors.
1738More specifically, \verb|lua_dofile| returns 2 if for any reason 1871More specifically, \verb|lua_dofile| returns 2 if for any reason
1739it could not open the file. 1872it could not open the file.
1873(In this case,
1874you may want to
1875check \verb|errno|,
1876call \verb|strerror|,
1877or call \verb|perror| to tell the user what went wrong.)
1740When called with argument \verb|NULL|, 1878When called with argument \verb|NULL|,
1741\verb|lua_dofile| executes the \verb|stdin| stream. 1879\verb|lua_dofile| executes the \verb|stdin| stream.
1742Functions \verb|lua_dofile| and \verb|lua_dobuffer| 1880Functions \verb|lua_dofile| and \verb|lua_dobuffer|
1743are both able to execute pre-compiled chunks. 1881are both able to execute pre-compiled chunks.
1744They automatically detect whether the chunk is text or binary, 1882They automatically detect whether the chunk is text or binary,
1745and load it accordingly (see program \IndexVerb{luac}). 1883and load it accordingly (see program \IndexVerb{luac}).
1746Function \verb|lua_dostring| executes only source code. 1884Function \verb|lua_dostring| executes only source code,
1885given in textual form.
1747 1886
1748The third parameter to \verb|lua_dobuffer| (\verb|name|) 1887The third parameter to \verb|lua_dobuffer| (\verb|name|)
1749is the ``name of the chunk'', 1888is the ``name of the chunk'',
1750used in error messages and debug information. 1889used in error messages and debug information.
1751If \verb|name| is \verb|NULL|, 1890If \verb|name| is \verb|NULL|,
1752Lua gives a default name to the chunk. 1891then Lua gives a default name to the chunk.
1753 1892
1754These functions return, in structure lua2C, 1893These functions return, in structure lua2C,
1755any values eventually returned by the chunks. 1894any values eventually returned by the chunks.
@@ -1758,12 +1897,13 @@ They also empty the stack C2lua.
1758 1897
1759\subsection{Manipulating Lua Objects} 1898\subsection{Manipulating Lua Objects}
1760To read the value of any global Lua variable, 1899To read the value of any global Lua variable,
1761one uses the function: 1900one uses the function
1762\Deffunc{lua_getglobal} 1901\Deffunc{lua_getglobal}
1763\begin{verbatim} 1902\begin{verbatim}
1764lua_Object lua_getglobal (const char *varname); 1903lua_Object lua_getglobal (const char *varname);
1765\end{verbatim} 1904\end{verbatim}
1766As in Lua, this function may trigger a tag method. 1905As in Lua, this function may trigger a tag method
1906for the ``getglobal'' event.
1767To read the real value of any global variable, 1907To read the real value of any global variable,
1768without invoking any tag method, 1908without invoking any tag method,
1769use the \emph{raw} version: 1909use the \emph{raw} version:
@@ -1773,12 +1913,13 @@ lua_Object lua_rawgetglobal (const char *varname);
1773\end{verbatim} 1913\end{verbatim}
1774 1914
1775To store a value previously pushed onto C2lua in a global variable, 1915To store a value previously pushed onto C2lua in a global variable,
1776there is the function: 1916there is the function
1777\Deffunc{lua_setglobal} 1917\Deffunc{lua_setglobal}
1778\begin{verbatim} 1918\begin{verbatim}
1779void lua_setglobal (const char *varname); 1919void lua_setglobal (const char *varname);
1780\end{verbatim} 1920\end{verbatim}
1781As in Lua, this function may trigger a tag method. 1921As in Lua, this function may trigger a tag method
1922for the ``setglobal'' event.
1782To set the real value of any global variable, 1923To set the real value of any global variable,
1783without invoking any tag method, 1924without invoking any tag method,
1784use the \emph{raw} version: 1925use the \emph{raw} version:
@@ -1795,7 +1936,8 @@ lua_Object lua_gettable (void);
1795\end{verbatim} 1936\end{verbatim}
1796pops a table and an index from the stack C2lua, 1937pops a table and an index from the stack C2lua,
1797and returns the contents of the table at that index. 1938and returns the contents of the table at that index.
1798As in Lua, this operation may trigger a tag method. 1939As in Lua, this operation may trigger a tag method
1940for the ``gettable'' event.
1799To get the real value of any table index, 1941To get the real value of any table index,
1800without invoking any tag method, 1942without invoking any tag method,
1801use the \emph{raw} version: 1943use the \emph{raw} version:
@@ -1805,14 +1947,15 @@ lua_Object lua_rawgettable (void);
1805\end{verbatim} 1947\end{verbatim}
1806 1948
1807To store a value in an index, 1949To store a value in an index,
1808the program must push the table, the index, 1950the program must push the table, the index, and the value onto C2lua
1809and the value onto C2lua, 1951(in this order),
1810and then call the function 1952and then call the function
1811\Deffunc{lua_settable} 1953\Deffunc{lua_settable}
1812\begin{verbatim} 1954\begin{verbatim}
1813void lua_settable (void); 1955void lua_settable (void);
1814\end{verbatim} 1956\end{verbatim}
1815Again, the tag method for ``settable'' may be called. 1957As in Lua, this operation may trigger a tag method
1958for the ``settable'' event.
1816To set the real value of any table index, 1959To set the real value of any table index,
1817without invoking any tag method, 1960without invoking any tag method,
1818use the \emph{raw} version: 1961use the \emph{raw} version:
@@ -1846,11 +1989,11 @@ Finally, the results are returned in structure lua2C
1846(recall that a Lua function may return many values), 1989(recall that a Lua function may return many values),
1847and can be retrieved with the macro \verb|lua_getresult|, 1990and can be retrieved with the macro \verb|lua_getresult|,
1848\Deffunc{lua_getresult} 1991\Deffunc{lua_getresult}
1849which is just another name to function \verb|lua_lua2C|. 1992which is just another name for the function \verb|lua_lua2C|.
1850Note that function \verb|lua_callfunction| 1993Note that \verb|lua_callfunction|
1851pops all elements from the C2lua stack. 1994pops all elements from the C2lua stack.
1852 1995
1853The following example shows how a C program may do the 1996The following example shows how the host program may do the
1854equivalent to the Lua code: 1997equivalent to the Lua code:
1855\begin{verbatim} 1998\begin{verbatim}
1856 a,b = f("how", t.x, 4) 1999 a,b = f("how", t.x, 4)
@@ -1869,18 +2012,19 @@ equivalent to the Lua code:
1869\end{verbatim} 2012\end{verbatim}
1870 2013
1871Some special Lua functions have exclusive interfaces. 2014Some special Lua functions have exclusive interfaces.
1872A C function can generate a Lua error calling the function 2015The host program can generate a Lua error calling the function
1873\Deffunc{lua_error} 2016\Deffunc{lua_error}
1874\begin{verbatim} 2017\begin{verbatim}
1875void lua_error (const char *message); 2018void lua_error (const char *message);
1876\end{verbatim} 2019\end{verbatim}
1877This function never returns. 2020This function never returns.
1878If the C function has been called from Lua, 2021If \verb|lua_error| is called from a C~function that has been called from Lua,
1879then the corresponding Lua execution terminates, 2022then the corresponding Lua execution terminates,
1880as if an error had occurred inside Lua code. 2023as if an error had occurred inside Lua code.
1881Otherwise, the whole host program terminates with a call to \verb|exit(1)|. 2024Otherwise, the whole host program terminates with a call to \verb|exit(1)|.
1882The \verb|message| is passed to the error handler function, 2025Before terminating execution,
1883\verb|_ERRORMESSAGE|. 2026the \verb|message| is passed to the error handler function,
2027\verb|_ERRORMESSAGE| \see{error}.
1884If \verb|message| is \verb|NULL|, 2028If \verb|message| is \verb|NULL|,
1885then \verb|_ERRORMESSAGE| is not called. 2029then \verb|_ERRORMESSAGE| is not called.
1886 2030
@@ -1915,7 +2059,7 @@ and the second is a \emph{cursor};
1915this cursor starts in 0, 2059this cursor starts in 0,
1916and for each call the function returns a value to 2060and for each call the function returns a value to
1917be used in the next call, 2061be used in the next call,
1918or 0 to signal the end of the traverse. 2062or 0 to signal the end of the traversal.
1919The function also returns, in the Lua2C array, 2063The function also returns, in the Lua2C array,
1920a key-value pair from the table. 2064a key-value pair from the table.
1921A typical traversal looks like the following code: 2065A typical traversal looks like the following code:
@@ -1936,9 +2080,9 @@ A typical traversal looks like the following code:
1936\end{verbatim} 2080\end{verbatim}
1937The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the 2081The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the
1938results of each iteration from the stack. 2082results of each iteration from the stack.
1939Without them, a traversal of a large table will overflow the stack. 2083Without them, a traversal of a large table may overflow the stack.
1940 2084
1941To traverse the global variables, you use \Deffunc{lua_nextvar} 2085To traverse the global variables, use \Deffunc{lua_nextvar}
1942\begin{verbatim} 2086\begin{verbatim}
1943const char *lua_nextvar (const char *varname); 2087const char *lua_nextvar (const char *varname);
1944\end{verbatim} 2088\end{verbatim}
@@ -1964,8 +2108,8 @@ A typical traversal looks like the following code:
1964 2108
1965 2109
1966\subsection{Defining C Functions} \label{LuacallC} 2110\subsection{Defining C Functions} \label{LuacallC}
1967To register a C function to Lua, 2111To register a C~function to Lua,
1968there is the following macro: 2112there is the following convenience macro:
1969\Deffunc{lua_register} 2113\Deffunc{lua_register}
1970\begin{verbatim} 2114\begin{verbatim}
1971#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n)) 2115#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
@@ -1983,39 +2127,42 @@ typedef void (*lua_CFunction) (void);
1983that is, a pointer to a function with no parameters and no results. 2127that is, a pointer to a function with no parameters and no results.
1984 2128
1985In order to communicate properly with Lua, 2129In order to communicate properly with Lua,
1986a C function must follow a protocol, 2130a C~function must follow a protocol,
1987which defines the way parameters and results are passed. 2131which defines the way parameters and results are passed.
1988 2132
1989A C function receives its arguments in structure lua2C; 2133A C~function receives its arguments in structure lua2C;
1990to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} 2134to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam}
1991again just another name for \verb|lua_lua2C|. 2135again just another name for \verb|lua_lua2C|.
1992To return values, a C function just pushes them onto the stack C2lua, 2136To return values, a C~function just pushes them onto the stack C2lua,
1993in direct order \see{valuesCLua}. 2137in direct order \see{valuesCLua}.
1994Like a Lua function, a C function called by Lua can also return 2138Like a Lua function, a C~function called by Lua can also return
1995many results. 2139many results.
1996 2140
1997When a C function is created, 2141When a C~function is created,
1998it is possible to associate some \emph{upvalues} to it, 2142it is possible to associate some \emph{upvalues} to it
2143\see{upvalue},
1999thus creating a C closure; 2144thus creating a C closure;
2000then these values are passed to the function whenever it is called, 2145these values are passed to the function whenever it is called,
2001as common arguments. 2146as common arguments.
2002To associate upvalues to a function, 2147To associate upvalues to a C~function,
2003first these values must be pushed on C2lua. 2148first these values must be pushed on C2lua.
2004Then the function \Deffunc{lua_pushcclosure} 2149Then the function \Deffunc{lua_pushcclosure}
2005\begin{verbatim} 2150\begin{verbatim}
2006void lua_pushcclosure (lua_CFunction fn, int n); 2151void lua_pushcclosure (lua_CFunction fn, int n);
2007\end{verbatim} 2152\end{verbatim}
2008is used to put the C function on C2lua, 2153is used to put the C~function on C2lua,
2009with the argument \verb|n| telling how many upvalues must be 2154with the argument \verb|n| telling how many upvalues must be
2010associated with the function; 2155associated with the function;
2011in fact, the macro \verb|lua_pushcfunction| is defined as 2156in fact, the macro \verb|lua_pushcfunction| is defined as
2012\verb|lua_pushcclosure| with \verb|n| set to 0. 2157\verb|lua_pushcclosure| with \verb|n| set to 0.
2013Then, any time the function is called, 2158Then, whenever the C~function is called,
2014these upvalues are inserted as the first arguments to the function, 2159these upvalues are inserted as the first arguments \M{n} to the function,
2015before the actual arguments provided in the call. 2160before the actual arguments provided in the call.
2016 2161
2017For some examples of C functions, see files \verb|lstrlib.c|, 2162For some examples of C~functions, see files \verb|lstrlib.c|,
2018\verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. 2163\verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution.
2164In particular,
2165\verb|liolib.c| defines C~closures with file handles are upvalues.
2019 2166
2020\subsection{References to Lua Objects} 2167\subsection{References to Lua Objects}
2021 2168
@@ -2034,15 +2181,15 @@ void lua_unref (int ref);
2034The function \verb|lua_ref| creates a reference 2181The function \verb|lua_ref| creates a reference
2035to the object that is on the top of the stack, 2182to the object that is on the top of the stack,
2036and returns this reference. 2183and returns this reference.
2037For a \nil{} object, 2184For a \nil\ object,
2038the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL} 2185the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL}
2039otherwise, it is a non-negative integer. 2186otherwise, it is a non-negative integer.
2040The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF} 2187The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF}
2041is different from any valid reference. 2188is different from any valid reference.
2042If \verb|lock| is true, the object is \emph{locked}: 2189If \verb|lock| is true, then the object is \emph{locked}:
2043this means the object will not be garbage collected. 2190this means the object will not be garbage collected.
2044Note that an unlocked reference may be garbage collected. 2191\emph{Unlocked references may be garbage collected}.
2045Whenever the referenced object is needed, 2192Whenever the referenced object is needed in~C,
2046a call to \verb|lua_getref| 2193a call to \verb|lua_getref|
2047returns a handle to it; 2194returns a handle to it;
2048if the object has been collected, 2195if the object has been collected,
@@ -2081,6 +2228,28 @@ and \verb|lua_iolibopen|, declared in \verb|lualib.h|.
2081 2228
2082\subsection{Predefined Functions} \label{predefined} 2229\subsection{Predefined Functions} \label{predefined}
2083 2230
2231\subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert}
2232Prints its only string argument to \IndexVerb{stderr}.
2233All error messages in Lua are printed through the function stored
2234in the \verb|_ALERT| global variable
2235\see{error}.
2236Therefore, a program may assign another function to this variable
2237to change the way such messages are shown
2238(for instance, for systems without \verb|stderr|).
2239
2240\subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert}
2241Issues an \emph{``assertion failed!''} error
2242when its argument \verb|v| is \nil.
2243This function is equivalent to the following Lua function:
2244\begin{verbatim}
2245 function assert (v, m)
2246 if not v then
2247 m = m or ""
2248 error("assertion failed! " .. m)
2249 end
2250 end
2251\end{verbatim}
2252
2084\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call} 2253\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call}
2085\label{pdf-call} 2254\label{pdf-call}
2086Calls function \verb|func| with 2255Calls function \verb|func| with
@@ -2092,24 +2261,24 @@ The call is equivalent to
2092where \verb|n| is the result of \verb|getn(arg)| \see{getn}. 2261where \verb|n| is the result of \verb|getn(arg)| \see{getn}.
2093 2262
2094By default, 2263By default,
2095all results from \verb|func| are just returned by the call. 2264all results from \verb|func| are simply returned by \verb|call|.
2096If the string \verb|mode| contains \verb|"p"|, 2265If the string \verb|mode| contains \verb|"p"|,
2097the results are \emph{packed} in a single table.\index{packed results} 2266then the results are \emph{packed} in a single table.\index{packed results}
2098That is, \verb|call| returns just one table; 2267That is, \verb|call| returns just one table;
2099at index \verb|n|, the table has the total number of results 2268at index \verb|n|, the table has the total number of results
2100from the call; 2269from the call;
2101the first result is at index 1, etc. 2270the first result is at index 1, etc.
2102For instance, the following calls produce the following results: 2271For instance, the following calls produce the following results:
2103\begin{verbatim} 2272\begin{verbatim}
2104a = call(sin, {5}) --> a = 0.0871557 = sin(5) 2273 a = call(sin, {5}) --> a = 0.0871557 = sin(5)
2105a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) 2274 a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments)
2106a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1} 2275 a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1}
2107t = {x=1} 2276 t = {x=1}
2108a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2} 2277 a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2}
2109\end{verbatim} 2278\end{verbatim}
2110 2279
2111By default, 2280By default,
2112if an error occurs during the function call, 2281if an error occurs during the call to \verb|func|,
2113the error is propagated. 2282the error is propagated.
2114If the string \verb|mode| contains \verb|"x"|, 2283If the string \verb|mode| contains \verb|"x"|,
2115then the call is \emph{protected}.\index{protected calls} 2284then the call is \emph{protected}.\index{protected calls}
@@ -2118,26 +2287,31 @@ regardless of what happens during the call.
2118Instead, it returns \nil\ to signal the error 2287Instead, it returns \nil\ to signal the error
2119(besides calling the appropriated error handler). 2288(besides calling the appropriated error handler).
2120 2289
2121If provided, 2290If \verb|errhandler| is provided,
2122\verb|errhandler| is temporarily set as the error function 2291the error function \verb|_ERRORMESSAGE| is temporarily set \verb|errhandler|,
2123\verb|_ERRORMESSAGE|, while \verb|func| runs. 2292while \verb|func| runs.
2124In particular, if \verb|errhandler| is \nil, 2293In particular, if \verb|errhandler| is \nil,
2125no error messages will be issued during the execution of the called function. 2294no error messages will be issued during the execution of the called function.
2126 2295
2127\subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage} 2296\subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage}
2128Forces a garbage collection cycle. 2297Forces a garbage collection cycle.
2129Returns the number of objects collected. 2298Returns the number of objects collected.
2130An optional argument, \verb|limit|, is a number that 2299The optional argument \verb|limit| is a number that
2131makes the next cycle occur only after that number of new 2300makes the next cycle occur only after that number of new
2132objects have been created. 2301objects have been created.
2133If \verb|limit| is absent or equal to 0, 2302If \verb|limit| is absent or equal to 0,
2134Lua uses an adaptive algorithm to set this limit. 2303then Lua uses an adaptive algorithm to set this limit.
2135\verb|collectgarbage| is equivalent to 2304\verb|collectgarbage| is equivalent to
2136the API function \verb|lua_collectgarbage|. 2305the API function \verb|lua_collectgarbage|.
2137 2306
2307\subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}}
2308\Deffunc{copytagmethods}
2309Copies all tag methods from one tag to another;
2310it returns \verb|tagto|.
2311
2138\subsubsection*{\ff \T{dofile (filename)}}\Deffunc{dofile} 2312\subsubsection*{\ff \T{dofile (filename)}}\Deffunc{dofile}
2139Receives a file name, 2313Receives a file name,
2140opens the file, and executes the file contents as a Lua chunk, 2314opens the named file, and executes its contents as a Lua chunk,
2141or as pre-compiled chunks. 2315or as pre-compiled chunks.
2142When called without arguments, 2316When called without arguments,
2143\verb|dofile| executes the contents of the standard input (\verb|stdin|). 2317\verb|dofile| executes the contents of the standard input (\verb|stdin|).
@@ -2151,14 +2325,140 @@ It issues an error when called with a non string argument.
2151\subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring} 2325\subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring}
2152Executes a given string as a Lua chunk. 2326Executes a given string as a Lua chunk.
2153If there is any error executing the string, 2327If there is any error executing the string,
2154\verb|dostring| returns \nil. 2328then \verb|dostring| returns \nil.
2155Otherwise, it returns the values returned by the chunk, 2329Otherwise, it returns the values returned by the chunk,
2156or a non \nil\ value if the chunk returns no values. 2330or a non \nil\ value if the chunk returns no values.
2157An optional second parameter (\verb|chunkname|) 2331The optional parameter \verb|chunkname|
2158is the ``name of the chunk'', 2332is the ``name of the chunk'',
2159used in error messages and debug information. 2333used in error messages and debug information.
2160\verb|dostring| is equivalent to the API function \verb|lua_dostring|. 2334\verb|dostring| is equivalent to the API function \verb|lua_dostring|.
2161 2335
2336\subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error}
2337Calls the error handler \see{error} and then terminates
2338the last protected function called
2339(in~C: \verb|lua_dofile|, \verb|lua_dostring|,
2340\verb|lua_dobuffer|, or \verb|lua_callfunction|;
2341in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
2342If \verb|message| is \nil, then the error handler is not called.
2343Function \verb|error| never returns.
2344\verb|error| is equivalent to the API function \verb|lua_error|.
2345
2346\subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach}
2347Executes the given \verb|function| over all elements of \verb|table|.
2348For each element, the function is called with the index and
2349respective value as arguments.
2350If the function returns any non-\nil\ value,
2351then the loop is broken, and this value is returned
2352as the final value of \verb|foreach|.
2353
2354This function could be defined in Lua:
2355\begin{verbatim}
2356 function foreach (t, f)
2357 local i, v = nil
2358 while 1 do
2359 i, v = next(t, i)
2360 if not i then break end
2361 local res = f(i, v)
2362 if res then return res end
2363 end
2364 end
2365\end{verbatim}
2366
2367You may change the \emph{values} of existing fields in the table during the traversal,
2368but
2369if you create new indices,
2370then
2371the semantics of \verb|foreach| is undefined.
2372
2373
2374\subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi}
2375Executes the given \verb|function| over the
2376numerical indices of \verb|table|.
2377For each index, the function is called with the index and
2378respective value as arguments.
2379Indices are visited in sequential order,
2380from 1 to \verb|n|,
2381where \verb|n| is the result of \verb|getn(table)| \see{getn}.
2382If the function returns any non-\nil\ value,
2383then the loop is broken, and this value is returned
2384as the final value of \verb|foreachi|.
2385
2386This function could be defined in Lua:
2387\begin{verbatim}
2388 function foreachi (t, f)
2389 for i=1,getn(t) do
2390 local res = f(i, t[i])
2391 if res then return res end
2392 end
2393 end
2394\end{verbatim}
2395
2396You may change the \emph{values} of existing fields in the table during the traversal,
2397but
2398if you create new indices (even non-numeric),
2399then
2400the semantics of \verb|foreachi| is undefined.
2401
2402\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar}
2403Executes \verb|function| over all global variables.
2404For each variable,
2405the function is called with its name and its value as arguments.
2406If the function returns any non-nil value,
2407then the loop is broken, and this value is returned
2408as the final value of \verb|foreachvar|.
2409
2410This function could be defined in Lua:
2411\begin{verbatim}
2412 function foreachvar (f)
2413 local n, v = nil
2414 while 1 do
2415 n, v = nextvar(n)
2416 if not n then break end
2417 local res = f(n, v)
2418 if res then return res end
2419 end
2420 end
2421\end{verbatim}
2422
2423You may change the values of existing global variables during the traversal,
2424but
2425if you create new global variables,
2426then
2427the semantics of \verb|foreachvar| is undefined.
2428
2429
2430\subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal}
2431Gets the value of a global variable,
2432or calls a tag method for ``getgloball''.
2433Its full semantics is explained in \See{tag-method}.
2434The string \verb|name| does not need to be a
2435syntactically valid variable name.
2436
2437\subsubsection*{\ff \T{getn (table)}}\Deffunc{getn}\label{getn}
2438Returns the ``size'' of a table, when seen as a list.
2439If the table has an \verb|n| field with a numeric value,
2440this value is its ``size''.
2441Otherwise, the size is the largest numerical index with a non-nil
2442value in the table.
2443This function could be defined in Lua:
2444\begin{verbatim}
2445 function getn (t)
2446 if type(t.n) == 'number' then return t.n end
2447 local max, i = 0, nil
2448 while 1 do
2449 i = next(t, i)
2450 if not i then break end
2451 if type(i) == 'number' and i>max then max=i end
2452 end
2453 return max
2454 end
2455\end{verbatim}
2456
2457\subsubsection*{\ff \T{gettagmethod (tag, event)}}
2458\Deffunc{gettagmethod}
2459Returns the current tag method
2460for a given pair \M{(tag, event)}.
2461
2162\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} 2462\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag}
2163Returns a new tag. 2463Returns a new tag.
2164\verb|newtag| is equivalent to the API function \verb|lua_newtag|. 2464\verb|newtag| is equivalent to the API function \verb|lua_newtag|.
@@ -2170,23 +2470,26 @@ is an index in this table.
2170It returns the next index of the table and the 2470It returns the next index of the table and the
2171value associated with the index. 2471value associated with the index.
2172When called with \nil\ as its second argument, 2472When called with \nil\ as its second argument,
2173the function returns the first index 2473\verb|next| returns the first index
2174of the table (and its associated value). 2474of the table and its associated value.
2175When called with the last index, 2475When called with the last index,
2176or with \nil\ in an empty table, 2476or with \nil\ in an empty table,
2177it returns \nil. 2477it returns \nil.
2178If the second argument is absent, it is interpreted as \nil. 2478If the second argument is absent, then it is interpreted as \nil.
2179 2479
2180Lua has no declaration of fields; 2480Lua has no declaration of fields;
2181semantically, there is no difference between a 2481semantically, there is no difference between a
2182field not present in a table or a field with value \nil. 2482field not present in a table or a field with value \nil.
2183Therefore, the function only considers fields with non \nil\ values. 2483Therefore, \verb|next| only considers fields with non \nil\ values.
2184The order in which the indices are enumerated is not specified, 2484The order in which the indices are enumerated is not specified,
2185\emph{even for numeric indices} 2485\emph{even for numeric indices}
2186(to traverse a table in numeric order, 2486(to traverse a table in numeric order,
2187use a counter or the function \verb|foreachi|). 2487use a counter or the function \verb|foreachi|).
2188If you create new indices in a table while 2488
2189traversing it, 2489You may change the \emph{values} of existing fields in the table during the traversal,
2490but
2491if you create new indices,
2492then
2190the semantics of \verb|next| is undefined. 2493the semantics of \verb|next| is undefined.
2191 2494
2192\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} 2495\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar}
@@ -2194,18 +2497,16 @@ This function is similar to the function \verb|next|,
2194but iterates instead over the global variables. 2497but iterates instead over the global variables.
2195Its single argument is the name of a global variable, 2498Its single argument is the name of a global variable,
2196or \nil\ to get a first name. 2499or \nil\ to get a first name.
2197If this argument is absent, it is interpreted as \nil. 2500If this argument is absent, then it is interpreted as \nil.
2198Similarly to \verb|next|, it returns the name of another variable 2501Like \verb|next|, \verb|nextvar| returns the name of another variable
2199and its value, 2502and its value,
2200or \nil\ if there are no more variables. 2503or \nil\ if there are no more variables.
2201If you create new global variables during the traversal,
2202the semantics of \verb|nextvar| is undefined.
2203 2504
2204\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring} 2505You may change the \emph{values} of existing global variables during the traversal,
2205Receives an argument of any type and 2506but
2206converts it to a string in a reasonable format. 2507if you create new global variables,
2207For complete control on how numbers are converted, 2508then
2208use function \verb|format|. 2509the semantics of \verb|nextvar| is undefined.
2209 2510
2210\subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print} 2511\subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print}
2211Receives any number of arguments, 2512Receives any number of arguments,
@@ -2215,77 +2516,11 @@ but only as a quick way to show a value,
2215for instance for debugging. 2516for instance for debugging.
2216See \See{libio} for functions for formatted output. 2517See \See{libio} for functions for formatted output.
2217 2518
2218\subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} 2519\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
2219Prints its only string argument to \IndexVerb{stderr}. 2520Gets the value of a global variable,
2220All error messages in Lua are printed through the function stored 2521without invoking any tag method.
2221in the \verb|_ALERT| global variable. 2522The string \verb|name| does not need to be a
2222Therefore, a program may assign another function to this variable 2523syntactically valid variable name.
2223to change the way such messages are shown
2224(for instance, for systems without \verb|stderr|).
2225
2226\subsubsection*{\ff \T{tonumber (e [, base])}}\Deffunc{tonumber}
2227Receives one argument,
2228and tries to convert it to a number.
2229If the argument is already a number or a string convertible
2230to a number, then \verb|tonumber| returns that number;
2231otherwise, it returns \nil.
2232
2233An optional argument specifies the base to interpret the numeral.
2234The base may be any integer between 2 and 36 inclusive.
2235In bases above 10, the letter `A' (either upper or lower case)
2236represents 10, `B' represents 11, and so forth, with `Z' representing 35.
2237
2238In base 10 (the default), the number may have a decimal part,
2239as well as an optional exponent part \see{coercion}.
2240In other bases, only unsigned integers are accepted.
2241
2242\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type}
2243Allows Lua to test the type of a value.
2244It receives one argument, and returns its type, coded as a string.
2245The possible results of this function are
2246\verb|"nil"| (a string, not the value \nil),
2247\verb|"number"|,
2248\verb|"string"|,
2249\verb|"table"|,
2250\verb|"function"|,
2251and \verb|"userdata"|.
2252
2253\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag}
2254Allows Lua to test the tag of a value \see{TypesSec}.
2255It receives one argument, and returns its tag (a number).
2256\verb|tag| is equivalent to the API function \verb|lua_tag|.
2257
2258\subsubsection*{\ff \T{settag (t, tag)}}\Deffunc{settag}
2259Sets the tag of a given table \see{TypesSec}.
2260\verb|tag| must be a value created with \verb|newtag|
2261\see{pdf-newtag}.
2262It returns the value of its first argument (the table).
2263For security reasons,
2264it is impossible to change the tag of a userdata from Lua.
2265
2266
2267\subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert}
2268Issues an \emph{``assertion failed!''} error
2269when its argument is \nil.
2270This function is equivalent to the following Lua function:
2271\begin{verbatim}
2272 function assert (v, m)
2273 if not v then
2274 m = m or ""
2275 error("assertion failed! " .. m)
2276 end
2277 end
2278\end{verbatim}
2279
2280\subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error}
2281Calls the error handler and then terminates
2282the last protected function called
2283(in~C: \verb|lua_dofile|, \verb|lua_dostring|,
2284\verb|lua_dobuffer|, or \verb|lua_callfunction|;
2285in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
2286If \verb|message| is \nil, the error handler is not called.
2287Function \verb|error| never returns.
2288\verb|error| is equivalent to the API function \verb|lua_error|.
2289 2524
2290\subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable} 2525\subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable}
2291Gets the real value of \verb|table[index]|, 2526Gets the real value of \verb|table[index]|,
@@ -2293,6 +2528,15 @@ without invoking any tag method.
2293\verb|table| must be a table, 2528\verb|table| must be a table,
2294and \verb|index| is any value different from \nil. 2529and \verb|index| is any value different from \nil.
2295 2530
2531\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
2532Sets the named global variable to the given value,
2533without invoking any tag method.
2534The string \verb|name| does not need to be a
2535syntactically valid variable name.
2536Therefore,
2537this function can be used to set global variables with strange names like
2538\verb|"m v 1"| or \verb|"34"|.
2539
2296\subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} 2540\subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable}
2297Sets the real value of \verb|table[index]| to \verb|value|, 2541Sets the real value of \verb|table[index]| to \verb|value|,
2298without invoking any tag method. 2542without invoking any tag method.
@@ -2300,142 +2544,67 @@ without invoking any tag method.
2300\verb|index| is any value different from \nil, 2544\verb|index| is any value different from \nil,
2301and \verb|value| is any Lua value. 2545and \verb|value| is any Lua value.
2302 2546
2303\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
2304Assigns the given value to a global variable.
2305The string \verb|name| does not need to be a
2306syntactically valid variable name.
2307Therefore,
2308this function can set global variables with strange names like
2309\verb|"m v 1"| or \verb|34|.
2310
2311\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} 2547\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal}
2312Assigns the given value to a global variable, 2548Sets the named global variable to the given value,
2313or calls a tag method. 2549or calls a tag method for ``setgloball''.
2314Its full semantics is explained in \See{tag-method}. 2550Its full semantics is explained in \See{tag-method}.
2315The string \verb|name| does not need to be a 2551The string \verb|name| does not need to be a
2316syntactically valid variable name. 2552syntactically valid variable name.
2317 2553
2318\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} 2554\subsubsection*{\ff \T{settag (t, tag)}}\Deffunc{settag}
2319Retrieves the value of a global variable. 2555Sets the tag of a given table \see{TypesSec}.
2320The string \verb|name| does not need to be a 2556\verb|tag| must be a value created with \verb|newtag|
2321syntactically valid variable name. 2557\see{pdf-newtag}.
2322 2558It returns the value of its first argument (the table).
2323\subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal} 2559For the safety of host programs,
2324Retrieves the value of a global variable, 2560it is impossible to change the tag of a userdata from Lua.
2325or calls a tag method.
2326Its full semantics is explained in \See{tag-method}.
2327The string \verb|name| does not need to be a
2328syntactically valid variable name.
2329 2561
2330\subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} 2562\subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}}
2331\Deffunc{settagmethod} 2563\Deffunc{settagmethod}
2332Sets a new tag method to the given pair \M{(tag, event)}. 2564Sets a new tag method to the given pair \M{(tag, event)}.
2333It returns the old method. 2565It returns the old method.
2334If \verb|newmethod| is \nil, 2566If \verb|newmethod| is \nil,
2335\verb|settagmethod| restores the default behavior for the given event. 2567then \verb|settagmethod| restores the default behavior for the given event.
2336
2337\subsubsection*{\ff \T{gettagmethod (tag, event)}}
2338\Deffunc{gettagmethod}
2339Returns the current tag method
2340for a given pair \M{(tag, event)}.
2341
2342\subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}}
2343\Deffunc{copytagmethods}
2344Copies all tag methods from one tag to another;
2345it returns \verb|tagto|.
2346
2347\subsubsection*{\ff \T{getn (table)}}\Deffunc{getn}\label{getn}
2348Returns the ``size'' of a table, when seen as a list.
2349If the table has an \verb|n| field with a numeric value,
2350this is its ``size''.
2351Otherwise, the size is the largest numerical index with a non-nil
2352value in the table.
2353This function could be defined in Lua:
2354\begin{verbatim}
2355 function getn (t)
2356 if type(t.n) == 'number' then return t.n end
2357 local max, i = 0, nil
2358 while 1 do
2359 i = next(t, i)
2360 if not i then break end
2361 if type(i) == 'number' and i>max then max=i end
2362 end
2363 return max
2364 end
2365\end{verbatim}
2366
2367 2568
2368\subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach} 2569\subsubsection*{\ff \T{sort (table [, comp])}}\Deffunc{sort}
2369Executes the given \verb|function| over all elements of \verb|table|. 2570Sorts table elements in a given order, \emph{in-place},
2370For each element, the function is called with the index and 2571from \verb|table[1]| to \verb|table[n]|,
2371respective value as arguments. 2572where \verb|n| is the result of \verb|getn(table)| \see{getn}.
2372If the function returns any non-\nil\ value, 2573If \verb|comp| is given,
2373the loop is broken, and the value is returned 2574it must be a function that receives two table elements,
2374as the final value of \verb|foreach|. 2575and returns true when the first is less than the second
2375 2576(so that \verb|not comp(a[i+1], a[i])| will be true after the sort).
2376This function could be defined in Lua: 2577If \verb|comp| is not given,
2377\begin{verbatim} 2578the standard Lua operator \verb|<| is used instead.
2378 function foreach (t, f)
2379 local i, v = nil
2380 while 1 do
2381 i, v = next(t, i)
2382 if not i then break end
2383 local res = f(i, v)
2384 if res then return res end
2385 end
2386 end
2387\end{verbatim}
2388 2579
2389If you create new indices in a table while 2580\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag}
2390traversing it, 2581Allows Lua programs to test the tag of a value \see{TypesSec}.
2391the semantics of \verb|foreach| is undefined. 2582It receives one argument, and returns its tag (a number).
2583\verb|tag| is equivalent to the API function \verb|lua_tag|.
2392 2584
2585\subsubsection*{\ff \T{tonumber (e [, base])}}\Deffunc{tonumber}
2586Receives one argument,
2587and tries to convert it to a number.
2588If the argument is already a number or a string convertible
2589to a number, then \verb|tonumber| returns that number;
2590otherwise, it returns \nil.
2393 2591
2394\subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi} 2592An optional argument specifies the base to interpret the numeral.
2395Executes the given \verb|function| over the 2593The base may be any integer between 2 and 36, inclusive.
2396numerical indices of \verb|table|. 2594In bases above~10, the letter `A' (either upper or lower case)
2397For each index, the function is called with the index and 2595represents~10, `B' represents~11, and so forth, with `Z' representing 35.
2398respective value as arguments.
2399Indices are visited in sequential order,
2400from 1 to \verb|n|,
2401where \verb|n| is the result of \verb|getn(table)| \see{getn}.
2402If the function returns any non-\nil\ value,
2403the loop is broken, and the value is returned
2404as the final value of \verb|foreachi|.
2405 2596
2406This function could be defined in Lua: 2597In base 10 (the default), the number may have a decimal part,
2407\begin{verbatim} 2598as well as an optional exponent part \see{coercion}.
2408 function foreachi (t, f) 2599In other bases, only unsigned integers are accepted.
2409 for i=1,getn(t) do
2410 local res = f(i, t[i])
2411 if res then return res end
2412 end
2413 end
2414\end{verbatim}
2415 2600
2416\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} 2601\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring}
2417Executes \verb|function| over all global variables. 2602Receives an argument of any type and
2418For each variable, 2603converts it to a string in a reasonable format.
2419the function is called with its name and its value as arguments. 2604For complete control on how numbers are converted,
2420If the function returns any non-nil value, 2605use function \verb|format|.
2421the loop is broken, and the value is returned
2422as the final value of \verb|foreachvar|.
2423 2606
2424This function could be defined in Lua:
2425\begin{verbatim}
2426 function foreachvar (f)
2427 local n, v = nil
2428 while 1 do
2429 n, v = nextvar(n)
2430 if not n then break end
2431 local res = f(n, v)
2432 if res then return res end
2433 end
2434 end
2435\end{verbatim}
2436 2607
2437If you create new global variables during the traversal,
2438the semantics of \verb|foreachvar| is undefined.
2439 2608
2440\subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert} 2609\subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert}
2441 2610
@@ -2445,12 +2614,11 @@ The default value for \verb|pos| is \verb|n+1|,
2445where \verb|n| is the result of \verb|getn(table)| \see{getn}, 2614where \verb|n| is the result of \verb|getn(table)| \see{getn},
2446so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end 2615so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end
2447of table \verb|t|. 2616of table \verb|t|.
2448 2617This function also sets or increments the field \verb|n| of the table
2449This function also sets or increments the field \verb|n| of the table,
2450to \verb|n+1|. 2618to \verb|n+1|.
2451 2619
2452This function is equivalent to the following Lua function, 2620This function is equivalent to the following Lua function,
2453except that the table accesses are all raw (that is, without tag methods): 2621except that the table accesses are all \emph{raw} (that is, without tag methods):
2454\begin{verbatim} 2622\begin{verbatim}
2455 function tinsert (t, ...) 2623 function tinsert (t, ...)
2456 local pos, value 2624 local pos, value
@@ -2473,16 +2641,15 @@ except that the table accesses are all raw (that is, without tag methods):
2473Removes from \verb|table| the element at position \verb|pos|, 2641Removes from \verb|table| the element at position \verb|pos|,
2474shifting other elements to close the space, if necessary. 2642shifting other elements to close the space, if necessary.
2475Returns the value of the removed element. 2643Returns the value of the removed element.
2476The default value for \verb|pos| is \verb|n| 2644The default value for \verb|pos| is \verb|n|,
2477(where \verb|n| is the result of \verb|getn(table)| \see{getn}), 2645where \verb|n| is the result of \verb|getn(table)| \see{getn},
2478so that a call \verb|tremove(t)| removes the last element 2646so that a call \verb|tremove(t)| removes the last element
2479of table \verb|t|. 2647of table \verb|t|.
2480 2648This function also sets or decrements the field \verb|n| of the table
2481This function also sets or decrements the field \verb|n| of the table,
2482to \verb|n-1|. 2649to \verb|n-1|.
2483 2650
2484This function is equivalent to the following Lua function, 2651This function is equivalent to the following Lua function,
2485except that the table accesses are all raw (that is, without tag methods): 2652except that the table accesses are all \emph{raw} (that is, without tag methods):
2486\begin{verbatim} 2653\begin{verbatim}
2487 function tremove (t, pos) 2654 function tremove (t, pos)
2488 local n = getn(t) 2655 local n = getn(t)
@@ -2498,16 +2665,17 @@ except that the table accesses are all raw (that is, without tag methods):
2498 end 2665 end
2499\end{verbatim} 2666\end{verbatim}
2500 2667
2501\subsubsection*{\ff \T{sort (table [, comp])}}\Deffunc{sort} 2668\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type}
2502Sorts table elements in a given order, \emph{in-place}, 2669Allows Lua programs to test the type of a value.
2503from \verb|table[1]| to \verb|table[n]|, 2670It receives one argument, and returns its type, coded as a string.
2504where \verb|n| is the result of \verb|getn(table)| \see{getn}. 2671The possible results of this function are
2505If \verb|comp| is given, 2672\verb|"nil"| (a string, not the value \nil),
2506it must be a function that receives two table elements, 2673\verb|"number"|,
2507and returns true when the first is less than the second 2674\verb|"string"|,
2508(so that \verb|not comp(a[i+1], a[i])| will be true after the sort). 2675\verb|"table"|,
2509If \verb|comp| is not given, 2676\verb|"function"|,
2510the standard Lua operator \verb|<| is used instead. 2677and \verb|"userdata"|.
2678\verb|type| is equivalent to the API function \verb|lua_type|.
2511 2679
2512 2680
2513\subsection{String Manipulation} 2681\subsection{String Manipulation}
@@ -2516,6 +2684,26 @@ such as finding and extracting substrings and pattern matching.
2516When indexing a string, the first character is at position~1 2684When indexing a string, the first character is at position~1
2517(not at~0, as in C). 2685(not at~0, as in C).
2518 2686
2687\subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte}
2688Returns the internal numerical code of the character \verb|s[i]|.
2689If \verb|i| is absent, then it is assumed to be 1.
2690If \verb|i| is negative,
2691it is replaced by the length of the string minus its
2692absolute value plus 1.
2693Therefore, \Math{-1} points to the last character of \verb|s|.
2694
2695\NOTE
2696\emph{numerical codes are not necessarily portable across platforms}.
2697
2698\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar}
2699Receives 0 or more integers.
2700Returns a string with length equal to the number of arguments,
2701wherein each character has the internal numerical code equal
2702to its correspondent argument.
2703
2704\NOTE
2705\emph{numerical codes are not necessarily portable across platforms}.
2706
2519\subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} 2707\subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}}
2520\Deffunc{strfind} 2708\Deffunc{strfind}
2521Looks for the first \emph{match} of 2709Looks for the first \emph{match} of
@@ -2523,7 +2711,7 @@ Looks for the first \emph{match} of
2523If it finds one, then it returns the indices on \verb|str| 2711If it finds one, then it returns the indices on \verb|str|
2524where this occurrence starts and ends; 2712where this occurrence starts and ends;
2525otherwise, it returns \nil. 2713otherwise, it returns \nil.
2526If the pattern specifies captures, 2714If the pattern specifies captures (see \verb|gsub| below),
2527the captured strings are returned as extra results. 2715the captured strings are returned as extra results.
2528A third optional numerical argument specifies where to start the search; 2716A third optional numerical argument specifies where to start the search;
2529its default value is 1. 2717its default value is 1.
@@ -2538,6 +2726,19 @@ with no characters in \verb|pattern| being considered ``magic''.
2538 2726
2539\subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen} 2727\subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen}
2540Receives a string and returns its length. 2728Receives a string and returns its length.
2729The empty string \verb|""| has length 0.
2730Embedded zeros are counted.
2731
2732\subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower}
2733Receives a string and returns a copy of that string with all
2734upper case letters changed to lower case.
2735All other characters are left unchanged.
2736The definition of what is an upper-case
2737letter depends on the current locale.
2738
2739\subsubsection*{\ff \T{strrep (s, n)}}\Deffunc{strrep}
2740Returns a string that is the concatenation of \verb|n| copies of
2741the string \verb|s|.
2541 2742
2542\subsubsection*{\ff \T{strsub (s, i [, j])}}\Deffunc{strsub} 2743\subsubsection*{\ff \T{strsub (s, i [, j])}}\Deffunc{strsub}
2543Returns another string, which is a substring of \verb|s|, 2744Returns another string, which is a substring of \verb|s|,
@@ -2555,13 +2756,6 @@ with length \verb|j|,
2555and the call \verb|strsub(s, -i)| returns a suffix of \verb|s| 2756and the call \verb|strsub(s, -i)| returns a suffix of \verb|s|
2556with length \verb|i|. 2757with length \verb|i|.
2557 2758
2558\subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower}
2559Receives a string and returns a copy of that string with all
2560upper case letters changed to lower case.
2561All other characters are left unchanged.
2562The definition of what is an upper case
2563letter depends on the current locale.
2564
2565\subsubsection*{\ff \T{strupper (s)}}\Deffunc{strupper} 2759\subsubsection*{\ff \T{strupper (s)}}\Deffunc{strupper}
2566Receives a string and returns a copy of that string with all 2760Receives a string and returns a copy of that string with all
2567lower case letters changed to upper case. 2761lower case letters changed to upper case.
@@ -2569,42 +2763,20 @@ All other characters are left unchanged.
2569The definition of what is a lower case 2763The definition of what is a lower case
2570letter depends on the current locale. 2764letter depends on the current locale.
2571 2765
2572\subsubsection*{\ff \T{strrep (s, n)}}\Deffunc{strrep}
2573Returns a string that is the concatenation of \verb|n| copies of
2574the string \verb|s|.
2575
2576\subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte}
2577Returns the internal numerical code of the character \verb|s[i]|.
2578If \verb|i| is absent, then it is assumed to be 1.
2579If \verb|i| is negative,
2580it is replaced by the length of the string minus its
2581absolute value plus 1.
2582Therefore, \Math{-1} points to the last character of \verb|s|.
2583
2584Note that numerical codes are not necessarily portable across platforms.
2585
2586\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar}
2587Receives 0 or more integers.
2588Returns a string with length equal to the number of arguments,
2589wherein each character has the internal numerical code equal
2590to its correspondent argument.
2591
2592Note that numerical codes are not necessarily portable across platforms.
2593
2594\subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\Deffunc{format} 2766\subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\Deffunc{format}
2595\label{format} 2767\label{format}
2596Returns a formatted version of its variable number of arguments 2768Returns a formatted version of its variable number of arguments
2597following the description given in its first argument (which must be a string). 2769following the description given in its first argument (which must be a string).
2598The format string follows the same rules as the \verb|printf| family of 2770The format string follows the same rules as the \verb|printf| family of
2599standard C functions. 2771standard C~functions.
2600The only differences are that the options/modifiers 2772The only differences are that the options/modifiers
2601\verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|, 2773\verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|,
2602and \verb|h| are not supported, 2774and \verb|h| are not supported,
2603and there is an extra option, \verb|q|. 2775and there is an extra option, \verb|q|.
2604This option formats a string in a form suitable to be safely read 2776The \verb|q| option formats a string in a form suitable to be safely read
2605back by the Lua interpreter: 2777back by the Lua interpreter:
2606The string is written between double quotes, 2778The string is written between double quotes,
2607and all double quotes, returns and backslashes in the string 2779and all double quotes, returns, and backslashes in the string
2608are correctly escaped when written. 2780are correctly escaped when written.
2609For instance, the call 2781For instance, the call
2610\begin{verbatim} 2782\begin{verbatim}
@@ -2616,7 +2788,7 @@ will produce the string:
2616 new line" 2788 new line"
2617\end{verbatim} 2789\end{verbatim}
2618 2790
2619Conversions can be applied to the n-th argument in the argument list, 2791Conversions can be applied to the \M{n}-th argument in the argument list,
2620rather than the next unused argument. 2792rather than the next unused argument.
2621In this case, the conversion character \verb|%| is replaced 2793In this case, the conversion character \verb|%| is replaced
2622by the sequence \verb|%d$|, where \verb|d| is a 2794by the sequence \verb|%d$|, where \verb|d| is a
@@ -2635,13 +2807,14 @@ the appropriate format string.
2635For example, \verb|"%*g"| can be simulated with 2807For example, \verb|"%*g"| can be simulated with
2636\verb|"%"..width.."g"|. 2808\verb|"%"..width.."g"|.
2637 2809
2638\emph{Note: function \T{format} can only be used with strings that do not 2810\NOTE
2639contain zeros (0).} 2811\emph{Neither the format string nor the string values to be formatted with
2812\T{format} can contain embedded zeros.}
2640 2813
2641\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} 2814\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}}
2642\Deffunc{gsub} 2815\Deffunc{gsub}
2643Returns a copy of \verb|s|, 2816Returns a copy of \verb|s|,
2644where all occurrences of the pattern \verb|pat| have been 2817in which all occurrences of the pattern \verb|pat| have been
2645replaced by a replacement string specified by \verb|repl|. 2818replaced by a replacement string specified by \verb|repl|.
2646This function also returns, as a second value, 2819This function also returns, as a second value,
2647the total number of substitutions made. 2820the total number of substitutions made.
@@ -2649,7 +2822,7 @@ the total number of substitutions made.
2649If \verb|repl| is a string, then its value is used for replacement. 2822If \verb|repl| is a string, then its value is used for replacement.
2650Any sequence in \verb|repl| of the form \verb|%n| 2823Any sequence in \verb|repl| of the form \verb|%n|
2651with \verb|n| between 1 and 9 2824with \verb|n| between 1 and 9
2652stands for the value of the n-th captured substring. 2825stands for the value of the \M{n}-th captured substring.
2653 2826
2654If \verb|repl| is a function, then this function is called every time a 2827If \verb|repl| is a function, then this function is called every time a
2655match occurs, with all captured substrings passed as arguments, 2828match occurs, with all captured substrings passed as arguments,
@@ -2658,7 +2831,7 @@ If the value returned by this function is a string,
2658then it is used as the replacement string; 2831then it is used as the replacement string;
2659otherwise, the replacement string is the empty string. 2832otherwise, the replacement string is the empty string.
2660 2833
2661A last optional parameter \verb|n| limits 2834The last, optional parameter \verb|n| limits
2662the maximum number of substitutions to occur. 2835the maximum number of substitutions to occur.
2663For instance, when \verb|n| is 1 only the first occurrence of 2836For instance, when \verb|n| is 1 only the first occurrence of
2664\verb|pat| is replaced. 2837\verb|pat| is replaced.
@@ -2713,18 +2886,19 @@ The following combinations are allowed in describing a character class:
2713\item[\T{\%\M{x}}] (where \M{x} is any non alphanumeric character) --- 2886\item[\T{\%\M{x}}] (where \M{x} is any non alphanumeric character) ---
2714represents the character \M{x}. 2887represents the character \M{x}.
2715This is the standard way to escape the magic characters \verb|()%.[]*-?|. 2888This is the standard way to escape the magic characters \verb|()%.[]*-?|.
2716It is strongly recommended that any control character (even the non magic), 2889It is strongly recommended that any control character (even the non magic)
2717when used to represent itself in a pattern, should be preceded by a \verb|%|. 2890should be preceded by a \verb|%|
2891when used to represent itself in a pattern,
2718 2892
2719\item[\T{[char-set]}] --- 2893\item[\T{[char-set]}] ---
2720Represents the class which is the union of all 2894represents the class which is the union of all
2721characters in char-set. 2895characters in char-set.
2722A range of characters may be specified by 2896A range of characters may be specified by
2723separating the end characters of the range with a \verb|-|. 2897separating the end characters of the range with a \verb|-|.
2724All classes \verb|%|\emph{x} described above can also be used as 2898All classes \verb|%|\emph{x} described above may also be used as
2725components in a char-set. 2899components in a char-set.
2726All other characters in char-set represent themselves. 2900All other characters in char-set represent themselves.
2727E.g., \verb|[%w_]| (or \verb|[_%w]|) 2901For example, \verb|[%w_]| (or \verb|[_%w]|)
2728represents all alphanumeric characters plus the underscore, 2902represents all alphanumeric characters plus the underscore,
2729\verb|[0-7]| represents the octal digits, 2903\verb|[0-7]| represents the octal digits,
2730and \verb|[0-7%l%-]| represents the octal digits plus 2904and \verb|[0-7%l%-]| represents the octal digits plus
@@ -2739,7 +2913,7 @@ represents the complement of char-set,
2739where char-set is interpreted as above. 2913where char-set is interpreted as above.
2740\end{description} 2914\end{description}
2741For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), 2915For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots),
2742the correspondent upper-case letter represents the complement of the class. 2916the corresponding upper-case letter represents the complement of the class.
2743For instance, \verb|%S| represents all non-space characters. 2917For instance, \verb|%S| represents all non-space characters.
2744 2918
2745The definitions of letter, space, etc. depend on the current locale. 2919The definitions of letter, space, etc. depend on the current locale.
@@ -2770,14 +2944,14 @@ a single character class followed by \verb|?|,
2770which matches 0 or 1 occurrence of a character in the class; 2944which matches 0 or 1 occurrence of a character in the class;
2771\item 2945\item
2772\T{\%\M{n}}, for \M{n} between 1 and 9; 2946\T{\%\M{n}}, for \M{n} between 1 and 9;
2773such item matches a sub-string equal to the n-th captured string 2947such item matches a sub-string equal to the \M{n}-th captured string
2774(see below); 2948(see below);
2775\item 2949\item
2776\T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; 2950\T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters;
2777such item matches strings that start with \M{x}, end with \M{y}, 2951such item matches strings that start with~\M{x}, end with~\M{y},
2778and where the \M{x} and \M{y} are \emph{balanced}. 2952and where the \M{x} and \M{y} are \emph{balanced}.
2779That means that, if one reads the string from left to write, 2953This means that, if one reads the string from left to right,
2780counting plus 1 for an \M{x} and minus 1 for a \M{y}, 2954counting \Math{+1} for an \M{x} and \Math{-1} for a \M{y},
2781the ending \M{y} is the first where the count reaches 0. 2955the ending \M{y} is the first where the count reaches 0.
2782For instance, the item \verb|%b()| matches expressions with 2956For instance, the item \verb|%b()| matches expressions with
2783balanced parentheses. 2957balanced parentheses.
@@ -2789,9 +2963,11 @@ A \verb|^| at the beginning of a pattern anchors the match at the
2789beginning of the subject string. 2963beginning of the subject string.
2790A \verb|$| at the end of a pattern anchors the match at the 2964A \verb|$| at the end of a pattern anchors the match at the
2791end of the subject string. 2965end of the subject string.
2966At other positions,
2967\verb|^| and \verb|$| have no special meaning and represent themselves.
2792 2968
2793\paragraph{Captures:} 2969\paragraph{Captures:}
2794a pattern may contain sub-patterns enclosed in parentheses, 2970A pattern may contain sub-patterns enclosed in parentheses,
2795that describe \Def{captures}. 2971that describe \Def{captures}.
2796When a match succeeds, the sub-strings of the subject string 2972When a match succeeds, the sub-strings of the subject string
2797that match captures are stored (\emph{captured}) for future use. 2973that match captures are stored (\emph{captured}) for future use.
@@ -2802,8 +2978,9 @@ stored as the first capture (and therefore has number~1);
2802the character matching \verb|.| is captured with number~2, 2978the character matching \verb|.| is captured with number~2,
2803and the part matching \verb|%s*| has number~3. 2979and the part matching \verb|%s*| has number~3.
2804 2980
2805{\em Note: A pattern cannot contain zeros (\verb|'\0'|). 2981\NOTE
2806Use \verb|'%z'| instead.} 2982{\em A pattern cannot contain embedded zeros.
2983Use \verb|%z| instead.}
2807 2984
2808 2985
2809\subsection{Mathematical Functions} \label{mathlib} 2986\subsection{Mathematical Functions} \label{mathlib}
@@ -2820,13 +2997,13 @@ The library provides the following functions:
2820\Deffunc{frexp}\Deffunc{ldexp} 2997\Deffunc{frexp}\Deffunc{ldexp}
2821\Deffunc{random}\Deffunc{randomseed} 2998\Deffunc{random}\Deffunc{randomseed}
2822\begin{verbatim} 2999\begin{verbatim}
2823abs acos asin atan atan2 ceil cos deg floor log log10 3000 abs acos asin atan atan2 ceil cos deg floor log log10
2824max min mod rad sin sqrt tan frexp ldexp 3001 max min mod rad sin sqrt tan frexp ldexp
2825random randomseed 3002 random randomseed
2826\end{verbatim} 3003\end{verbatim}
2827plus a global variable \IndexVerb{PI}. 3004plus a global variable \IndexVerb{PI}.
2828Most of them 3005Most of them
2829are only interfaces to the homonymous functions in the C library, 3006are only interfaces to the homonymous functions in the C~library,
2830except that, for the trigonometric functions, 3007except that, for the trigonometric functions,
2831all angles are expressed in \emph{degrees}, not radians. 3008all angles are expressed in \emph{degrees}, not radians.
2832Functions \IndexVerb{deg} and \IndexVerb{rad} can be used to convert 3009Functions \IndexVerb{deg} and \IndexVerb{rad} can be used to convert
@@ -2835,11 +3012,12 @@ between radians and degrees.
2835The function \verb|max| returns the maximum 3012The function \verb|max| returns the maximum
2836value of its numeric arguments. 3013value of its numeric arguments.
2837Similarly, \verb|min| computes the minimum. 3014Similarly, \verb|min| computes the minimum.
2838Both can be used with 1, 2 or more arguments. 3015Both can be used with 1, 2, or more arguments.
2839 3016
2840The functions \verb|random| and \verb|randomseed| are interfaces to 3017The functions \verb|random| and \verb|randomseed| are interfaces to
2841the simple random generator functions \verb|rand| and \verb|srand|, 3018the simple random generator functions \verb|rand| and \verb|srand|,
2842provided by ANSI C. 3019provided by ANSI C.
3020(No guarantees can be given for their statistical properties.)
2843The function \verb|random|, when called without arguments, 3021The function \verb|random|, when called without arguments,
2844returns a pseudo-random real number in the range \Math{[0,1)}. 3022returns a pseudo-random real number in the range \Math{[0,1)}.
2845When called with a number \Math{n}, 3023When called with a number \Math{n},
@@ -2855,7 +3033,7 @@ over two \Def{file handles}, one for reading and one for writing.
2855These handles are stored in two Lua global variables, 3033These handles are stored in two Lua global variables,
2856called \verb|_INPUT| and \verb|_OUTPUT|. 3034called \verb|_INPUT| and \verb|_OUTPUT|.
2857The global variables 3035The global variables
2858\verb|_STDIN|, \verb|_STDOUT| and \verb|_STDERR| 3036\verb|_STDIN|, \verb|_STDOUT|, and \verb|_STDERR|
2859are initialized with file descriptors for 3037are initialized with file descriptors for
2860\verb|stdin|, \verb|stdout| and \verb|stderr|. 3038\verb|stdin|, \verb|stdout| and \verb|stderr|.
2861Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|. 3039Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|.
@@ -2877,7 +3055,7 @@ It returns a new file handle,
2877or, in case of errors, \nil\ plus a string describing the error. 3055or, in case of errors, \nil\ plus a string describing the error.
2878This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. 3056This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
2879 3057
2880The string mode can be any of the following: 3058The \verb|mode| string can be any of the following:
2881\begin{description} 3059\begin{description}
2882\item[``r''] read mode; 3060\item[``r''] read mode;
2883\item[``w''] write mode; 3061\item[``w''] write mode;
@@ -2887,8 +3065,9 @@ The string mode can be any of the following:
2887\item[``a+''] append update mode, previous data is preserved, 3065\item[``a+''] append update mode, previous data is preserved,
2888 writing is only allowed at the end of file. 3066 writing is only allowed at the end of file.
2889\end{description} 3067\end{description}
2890The string mode may also have a \verb|b| at the end, 3068The \verb|mode| string may also have a \verb|b| at the end,
2891which is needed in some systems to open the file in binary mode. 3069which is needed in some systems to open the file in binary mode.
3070This string is exactlty what is used in the standard~C function \verb|fopen|.
2892 3071
2893\subsubsection*{\ff \T{closefile (handle)}}\Deffunc{closefile} 3072\subsubsection*{\ff \T{closefile (handle)}}\Deffunc{closefile}
2894 3073
@@ -2972,7 +3151,7 @@ plus a string describing the error.
2972 3151
2973Saves any written data to the given file. 3152Saves any written data to the given file.
2974If \verb|filehandle| is not specified, 3153If \verb|filehandle| is not specified,
2975flushes all open files. 3154then \verb|flush| flushes all open files.
2976If this function fails, it returns \nil, 3155If this function fails, it returns \nil,
2977plus a string describing the error. 3156plus a string describing the error.
2978 3157
@@ -3016,7 +3195,7 @@ according to the given formats, which specify what to read.
3016For each format, 3195For each format,
3017the function returns a string (or a number) with the characters read, 3196the function returns a string (or a number) with the characters read,
3018or \nil\ if it cannot read data with the specified format. 3197or \nil\ if it cannot read data with the specified format.
3019When called without patterns, 3198When called without formats,
3020it uses a default format that reads the next line 3199it uses a default format that reads the next line
3021(see below). 3200(see below).
3022 3201
@@ -3032,6 +3211,8 @@ On end of file, it returns the empty string.
3032\item[``*w''] reads the next word 3211\item[``*w''] reads the next word
3033(maximal sequence of non white-space characters), 3212(maximal sequence of non white-space characters),
3034skipping spaces if necessary, or \nil\ on end of file. 3213skipping spaces if necessary, or \nil\ on end of file.
3214\item[\emph{number}] reads a string with up to that number of characters,
3215or \nil\ on end of file.
3035\end{description} 3216\end{description}
3036 3217
3037\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write} 3218\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write}
@@ -3049,7 +3230,7 @@ plus a string describing the error.
3049 3230
3050Returns a string containing date and time 3231Returns a string containing date and time
3051formatted according to the given string \verb|format|, 3232formatted according to the given string \verb|format|,
3052following the same rules of the ANSI C function \verb|strftime|. 3233following the same rules of the ANSI~C function \verb|strftime|.
3053When called without arguments, 3234When called without arguments,
3054it returns a reasonable date and time representation that depends on 3235it returns a reasonable date and time representation that depends on
3055the host system and on the current locale. 3236the host system and on the current locale.
@@ -3061,7 +3242,7 @@ used by the program, in seconds.
3061 3242
3062\subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit} 3243\subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit}
3063 3244
3064Calls the C function \verb|exit|, 3245Calls the C~function \verb|exit|,
3065with an optional \verb|code|, 3246with an optional \verb|code|,
3066to terminate the program. 3247to terminate the program.
3067The default value for \verb|code| is the success code. 3248The default value for \verb|code| is the success code.
@@ -3073,13 +3254,13 @@ or \nil\ if the variable is not defined.
3073 3254
3074\subsubsection*{\ff \T{execute (command)}}\Deffunc{execute} 3255\subsubsection*{\ff \T{execute (command)}}\Deffunc{execute}
3075 3256
3076This function is equivalent to the C function \verb|system|. 3257This function is equivalent to the C~function \verb|system|.
3077It passes \verb|command| to be executed by an operating system shell. 3258It passes \verb|command| to be executed by an operating system shell.
3078It returns a status code, which is system-dependent. 3259It returns a status code, which is system-dependent.
3079 3260
3080\subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} 3261\subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale}
3081 3262
3082This function is an interface to the ANSI C function \verb|setlocale|. 3263This function is an interface to the ANSI~C function \verb|setlocale|.
3083\verb|locale| is a string specifying a locale; 3264\verb|locale| is a string specifying a locale;
3084\verb|category| is an optional string describing which category to change: 3265\verb|category| is an optional string describing which category to change:
3085\verb|"all"|, \verb|"collate"|, \verb|"ctype"|, 3266\verb|"all"|, \verb|"collate"|, \verb|"ctype"|,
@@ -3089,7 +3270,7 @@ The function returns the name of the new locale,
3089or \nil\ if the request cannot be honored. 3270or \nil\ if the request cannot be honored.
3090 3271
3091 3272
3092\section{The Debugger Interface} \label{debugI} 3273\section{The Debug Interface} \label{debugI}
3093 3274
3094Lua has no built-in debugging facilities. 3275Lua has no built-in debugging facilities.
3095Instead, it offers a special interface, 3276Instead, it offers a special interface,
@@ -3097,7 +3278,8 @@ by means of functions and \emph{hooks},
3097which allows the construction of different 3278which allows the construction of different
3098kinds of debuggers, profilers, and other tools 3279kinds of debuggers, profilers, and other tools
3099that need ``inside information'' from the interpreter. 3280that need ``inside information'' from the interpreter.
3100This interface is declared in the header file \verb|luadebug.h|. 3281This interface is declared in the header file \verb|luadebug.h|,
3282and has \emph{no} single-state variant.
3101 3283
3102\subsection{Stack and Function Information} 3284\subsection{Stack and Function Information}
3103 3285
@@ -3106,23 +3288,24 @@ The main function to get information about the interpreter stack is
3106\begin{verbatim} 3288\begin{verbatim}
3107int lua_getstack (lua_State *L, int level, lua_Debug *ar); 3289int lua_getstack (lua_State *L, int level, lua_Debug *ar);
3108\end{verbatim} 3290\end{verbatim}
3109It fills parts of a structure (\verb|lua_Debug|) with 3291It fills parts of a \verb|lua_Debug| structure with
3110an identification of the \emph{activation record} 3292an identification of the \emph{activation record}
3111of the function executing at a given level. 3293of the function executing at a given level.
3112Level~0 is the current running function, 3294Level~0 is the current running function,
3113while level \Math{n+1} is the function that has called level \Math{n}. 3295whereas level \Math{n+1} is the function that has called level \Math{n}.
3114Usually, \verb|lua_getstack| returns 1; 3296Usually, \verb|lua_getstack| returns 1;
3115when called with a level greater than the stack depth, 3297when called with a level greater than the stack depth,
3116it returns 0. 3298it returns 0.
3117 3299
3118The structure \verb|lua_Debug| is used to carry different informations 3300\Deffunc{lua_Debug}
3119about an active function: \Deffunc{lua_Debug} 3301The structure \verb|lua_Debug| is used to carry different pieces of information
3302about an active function:
3120\begin{verbatim} 3303\begin{verbatim}
3121struct lua_Debug { 3304struct lua_Debug {
3122 const char *event; /* `call', `return' */ 3305 const char *event; /* "call", "return" */
3123 const char *source; /* (S) */ 3306 const char *source; /* (S) */
3124 int linedefined; /* (S) */ 3307 int linedefined; /* (S) */
3125 const char *what; /* (S) `Lua' function, `C' function, Lua `main' */ 3308 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */
3126 int currentline; /* (l) */ 3309 int currentline; /* (l) */
3127 const char *name; /* (n) */ 3310 const char *name; /* (n) */
3128 const char *namewhat; /* (n) global, tag method, local, field */ 3311 const char *namewhat; /* (n) global, tag method, local, field */
@@ -3135,15 +3318,18 @@ struct lua_Debug {
3135The \verb|lua_getstack| function fills only the private part 3318The \verb|lua_getstack| function fills only the private part
3136of this structure, for future use. 3319of this structure, for future use.
3137To fill in the other fields of \verb|lua_Debug| with useful information, 3320To fill in the other fields of \verb|lua_Debug| with useful information,
3138you call \Deffunc{lua_getinfo} 3321call \Deffunc{lua_getinfo}
3139\begin{verbatim} 3322\begin{verbatim}
3140int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); 3323int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
3141\end{verbatim} 3324\end{verbatim}
3142Each character in string \verb|what| selects some fields to be filled, 3325This function returns 0 on error
3143as indicated by the letter in parentheses in the structure definition; 3326(e.g., an invalid option in \verb|what|).
3327Each character in the string \verb|what|
3328selects some fields of \verb|ar| to be filled,
3329as indicated by the letter in parentheses in the definition of \verb|lua_Debug|;
3144that is, an \verb|S| fills the fields \verb|source| and \verb|linedefined|, 3330that is, an \verb|S| fills the fields \verb|source| and \verb|linedefined|,
3145and \verb|l| fills the field \verb|currentline|, etc. 3331and \verb|l| fills the field \verb|currentline|, etc.
3146Next we describe each field: 3332We describe each field below:
3147\begin{description} 3333\begin{description}
3148 3334
3149\item[source] 3335\item[source]
@@ -3156,7 +3342,7 @@ if the function was defined in a file,
3156the line number where starts the definition of the function. 3342the line number where starts the definition of the function.
3157 3343
3158\item[what] the string \verb|"Lua"| if this is a Lua function, 3344\item[what] the string \verb|"Lua"| if this is a Lua function,
3159\verb|"C"| if this is a C function, 3345\verb|"C"| if this is a C~function,
3160or \verb|"main"| if this is the main part of a chunk. 3346or \verb|"main"| if this is the main part of a chunk.
3161 3347
3162\item[currentline] 3348\item[currentline]
@@ -3175,11 +3361,11 @@ while others may be stored only in a table field.
3175The \verb|lua_getinfo| function checks whether the given 3361The \verb|lua_getinfo| function checks whether the given
3176function is a tag method or the value of a global variable. 3362function is a tag method or the value of a global variable.
3177If the given function is a tag method, 3363If the given function is a tag method,
3178\verb|name| points to the event name. 3364then \verb|name| points to the event name.
3179If the given function is the value of a global variable, 3365If the given function is the value of a global variable,
3180\verb|name| points to the variable name. 3366then \verb|name| points to the variable name.
3181If the given function is neither a tag method nor a global variable, 3367If the given function is neither a tag method nor a global variable,
3182\verb|name| is set to \verb|NULL|. 3368then \verb|name| is set to \verb|NULL|.
3183 3369
3184\item[namewhat] 3370\item[namewhat]
3185Explains the previous field. 3371Explains the previous field.
@@ -3190,8 +3376,8 @@ if the function is a tag method,
3190otherwise \verb|namewhat| is \verb|""| (the empty string). 3376otherwise \verb|namewhat| is \verb|""| (the empty string).
3191 3377
3192\item[nups] 3378\item[nups]
3193Number of upvalues of a C function. 3379Number of upvalues of a C~function.
3194If the function is not a C function, 3380If the function is not a C~function,
3195\verb|nups| is set to 0. 3381\verb|nups| is set to 0.
3196 3382
3197\item[func] 3383\item[func]
@@ -3206,6 +3392,10 @@ int lua_setdebug (lua_State *L, int debug);
3206\end{verbatim} 3392\end{verbatim}
3207This function sets the flag and returns its previous value. 3393This function sets the flag and returns its previous value.
3208This flag can also be set from Lua~\see{pragma}. 3394This flag can also be set from Lua~\see{pragma}.
3395Setting the flag using \verb|lua_setdebug| affects all chunks that are
3396compiled afterwards.
3397Individual functions may still control the generation of debug information
3398by using \verb|$debug| or \verb|$nodebug|.
3209 3399
3210\subsection{Manipulating Local Variables} 3400\subsection{Manipulating Local Variables}
3211 3401
@@ -3235,7 +3425,7 @@ int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
3235\end{verbatim} 3425\end{verbatim}
3236The parameter \verb|ar| must be a valid activation record, 3426The parameter \verb|ar| must be a valid activation record,
3237filled by a previous call to \verb|lua_getstack| or 3427filled by a previous call to \verb|lua_getstack| or
3238given as argument to a hook (see next section). 3428given as argument to a hook \see{sub-hooks}.
3239To use \verb|lua_getlocal|, 3429To use \verb|lua_getlocal|,
3240you fill the \verb|index| field of \verb|v| with the index 3430you fill the \verb|index| field of \verb|v| with the index
3241of a local variable; then the function fills the fields 3431of a local variable; then the function fills the fields
@@ -3256,7 +3446,7 @@ int listvars (lua_State *L, int level) {
3256 int i; 3446 int i;
3257 if (lua_getstack(L, level, &ar) == 0) 3447 if (lua_getstack(L, level, &ar) == 0)
3258 return 0; /* failure: no such level on the stack */ 3448 return 0; /* failure: no such level on the stack */
3259 for (i=1; ;i++) { 3449 for (i=1; ; i++) {
3260 lua_Localvar v; 3450 lua_Localvar v;
3261 v.index = i; 3451 v.index = i;
3262 if (lua_getlocal(L, &ar, &v) == 0) 3452 if (lua_getlocal(L, &ar, &v) == 0)
@@ -3267,7 +3457,7 @@ int listvars (lua_State *L, int level) {
3267\end{verbatim} 3457\end{verbatim}
3268 3458
3269 3459
3270\subsection{Hooks} 3460\subsection{Hooks}\label{sub-hooks}
3271 3461
3272The Lua interpreter offers two hooks for debugging purposes: 3462The Lua interpreter offers two hooks for debugging purposes:
3273a \emph{call} hook and a \emph{line} hook. 3463a \emph{call} hook and a \emph{line} hook.
@@ -3297,8 +3487,9 @@ local variables.
3297 3487
3298The line hook is called every time the interpreter changes 3488The line hook is called every time the interpreter changes
3299the line of code it is executing. 3489the line of code it is executing.
3300The \verb|currentline| field of \verb|ar| has the line number. 3490The \verb|event| field of \verb|ar| has the string \verb|"line"|,
3301Again, you can use this \verb|ar| in other calls to the API. 3491and the \verb|currentline| field has the line number.
3492Again, you can use this \verb|ar| in other calls to the debug API.
3302This hook is called only if the active function 3493This hook is called only if the active function
3303has been compiled with debug information~\see{pragma}. 3494has been compiled with debug information~\see{pragma}.
3304 3495
@@ -3313,10 +3504,10 @@ called by the hook, because those errors are protected;
3313the control returns to the hook anyway.) 3504the control returns to the hook anyway.)
3314 3505
3315 3506
3316\subsection{The Reflexive Debugger Interface} 3507\subsection{The Reflexive Debug Interface}
3317 3508
3318The library \verb|ldblib| provides 3509The library \verb|ldblib| provides
3319the functionality of the debugger interface to Lua programs. 3510the functionality of the debug interface to Lua programs.
3320If you want to use this library, 3511If you want to use this library,
3321your host application must open it, 3512your host application must open it,
3322by calling \verb|lua_dblibopen|. 3513by calling \verb|lua_dblibopen|.
@@ -3332,9 +3523,9 @@ As a general rule, if your program does not need this library,
3332do not open it. 3523do not open it.
3333 3524
3334 3525
3335\subsubsection*{\ff \T{getstack (level, what)}}\Deffunc{getstack} 3526\subsubsection*{\ff \T{getstack (level, [what])}}\Deffunc{getstack}
3336 3527
3337This function returns a table with informations about the function 3528This function returns a table with information about the function
3338running at level \verb|level| of the stack. 3529running at level \verb|level| of the stack.
3339Level 0 is the current function (\verb|getstack| itself); 3530Level 0 is the current function (\verb|getstack| itself);
3340level 1 is the function that called \verb|getstack|. 3531level 1 is the function that called \verb|getstack|.
@@ -3342,9 +3533,11 @@ If \verb|level| is larger than the number of active functions,
3342the function returns \nil. 3533the function returns \nil.
3343The table contains all the fields returned by \verb|lua_getinfo|, 3534The table contains all the fields returned by \verb|lua_getinfo|,
3344with the string \verb|what| describing what to get. 3535with the string \verb|what| describing what to get.
3536The default for \rerb|what| is to get all information available.
3345 3537
3346For instance, the expression \verb|getstack(1, 'n').name| returns 3538For instance, the expression \verb|getstack(1,"n").name| returns
3347the name of the current function. 3539the name of the current function,
3540if a reasonable name can be found.
3348 3541
3349 3542
3350\subsubsection*{\ff \T{getlocal (level, local)}}\Deffunc{getlocal} 3543\subsubsection*{\ff \T{getlocal (level, local)}}\Deffunc{getlocal}
@@ -3402,11 +3595,13 @@ the language is frequently used as a stand-alone interpreter.
3402An implementation of such an interpreter, 3595An implementation of such an interpreter,
3403called simply \verb|lua|, 3596called simply \verb|lua|,
3404is provided with the standard distribution. 3597is provided with the standard distribution.
3598
3405This program can be called with any sequence of the following arguments: 3599This program can be called with any sequence of the following arguments:
3406\begin{description} 3600\begin{description}
3407\item[\T{-}] executes \verb|stdin| as a file; 3601\item[\T{-}] executes \verb|stdin| as a file;
3602\item[\T{-c}] calls \verb|lua_close| after running all arguments;
3408\item[\T{-d}] turns on debug information; 3603\item[\T{-d}] turns on debug information;
3409\item[\T{-e stat}] executes string \verb|stat|; 3604\item[\T{-e} \rm\emph{stat}] executes string \verb|stat|;
3410\item[\T{-f filename}] executes file \verb|filename| with the 3605\item[\T{-f filename}] executes file \verb|filename| with the
3411remaining arguments in table \verb|arg|; 3606remaining arguments in table \verb|arg|;
3412\item[\T{-i}] enters interactive mode with prompt; 3607\item[\T{-i}] enters interactive mode with prompt;
@@ -3424,7 +3619,7 @@ For instance, an invocation like
3424\begin{verbatim} 3619\begin{verbatim}
3425$ lua -i a=test prog.lua 3620$ lua -i a=test prog.lua
3426\end{verbatim} 3621\end{verbatim}
3427will first interact with the user until an \verb|EOF|, 3622will first interact with the user until an \verb|EOF| in \verb|stdin|,
3428then will set \verb|a| to \verb|"test"|, 3623then will set \verb|a| to \verb|"test"|,
3429and finally will run the file \verb|prog.lua|. 3624and finally will run the file \verb|prog.lua|.
3430 3625
@@ -3443,19 +3638,21 @@ then creates a table \T{arg},
3443 arg = {"t1", "t3"; n = 2, [0] = "b.lua"} 3638 arg = {"t1", "t3"; n = 2, [0] = "b.lua"}
3444\end{verbatim} 3639\end{verbatim}
3445and then runs the file \T{b.lua}. 3640and then runs the file \T{b.lua}.
3641The stand-alone interpreter also provides a \verb|getarg| function that
3642can be used to access \emph{all} command line arguments.
3446 3643
3447In interactive mode, 3644In interactive mode,
3448a multi-line statement can be written finishing intermediate 3645a multi-line statement can be written finishing intermediate
3449lines with a backslash (\verb|\|). 3646lines with a backslash (\verb|\|).
3450If the global variable \verb|_PROMPT| is defined as a string, 3647If the global variable \verb|_PROMPT| is defined as a string,
3451its value is used as the prompt. \Index{_PROMPT} 3648its value is used as the prompt. \index{_PROMPT}
3452Therefore, the prompt can be changed like below: 3649Therefore, the prompt can be changed like below:
3453\begin{verbatim} 3650\begin{verbatim}
3454$ lua _PROMPT='myprompt> ' -i 3651$ lua _PROMPT='myprompt> ' -i
3455\end{verbatim} 3652\end{verbatim}
3456 3653
3457In Unix systems, Lua scripts can be made into executable programs 3654In Unix systems, Lua scripts can be made into executable programs
3458by using the \verb|#!| form, 3655by using \verb|chmod +x| and the~\verb|#!| form,
3459as in \verb|#!/usr/local/bin/lua|, 3656as in \verb|#!/usr/local/bin/lua|,
3460or \verb|#!/usr/local/bin/lua -f| to get other arguments. 3657or \verb|#!/usr/local/bin/lua -f| to get other arguments.
3461 3658
@@ -3470,7 +3667,6 @@ who found the name of the game.
3470Lua means \emph{moon} in Portuguese. 3667Lua means \emph{moon} in Portuguese.
3471 3668
3472 3669
3473
3474\appendix 3670\appendix
3475 3671
3476\section*{Incompatibilities with Previous Versions} 3672\section*{Incompatibilities with Previous Versions}
@@ -3482,12 +3678,154 @@ Here is a list of all these incompatibilities.
3482 3678
3483\subsection*{Incompatibilities with \Index{version 3.2}} 3679\subsection*{Incompatibilities with \Index{version 3.2}}
3484\begin{itemize} 3680\begin{itemize}
3485\item
3486 3681
3682\item
3683General read patterns are now deprecated.
3684\item
3685Garbage-collection tag methods for tables is now deprecated.
3686\item
3687\verb|setglobal|, \verb|rawsetglobal|, and \verb|sort| no longer return a value;
3688\verb|type| no longer return a second value.
3689\item
3690In nested function calls like \verb|f(g(x))|
3691\emph{all} return values from \verb|g| are passed as arguments to \verb|f|.
3692(This only happens when \verb|g| is the last
3693[or the only] argument to \verb|f|.)
3694\item
3695There is now only one tag method for order operators.
3696\item
3697The debug API has been completely rewritten.
3698\item
3699The pre-compiler may use the fact that some operators are associative,
3700for optimizations.
3701This may cause problems if these operators
3702have non-associative tag methods.
3703\item
3704All functions from the old API are now macros.
3705\item
3706A \verb|const| qualifier has been added to \verb|char *|
3707in all API functions that handle C~strings.
3708\item
3709\verb|luaL_openlib| no longer automatically calls \verb|lua_open|.
3710So,
3711you must now explicitly call \verb|lua_open| before opening
3712the standard libraries.
3713\item
3714\verb|lua_type| now returns a string describing the type,
3715and is no longer a synonym for \verb|lua_tag|.
3487\item Old pre-compiled code is obsolete, and must be re-compiled. 3716\item Old pre-compiled code is obsolete, and must be re-compiled.
3488 3717
3489\end{itemize} 3718\end{itemize}
3490 3719
3720%{===============================================================
3721\section*{The complete syntax of Lua}
3722
3723\renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent}
3724
3725\renewcommand{\OrNL}{\\ & \Or & }
3726
3727\begin{Produc}
3728
3729\produc{chunk}{\rep{stat} \opt{ret}}
3730
3731\produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}}
3732
3733\produc{label}{\ter{$\vert$} name \ter{$\vert$}}
3734
3735\produc{stat}{%
3736 varlist1 \ter{=} explist1
3737\OrNL functioncall
3738\OrNL \rwd{do} block \rwd{end}
3739\OrNL \rwd{while} exp1 \rwd{do} block \rwd{end}
3740\OrNL \rwd{repeat} block \rwd{until} exp1
3741\OrNL \rwd{if} exp1 \rwd{then} block
3742 \rep{\rwd{elseif} exp1 \rwd{then} block}
3743 \opt{\rwd{else} block} \rwd{end}
3744\OrNL \rwd{return} \opt{explist1}
3745\OrNL \rwd{break} \opt{name}
3746\OrNL \rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
3747 \rwd{do} block \rwd{end}
3748\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
3749\OrNL \rwd{local} declist \opt{init}
3750}
3751
3752\produc{var}{%
3753 name
3754\OrNL simpleexp \ter{[} exp1 \ter{]}
3755\OrNL simpleexp \ter{.} name
3756}
3757
3758\produc{varlist1}{var \rep{\ter{,} var}}
3759
3760\produc{declist}{name \rep{\ter{,} name}}
3761
3762\produc{init}{\ter{=} explist1}
3763
3764\produc{exp}{%
3765 \rwd{nil}
3766\Or number
3767\Or literal
3768\Or function
3769\Or simpleexp
3770\Or \ter{(} exp \ter{)}
3771}
3772
3773\produc{exp1}{exp}
3774
3775\produc{explist1}{\rep{exp1 \ter{,}} exp}
3776
3777\produc{simpleexp}{%
3778 var
3779\Or upvalue
3780\Or functioncall
3781\Or tableconstructor
3782}
3783
3784\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
3785\produc{fieldlist}{%
3786 lfieldlist
3787\Or ffieldlist
3788\Or lfieldlist \ter{;} ffieldlist
3789\Or ffieldlist \ter{;} lfieldlist
3790}
3791\produc{lfieldlist}{\opt{lfieldlist1}}
3792\produc{ffieldlist}{\opt{ffieldlist1}}
3793\produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}}
3794\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
3795\produc{ffield}{%
3796 \ter{[} exp \ter{]} \ter{=} exp
3797\Or name \ter{=} exp
3798}
3799
3800\produc{functioncall}{%
3801 simpleexp args
3802\Or simpleexp \ter{:} name args
3803}
3804
3805\produc{args}{%
3806 \ter{(} \opt{explist1} \ter{)}
3807\Or tableconstructor
3808\Or \ter{literal}
3809}
3810
3811\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
3812
3813\produc{funcname}{%
3814 name
3815\OrNL name \ter{.} name
3816\OrNL name \ter{:} name
3817}
3818
3819\produc{parlist1}{%
3820 \ter{\ldots}
3821\Or name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}
3822}
3823
3824\produc{upvalue}{\ter{\%} name}
3825
3826\end{Produc}
3827%}===============================================================
3828
3491% restore underscore to usual meaning 3829% restore underscore to usual meaning
3492\catcode`\_=8 3830\catcode`\_=8
3493 3831
@@ -3498,5 +3836,3 @@ Here is a list of all these incompatibilities.
3498 3836
3499 3837
3500\end{document} 3838\end{document}
3501
3502