summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2001-09-24 12:54:36 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2001-09-24 12:54:36 -0300
commitc44c68450a636647caea90872582e03a30bfb6e4 (patch)
tree25264a98945539eaf5b3972ab54f3b2b65783d44
parentabdbe883a86bbc7fbf1d1bfc50756e1b42fc45b5 (diff)
downloadlua-c44c68450a636647caea90872582e03a30bfb6e4.tar.gz
lua-c44c68450a636647caea90872582e03a30bfb6e4.tar.bz2
lua-c44c68450a636647caea90872582e03a30bfb6e4.zip
changes by lhf
-rw-r--r--manual.tex1808
1 files changed, 1010 insertions, 798 deletions
diff --git a/manual.tex b/manual.tex
index 22d6393e..3bc18b07 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,21 +1,24 @@
1% $Id: manual.tex,v 1.50 2001/07/19 13:36:18 roberto Exp roberto $ 1% $Id: manual.tex,v 1.51 2001/07/24 17:25:03 roberto Exp roberto $
2 2
3\documentclass[11pt]{article} 3\documentclass[11pt,twoside,draft]{article}
4\usepackage{fullpage} 4\usepackage{fullpage}
5\usepackage{bnf} 5\usepackage{bnf}
6\usepackage{graphicx} 6\usepackage{graphicx}
7%\usepackage{times}
8 7
8% no need for subscripts...
9\catcode`\_=12 9\catcode`\_=12
10 10
11%\newcommand{\See}[1]{Section~\ref{#1}} 11%\newcommand{\See}[1]{Section~\ref{#1}}
12\newcommand{\See}[1]{\S\ref{#1}} 12\newcommand{\See}[1]{\S\ref{#1}}
13%\newcommand{\see}[1]{(see~\See{#1} on page \pageref{#1})}
13\newcommand{\see}[1]{(see~\See{#1})} 14\newcommand{\see}[1]{(see~\See{#1})}
15\newcommand{\seepage}[1]{(see page~\pageref{#1})}
14\newcommand{\M}[1]{{\rm\emph{#1}}} 16\newcommand{\M}[1]{{\rm\emph{#1}}}
15\newcommand{\T}[1]{{\tt #1}} 17\newcommand{\T}[1]{{\tt #1}}
16\newcommand{\Math}[1]{$#1$} 18\newcommand{\Math}[1]{$#1$}
17\newcommand{\nil}{{\bf nil}} 19\newcommand{\nil}{{\bf nil}}
18\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} 20%\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
21\def\tecgraf{{\sf TeCGraf}}
19 22
20\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}} 23\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}}
21\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}} 24\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}}
@@ -26,12 +29,16 @@
26\newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}} 29\newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}}
27\newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}} 30\newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}}
28\newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}} 31\newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}}
32\newcommand{\IndexKW}[1]{\index{keywords!#1@{\tt #1}}}
29 33
30\newcommand{\ff}{$\bullet$\ } 34\newcommand{\ff}{$\bullet$\ }
31 35
32\newcommand{\Version}{4.1 (alpha)} 36\newcommand{\Version}{4.1 (alpha)}
33 37
34% LHF 38% changes to bnf.sty by LHF
39\renewcommand{\Or}{$|$ }
40\renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}}
41\renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}}
35\renewcommand{\ter}[1]{{\rm`{\tt#1}'}} 42\renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
36\newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } 43\newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: }
37 44
@@ -67,16 +74,16 @@ Last revised on \today
67\newpage 74\newpage
68\begin{quotation} 75\begin{quotation}
69\parskip=10pt 76\parskip=10pt
77\parindent=0pt
70\footnotesize 78\footnotesize
71\null\vfill 79\null\vfill
72 80
73\noindent 81\noindent
74Copyright \copyright\ 1994--2001 TeCGraf, PUC-Rio. All rights reserved. 82Copyright \copyright\ 1994--2001 TeCGraf, PUC-Rio. All rights reserved.
75 83
76\noindent
77Permission is hereby granted, without written agreement and without license 84Permission is hereby granted, without written agreement and without license
78or royalty fees, to use, copy, modify, translate, and distribute 85or royalty fees, to use, copy, modify, translate, and distribute
79this software and its documentation (hereby called the "package") 86this software and its documentation (hereby called the ``package'')
80for any purpose, including commercial applications, subject to 87for any purpose, including commercial applications, subject to
81the following conditions: 88the following conditions:
82\begin{itemize} 89\begin{itemize}
@@ -93,27 +100,24 @@ the following conditions:
93\end{itemize} 100\end{itemize}
94The authors specifically disclaim any warranties, including, but not limited 101The authors specifically disclaim any warranties, including, but not limited
95to, the implied warranties of merchantability and fitness for a particular 102to, the implied warranties of merchantability and fitness for a particular
96purpose. The package provided hereunder is on an ``as is'' basis, and the 103purpose. The package provided hereunder is on an ``as~is'' basis, and the
97authors have no obligation to provide maintenance, support, updates, 104authors have no obligation to provide maintenance, support, updates,
98enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the 105enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the
99authors be held liable to any party for direct, indirect, special, 106authors be held liable to any party for direct, indirect, special,
100incidental, or consequential damages arising out of the use of this package 107incidental, or consequential damages arising out of the use of this package
101and its documentation. 108and its documentation.
102 109
103\noindent
104The Lua language and this implementation have been entirely designed and 110The Lua language and this implementation have been entirely designed and
105written by Waldemar Celes, Roberto Ierusalimschy, and Luiz Henrique de 111written by Waldemar Celes, Roberto Ierusalimschy, and Luiz Henrique de
106Figueiredo at TeCGraf, PUC-Rio in Brazil. 112Figueiredo at TeCGraf, PUC-Rio in Brazil.
107 113
108\noindent
109This implementation contains no third-party code. 114This implementation contains no third-party code.
110 115
111\noindent
112Copies of this manual can be obtained at 116Copies of this manual can be obtained at
113\verb|http://www.lua.org|. 117Lua's official web site,
118\verb|www.lua.org|.
114 119
115\bigskip 120\bigskip
116\noindent
117The Lua logo was designed by A. Nakonechny. 121The Lua logo was designed by A. Nakonechny.
118Copyright \copyright\ 1998. All rights reserved. 122Copyright \copyright\ 1998. All rights reserved.
119\end{quotation} 123\end{quotation}
@@ -123,8 +127,8 @@ Copyright \copyright\ 1998. All rights reserved.
123\title{\Large\bf Reference Manual of the Programming Language Lua \Version} 127\title{\Large\bf Reference Manual of the Programming Language Lua \Version}
124 128
125\author{% 129\author{%
126Roberto Ierusalimschy\quad 130Roberto Ierusalimschy\qquad
127Luiz Henrique de Figueiredo\quad 131Luiz Henrique de Figueiredo\qquad
128Waldemar Celes 132Waldemar Celes
129\vspace{1.0ex}\\ 133\vspace{1.0ex}\\
130\smallskip 134\smallskip
@@ -134,7 +138,7 @@ Waldemar Celes
134\tecgraf\ --- Computer Science Department --- PUC-Rio 138\tecgraf\ --- Computer Science Department --- PUC-Rio
135} 139}
136 140
137\date{{\small \tt\$Date: 2001/07/19 13:36:18 $ $}} 141%\date{{\small \tt\$Date: 2001/07/24 17:25:03 $ $}}
138 142
139\maketitle 143\maketitle
140 144
@@ -202,7 +206,7 @@ a intera\c{c}\~ao entre programas Lua e programas C~hospedeiros.
202\pagestyle{plain} 206\pagestyle{plain}
203\pagenumbering{arabic} 207\pagenumbering{arabic}
204 208
205 209%------------------------------------------------------------------------------
206\section{Introduction} 210\section{Introduction}
207 211
208Lua is an extension programming language designed to support 212Lua is an extension programming language designed to support
@@ -210,33 +214,29 @@ general procedural programming with data description
210facilities. 214facilities.
211Lua is intended to be used as a powerful, light-weight 215Lua is intended to be used as a powerful, light-weight
212configuration language for any program that needs one. 216configuration language for any program that needs one.
213
214Lua is implemented as a library, written in C. 217Lua is implemented as a library, written in C.
218
215Being an extension language, Lua has no notion of a ``main'' program: 219Being an extension language, Lua has no notion of a ``main'' program:
216it only works \emph{embedded} in a host client, 220it only works \emph{embedded} in a host client,
217called the \emph{embedding} program. 221called the \emph{embedding program} or simply the \emph{host}.
218This host program can invoke functions to execute a piece of 222This host program can invoke functions to execute a piece of Lua code,
219code in Lua, can write and read Lua variables, 223can write and read Lua variables,
220and can register C~functions to be called by Lua code. 224and can register C~functions to be called by Lua code.
221Through the use of C~functions, Lua can be augmented to cope with 225Through the use of C~functions, Lua can be augmented to cope with
222a wide range of different domains, 226a wide range of different domains,
223thus creating customized programming languages sharing a syntactical framework. 227thus creating customized programming languages sharing a syntactical framework.
224 228
225Lua is free-distribution software, 229Lua is free software,
226and is provided as usual with no guarantees, 230and is provided as usual with no guarantees,
227as stated in its copyright notice. 231as stated in its copyright notice.
228The implementation described in this manual is available 232The implementation described in this manual is available
229at the following URL's: 233at Lua's official web site, \verb|www.lua.org|.
230\begin{verbatim}
231 http://www.lua.org
232 ftp://ftp.lua.org
233\end{verbatim}
234 234
235Like any other reference manual, 235Like any other reference manual,
236this document is dry in places. 236this document is dry in places.
237For a discussion of the decisions behind the design of Lua, 237For a discussion of the decisions behind the design of Lua,
238see the papers below, 238see the papers below,
239which are available at the web site above. 239which are available at Lua's web site.
240\begin{itemize} 240\begin{itemize}
241\item 241\item
242R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes. 242R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes.
@@ -250,14 +250,29 @@ The design and implementation of a language for extending applications.
250L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes. 250L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes.
251Lua: an extensible embedded language. 251Lua: an extensible embedded language.
252\emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33. 252\emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33.
253\item
254R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes.
255The evolution of an extension language: a history of Lua,
256\emph{Proceedings of V Brazilian Symposium on Programming Languages} (2001) B-14--B-28.
253\end{itemize} 257\end{itemize}
254 258
255\section{Environment and Chunks} 259%------------------------------------------------------------------------------
260\section{Lua Concepts}\label{concepts}
261
262This section describes the main concepts of Lua as a language.
263The syntax and semantics of Lua are described in \See{language}.
264The discussion below is not purely conceptual;
265it includes references to the C~API \see{API},
266because Lua is designed to be embedded in host programs.
267It also includes references to the standard libraries \see{libraries}.
268
269
270\subsection{Environment and Chunks}
256 271
257All statements in Lua are executed in a \Def{global environment}. 272All statements in Lua are executed in a \Def{global environment}.
258This environment is initialized with a call from the embedding program to 273This environment is initialized with a call from the embedding program to
259\verb|lua_open| and 274\verb|lua_open| and
260persists until a call to \verb|lua_close|, 275persists until a call to \verb|lua_close|
261or the end of the embedding program. 276or the end of the embedding program.
262If necessary, 277If necessary,
263the host programmer can create multiple independent global 278the host programmer can create multiple independent global
@@ -266,34 +281,17 @@ environments, and freely switch between them \see{mangstate}.
266The global environment can be manipulated by Lua code or 281The global environment can be manipulated by Lua code or
267by the embedding program, 282by the embedding program,
268which can read and write global variables 283which can read and write global variables
269using API functions from the library that implements Lua. 284using the API functions from the library that implements Lua.
270
271\Index{Global variables} in Lua do not need to be declared.
272Any variable is assumed to be global unless explicitly declared local
273\see{localvar}.
274Before the first assignment, the value of a global variable is \nil\ %
275(this default can be changed; see \See{tag-method}).
276A table is used to keep all global names and values
277(tables are explained in \See{TypesSec}).
278 285
279The unit of execution of Lua is called a \Def{chunk}. 286The unit of execution of Lua is called a \Def{chunk}.
280A chunk is simply a sequence of statements, 287A chunk is simply a sequence of statements,
281which are executed sequentially. 288which are executed sequentially.
282Each statement can be optionally followed by a semicolon:
283\begin{Produc}
284\produc{chunk}{\rep{stat \opt{\ter{;}}}}
285\end{Produc}%
286Statements are described in \See{stats}. 289Statements are described in \See{stats}.
287(The notation above is the usual extended BNF,
288in which
289\rep{\emph{a}} means 0 or more \emph{a}'s,
290\opt{\emph{a}} means an optional \emph{a}, and
291\oneormore{\emph{a}} means one or more \emph{a}'s.
292The complete syntax of Lua is given on page~\pageref{BNF}.)
293 290
294A chunk may be stored in a file or in a string inside the host program. 291A chunk may be stored in a file or in a string inside the host program.
295When a chunk is executed, first it is pre-compiled into bytecodes for 292When a chunk is executed, first it is pre-compiled into bytecodes for
296a virtual machine, and then the statements are executed in sequential order, 293a virtual machine,
294and then the compiled statements are executed in sequential order,
297by simulating the virtual machine. 295by simulating the virtual machine.
298All modifications a chunk effects on the global environment persist 296All modifications a chunk effects on the global environment persist
299after the chunk ends. 297after the chunk ends.
@@ -301,38 +299,39 @@ after the chunk ends.
301Chunks may also be pre-compiled into binary form and stored in files; 299Chunks may also be pre-compiled into binary form and stored in files;
302see program \IndexVerb{luac} for details. 300see program \IndexVerb{luac} for details.
303Text files with chunks and their binary pre-compiled forms 301Text files with chunks and their binary pre-compiled forms
304are interchangeable. 302are interchangeable;
305Lua automatically detects the file type and acts accordingly. 303Lua automatically detects the file type and acts accordingly.
306\index{pre-compilation} 304\index{pre-compilation}
307 305
308 306
309\section{\Index{Types and Tags}} \label{TypesSec} 307\subsection{\Index{Values and Types}} \label{TypesSec}
310 308
311Lua is a \emph{dynamically typed language}. 309Lua is a \emph{dynamically typed language}.
312This means that 310This means that
313variables do not have types; only values do. 311variables do not have types; only values do.
314Therefore, there are no type definitions in the language. 312Therefore, there are no type definitions in the language.
315All values carry their own type. 313All values carry their own type.
316Besides a type, all values also have a \IndexEmph{tag}. 314Besides a type, all values also have a tag \see{tags}.
317 315
318There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, 316There are six \Index{basic types} in Lua: \Def{nil}, \Def{number},
319\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. 317\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}.
320\emph{Nil} is the type of the value \nil, 318\emph{Nil} is the type of the value \nil,
321whose main property is to be different from any other value. 319whose main property is to be different from any other value.
322\emph{Number} represents real (double-precision floating-point) numbers, 320\emph{Number} represents real
323while \emph{string} has the usual meaning. 321%(double-precision floating-point)
322numbers.
323\emph{String} represents arrays of characters.
324\index{eight-bit clean} 324\index{eight-bit clean}
325Lua is 8-bit clean, 325Lua is 8-bit clean,
326and so strings may contain any 8-bit character, 326and so strings may contain any 8-bit character,
327including embedded zeros (\verb|'\0'|) \see{lexical}. 327including embedded zeros (\verb|'\0'|) \see{lexical}.
328The \verb|type| function returns a string describing the type
329of a given value \see{pdf-type}.
330 328
331Functions are considered \emph{first-class values} in Lua. 329Functions are considered \emph{first-class values} in Lua.
332This means that functions can be stored in variables, 330This means that functions can be stored in variables,
333passed as arguments to other functions, and returned as results. 331passed as arguments to other functions, and returned as results.
334Lua can call (and manipulate) functions written in Lua and 332Lua can call (and manipulate) functions written in Lua and
335functions written in C. 333functions written in C
334\see{functioncall}.
336 335
337The type \emph{userdata} is provided to allow 336The type \emph{userdata} is provided to allow
338arbitrary \Index{C~pointers} to be stored in Lua variables. 337arbitrary \Index{C~pointers} to be stored in Lua variables.
@@ -340,135 +339,198 @@ This type corresponds to a \verb|void*|
340and has no pre-defined operations in Lua, 339and has no pre-defined operations in Lua,
341except assignment and equality test. 340except assignment and equality test.
342However, by using \emph{tag methods}, 341However, by using \emph{tag methods},
343the programmer can define operations for \emph{userdata} values 342the programmer can define operations for userdata values
344\see{tag-method}. 343\see{tag-method}.
344Userdata values cannot be created or modified in Lua,
345only through the C~API.
346This guarantees the integrity of data owned by the host program.
345 347
346The type \emph{table} implements \Index{associative arrays}, 348The type \emph{table} implements \Index{associative arrays},
347that is, \Index{arrays} that can be indexed not only with numbers, 349that is, \Index{arrays} that can be indexed not only with numbers,
348but with any value (except \nil). 350but with any value (except \nil).
349Therefore, this type may be used not only to represent ordinary arrays, 351Moreover,
352tables are \emph{heterogeneous},
353that is, they can contain values of all types.
354Tables are the main data structuring mechanism in Lua;
355they may be used not only to represent ordinary arrays,
350but also symbol tables, sets, records, graphs, trees, etc. 356but also symbol tables, sets, records, graphs, trees, etc.
351Tables are the main data structuring mechanism in Lua.
352To represent \Index{records}, Lua uses the field name as an index. 357To represent \Index{records}, Lua uses the field name as an index.
353The language supports this representation by 358The language supports this representation by
354providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. 359providing \verb|a.name| as syntactic sugar for \verb|a["name"]|.
355Tables may also carry \emph{methods}: 360There are several convenient ways to create tables in Lua
356Because functions are first class values, 361\see{tableconstructor}.
362
363Like indices, the value of a table field can be of any type.
364In particular,
365because functions are first class values,
357table fields may contain functions. 366table fields may contain functions.
367So, tables may also carry \emph{methods}.
358The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, 368The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
359which calls the method \verb|f| from the table \verb|t| passing 369which calls the method \verb|f| from the table \verb|t| passing
360the table itself as the first parameter \see{func-def}. 370the table itself as the first parameter \see{func-def}.
361 371
362Note that tables are \emph{objects}, and not values. 372Strings, tables, functions, and userdata values are \emph{objects}:
363Variables do not contain tables, only \emph{references} to them. 373variables do not actually \emph{contain} these values,
364Assignment, parameter passing, and returns always manipulate references 374only \emph{references} to them.
365to tables, and do not imply any kind of copy. 375Assignment, parameter passing, and returns from functions
366Moreover, tables must be explicitly created before used 376always manipulate references to these values, and do not imply any kind of copy.
367\see{tableconstructor}.
368 377
378The library function \verb|type| returns a string describing the type
379of a given value \see{pdf-type}.
380
381
382\subsection{\Index{Coercion}} \label{coercion}
383
384Lua provides automatic conversion between string and number values at run time.
385Any arithmetic operation applied to a string tries to convert
386that string to a number, following the usual rules.
387Conversely, whenever a number is used when a string is expected,
388the number is converted to a string, in a reasonable format.
389The format is chosen so that
390a conversion from number to string then back to number
391reproduces the original number \emph{exactly}.
392The conversion does not necessarily produces nice-looking text for some numbers.
393For complete control of how numbers are converted to strings,
394use the \verb|format| function \see{format}.
395
396
397\subsection{Variables}
398
399There are two kinds of variables in Lua:
400global variables
401and local variables.
402\Index{Global variables} do not need to be declared.
403Variables are assumed to be global unless explicitly declared local
404\see{localvar}.
405Before the first assignment, the value of a variable is \nil\ %
406(this default can be changed for global variables; see \See{tag-method}).
369 407
370\subsection{Tags} 408An ordinary Lua table is used to keep all global names and values.
409This table can be accessed and changed with the \verb|globals| function
410\see{pdf-globals}.
411
412
413\subsection{Tags}\label{tags}
371 414
372Each type has a \emph{name}, 415Each type has a \emph{name},
373and a numerical identifier, 416which is a string,
374called a \Index{tag}. 417and a \IndexEmph{tag},
375Tags are mainly used by C code, 418which is an integer.
419Tags are mainly used by C~code,
376to avoid the manipulation of strings. 420to avoid the manipulation of strings.
377Most operations over types, in the C API, 421In the C~API,
378require a tag to identify the type. 422most operations over types require a tag to identify the type.
379In Lua, all operations over types work 423In Lua, all operations over types work transparently
380both with type names or tags. 424with both type names and tags.
425The \verb|tag| function returns the tag of a given value \see{pdf-tag}.
381 426
382 427
383\subsection{User-defined Types} 428\subsection{User-defined Types}
384 429
385Lua programs can create new types, 430Lua programs can create new types,
386called \Index{User-defined Types}. 431called \IndexEmph{user-defined types}.
387A user-defined type is always based on a base type, 432A user-defined type is always based on a base type,
388either a table or a userdata. 433which can be either table or userdata.
389Objects of an extended type have an internal structure 434Objects of a user-defined type have an internal structure
390identical to the corresponding base type, 435identical to the corresponding base type,
391but may have diferent semantics for each operation. 436but the programmer may define different semantics for each operation on them
437\see{tag-method}.
392 438
393The \verb|newtype| function creates a new type \see{pdf-newtype}. 439The \verb|newtype| function creates a new type \see{pdf-newtype}
394Types created by Lua programs are always based upon tables; 440with a name selected by the programmer.
395types created by C can be based upon tables or upon userdata. 441Types created by Lua programs are always based on tables;
442types created in~C can be based on tables or on userdata.
396The \verb|settagmethod| function defines new semantics for 443The \verb|settagmethod| function defines new semantics for
397the operations of this new type \see{tag-method}. 444the operations of this new type \see{tag-method}.
398The \verb|settype| function changes the type of a given object 445The \verb|settype| function changes the type of a given object
399\see{pdf-settype}. 446\see{pdf-settype}.
400 447
401 448
402\section{Garbage Collection}\label{GC} 449\subsection{Garbage Collection}\label{GC}
403 450
404Lua does automatic memory management. 451Lua does automatic memory management.
405To do that, 452This means that
406Lua runs a \Index{garbage collector} from time to time. 453you do not have to worry about allocating memory for new objects
407All objects in Lua are subjected to automatic management: 454and freeing it when the objects are no longer needed.
455Lua manages memory automatically by running
456a \Index{garbage collector} from time to time
457and
458collecting all ``dead'' objects
459(essentially, all objects that are no longer accessible from Lua
460as the value of a global variable or table field).
461All objects in Lua are subject to automatic management:
408tables, userdata, functions, and strings. 462tables, userdata, functions, and strings.
409 463
464Using the C~API,
465you can set garbage-collector tag methods for user-defined
466types based on userdata \see{tag-method}.
467Lua calls those functions when it is about to free a userdata
468of the corresponding type.
469Using this facility, you can coordinate Lua's garbage collection
470with external resource management
471(such as closing files, network or database connections,
472or freeing your own memory).
473
410Lua uses two numbers to control its garbage-collection cycles. 474Lua uses two numbers to control its garbage-collection cycles.
411One number counts how many bytes of dynamic memory Lua is using, 475One number counts how many bytes of dynamic memory Lua is using,
412and the other is a threshold. 476and the other is a threshold.
413When the number of bytes crosses the threshold, 477When the number of bytes crosses the threshold,
414Lua runs the garbage collector, 478Lua runs the garbage collector,
415which reclaims the memory of all ``dead'' objects 479which reclaims the memory of all ``dead'' objects.
416(that is, objects no longer accessible from Lua).
417The byte counter is corrected, 480The byte counter is corrected,
418and then the threshold is reset to twice the value of the byte counter. 481and then the threshold is reset to twice the value of the byte counter.
419 482
420Through the C API, you can consult those numbers, 483Through the C~API, you can query those numbers,
421and change the threshold \see{GC-API}. 484and change the threshold \see{GC-API}.
422Setting the threshold to zero actually forces an immediate 485Setting the threshold to zero actually forces an immediate
423garbage-collection cycle, 486garbage-collection cycle,
424while setting it to a huge number stops the garbage collector. 487while setting it to a huge number effectively stops the garbage collector.
425Using Lua code you have a more limited control of memory management, 488Using Lua code you have a more limited control over garbage-collection cycles,
426through functions \verb|gcinfo| and \verb|collectgarbage|. 489through the functions \verb|gcinfo| and \verb|collectgarbage|
427 490\see{predefined}.
428
429You can set garbage-collector tag methods for user-defined
430types based on userdata \see{tag-method}.
431Lua calls those functions when it is about to free a userdata
432of the corresponding type.
433Using this facility, you can coordinate Lua's garbage collection
434with external resourse management
435(such as closing files or freeing your own memory).
436 491
437 492
438\subsection{Weak Tables}\label{weak-table} 493\subsection{Weak Tables}\label{weak-table}
439 494
440A \IndexEmph{weak table} is a table whose elements are 495A \IndexEmph{weak table} is a table whose elements are
441\IndexEmph{weak references}. 496\IndexEmph{weak references}.
442A weak reference is ignored by the garbage collector, 497A weak reference is ignored by the garbage collector.
443so that if the only references to an object are weak references, 498In other words,
444the garbage collector will collect that object. 499if the only references to an object are weak references,
500then the garbage collector will collect that object.
445 501
446A weak table can have weak keys, weak values, or both. 502A weak table can have weak keys, weak values, or both.
447A table with weak keys allows the collection of its keys, 503A table with weak keys allows the collection of its keys,
448but avoids the collection of its values. 504but prevents the collection of its values.
449A table with both weak keys and weak values allow the collection of both. 505A table with both weak keys and weak values allows the collection of
506both keys and values
450In any case, if either the key or the value is collected, 507In any case, if either the key or the value is collected,
451the whole pair is removed from the table. 508the whole pair is removed from the table.
452The weakness of a table is controled by the 509The weakness of a table is controled by the
453function \verb|weakmode| \see{weakmode}. 510\verb|weakmode| function \see{weakmode}.
454 511
455 512
456\section{The Language} 513%------------------------------------------------------------------------------
514\section{The Language}\label{language}
457 515
458This section describes the lexis, the syntax, and the semantics of Lua. 516This section describes the lexis, the syntax, and the semantics of Lua.
459 517In other words,
518this section describes
519which tokens are valid,
520how they can be combined,
521and what their combinations mean.
460 522
461\subsection{Lexical Conventions} \label{lexical} 523\subsection{Lexical Conventions} \label{lexical}
462 524
463\IndexEmph{Identifiers} in Lua can be any string of letters, 525\IndexEmph{Identifiers} in Lua can be any string of letters,
464digits, and underscores, 526digits, and underscores,
465not beginning with a digit. 527not beginning with a digit.
466This coincides with the definition of identifiers in most languages, 528This coincides with the definition of identifiers in most languages.
467except that 529(The definition of letter depends on the current locale:
468the definition of letter depends on the current locale: 530any character considered alphabetic by the current locale
469Any character considered alphabetic by the current locale 531can be used in an identifier.)
470can be used in an identifier. 532
471The following words are \emph{reserved}, 533The following \IndexEmph{keywords} are reserved,
472and cannot be used as identifiers: 534and cannot be used as identifiers:
473\index{reserved words} 535\index{reserved words}
474\begin{verbatim} 536\begin{verbatim}
@@ -477,21 +539,25 @@ and cannot be used as identifiers:
477 in local nil not or 539 in local nil not or
478 repeat return then until while 540 repeat return then until while
479\end{verbatim} 541\end{verbatim}
480(\rwd{global} is reserved for future use.) 542(The keyword \rwd{global} is reserved for future use.)
543%\IndexKW{and}\IndexKW{break}\IndexKW{do}\IndexKW{else}\IndexKW{elseif}
544%\IndexKW{end}\IndexKW{for}\IndexKW{function}\IndexKW{global}\IndexKW{if}
545%\IndexKW{in}\IndexKW{local}\IndexKW{nil}\IndexKW{not}\IndexKW{or}
546%\IndexKW{repeat}\IndexKW{return}\IndexKW{then}\IndexKW{until}\IndexKW{while}
481 547
482Lua is a case-sensitive language: 548Lua is a case-sensitive language:
483\T{and} is a reserved word, but \T{And} and \T{\'and} 549\T{and} is a reserved word, but \T{And} and \T{\'and}
484(if the locale permits) are two different, valid identifiers. 550(if the locale permits) are two different, valid identifiers.
485As a convention, identifiers starting with underscore followed by 551As a convention, identifiers starting with an underscore followed by
486uppercase letters (such as \verb|_INPUT|) 552uppercase letters (such as \verb|_INPUT|)
487are reserved for internal variables. 553are reserved for internal variables.
488 554
489The following strings denote other \Index{tokens}: 555The following strings denote other \Index{tokens}:
490\begin{verbatim} 556\begin{verbatim}
491 + - * / ^ % 557 + - * / ^ %
492 ~= <= >= < > == = 558 ~= <= >= < > == =
493 ( ) { } [ ] 559 ( ) { } [ ]
494 ; : , . .. ... 560 ; : , . .. ...
495\end{verbatim} 561\end{verbatim}
496 562
497\IndexEmph{Literal strings} 563\IndexEmph{Literal strings}
@@ -515,17 +581,20 @@ where \emph{ddd} is a sequence of up to three \emph{decimal} digits.
515Strings in Lua may contain any 8-bit value, including embedded zeros, 581Strings in Lua may contain any 8-bit value, including embedded zeros,
516which can be specified as `\verb|\000|'. 582which can be specified as `\verb|\000|'.
517 583
518Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|. 584Literal strings can also be delimited by matching \verb|[[| $\ldots$ \verb|]]|.
519Literals in this bracketed form may run for several lines, 585Literals in this bracketed form may run for several lines,
520may contain nested \verb|[[| \dots\ \verb|]]| pairs, 586may contain nested \verb|[[| $\ldots$ \verb|]]| pairs,
521and do not interpret escape sequences. 587and do not interpret escape sequences.
522When the \verb|[[| is immediatly followed by a newline, 588For convenience,
589when the opening \verb|[[| is immediately followed by a newline,
523this newline is not included in the string. 590this newline is not included in the string.
524This form is specially convenient for 591This form is specially convenient for
525writing strings that contain program pieces or 592writing strings that contain program pieces or
526other quoted strings. 593other quoted strings.
527As an example, in a system using ASCII, 594As an example, in a system using ASCII
528the following three literals are equivalent: 595(in which
596`\verb|a|' is coded as~97, newline is coded as~10, and `\verb|1|' is coded as~49),
597the following four literals below are equivalent:
529\begin{verbatim} 598\begin{verbatim}
530 1) "alo\n123\"" 599 1) "alo\n123\""
531 2) '\97lo\10\04923"' 600 2) '\97lo\10\04923"'
@@ -536,13 +605,6 @@ the following three literals are equivalent:
536 123"]] 605 123"]]
537\end{verbatim} 606\end{verbatim}
538 607
539\IndexEmph{Comments} start anywhere outside a string with a
540double hyphen (\verb|--|) and run until the end of the line.
541Moreover,
542the first line of a chunk is skipped if it starts with \verb|#|.
543This facility allows the use of Lua as a script interpreter
544in Unix systems \see{lua-sa}.
545
546\IndexEmph{Numerical constants} may be written with an optional decimal part 608\IndexEmph{Numerical constants} may be written with an optional decimal part
547and an optional decimal exponent. 609and an optional decimal exponent.
548Examples of valid numerical constants are 610Examples of valid numerical constants are
@@ -550,21 +612,57 @@ Examples of valid numerical constants are
550 3 3.0 3.1416 314.16e-2 0.31416E1 612 3 3.0 3.1416 314.16e-2 0.31416E1
551\end{verbatim} 613\end{verbatim}
552 614
553\subsection{\Index{Coercion}} \label{coercion} 615\IndexEmph{Comments} start anywhere outside a string with a
616double hyphen (\verb|--|) and run until the end of the line.
617(There are no block comments in Lua.)
618For convenience,
619the first line of a chunk is skipped if it starts with \verb|#|.
620This facility allows the use of Lua as a script interpreter
621in Unix systems \see{lua-sa}.
554 622
555Lua provides some automatic conversions between values at run time.
556Any arithmetic operation applied to a string tries to convert
557that string to a number, following the usual rules.
558Conversely, whenever a number is used when a string is expected,
559that number is converted to a string, in a reasonable format.
560The format is chosen so that
561a conversion from number to string then back to number
562reproduces the original number \emph{exactly}.
563Thus,
564the conversion does not necessarily produces nice-looking text for some numbers.
565For complete control of how numbers are converted to strings,
566use the \verb|format| function \see{format}.
567 623
624\subsection{Variables}\label{variables}
625
626Variables are places that store values.
627In Lua, variables are given by simple identifiers or by table fields.
628
629A single name can denote a global variable, a local variable,
630or a formal parameter in a function
631(formal parameters are just local variables):
632\begin{Produc}
633\produc{var}{name}
634\end{Produc}%
635
636Square brackets are used to index a table:
637\begin{Produc}
638\produc{var}{exp \ter{[} exp \ter{]}}
639\end{Produc}%
640The first expression should result in a table value,
641from where the field given by the second expression gets the assigned value.
642
643The syntax \verb|var.NAME| is just syntactic sugar for
644\verb|var["NAME"]|:
645\begin{Produc}
646\produc{var}{exp \ter{.} name}
647\end{Produc}%
648Expressions are discussed in \See{expressions}.
649
650The meaning of assignments and evaluations of global variables and
651indexed variables can be changed by tag methods \see{tag-method}.
652An assignment to a global variable \verb|x = val|
653is equivalent to a call \verb|setglobal("x", val)| and
654an assignment to an indexed variable \verb|t[i] = val| is equivalent to
655\verb|settable_event(t,i,val)|.
656An access to a global variable \verb|x|
657is equivalent to a call \verb|getglobal("x")| and
658an access to an indexed variable \verb|t[i]| is equivalent to
659a call \verb|gettable_event(t,i)|.
660Of course,
661\verb|i| and \verb|val| can be complicated expressions.
662See \See{tag-method} for a complete description of these functions
663(\verb|setglobal| and \verb|getglobal| are in the basic library;
664\T{settable\_event} and \T{gettable\_event}
665are used for explanatory purposes only).
568 666
569 667
570\subsection{Statements}\label{stats} 668\subsection{Statements}\label{stats}
@@ -577,6 +675,25 @@ Non-conventional commands include table constructors
577\see{tableconstructor} 675\see{tableconstructor}
578and local variable declarations \see{localvar}. 676and local variable declarations \see{localvar}.
579 677
678\subsubsection{Chunks}\label{chunks}
679The unit of execution of Lua is called a \Def{chunk}.
680A chunk is simply a sequence of statements,
681which are executed sequentially.
682Each statement can be optionally followed by a semicolon:
683\begin{Produc}
684\produc{chunk}{\rep{stat \opt{\ter{;}}}}
685\end{Produc}%
686
687The notation used above is the usual extended BNF,
688in which
689\rep{\emph{a}}~means 0 or more \emph{a}'s, and
690\opt{\emph{a}}~means an optional \emph{a}.
691Non-terminals are shown in \emph{italics},
692keywords are shown in {\bf bold},
693and other terminal symbols are shown in {\tt typewriter} font,
694enclosed in single quotes.
695The complete syntax of Lua in EBNF is given on page~\pageref{BNF}.
696
580\subsubsection{Blocks} 697\subsubsection{Blocks}
581A \Index{block} is a list of statements; 698A \Index{block} is a list of statements;
582syntactically, a block is equal to a chunk: 699syntactically, a block is equal to a chunk:
@@ -603,70 +720,43 @@ The elements in both lists are separated by commas:
603\begin{Produc} 720\begin{Produc}
604\produc{stat}{varlist1 \ter{=} explist1} 721\produc{stat}{varlist1 \ter{=} explist1}
605\produc{varlist1}{var \rep{\ter{,} var}} 722\produc{varlist1}{var \rep{\ter{,} var}}
723\produc{explist1}{exp \rep{\ter{,} exp}}
606\end{Produc}% 724\end{Produc}%
725Expressions are discussed in \See{expressions}.
726
727Before the assignment,
728the list of values is \emph{adjusted} to the length of
729the list of variables.\index{adjustment}
730If there are more values than are needed,
731the excess values are thrown away.
732If there are less values than are needed,
733the list is extended with as many \nil's as needed.
734If the list of expressions ends with a function call,
735then all values returned by that function call enter in the list of values,
736before the adjust
737(except when the call is enclosed in parentheses; see \See{expressions}).
738
607This statement first evaluates all values on the right side 739This statement first evaluates all values on the right side
608and eventual indices on the left side, 740and eventual indices on the left side,
609and then makes the assignments. 741and then makes the assignments.
610So, the code 742So, the code
611\begin{verbatim} 743\begin{verbatim}
612 i = 3 744 i = 3
613 i, a[i] = 4, 20 745 i, a[i] = i+1, 20
614\end{verbatim} 746\end{verbatim}
615sets \verb|a[3]| to 20, but does not affect \verb|a[4]| 747sets \verb|a[3]| to 20, but does not affect \verb|a[4]|
616because the \verb|i| in \verb|a[i]| is evaluated 748because the \verb|i| in \verb|a[i]| is evaluated
617before it is assigned \verb|4|. 749before it is assigned 4.
618 750
619Multiple assignment can be used to exchange two values, as in 751Multiple assignment can be used to exchange two values, as in
620\begin{verbatim} 752\begin{verbatim}
621 x, y = y, x 753 x, y = y, x
622\end{verbatim} 754\end{verbatim}
623 755
624Before the assignment, the list of values is adjusted to
625the length of the list of variables.
626If there are more values than are needed,
627the excess values are thrown away.
628If there are less values than are needed,
629the list is extended with as many \nil's as needed.
630If the list of expressions (\M{explist1}) ends with a function call,
631all values returned by the function call enter in the list of values,
632before the adjust.
633
634A single name can denote a global variable, a local variable,
635or a formal parameter:
636\begin{Produc}
637\produc{var}{name}
638\end{Produc}%
639
640Square brackets are used to index a table:
641\begin{Produc}
642\produc{var}{exp \ter{[} exp \ter{]}}
643\end{Produc}%
644The first expression (\M{exp}) should result in a table value,
645from where the field indexed by the expression \M{exp}
646value gets the assigned value.
647
648The syntax \verb|var.NAME| is just syntactic sugar for
649\verb|var["NAME"]|:
650\begin{Produc}
651\produc{var}{exp \ter{.} name}
652\end{Produc}%
653
654The meaning of assignments and evaluations of global variables and
655indexed variables can be changed by tag methods \see{tag-method}.
656Actually,
657an assignment \verb|x = val|, where \verb|x| is a global variable,
658is equivalent to a call \verb|setglobal("x", val)| and
659an assignment \verb|t[i] = val| is equivalent to
660\verb|settable_event(t,i,val)|.
661See \See{tag-method} for a complete description of these functions
662(\verb|setglobal| is in the basic library;
663\T{settable\_event} is used for explanatory purposes only).
664
665\subsubsection{Control Structures}\label{control} 756\subsubsection{Control Structures}\label{control}
666The control structures 757The control structures
667\rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and 758\rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and
668familiar syntax 759familiar syntax:
669%(there is also a \rwd{for} statement; see \See{for}):
670\index{while-do statement} 760\index{while-do statement}
671\index{repeat-until statement} 761\index{repeat-until statement}
672\index{if-then-else statement} 762\index{if-then-else statement}
@@ -677,6 +767,8 @@ familiar syntax
677 \rep{\rwd{elseif} exp \rwd{then} block} 767 \rep{\rwd{elseif} exp \rwd{then} block}
678 \opt{\rwd{else} block} \rwd{end}} 768 \opt{\rwd{else} block} \rwd{end}}
679\end{Produc}% 769\end{Produc}%
770There is also a \rwd{for} statement in two flavors \see{for}.
771
680The \Index{condition expression} \M{exp} of a 772The \Index{condition expression} \M{exp} of a
681control structure may return any value. 773control structure may return any value.
682All values different from \nil\ are considered true; 774All values different from \nil\ are considered true;
@@ -686,41 +778,51 @@ The \rwd{return} statement is used to return values
686from a function or from a chunk. 778from a function or from a chunk.
687\label{return}% 779\label{return}%
688\index{return statement}% 780\index{return statement}%
689Because functions or chunks may return more than one value, 781Functions and chunks may return more than one value,
690the syntax for the \rwd{return} statement is 782and so the syntax for the \rwd{return} statement is
691\begin{Produc} 783\begin{Produc}
692\produc{stat}{\rwd{return} \opt{explist1}} 784\produc{stat}{\rwd{return} \opt{explist1}}
693\end{Produc}% 785\end{Produc}%
694 786
695The \rwd{break} statement can be used to terminate the execution of a loop, 787The \rwd{break} statement can be used to terminate the execution of a
788\rwd{while}, \rwd{repeat}, or \rwd{for} loop,
696skipping to the next statement after the loop: 789skipping to the next statement after the loop:
697\index{break statement} 790\index{break statement}
698\begin{Produc} 791\begin{Produc}
699\produc{stat}{\rwd{break}} 792\produc{stat}{\rwd{break}}
700\end{Produc}% 793\end{Produc}%
701A \rwd{break} ends the innermost enclosing loop 794A \rwd{break} ends the innermost enclosing loop.
702(\rwd{while}, \rwd{repeat}, or \rwd{for}).
703 795
704\NOTE 796\NOTE
705For syntactic reasons, \rwd{return} and \rwd{break} 797For syntactic reasons, \rwd{return} and \rwd{break}
706statements can only be written as the \emph{last} statements of a block. 798statements can only be written as the \emph{last} statements of a block.
707If it is really necessary to \rwd{return} or \rwd{break} in the 799If it is really necessary to \rwd{return} or \rwd{break} in the
708middle of a block, 800middle of a block,
709an explicit inner block can used, 801then an explicit inner block can used,
710as in the idiom `\verb|do return end|', 802as in the idioms
711because now \rwd{return} is last statement in the inner block. 803`\verb|do return end|' and
804`\verb|do break end|',
805because now \rwd{return} and \rwd{break} are last statements in the inner block.
806In practice,
807these idioms are only used during debugging.
808(The idiom `\verb|do return end|' can be added at the beginning of a chunk
809for syntax checking only.)
712 810
713\subsubsection{For Statement} \label{for}\index{for statement} 811\subsubsection{For Statement} \label{for}\index{for statement}
714 812
715The \rwd{for} statement has two forms, 813The \rwd{for} statement has two forms,
716one for numbers and one for tables. 814one for numbers and one for tables.
717\newpage 815
718The numerical \rwd{for} loop has the following syntax: 816The numerical \rwd{for} loop
817repeats a block of code while a control variables runs through an arithmetic progression. It has the following syntax:
719\begin{Produc} 818\begin{Produc}
720\produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp} 819\produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
721 \rwd{do} block \rwd{end}} 820 \rwd{do} block \rwd{end}}
722\end{Produc}% 821\end{Produc}%
723A \rwd{for} statement like 822The \emph{block} is repeated for \emph{name} starting at the value of
823the first \emph{exp}, until it reaches the second \emph{exp} by steps of the
824third \emph{exp}.
825More precisely, a \rwd{for} statement like
724\begin{verbatim} 826\begin{verbatim}
725 for var = e1, e2, e3 do block end 827 for var = e1, e2, e3 do block end
726\end{verbatim} 828\end{verbatim}
@@ -744,11 +846,11 @@ the block.
744\item If the third expression (the step) is absent, then a step of~1 is used. 846\item If the third expression (the step) is absent, then a step of~1 is used.
745\item Both the limit and the step are evaluated only once, 847\item Both the limit and the step are evaluated only once,
746before the loop starts. 848before the loop starts.
747\item The variable \verb|var| is local to the statement; 849\item You can use \rwd{break} to exit a \rwd{for} loop.
748you cannot use its value after the \rwd{for} ends. 850\item The loop variable \verb|var| is local to the statement;
749\item You can use \rwd{break} to exit a \rwd{for}. 851you cannot use its value after the \rwd{for} ends or is broken.
750If you need the value of the index, 852If you need the value of the loop variable \verb|var|,
751assign it to another variable before breaking. 853then assign it to another variable before breaking or exiting the loop.
752\end{itemize} 854\end{itemize}
753 855
754The table \rwd{for} statement traverses all pairs 856The table \rwd{for} statement traverses all pairs
@@ -781,11 +883,11 @@ The name is here for explanatory purposes only.
781the block. 883the block.
782\item The behavior is \emph{undefined} if you change 884\item The behavior is \emph{undefined} if you change
783the table \verb|_t| during the traversal. 885the table \verb|_t| during the traversal.
784\item The variables \verb|index| and \verb|value| are local to the statement; 886\item You can use \rwd{break} to exit a \rwd{for} loop.
887\item The loop variables \verb|index| and \verb|value| are local to the statement;
785you cannot use their values after the \rwd{for} ends. 888you cannot use their values after the \rwd{for} ends.
786\item You can use \rwd{break} to exit a \rwd{for}.
787If you need the value of \verb|index| or \verb|value|, 889If you need the value of \verb|index| or \verb|value|,
788assign them to other variables before breaking. 890then assign them to other variables before breaking or exiting the loop.
789\item The order that table elements are traversed is undefined, 891\item The order that table elements are traversed is undefined,
790\emph{even for numerical indices}. 892\emph{even for numerical indices}.
791If you want to traverse indices in numerical order, 893If you want to traverse indices in numerical order,
@@ -806,29 +908,29 @@ Function calls are explained in \See{functioncall}.
806\Index{Local variables} may be declared anywhere inside a block. 908\Index{Local variables} may be declared anywhere inside a block.
807The declaration may include an initial assignment: 909The declaration may include an initial assignment:
808\begin{Produc} 910\begin{Produc}
809\produc{stat}{\rwd{local} declist \opt{init}} 911\produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}}
810\produc{declist}{name \rep{\ter{,} name}} 912\produc{namelist}{name \rep{\ter{,} name}}
811\produc{init}{\ter{=} explist1}
812\end{Produc}% 913\end{Produc}%
813If present, an initial assignment has the same semantics 914If present, an initial assignment has the same semantics
814of a multiple assignment. 915of a multiple assignment \see{assignment}.
815Otherwise, all variables are initialized with \nil. 916Otherwise, all variables are initialized with \nil.
816 917
817A chunk is also a block,
818and so local variables can be declared outside any explicit block.
819
820The scope of local variables begins \emph{after} 918The scope of local variables begins \emph{after}
821the declaration and lasts until the end of the block. 919the declaration and lasts until the end of the block.
822Thus, the code 920Thus, the code
823\verb|local print=print| 921\verb|local print=print|
824creates a local variable called \verb|print| whose 922creates a local variable named \verb|print| whose
825initial value is that of the \emph{global} variable of the same name. 923initial value is that of the \emph{global} variable of the same name.
826 924
925A chunk is also a block \see{chunks},
926and so local variables can be declared outside any explicit block.
927Such local variables die when the chunk ends.
928
827 929
828\subsection{\Index{Expressions}} 930\subsection{\Index{Expressions}}\label{expressions}
829 931
830\subsubsection{\Index{Basic Expressions}} 932%\subsubsection{\Index{Basic Expressions}}
831The basic expressions in Lua are 933The basic expressions in Lua are the following:
832\begin{Produc} 934\begin{Produc}
833\produc{exp}{\ter{(} exp \ter{)}} 935\produc{exp}{\ter{(} exp \ter{)}}
834\produc{exp}{\rwd{nil}} 936\produc{exp}{\rwd{nil}}
@@ -841,25 +943,23 @@ The basic expressions in Lua are
841\produc{exp}{tableconstructor} 943\produc{exp}{tableconstructor}
842\end{Produc}% 944\end{Produc}%
843 945
844An expression enclosed in parentheses always results 946An expression enclosed in parentheses always results in only one value
845in only one value. 947(the only expressions that can result in multiple values are function calls).
948Thus,
949\verb|(f(x,y,z))| is always a single value,
950even if \verb|f| returns several values.
951(The value of \verb|(f(x,y,z))| is the first value returned by \verb|f|
952or \nil\ if \verb|f| does not return any values.)
846 953
847Numbers (numerical constants) and 954\emph{Numbers} and \emph{literal strings} are explained in \See{lexical};
848literal strings are explained in \See{lexical}; 955variables are explained in \See{variables};
849variables are explained in \See{assignment};
850upvalues are explained in \See{upvalue}; 956upvalues are explained in \See{upvalue};
851function definitions are explained in \See{func-def}; 957function definitions are explained in \See{func-def};
852function calls are explained in \See{functioncall}. 958function calls are explained in \See{functioncall};
853Table constructors are explained in \See{tableconstructor}. 959table constructors are explained in \See{tableconstructor}.
854
855An access to a global variable \verb|x| is equivalent to a
856call \verb|getglobal("x")| and
857an access to an indexed variable \verb|t[i]| is equivalent to
858a call \verb|gettable_event(t,i)|.
859See \See{tag-method} for a description of these functions
860(\verb|getglobal| is in the basic library;
861\T{gettable\_event} is used for explanatory purposes only).
862 960
961Expressions can also be built with arithmetic operators, relational operators,
962and logical operadors, all of which are explained below.
863 963
864\subsubsection{Arithmetic Operators} 964\subsubsection{Arithmetic Operators}
865Lua supports the usual \Index{arithmetic operators}: 965Lua supports the usual \Index{arithmetic operators}:
@@ -868,31 +968,44 @@ the binary \verb|+| (addition),
868\verb|/| (division), and \verb|^| (exponentiation); 968\verb|/| (division), and \verb|^| (exponentiation);
869and unary \verb|-| (negation). 969and unary \verb|-| (negation).
870If the operands are numbers, or strings that can be converted to 970If the operands are numbers, or strings that can be converted to
871numbers (according to the rules given in \See{coercion}), 971numbers \see{coercion},
872then all operations except exponentiation have the usual meaning. 972then all operations except exponentiation have the usual meaning;
873Otherwise, an appropriate tag method is called \see{tag-method}. 973otherwise, an appropriate tag method is called \see{tag-method}.
874An exponentiation always calls a tag method. 974An exponentiation always calls a tag method.
875The standard mathematical library redefines this method for numbers, 975The standard mathematical library redefines this method for numbers,
876giving the expected meaning to \Index{exponentiation} 976giving the expected meaning to \Index{exponentiation}
877\see{mathlib}. 977\see{mathlib}.
878 978
879\subsubsection{Relational Operators} 979\subsubsection{Relational Operators}\label{rel-ops}
880The \Index{relational operators} in Lua are 980The \Index{relational operators} in Lua are
881\begin{verbatim} 981\begin{verbatim}
882 == ~= < > <= >= 982 == ~= < > <= >=
883\end{verbatim} 983\end{verbatim}
884These operators return \nil\ as false and a value different from \nil\ as true. 984These operators return \nil\ as false and a value different from \nil\ as true.
885 985
886Equality (\verb|==|) first compares the tags of its operands. 986Equality (\verb|==|) first compares the type of its operands.
887If they are different, then the result is \nil. 987If the types are different, then the result is \nil.
888Otherwise, their values are compared. 988Otherwise, the values of the operands are compared.
889Numbers and strings are compared in the usual way. 989Numbers are compared in the usual way.
890Tables, userdata, and functions are compared by reference, 990Strings, tables, userdata, and functions are compared \emph{by reference},
891that is, 991that is,
892two tables are considered equal only if they are the \emph{same} table. 992two tables are considered equal only if they are the \emph{same} table.
893Every time you create a new table (or userdata, or function) this 993In particular,
894new value is different from any previously existing value. 994equality is a constant-time operation and does not depend on the size of the
895The operator \verb|~=| is exactly the negation of equality (\verb|==|). 995strings or tables.
996
997Every time you create a new table (or string, userdata, or function),
998this new value is different from any previously existing value.
999In particular,
1000this is true for strings,
1001even if a string is built in different ways.
1002For example, all strings below are equal,
1003that is, they are the \emph{same} string:
1004\begin{verbatim}
1005 "Lua" .. " 4.1"
1006 "Lua " .. "4.1"
1007 "Lua 4.1"
1008\end{verbatim}
896 1009
897\NOTE 1010\NOTE
898The conversion rules of \See{coercion} 1011The conversion rules of \See{coercion}
@@ -902,27 +1015,39 @@ and \verb|t[0]| and \verb|t["0"]| denote different
902entries in a table. 1015entries in a table.
903\medskip 1016\medskip
904 1017
1018The operator \verb|~=| is exactly the negation of equality (\verb|==|).
1019
905The order operators work as follows. 1020The order operators work as follows.
906If both arguments are numbers, then they are compared as such. 1021If both arguments are numbers, then they are compared as such.
907Otherwise, if both arguments are strings, 1022Otherwise, if both arguments are strings,
908then their values are compared using lexicographical order. 1023then their values are compared according to the current locale (see below).
909Otherwise, the ``lt'' tag method is called \see{tag-method}. 1024Otherwise, the ``lt'' tag method is called \see{tag-method}.
910 1025
1026String comparison according to the current locale
1027means that
1028if you sort strings using \verb|<=|,
1029then
1030\emph{\'agua} will appear before \emph{book}
1031and close to all other strings beginning with \emph{ag},
1032even though \emph{\'a}~appears after \emph{b} in the usual ISO Latin encoding.
1033\index{string comparison}
1034
1035
911\subsubsection{Logical Operators} 1036\subsubsection{Logical Operators}
912The \Index{logical operators} in Lua are 1037The \Index{logical operators} in Lua are
913\index{and}\index{or}\index{not} 1038\index{and}\index{or}\index{not}
914\begin{verbatim} 1039\begin{verbatim}
915 and or not 1040 and or not
916\end{verbatim} 1041\end{verbatim}
917Like the control structures, all logical operators 1042Like the control structures \see{control},
918consider \nil\ as false and anything else as true. 1043all logical operators consider \nil\ as false and anything else as true.
919 1044
920The conjunction operator \verb|and| returns \nil\ if its first argument is \nil; 1045The conjunction operator \rwd{and} returns \nil\ if its first argument is \nil;
921otherwise, it returns its second argument. 1046otherwise, \rwd{and} returns its second argument.
922The disjunction operator \verb|or| returns its first argument 1047The disjunction operator \rwd{or} returns its first argument
923if it is different from \nil; 1048if it is different from \nil;
924otherwise, it returns its second argument. 1049otherwise, \rwd{or} returns its second argument.
925Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, 1050Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation},
926that is, 1051that is,
927the second operand is evaluated only if necessary. 1052the second operand is evaluated only if necessary.
928 1053
@@ -950,14 +1075,14 @@ provided that \verb|b| is not \nil.
950 1075
951\subsubsection{Concatenation} \label{concat} 1076\subsubsection{Concatenation} \label{concat}
952The string \Index{concatenation} operator in Lua is 1077The string \Index{concatenation} operator in Lua is
953denoted by two dots (`\IndexVerb{..}'). 1078denoted by two dots (`\verb|..|').
954If both operands are strings or numbers, then they are converted to 1079If both operands are strings or numbers, then they are converted to
955strings according to the rules in \See{coercion}. 1080strings according to the rules mentioned in \See{coercion}.
956Otherwise, the ``concat'' tag method is called \see{tag-method}. 1081Otherwise, the ``concat'' tag method is called \see{tag-method}.
957 1082
958\subsubsection{Precedence} 1083\subsubsection{Precedence}
959\Index{Operator precedence} in Lua follows the table below, 1084\Index{Operator precedence} in Lua follows the table below,
960from the lower to the higher priority: 1085from lower to higher priority:
961\begin{verbatim} 1086\begin{verbatim}
962 and or 1087 and or
963 < > <= >= ~= == 1088 < > <= >= ~= ==
@@ -977,6 +1102,8 @@ as long as these optimizations do not change normal results.
977However, these optimizations may change some results 1102However, these optimizations may change some results
978if you define non-associative (or non-commutative) 1103if you define non-associative (or non-commutative)
979tag methods for these operators. 1104tag methods for these operators.
1105In general,
1106you should not write code that depends on the order of evaluation.
980 1107
981\subsubsection{Table Constructors} \label{tableconstructor} 1108\subsubsection{Table Constructors} \label{tableconstructor}
982Table \Index{constructors} are expressions that create tables; 1109Table \Index{constructors} are expressions that create tables;
@@ -989,11 +1116,12 @@ The general syntax for constructors is
989\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist 1116\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist
990 \Or ffieldlist \ter{;} lfieldlist} 1117 \Or ffieldlist \ter{;} lfieldlist}
991\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}} 1118\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}}
992\produc{ffieldlist}{\opt{ffieldlist1}} 1119\produc{ffieldlist}{\opt{ffieldlist1 \opt{\ter{,}}}}
993\end{Produc}% 1120\end{Produc}%
994 1121
995The form \emph{explist1} is used to initialize lists. 1122The form \emph{explist1} is used to initialize \IndexEmph{lists}.
996The expressions in the list are assigned to consecutive numerical indices, 1123The expressions in a list are assigned to consecutive numerical indices
1124in the table,
997starting with~1. 1125starting with~1.
998For example, 1126For example,
999\begin{verbatim} 1127\begin{verbatim}
@@ -1009,12 +1137,16 @@ is equivalent to
1009 a = temp 1137 a = temp
1010 end 1138 end
1011\end{verbatim} 1139\end{verbatim}
1140
1012If the last expression in the list is a function call, 1141If the last expression in the list is a function call,
1013all values returned by the call enter the list \see{functioncall}. 1142then all values returned by the call enter the list consecutively
1143\see{functioncall}.
1144To avoid this,
1145enclose the function call in parentheses.
1014 1146
1015The form \emph{ffieldlist1} initializes other fields in a table: 1147The form \emph{ffieldlist1} initializes other fields in a table:
1016\begin{Produc} 1148\begin{Produc}
1017\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} 1149\produc{ffieldlist1}{ffield \rep{\ter{,} ffield}}
1018\produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp} 1150\produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp}
1019\end{Produc}% 1151\end{Produc}%
1020For example, 1152For example,
@@ -1026,8 +1158,8 @@ is equivalent to
1026 do 1158 do
1027 local temp = {} 1159 local temp = {}
1028 temp[f(k)] = g(y) 1160 temp[f(k)] = g(y)
1029 temp.x = 1 -- or temp["x"] = 1 1161 temp["x"] = 1 -- or temp.x = 1
1030 temp.y = 3 -- or temp["y"] = 3 1162 temp["y"] = 3 -- or temp.y = 3
1031 temp[0] = b+c 1163 temp[0] = b+c
1032 a = temp 1164 a = temp
1033 end 1165 end
@@ -1035,7 +1167,8 @@ is equivalent to
1035An expression like \verb|{x = 1, y = 4}| is 1167An expression like \verb|{x = 1, y = 4}| is
1036in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. 1168in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
1037 1169
1038Both forms may have an optional trailing comma, 1170Both forms may have an optional trailing comma
1171(for convinence of machine-generated code),
1039and can be used in the same constructor separated by 1172and can be used in the same constructor separated by
1040a semi-colon. 1173a semi-colon.
1041For example, all forms below are correct. 1174For example, all forms below are correct.
@@ -1051,7 +1184,8 @@ A \Index{function call} in Lua has the following syntax:
1051\begin{Produc} 1184\begin{Produc}
1052\produc{functioncall}{exp args} 1185\produc{functioncall}{exp args}
1053\end{Produc}% 1186\end{Produc}%
1054First, \M{exp} and \M{args} are evaluated. 1187In a function call,
1188first \M{exp} and \M{args} are evaluated.
1055If the value of \M{exp} has type \emph{function}, 1189If the value of \M{exp} has type \emph{function},
1056then this function is called, 1190then this function is called,
1057with the given arguments. 1191with the given arguments.
@@ -1072,7 +1206,6 @@ except that \verb|v| is evaluated only once.
1072Arguments have the following syntax: 1206Arguments have the following syntax:
1073\begin{Produc} 1207\begin{Produc}
1074\produc{args}{\ter{(} \opt{explist1} \ter{)}} 1208\produc{args}{\ter{(} \opt{explist1} \ter{)}}
1075\produc{explist1}{\rep{exp \ter{,}} exp}
1076\produc{args}{tableconstructor} 1209\produc{args}{tableconstructor}
1077\produc{args}{literal} 1210\produc{args}{literal}
1078\end{Produc}% 1211\end{Produc}%
@@ -1096,7 +1229,9 @@ or in the middle of a list of expressions,
1096then its return list is adjusted to~1, 1229then its return list is adjusted to~1,
1097thus discarding all returned values but the first one. 1230thus discarding all returned values but the first one.
1098If the function is called as the last element of a list of expressions, 1231If the function is called as the last element of a list of expressions,
1099then no adjustment is made. 1232then no adjustment is made
1233(unless the call is enclosed in parentheses).
1234
1100Here are some examples: 1235Here are some examples:
1101\begin{verbatim} 1236\begin{verbatim}
1102 f() -- adjusted to 0 results 1237 f() -- adjusted to 0 results
@@ -1111,11 +1246,11 @@ Here are some examples:
1111 {f(), nil} -- f() is adjusted to 1 result 1246 {f(), nil} -- f() is adjusted to 1 result
1112\end{verbatim} 1247\end{verbatim}
1113 1248
1114If you embrace a function call in parentheses, 1249If you enclose a function call in parentheses,
1115then it is adjusted to return exactly one value: 1250then it is adjusted to return exactly one value:
1116\begin{verbatim} 1251\begin{verbatim}
1117 return x, y, (f()) -- returns x, y, and one value from f() 1252 return x,y,(f()) -- returns x, y, and the first value from f()
1118 {(f())} -- create a table with exactly one element 1253 {(f())} -- creates a table with exactly one element
1119\end{verbatim} 1254\end{verbatim}
1120 1255
1121\subsubsection{\Index{Function Definitions}} \label{func-def} 1256\subsubsection{\Index{Function Definitions}} \label{func-def}
@@ -1132,17 +1267,17 @@ The statement
1132\begin{verbatim} 1267\begin{verbatim}
1133 function f () ... end 1268 function f () ... end
1134\end{verbatim} 1269\end{verbatim}
1135is just syntactic sugar for 1270is syntactic sugar for
1136\begin{verbatim} 1271\begin{verbatim}
1137 f = function () ... end 1272 f = function () ... end
1138\end{verbatim} 1273\end{verbatim}
1139and the statement 1274and the statement
1140\begin{verbatim} 1275\begin{verbatim}
1141 function v.c.f () ... end 1276 function t.a.b.c.f () ... end
1142\end{verbatim} 1277\end{verbatim}
1143is syntactic sugar for 1278is syntactic sugar for
1144\begin{verbatim} 1279\begin{verbatim}
1145 v.c.f = function () ... end 1280 t.a.b.c.f = function () ... end
1146\end{verbatim} 1281\end{verbatim}
1147 1282
1148A function definition is an executable expression, 1283A function definition is an executable expression,
@@ -1150,7 +1285,7 @@ whose value has type \emph{function}.
1150When Lua pre-compiles a chunk, 1285When Lua pre-compiles a chunk,
1151all its function bodies are pre-compiled too. 1286all its function bodies are pre-compiled too.
1152Then, whenever Lua executes the function definition, 1287Then, whenever Lua executes the function definition,
1153its upvalues are fixed \see{upvalue}, 1288its upvalues (if any) are fixed \see{upvalue},
1154and the function is \emph{instantiated} (or \emph{closed}). 1289and the function is \emph{instantiated} (or \emph{closed}).
1155This function instance (or \emph{closure}) 1290This function instance (or \emph{closure})
1156is the final value of the expression. 1291is the final value of the expression.
@@ -1161,7 +1296,7 @@ Parameters act as local variables,
1161initialized with the argument values: 1296initialized with the argument values:
1162\begin{Produc} 1297\begin{Produc}
1163\produc{parlist1}{\ter{\ldots}} 1298\produc{parlist1}{\ter{\ldots}}
1164\produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} 1299\produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}}
1165\end{Produc}% 1300\end{Produc}%
1166\label{vararg}% 1301\label{vararg}%
1167When a function is called, 1302When a function is called,
@@ -1194,9 +1329,9 @@ Then, we have the following mapping from arguments to parameters:
1194 f(r()) a=1, b=2 1329 f(r()) a=1, b=2
1195 1330
1196 g(3) a=3, b=nil, arg={n=0} 1331 g(3) a=3, b=nil, arg={n=0}
1197 g(3, 4) a=3, b=4, arg={n=0} 1332 g(3, 4) a=3, b=4, arg={n=0}
1198 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} 1333 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
1199 g(5, r()) a=5, b=1, arg={2, 3; n=2} 1334 g(5, r()) a=5, b=1, arg={2, 3; n=2}
1200\end{verbatim} 1335\end{verbatim}
1201 1336
1202Results are returned using the \rwd{return} statement \see{return}. 1337Results are returned using the \rwd{return} statement \see{return}.
@@ -1207,14 +1342,13 @@ then the function returns with no results.
1207The \emph{colon} syntax 1342The \emph{colon} syntax
1208is used for defining \IndexEmph{methods}, 1343is used for defining \IndexEmph{methods},
1209that is, functions that have an implicit extra parameter \IndexVerb{self}. 1344that is, functions that have an implicit extra parameter \IndexVerb{self}.
1210 1345Thus, the statement
1211The statement
1212\begin{verbatim} 1346\begin{verbatim}
1213 function v.c:f (...) ... end 1347 function t.a.b.c:f (...) ... end
1214\end{verbatim} 1348\end{verbatim}
1215is just syntactic sugar for 1349is syntactic sugar for
1216\begin{verbatim} 1350\begin{verbatim}
1217 v.c.f = function (self, ...) ... end 1351 t.a.b.c.f = function (self, ...) ... end
1218\end{verbatim} 1352\end{verbatim}
1219Note that the function gets an extra formal parameter called \verb|self|. 1353Note that the function gets an extra formal parameter called \verb|self|.
1220 1354
@@ -1237,13 +1371,14 @@ whose syntax is
1237\end{Produc}% 1371\end{Produc}%
1238 1372
1239An upvalue is somewhat similar to a variable expression, 1373An upvalue is somewhat similar to a variable expression,
1240but whose value is \emph{frozen} when the function wherein it 1374but whose value is \emph{frozen} when the function in which it
1241appears is instantiated. 1375appears is instantiated.
1242The name used in an upvalue may be the name of any variable visible 1376The name used in an upvalue may be the name of any variable visible
1243at the point where the function is defined, 1377at the point where the function is defined,
1244that is, 1378that is,
1245global variables and local variables 1379global variables and local variables
1246from the \emph{immediately enclosing} function. 1380from the \emph{immediately enclosing} function.
1381
1247Note that when the upvalue is a table, 1382Note that when the upvalue is a table,
1248only the \emph{reference} to that table 1383only the \emph{reference} to that table
1249(which is the value of the upvalue) is frozen; 1384(which is the value of the upvalue) is frozen;
@@ -1293,8 +1428,8 @@ So, for this kind of error, Lua does not call
1293the \verb|_ERRORMESSAGE| function; 1428the \verb|_ERRORMESSAGE| function;
1294instead, the corresponding function from the library 1429instead, the corresponding function from the library
1295returns immediately with a special error code (\verb|LUA_ERRMEM|). 1430returns immediately with a special error code (\verb|LUA_ERRMEM|).
1296This and other error codes are defined in \verb|lua.h|; 1431This and other error codes are defined in \verb|lua.h|
1297\See{luado}. 1432\see{luado}.
1298 1433
1299The only argument to \verb|_ERRORMESSAGE| is a string 1434The only argument to \verb|_ERRORMESSAGE| is a string
1300describing the error. 1435describing the error.
@@ -1312,9 +1447,9 @@ Lua code can ``catch'' an error using the function
1312\verb|call| \see{pdf-call}. 1447\verb|call| \see{pdf-call}.
1313 1448
1314 1449
1315\subsection{Tag Methods} \label{tag-method}\index{tag method} 1450\subsection{Tag Methods} \label{tag-method}
1316 1451
1317A tag method is a programmer-defined function 1452A \IndexEmph{tag method} is a programmer-defined function
1318that defines how Lua operations act over user-defined types 1453that defines how Lua operations act over user-defined types
1319(and, sometimes, over basic types as well). 1454(and, sometimes, over basic types as well).
1320An \Def{event} is any operation that may invoke a tag method. 1455An \Def{event} is any operation that may invoke a tag method.
@@ -1323,8 +1458,9 @@ Lua selects the tag method called for any specific event
1323according to the types of the values involved 1458according to the types of the values involved
1324in the event \see{TypesSec}. 1459in the event \see{TypesSec}.
1325The function \IndexLIB{settagmethod} changes the tag method 1460The function \IndexLIB{settagmethod} changes the tag method
1326associated with a given pair \M{(type, event)}. 1461associated with a given pair (\M{type}, \M{event}).
1327Its first parameter is the type (its name or its tag), 1462The first parameter to \verb|settagmethod| is the type
1463(represented by its name or tag),
1328the second parameter is the event name (a string; see below), 1464the second parameter is the event name (a string; see below),
1329and the third parameter is the new method (a function), 1465and the third parameter is the new method (a function),
1330or \nil\ to restore the default behavior for the pair. 1466or \nil\ to restore the default behavior for the pair.
@@ -1344,7 +1480,7 @@ The code shown here in Lua is only illustrative;
1344the real behavior is hard coded in the interpreter, 1480the real behavior is hard coded in the interpreter,
1345and it is much more efficient than this simulation. 1481and it is much more efficient than this simulation.
1346All functions used in these descriptions 1482All functions used in these descriptions
1347(\verb|rawget|, \verb|tonumber|, \verb|call|, etc.) 1483(\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)\
1348are described in \See{predefined}. 1484are described in \See{predefined}.
1349 1485
1350\begin{description} 1486\begin{description}
@@ -1615,7 +1751,8 @@ Lua does the equivalent of the call \verb|gc_event(nil)|.
1615 1751
1616 1752
1617 1753
1618\section{The Application Program Interface} 1754%------------------------------------------------------------------------------
1755\section{The Application Program Interface}\label{API}
1619\index{C API} 1756\index{C API}
1620This section describes the API for Lua, that is, 1757This section describes the API for Lua, that is,
1621the set of C~functions available to the host program to communicate 1758the set of C~functions available to the host program to communicate
@@ -1627,17 +1764,17 @@ are declared in the header file \verb|lua.h|.
1627Even when we use the term ``function'', 1764Even when we use the term ``function'',
1628any facility in the API may be provided as a \emph{macro} instead. 1765any facility in the API may be provided as a \emph{macro} instead.
1629All such macros use each of its arguments exactly once 1766All such macros use each of its arguments exactly once
1630(except for the first argument, which is always a state), 1767(except for the first argument, which is always a Lua state),
1631and so do not generate hidden side-effects. 1768and so do not generate hidden side-effects.
1632 1769
1633 1770
1634\subsection{States} \label{mangstate} 1771\subsection{States} \label{mangstate}
1635 1772
1636The Lua library is fully reentrant: 1773The Lua library is fully reentrant:
1637it does not have any global variables. 1774it has no global variables.
1638\index{state} 1775\index{state}
1639The whole state of the Lua interpreter 1776The whole state of the Lua interpreter
1640(global variables, stack, tag methods, etc.) 1777(global variables, stack, tag methods, etc.)\
1641is stored in a dynamically allocated structure of type \verb|lua_State|; 1778is stored in a dynamically allocated structure of type \verb|lua_State|;
1642\DefAPI{lua_State} 1779\DefAPI{lua_State}
1643this state must be passed as the first argument to 1780this state must be passed as the first argument to
@@ -1672,7 +1809,7 @@ On the other hand,
1672long-running programs --- 1809long-running programs ---
1673like a daemon or a web server --- 1810like a daemon or a web server ---
1674might need to release states as soon as they are not needed, 1811might need to release states as soon as they are not needed,
1675to avoid growing too big. 1812to avoid growing too large.
1676 1813
1677With the exception of \verb|lua_open|, 1814With the exception of \verb|lua_open|,
1678all functions in the Lua API need a state as their first argument. 1815all functions in the Lua API need a state as their first argument.
@@ -1680,26 +1817,26 @@ all functions in the Lua API need a state as their first argument.
1680 1817
1681\subsection{Threads} 1818\subsection{Threads}
1682 1819
1683Lua offers a partial support for multiple threads. 1820Lua offers a partial support for multiple threads of execution.
1684If you have a C library that offers multi-threading or co-routines, 1821If you have a C~library that offers multi-threading or co-routines,
1685Lua can cooperate with it to implement the equivalent facility in Lua. 1822then Lua can cooperate with it to implement the equivalent facility in Lua.
1686The following function creates a new ``thread'' in Lua: 1823The following function creates a new ``thread'' in Lua:
1687\begin{verbatim} 1824\begin{verbatim}
1688 lua_State *lua_newthread (lua_State *L, int stacksize); 1825 lua_State *lua_newthread (lua_State *L, int stacksize);
1689\end{verbatim} 1826\end{verbatim}
1690\DefAPI{lua_newthread} 1827\DefAPI{lua_newthread}
1691The new state returned by this function shares with the original state 1828The new state returned by this function shares with the original state
1692all global environment (such as tables, tag methods, etc.), 1829all global environment (such as tables, tag methods, etc.),
1693but has an independent stack. 1830but has an independent run-time stack.
1694(The use of these multiple stacks must be ``syncronized'' with C. 1831(The use of these multiple stacks must be ``syncronized'' with C.
1695How to explain that? TO BE WRITTEN.) 1832How to explain that? TO BE WRITTEN.)
1696 1833
1697Each thread has an independent table for global variables. 1834Each thread has an independent table for global variables.
1698When you create a thread this table is the same as of the given state, 1835When you create a thread, this table is the same as that of the given state,
1699but you can change each one independently. 1836but you can change each one independently.
1700 1837
1701You destroy threads with \verb|lua_close|. 1838You destroy threads with \verb|lua_close|.
1702When you destroy the last thread of a global state, 1839When you destroy the last thread sharing a given state,
1703the state itself is also destroyed. 1840the state itself is also destroyed.
1704 1841
1705 1842
@@ -1707,7 +1844,7 @@ the state itself is also destroyed.
1707 1844
1708Lua uses a \emph{stack} to pass values to and from C. 1845Lua uses a \emph{stack} to pass values to and from C.
1709Each element in this stack represents a Lua value 1846Each element in this stack represents a Lua value
1710(nil, number, string, etc.). 1847(\nil, number, string, etc.).
1711 1848
1712For convenience, 1849For convenience,
1713most query operations in the API do not follow a strict stack discipline. 1850most query operations in the API do not follow a strict stack discipline.
@@ -1716,7 +1853,7 @@ A positive index represents an \emph{absolute} stack position
1716(starting at~1, not 0 as in C); 1853(starting at~1, not 0 as in C);
1717a negative index represents an \emph{offset} from the top of the stack. 1854a negative index represents an \emph{offset} from the top of the stack.
1718More specifically, if the stack has \M{n} elements, 1855More specifically, if the stack has \M{n} elements,
1719index~1 represents the first element 1856then index~1 represents the first element
1720(that is, the first element pushed onto the stack), 1857(that is, the first element pushed onto the stack),
1721and 1858and
1722index~\M{n} represents the last element; 1859index~\M{n} represents the last element;
@@ -1755,8 +1892,8 @@ when your code has loops pushing elements onto the stack.
1755Most query functions accept as indices any value inside the 1892Most query functions accept as indices any value inside the
1756available stack space. 1893available stack space.
1757Such indices are called \emph{acceptable indices}. 1894Such indices are called \emph{acceptable indices}.
1758More formally, we can define an \IndexEmph{acceptable index} 1895More formally, we define an \IndexEmph{acceptable index}
1759as 1896as follows:
1760\begin{verbatim} 1897\begin{verbatim}
1761 (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) 1898 (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace)
1762\end{verbatim} 1899\end{verbatim}
@@ -1779,7 +1916,7 @@ and sets the stack top to that index.
1779If the new top is larger than the old one, 1916If the new top is larger than the old one,
1780then the new elements are filled with \nil. 1917then the new elements are filled with \nil.
1781If \verb|index| is 0, then all stack elements are removed. 1918If \verb|index| is 0, then all stack elements are removed.
1782A useful macro defined in the API is 1919A useful macro defined in the \verb|lua.h| is
1783\begin{verbatim} 1920\begin{verbatim}
1784 #define lua_pop(L,n) lua_settop(L, -(n)-1) 1921 #define lua_pop(L,n) lua_settop(L, -(n)-1)
1785\end{verbatim} 1922\end{verbatim}
@@ -1789,22 +1926,23 @@ which pops \verb|n| elements from the stack.
1789\verb|lua_pushvalue| pushes onto the stack a \emph{copy} of the element 1926\verb|lua_pushvalue| pushes onto the stack a \emph{copy} of the element
1790at the given index. 1927at the given index.
1791\verb|lua_remove| removes the element at the given position, 1928\verb|lua_remove| removes the element at the given position,
1792shifting down the elements on top of that position to fill in the gap. 1929shifting down the elements above that position to fill the gap.
1793\verb|lua_insert| moves the top element into the given position, 1930\verb|lua_insert| moves the top element into the given position,
1794shifting up the elements on top of that position to open space. 1931shifting up the elements above that position to open space.
1795These functions accept only valid indices. 1932These functions accept only valid indices.
1796As an example, if the stack starts as \verb|10 20 30 40 50| 1933
1797(from bottom to top), 1934As an example, if the stack starts as \verb|10 20 30 40 50*|
1935(from bottom to top; the \verb|*| marks the top),
1798then 1936then
1799\begin{verbatim} 1937\begin{verbatim}
1800 lua_pushvalue(L, 3) --> 10 20 30 40 50 30 1938 lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
1801 lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30 1939 lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
1802 lua_remove(L, -3) --> 10 20 30 40 30 30 1940 lua_remove(L, -3) --> 10 20 30 40 30 30*
1803 lua_remove(L, 6) --> 10 20 30 40 30 1941 lua_remove(L, 6) --> 10 20 30 40 30*
1804 lua_insert(L, 1) --> 30 10 20 30 40 1942 lua_insert(L, 1) --> 30 10 20 30 40*
1805 lua_insert(L, -1) --> 30 10 20 30 40 (no effect) 1943 lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
1806 lua_settop(L, -3) --> 30 10 20 1944 lua_settop(L, -3) --> 30 10 20*
1807 lua_settop(L, 6) --> 30 10 20 nil nil nil 1945 lua_settop(L, 6) --> 30 10 20 nil nil nil*
1808\end{verbatim} 1946\end{verbatim}
1809 1947
1810 1948
@@ -1833,7 +1971,8 @@ These functions can be called with any acceptable index.
1833\verb|lua_tag| returns the tag of a value in the stack, 1971\verb|lua_tag| returns the tag of a value in the stack,
1834or \verb|LUA_TNONE| for a non-valid index 1972or \verb|LUA_TNONE| for a non-valid index
1835(that is, if that stack position is ``empty''). 1973(that is, if that stack position is ``empty'').
1836The tags for the basic types are the following constants: 1974The tags for the basic types are the following constants
1975defined in \verb|lua.h|:
1837\verb|LUA_TNIL|, 1976\verb|LUA_TNIL|,
1838\verb|LUA_TNUMBER|, 1977\verb|LUA_TNUMBER|,
1839\verb|LUA_TSTRING|, 1978\verb|LUA_TSTRING|,
@@ -1841,9 +1980,9 @@ The tags for the basic types are the following constants:
1841\verb|LUA_TFUNCTION|, 1980\verb|LUA_TFUNCTION|,
1842\verb|LUA_TUSERDATA|. 1981\verb|LUA_TUSERDATA|.
1843\verb|lua_rawtag| is similar to \verb|lua_tag|, 1982\verb|lua_rawtag| is similar to \verb|lua_tag|,
1844but it returns the tag of the basic (raw) type of a value. 1983but returns the tag of the basic (raw) type of a value.
1845\verb|lua_type| is similar to \verb|lua_tag|, 1984\verb|lua_type| is similar to \verb|lua_tag|,
1846but it returns the type name of the given value. 1985but returns the type name of the given value.
1847 1986
1848The \verb|lua_is*| functions return~1 if the object is compatible 1987The \verb|lua_is*| functions return~1 if the object is compatible
1849with the given type, and 0 otherwise. 1988with the given type, and 0 otherwise.
@@ -1862,15 +2001,17 @@ The API also has functions to compare two values in the stack:
1862 int lua_lessthan (lua_State *L, int index1, int index2); 2001 int lua_lessthan (lua_State *L, int index1, int index2);
1863\end{verbatim} 2002\end{verbatim}
1864\DefAPI{lua_equal} \DefAPI{lua_lessthan} 2003\DefAPI{lua_equal} \DefAPI{lua_lessthan}
1865These functions are equivalent to their counterparts in Lua. 2004These functions are equivalent to their counterparts in Lua \see{rel-ops}.
1866Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event| 2005Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event|
1867described in \See{tag-method}. 2006described in \See{tag-method}.
1868Both functions return 0 if any of the indices are non-valid. 2007Both functions return 0 if any of the indices are non-valid.
1869 2008
2009\subsection{Getting Values from the Stack}
2010
1870To translate a value in the stack to a specific C~type, 2011To translate a value in the stack to a specific C~type,
1871you can use the following conversion functions: 2012you can use the following conversion functions:
1872\begin{verbatim} 2013\begin{verbatim}
1873 double lua_tonumber (lua_State *L, int index); 2014 lua_Number lua_tonumber (lua_State *L, int index);
1874 const char *lua_tostring (lua_State *L, int index); 2015 const char *lua_tostring (lua_State *L, int index);
1875 size_t lua_strlen (lua_State *L, int index); 2016 size_t lua_strlen (lua_State *L, int index);
1876 lua_CFunction lua_tocfunction (lua_State *L, int index); 2017 lua_CFunction lua_tocfunction (lua_State *L, int index);
@@ -1882,28 +2023,31 @@ These functions can be called with any acceptable index.
1882When called with a non-valid index, 2023When called with a non-valid index,
1883they act as if the given value had an incorrect type. 2024they act as if the given value had an incorrect type.
1884 2025
1885\verb|lua_tonumber| converts the value at the given index 2026\verb|lua_tonumber| converts the Lua value at the given index
1886to a floating-point number. 2027to a number (by default, \verb|lua_Number| is \verb|double|).
1887This value must be a number or a string convertible to number 2028\DefAPI{lua_Number}
2029The Lua value must be a number or a string convertible to number
1888\see{coercion}; otherwise, \verb|lua_tonumber| returns~0. 2030\see{coercion}; otherwise, \verb|lua_tonumber| returns~0.
1889 2031
1890\verb|lua_tostring| converts a Lua value to a string 2032\verb|lua_tostring| converts the Lua value at the given index to a string
1891(\verb|const char*|). 2033(\verb|const char*|).
1892This value must be a string or a number; 2034The Lua value must be a string or a number;
1893otherwise, the function returns \verb|NULL|. 2035otherwise, the function returns \verb|NULL|.
1894If the value is a number, 2036If the value is a number,
1895\verb|lua_tostring| also changes the 2037then \verb|lua_tostring| also
1896actual value in the stack to a string. 2038\emph{changes the actual value in the stack to a string}.
1897This function returns a pointer to a string inside the Lua environment. 2039This change confuses \verb|lua_next| when \verb|lua_tostring| is applied to keys.
1898This pointer is always fully aligned. 2040\verb|lua_tostring| returns a fully aligned pointer to a string inside the Lua environment.
1899The strings always have a zero (\verb|'\0'|) 2041This string always has a zero (\verb|'\0'|)
1900after their last character (as in C), 2042after its last character (as in~C),
1901but may contain other zeros in their body. 2043but may contain other zeros in its body.
1902If you do not know whether a string may contain zeros, 2044If you do not know whether a string may contain zeros,
1903you can use \verb|lua_strlen| to get its actual length. 2045you can use \verb|lua_strlen| to get its actual length.
1904Because Lua has garbage collection, 2046Because Lua has garbage collection,
1905there is no guarantee that the pointer returned by \verb|lua_tostring| 2047there is no guarantee that the pointer returned by \verb|lua_tostring|
1906will be valid after the respective value is removed from the stack. 2048will be valid after the corresponding value is removed from the stack.
2049So, if you need the string after the current function returns,
2050then you should duplicate it (or lock it; see \See{lock}).
1907 2051
1908\verb|lua_tocfunction| converts a value in the stack to a C~function. 2052\verb|lua_tocfunction| converts a value in the stack to a C~function.
1909This value must be a C~function; 2053This value must be a C~function;
@@ -1916,12 +2060,12 @@ otherwise, \verb|lua_touserdata| returns \verb|NULL|.
1916 2060
1917 2061
1918 2062
1919\subsection{Pushing values onto the Stack} 2063\subsection{Pushing Values onto the Stack}
1920 2064
1921The API has the following functions to 2065The API has the following functions to
1922push C~values onto the stack: 2066push C~values onto the stack:
1923\begin{verbatim} 2067\begin{verbatim}
1924 void lua_pushnumber (lua_State *L, double n); 2068 void lua_pushnumber (lua_State *L, lua_Number n);
1925 void lua_pushlstring (lua_State *L, const char *s, size_t len); 2069 void lua_pushlstring (lua_State *L, const char *s, size_t len);
1926 void lua_pushstring (lua_State *L, const char *s); 2070 void lua_pushstring (lua_State *L, const char *s);
1927 void lua_pushnil (lua_State *L); 2071 void lua_pushnil (lua_State *L);
@@ -1937,13 +2081,15 @@ In particular, \verb|lua_pushlstring| and \verb|lua_pushstring|
1937make an \emph{internal copy} of the given string. 2081make an \emph{internal copy} of the given string.
1938\verb|lua_pushstring| can only be used to push proper C~strings 2082\verb|lua_pushstring| can only be used to push proper C~strings
1939(that is, strings that end with a zero and do not contain embedded zeros); 2083(that is, strings that end with a zero and do not contain embedded zeros);
1940otherwise you should use the more general \verb|lua_pushlstring|, 2084otherwise, you should use the more general \verb|lua_pushlstring|,
1941which accepts an explicit size. 2085which accepts an explicit size.
1942 2086
1943 2087
1944\subsection{Garbage Collection API}\label{GC-API} 2088\subsection{Controlling Garbage Collection}\label{GC-API}
1945 2089
1946Lua uses two numbers to control its garbage collection \see{GC}. 2090Lua uses two numbers to control its garbage collection:
2091the \emph{count} and the \emph{threshold}
2092\see{GC}.
1947You can access the current values of these two numbers through the 2093You can access the current values of these two numbers through the
1948following functions: 2094following functions:
1949\begin{verbatim} 2095\begin{verbatim}
@@ -1961,9 +2107,12 @@ Again, the \verb|newthreshold| value is given in Kbytes.
1961When you call this function, 2107When you call this function,
1962Lua sets the new threshold and checks it against the byte counter. 2108Lua sets the new threshold and checks it against the byte counter.
1963If the new threshold is smaller than the byte counter, 2109If the new threshold is smaller than the byte counter,
1964then Lua immediately runs the garbage collector; 2110then Lua immediately runs the garbage collector.
1965after the collection, 2111In particular
2112\verb|lua_setgcthreshold(L,0)| forces a garbage collectiion.
2113After the collection,
1966a new threshold is set according to the previous rule. 2114a new threshold is set according to the previous rule.
2115%% TODO: What `previous rule'?
1967 2116
1968If you want to change the adaptive behavior of the garbage collector, 2117If you want to change the adaptive behavior of the garbage collector,
1969you can use the garbage-collection tag method for \nil\ % 2118you can use the garbage-collection tag method for \nil\ %
@@ -1975,8 +2124,8 @@ to set your own threshold
1975 2124
1976You can create new userdata with the following functions: 2125You can create new userdata with the following functions:
1977\begin{verbatim} 2126\begin{verbatim}
1978 void *lua_newuserdata (lua_State *L, size_t size); 2127 void *lua_newuserdata (lua_State *L, size_t size);
1979 void lua_newuserdatabox (lua_State *L, void *u); 2128 void lua_newuserdatabox (lua_State *L, void *u);
1980\end{verbatim} 2129\end{verbatim}
1981\DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox} 2130\DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox}
1982The first function, \verb|lua_newuserdata|, 2131The first function, \verb|lua_newuserdata|,
@@ -1988,7 +2137,7 @@ gets a pointer and pushes on the stack a new userdata
1988with that pointer. 2137with that pointer.
1989In this case, Lua does not care about the pointer's value. 2138In this case, Lua does not care about the pointer's value.
1990By default, all userdata are created with a standard tag, 2139By default, all userdata are created with a standard tag,
1991\verb|LUA_TUSERDATA|. 2140\verb|LUA_TUSERDATA|, which is defined in \verb|lua.h|.
1992 2141
1993When Lua collects a userdata created by \verb|lua_newuserdata|, 2142When Lua collects a userdata created by \verb|lua_newuserdata|,
1994it automatically frees its corresponding memory. 2143it automatically frees its corresponding memory.
@@ -2005,9 +2154,10 @@ User-defined types are created with the function
2005 int lua_newtype (lua_State *L, const char *name, int basictype); 2154 int lua_newtype (lua_State *L, const char *name, int basictype);
2006\end{verbatim} 2155\end{verbatim}
2007\DefAPI{lua_newtype} 2156\DefAPI{lua_newtype}
2157where
2008\verb|name| is the name of the new type, 2158\verb|name| is the name of the new type,
2009and \verb|basictype| is the basic type for objects with this new type, 2159and \verb|basictype| is the basic type for objects with this new type,
2010which can be \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|. 2160which can be either \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|.
2011 2161
2012The function \verb|lua_settag| changes the tag (i.e., the type) of 2162The function \verb|lua_settag| changes the tag (i.e., the type) of
2013the object on top of the stack (without popping it): 2163the object on top of the stack (without popping it):
@@ -2016,6 +2166,7 @@ the object on top of the stack (without popping it):
2016\end{verbatim} 2166\end{verbatim}
2017\DefAPI{lua_settag} 2167\DefAPI{lua_settag}
2018The given \verb|tag| must be a user-defined tag, 2168The given \verb|tag| must be a user-defined tag,
2169%% TODO: nao pode voltar ao tag original, ie basico?
2019and the basic type of the object must be the basic type for that 2170and the basic type of the object must be the basic type for that
2020tag (userdata or table). 2171tag (userdata or table).
2021 2172
@@ -2028,9 +2179,9 @@ and a type name to a tag:
2028\DefAPI{lua_name2tag}\DefAPI{lua_tag2name} 2179\DefAPI{lua_name2tag}\DefAPI{lua_tag2name}
2029 2180
2030 2181
2031\subsection{Executing Lua Code}\label{luado} 2182\subsection{Executing Lua Chunks}\label{luado}
2032A host program can execute Lua chunks written in a file or in a string 2183A host program can execute Lua chunks written in a file or in a string
2033by using the following functions:% 2184by using the following functions:
2034\begin{verbatim} 2185\begin{verbatim}
2035 int lua_dofile (lua_State *L, const char *filename); 2186 int lua_dofile (lua_State *L, const char *filename);
2036 int lua_dostring (lua_State *L, const char *string); 2187 int lua_dostring (lua_State *L, const char *string);
@@ -2039,7 +2190,9 @@ by using the following functions:%
2039\end{verbatim} 2190\end{verbatim}
2040\DefAPI{lua_dofile}\DefAPI{lua_dostring}\DefAPI{lua_dobuffer}% 2191\DefAPI{lua_dofile}\DefAPI{lua_dostring}\DefAPI{lua_dobuffer}%
2041These functions return 2192These functions return
20420 in case of success, or one of the following error codes if they fail: 21930 in case of success, or one of the following error codes
2194(defined in \verb|lua.h|)
2195if they fail:
2043\begin{itemize} 2196\begin{itemize}
2044\item \IndexAPI{LUA_ERRRUN} --- 2197\item \IndexAPI{LUA_ERRRUN} ---
2045error while running the chunk. 2198error while running the chunk.
@@ -2059,7 +2212,6 @@ check \verb|errno|,
2059call \verb|strerror|, 2212call \verb|strerror|,
2060or call \verb|perror| to tell the user what went wrong. 2213or call \verb|perror| to tell the user what went wrong.
2061\end{itemize} 2214\end{itemize}
2062These constants are defined in \verb|lua.h|.
2063 2215
2064When called with argument \verb|NULL|, 2216When called with argument \verb|NULL|,
2065\verb|lua_dofile| executes the \verb|stdin| stream. 2217\verb|lua_dofile| executes the \verb|stdin| stream.
@@ -2080,6 +2232,7 @@ These functions push onto the stack
2080any values eventually returned by the chunk. 2232any values eventually returned by the chunk.
2081A chunk may return any number of values; 2233A chunk may return any number of values;
2082Lua takes care that these values fit into the stack space, 2234Lua takes care that these values fit into the stack space,
2235%% TODO: how? o que acontece se nao da'?
2083but after the call the responsibility is back to you. 2236but after the call the responsibility is back to you.
2084If you need to push other elements after calling any of these functions, 2237If you need to push other elements after calling any of these functions,
2085and you want to ``play safe'', 2238and you want to ``play safe'',
@@ -2088,7 +2241,7 @@ with \verb|lua_stackspace|
2088or remove the returned elements 2241or remove the returned elements
2089from the stack (if you do not need them). 2242from the stack (if you do not need them).
2090For instance, the following code 2243For instance, the following code
2091loads a chunk in a file and discards all results returned by this chunk, 2244executes a chunk from a file and discards all results returned by this chunk,
2092leaving the stack as it was before the call: 2245leaving the stack as it was before the call:
2093\begin{verbatim} 2246\begin{verbatim}
2094 { 2247 {
@@ -2098,8 +2251,18 @@ leaving the stack as it was before the call:
2098 } 2251 }
2099\end{verbatim} 2252\end{verbatim}
2100 2253
2254\subsection{Loading Lua Chunks}
2255You can load Lua chunks without executing them with
2256\begin{verbatim}
2257 int lua_loadfile (lua_State *L, const char *filename);
2258 int lua_loadbuffer (lua_State *L, const char *buff,
2259 size_t size, const char *name);
2260\end{verbatim}
2261The compiled chunk is left as a function on top of the stack.
2262The return values are the same as those of
2263\verb|lua_dofile| and \verb|lua_dobuffer|.
2101 2264
2102\subsection{Manipulating Global Variables in Lua} 2265\subsection{Manipulating Global Variables}
2103 2266
2104To read the value of a global Lua variable, 2267To read the value of a global Lua variable,
2105you call 2268you call
@@ -2108,6 +2271,8 @@ you call
2108\end{verbatim} 2271\end{verbatim}
2109\DefAPI{lua_getglobal} 2272\DefAPI{lua_getglobal}
2110which pushes onto the stack the value of the given variable. 2273which pushes onto the stack the value of the given variable.
2274(The string \verb|varname| does not need to be a
2275syntactically valid variable name.)
2111As in Lua, this function may trigger a tag method 2276As in Lua, this function may trigger a tag method
2112for the ``getglobal'' event \see{tag-method}. 2277for the ``getglobal'' event \see{tag-method}.
2113To read the real value of a global variable, 2278To read the real value of a global variable,
@@ -2122,6 +2287,8 @@ you call
2122\end{verbatim} 2287\end{verbatim}
2123\DefAPI{lua_setglobal} 2288\DefAPI{lua_setglobal}
2124which pops from the stack the value to be stored in the given variable. 2289which pops from the stack the value to be stored in the given variable.
2290(The string \verb|varname| does not need to be a
2291syntactically valid variable name.)
2125As in Lua, this function may trigger a tag method 2292As in Lua, this function may trigger a tag method
2126for the ``setglobal'' event \see{tag-method}. 2293for the ``setglobal'' event \see{tag-method}.
2127To set the real value of a global variable, 2294To set the real value of a global variable,
@@ -2144,19 +2311,30 @@ you call
2144\DefAPI{lua_setglobals} 2311\DefAPI{lua_setglobals}
2145The table to be used is popped from the stack. 2312The table to be used is popped from the stack.
2146 2313
2147\subsection{Manipulating Tables in Lua} 2314\subsection{Manipulating Tables}
2148Lua tables can also be manipulated through the API.
2149 2315
2150To read a value from a table, call 2316Tables are created by calling
2317The function
2318\begin{verbatim}
2319 void lua_newtable (lua_State *L);
2320\end{verbatim}
2321\DefAPI{lua_newtable}
2322This function creates a new, empty table and pushes it onto the stack.
2323
2324To read a value from a table that resides somewhere in the stack,
2325call
2151\begin{verbatim} 2326\begin{verbatim}
2152 void lua_gettable (lua_State *L, int index); 2327 void lua_gettable (lua_State *L, int index);
2153\end{verbatim} 2328\end{verbatim}
2154\DefAPI{lua_gettable} 2329\DefAPI{lua_gettable}
2155where \verb|index| refers to the table. 2330where \verb|index| refers to the table.
2156\verb|lua_gettable| pops a key from the stack, 2331\verb|lua_gettable| pops a key from the stack
2157and returns (on the stack) the contents of the table at that key. 2332and returns (on the stack) the contents of the table at that key.
2158As in Lua, this operation may trigger a tag method 2333The table is left where it was in the stack;
2159for the ``gettable'' event. 2334this is convenient for getting multiple values from a table.
2335
2336As in Lua, this function may trigger a tag method
2337for the ``gettable'' event \see{tag-method}.
2160To get the real value of any table key, 2338To get the real value of any table key,
2161without invoking any tag method, 2339without invoking any tag method,
2162use the \emph{raw} version: 2340use the \emph{raw} version:
@@ -2175,6 +2353,9 @@ and then call
2175\DefAPI{lua_settable} 2353\DefAPI{lua_settable}
2176where \verb|index| refers to the table. 2354where \verb|index| refers to the table.
2177\verb|lua_settable| pops from the stack both the key and the value. 2355\verb|lua_settable| pops from the stack both the key and the value.
2356The table is left where it was in the stack;
2357this is convenient for setting multiple values in a table.
2358
2178As in Lua, this operation may trigger a tag method 2359As in Lua, this operation may trigger a tag method
2179for the ``settable'' event. 2360for the ``settable'' event.
2180To set the real value of any table index, 2361To set the real value of any table index,
@@ -2185,12 +2366,50 @@ use the \emph{raw} version:
2185\end{verbatim} 2366\end{verbatim}
2186\DefAPI{lua_rawset} 2367\DefAPI{lua_rawset}
2187 2368
2188Finally, the function 2369You can traverse a table with the function
2189\begin{verbatim} 2370\begin{verbatim}
2190 void lua_newtable (lua_State *L); 2371 int lua_next (lua_State *L, int index);
2191\end{verbatim} 2372\end{verbatim}
2192\DefAPI{lua_newtable} 2373\DefAPI{lua_next}
2193creates a new, empty table and pushes it onto the stack. 2374where \verb|index| refers to the table to be traversed.
2375The function pops a key from the stack,
2376and pushes a key-value pair from the table
2377(the ``next'' pair after the given key).
2378If there are no more elements, then \verb|lua_next| returns 0
2379(and pushes nothing).
2380Use a \nil\ key to signal the start of a traversal.
2381
2382A typical traversal looks like this:
2383\begin{verbatim}
2384 /* table is in the stack at index `t' */
2385 lua_pushnil(L); /* first key */
2386 while (lua_next(L, t) != 0) {
2387 /* `key' is at index -2 and `value' at index -1 */
2388 printf("%s - %s\n",
2389 lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
2390 lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */
2391 }
2392\end{verbatim}
2393
2394NOTE:
2395Do not call \verb|lua_tostring| on a key,
2396unless you know the key is actually a string.
2397Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
2398this confuses \verb|lua_next|.
2399
2400The following functions control the weak mode of a table:
2401\begin{verbatim}
2402 void lua_setweakmode (lua_State *L, int mode);
2403 int lua_getweakmode (lua_State *L, int index);
2404\end{verbatim}
2405\DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode}
2406Both functions operate over the table at the top of the stack.
2407Modes are described as bit sets, so that
2408\verb|LUA_WEAK_KEY| means weak keys,
2409\verb|LUA_WEAK_VALUE| means weak values,
2410\verb"LUA_WEAK_KEY | LUA_WEAK_VALUE" means both,
2411and zero means none.
2412
2194 2413
2195\subsection{Using Tables as Arrays} 2414\subsection{Using Tables as Arrays}
2196The API has functions that help to use Lua tables as arrays, 2415The API has functions that help to use Lua tables as arrays,
@@ -2210,15 +2429,15 @@ at stack position \verb|index|.
2210 2429
2211\verb|lua_rawseti| sets the value of the \M{n}-th element of the table 2430\verb|lua_rawseti| sets the value of the \M{n}-th element of the table
2212at stack position \verb|index| to the value at the top of the stack, 2431at stack position \verb|index| to the value at the top of the stack,
2213removing the value from the stack. 2432removing this value from the stack.
2214 2433
2215\verb|lua_getn| returns the number of elements in the table 2434\verb|lua_getn| returns the number of elements in the table
2216at stack position \verb|index|. 2435at stack position \verb|index|.
2217This number is the value of the table field \verb|n|, 2436This number is the value of the table field \verb|n|,
2218if it has a numeric value, 2437if it has a numeric value,
2219or the largest numerical index with a non-nil value in the table. 2438or the largest numerical index with a non-\nil\ value in the table.
2220 2439
2221\subsection{Calling Lua Functions} 2440\subsection{Calling Functions}
2222 2441
2223Functions defined in Lua 2442Functions defined in Lua
2224(and C~functions registered in Lua) 2443(and C~functions registered in Lua)
@@ -2226,7 +2445,7 @@ can be called from the host program.
2226This is done using the following protocol: 2445This is done using the following protocol:
2227First, the function to be called is pushed onto the stack; 2446First, the function to be called is pushed onto the stack;
2228then, the arguments to the function are pushed 2447then, the arguments to the function are pushed
2229\see{pushing} in \emph{direct order}, that is, the first argument is pushed first. 2448in \emph{direct order}, that is, the first argument is pushed first.
2230Finally, the function is called using 2449Finally, the function is called using
2231\begin{verbatim} 2450\begin{verbatim}
2232 int lua_call (lua_State *L, int nargs, int nresults); 2451 int lua_call (lua_State *L, int nargs, int nresults);
@@ -2235,6 +2454,7 @@ Finally, the function is called using
2235This function returns the same error codes as \verb|lua_dostring| and 2454This function returns the same error codes as \verb|lua_dostring| and
2236friends \see{luado}. 2455friends \see{luado}.
2237If you want to propagate the error, 2456If you want to propagate the error,
2457%% TODO: explain 'propagate'.
2238instead of returning an error code, 2458instead of returning an error code,
2239use 2459use
2240\begin{verbatim} 2460\begin{verbatim}
@@ -2249,23 +2469,23 @@ and the function results are pushed.
2249The number of results are adjusted to \verb|nresults|, 2469The number of results are adjusted to \verb|nresults|,
2250unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. 2470unless \verb|nresults| is \IndexAPI{LUA_MULTRET}.
2251In that case, \emph{all} results from the function are pushed. 2471In that case, \emph{all} results from the function are pushed.
2252The function results are pushed in direct order 2472The function results are pushed onto the stack in direct order
2253(the first result is pushed first), 2473(the first result is pushed first),
2254so that after the call the last result is on the top. 2474so that after the call the last result is on the top.
2255 2475
2256The following example shows how the host program may do the 2476The following example shows how the host program may do the
2257equivalent to the Lua code: 2477equivalent to the Lua code:
2258\begin{verbatim} 2478\begin{verbatim}
2259 a,b = f("how", t.x, 4) 2479 a,b = f("how", t.x, 14)
2260\end{verbatim} 2480\end{verbatim}
2261Here it is in~C: 2481Here it is in~C:
2262\begin{verbatim} 2482\begin{verbatim}
2263 lua_getglobal(L, "t"); /* global `t' (for later use) */ 2483 lua_getglobal(L, "t"); /* global `t' (for later use) */
2264 lua_getglobal(L, "f"); /* function to be called */ 2484 lua_getglobal(L, "f"); /* function to be called */
2265 lua_pushstring(L, "how"); /* 1st argument */ 2485 lua_pushstring(L, "how"); /* 1st argument */
2266 lua_pushstring(L, "x"); /* push the string `x' */ 2486 lua_pushstring(L, "x"); /* push the string "x" */
2267 lua_gettable(L, -4); /* push result of t.x (2nd arg) */ 2487 lua_gettable(L, -4); /* push result of t.x (2nd arg) */
2268 lua_pushnumber(L, 4); /* 3rd argument */ 2488 lua_pushnumber(L, 14); /* 3rd argument */
2269 lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */ 2489 lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */
2270 lua_setglobal(L, "b"); /* set global variable `b' */ 2490 lua_setglobal(L, "b"); /* set global variable `b' */
2271 lua_setglobal(L, "a"); /* set global variable `a' */ 2491 lua_setglobal(L, "a"); /* set global variable `a' */
@@ -2277,7 +2497,7 @@ This is considered good programming practice.
2277 2497
2278\medskip 2498\medskip
2279 2499
2280 2500%% TODO: mover essas 2 para algum lugar melhor.
2281Some special Lua functions have their own C~interfaces. 2501Some special Lua functions have their own C~interfaces.
2282The host program can generate a Lua error calling the function 2502The host program can generate a Lua error calling the function
2283\begin{verbatim} 2503\begin{verbatim}
@@ -2296,8 +2516,18 @@ the \verb|message| is passed to the error handler function,
2296If \verb|message| is \verb|NULL|, 2516If \verb|message| is \verb|NULL|,
2297then \verb|_ERRORMESSAGE| is not called. 2517then \verb|_ERRORMESSAGE| is not called.
2298 2518
2299\medskip 2519The function
2520\begin{verbatim}
2521 void lua_concat (lua_State *L, int n);
2522\end{verbatim}
2523\DefAPI{lua_concat}
2524concatenates the \verb|n| values at the top of the stack,
2525pops them, and leaves the result at the top;
2526\verb|n|~must be at least 2.
2527Concatenation is done following the usual semantics of Lua
2528\see{concat}.
2300 2529
2530\subsection{Manipulating Tag Methods}
2301Tag methods can be changed with 2531Tag methods can be changed with
2302\begin{verbatim} 2532\begin{verbatim}
2303 void lua_settagmethod (lua_State *L, int tag, const char *event); 2533 void lua_settagmethod (lua_State *L, int tag, const char *event);
@@ -2321,62 +2551,17 @@ to another:
2321\DefAPI{lua_copytagmethods} 2551\DefAPI{lua_copytagmethods}
2322This function returns \verb|tagto|. 2552This function returns \verb|tagto|.
2323 2553
2324\medskip
2325
2326You can traverse a table with the function
2327\begin{verbatim}
2328 int lua_next (lua_State *L, int index);
2329\end{verbatim}
2330\DefAPI{lua_next}
2331where \verb|index| refers to the table to be traversed.
2332The function pops a key from the stack,
2333and pushes a key-value pair from the table
2334(the ``next'' pair after the given key).
2335If there are no more elements, then the function returns 0
2336(and pushes nothing).
2337A typical traversal looks like this:
2338\begin{verbatim}
2339 /* table is in the stack at index `t' */
2340 lua_pushnil(L); /* first key */
2341 while (lua_next(L, t) != 0) {
2342 /* `key' is at index -2 and `value' at index -1 */
2343 printf("%s - %s\n",
2344 lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
2345 lua_pop(L, 1); /* removes `value'; keeps `index' for next iteration */
2346 }
2347\end{verbatim}
2348
2349The function
2350\begin{verbatim}
2351 void lua_concat (lua_State *L, int n);
2352\end{verbatim}
2353\DefAPI{lua_concat}
2354concatenates the \verb|n| values at the top of the stack,
2355pops them, and leaves the result at the top;
2356\verb|n|~must be at least 2.
2357Concatenation is done following the usual semantics of Lua
2358\see{concat}.
2359
2360 2554
2361\subsection{Defining C Functions} \label{LuacallC} 2555\subsection{Defining C Functions} \label{LuacallC}
2362To register a C~function to Lua, 2556Lua can be extended with functions written in~C.
2363there is the following convenience macro: 2557These functions must be of type \verb|lua_CFunction|,
2364\begin{verbatim}
2365 #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
2366 /* const char *n; */
2367 /* lua_CFunction f; */
2368\end{verbatim}
2369\DefAPI{lua_register}
2370which receives the name the function will have in Lua,
2371and a pointer to the function.
2372This pointer must have type \verb|lua_CFunction|,
2373which is defined as 2558which is defined as
2374\begin{verbatim} 2559\begin{verbatim}
2375 typedef int (*lua_CFunction) (lua_State *L); 2560 typedef int (*lua_CFunction) (lua_State *L);
2376\end{verbatim} 2561\end{verbatim}
2377\DefAPI{lua_CFunction} 2562\DefAPI{lua_CFunction}
2378that is, a pointer to a function with integer result and a single argument, 2563A C~function receives a Lua environment and returns an integer,
2379a Lua environment. 2564the number of values it has returned to Lua.
2380 2565
2381In order to communicate properly with Lua, 2566In order to communicate properly with Lua,
2382a C~function must follow the following protocol, 2567a C~function must follow the following protocol,
@@ -2394,7 +2579,7 @@ of numerical arguments and returns their average and sum:
2394\begin{verbatim} 2579\begin{verbatim}
2395 static int foo (lua_State *L) { 2580 static int foo (lua_State *L) {
2396 int n = lua_gettop(L); /* number of arguments */ 2581 int n = lua_gettop(L); /* number of arguments */
2397 double sum = 0; 2582 lua_Number sum = 0;
2398 int i; 2583 int i;
2399 for (i = 1; i <= n; i++) { 2584 for (i = 1; i <= n; i++) {
2400 if (!lua_isnumber(L, i)) 2585 if (!lua_isnumber(L, i))
@@ -2406,11 +2591,25 @@ of numerical arguments and returns their average and sum:
2406 return 2; /* number of results */ 2591 return 2; /* number of results */
2407 } 2592 }
2408\end{verbatim} 2593\end{verbatim}
2409This function may be registered in Lua as `\verb|average|' by calling 2594
2595To register a C~function to Lua,
2596there is the following convenience macro:
2597\begin{verbatim}
2598 #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
2599 /* const char *n; */
2600 /* lua_CFunction f; */
2601\end{verbatim}
2602\DefAPI{lua_register}
2603which receives the name the function will have in Lua,
2604and a pointer to the function.
2605Thus,
2606the C~function `\verb|foo|' above may be registered in Lua as `\verb|average|'
2607by calling
2410\begin{verbatim} 2608\begin{verbatim}
2411 lua_register(L, "average", foo); 2609 lua_register(L, "average", foo);
2412\end{verbatim} 2610\end{verbatim}
2413 2611
2612\subsection{Defining C Closures}
2414 2613
2415When a C~function is created, 2614When a C~function is created,
2416it is possible to associate some \emph{upvalues} to it 2615it is possible to associate some \emph{upvalues} to it
@@ -2440,12 +2639,13 @@ This makes it easy to get the upvalues without knowing how many arguments
2440the function received (recall that functions in Lua can receive any number of 2639the function received (recall that functions in Lua can receive any number of
2441arguments): The \M{i}-th upvalue is in the stack at index \Math{i-(n+1)}, 2640arguments): The \M{i}-th upvalue is in the stack at index \Math{i-(n+1)},
2442where \M{n} is the number of upvalues. 2641where \M{n} is the number of upvalues.
2642(A C~function that uses upvalues must know beforehand how many it expects.)
2443 2643
2444For more examples of C~functions and closures, see files 2644For examples of C~functions and closures, see files
2445\verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c| 2645\verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c|
2446in the official Lua distribution. 2646in the official Lua distribution.
2447 2647
2448\subsection{References to Lua Objects} 2648\subsection{References to Lua Values} \label{lock}
2449 2649
2450If the C~code needs to keep a Lua value 2650If the C~code needs to keep a Lua value
2451outside the life span of a C~function, 2651outside the life span of a C~function,
@@ -2463,9 +2663,11 @@ the stack, creates a reference to it,
2463and returns this reference. 2663and returns this reference.
2464For a \nil\ value, 2664For a \nil\ value,
2465the reference is always \verb|LUA_REFNIL|.\DefAPI{LUA_REFNIL} 2665the reference is always \verb|LUA_REFNIL|.\DefAPI{LUA_REFNIL}
2666%% TODO: why LUA_REFNIL? pode-se chamar lua_getref(L,LUA_REFNIL)?
2466(\verb|lua.h| also defines a constant \verb|LUA_NOREF| \DefAPI{LUA_NOREF} 2667(\verb|lua.h| also defines a constant \verb|LUA_NOREF| \DefAPI{LUA_NOREF}
2467that 2668that
2468is different from any valid reference.) 2669is different from any valid reference.)
2670%% TODO: give example of use of LUA_NOREF
2469If \verb|lock| is not zero, then the object is \emph{locked}: 2671If \verb|lock| is not zero, then the object is \emph{locked}:
2470this means the object will not be garbage collected. 2672this means the object will not be garbage collected.
2471\emph{Unlocked references may be garbage collected}. 2673\emph{Unlocked references may be garbage collected}.
@@ -2481,12 +2683,13 @@ it should be released with a call to \verb|lua_unref|.
2481 2683
2482 2684
2483\subsubsection*{Registry} 2685\subsubsection*{Registry}
2686%% TODO: nao precisa de secao propria? explicar melhor o uso.
2484 2687
2485When Lua starts, it registers a table at position 2688When Lua starts, it registers a table at position
2486\IndexAPI{LUA_REFREGISTRY}. 2689\IndexAPI{LUA_REFREGISTRY}.
2487It can be accessed through the macro 2690It can be accessed through the macro
2488\begin{verbatim} 2691\begin{verbatim}
2489 #define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY) 2692 #define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY)
2490\end{verbatim} 2693\end{verbatim}
2491\DefAPI{lua_getregistry} 2694\DefAPI{lua_getregistry}
2492This table can be used by C~libraries as a general registry mechanism. 2695This table can be used by C~libraries as a general registry mechanism.
@@ -2495,37 +2698,237 @@ as long as it chooses a key different from other libraries.
2495 2698
2496 2699
2497 2700
2498\subsection{Weak Tables} 2701%------------------------------------------------------------------------------
2702\section{The Debug Interface} \label{debugI}
2703
2704Lua has no built-in debugging facilities.
2705Instead, it offers a special interface,
2706by means of functions and \emph{hooks},
2707which allows the construction of different
2708kinds of debuggers, profilers, and other tools
2709that need ``inside information'' from the interpreter.
2710This interface is declared in \verb|luadebug.h|.
2711
2712\subsection{Stack and Function Information}
2713
2714The main function to get information about the interpreter stack is
2715\begin{verbatim}
2716 int lua_getstack (lua_State *L, int level, lua_Debug *ar);
2717\end{verbatim}
2718\DefAPI{lua_getstack}
2719This function fills parts of a \verb|lua_Debug| structure with
2720an identification of the \emph{activation record}
2721of the function executing at a given level.
2722Level~0 is the current running function,
2723whereas level \Math{n+1} is the function that has called level \Math{n}.
2724Usually, \verb|lua_getstack| returns 1;
2725when called with a level greater than the stack depth,
2726it returns 0.
2499 2727
2500The following constants and functions control the weak mode of a table: 2728The structure \verb|lua_Debug| is used to carry different pieces of
2729information about an active function:
2501\begin{verbatim} 2730\begin{verbatim}
2502 #define LUA_WEAK_KEY ... 2731 typedef struct lua_Debug {
2503 #define LUA_WEAK_VALUE ... 2732 const char *event; /* "call", "return" */
2733 int currentline; /* (l) */
2734 const char *name; /* (n) */
2735 const char *namewhat; /* (n) global, tag method, local, field */
2736 int nups; /* (u) number of upvalues */
2737 int linedefined; /* (S) */
2738 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */
2739 const char *source; /* (S) */
2740 char short_src[LUA_IDSIZE]; /* (S) */
2741
2742 /* private part */
2743 ...
2744 } lua_Debug;
2504\end{verbatim} 2745\end{verbatim}
2746\DefAPI{lua_Debug}
2747\verb|lua_getstack| fills only the private part
2748of this structure, for future use.
2749To fill the other fields of \verb|lua_Debug| with useful information,
2750call
2505\begin{verbatim} 2751\begin{verbatim}
2506 void lua_setweakmode (lua_State *L, int mode); 2752 int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
2507 int lua_getweakmode (lua_State *L, int index);
2508\end{verbatim} 2753\end{verbatim}
2509\DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode} 2754\DefAPI{lua_getinfo}
2510Both functions operate over the table at the top of the stack. 2755This function returns 0 on error
2511Modes are described as bit sets, so that 2756(for instance, an invalid option in \verb|what|).
2512\verb|LUA_WEAK_KEY| means weak keys, 2757Each character in the string \verb|what|
2513\verb|LUA_WEAK_VALUE| means weak values, 2758selects some fields of \verb|ar| to be filled,
2514\verb|LUA_WEAK_KEY | LUA_WEAK_VALUE| means both, 2759as indicated by the letter in parentheses in the definition of \verb|lua_Debug|
2515and zero means none. 2760above:
2761`\verb|S|' fills in the fields \verb|source|, \verb|linedefined|,
2762and \verb|what|;
2763`\verb|l|' fills in the field \verb|currentline|, etc.
2764Moreover, `\verb|f|' pushes onto the stack the function that is
2765running at the given level.
2766
2767To get information about a function that is not active (that is,
2768it is not in the stack),
2769you push the function onto the stack,
2770and start the \verb|what| string with the character `\verb|>|'.
2771For instance, to know in which line a function \verb|f| was defined,
2772you can write
2773\begin{verbatim}
2774 lua_Debug ar;
2775 lua_getglobal(L, "f");
2776 lua_getinfo(L, ">S", &ar);
2777 printf("%d\n", ar.linedefined);
2778\end{verbatim}
2779The fields of \verb|lua_Debug| have the following meaning:
2780\begin{description}\leftskip=20pt
2781
2782\item[source]
2783If the function was defined in a string,
2784then \verb|source| is that string;
2785if the function was defined in a file,
2786then \verb|source| starts with a \verb|@| followed by the file name.
2787
2788\item[short\_src]
2789A ``printable'' version of \verb|source|, to be used in error messages.
2790
2791\item[linedefined]
2792the line number where the definition of the function starts.
2516 2793
2794\item[what] the string \verb|"Lua"| if this is a Lua function,
2795\verb|"C"| if this is a C~function,
2796or \verb|"main"| if this is the main part of a chunk.
2517 2797
2518\section{Standard Libraries} 2798\item[currentline]
2799the current line where the given function is executing.
2800When no line information is available,
2801\verb|currentline| is set to \Math{-1}.
2802
2803\item[name]
2804a reasonable name for the given function.
2805Because functions in Lua are first class values,
2806they do not have a fixed name:
2807Some functions may be the value of many global variables,
2808while others may be stored only in a table field.
2809The \verb|lua_getinfo| function checks whether the given
2810function is a tag method or the value of a global variable.
2811If the given function is a tag method,
2812then \verb|name| points to the event name.
2813%% TODO: mas qual o tag? Agora que temos tipos com nome, seria util saber
2814%% o tipo de TM. Em particular para mensagens de erro.
2815If the given function is the value of a global variable,
2816then \verb|name| points to the variable name.
2817If the given function is neither a tag method nor a global variable,
2818then \verb|name| is set to \verb|NULL|.
2819
2820\item[namewhat]
2821Explains the previous field.
2822If the function is a global variable,
2823\verb|namewhat| is \verb|"global"|;
2824if the function is a tag method,
2825\verb|namewhat| is \verb|"tag-method"|;
2826otherwise, \verb|namewhat| is \verb|""| (the empty string).
2827
2828\item[nups]
2829Number of upvalues of the function.
2830
2831\end{description}
2832
2833
2834\subsection{Manipulating Local Variables}
2835
2836For the manipulation of local variables,
2837\verb|luadebug.h| uses indices:
2838The first parameter or local variable has index~1, and so on,
2839until the last active local variable.
2840
2841The following functions allow the manipulation of the
2842local variables of a given activation record:
2843\begin{verbatim}
2844 const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
2845 const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
2846\end{verbatim}
2847\DefAPI{lua_getlocal}\DefAPI{lua_setlocal}
2848The parameter \verb|ar| must be a valid activation record,
2849filled by a previous call to \verb|lua_getstack| or
2850given as argument to a hook \see{sub-hooks}.
2851\verb|lua_getlocal| gets the index \verb|n| of a local variable,
2852pushes its value onto the stack,
2853and returns its name.
2854%% TODO: why return name?
2855\verb|lua_setlocal| assigns the value at the top of the stack
2856to the variable and returns its name.
2857Both functions return \verb|NULL| on failure,
2858that is
2859when the index is greater than
2860the number of active local variables.
2861
2862As an example, the following function lists the names of all
2863local variables for a function at a given level of the stack:
2864\begin{verbatim}
2865 int listvars (lua_State *L, int level) {
2866 lua_Debug ar;
2867 int i = 1;
2868 const char *name;
2869 if (lua_getstack(L, level, &ar) == 0)
2870 return 0; /* failure: no such level in the stack */
2871 while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
2872 printf("%s\n", name);
2873 lua_pop(L, 1); /* remove variable value */
2874 }
2875 return 1;
2876 }
2877\end{verbatim}
2878
2879
2880\subsection{Hooks}\label{sub-hooks}
2881
2882The Lua interpreter offers two hooks for debugging purposes:
2883a \emph{call} hook and a \emph{line} hook.
2884Both have type \verb|lua_Hook|, defined as follows:
2885\begin{verbatim}
2886 typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
2887\end{verbatim}
2888\DefAPI{lua_Hook}
2889You can set the hooks with the following functions:
2890\begin{verbatim}
2891 lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
2892 lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
2893\end{verbatim}
2894\DefAPI{lua_setcallhook}\DefAPI{lua_setlinehook}
2895A hook is disabled when its value is \verb|NULL|,
2896which is the initial value of both hooks.
2897The functions \verb|lua_setcallhook| and \verb|lua_setlinehook|
2898set their corresponding hooks and return their previous values.
2899
2900The call hook is called whenever the
2901interpreter enters or leaves a function.
2902The \verb|event| field of \verb|ar| has the strings \verb|"call"|
2903or \verb|"return"|.
2904This \verb|ar| can then be used in calls to \verb|lua_getinfo|,
2905\verb|lua_getlocal|, and \verb|lua_setlocal|
2906to get more information about the function and to manipulate its
2907local variables.
2908
2909The line hook is called every time the interpreter changes
2910the line of code it is executing.
2911The \verb|event| field of \verb|ar| has the string \verb|"line"|,
2912and the \verb|currentline| field has the line number.
2913Again, you can use this \verb|ar| in other calls to the debug API.
2914
2915While Lua is running a hook, it disables other calls to hooks.
2916Therefore, if a hook calls Lua to execute a function or a chunk,
2917this execution ocurrs without any calls to hooks.
2918
2919
2920%------------------------------------------------------------------------------
2921\section{Standard Libraries}\label{libraries}
2519 2922
2520The standard libraries provide useful functions 2923The standard libraries provide useful functions
2521that are implemented directly through the standard API. 2924that are implemented directly through the standard C~API.
2522Therefore, they are not necessary to the language, 2925Therefore, they are not essential to the language,
2523and are provided as separate C~modules. 2926and are provided as separate C~modules.
2524Currently, Lua has the following standard libraries: 2927Currently, Lua has the following standard libraries:
2525\begin{itemize} 2928\begin{itemize}
2526\item basic library; 2929\item basic library;
2527\item string manipulation; 2930\item string manipulation;
2528\item mathematical functions (sin, log, etc); 2931\item mathematical functions (sin, log, etc.);
2529\item input and output (plus some system facilities). 2932\item input and output (plus some system facilities).
2530\end{itemize} 2933\end{itemize}
2531To have access to these libraries, 2934To have access to these libraries,
@@ -2538,14 +2941,16 @@ and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|.
2538\DefAPI{lua_mathlibopen} 2941\DefAPI{lua_mathlibopen}
2539\DefAPI{lua_iolibopen} 2942\DefAPI{lua_iolibopen}
2540 2943
2944Lua's web site has links to Lua libraries written by users.
2945
2541\subsection{Basic Functions} \label{predefined} 2946\subsection{Basic Functions} \label{predefined}
2542 2947
2543The basic library provides some core functions to Lua. 2948The basic library provides some core functions to Lua.
2544Therefore, if you do not include this library in your application, 2949If you do not include this library in your application,
2545you should check carefully whether you need to provide some alternative 2950you should check carefully whether you need to provide some alternative
2546implementation for some facilities. 2951implementation for some facilities.
2547(For instance, 2952(For instance,
2548without function \verb|_ERRORMESSAGE|, 2953without an \verb|_ERRORMESSAGE| function,
2549Lua is unable to show error messages.) 2954Lua is unable to show error messages.)
2550 2955
2551\subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert} 2956\subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert}
@@ -2607,8 +3012,6 @@ If the new threshold is smaller than the byte counter,
2607then Lua immediately runs the garbage collector \see{GC}. 3012then Lua immediately runs the garbage collector \see{GC}.
2608If \verb|limit| is absent, it defaults to zero 3013If \verb|limit| is absent, it defaults to zero
2609(thus forcing a garbage-collection cycle). 3014(thus forcing a garbage-collection cycle).
2610%\verb|collectgarbage| is equivalent to
2611%the API function \verb|lua_setgcthreshold|.
2612 3015
2613\subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}} 3016\subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}}
2614\DefLIB{copytagmethods} 3017\DefLIB{copytagmethods}
@@ -2617,8 +3020,7 @@ returns \verb|tagto|.
2617 3020
2618\subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile} 3021\subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile}
2619Receives a file name, 3022Receives a file name,
2620opens the named file, and executes its contents as a Lua chunk, 3023opens the named file, and executes its contents as a Lua chunk.
2621or as pre-compiled chunks.
2622When called without arguments, 3024When called without arguments,
2623\verb|dofile| executes the contents of the standard input (\verb|stdin|). 3025\verb|dofile| executes the contents of the standard input (\verb|stdin|).
2624If there is any error executing the file, 3026If there is any error executing the file,
@@ -2634,7 +3036,7 @@ It issues an error when called with a non-string argument.
2634\subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring} 3036\subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring}
2635Executes a given string as a Lua chunk. 3037Executes a given string as a Lua chunk.
2636If there is any error executing the string, 3038If there is any error executing the string,
2637then \verb|dostring| returns \nil plus a string describing 3039then \verb|dostring| returns \nil\ plus a string describing
2638the error (see \verb|dofile|). 3040the error (see \verb|dofile|).
2639Otherwise, it returns the values returned by the chunk, 3041Otherwise, it returns the values returned by the chunk,
2640or a non-\nil\ value if the chunk returns no values. 3042or a non-\nil\ value if the chunk returns no values.
@@ -2650,16 +3052,15 @@ the last protected function called
2650in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). 3052in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
2651If \verb|message| is \nil, then the error handler is not called. 3053If \verb|message| is \nil, then the error handler is not called.
2652Function \verb|error| never returns. 3054Function \verb|error| never returns.
2653%\verb|error| is equivalent to the API function \verb|lua_error|.
2654 3055
2655\subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach} 3056\subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach}
2656Executes the given \verb|func| over all elements of \verb|table|. 3057Executes the given \verb|func| over all elements of \verb|table|.
2657For each element, the function is called with the index and 3058For each element, the function is called with the index and
2658respective value as arguments. 3059respective value as arguments.
2659If the function returns any non-\nil\ value, 3060If the function returns a non-\nil\ value,
2660then the loop is broken, and this value is returned 3061then the loop is broken, and this value is returned
2661as the final value of \verb|foreach|. 3062as the final value of \verb|foreach|.
2662This function could be defined in Lua: 3063This function is equivalent to the following Lua function:
2663\begin{verbatim} 3064\begin{verbatim}
2664 function foreach (t, f) 3065 function foreach (t, f)
2665 for i, v in t do 3066 for i, v in t do
@@ -2681,10 +3082,10 @@ respective value as arguments.
2681Indices are visited in sequential order, 3082Indices are visited in sequential order,
2682from~1 to \verb|n|, 3083from~1 to \verb|n|,
2683where \verb|n| is the result of \verb|getn(table)| (see below). 3084where \verb|n| is the result of \verb|getn(table)| (see below).
2684If the function returns any non-\nil\ value, 3085If the function returns a non-\nil\ value,
2685then the loop is broken, and this value is returned 3086then the loop is broken, and this value is returned
2686as the final value of \verb|foreachi|. 3087as the final value of \verb|foreachi|.
2687This function could be defined in Lua: 3088This function is equivalent to the following Lua function:
2688\begin{verbatim} 3089\begin{verbatim}
2689 function foreachi (t, f) 3090 function foreachi (t, f)
2690 for i=1,getn(t) do 3091 for i=1,getn(t) do
@@ -2701,7 +3102,7 @@ current garbage collector threshold (also in Kbytes).
2701 3102
2702\subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal} 3103\subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal}
2703Gets the value of a global variable, 3104Gets the value of a global variable,
2704or calls a tag method for ``getglobal''. 3105possibly via a ``getglobal'' tag method.
2705Its full semantics is explained in \See{tag-method}. 3106Its full semantics is explained in \See{tag-method}.
2706The string \verb|name| does not need to be a 3107The string \verb|name| does not need to be a
2707syntactically valid variable name. 3108syntactically valid variable name.
@@ -2710,9 +3111,9 @@ syntactically valid variable name.
2710Returns the ``size'' of a table, when seen as a list. 3111Returns the ``size'' of a table, when seen as a list.
2711If the table has an \verb|n| field with a numeric value, 3112If the table has an \verb|n| field with a numeric value,
2712this value is the ``size'' of the table. 3113this value is the ``size'' of the table.
2713Otherwise, the ``size'' is the largest numerical index with a non-nil 3114Otherwise, the ``size'' is the largest numerical index with a non-\nil\
2714value in the table. 3115value in the table.
2715This function could be defined in Lua: 3116This function is equivalent to the following Lua function:
2716\begin{verbatim} 3117\begin{verbatim}
2717 function getn (t) 3118 function getn (t)
2718 if type(t.n) == "number" then return t.n end 3119 if type(t.n) == "number" then return t.n end
@@ -2729,13 +3130,23 @@ This function could be defined in Lua:
2729Returns the current tag method 3130Returns the current tag method
2730for a given pair \M{(tag, event)}. 3131for a given pair \M{(tag, event)}.
2731This function cannot be used to get a tag method for the ``gc'' event. 3132This function cannot be used to get a tag method for the ``gc'' event.
2732(Such tag methods can only be manipulated by C~code.) 3133(``gc'' tag methods can only be manipulated by C~code.)
2733 3134
2734\subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals} 3135\subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals}
2735Returns the current table of globals. 3136Returns the current table of globals.
2736If the argument \verb|table| is given, 3137If the argument \verb|table| is given,
2737then it also sets this table as the table of globals. 3138then it also sets this table as the table of globals.
2738 3139
3140\subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile}
3141Similar to \verb|dofile|,
3142but returns the contents of a Lua chunk as a function,
3143instead of executing it.
3144
3145\subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring}
3146Similar to \verb|dostring|,
3147but returns the contents of a Lua chunk as a function,
3148instead of executing it.
3149
2739\subsubsection*{\ff \T{newtype (name)}}\DefLIB{newtype}\label{pdf-newtype} 3150\subsubsection*{\ff \T{newtype (name)}}\DefLIB{newtype}\label{pdf-newtype}
2740Creates a new type with the given name 3151Creates a new type with the given name
2741(which can be used only for table objects). 3152(which can be used only for table objects).
@@ -2773,20 +3184,20 @@ and prints their values in \verb|stdout|,
2773using the strings returned by \verb|tostring|. 3184using the strings returned by \verb|tostring|.
2774This function is not intended for formatted output, 3185This function is not intended for formatted output,
2775but only as a quick way to show a value, 3186but only as a quick way to show a value,
2776for instance for debugging. 3187typically for debugging.
2777See \See{libio} for functions for formatted output. 3188For formatted output, see \verb|format| \see{format}.
2778 3189
2779\subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget} 3190\subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget}
2780Gets the real value of \verb|table[index]|, 3191Gets the real value of \verb|table[index]|,
2781without invoking any tag method. 3192without invoking any tag method.
2782\verb|table| must be a table, 3193\verb|table| must be a table;
2783and \verb|index| is any value different from \nil. 3194\verb|index| is any value different from \nil.
2784 3195
2785\subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset} 3196\subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset}
2786Sets the real value of \verb|table[index]| to \verb|value|, 3197Sets the real value of \verb|table[index]| to \verb|value|,
2787without invoking any tag method. 3198without invoking any tag method.
2788\verb|table| must be a table, 3199\verb|table| must be a table;
2789\verb|index| is any value different from \nil, 3200\verb|index| is any value different from \nil;
2790and \verb|value| is any Lua value. 3201and \verb|value| is any Lua value.
2791 3202
2792\subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype} 3203\subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype}
@@ -2805,7 +3216,7 @@ TO BE WRITTEN.
2805 3216
2806\subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal} 3217\subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal}
2807Sets the named global variable to the given value, 3218Sets the named global variable to the given value,
2808or calls a tag method for ``setglobal''. 3219possibly via a ``setglobal'' tag method.
2809Its full semantics is explained in \See{tag-method}. 3220Its full semantics is explained in \See{tag-method}.
2810The string \verb|name| does not need to be a 3221The string \verb|name| does not need to be a
2811syntactically valid variable name. 3222syntactically valid variable name.
@@ -2813,9 +3224,9 @@ syntactically valid variable name.
2813\subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype} 3224\subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype}
2814Sets the type of a given table \see{TypesSec}. 3225Sets the type of a given table \see{TypesSec}.
2815\verb|type| must be the name or the tag of a user-defined type. 3226\verb|type| must be the name or the tag of a user-defined type.
2816\verb|settag| returns the value of its first argument (the table). 3227\verb|settype| returns the value of its first argument (the table).
2817For the safety of host programs, 3228For the safety of host programs,
2818it is impossible to change the tag of a userdata from Lua. 3229you can only change the type of userdata from~C, not from Lua.
2819 3230
2820\subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} 3231\subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}}
2821\DefLIB{settagmethod} 3232\DefLIB{settagmethod}
@@ -2824,7 +3235,7 @@ returns the old method.
2824If \verb|newmethod| is \nil, 3235If \verb|newmethod| is \nil,
2825then \verb|settagmethod| restores the default behavior for the given event. 3236then \verb|settagmethod| restores the default behavior for the given event.
2826This function cannot be used to set a tag method for the ``gc'' event. 3237This function cannot be used to set a tag method for the ``gc'' event.
2827(Such tag methods can only be manipulated by C~code.) 3238(``gc'' tag methods can only be manipulated by C~code.)
2828 3239
2829\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} 3240\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort}
2830Sorts table elements in a given order, \emph{in-place}, 3241Sorts table elements in a given order, \emph{in-place},
@@ -2834,7 +3245,7 @@ If \verb|comp| is given,
2834then it must be a function that receives two table elements, 3245then it must be a function that receives two table elements,
2835and returns true (that is, a value different from \nil) 3246and returns true (that is, a value different from \nil)
2836when the first is less than the second 3247when the first is less than the second
2837(so that \verb|not comp(a[i+1], a[i])| will be true after the sort). 3248(so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
2838If \verb|comp| is not given, 3249If \verb|comp| is not given,
2839then the standard Lua operator \verb|<| is used instead. 3250then the standard Lua operator \verb|<| is used instead.
2840 3251
@@ -2843,9 +3254,8 @@ The sort algorithm is \emph{not} stable
2843may have their relative positions changed by the sort). 3254may have their relative positions changed by the sort).
2844 3255
2845\subsubsection*{\ff \T{tag (v)}}\DefLIB{tag}\label{pdf-tag} 3256\subsubsection*{\ff \T{tag (v)}}\DefLIB{tag}\label{pdf-tag}
2846Allows Lua programs to test the tag of a value \see{TypesSec}. 3257Returns the tag of a value \see{TypesSec}.
2847It receives one argument, and returns its tag (a number). 3258Tags are integers.
2848%\verb|tag| is equivalent to the API function \verb|lua_tag|.
2849 3259
2850\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} 3260\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
2851Tries to convert its argument to a number. 3261Tries to convert its argument to a number.
@@ -2855,7 +3265,7 @@ otherwise, it returns \nil.
2855 3265
2856An optional argument specifies the base to interpret the numeral. 3266An optional argument specifies the base to interpret the numeral.
2857The base may be any integer between 2 and 36, inclusive. 3267The base may be any integer between 2 and 36, inclusive.
2858In bases above~10, the letter `A' (either upper or lower case) 3268In bases above~10, the letter `A' (in either upper or lower case)
2859represents~10, `B' represents~11, and so forth, with `Z' representing 35. 3269represents~10, `B' represents~11, and so forth, with `Z' representing 35.
2860In base 10 (the default), the number may have a decimal part, 3270In base 10 (the default), the number may have a decimal part,
2861as well as an optional exponent part \see{coercion}. 3271as well as an optional exponent part \see{coercion}.
@@ -2865,13 +3275,13 @@ In other bases, only unsigned integers are accepted.
2865Receives an argument of any type and 3275Receives an argument of any type and
2866converts it to a string in a reasonable format. 3276converts it to a string in a reasonable format.
2867For complete control of how numbers are converted, 3277For complete control of how numbers are converted,
2868use function \verb|format|. 3278use \verb|format| \see{format}.
2869 3279
2870 3280
2871\subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert} 3281\subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert}
2872 3282
2873Inserts element \verb|value| at table position \verb|pos|, 3283Inserts element \verb|value| at position \verb|pos| in \verb|table|,
2874shifting other elements to open space, if necessary. 3284shifting other elements up to open space, if necessary.
2875The default value for \verb|pos| is \verb|n+1|, 3285The default value for \verb|pos| is \verb|n+1|,
2876where \verb|n| is the result of \verb|getn(table)| \see{getn}, 3286where \verb|n| is the result of \verb|getn(table)| \see{getn},
2877so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end 3287so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end
@@ -2879,7 +3289,7 @@ of table \verb|t|.
2879This function also sets or increments the field \verb|n| of the table 3289This function also sets or increments the field \verb|n| of the table
2880to \verb|n+1|. 3290to \verb|n+1|.
2881This function is equivalent to the following Lua function, 3291This function is equivalent to the following Lua function,
2882except that the table accesses are all \emph{raw} 3292except that the table accesses in \verb|tinsert| are all \emph{raw}
2883(that is, without tag methods): 3293(that is, without tag methods):
2884\begin{verbatim} 3294\begin{verbatim}
2885 function tinsert (t, ...) 3295 function tinsert (t, ...)
@@ -2901,7 +3311,7 @@ except that the table accesses are all \emph{raw}
2901\subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove} 3311\subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove}
2902 3312
2903Removes from \verb|table| the element at position \verb|pos|, 3313Removes from \verb|table| the element at position \verb|pos|,
2904shifting other elements to close the space, if necessary. 3314shifting other elements down to close the space, if necessary.
2905Returns the value of the removed element. 3315Returns the value of the removed element.
2906The default value for \verb|pos| is \verb|n|, 3316The default value for \verb|pos| is \verb|n|,
2907where \verb|n| is the result of \verb|getn(table)| \see{getn}, 3317where \verb|n| is the result of \verb|getn(table)| \see{getn},
@@ -2909,9 +3319,8 @@ so that a call \verb|tremove(t)| removes the last element
2909of table \verb|t|. 3319of table \verb|t|.
2910This function also sets or decrements the field \verb|n| of the table 3320This function also sets or decrements the field \verb|n| of the table
2911to \verb|n-1|. 3321to \verb|n-1|.
2912
2913This function is equivalent to the following Lua function, 3322This function is equivalent to the following Lua function,
2914except that the table accesses are all \emph{raw} 3323except that the table accesses in \verb|tremove| are all \emph{raw}
2915(that is, without tag methods): 3324(that is, without tag methods):
2916\begin{verbatim} 3325\begin{verbatim}
2917 function tremove (t, pos) 3326 function tremove (t, pos)
@@ -2929,7 +3338,9 @@ except that the table accesses are all \emph{raw}
2929\end{verbatim} 3338\end{verbatim}
2930 3339
2931\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} 3340\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
2932Returns the type name of its only argument. 3341Returns the type name of a value.
3342Type names are strings and are set with \verb|settype| for user-defined types.
3343For other types, \verb|type| is equivalent to \verb|rawtype|.
2933 3344
2934\subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack} 3345\subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack}
2935Returns all elements from the given list. 3346Returns all elements from the given list.
@@ -2938,15 +3349,15 @@ This function is equivalent to
2938 return list[1], list[2], ..., list[n] 3349 return list[1], list[2], ..., list[n]
2939\end{verbatim} 3350\end{verbatim}
2940except that the above code can be valid only for a fixed \M{n}. 3351except that the above code can be valid only for a fixed \M{n}.
2941The number of returned values, \M{n}, 3352The number \M{n} of returned values
2942is the result of \verb|getn(list)| \see{getn}, 3353is the result of \verb|getn(list)| \seepage{getn}.
2943 3354
2944\subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode} 3355\subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode}
2945 3356
2946Controls the weakness of a table. 3357Controls the weakness of a table.
2947When \verb|mode| is \verb|"?"|, 3358When \verb|mode| is \verb|"?"|,
2948returns the current mode of the table, as a string; 3359\verb|weakmode| returns the current mode of the table, as a string;
2949otherwise, sets the weakmode of the table to the given mode (also a string). 3360otherwise, it sets the weakmode of the table to the given mode (also a string).
2950Valid mode strings are \verb|"k"| for weak keys, 3361Valid mode strings are \verb|"k"| for weak keys,
2951\verb|"v"| for weak values, 3362\verb|"v"| for weak values,
2952\verb|"kv"| for both, 3363\verb|"kv"| for both,
@@ -2958,8 +3369,7 @@ This library provides generic functions for string manipulation,
2958such as finding and extracting substrings and pattern matching. 3369such as finding and extracting substrings and pattern matching.
2959When indexing a string in Lua, the first character is at position~1 3370When indexing a string in Lua, the first character is at position~1
2960(not at~0, as in C). 3371(not at~0, as in C).
2961Also, 3372Indices are allowed to be negative and are interpreted as indexing backwards,
2962indices are allowed to be negative and are interpreted as indexing backwards,
2963from the end of the string. Thus, the last character is at position \Math{-1}, 3373from the end of the string. Thus, the last character is at position \Math{-1},
2964and so on. 3374and so on.
2965 3375
@@ -2974,16 +3384,15 @@ Numerical codes are not necessarily portable across platforms.
2974\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\DefLIB{strchar} 3384\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\DefLIB{strchar}
2975Receives 0 or more integers. 3385Receives 0 or more integers.
2976Returns a string with length equal to the number of arguments, 3386Returns a string with length equal to the number of arguments,
2977wherein each character has the internal numerical code equal 3387in which each character has the internal numerical code equal
2978to its correspondent argument. 3388to its correspondent argument.
2979 3389
2980\NOTE 3390\NOTE
2981Numerical codes are not necessarily portable across platforms. 3391Numerical codes are not necessarily portable across platforms.
2982 3392
2983\subsubsection*{\ff \T{strfind (s, pattern [, init [, plain]])}} 3393\subsubsection*{\ff \T{strfind (s, pattern [, init [, plain]])}}\DefLIB{strfind}
2984\DefLIB{strfind}
2985Looks for the first \emph{match} of 3394Looks for the first \emph{match} of
2986\verb|pattern| in \verb|s|. 3395\verb|pattern| in the string \verb|s|.
2987If it finds one, then \verb|strfind| returns the indices of \verb|s| 3396If it finds one, then \verb|strfind| returns the indices of \verb|s|
2988where this occurrence starts and ends; 3397where this occurrence starts and ends;
2989otherwise, it returns \nil. 3398otherwise, it returns \nil.
@@ -3006,10 +3415,9 @@ and so \verb|"a\000b\000c"| has length 5.
3006 3415
3007\subsubsection*{\ff \T{strlower (s)}}\DefLIB{strlower} 3416\subsubsection*{\ff \T{strlower (s)}}\DefLIB{strlower}
3008Receives a string and returns a copy of that string with all 3417Receives a string and returns a copy of that string with all
3009upper case letters changed to lower case. 3418uppercase letters changed to lowercase.
3010All other characters are left unchanged. 3419All other characters are left unchanged.
3011The definition of what is an upper-case 3420The definition of what an uppercase letter is depends on the current locale.
3012letter depends on the current locale.
3013 3421
3014\subsubsection*{\ff \T{strrep (s, n)}}\DefLIB{strrep} 3422\subsubsection*{\ff \T{strrep (s, n)}}\DefLIB{strrep}
3015Returns a string that is the concatenation of \verb|n| copies of 3423Returns a string that is the concatenation of \verb|n| copies of
@@ -3018,7 +3426,7 @@ the string \verb|s|.
3018\subsubsection*{\ff \T{strsub (s, i [, j])}}\DefLIB{strsub} 3426\subsubsection*{\ff \T{strsub (s, i [, j])}}\DefLIB{strsub}
3019Returns another string, which is a substring of \verb|s|, 3427Returns another string, which is a substring of \verb|s|,
3020starting at \verb|i| and running until \verb|j|; 3428starting at \verb|i| and running until \verb|j|;
3021\verb|i| and \verb|j| may be negative, 3429\verb|i| and \verb|j| may be negative.
3022If \verb|j| is absent, then it is assumed to be equal to \Math{-1} 3430If \verb|j| is absent, then it is assumed to be equal to \Math{-1}
3023(which is the same as the string length). 3431(which is the same as the string length).
3024In particular, 3432In particular,
@@ -3029,10 +3437,9 @@ with length \verb|i|.
3029 3437
3030\subsubsection*{\ff \T{strupper (s)}}\DefLIB{strupper} 3438\subsubsection*{\ff \T{strupper (s)}}\DefLIB{strupper}
3031Receives a string and returns a copy of that string with all 3439Receives a string and returns a copy of that string with all
3032lower case letters changed to upper case. 3440lowercase letters changed to uppercase.
3033All other characters are left unchanged. 3441All other characters are left unchanged.
3034The definition of what is a lower case 3442The definition of what a lowercase letter is depends on the current locale.
3035letter depends on the current locale.
3036 3443
3037\subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\DefLIB{format} 3444\subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\DefLIB{format}
3038\label{format} 3445\label{format}
@@ -3081,8 +3488,8 @@ replaced by a replacement string specified by \verb|repl|.
3081the total number of substitutions made. 3488the total number of substitutions made.
3082 3489
3083If \verb|repl| is a string, then its value is used for replacement. 3490If \verb|repl| is a string, then its value is used for replacement.
3084Any sequence in \verb|repl| of the form \verb|%n| 3491Any sequence in \verb|repl| of the form \verb|%|\M{n},
3085with \verb|n| between 1 and 9 3492with \M{n} between 1 and 9,
3086stands for the value of the \M{n}-th captured substring. 3493stands for the value of the \M{n}-th captured substring.
3087 3494
3088If \verb|repl| is a function, then this function is called every time a 3495If \verb|repl| is a function, then this function is called every time a
@@ -3114,11 +3521,11 @@ Here are some examples:
3114 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) 3521 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
3115 --> x="4+5 = 9" 3522 --> x="4+5 = 9"
3116 3523
3117 local t = {name="lua", version="4.0"} 3524 local t = {name="Lua", version="4.1"}
3118 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) 3525 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
3119 --> x="lua - 4.0" 3526 --> x="Lua - 4.1"
3120 3527
3121 t = {n=0} 3528 local t = {n=0}
3122 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) 3529 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
3123 --> t={"first", "second", "word"; n=3} 3530 --> t={"first", "second", "word"; n=3}
3124\end{verbatim} 3531\end{verbatim}
@@ -3129,7 +3536,7 @@ Here are some examples:
3129\paragraph{Character Class:} 3536\paragraph{Character Class:}
3130a \Def{character class} is used to represent a set of characters. 3537a \Def{character class} is used to represent a set of characters.
3131The following combinations are allowed in describing a character class: 3538The following combinations are allowed in describing a character class:
3132\begin{description} 3539\begin{description}\leftskip=20pt
3133\item[\emph{x}] (where \emph{x} is not one of the magic characters 3540\item[\emph{x}] (where \emph{x} is not one of the magic characters
3134\verb|^$()%.[]*+-?|) 3541\verb|^$()%.[]*+-?|)
3135--- represents the character \emph{x} itself. 3542--- represents the character \emph{x} itself.
@@ -3137,10 +3544,10 @@ The following combinations are allowed in describing a character class:
3137\item[\T{\%a}] --- represents all letters. 3544\item[\T{\%a}] --- represents all letters.
3138\item[\T{\%c}] --- represents all control characters. 3545\item[\T{\%c}] --- represents all control characters.
3139\item[\T{\%d}] --- represents all digits. 3546\item[\T{\%d}] --- represents all digits.
3140\item[\T{\%l}] --- represents all lower case letters. 3547\item[\T{\%l}] --- represents all lowercase letters.
3141\item[\T{\%p}] --- represents all punctuation characters. 3548\item[\T{\%p}] --- represents all punctuation characters.
3142\item[\T{\%s}] --- represents all space characters. 3549\item[\T{\%s}] --- represents all space characters.
3143\item[\T{\%u}] --- represents all upper case letters. 3550\item[\T{\%u}] --- represents all uppercase letters.
3144\item[\T{\%w}] --- represents all alphanumeric characters. 3551\item[\T{\%w}] --- represents all alphanumeric characters.
3145\item[\T{\%x}] --- represents all hexadecimal digits. 3552\item[\T{\%x}] --- represents all hexadecimal digits.
3146\item[\T{\%z}] --- represents the character with representation 0. 3553\item[\T{\%z}] --- represents the character with representation 0.
@@ -3151,33 +3558,33 @@ We recommend that any punctuation character (even the non magic)
3151should be preceded by a \verb|%| 3558should be preceded by a \verb|%|
3152when used to represent itself in a pattern. 3559when used to represent itself in a pattern.
3153 3560
3154\item[\T{[char-set]}] --- 3561\item[\T{[\M{set}]}] ---
3155represents the class which is the union of all 3562represents the class which is the union of all
3156characters in \verb|char-set|. 3563characters in \M{set}.
3157A range of characters may be specified by 3564A range of characters may be specified by
3158separating the end characters of the range with a \verb|-|. 3565separating the end characters of the range with a \verb|-|.
3159All classes \verb|%|\emph{x} described above may also be used as 3566All classes \verb|%|\emph{x} described above may also be used as
3160components in a char-set. 3567components in \M{set}.
3161All other characters in char-set represent themselves. 3568All other characters in \M{set} represent themselves.
3162For example, \verb|[%w_]| (or \verb|[_%w]|) 3569For example, \verb|[%w_]| (or \verb|[_%w]|)
3163represents all alphanumeric characters plus the underscore, 3570represents all alphanumeric characters plus the underscore,
3164\verb|[0-7]| represents the octal digits, 3571\verb|[0-7]| represents the octal digits,
3165and \verb|[0-7%l%-]| represents the octal digits plus 3572and \verb|[0-7%l%-]| represents the octal digits plus
3166the lower case letters plus the \verb|-| character. 3573the lowercase letters plus the \verb|-| character.
3167 3574
3168The interaction between ranges and classes is not defined. 3575The interaction between ranges and classes is not defined.
3169Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]| 3576Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]|
3170have no meaning. 3577have no meaning.
3171 3578
3172\item[\T{[\^\null char-set]}] --- 3579\item[\T{[\^\null\M{set}]}] ---
3173represents the complement of \verb|char-set|, 3580represents the complement of \M{set},
3174where \verb|char-set| is interpreted as above. 3581where \M{set} is interpreted as above.
3175\end{description} 3582\end{description}
3176For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), 3583For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots),
3177the corresponding upper-case letter represents the complement of the class. 3584the corresponding uppercase letter represents the complement of the class.
3178For instance, \verb|%S| represents all non-space characters. 3585For instance, \verb|%S| represents all non-space characters.
3179 3586
3180The definitions of letter, space, etc. depend on the current locale. 3587The definitions of letter, space, etc.\ depend on the current locale.
3181In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|. 3588In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|.
3182The second form should be preferred for portability. 3589The second form should be preferred for portability.
3183 3590
@@ -3199,7 +3606,7 @@ These repetition items will always match the longest possible sequence;
3199a single character class followed by \verb|-|, 3606a single character class followed by \verb|-|,
3200which also matches 0 or more repetitions of characters in the class. 3607which also matches 0 or more repetitions of characters in the class.
3201Unlike \verb|*|, 3608Unlike \verb|*|,
3202these repetition items will always match the shortest possible sequence; 3609these repetition items will always match the \emph{shortest} possible sequence;
3203\item 3610\item
3204a single character class followed by \verb|?|, 3611a single character class followed by \verb|?|,
3205which matches 0 or 1 occurrence of a character in the class; 3612which matches 0 or 1 occurrence of a character in the class;
@@ -3228,7 +3635,7 @@ At other positions,
3228\verb|^| and \verb|$| have no special meaning and represent themselves. 3635\verb|^| and \verb|$| have no special meaning and represent themselves.
3229 3636
3230\paragraph{Captures:} 3637\paragraph{Captures:}
3231A pattern may contain sub-patterns enclosed in parentheses, 3638A pattern may contain sub-patterns enclosed in parentheses;
3232they describe \Def{captures}. 3639they describe \Def{captures}.
3233When a match succeeds, the sub-strings of the subject string 3640When a match succeeds, the sub-strings of the subject string
3234that match captures are stored (\emph{captured}) for future use. 3641that match captures are stored (\emph{captured}) for future use.
@@ -3245,8 +3652,10 @@ A pattern cannot contain embedded zeros. Use \verb|%z| instead.
3245 3652
3246\subsection{Mathematical Functions} \label{mathlib} 3653\subsection{Mathematical Functions} \label{mathlib}
3247 3654
3248This library is an interface to some functions of the standard C~math library. 3655This library is an interface to most functions of the standard C~math library.
3249In addition, it registers a tag method for the binary operator \verb|^| that 3656(Some have slightly different names.)
3657In addition,
3658it registers a tag method for the binary exponentiation operator \verb|^| that
3250returns \Math{x^y} when applied to numbers \verb|x^y|. 3659returns \Math{x^y} when applied to numbers \verb|x^y|.
3251 3660
3252The library provides the following functions: 3661The library provides the following functions:
@@ -3274,20 +3683,20 @@ Both can be used with 1, 2, or more arguments.
3274 3683
3275The functions \verb|random| and \verb|randomseed| are interfaces to 3684The functions \verb|random| and \verb|randomseed| are interfaces to
3276the simple random generator functions \verb|rand| and \verb|srand|, 3685the simple random generator functions \verb|rand| and \verb|srand|,
3277provided by ANSI C. 3686provided by ANSI~C.
3278(No guarantees can be given for their statistical properties.) 3687(No guarantees can be given for their statistical properties.)
3279The function \verb|random|, when called without arguments, 3688When called without arguments,
3280returns a pseudo-random real number in the range \Math{[0,1)}. 3689\verb|random| returns a pseudo-random real number in the range \Math{[0,1)}.
3281When called with a number \Math{n}, 3690When called with a number \Math{n},
3282\verb|random| returns a pseudo-random integer in the range \Math{[1,n]}. 3691\verb|random| returns a pseudo-random integer in the range \Math{[1,n]}.
3283When called with two arguments, \Math{l} and \Math{u}, 3692When called with two arguments, \Math{l} and \Math{u},
3284\verb|random| returns a pseudo-random integer in the range \Math{[l,u]}. 3693\verb|random| returns a pseudo-random integer in the range \Math{[l,u]}.
3285 3694
3286 3695
3287\subsection{I/O Facilities} \label{libio} 3696\subsection{Input and Output Facilities} \label{libio}
3288 3697
3289All input and output operations in Lua are done, by default, 3698All input and output operations in Lua are done, by default,
3290over two \Def{file handles}, one for reading and one for writing. 3699over two \Def{file handles}: one for reading and one for writing.
3291These handles are stored in two Lua global variables, 3700These handles are stored in two Lua global variables,
3292called \verb|_INPUT| and \verb|_OUTPUT|. 3701called \verb|_INPUT| and \verb|_OUTPUT|.
3293The global variables 3702The global variables
@@ -3314,7 +3723,7 @@ or, in case of errors, \nil\ plus a string describing the error.
3314This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. 3723This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
3315 3724
3316The \verb|mode| string can be any of the following: 3725The \verb|mode| string can be any of the following:
3317\begin{description} 3726\begin{description}\leftskip=20pt
3318\item[``r''] read mode; 3727\item[``r''] read mode;
3319\item[``w''] write mode; 3728\item[``w''] write mode;
3320\item[``a''] append mode; 3729\item[``a''] append mode;
@@ -3381,7 +3790,8 @@ usually limited and depends on the system.
3381\subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto} 3790\subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto}
3382 3791
3383Opens a file named \verb|filename| (in text mode) 3792Opens a file named \verb|filename| (in text mode)
3384and sets its handle as the value of \verb|_OUTPUT|. 3793sets its handle as the value of \verb|_OUTPUT|,
3794and returns this value.
3385Unlike the \verb|writeto| operation, 3795Unlike the \verb|writeto| operation,
3386this function does not erase any previous contents of the file; 3796this function does not erase any previous contents of the file;
3387instead, anything written to the file is appended to its end. 3797instead, anything written to the file is appended to its end.
@@ -3414,14 +3824,14 @@ Sets and gets the file position,
3414measured in bytes from the beginning of the file, 3824measured in bytes from the beginning of the file,
3415to the position given by \verb|offset| plus a base 3825to the position given by \verb|offset| plus a base
3416specified by the string \verb|whence|, as follows: 3826specified by the string \verb|whence|, as follows:
3417\begin{description} 3827\begin{description}\leftskip=20pt
3418\item[``set''] base is position 0 (beginning of the file); 3828\item[``set''] base is position 0 (beginning of the file);
3419\item[``cur''] base is current position; 3829\item[``cur''] base is current position;
3420\item[``end''] base is end of file; 3830\item[``end''] base is end of file;
3421\end{description} 3831\end{description}
3422In case of success, function \verb|seek| returns the final file position, 3832In case of success, function \verb|seek| returns the final file position,
3423measured in bytes from the beginning of the file. 3833measured in bytes from the beginning of the file.
3424If the call fails, it returns \nil, 3834If this function fails, it returns \nil,
3425plus a string describing the error. 3835plus a string describing the error.
3426 3836
3427The default value for \verb|whence| is \verb|"cur"|, 3837The default value for \verb|whence| is \verb|"cur"|,
@@ -3446,8 +3856,8 @@ be used for a temporary file.
3446The file must be explicitly opened before its use 3856The file must be explicitly opened before its use
3447and removed when no longer needed. 3857and removed when no longer needed.
3448 3858
3449This function is equivalent to the \verb|tmpnam| C function, 3859This function is equivalent to the \verb|tmpnam| C~function,
3450and many people advise against its use, 3860and many people (and even some compilers!) advise against its use,
3451because between the time you call the function 3861because between the time you call the function
3452and the time you open the file, 3862and the time you open the file,
3453it is possible for another process 3863it is possible for another process
@@ -3462,11 +3872,11 @@ For each format,
3462the function returns a string (or a number) with the characters read, 3872the function returns a string (or a number) with the characters read,
3463or \nil\ if it cannot read data with the specified format. 3873or \nil\ if it cannot read data with the specified format.
3464When called without formats, 3874When called without formats,
3465it uses a default format that reads the next line 3875it uses a default format that reads the entire next line
3466(see below). 3876(see below).
3467 3877
3468The available formats are 3878The available formats are
3469\begin{description} 3879\begin{description}\leftskip=20pt
3470\item[``*n''] reads a number; 3880\item[``*n''] reads a number;
3471this is the only format that returns a number instead of a string. 3881this is the only format that returns a number instead of a string.
3472\item[``*a''] reads the whole file, starting at the current position. 3882\item[``*a''] reads the whole file, starting at the current position.
@@ -3474,17 +3884,17 @@ On end of file, it returns the empty string.
3474\item[``*u\emph{string}''] reads until the first occurence of 3884\item[``*u\emph{string}''] reads until the first occurence of
3475\emph{string} in the file. 3885\emph{string} in the file.
3476The string itself is read, but it is not included in the result. 3886The string itself is read, but it is not included in the result.
3477If it cannot finds the string, 3887If \verb|read| cannot finds the string,
3478reads (and returns) the file until its end, 3888it reads (and returns) the file until its end,
3479or \nil\ if the file was already on its end. 3889or \nil\ if the file was already at its end.
3480\item[``*l''] equivalent to \verb|"*u\n"|. 3890\item[``*l''] equivalent to \verb|"*u\n"|.
3481Reads the next line (skipping the end of line), 3891Reads the next line (skipping the end of line),
3482returning \nil\ on end of file. 3892returning \nil\ on end of file.
3483This is the default format. 3893This is the default format.
3484\item[\emph{number}] reads a string with up to that number of characters, 3894\item[\emph{number}] reads a string with up to that number of characters,
3485or \nil\ on end of file. 3895or \nil\ on end of file.
3486Particularly, if number is zero, 3896If number is zero,
3487reads nothing and returns an empty string, 3897it reads nothing and returns an empty string,
3488or \nil\ on end of file. 3898or \nil\ on end of file.
3489\end{description} 3899\end{description}
3490 3900
@@ -3517,29 +3927,30 @@ this is the time to be formatted
3517Otherwise, \verb|date| formats the current time. 3927Otherwise, \verb|date| formats the current time.
3518 3928
3519If \verb|format| starts with \verb|!|, 3929If \verb|format| starts with \verb|!|,
3520the date is formatted in Coordinated Universal Time. 3930then the date is formatted in Coordinated Universal Time.
3521 3931
3522After that optional character, 3932After that optional character,
3523if \verb|format| is \verb|*t|, 3933if \verb|format| is \verb|*t|,
3524the function returns a table with the following fields: 3934then \verb|date| returns a table with the following fields:
3525\verb|year|, \verb|month| (1-12), \verb|day| (1-31), 3935\verb|year|, \verb|month| (1--12), \verb|day| (1--31),
3526\verb|hour| (0-23), \verb|min| (0-59), \verb|sec| (0-59), 3936\verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--59),
3527\verb|wday| (weekday, Sunday is 1), 3937\verb|wday| (weekday, Sunday is 1),
3528\verb|yday| (day of the year), 3938\verb|yday| (day of the year),
3529and \verb|isdst| (daylight saving flag). 3939and \verb|isdst| (daylight saving flag).
3530 3940
3531If format is not \verb|*t|, the function returns the date 3941If format is not \verb|*t|,
3532as a string, formatted according with the 3942then \verb|date| returns the date as a string,
3533same rules of the ANSI~C function \verb|strftime|. 3943formatted according with the same rules of the C~function \verb|strftime|.
3534When called without arguments, 3944When called without arguments,
3535it returns a reasonable date and time representation that depends on 3945\verb|date| returns a reasonable date and time representation that depends on
3536the host system and on the current locale. 3946the host system and on the current locale (thus, \verb|date()| is equivalent
3947to \verb|date("%c")|).
3537 3948
3538\subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime} 3949\subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime}
3539 3950
3540Returns the number of seconds from time \verb|t1| to time \verb|t2|. 3951Returns the number of seconds from time \verb|t1| to time \verb|t2|.
3541In Posix, Windows, and some other systems, 3952In Posix, Windows, and some other systems,
3542this value is exactly \Math{t1-t2}. 3953this value is exactly \verb|t1|\Math{-}\verb|t2|.
3543 3954
3544\subsubsection*{\ff \T{execute (command)}}\DefLIB{execute} 3955\subsubsection*{\ff \T{execute (command)}}\DefLIB{execute}
3545 3956
@@ -3551,7 +3962,7 @@ It returns a status code, which is system-dependent.
3551 3962
3552Calls the C~function \verb|exit|, 3963Calls the C~function \verb|exit|,
3553with an optional \verb|code|, 3964with an optional \verb|code|,
3554to terminate the program. 3965to terminate the host program.
3555The default value for \verb|code| is the success code. 3966The default value for \verb|code| is the success code.
3556 3967
3557\subsubsection*{\ff \T{getenv (varname)}}\DefLIB{getenv} 3968\subsubsection*{\ff \T{getenv (varname)}}\DefLIB{getenv}
@@ -3561,7 +3972,7 @@ or \nil\ if the variable is not defined.
3561 3972
3562\subsubsection*{\ff \T{setlocale (locale [, category])}}\DefLIB{setlocale} 3973\subsubsection*{\ff \T{setlocale (locale [, category])}}\DefLIB{setlocale}
3563 3974
3564This function is an interface to the ANSI~C function \verb|setlocale|. 3975This function is an interface to the C~function \verb|setlocale|.
3565\verb|locale| is a string specifying a locale; 3976\verb|locale| is a string specifying a locale;
3566\verb|category| is an optional string describing which category to change: 3977\verb|category| is an optional string describing which category to change:
3567\verb|"all"|, \verb|"collate"|, \verb|"ctype"|, 3978\verb|"all"|, \verb|"collate"|, \verb|"ctype"|,
@@ -3572,8 +3983,8 @@ or \nil\ if the request cannot be honored.
3572 3983
3573\subsubsection*{\ff \T{time ([table])}}\DefLIB{time} 3984\subsubsection*{\ff \T{time ([table])}}\DefLIB{time}
3574 3985
3575Returns the current time (when called without arguments), 3986Returns the current time when called without arguments,
3576or a time representing the date/time specified by the given table. 3987or a time representing the date and time specified by the given table.
3577This table must have fields \verb|year|, \verb|month|, and \verb|day|, 3988This table must have fields \verb|year|, \verb|month|, and \verb|day|,
3578and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| 3989and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst|
3579(for a description of these fields, see the \verb|date| function). 3990(for a description of these fields, see the \verb|date| function).
@@ -3582,223 +3993,8 @@ The returned value is a number, whose meaning depends on your system.
3582In Posix, Windows, and some other systems, this number counts the number 3993In Posix, Windows, and some other systems, this number counts the number
3583of seconds since some given start time (the ``epoch''). 3994of seconds since some given start time (the ``epoch'').
3584In other systems, the meaning is not specified, 3995In other systems, the meaning is not specified,
3585and such number can be used only as an argument to 3996and the number returned bt \verb|time| can be used only as an argument to
3586functions \verb|date| and \verb|difftime|. 3997\verb|date| and \verb|difftime|.
3587
3588
3589\section{The Debug Interface} \label{debugI}
3590
3591Lua has no built-in debugging facilities.
3592Instead, it offers a special interface,
3593by means of functions and \emph{hooks},
3594which allows the construction of different
3595kinds of debuggers, profilers, and other tools
3596that need ``inside information'' from the interpreter.
3597This interface is declared in \verb|luadebug.h|.
3598
3599\subsection{Stack and Function Information}
3600
3601The main function to get information about the interpreter stack is
3602\begin{verbatim}
3603 int lua_getstack (lua_State *L, int level, lua_Debug *ar);
3604\end{verbatim}
3605\DefAPI{lua_getstack}
3606It fills parts of a \verb|lua_Debug| structure with
3607an identification of the \emph{activation record}
3608of the function executing at a given level.
3609Level~0 is the current running function,
3610whereas level \Math{n+1} is the function that has called level \Math{n}.
3611Usually, \verb|lua_getstack| returns 1;
3612when called with a level greater than the stack depth,
3613it returns 0.
3614
3615The structure \verb|lua_Debug| is used to carry different pieces of
3616information about an active function:
3617\begin{verbatim}
3618 typedef struct lua_Debug {
3619 const char *event; /* "call", "return" */
3620 int currentline; /* (l) */
3621 const char *name; /* (n) */
3622 const char *namewhat; /* (n) global, tag method, local, field */
3623 int nups; /* (u) number of upvalues */
3624 int linedefined; /* (S) */
3625 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */
3626 const char *source; /* (S) */
3627 char short_src[LUA_IDSIZE]; /* (S) */
3628
3629 /* private part */
3630 ...
3631 } lua_Debug;
3632\end{verbatim}
3633\DefAPI{lua_Debug}
3634\verb|lua_getstack| fills only the private part
3635of this structure, for future use.
3636To fill in the other fields of \verb|lua_Debug| with useful information,
3637call
3638\begin{verbatim}
3639 int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
3640\end{verbatim}
3641\DefAPI{lua_getinfo}
3642This function returns 0 on error
3643(e.g., an invalid option in \verb|what|).
3644Each character in the string \verb|what|
3645selects some fields of \verb|ar| to be filled,
3646as indicated by the letter in parentheses in the definition of \verb|lua_Debug|:
3647`\verb|S|' fills in the fields \verb|source|, \verb|linedefined|,
3648and \verb|what|;
3649`\verb|l|' fills in the field \verb|currentline|, etc.
3650Moreover, `\verb|f|' pushes onto the stack the function that is
3651running at the given level.
3652
3653To get information about a function that is not active (that is,
3654it is not in the stack),
3655you push the function onto the stack,
3656and start the \verb|what| string with the character \verb|>|.
3657For instance, to know in which line a function \verb|f| was defined,
3658you can write
3659\begin{verbatim}
3660 lua_Debug ar;
3661 lua_getglobal(L, "f");
3662 lua_getinfo(L, ">S", &ar);
3663 printf("%d\n", ar.linedefined);
3664\end{verbatim}
3665The fields of \verb|lua_Debug| have the following meaning:
3666\begin{description}
3667
3668\item[source]
3669If the function was defined in a string,
3670\verb|source| is that string;
3671if the function was defined in a file,
3672\verb|source| starts with a \verb|@| followed by the file name.
3673
3674\item[short\_src]
3675A ``printable'' version of \verb|source|, to be used in error messages.
3676
3677\item[linedefined]
3678the line number where the definition of the function starts.
3679
3680\item[what] the string \verb|"Lua"| if this is a Lua function,
3681\verb|"C"| if this is a C~function,
3682or \verb|"main"| if this is the main part of a chunk.
3683
3684\item[currentline]
3685the current line where the given function is executing.
3686When no line information is available,
3687\verb|currentline| is set to \Math{-1}.
3688
3689\item[name]
3690a reasonable name for the given function.
3691Because functions in Lua are first class values,
3692they do not have a fixed name:
3693Some functions may be the value of many global variables,
3694while others may be stored only in a table field.
3695The \verb|lua_getinfo| function checks whether the given
3696function is a tag method or the value of a global variable.
3697If the given function is a tag method,
3698then \verb|name| points to the event name.
3699If the given function is the value of a global variable,
3700then \verb|name| points to the variable name.
3701If the given function is neither a tag method nor a global variable,
3702then \verb|name| is set to \verb|NULL|.
3703
3704\item[namewhat]
3705Explains the previous field.
3706If the function is a global variable,
3707\verb|namewhat| is \verb|"global"|;
3708if the function is a tag method,
3709\verb|namewhat| is \verb|"tag-method"|;
3710otherwise \verb|namewhat| is \verb|""| (the empty string).
3711
3712\item[nups]
3713Number of upvalues of a function.
3714
3715\end{description}
3716
3717
3718\subsection{Manipulating Local Variables}
3719
3720For the manipulation of local variables,
3721\verb|luadebug.h| uses indices:
3722The first parameter or local variable has index~1, and so on,
3723until the last active local variable.
3724
3725The following functions allow the manipulation of the
3726local variables of a given activation record.
3727\begin{verbatim}
3728 const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
3729 const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
3730\end{verbatim}
3731\DefAPI{lua_getlocal}\DefAPI{lua_setlocal}
3732The parameter \verb|ar| must be a valid activation record,
3733filled by a previous call to \verb|lua_getstack| or
3734given as argument to a hook \see{sub-hooks}.
3735Function \verb|lua_getlocal| gets the index of a local variable
3736(\verb|n|), pushes its value onto the stack,
3737and returns its name.
3738For \verb|lua_setlocal|,
3739you push the new value onto the stack,
3740and the function assigns that value to the variable and returns its name.
3741Both functions return \verb|NULL| on failure;
3742that happens if the index is greater than
3743the number of active local variables.
3744
3745As an example, the following function lists the names of all
3746local variables for a function at a given level of the stack:
3747\begin{verbatim}
3748 int listvars (lua_State *L, int level) {
3749 lua_Debug ar;
3750 int i = 1;
3751 const char *name;
3752 if (lua_getstack(L, level, &ar) == 0)
3753 return 0; /* failure: no such level in the stack */
3754 while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
3755 printf("%s\n", name);
3756 lua_pop(L, 1); /* remove variable value */
3757 }
3758 return 1;
3759 }
3760\end{verbatim}
3761
3762
3763\subsection{Hooks}\label{sub-hooks}
3764
3765The Lua interpreter offers two hooks for debugging purposes:
3766a \emph{call} hook and a \emph{line} hook.
3767Both have the same type,
3768\begin{verbatim}
3769 typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
3770\end{verbatim}
3771\DefAPI{lua_Hook}
3772and you can set them with the following functions:
3773\begin{verbatim}
3774 lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
3775 lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
3776\end{verbatim}
3777\DefAPI{lua_setcallhook}\DefAPI{lua_setlinehook}
3778A hook is disabled when its value is \verb|NULL|,
3779which is the initial value of both hooks.
3780The functions \verb|lua_setcallhook| and \verb|lua_setlinehook|
3781set their corresponding hooks and return their previous values.
3782
3783The call hook is called whenever the
3784interpreter enters or leaves a function.
3785The \verb|event| field of \verb|ar| has the strings \verb|"call"|
3786or \verb|"return"|.
3787This \verb|ar| can then be used in calls to \verb|lua_getinfo|,
3788\verb|lua_getlocal|, and \verb|lua_setlocal|
3789to get more information about the function and to manipulate its
3790local variables.
3791
3792The line hook is called every time the interpreter changes
3793the line of code it is executing.
3794The \verb|event| field of \verb|ar| has the string \verb|"line"|,
3795and the \verb|currentline| field has the line number.
3796Again, you can use this \verb|ar| in other calls to the debug API.
3797
3798While Lua is running a hook, it disables other calls to hooks.
3799Therefore, if a hook calls Lua to execute a function or a chunk,
3800this execution ocurrs without any calls to hooks.
3801
3802 3998
3803\subsection{The Reflexive Debug Interface} 3999\subsection{The Reflexive Debug Interface}
3804 4000
@@ -3811,7 +4007,7 @@ by calling \verb|lua_dblibopen|.
3811 4007
3812You should exert great care when using this library. 4008You should exert great care when using this library.
3813The functions provided here should be used exclusively for debugging 4009The functions provided here should be used exclusively for debugging
3814and similar tasks (e.g., profiling). 4010and similar tasks, such as profiling.
3815Please resist the temptation to use them as a 4011Please resist the temptation to use them as a
3816usual programming tool: 4012usual programming tool:
3817They can be \emph{very} slow. 4013They can be \emph{very} slow.
@@ -3835,7 +4031,8 @@ then \verb|getinfo| returns \nil.
3835The returned table contains all the fields returned by \verb|lua_getinfo|, 4031The returned table contains all the fields returned by \verb|lua_getinfo|,
3836with the string \verb|what| describing what to get. 4032with the string \verb|what| describing what to get.
3837The default for \verb|what| is to get all information available. 4033The default for \verb|what| is to get all information available.
3838The option \verb|f|, if present, 4034If present,
4035the option \verb|f|
3839adds a field named \verb|func| with the function itself. 4036adds a field named \verb|func| with the function itself.
3840 4037
3841For instance, the expression \verb|getinfo(1,"n").name| returns 4038For instance, the expression \verb|getinfo(1,"n").name| returns
@@ -3862,6 +4059,7 @@ with index \verb|local| of the function at level \verb|level| of the stack.
3862The function returns \nil\ if there is no local 4059The function returns \nil\ if there is no local
3863variable with the given index, 4060variable with the given index,
3864and raises an error when called with a \verb|level| out of range. 4061and raises an error when called with a \verb|level| out of range.
4062(You can call \verb|getinfo| to check whether the level is valid.)
3865 4063
3866\subsubsection*{\ff \T{setcallhook (hook)}}\DefLIB{setcallhook} 4064\subsubsection*{\ff \T{setcallhook (hook)}}\DefLIB{setcallhook}
3867 4065
@@ -3876,7 +4074,7 @@ the function being called or returning
3876and level~1 is the hook function). 4074and level~1 is the hook function).
3877When called without arguments, 4075When called without arguments,
3878this function turns off call hooks. 4076this function turns off call hooks.
3879\verb|setcallhook| returns the old hook. 4077\verb|setcallhook| returns the old call hook.
3880 4078
3881\subsubsection*{\ff \T{setlinehook (hook)}}\DefLIB{setlinehook} 4079\subsubsection*{\ff \T{setlinehook (hook)}}\DefLIB{setlinehook}
3882 4080
@@ -3887,14 +4085,15 @@ The only argument to the line hook is the line number the interpreter
3887is about to execute. 4085is about to execute.
3888When called without arguments, 4086When called without arguments,
3889this function turns off line hooks. 4087this function turns off line hooks.
3890\verb|setlinehook| returns the old hook. 4088\verb|setlinehook| returns the old line hook.
3891 4089
3892 4090
4091%------------------------------------------------------------------------------
3893\section{\Index{Lua Stand-alone}} \label{lua-sa} 4092\section{\Index{Lua Stand-alone}} \label{lua-sa}
3894 4093
3895Although Lua has been designed as an extension language, 4094Although Lua has been designed as an extension language,
3896to be embedded in a host C~program, 4095to be embedded in a host C~program,
3897it is frequently used as a stand-alone language. 4096it is also frequently used as a stand-alone language.
3898An interpreter for Lua as a stand-alone language, 4097An interpreter for Lua as a stand-alone language,
3899called simply \verb|lua|, 4098called simply \verb|lua|,
3900is provided with the standard distribution. 4099is provided with the standard distribution.
@@ -3903,15 +4102,15 @@ This program can be called with any sequence of the following arguments:
3903\item[\T{-sNUM}] sets the stack size to \T{NUM} 4102\item[\T{-sNUM}] sets the stack size to \T{NUM}
3904(if present, this must be the first option); 4103(if present, this must be the first option);
3905\item[\T{-} ] executes \verb|stdin| as a file; 4104\item[\T{-} ] executes \verb|stdin| as a file;
3906\item[\T{-c}] calls \verb|lua_close| after running all arguments; 4105\item[\T{-c}] calls \verb|lua_close| after processing all arguments;
3907\item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; 4106\item[\T{-e} \rm\emph{stat}] executes string \emph{stat};
3908\item[\T{-f filename}] executes file \verb|filename| with the 4107\item[\T{-f} \rm\emph{filename}] executes file \emph{filename} with the
3909remaining arguments in table \verb|arg|; 4108remaining arguments in table \verb|arg|;
3910\item[\T{-i}] enters interactive mode with prompt; 4109\item[\T{-i}] enters interactive mode with prompt;
3911\item[\T{-q}] enters interactive mode without prompt; 4110\item[\T{-q}] enters interactive mode without prompt;
3912\item[\T{-v}] prints version information; 4111\item[\T{-v}] prints version information;
3913\item[\T{var=value}] sets global \verb|var| to string \verb|"value"|; 4112\item[\T{var=}\rm\emph{value}] sets global \verb|var| to string \verb|"|\emph{value}\verb|"|;
3914\item[\T{filename}] executes file \verb|filename|. 4113\item[\emph{filename}] executes file \emph{filename}.
3915\end{description} 4114\end{description}
3916When called without arguments, 4115When called without arguments,
3917\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, 4116\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
@@ -3944,9 +4143,12 @@ then creates a table
3944 arg = {"t1", "t3"; n = 2, [0] = "b.lua"} 4143 arg = {"t1", "t3"; n = 2, [0] = "b.lua"}
3945\end{verbatim} 4144\end{verbatim}
3946and finally runs the file \T{b.lua}. 4145and finally runs the file \T{b.lua}.
3947\DefLIB{getargs} 4146
3948The stand-alone interpreter also provides a \verb|getargs| function that 4147The stand-alone interpreter includes
4148all standard libraries plus the reflexive debug interface.
4149It also provides a \verb|getargs| function that
3949can be used to access \emph{all} command line arguments. 4150can be used to access \emph{all} command line arguments.
4151\DefLIB{getargs}
3950For instance, if you call Lua with the line 4152For instance, if you call Lua with the line
3951\begin{verbatim} 4153\begin{verbatim}
3952 $ lua -c a b 4154 $ lua -c a b
@@ -3957,7 +4159,7 @@ then a call to \verb|getargs| in \verb|a| or \verb|b| will return the table
3957\end{verbatim} 4159\end{verbatim}
3958 4160
3959In interactive mode, 4161In interactive mode,
3960a multi-line statement can be written finishing intermediate 4162a multi-line statement can be written ending intermediate
3961lines with a backslash (`\verb|\|'). 4163lines with a backslash (`\verb|\|').
3962If the global variable \IndexVerb{_PROMPT} is defined as a string, 4164If the global variable \IndexVerb{_PROMPT} is defined as a string,
3963then its value is used as the prompt. 4165then its value is used as the prompt.
@@ -3966,19 +4168,26 @@ Therefore, the prompt can be changed directly on the command line:
3966 $ lua _PROMPT='myprompt> ' -i 4168 $ lua _PROMPT='myprompt> ' -i
3967\end{verbatim} 4169\end{verbatim}
3968or in any Lua programs by assigning to \verb|_PROMPT|. 4170or in any Lua programs by assigning to \verb|_PROMPT|.
4171Note the use of \verb|-i| to enter interactive mode; otherwise,
4172the program would end just after the assignment to \verb|_PROMPT|.
3969 4173
3970In Unix systems, Lua scripts can be made into executable programs 4174In Unix systems, Lua scripts can be made into executable programs
3971by using \verb|chmod +x| and the~\verb|#!| form, 4175by using \verb|chmod +x| and the~\verb|#!| form,
3972as in \verb|#!/usr/local/bin/lua|, 4176as in \verb|#!/usr/local/bin/lua|,
3973or \verb|#!/usr/local/bin/lua -f| to get other arguments. 4177or \verb|#!/usr/local/bin/lua -f| to get other arguments.
4178(Of course,
4179the location of the Lua interpreter may be different in your machine.
4180If \verb|lua| is in your \verb|PATH|,
4181then a more portable solution is \verb|#!/usr/bin/env lua|.)
3974 4182
3975 4183
4184%------------------------------------------------------------------------------
3976\section*{Acknowledgments} 4185\section*{Acknowledgments}
3977 4186
3978The authors would like to thank CENPES/PETROBRAS which, 4187The authors thank CENPES/PETROBRAS which,
3979jointly with \tecgraf, used early versions of 4188jointly with \tecgraf, used early versions of
3980this system extensively and gave valuable comments. 4189this system extensively and gave valuable comments.
3981The authors would also like to thank Carlos Henrique Levy, 4190The authors also thank Carlos Henrique Levy,
3982who found the name of the game. 4191who found the name of the game.
3983Lua means ``moon'' in Portuguese. 4192Lua means ``moon'' in Portuguese.
3984 4193
@@ -4045,6 +4254,7 @@ The \verb|lua_pushuserdata| function has been replaced by
4045\end{itemize} 4254\end{itemize}
4046 4255
4047%{=============================================================== 4256%{===============================================================
4257\newpage
4048\section*{The Complete Syntax of Lua} \label{BNF} 4258\section*{The Complete Syntax of Lua} \label{BNF}
4049 4259
4050\addcontentsline{toc}{section}{The Complete Syntax of Lua} 4260\addcontentsline{toc}{section}{The Complete Syntax of Lua}
@@ -4057,8 +4267,6 @@ The \verb|lua_pushuserdata| function has been replaced by
4057 4267
4058\index{grammar} 4268\index{grammar}
4059 4269
4060
4061
4062\begin{Produc} 4270\begin{Produc}
4063 4271
4064\produc{chunk}{\rep{stat \opt{\ter{;}}}} 4272\produc{chunk}{\rep{stat \opt{\ter{;}}}}
@@ -4081,7 +4289,7 @@ The \verb|lua_pushuserdata| function has been replaced by
4081\OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp 4289\OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp
4082 \rwd{do} block \rwd{end} 4290 \rwd{do} block \rwd{end}
4083\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} 4291\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
4084\OrNL \rwd{local} declist \opt{init} 4292\OrNL \rwd{local} namelist \opt{init}
4085} 4293}
4086 4294
4087\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} 4295\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}}
@@ -4097,7 +4305,7 @@ The \verb|lua_pushuserdata| function has been replaced by
4097 4305
4098\produc{varorfunc}{var \Or functioncall} 4306\produc{varorfunc}{var \Or functioncall}
4099 4307
4100\produc{declist}{\Nter{name} \rep{\ter{,} \Nter{name}}} 4308\produc{namelist}{\Nter{name} \rep{\ter{,} \Nter{name}}}
4101 4309
4102\produc{init}{\ter{=} explist1} 4310\produc{init}{\ter{=} explist1}
4103 4311
@@ -4160,6 +4368,10 @@ The \verb|lua_pushuserdata| function has been replaced by
4160\produc{unop}{\ter{-} \Or \rwd{not}} 4368\produc{unop}{\ter{-} \Or \rwd{not}}
4161 4369
4162\end{Produc} 4370\end{Produc}
4371
4372
4373\NOTE
4374This grammar is not (yet) consistent with the productions in the text.
4163%}=============================================================== 4375%}===============================================================
4164 4376
4165% Index 4377% Index