aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--manual.tex4539
1 files changed, 0 insertions, 4539 deletions
diff --git a/manual.tex b/manual.tex
deleted file mode 100644
index 35984019..00000000
--- a/manual.tex
+++ /dev/null
@@ -1,4539 +0,0 @@
1% $Id: manual.tex,v 2.1 2003/01/22 16:29:38 roberto Exp roberto $
2%{[(
3
4\documentclass[11pt,twoside]{article}
5\usepackage{fullpage}
6\usepackage{iso}
7\usepackage{graphicx}
8
9
10
11% Right arrow (internal use)
12\newcommand{\ra}{\(\rightarrow\)\ }
13
14% Terminal Simbols
15\newcommand{\ter}[1]{{\rm`{\tt#1}'}}
16%reserved words
17\newcommand{\rwd}[1]{{\bf\lowercase{#1}}}
18% empty production
19\newcommand{\emptyprod}{$\epsilon$ }
20
21% repetitions and optionals
22\newcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}}
23\newcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}}
24\newcommand{\oneormore}[1]{{\rm\{}#1{\/\rm\}$^+$}}
25
26\newcommand{\prg}[1]{{\it #1\/}}
27
28%productions: \produc{non-terminal}{rule}
29\newcommand{\produc}[2]{#1 & \ra & #2\index{grammar!#1}\\}
30
31%new line inside a production
32\newcommand{\NL}{\\ & &}
33%new line indented
34\newcommand{\NLI}{\NL\hspace{2ex}}
35
36% 'or'
37\newcommand{\Or}{$|$ }
38
39% 'or' in a new line
40\newcommand{\OrNL}{\\ & \Or & }
41
42%Environment for productions
43\newenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{5ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent}
44
45
46%\newcommand{\See}[1]{Section~\ref{#1}}
47\newcommand{\See}[1]{\S\ref{#1}}
48%\newcommand{\see}[1]{(see~\See{#1} on page \pageref{#1})}
49\newcommand{\see}[1]{(see~\See{#1})}
50\newcommand{\seepage}[1]{(see page~\pageref{#1})}
51\newcommand{\M}[1]{{\rm\emph{#1}}}
52\newcommand{\T}[1]{{\tt #1}}
53\newcommand{\Math}[1]{$#1$}
54\newcommand{\nil}{{\bf nil}}
55\newcommand{\False}{{\bf false}}
56\newcommand{\True}{{\bf true}}
57%\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
58\def\tecgraf{{\sf Tecgraf}}
59
60\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}}
61\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}}
62\newcommand{\IndexEmph}[1]{\emph{#1}\index{#1@{\lowercase{#1}}}}
63\newcommand{\IndexTM}[1]{\index{#1 event@{\Q{#1} event}}\index{metamethod!#1}}
64\newcommand{\Def}[1]{\emph{#1}\index{#1}}
65\newcommand{\IndexAPI}[1]{\T{#1}\DefAPI{#1}}
66\newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}}
67\newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}}
68\newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}}
69\newcommand{\IndexKW}[1]{\index{keywords!#1@{\tt #1}}}
70
71\newcommand{\Q}[1]{``#1''}
72\newcommand{\Em}{---}
73\newcommand{\En}{--}
74\newcommand{\C}[1]{}
75
76\newcommand{\ff}{$\bullet$\ }
77
78\newcommand{\Version}{5.0 (beta)}
79
80\newcommand{\Nter}[1]{{\tt#1}}
81\newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: }
82
83\newcommand{\At}{{\tt @}} %{\verb|@|}
84\newcommand{\Nb}{~}
85
86\makeindex
87
88\begin{document}
89
90%{===============================================================
91\thispagestyle{empty}
92\pagestyle{empty}
93
94{
95\parindent=0pt
96\vglue1.5in
97{\LARGE\bf
98The Lua Programming Language}
99\hfill
100\vskip4pt \hrule height 4pt width \hsize \vskip4pt
101\hfill
102Reference Manual for Lua version \Version
103\\
104\null
105\hfill
106Last revised on \today
107\\
108\vfill
109\centering
110\includegraphics[width=0.7\textwidth]{nolabel.ps}
111\vfill
112\vskip4pt \hrule height 2pt width \hsize
113}
114
115\newpage
116\begin{quotation}
117\parskip=10pt
118\parindent=0pt
119\footnotesize
120\null\vfill
121
122\noindent
123Copyright \copyright\ 2002 Tecgraf, PUC-Rio. All rights reserved.
124
125Permission is hereby granted, free of charge,
126to any person obtaining a copy of this software
127and associated documentation files (the "Software"),
128to deal in the Software without restriction,
129including without limitation the rights to use, copy, modify,
130merge, publish, distribute, sublicense,
131and/or sell copies of the Software,
132and to permit persons to whom the Software is furnished to do so,
133subject to the following conditions:
134
135The above copyright notice and this permission notice shall be
136included in all copies or substantial portions of the Software.
137
138THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
139EXPRESS OR IMPLIED,
140INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
141FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
142IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
143FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
144WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
145ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
146OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
147
148
149Copies of this manual can be obtained at
150Lua's official web site,
151\verb|www.lua.org|.
152
153\bigskip
154The Lua logo was designed by A. Nakonechny.
155Copyright \copyright\ 1998. All rights reserved.
156\end{quotation}
157%}===============================================================
158\newpage
159
160\title{\Large\bf Reference Manual of the Programming Language Lua \Version}
161
162\author{%
163Roberto Ierusalimschy\qquad
164Luiz Henrique de Figueiredo\qquad
165Waldemar Celes
166\vspace{1.0ex}\\
167\smallskip
168\small\tt lua@tecgraf.puc-rio.br
169\vspace{2.0ex}\\
170%MCC 08/95 ---
171\tecgraf\ --- Computer Science Department --- PUC-Rio
172}
173
174%\date{{\small \tt\$Date: 2003/01/22 16:29:38 $ $}}
175
176\maketitle
177
178\pagestyle{plain}
179\pagenumbering{roman}
180
181\begin{abstract}
182\noindent
183Lua is a powerful, light-weight programming language
184designed for extending applications.
185Lua is also frequently used as a general-purpose, stand-alone language.
186Lua combines simple procedural syntax
187(similar to Pascal)
188with
189powerful data description constructs
190based on associative arrays and extensible semantics.
191Lua is
192dynamically typed,
193interpreted from opcodes,
194and has automatic memory management with garbage collection,
195making it ideal for
196configuration,
197scripting,
198and
199rapid prototyping.
200
201This document describes version \Version{} of the Lua programming language
202and the Application Program Interface (API)
203that allows interaction between Lua programs and their host C~programs.
204\end{abstract}
205
206\def\abstractname{Resumo}
207\begin{abstract}
208\noindent
209Lua é uma linguagem de programação
210poderosa e leve,
211projetada para estender aplicações.
212Lua também é frequentemente usada como uma linguagem de propósito geral.
213Lua combina programação procedural
214(com sintaxe semelhante à de Pascal)
215com
216poderosas construções para descrição de dados,
217baseadas em tabelas associativas e semântica extensível.
218Lua é
219tipada dinamicamente,
220interpretada a partir de \emph{opcodes},
221e tem gerenciamento automático de memória com coleta de lixo.
222Essas características fazem de Lua uma linguagem ideal para
223configuração,
224automação (\emph{scripting})
225e prototipagem rápida.
226
227Este documento descreve a versão \Version{} da linguagem de
228programação Lua e a Interface de Programação (API) que permite
229a interação entre programas Lua e programas C~hospedeiros.
230\end{abstract}
231
232\newpage
233\null
234\newpage
235\tableofcontents
236
237\newpage
238\setcounter{page}{1}
239\pagestyle{plain}
240\pagenumbering{arabic}
241
242\catcode`\_=12
243\catcode`\$=12
244\catcode`\#=12
245\catcode`\%=12
246\catcode`\^=12
247\catcode`\~=12
248\catcode`\&=12
249
250
251
252\C{-------------------------------------------------------------------------}
253\section{Introduction}
254
255Lua is an extension programming language designed to support
256general procedural programming with data description
257facilities.
258Lua is intended to be used as a powerful, light-weight
259configuration language for any program that needs one.
260Lua is implemented as a library, written in C.
261
262Being an extension language, Lua has no notion of a \Q{main} program:
263it only works \emph{embedded} in a host client,
264called the \emph{embedding program} or simply the \emph{host}.
265This host program can invoke functions to execute a piece of Lua code,
266can write and read Lua variables,
267and can register C\Nb{}functions to be called by Lua code.
268Through the use of C\Nb{}functions, Lua can be augmented to cope with
269a wide range of different domains,
270thus creating customized programming languages sharing a syntactical framework.
271
272Lua is free software,
273and is provided as usual with no guarantees,
274as stated in its copyright notice.
275The implementation described in this manual is available
276at Lua's official web site, \verb|www.lua.org|.
277
278Like any other reference manual,
279this document is dry in places.
280For a discussion of the decisions behind the design of Lua,
281see the papers below,
282which are available at Lua's web site.
283\begin{itemize}
284\item
285R.\Nb{}Ierusalimschy, L.\Nb{}H.\Nb{}de Figueiredo, and W.\Nb{}Celes.
286Lua\Em{}an extensible extension language.
287\emph{Software: Practice & Experience} {\bf 26} #6 (1996) 635\En{}652.
288\item
289L.\Nb{}H.\Nb{}de Figueiredo, R.\Nb{}Ierusalimschy, and W.\Nb{}Celes.
290The design and implementation of a language for extending applications.
291\emph{Proceedings of XXI Brazilian Seminar on Software and Hardware} (1994) 273\En{}283.
292\item
293L.\Nb{}H.\Nb{}de Figueiredo, R.\Nb{}Ierusalimschy, and W.\Nb{}Celes.
294Lua: an extensible embedded language.
295\emph{Dr. Dobb's Journal} {\bf 21} #12 (Dec 1996) 26\En{}33.
296\item
297R.\Nb{}Ierusalimschy, L.\Nb{}H.\Nb{}de Figueiredo, and W.\Nb{}Celes.
298The evolution of an extension language: a history of Lua,
299\emph{Proceedings of V Brazilian Symposium on Programming Languages} (2001) B-14\En{}B-28.
300\end{itemize}
301
302Lua means \Q{moon} in Portuguese.
303
304\C{-------------------------------------------------------------------------}
305\section{Lua Concepts}\label{concepts}
306
307This section describes the main concepts of Lua as a language.
308The syntax and semantics of Lua are described in \See{language}.
309The discussion below is not purely conceptual;
310it includes references to the C\Nb{}API \see{API},
311because Lua is designed to be embedded in host programs.
312It also includes references to the standard libraries \see{libraries}.
313
314
315\subsection{Environment and Chunks}
316
317All statements in Lua are executed in a \Def{global environment}.
318This environment is initialized with a call from the embedding program to
319\verb|lua_open| and
320persists until a call to \verb|lua_close|
321or the end of the embedding program.
322The host program can create multiple independent global
323environments, and freely switch among them \see{mangstate}.
324
325The unit of execution of Lua is called a \Def{chunk}.
326A chunk is simply a sequence of statements.
327Statements are described in \See{stats}.
328
329A chunk may be stored in a file or in a string inside the host program.
330When a chunk is executed, first it is pre-compiled into opcodes for
331a virtual machine,
332and then the compiled statements are executed
333by an interpreter for the virtual machine.
334All modifications that a chunk makes to the global environment persist
335after the chunk ends.
336
337Chunks may also be pre-compiled into binary form and stored in files;
338see program \IndexVerb{luac} for details.
339Programs in source and compiled forms are interchangeable;
340Lua automatically detects the file type and acts accordingly.
341\index{pre-compilation}
342
343
344\subsection{Table of Globals} \label{global-table}
345
346????
347
348\subsection{\Index{Values and Types}} \label{TypesSec}
349
350Lua is a \emph{dynamically typed language}.
351That means that
352variables do not have types; only values do.
353There are no type definitions in the language.
354All values carry their own type.
355
356There are eight \Index{basic types} in Lua:
357\Def{nil}, \Def{boolean}, \Def{number},
358\Def{string}, \Def{function}, \Def{userdata}, \Def{thread}, and \Def{table}.
359\emph{Nil} is the type of the value \nil{},
360whose main property is to be different from any other value;
361usually it represents the absence of a useful value.
362\emph{Boolean} is the type of the values \False{} and \True{}.
363In Lua, both \nil{} and \False{} make a condition false,
364and any other value makes it true.
365\emph{Number} represents real (double-precision floating-point) numbers.
366(It is not difficult to build Lua interpreters that use other
367internal representations for numbers,
368such as single-precision float or long integers.)
369\emph{String} represents arrays of characters.
370\index{eight-bit clean}
371Lua is 8-bit clean,
372so strings may contain any 8-bit character,
373including embedded zeros (\verb|'\0'|) \see{lexical}.
374
375Functions are \emph{first-class values} in Lua.
376That means that functions can be stored in variables,
377passed as arguments to other functions, and returned as results.
378Lua can call (and manipulate) functions written in Lua and
379functions written in C
380\see{functioncall}.
381
382The type \emph{userdata} is provided to allow arbitrary C data to
383be stored in Lua variables.
384This type corresponds to a block of raw memory
385and has no pre-defined operations in Lua,
386except assignment and identity test.
387However, by using \emph{metatables},
388the programmer can define operations for userdata values
389\see{metatable}.
390Userdata values cannot be created or modified in Lua,
391only through the C\Nb{}API.
392This guarantees the integrity of data owned by the host program.
393
394The type \Def{thread} represents independent threads of execution,
395and it is used to implement coroutines.
396(This is an experimental area; it needs more documentation,
397and is subject to changes in the future.)
398
399The type \emph{table} implements \Index{associative arrays},
400that is, \Index{arrays} that can be indexed not only with numbers,
401but with any value (except \nil{}).
402Moreover,
403tables can be \emph{heterogeneous},
404that is, they can contain values of all types (except \nil{}).
405Tables are the sole data structuring mechanism in Lua;
406they may be used to represent not only ordinary arrays,
407but also symbol tables, sets, records, graphs, trees, etc.
408To represent \Index{records}, Lua uses the field name as an index.
409The language supports this representation by
410providing \verb|a.name| as syntactic sugar for \verb|a["name"]|.
411There are several convenient ways to create tables in Lua
412\see{tableconstructor}.
413
414Like indices, the value of a table field can be of any type.
415In particular,
416because functions are first class values,
417table fields may contain functions.
418Thus tables may also carry \emph{methods} \see{func-def}.
419
420Tables, functions, and userdata values are \emph{objects}:
421variables do not actually \emph{contain} these values,
422only \emph{references} to them.
423Assignment, parameter passing, and function returns
424always manipulate references to these values,
425and do not imply any kind of copy.
426
427The library function \verb|type| returns a string describing the type
428of a given value \see{pdf-type}.
429
430
431\subsubsection{Metatables}
432
433Each table and userdata object in Lua may have a \Index{metatable}.
434
435You can change several aspects of the behavior
436of an object by setting specific fields in its metatable.
437For instance, when an object is the operand of an addition,
438Lua checks for a function in the field \verb|"__add"| in its metatable.
439If it finds one,
440Lua calls that function to perform the addition.
441
442We call the keys in a metatable \Index{events},
443and the values \Index{metamethods}.
444In the previous example, \verb|"add"| is the event,
445and the function is the metamethod that performs the addition.
446
447A metatable controls how an object behaves in arithmetic operations,
448order comparisons, concatenation, and indexing.
449A metatable can also define a function to be called when a userdata
450is garbage collected.
451\See{metatable} gives a detailed description of which events you
452can control with metatables.
453
454You can query and change the metatable of an object
455through the \verb|setmetatable| and \verb|getmetatable|
456functions \see{pdf-getmetatable}.
457
458
459
460\subsection{Coercion} \label{coercion}
461
462Lua provides automatic conversion between
463string and number values at run time.
464Any arithmetic operation applied to a string tries to convert
465that string to a number, following the usual rules.
466Conversely, whenever a number is used where a string is expected,
467the number is converted to a string, in a reasonable format.
468The format is chosen so that
469a conversion from number to string then back to number
470reproduces the original number \emph{exactly}.
471For complete control of how numbers are converted to strings,
472use the \verb|format| function \see{format}.
473
474
475\subsection{Variables}
476
477There are two kinds of variables in Lua:
478global variables
479and local variables.
480Variables are assumed to be global unless explicitly declared local
481\see{localvar}.
482Before the first assignment to a variable, its value is \nil{}.
483
484All global variables live as fields in ordinary Lua tables.
485Usually, globals live in a table called \Index{table of globals}.
486However, a function can individually change its global table,
487so that all global variables in that function will refer to that table.
488This mechanism allows the creation of \Index{namespaces} and other
489modularization facilities.
490
491\Index{Local variables} are lexically scoped.
492Therefore, local variables can be freely accessed by functions
493defined inside their scope \see{visibility}.
494
495
496\subsection{Garbage Collection}\label{GC}
497
498Lua does automatic memory management.
499That means that
500you do not have to worry about allocating memory for new objects
501and freeing it when the objects are no longer needed.
502Lua manages memory automatically by running
503a \Index{garbage collector} from time to time
504and
505collecting all dead objects
506(all objects that are no longer accessible from Lua).
507All objects in Lua are subject to automatic management:
508tables, userdata, functions, and strings.
509
510Using the C\Nb{}API,
511you can set garbage-collector metamethods for userdata \see{metatable}.
512When it is about to free a userdata,
513Lua calls the metamethod associated with event \verb|gc| in the
514userdata's metatable.
515Using such facility, you can coordinate Lua's garbage collection
516with external resource management
517(such as closing files, network or database connections,
518or freeing your own memory).
519
520Lua uses two numbers to control its garbage-collection cycles.
521One number counts how many bytes of dynamic memory Lua is using,
522and the other is a threshold.
523When the number of bytes crosses the threshold,
524Lua runs the garbage collector,
525which reclaims the memory of all dead objects.
526The byte counter is adjusted,
527and then the threshold is reset to twice the new value of the byte counter.
528
529Through the C\Nb{}API, you can query those numbers,
530and change the threshold \see{GC-API}.
531Setting the threshold to zero actually forces an immediate
532garbage-collection cycle,
533while setting it to a huge number effectively stops the garbage collector.
534Using Lua code you have a more limited control over garbage-collection cycles,
535through the functions \verb|gcinfo| and \verb|collectgarbage|
536\see{predefined}.
537
538
539\subsubsection{Weak Tables}\label{weak-table}
540
541A \IndexEmph{weak table} is a table whose elements are
542\IndexEmph{weak references}.
543A weak reference is ignored by the garbage collector.
544In other words,
545if the only references to an object are weak references,
546then the garbage collector will collect that object.
547
548A weak table can have weak keys, weak values, or both.
549A table with weak keys allows the collection of its keys,
550but prevents the collection of its values.
551A table with both weak keys and weak values allows the collection of
552both keys and values.
553In any case, if either the key or the value is collected,
554the whole pair is removed from the table.
555The weakness of a table is controlled by the value of the
556\verb|__mode| field of its metatable.
557If the \verb|__mode| field is a string containing the character \verb|k|,
558the keys in the table are weak.
559If \verb|__mode| contains \verb|v|,
560the values in the table are weak.
561
562
563\C{-------------------------------------------------------------------------}
564\section{The Language}\label{language}
565
566This section describes the lexis, the syntax, and the semantics of Lua.
567In other words,
568this section describes
569which tokens are valid,
570how they can be combined,
571and what their combinations mean.
572
573\subsection{Lexical Conventions} \label{lexical}
574
575\IndexEmph{Identifiers} in Lua can be any string of letters,
576digits, and underscores,
577not beginning with a digit.
578This coincides with the definition of identifiers in most languages.
579(The definition of letter depends on the current locale:
580any character considered alphabetic by the current locale
581can be used in an identifier.)
582
583The following \IndexEmph{keywords} are reserved,
584and cannot be used as identifiers:
585\index{reserved words}
586\begin{verbatim}
587 and break do else elseif
588 end false for function if
589 in local nil not or
590 repeat return then true until
591 while
592\end{verbatim}
593
594Lua is a case-sensitive language:
595\T{and} is a reserved word, but \T{And} and \T{AND}
596are two different, valid identifiers.
597As a convention, identifiers starting with an underscore followed by
598uppercase letters (such as \verb|_VERSION|)
599are reserved for internal variables used by Lua.
600
601The following strings denote other \Index{tokens}:
602\begin{verbatim}
603 + - * / ^ =
604 ~= <= >= < > ==
605 ( ) { } [ ]
606 ; : , . .. ...
607\end{verbatim}
608
609\IndexEmph{Literal strings}
610can be delimited by matching single or double quotes,
611and can contain the C-like escape sequences
612`\verb|\a|' (bell),
613`\verb|\b|' (backspace),
614`\verb|\f|' (form feed),
615`\verb|\n|' (newline),
616`\verb|\r|' (carriage return),
617`\verb|\t|' (horizontal tab),
618`\verb|\v|' (vertical tab),
619`\verb|\\|' (backslash),
620`\verb|\"|' (quotation mark),
621`\verb|\'|' (apostrophe),
622`\verb|\[|' (left square bracket),
623`\verb|\]|' (right square bracket),
624and `\verb|\|\emph{newline}' (that is, a backslash followed by a real newline,
625which results in a newline in the string).
626A character in a string may also be specified by its numerical value
627using the escape sequence `\verb|\|\emph{ddd}',
628where \emph{ddd} is a sequence of up to three \emph{decimal} digits.
629Strings in Lua may contain any 8-bit value, including embedded zeros,
630which can be specified as `\verb|\0|'.
631
632Literal strings can also be delimited by matching
633\verb|[[| \Math{\ldots} \verb|]]|.
634Literals in this bracketed form may run for several lines,
635may contain nested \verb|[[| \Math{\ldots} \verb|]]| pairs,
636and do not interpret escape sequences.
637For convenience,
638when the opening \verb|[[| is immediately followed by a newline,
639the newline is not included in the string. \C{ ]]}
640That form is specially convenient for
641writing strings that contain program pieces or
642other quoted strings.
643As an example, in a system using ASCII
644(in which `\verb|a|' is coded as\Nb{}97,
645newline is coded as\Nb{}10, and `\verb|1|' is coded as\Nb{}49),
646the four literals below denote the same string:
647\begin{verbatim}
648 (1) "alo\n123\""
649 (2) '\97lo\10\04923"'
650 (3) [[alo
651 123"]]
652 (4) [[
653 alo
654 123"]]
655\end{verbatim}
656
657\IndexEmph{Numerical constants} may be written with an optional decimal part
658and an optional decimal exponent.
659Examples of valid numerical constants are
660\begin{verbatim}
661 3 3.0 3.1416 314.16e-2 0.31416E1
662\end{verbatim}
663
664\IndexEmph{Comments} start anywhere outside a string with a
665double hyphen (\verb|--|);
666If the text after \verb|--| is different from \verb|[[|,
667the comment is a short comment,
668that runs until the end of the line.
669Otherwise, it is a long comment,
670that runs until the corresponding \verb|]]|.
671Long comments may run for several lines,
672and may contain nested \verb|[[| \Math{\ldots} \verb|]]| pairs.
673For convenience,
674the first line of a chunk is skipped if it starts with \verb|#|.
675This facility allows the use of Lua as a script interpreter
676in Unix systems \see{lua-sa}.
677
678
679\subsection{Variables}\label{variables}
680
681Variables are places that store values.
682\C{In Lua, variables are given by simple identifiers or by table fields.}
683
684A single name can denote a global variable, a local variable,
685or a formal parameter in a function
686(formal parameters are just local variables):
687\begin{Produc}
688\produc{var}{\Nter{Name}}
689\end{Produc}
690Square brackets are used to index a table:
691\begin{Produc}
692\produc{var}{prefixexp \ter{[} exp \ter{]}}
693\end{Produc}
694The first expression should result in a table value,
695and the second expression identifies a specific entry inside that table.
696
697The syntax \verb|var.NAME| is just syntactic sugar for
698\verb|var["NAME"]|:
699\begin{Produc}
700\produc{var}{prefixexp \ter{.} \Nter{Name}}
701\end{Produc}
702
703The expression denoting the table to be indexed has a restricted syntax;
704see \See{expressions} for details.
705
706The meaning of assignments and evaluations of global and
707indexed variables can be changed via metatables.
708An assignment to a global variable \verb|x = val|
709is equivalent to the assignment
710\verb|_glob.x = val|,
711where \verb|_glob| is the table of globals of the running function
712(see \See{global-table} for a discussion about the table of globals).
713An assignment to an indexed variable \verb|t[i] = val| is equivalent to
714\verb|settable_event(t,i,val)|.
715An access to a global variable \verb|x|
716is equivalent to \verb|_glob.x|
717(again, see \See{global-table} for a discussion about \verb|_glob|).
718An access to an indexed variable \verb|t[i]| is equivalent to
719a call \verb|gettable_event(t,i)|.
720See \See{metatable} for a complete description of the
721\verb|settable_event| and \verb|gettable_event| functions.
722(These functions are not defined or callable in Lua.
723We use them here only for explanatory purposes.)
724
725
726\subsection{Statements}\label{stats}
727
728Lua supports an almost conventional set of \Index{statements},
729similar to those in Pascal or C.
730The conventional commands include
731assignment, control structures, and procedure calls.
732Non-conventional commands include table constructors
733and variable declarations.
734
735\subsubsection{Chunks}\label{chunks}
736The unit of execution of Lua is called a \Def{chunk}.
737A chunk is simply a sequence of statements,
738which are executed sequentially.
739Each statement can be optionally followed by a semicolon:
740\begin{Produc}
741\produc{chunk}{\rep{stat \opt{\ter{;}}}}
742\end{Produc}
743
744\subsubsection{Blocks}
745A \Index{block} is a list of statements;
746syntactically, a block is equal to a chunk:
747\begin{Produc}
748\produc{block}{chunk}
749\end{Produc}
750
751A block may be explicitly delimited to produce a single statement:
752\begin{Produc}
753\produc{stat}{\rwd{do} block \rwd{end}}
754\end{Produc}
755\IndexKW{do}
756Explicit blocks are useful
757to control the scope of variable declarations.
758Explicit blocks are also sometimes used to
759add a \rwd{return} or \rwd{break} statement in the middle
760of another block \see{control}.
761
762\subsubsection{\Index{Assignment}} \label{assignment}
763Lua allows \Index{multiple assignment}.
764Therefore, the syntax for assignment
765defines a list of variables on the left side
766and a list of expressions on the right side.
767The elements in both lists are separated by commas:
768\begin{Produc}
769\produc{stat}{varlist1 \ter{=} explist1}
770\produc{varlist1}{var \rep{\ter{,} var}}
771\produc{explist1}{exp \rep{\ter{,} exp}}
772\end{Produc}
773Expressions are discussed in \See{expressions}.
774
775Before the assignment,
776the list of values is \emph{adjusted} to the length of
777the list of variables.\index{adjustment}
778If there are more values than needed,
779the excess values are thrown away.
780If there are fewer values than needed,
781the list is extended with as many \nil{}'s as needed.
782If the list of expressions ends with a function call,
783then all values returned by that function call enter in the list of values,
784before the adjustment
785(except when the call is enclosed in parentheses; see \See{expressions}).
786
787The assignment statement first evaluates all its expressions,
788and only then are the assignments performed.
789Thus the code
790\begin{verbatim}
791 i = 3
792 i, a[i] = i+1, 20
793\end{verbatim}
794sets \verb|a[3]| to 20, without affecting \verb|a[4]|
795because the \verb|i| in \verb|a[i]| is evaluated
796before it is assigned 4.
797Similarly, the line
798\begin{verbatim}
799 x, y = y, x
800\end{verbatim}
801exchanges the values of \verb|x| and \verb|y|.
802
803\subsubsection{Control Structures}\label{control}
804The control structures
805\rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and
806familiar syntax:
807\index{while-do statement}\IndexKW{while}
808\index{repeat-until statement}\IndexKW{repeat}\IndexKW{until}
809\index{if-then-else statement}\IndexKW{if}\IndexKW{else}\IndexKW{elseif}
810\begin{Produc}
811\produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}}
812\produc{stat}{\rwd{repeat} block \rwd{until} exp}
813\produc{stat}{\rwd{if} exp \rwd{then} block
814 \rep{\rwd{elseif} exp \rwd{then} block}
815 \opt{\rwd{else} block} \rwd{end}}
816\end{Produc}
817Lua also has a \rwd{for} statement, in two flavors \see{for}.
818
819The \Index{condition expression} \M{exp} of a
820control structure may return any value.
821Both \False{} and \nil{} are considered false.
822All values different from \nil{} and \False{} are considered true
823(in particular, the number 0 and the empty string are also true).
824
825The \rwd{return} statement is used to return values
826from a function or from a chunk.\IndexKW{return}
827\label{return}
828\index{return statement}
829Functions and chunks may return more than one value,
830so the syntax for the \rwd{return} statement is
831\begin{Produc}
832\produc{stat}{\rwd{return} \opt{explist1}}
833\end{Produc}
834
835The \rwd{break} statement can be used to terminate the execution of a
836\rwd{while}, \rwd{repeat}, or \rwd{for} loop,
837and to skip to the next statement after the loop:\IndexKW{break}
838\index{break statement}
839\begin{Produc}
840\produc{stat}{\rwd{break}}
841\end{Produc}
842A \rwd{break} ends the innermost enclosing loop.
843
844\NOTE
845For syntactic reasons, \rwd{return} and \rwd{break}
846statements can only be written as the \emph{last} statement of a block.
847If it is really necessary to \rwd{return} or \rwd{break} in the
848middle of a block,
849then an explicit inner block can used,
850as in the idioms
851`\verb|do return end|' and
852`\verb|do break end|',
853because now \rwd{return} and \rwd{break} are the last statements in
854their (inner) blocks.
855In practice,
856those idioms are only used during debugging.
857(For instance, a line `\verb|do return end|' can be added at the
858beginning of a chunk for syntax checking only.)
859
860\subsubsection{For Statement} \label{for}\index{for statement}
861
862The \rwd{for} statement has two forms,
863one numeric and one generic.
864\IndexKW{for}\IndexKW{in}
865
866The numeric \rwd{for} loop repeats a block of code while a
867control variable runs through an arithmetic progression.
868It has the following syntax:
869\begin{Produc}
870\produc{stat}{\rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
871 \rwd{do} block \rwd{end}}
872\end{Produc}
873The \emph{block} is repeated for \emph{name} starting at the value of
874the first \emph{exp}, until it passes the second \emph{exp} by steps of the
875third \emph{exp}.
876More precisely, a \rwd{for} statement like
877\begin{verbatim}
878 for var = e1, e2, e3 do block end
879\end{verbatim}
880is equivalent to the code:
881\begin{verbatim}
882 do
883 local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
884 if not (var and _limit and _step) then error() end
885 while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
886 block
887 var = var+_step
888 end
889 end
890\end{verbatim}
891Note the following:
892\begin{itemize}\itemsep=0pt
893\item Both the limit and the step are evaluated only once,
894before the loop starts.
895\item \verb|_limit| and \verb|_step| are invisible variables.
896The names are here for explanatory purposes only.
897\item The behavior is \emph{undefined} if you assign to \verb|var| inside
898the block.
899\item If the third expression (the step) is absent, then a step of\Nb{}1 is used.
900\item You can use \rwd{break} to exit a \rwd{for} loop.
901\item The loop variable \verb|var| is local to the statement;
902you cannot use its value after the \rwd{for} ends or is broken.
903If you need the value of the loop variable \verb|var|,
904then assign it to another variable before breaking or exiting the loop.
905\end{itemize}
906
907The generic \rwd{for} statement works over functions,
908called \Index{generators}.
909It calls its generator to produce a new value for each iteration,
910stopping when the new value is \nil{}.
911It has the following syntax:
912\begin{Produc}
913\produc{stat}{\rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
914 \rwd{do} block \rwd{end}}
915\end{Produc}
916A \rwd{for} statement like
917\begin{verbatim}
918 for var_1, ..., var_n in explist do block end
919\end{verbatim}
920is equivalent to the code:
921\begin{verbatim}
922 do
923 local _f, _s, var_1, ..., var_n = explist
924 while true do
925 var_1, ..., var_n = _f(_s, var_1)
926 if var_1 == nil then break end
927 block
928 end
929 end
930\end{verbatim}
931Note the following:
932\begin{itemize}\itemsep=0pt
933\item \verb|explist| is evaluated only once.
934Its results are a \Q{generator} function,
935a \Q{state}, and an initial value for the first \Q{iterator variable}.
936\item \verb|_f| and \verb|_s| are invisible variables.
937The names are here for explanatory purposes only.
938\item The behavior is \emph{undefined} if you assign to any
939\verb|var_i| inside the block.
940\item You can use \rwd{break} to exit a \rwd{for} loop.
941\item The loop variables \verb|var_i| are local to the statement;
942you cannot use their values after the \rwd{for} ends.
943If you need these values,
944then assign them to other variables before breaking or exiting the loop.
945\end{itemize}
946
947
948\subsubsection{Function Calls as Statements} \label{funcstat}
949Because of possible side-effects,
950function calls can be executed as statements:
951\begin{Produc}
952\produc{stat}{functioncall}
953\end{Produc}
954In this case, all returned values are thrown away.
955Function calls are explained in \See{functioncall}.
956
957\subsubsection{Local Declarations} \label{localvar}
958\Index{Local variables} may be declared anywhere inside a block.
959The declaration may include an initial assignment:\IndexKW{local}
960\begin{Produc}
961\produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}}
962\produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
963\end{Produc}
964If present, an initial assignment has the same semantics
965of a multiple assignment \see{assignment}.
966Otherwise, all variables are initialized with \nil{}.
967
968A chunk is also a block \see{chunks},
969so local variables can be declared outside any explicit block.
970Such local variables die when the chunk ends.
971
972Visibility rules for local variables are explained in \See{visibility}.
973
974
975\subsection{\Index{Expressions}}\label{expressions}
976
977\C{\subsubsection{\Index{Basic Expressions}}}
978The basic expressions in Lua are the following:
979\begin{Produc}
980\produc{exp}{prefixexp}
981\produc{exp}{\rwd{nil} \Or \rwd{false} \Or \rwd{true}}
982\produc{exp}{Number}
983\produc{exp}{Literal}
984\produc{exp}{function}
985\produc{exp}{tableconstructor}
986\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
987\end{Produc}
988\IndexKW{nil}\IndexKW{false}\IndexKW{true}
989
990An expression enclosed in parentheses always results in only one value.
991Thus,
992\verb|(f(x,y,z))| is always a single value,
993even if \verb|f| returns several values.
994(The value of \verb|(f(x,y,z))| is the first value returned by \verb|f|
995or \nil{} if \verb|f| does not return any values.)
996
997\emph{Numbers} and \emph{literal strings} are explained in \See{lexical};
998variables are explained in \See{variables};
999function definitions are explained in \See{func-def};
1000function calls are explained in \See{functioncall};
1001table constructors are explained in \See{tableconstructor}.
1002
1003Expressions can also be built with arithmetic operators, relational operators,
1004and logical operators, all of which are explained below.
1005
1006\subsubsection{Arithmetic Operators}
1007Lua supports the usual \Index{arithmetic operators}:
1008the binary \verb|+| (addition),
1009\verb|-| (subtraction), \verb|*| (multiplication),
1010\verb|/| (division), and \verb|^| (exponentiation);
1011and unary \verb|-| (negation).
1012If the operands are numbers, or strings that can be converted to
1013numbers \see{coercion},
1014then all operations except exponentiation have the usual meaning,
1015while exponentiation calls a global function \verb|pow|; ??
1016otherwise, an appropriate metamethod is called \see{metatable}.
1017The standard mathematical library defines function \verb|pow|,
1018giving the expected meaning to \Index{exponentiation}
1019\see{mathlib}.
1020
1021\subsubsection{Relational Operators}\label{rel-ops}
1022The \Index{relational operators} in Lua are
1023\begin{verbatim}
1024 == ~= < > <= >=
1025\end{verbatim}
1026These operators always result in \False{} or \True{}.
1027
1028Equality (\verb|==|) first compares the type of its operands.
1029If the types are different, then the result is \False{}.
1030Otherwise, the values of the operands are compared.
1031Numbers and strings are compared in the usual way.
1032Tables, userdata, and functions are compared \emph{by reference},
1033that is,
1034two tables are considered equal only if they are the \emph{same} table.
1035
1036\C{TODO eq metamethod}
1037
1038Every time you create a new table (or userdata, or function),
1039this new value is different from any previously existing value.
1040
1041\NOTE
1042The conversion rules of \See{coercion}
1043\emph{do not} apply to equality comparisons.
1044Thus, \verb|"0"==0| evaluates to \emph{false},
1045and \verb|t[0]| and \verb|t["0"]| denote different
1046entries in a table.
1047\medskip
1048
1049The operator \verb|~=| is exactly the negation of equality (\verb|==|).
1050
1051The order operators work as follows.
1052If both arguments are numbers, then they are compared as such.
1053Otherwise, if both arguments are strings,
1054then their values are compared according to the current locale.
1055Otherwise, the \Q{lt} or the \Q{le} metamethod is called \see{metatable}.
1056
1057
1058\subsubsection{Logical Operators}
1059The \Index{logical operators} in Lua are
1060\index{and}\index{or}\index{not}
1061\begin{verbatim}
1062 and or not
1063\end{verbatim}
1064Like the control structures \see{control},
1065all logical operators consider both \False{} and \nil{} as false
1066and anything else as true.
1067\IndexKW{and}\IndexKW{or}\IndexKW{not}
1068
1069The operator \rwd{not} always return \False{} or \True{}.
1070
1071The conjunction operator \rwd{and} returns its first argument
1072if its value is \False{} or \nil{};
1073otherwise, \rwd{and} returns its second argument.
1074The disjunction operator \rwd{or} returns its first argument
1075if it is different from \nil{} and \False{};
1076otherwise, \rwd{or} returns its second argument.
1077Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation},
1078that is,
1079the second operand is evaluated only if necessary.
1080For example,
1081\begin{verbatim}
1082 10 or error() -> 10
1083 nil or "a" -> "a"
1084 nil and 10 -> nil
1085 false and error() -> false
1086 false and nil -> false
1087 false or nil -> nil
1088 10 and 20 -> 20
1089\end{verbatim}
1090
1091\subsubsection{Concatenation} \label{concat}
1092The string \Index{concatenation} operator in Lua is
1093denoted by two dots (`\verb|..|').
1094If both operands are strings or numbers, then they are converted to
1095strings according to the rules mentioned in \See{coercion}.
1096Otherwise, the \Q{concat} metamethod is called \see{metatable}.
1097
1098\subsubsection{Precedence}
1099\Index{Operator precedence} in Lua follows the table below,
1100from lower to higher priority:
1101\begin{verbatim}
1102 or
1103 and
1104 < > <= >= ~= ==
1105 ..
1106 + -
1107 * /
1108 not - (unary)
1109 ^
1110\end{verbatim}
1111The \verb|..| (concatenation) and \verb|^| (exponentiation)
1112operators are right associative.
1113All other binary operators are left associative.
1114
1115\subsubsection{Table Constructors} \label{tableconstructor}
1116Table \Index{constructors} are expressions that create tables;
1117every time a constructor is evaluated, a new table is created.
1118Constructors can be used to create empty tables,
1119or to create a table and initialize some of its fields.
1120The general syntax for constructors is
1121\begin{Produc}
1122\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
1123\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
1124\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or
1125 \Nter{Name} \ter{=} exp \Or exp}
1126\produc{fieldsep}{\ter{,} \Or \ter{;}}
1127\end{Produc}
1128
1129Each field of the form \verb|[exp1] = exp2| adds to the new table an entry
1130with key \verb|exp1| and value \verb|exp2|.
1131A field of the form \verb|name = exp| is equivalent to
1132\verb|["name"] = exp|.
1133Finally, fields of the form \verb|exp| are equivalent to
1134\verb|[i] = exp|, where \verb|i| are consecutive numerical integers,
1135starting with 1.
1136Fields in the other formats do not affect this counting.
1137For example,
1138\begin{verbatim}
1139 a = {[f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45}
1140\end{verbatim}
1141is equivalent to
1142\begin{verbatim}
1143 do
1144 local temp = {}
1145 temp[f(1)] = g
1146 temp[1] = "x" -- 1st exp
1147 temp[2] = "y" -- 2nd exp
1148 temp.x = 1 -- temp["x"] = 1
1149 temp[3] = f(x) -- 3rd exp
1150 temp[30] = 23
1151 temp[4] = 45 -- 4th exp
1152 a = temp
1153 end
1154\end{verbatim}
1155
1156If the last expression in the list is a function call,
1157then all values returned by the call enter the list consecutively
1158\see{functioncall}.
1159If you want to avoid this,
1160enclose the function call in parentheses.
1161
1162The field list may have an optional trailing separator,
1163as a convenience for machine-generated code.
1164
1165
1166\subsubsection{Function Calls} \label{functioncall}
1167A \Index{function call} in Lua has the following syntax:
1168\begin{Produc}
1169\produc{functioncall}{prefixexp args}
1170\end{Produc}
1171In a function call,
1172first \M{prefixexp} and \M{args} are evaluated.
1173If the value of \M{prefixexp} has type \emph{function},
1174then that function is called,
1175with the given arguments.
1176Otherwise, its \Q{call} metamethod is called,
1177having as first parameter the value of \M{prefixexp},
1178followed by the original call arguments
1179\see{metatable}.
1180
1181The form
1182\begin{Produc}
1183\produc{functioncall}{prefixexp \ter{:} \Nter{name} args}
1184\end{Produc}
1185can be used to call \Q{methods}.
1186A call \verb|v:name(...)|
1187is syntactic sugar for \verb|v.name(v, ...)|,
1188except that \verb|v| is evaluated only once.
1189
1190Arguments have the following syntax:
1191\begin{Produc}
1192\produc{args}{\ter{(} \opt{explist1} \ter{)}}
1193\produc{args}{tableconstructor}
1194\produc{args}{Literal}
1195\end{Produc}
1196All argument expressions are evaluated before the call.
1197A call of the form \verb|f{...}| is syntactic sugar for
1198\verb|f({...})|, that is,
1199the argument list is a single new table.
1200A call of the form \verb|f'...'|
1201(or \verb|f"..."| or \verb|f[[...]]|) is syntactic sugar for
1202\verb|f('...')|, that is,
1203the argument list is a single literal string.
1204
1205Because a function can return any number of results
1206\see{return},
1207the number of results must be adjusted before they are used.
1208If the function is called as a statement \see{funcstat},
1209then its return list is adjusted to\Nb{}0 elements,
1210thus discarding all returned values.
1211If the function is called inside another expression,
1212or in the middle of a list of expressions,
1213then its return list is adjusted to\Nb{}1 element,
1214thus discarding all returned values but the first one.
1215If the function is called as the last element of a list of expressions,
1216then no adjustment is made
1217(unless the call is enclosed in parentheses).
1218
1219Here are some examples:
1220\begin{verbatim}
1221 f() -- adjusted to 0 results
1222 g(f(), x) -- f() is adjusted to 1 result
1223 g(x, f()) -- g gets x plus all values returned by f()
1224 a,b,c = f(), x -- f() is adjusted to 1 result (and c gets nil)
1225 a,b,c = x, f() -- f() is adjusted to 2
1226 a,b,c = f() -- f() is adjusted to 3
1227 return f() -- returns all values returned by f()
1228 return x,y,f() -- returns x, y, and all values returned by f()
1229 {f()} -- creates a list with all values returned by f()
1230 {f(), nil} -- f() is adjusted to 1 result
1231\end{verbatim}
1232
1233If you enclose a function call in parentheses,
1234then it is adjusted to return exactly one value:
1235\begin{verbatim}
1236 return x,y,(f()) -- returns x, y, and the first value from f()
1237 {(f())} -- creates a table with exactly one element
1238\end{verbatim}
1239
1240As an exception to the format-free syntax of Lua,
1241you cannot put a line break before the \verb|(| in a function call.
1242That restriction avoids some ambiguities in the language.
1243If you write
1244\begin{verbatim}
1245 a = f
1246 (g).x(a)
1247\end{verbatim}
1248Lua would read that as \verb|a = f(g).x(a)|.
1249So, if you want two statements, you must add a semi-colon between them.
1250If you actually want to call \verb|f|,
1251you must remove the line break before \verb|(g)|.
1252
1253
1254\subsubsection{\Index{Function Definitions}} \label{func-def}
1255
1256The syntax for function definition is\IndexKW{function}
1257\begin{Produc}
1258\produc{function}{\rwd{function} funcbody}
1259\produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
1260\end{Produc}
1261
1262The following syntactic sugar simplifies function definitions:
1263\begin{Produc}
1264\produc{stat}{\rwd{function} funcname funcbody}
1265\produc{stat}{\rwd{local} \rwd{function} \Nter{name} funcbody}
1266\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} \opt{\ter{:} \Nter{name}}}
1267\end{Produc}
1268The statement
1269\begin{verbatim}
1270 function f () ... end
1271\end{verbatim}
1272translates to
1273\begin{verbatim}
1274 f = function () ... end
1275\end{verbatim}
1276The statement
1277\begin{verbatim}
1278 function t.a.b.c.f () ... end
1279\end{verbatim}
1280translates to
1281\begin{verbatim}
1282 t.a.b.c.f = function () ... end
1283\end{verbatim}
1284The statement
1285\begin{verbatim}
1286 local function f () ... end
1287\end{verbatim}
1288translates to
1289\begin{verbatim}
1290 local f; f = function () ... end
1291\end{verbatim}
1292
1293A function definition is an executable expression,
1294whose value has type \emph{function}.
1295When Lua pre-compiles a chunk,
1296all its function bodies are pre-compiled too.
1297Then, whenever Lua executes the function definition,
1298the function is \emph{instantiated} (or \emph{closed}).
1299This function instance (or \emph{closure})
1300is the final value of the expression.
1301Different instances of the same function
1302may refer to different non-local variables \see{visibility}
1303and may have different tables of globals \see{global-table}.
1304
1305Parameters act as local variables that are
1306initialized with the argument values:
1307\begin{Produc}
1308\produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}}
1309\produc{parlist1}{\ter{\ldots}}
1310\end{Produc}
1311\label{vararg}
1312When a function is called,
1313the list of \Index{arguments} is adjusted to
1314the length of the list of parameters,
1315unless the function is a \Def{vararg function},
1316which is
1317indicated by three dots (`\verb|...|') at the end of its parameter list.
1318A vararg function does not adjust its argument list;
1319instead, it collects all extra arguments into an implicit parameter,
1320called \IndexLIB{arg}.
1321The value of \verb|arg| is a table,
1322with a field\Nb{}\verb|n| whose value is the number of extra arguments,
1323and with the extra arguments at positions 1,\Nb{}2,\Nb{}\ldots,\Nb{}\verb|n|.
1324
1325As an example, consider the following definitions:
1326\begin{verbatim}
1327 function f(a, b) end
1328 function g(a, b, ...) end
1329 function r() return 1,2,3 end
1330\end{verbatim}
1331Then, we have the following mapping from arguments to parameters:
1332\begin{verbatim}
1333 CALL PARAMETERS
1334
1335 f(3) a=3, b=nil
1336 f(3, 4) a=3, b=4
1337 f(3, 4, 5) a=3, b=4
1338 f(r(), 10) a=1, b=10
1339 f(r()) a=1, b=2
1340
1341 g(3) a=3, b=nil, arg={n=0}
1342 g(3, 4) a=3, b=4, arg={n=0}
1343 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
1344 g(5, r()) a=5, b=1, arg={2, 3; n=2}
1345\end{verbatim}
1346
1347Results are returned using the \rwd{return} statement \see{return}.
1348If control reaches the end of a function
1349without encountering a \rwd{return} statement,
1350then the function returns with no results.
1351
1352The \emph{colon} syntax
1353is used for defining \IndexEmph{methods},
1354that is, functions that have an implicit extra parameter \IndexVerb{self}.
1355Thus, the statement
1356\begin{verbatim}
1357 function t.a.b.c:f (...) ... end
1358\end{verbatim}
1359is syntactic sugar for
1360\begin{verbatim}
1361 t.a.b.c.f = function (self, ...) ... end
1362\end{verbatim}
1363
1364
1365\subsection{Visibility Rules} \label{visibility}
1366\index{visibility}
1367
1368Lua is a lexically scoped language.
1369The scope of variables begins at the first statement \emph{after}
1370their declaration and lasts until the end of the innermost block that
1371includes the declaration.
1372For instance:
1373\begin{verbatim}
1374 x = 10 -- global variable
1375 do -- new block
1376 local x = x -- new `x', with value 10
1377 print(x) --> 10
1378 x = x+1
1379 do -- another block
1380 local x = x+1 -- another `x'
1381 print(x) --> 12
1382 end
1383 print(x) --> 11
1384 end
1385 print(x) --> 10 (the global one)
1386\end{verbatim}
1387Notice that, in a declaration like \verb|local x = x|,
1388the new \verb|x| being declared is not in scope yet,
1389so the second \verb|x| refers to the \Q{outside} variable.
1390
1391Because of these \Index{lexical scoping} rules,
1392local variables can be freely accessed by functions
1393defined inside their scope.
1394For instance:
1395\begin{verbatim}
1396 local counter = 0
1397 function inc (x)
1398 counter = counter + x
1399 return counter
1400 end
1401\end{verbatim}
1402
1403Notice that each execution of a \rwd{local} statement
1404\Q{creates} new local variables.
1405Consider the following example:
1406\begin{verbatim}
1407 a = {}
1408 local x = 20
1409 for i=1,10 do
1410 local y = 0
1411 a[i] = function () y=y+1; return x+y end
1412 end
1413\end{verbatim}
1414The loop creates ten closures
1415(that is, instances of the anonymous function).
1416Each of these closures uses a different \verb|y| variable,
1417while all of them share the same \verb|x|.
1418
1419\subsection{Error Handling} \label{error}
1420
1421Because Lua is an extension language,
1422all Lua actions start from C\Nb{}code in the host program
1423calling a function from the Lua library \see{pcall}.
1424Whenever an error occurs during Lua compilation or execution,
1425control returns to C,
1426which can take appropriate measures
1427(such as to print an error message).
1428
1429Lua code can explicitly generate an error by calling the
1430function \verb|error| \see{pdf-error}.
1431If you need to catch errors in Lua,
1432you can use the \verb|pcall| function \see{pdf-pcall}.
1433
1434
1435\subsection{Metatables} \label{metatable}
1436
1437Every table and userdata value in Lua may have a \emph{metatable}.
1438This \IndexEmph{metatable} is a table that defines the behavior of
1439the original table and userdata under certain special operations.
1440You can query and change the metatable of an object with
1441functions \verb|setmetatable| and \verb|getmetatable| \see{pdf-getmetatable}.
1442
1443For each of those operations Lua associates a specific key
1444called an \emph{event}.
1445When Lua performs one of those operations over a table or a userdata,
1446it checks whether that object has a metatable with the corresponding event.
1447If so, the value associated with that key (the \IndexEmph{metamethod})
1448controls how Lua will perform the operation.
1449
1450Metatables control the operations listed next.
1451Each operation is identified by its corresponding name.
1452The key for each operation is a string with its name prefixed by
1453two underscores;
1454for instance, the key for operation \Q{add} is the
1455string \verb|"__add"|.
1456The semantics of these operations is better explained by a Lua function
1457describing how the interpreter executes that operation.
1458\C{Each function shows how a handler is called,}
1459\C{its arguments (that is, its signature),}
1460\C{its results,}
1461\C{and the default behavior in the absence of a handler.}
1462The code shown here in Lua is only illustrative;
1463the real behavior is hard coded in the interpreter,
1464and it is much more efficient than this simulation.
1465All functions used in these descriptions
1466(\verb|rawget|, \verb|tonumber|, etc.)
1467are described in \See{predefined}.
1468
1469\begin{description}
1470
1471\item[\Q{add}:]\IndexTM{add}
1472the \verb|+| operation.
1473
1474The function \verb|getbinhandler| below defines how Lua chooses a handler
1475for a binary operation.
1476First, Lua tries the first operand.
1477If its type does not define a handler for the operation,
1478then Lua tries the second operand.
1479\begin{verbatim}
1480 function getbinhandler (op1, op2, event)
1481 return metatable(op1)[event] or metatable(op2)[event]
1482 end
1483\end{verbatim}
1484Using that function,
1485the behavior of the \Q{add} operation is
1486\begin{verbatim}
1487 function add_event (op1, op2)
1488 local o1, o2 = tonumber(op1), tonumber(op2)
1489 if o1 and o2 then -- both operands are numeric
1490 return o1+o2 -- '+' here is the primitive 'add'
1491 else -- at least one of the operands is not numeric
1492 local h = getbinhandler(op1, op2, "__add")
1493 if h then
1494 -- call the handler with both operands
1495 return h(op1, op2)
1496 else -- no handler available: default behavior
1497 error("unexpected type at arithmetic operation")
1498 end
1499 end
1500 end
1501\end{verbatim}
1502
1503\item[\Q{sub}:]\IndexTM{sub}
1504the \verb|-| operation.
1505Behavior similar to the \Q{add} operation.
1506
1507\item[\Q{mul}:]\IndexTM{mul}
1508the \verb|*| operation.
1509Behavior similar to the \Q{add} operation.
1510
1511\item[\Q{div}:]\IndexTM{div}
1512the \verb|/| operation.
1513Behavior similar to the \Q{add} operation.
1514
1515\item[\Q{pow}:]\IndexTM{pow}
1516the \verb|^| operation (exponentiation) operation.
1517\begin{verbatim} ??
1518 function pow_event (op1, op2)
1519 local h = getbinhandler(op1, op2, "__pow") ???
1520 if h then
1521 -- call the handler with both operands
1522 return h(op1, op2)
1523 else -- no handler available: default behavior
1524 error("unexpected type at arithmetic operation")
1525 end
1526 end
1527\end{verbatim}
1528
1529\item[\Q{unm}:]\IndexTM{unm}
1530the unary \verb|-| operation.
1531\begin{verbatim}
1532 function unm_event (op)
1533 local o = tonumber(op)
1534 if o then -- operand is numeric
1535 return -o -- '-' here is the primitive 'unm'
1536 else -- the operand is not numeric.
1537 -- Try to get a handler from the operand;
1538 local h = metatable(op).__unm
1539 if h then
1540 -- call the handler with the operand and nil
1541 return h(op, nil)
1542 else -- no handler available: default behavior
1543 error("unexpected type at arithmetic operation")
1544 end
1545 end
1546 end
1547\end{verbatim}
1548
1549\item[\Q{lt}:]\IndexTM{lt}
1550the \verb|<| operation.
1551\begin{verbatim}
1552 function lt_event (op1, op2)
1553 if type(op1) == "number" and type(op2) == "number" then
1554 return op1 < op2 -- numeric comparison
1555 elseif type(op1) == "string" and type(op2) == "string" then
1556 return op1 < op2 -- lexicographic comparison
1557 else
1558 local h = getbinhandler(op1, op2, "__lt")
1559 if h then
1560 return h(op1, op2)
1561 else
1562 error("unexpected type at comparison");
1563 end
1564 end
1565 end
1566\end{verbatim}
1567\verb|a>b| is equivalent to \verb|b<a|.
1568
1569\item[\Q{le}:]\IndexTM{lt}
1570the \verb|<=| operation.
1571\begin{verbatim}
1572 function le_event (op1, op2)
1573 if type(op1) == "number" and type(op2) == "number" then
1574 return op1 <= op2 -- numeric comparison
1575 elseif type(op1) == "string" and type(op2) == "string" then
1576 return op1 <= op2 -- lexicographic comparison
1577 else
1578 local h = getbinhandler(op1, op2, "__le")
1579 if h then
1580 return h(op1, op2)
1581 else
1582 h = getbinhandler(op1, op2, "__lt")
1583 if h then
1584 return not h(op2, op1)
1585 else
1586 error("unexpected type at comparison");
1587 end
1588 end
1589 end
1590 end
1591\end{verbatim}
1592\verb|a>=b| is equivalent to \verb|b<=a|.
1593Notice that, in the absence of a \Q{le} metamethod,
1594Lua tries the \Q{lt}, assuming that \verb|a<=b| is
1595equivalent to \verb|not (b<a)|.
1596
1597
1598\item[\Q{concat}:]\IndexTM{concatenation}
1599the \verb|..| (concatenation) operation.
1600\begin{verbatim}
1601 function concat_event (op1, op2)
1602 if (type(op1) == "string" or type(op1) == "number") and
1603 (type(op2) == "string" or type(op2) == "number") then
1604 return op1..op2 -- primitive string concatenation
1605 else
1606 local h = getbinhandler(op1, op2, "__concat")
1607 if h then
1608 return h(op1, op2)
1609 else
1610 error("unexpected type for concatenation")
1611 end
1612 end
1613 end
1614\end{verbatim}
1615
1616\item[\Q{index}:]\IndexTM{index}
1617The \Q{gettable} operation \verb|table[key]|.
1618\begin{verbatim}
1619 function gettable_event (table, key)
1620 local h
1621 if type(table) == "table" then
1622 local v = rawget(table, key)
1623 if v ~= nil then return v end
1624 h = metatable(table).__index
1625 if h == nil then return nil end
1626 else
1627 h = metatable(table).__index
1628 if h == nil then
1629 error("indexed expression not a table");
1630 end
1631 end
1632 if type(h) == "function" then
1633 return h(table, key) -- call the handler
1634 else return h[key] -- or repeat operation with it
1635 end
1636\end{verbatim}
1637
1638\item[\Q{newindex}:]\IndexTM{index}
1639The \Q{settable} operation \verb|table[key] = value|.
1640\begin{verbatim}
1641 function settable_event (table, key, value)
1642 local h
1643 if type(table) == "table" then
1644 local v = rawget(table, key)
1645 if v ~= nil then rawset(table, key, value); return end
1646 h = metatable(table).__newindex
1647 if h == nil then rawset(table, key, value); return end
1648 else
1649 h = metatable(table).__newindex
1650 if h == nil then
1651 error("indexed expression not a table");
1652 end
1653 end
1654 if type(h) == "function" then
1655 return h(table, key,value) -- call the handler
1656 else h[key] = value -- or repeat operation with it
1657 end
1658\end{verbatim}
1659
1660
1661\item[\Q{call}:]\IndexTM{call}
1662called when Lua calls a value.
1663\begin{verbatim}
1664 function function_event (func, ...)
1665 if type(func) == "function" then
1666 return func(unpack(arg)) -- regular call
1667 else
1668 local h = metatable(func).__call
1669 if h then
1670 table.insert(arg, 1, func)
1671 return h(unpack(arg))
1672 else
1673 error("call expression not a function")
1674 end
1675 end
1676 end
1677\end{verbatim}
1678
1679\end{description}
1680
1681\subsubsection{Metatables and Garbage collection}
1682
1683Metatables may also define \IndexEmph{finalizer} methods
1684for userdata values.
1685For each userdata to be collected,
1686Lua does the equivalent of the following function:
1687\begin{verbatim}
1688 function gc_event (obj)
1689 local h = metatable(obj).__gc
1690 if h then
1691 h(obj)
1692 end
1693 end
1694\end{verbatim}
1695In a garbage-collection cycle,
1696the finalizers for userdata are called in \emph{reverse}
1697order of their creation,
1698that is, the first finalizer to be called is the one associated
1699with the last userdata created in the program
1700(among those to be collected in the same cycle).
1701
1702
1703
1704\subsection{Coroutines}
1705
1706Lua supports coroutines,
1707also called \emph{semi-coroutines}
1708or \emph{collaborative multithreading}.
1709A coroutine in Lua represents an independent thread of execution.
1710Unlike \Q{real} threads, however,
1711a coroutine only suspends its execution by explicitly calling
1712an yield function.
1713
1714You create a coroutine with a call to \IndexVerb{coroutine.create}.
1715Its sole argument is a function
1716that is the main function of the coroutine.
1717The \verb|coroutine.create| only creates a new coroutine and
1718returns a handle to it (an object of type \emph{thread}).
1719It does not start the coroutine execution.
1720
1721When you first call \IndexVerb{coroutine.resume},
1722passing as argument the thread returned by \verb|coroutine.create|,
1723the coroutine starts its execution,
1724at the first line of its main function.
1725Extra arguments passed to \verb|coroutine.resume| are given as
1726parameters for the coroutine main function.
1727After the coroutine starts running,
1728it runs until it terminates or it \emph{yields}.
1729
1730A coroutine can terminate its execution in two ways:
1731Normally, when its main function returns
1732(explicitly or implicitly, after the last instruction);
1733and abnormally, if there is an unprotected error.
1734In the first case, \verb|coroutine.resume| returns \True{},
1735plus any values returned by the coroutine main function.
1736In case of errors, \verb|coroutine.resume| returns \False{}
1737plus an error message.
1738
1739A coroutine yields by calling \IndexVerb{coroutine.yield}.
1740When a coroutine yields,
1741the corresponding \verb|coroutine.resume| returns immediately,
1742even if the yield happens inside nested function calls
1743(that is, not in the main function,
1744but in a function directly or indirectly called by the main function).
1745In the case of a yield, \verb|coroutine.resume| also returns \True{},
1746plus any values passed to \verb|coroutine.yield|.
1747The next time you resume the same coroutine,
1748it continues its execution from the point where it yielded,
1749with the call to \verb|coroutine.yield| returning any extra
1750arguments passed to \verb|coroutine.resume|.
1751
1752The \IndexVerb{coroutine.wrap} function creates a coroutine
1753like \verb|coroutine.create|,
1754but instead of returning the coroutine itself,
1755it returns a function that, when called, resumes the coroutine.
1756Any arguments passed to that function
1757go as extra arguments to resume.
1758The function returns all the values returned by resume,
1759but the first one (the boolean error code).
1760Unlike \verb|coroutine.resume|,
1761this function does not catch errors;
1762any error is propagated to the caller.
1763
1764As a complete example,
1765consider the next code:
1766\begin{verbatim}
1767function foo1 (a)
1768 print("foo", a)
1769 return coroutine.yield(2*a)
1770end
1771
1772co = coroutine.create(function (a,b)
1773 print("co-body", a, b)
1774 local r = foo1(a+1)
1775 print("co-body", r)
1776 local r, s = coroutine.yield(a+b, a-b)
1777 print("co-body", r, s)
1778 return b, "end"
1779end)
1780
1781a, b = coroutine.resume(co, 1, 10)
1782print("main", a, b)
1783a, b, c = coroutine.resume(co, "r")
1784print("main", a, b, c)
1785a, b, c = coroutine.resume(co, "x", "y")
1786print("main", a, b, c)
1787a, b = coroutine.resume(co, "x", "y")
1788print("main", a, b)
1789\end{verbatim}
1790When you run it, it produces the following output:
1791\begin{verbatim}
1792co-body 1 10
1793foo 2
1794main true 4
1795co-body r
1796main true 11 -9
1797co-body x y
1798main true 10 end
1799main false cannot resume dead coroutine
1800\end{verbatim}
1801
1802
1803
1804\C{-------------------------------------------------------------------------}
1805\section{The Application Program Interface}\label{API}
1806\index{C API}
1807
1808This section describes the API for Lua, that is,
1809the set of C\Nb{}functions available to the host program to communicate
1810with Lua.
1811All API functions and related types and constants
1812are declared in the header file \verb|lua.h|.
1813
1814\NOTE
1815Even when we use the term \Q{function},
1816any facility in the API may be provided as a \emph{macro} instead.
1817All such macros use each of its arguments exactly once
1818(except for the first argument, which is always a Lua state),
1819and so do not generate hidden side-effects.
1820
1821
1822\subsection{States} \label{mangstate}
1823
1824The Lua library is fully reentrant:
1825it has no global variables.
1826\index{state}
1827The whole state of the Lua interpreter
1828(global variables, stack, etc.)
1829is stored in a dynamically allocated structure of type \verb|lua_State|;
1830\DefAPI{lua_State}
1831this state must be passed as the first argument to
1832every function in the library (except \verb|lua_open| below).
1833
1834Before calling any API function,
1835you must create a state by calling
1836\begin{verbatim}
1837 lua_State *lua_open (void);
1838\end{verbatim}
1839\DefAPI{lua_open}
1840
1841To release a state created with \verb|lua_open|, call
1842\begin{verbatim}
1843 void lua_close (lua_State *L);
1844\end{verbatim}
1845\DefAPI{lua_close}
1846This function destroys all objects in the given Lua environment
1847(calling the corresponding garbage-collection metamethods, if any)
1848and frees all dynamic memory used by that state.
1849On several platforms, you may not need to call this function,
1850because all resources are naturally released when the host program ends.
1851On the other hand,
1852long-running programs \Em{}
1853like a daemon or a web server \Em{}
1854might need to release states as soon as they are not needed,
1855to avoid growing too large.
1856
1857
1858\subsection{Threads}
1859
1860Lua offers partial support for multiple threads of execution.
1861If you have a C\Nb{}library that offers multi-threading,
1862then Lua can cooperate with it to implement the equivalent facility in Lua.
1863Also, Lua implements its own coroutine system on top of threads.
1864The following function creates a new \Q{thread} in Lua:
1865\begin{verbatim}
1866 lua_State *lua_newthread (lua_State *L);
1867\end{verbatim}
1868\DefAPI{lua_newthread}
1869The new state returned by this function shares with the original state
1870all global environment (such as tables),
1871but has an independent run-time stack.
1872(The use of these multiple stacks must be \Q{synchronized} with C.
1873How to explain that? TO BE WRITTEN.)
1874
1875Each thread has an independent table for global variables.
1876When you create a thread, this table is the same as that of the given state,
1877but you can change each one independently.
1878
1879You destroy threads with \DefAPI{lua_closethread}
1880\begin{verbatim}
1881 void lua_closethread (lua_State *L, lua_State *thread);
1882\end{verbatim}
1883You cannot close the sole (or last) thread of a state.
1884Instead, you must close the state itself.
1885
1886
1887\subsection{The Stack and Indices}
1888
1889Lua uses a virtual \emph{stack} to pass values to and from C.
1890Each element in this stack represents a Lua value
1891(\nil{}, number, string, etc.).
1892
1893Each C invocation has its own stack.
1894Whenever Lua calls C, the called function gets a new stack,
1895which is independent of previous stacks and of stacks of still
1896active C functions.
1897That stack initially contains any arguments to the C function,
1898and it is where the C function pushes its results \see{LuacallC}.
1899
1900For convenience,
1901most query operations in the API do not follow a strict stack discipline.
1902Instead, they can refer to any element in the stack by using an \emph{index}:
1903A positive index represents an \emph{absolute} stack position
1904(starting at\Nb{}1);
1905a negative index represents an \emph{offset} from the top of the stack.
1906More specifically, if the stack has \M{n} elements,
1907then index\Nb{}1 represents the first element
1908(that is, the element that was pushed onto the stack first),
1909and
1910index\Nb{}\M{n} represents the last element;
1911index\Nb{}\Math{-1} also represents the last element
1912(that is, the element at the top),
1913and index \Math{-n} represents the first element.
1914We say that an index is \emph{valid}
1915if it lies between\Nb{}1 and the stack top
1916(that is, if \verb|1 <= abs(index) <= top|).
1917\index{stack index} \index{valid index}
1918
1919At any time, you can get the index of the top element by calling
1920\begin{verbatim}
1921 int lua_gettop (lua_State *L);
1922\end{verbatim}
1923\DefAPI{lua_gettop}
1924Because indices start at\Nb{}1,
1925the result of \verb|lua_gettop| is equal to the number of elements in the stack
1926(and so 0\Nb{}means an empty stack).
1927
1928When you interact with Lua API,
1929\emph{you are responsible for controlling stack overflow}.
1930The function
1931\begin{verbatim}
1932 int lua_checkstack (lua_State *L, int extra);
1933\end{verbatim}
1934\DefAPI{lua_checkstack}
1935grows the stack size to \verb|top + extra| elements;
1936it returns false if it cannot grow the stack to that size.
1937This function never shrinks the stack;
1938if the stack is already bigger than the new size,
1939it is left unchanged.
1940
1941Whenever Lua calls C, \DefAPI{LUA_MINSTACK}
1942it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true,
1943that is,
1944at least \verb|LUA_MINSTACK| positions are still available.
1945\verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20,
1946so that usually you do not have to worry about stack space
1947unless your code has loops pushing elements onto the stack.
1948
1949Most query functions accept as indices any value inside the
1950available stack space, that is, indices up to the maximum stack size
1951you (or Lua) have set through \verb|lua_checkstack|.
1952Such indices are called \emph{acceptable indices}.
1953More formally, we define an \IndexEmph{acceptable index}
1954as follows:
1955\begin{verbatim}
1956 (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace)
1957\end{verbatim}
1958Note that 0 is never an acceptable index.
1959
1960Unless otherwise noted,
1961any function that accepts valid indices can also be called with
1962\Index{pseudo-indices},
1963which represent some Lua values that are accessible to the C\Nb{}code
1964but are not in the stack.
1965Pseudo-indices are used to access the table of globals \see{globals},
1966the registry, and the upvalues of a C function \see{c-closure}.
1967
1968\subsection{Stack Manipulation}
1969The API offers the following functions for basic stack manipulation:
1970\begin{verbatim}
1971 void lua_settop (lua_State *L, int index);
1972 void lua_pushvalue (lua_State *L, int index);
1973 void lua_remove (lua_State *L, int index);
1974 void lua_insert (lua_State *L, int index);
1975 void lua_replace (lua_State *L, int index);
1976\end{verbatim}
1977\DefAPI{lua_settop}\DefAPI{lua_pushvalue}
1978\DefAPI{lua_remove}\DefAPI{lua_insert}\DefAPI{lua_replace}
1979
1980\verb|lua_settop| accepts any acceptable index,
1981or 0,
1982and sets the stack top to that index.
1983If the new top is larger than the old one,
1984then the new elements are filled with \nil{}.
1985If \verb|index| is 0, then all stack elements are removed.
1986A useful macro defined in the \verb|lua.h| is
1987\begin{verbatim}
1988 #define lua_pop(L,n) lua_settop(L, -(n)-1)
1989\end{verbatim}
1990\DefAPI{lua_pop}
1991which pops \verb|n| elements from the stack.
1992
1993\verb|lua_pushvalue| pushes onto the stack a copy of the element
1994at the given index.
1995\verb|lua_remove| removes the element at the given position,
1996shifting down the elements above that position to fill the gap.
1997\verb|lua_insert| moves the top element into the given position,
1998shifting up the elements above that position to open space.
1999\verb|lua_replace| moves the top element into the given position,
2000without shifting any element (therefore replacing the value at
2001the given position).
2002These functions accept only valid indices.
2003(Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with
2004pseudo-indices, as they do not represent a stack position.)
2005
2006As an example, if the stack starts as \verb|10 20 30 40 50*|
2007(from bottom to top; the \verb|*| marks the top),
2008then
2009\begin{verbatim}
2010 lua_pushvalue(L, 3) --> 10 20 30 40 50 30*
2011 lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30*
2012 lua_remove(L, -3) --> 10 20 30 40 30 30*
2013 lua_remove(L, 6) --> 10 20 30 40 30*
2014 lua_insert(L, 1) --> 30 10 20 30 40*
2015 lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
2016 lua_replace(L, 2) --> 30 40 20 30*
2017 lua_settop(L, -3) --> 30 40*
2018 lua_settop(L, 6) --> 30 40 nil nil nil nil*
2019\end{verbatim}
2020
2021
2022
2023\subsection{Querying the Stack}
2024
2025To check the type of a stack element,
2026the following functions are available:
2027\begin{verbatim}
2028 int lua_type (lua_State *L, int index);
2029 int lua_isnil (lua_State *L, int index);
2030 int lua_isboolean (lua_State *L, int index);
2031 int lua_isnumber (lua_State *L, int index);
2032 int lua_isstring (lua_State *L, int index);
2033 int lua_istable (lua_State *L, int index);
2034 int lua_isfunction (lua_State *L, int index);
2035 int lua_iscfunction (lua_State *L, int index);
2036 int lua_isuserdata (lua_State *L, int index);
2037 int lua_islightuserdata (lua_State *L, int index);
2038\end{verbatim}
2039\DefAPI{lua_type}
2040\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
2041\DefAPI{lua_istable}\DefAPI{lua_isboolean}
2042\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}
2043\DefAPI{lua_isuserdata}\DefAPI{lua_islightuserdata}
2044These functions can be called with any acceptable index.
2045
2046\verb|lua_type| returns the type of a value in the stack,
2047or \verb|LUA_TNONE| for a non-valid index
2048(that is, if that stack position is \Q{empty}).
2049The types are coded by the following constants
2050defined in \verb|lua.h|:
2051\verb|LUA_TNIL|,
2052\verb|LUA_TNUMBER|,
2053\verb|LUA_TBOOLEAN|,
2054\verb|LUA_TSTRING|,
2055\verb|LUA_TTABLE|,
2056\verb|LUA_TFUNCTION|,
2057\verb|LUA_TUSERDATA|,
2058\verb|LUA_TTHREAD|,
2059\verb|LUA_TLIGHTUSERDATA|.
2060The following function translates such constants to a type name:
2061\begin{verbatim}
2062 const char *lua_typename (lua_State *L, int type);
2063\end{verbatim}
2064\DefAPI{lua_typename}
2065
2066The \verb|lua_is*| functions return\Nb{}1 if the object is compatible
2067with the given type, and 0 otherwise.
2068\verb|lua_isboolean| is an exception to this rule,
2069and it succeeds only for boolean values
2070(otherwise it would be useless,
2071as any value has a boolean value).
2072They always return 0 for a non-valid index.
2073\verb|lua_isnumber| accepts numbers and numerical strings,
2074\verb|lua_isstring| accepts strings and numbers \see{coercion},
2075\verb|lua_isfunction| accepts both Lua functions and C\Nb{}functions,
2076and \verb|lua_isuserdata| accepts both full and light userdata.
2077To distinguish between Lua functions and C\Nb{}functions,
2078you should use \verb|lua_iscfunction|.
2079To distinguish between full and light userdata,
2080you can use \verb|lua_islightuserdata|.
2081To distinguish between numbers and numerical strings,
2082you can use \verb|lua_type|.
2083
2084The API also has functions to compare two values in the stack:
2085\begin{verbatim}
2086 int lua_equal (lua_State *L, int index1, int index2);
2087 int lua_lessthan (lua_State *L, int index1, int index2);
2088\end{verbatim}
2089\DefAPI{lua_equal} \DefAPI{lua_lessthan}
2090These functions are equivalent to their counterparts in Lua \see{rel-ops}.
2091Both functions return 0 if any of the indices are non-valid.
2092
2093\subsection{Getting Values from the Stack}\label{lua-to}
2094
2095To translate a value in the stack to a specific C\Nb{}type,
2096you can use the following conversion functions:
2097\begin{verbatim}
2098 int lua_toboolean (lua_State *L, int index);
2099 lua_Number lua_tonumber (lua_State *L, int index);
2100 const char *lua_tostring (lua_State *L, int index);
2101 size_t lua_strlen (lua_State *L, int index);
2102 lua_CFunction lua_tocfunction (lua_State *L, int index);
2103 void *lua_touserdata (lua_State *L, int index);
2104\end{verbatim}
2105\DefAPI{lua_tonumber}\DefAPI{lua_tostring}\DefAPI{lua_strlen}
2106\DefAPI{lua_tocfunction}\DefAPI{lua_touserdata}\DefAPI{lua_toboolean}
2107These functions can be called with any acceptable index.
2108When called with a non-valid index,
2109they act as if the given value had an incorrect type.
2110
2111\verb|lua_toboolean| converts the Lua value at the given index
2112to a C \Q{boolean} value (that is, 0 or 1).
2113Like all tests in Lua, it returns 1 for any Lua value different from
2114\False{} and \nil{};
2115otherwise it returns 0.
2116It also returns 0 when called with a non-valid index.
2117(If you want to accept only real boolean values,
2118use \verb|lua_isboolean| to test the type of the value.)
2119
2120\verb|lua_tonumber| converts the Lua value at the given index
2121to a number (by default, \verb|lua_Number| is \verb|double|).
2122\DefAPI{lua_Number}
2123The Lua value must be a number or a string convertible to number
2124\see{coercion}; otherwise, \verb|lua_tonumber| returns\Nb{}0.
2125
2126\verb|lua_tostring| converts the Lua value at the given index to a string
2127(\verb|const char*|).
2128The Lua value must be a string or a number;
2129otherwise, the function returns \verb|NULL|.
2130If the value is a number,
2131then \verb|lua_tostring| also
2132\emph{changes the actual value in the stack to a string}.
2133(This change confuses \verb|lua_next|
2134when \verb|lua_tostring| is applied to keys.)
2135\verb|lua_tostring| returns a fully aligned pointer
2136to a string inside the Lua environment.
2137This string always has a zero (\verb|'\0'|)
2138after its last character (as in\Nb{}C),
2139but may contain other zeros in its body.
2140If you do not know whether a string may contain zeros,
2141you can use \verb|lua_strlen| to get its actual length.
2142Because Lua has garbage collection,
2143there is no guarantee that the pointer returned by \verb|lua_tostring|
2144will be valid after the corresponding value is removed from the stack.
2145If you need the string after the current function returns,
2146then you should duplicate it (or put it into the registry \see{registry}).
2147
2148\verb|lua_tocfunction| converts a value in the stack to a C\Nb{}function.
2149This value must be a C\Nb{}function;
2150otherwise, \verb|lua_tocfunction| returns \verb|NULL|.
2151The type \verb|lua_CFunction| is explained in \See{LuacallC}.
2152
2153\verb|lua_touserdata| is explained in \See{userdata}.
2154
2155
2156\subsection{Pushing Values onto the Stack}
2157
2158The API has the following functions to
2159push C\Nb{}values onto the stack:
2160\begin{verbatim}
2161 void lua_pushboolean (lua_State *L, int b);
2162 void lua_pushnumber (lua_State *L, lua_Number n);
2163 void lua_pushlstring (lua_State *L, const char *s, size_t len);
2164 void lua_pushstring (lua_State *L, const char *s);
2165 void lua_pushnil (lua_State *L);
2166 void lua_pushcfunction (lua_State *L, lua_CFunction f);
2167 void lua_pushlightuserdata (lua_State *L, void *p);
2168\end{verbatim}
2169
2170\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring}
2171\DefAPI{lua_pushcfunction}\DefAPI{lua_pushlightuserdata}\DefAPI{lua_pushboolean}
2172\DefAPI{lua_pushnil}\label{pushing}
2173These functions receive a C\Nb{}value,
2174convert it to a corresponding Lua value,
2175and push the result onto the stack.
2176In particular, \verb|lua_pushlstring| and \verb|lua_pushstring|
2177make an internal copy of the given string.
2178\verb|lua_pushstring| can only be used to push proper C\Nb{}strings
2179(that is, strings that end with a zero and do not contain embedded zeros);
2180otherwise, you should use the more general \verb|lua_pushlstring|,
2181which accepts an explicit size.
2182
2183You can also push \Q{formatted} strings:
2184\begin{verbatim}
2185 const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
2186 const char *lua_pushvfstring (lua_State *L, const char *fmt,
2187 va_list argp);
2188\end{verbatim}
2189\DefAPI{lua_pushfstring}\DefAPI{lua_pushvfstring}
2190Both functions push onto the stack a formatted string,
2191and return a pointer to that string.
2192These functions are similar to \verb|sprintf| and \verb|vsprintf|,
2193but with some important differences:
2194\begin{itemize}
2195\item You do not have to allocate the space for the result;
2196the result is a Lua string, and Lua takes care of memory allocation
2197(and deallocation, later).
2198\item The conversion specifiers are quite restricted.
2199There are no flags, widths, or precisions.
2200The conversion specifiers can be simply
2201\verb|%%| (inserts a \verb|%| in the string),
2202\verb|%s| (inserts a zero-terminated string, with no size restrictions),
2203\verb|%f| (inserts a \verb|lua_Number|),
2204\verb|%d| (inserts an \verb|int|),
2205\verb|%c| (inserts an \verb|int| as a character).
2206\end{itemize}
2207
2208
2209\subsection{Controlling Garbage Collection}\label{GC-API}
2210
2211Lua uses two numbers to control its garbage collection:
2212the \emph{count} and the \emph{threshold} \see{GC}.
2213The first counts the amount of memory in use by Lua;
2214when the count reaches the threshold,
2215Lua runs its garbage collector.
2216After the collection, the count is updated,
2217and the threshold is set to twice the count value.
2218
2219You can access the current values of these two numbers through the
2220following functions:
2221\begin{verbatim}
2222 int lua_getgccount (lua_State *L);
2223 int lua_getgcthreshold (lua_State *L);
2224\end{verbatim}
2225\DefAPI{lua_getgcthreshold} \DefAPI{lua_getgccount}
2226Both return their respective values in Kbytes.
2227You can change the threshold value with
2228\begin{verbatim}
2229 void lua_setgcthreshold (lua_State *L, int newthreshold);
2230\end{verbatim}
2231\DefAPI{lua_setgcthreshold}
2232Again, the \verb|newthreshold| value is given in Kbytes.
2233When you call this function,
2234Lua sets the new threshold and checks it against the byte counter.
2235If the new threshold is smaller than the byte counter,
2236then Lua immediately runs the garbage collector.
2237In particular
2238\verb|lua_setgcthreshold(L,0)| forces a garbage collection.
2239After the collection,
2240a new threshold is set according to the previous rule.
2241
2242\C{TODO do we need a new way to do that??}
2243\C{ If you want to change the adaptive behavior of the garbage collector,}
2244\C{ you can use the garbage-collection tag method for \nil{} }
2245\C{ to set your own threshold}
2246\C{ (the tag method is called after Lua resets the threshold).}
2247
2248
2249\subsection{Userdata}\label{userdata}
2250
2251Userdata represents C values in Lua.
2252Lua supports two types of userdata:
2253\Def{full userdata} and \Def{light userdata}.
2254
2255A full userdata represents a block of memory.
2256It is an object (like a table):
2257You must create it, it can have its own metatable,
2258and you can detect when it is being collected.
2259A full userdata is only equal to itself (under raw equality).
2260
2261A light userdata represents a pointer.
2262It is a value (like a number):
2263You do not create it, it has no metatables,
2264it is not collected (as it was never created).
2265A light userdata is equal to \Q{any}
2266light userdata with the same address.
2267
2268In Lua code, there is no way to test whether a userdata is full or light;
2269both have type \verb|userdata|.
2270In C code, \verb|lua_type| returns \verb|LUA_TUSERDATA| for full userdata,
2271and \verb|LUA_LIGHTUSERDATA| for light userdata.
2272
2273You can create new full userdata with the following function:
2274\begin{verbatim}
2275 void *lua_newuserdata (lua_State *L, size_t size);
2276\end{verbatim}
2277\DefAPI{lua_newuserdata}
2278It allocates a new block of memory with the given size,
2279pushes on the stack a new userdata with the block address,
2280and returns this address.
2281
2282To push a light userdata into the stack you use
2283\verb|lua_pushlightuserdata| \see{pushing}.
2284
2285\verb|lua_touserdata| \see{lua-to} retrieves the value of a userdata.
2286When applied on a full userdata, it returns the address of its block;
2287when applied on a light userdata, it returns its pointer;
2288when applied on a non-userdata value, it returns \verb|NULL|.
2289
2290When Lua collects a full userdata,
2291it calls its \verb|gc| metamethod, if any,
2292and then it frees its corresponding memory.
2293
2294
2295\subsection{Metatables}
2296
2297The following functions allow you to manipulate the metatables
2298of an object:
2299\begin{verbatim}
2300 int lua_getmetatable (lua_State *L, int objindex);
2301 int lua_setmetatable (lua_State *L, int objindex);
2302\end{verbatim}
2303\DefAPI{lua_getmetatable}\DefAPI{lua_setmetatable}
2304Both get at \verb|objindex| a valid index for an object.
2305\verb|lua_getmetatable| pushes on the stack the metatable of that object;
2306\verb|lua_setmetatable| sets the table on the top of the stack as the
2307new metatable for that object (and pops the table).
2308
2309If the object does not have a metatable,
2310\verb|lua_getmetatable| returns 0, and pushes nothing on the stack.
2311\verb|lua_setmetatable| returns 0 when it cannot
2312set the metatable of the given object
2313(that is, when the object is not a userdata nor a table);
2314even then it pops the table from the stack.
2315
2316\subsection{Loading Lua Chunks}
2317
2318You can load a Lua chunk with
2319\begin{verbatim}
2320 typedef const char * (*lua_Chunkreader)
2321 (lua_State *L, void *data, size_t *size);
2322
2323 int lua_load (lua_State *L, lua_Chunkreader reader, void *data,
2324 const char *chunkname);
2325\end{verbatim}
2326\DefAPI{Chunkreader}\DefAPI{lua_load}
2327The return values of \verb|lua_load| are:
2328\begin{itemize}
2329\item 0 \Em{} no errors;
2330\item \IndexAPI{LUA_ERRSYNTAX} \Em{}
2331syntax error during pre-compilation.
2332\item \IndexAPI{LUA_ERRMEM} \Em{}
2333memory allocation error.
2334\end{itemize}
2335If there are no errors,
2336\verb|lua_load| pushes the compiled chunk as a Lua
2337function on top of the stack.
2338Otherwise, it pushes an error message.
2339
2340\verb|lua_load| automatically detects whether the chunk is text or binary,
2341and loads it accordingly (see program \IndexVerb{luac}).
2342
2343\verb|lua_load| uses the \emph{reader} to read the chunk.
2344Everytime it needs another piece of the chunk,
2345it calls the reader,
2346passing along its \verb|data| parameter.
2347The reader must return a pointer to a block of memory
2348with a new part of the chunk,
2349and set \verb|size| to the block size.
2350To signal the end of the chunk, the reader must return \verb|NULL|.
2351The reader function may return pieces of any size greater than zero.
2352
2353In the current implementation,
2354the reader function cannot call any Lua function;
2355to ensure that, it always receives \verb|NULL| as the Lua state.
2356
2357The \emph{chunkname} is used for error messages
2358and debug information \see{debugI}.
2359
2360See the auxiliary library (\verb|lauxlib|)
2361for examples of how to use \verb|lua_load|,
2362and for some ready-to-use functions to load chunks
2363from files and from strings.
2364
2365\subsection{Manipulating Tables}
2366
2367Tables are created by calling
2368the function
2369\begin{verbatim}
2370 void lua_newtable (lua_State *L);
2371\end{verbatim}
2372\DefAPI{lua_newtable}
2373This function creates a new, empty table and pushes it onto the stack.
2374
2375To read a value from a table that resides somewhere in the stack,
2376call
2377\begin{verbatim}
2378 void lua_gettable (lua_State *L, int index);
2379\end{verbatim}
2380\DefAPI{lua_gettable}
2381where \verb|index| points to the table.
2382\verb|lua_gettable| pops a key from the stack
2383and returns (on the stack) the contents of the table at that key.
2384The table is left where it was in the stack;
2385this is convenient for getting multiple values from a table.
2386
2387As in Lua, this function may trigger a metamethod
2388for the \Q{index} event \see{metatable}.
2389To get the real value of any table key,
2390without invoking any metamethod,
2391use the \emph{raw} version:
2392\begin{verbatim}
2393 void lua_rawget (lua_State *L, int index);
2394\end{verbatim}
2395\DefAPI{lua_rawget}
2396
2397To store a value into a table that resides somewhere in the stack,
2398you push the key and the value onto the stack
2399(in this order),
2400and then call
2401\begin{verbatim}
2402 void lua_settable (lua_State *L, int index);
2403\end{verbatim}
2404\DefAPI{lua_settable}
2405where \verb|index| points to the table.
2406\verb|lua_settable| pops from the stack both the key and the value.
2407The table is left where it was in the stack;
2408this is convenient for setting multiple values in a table.
2409
2410As in Lua, this operation may trigger a metamethod
2411for the \Q{settable} or \Q{newindex} events.
2412To set the real value of any table index,
2413without invoking any metamethod,
2414use the \emph{raw} version:
2415\begin{verbatim}
2416 void lua_rawset (lua_State *L, int index);
2417\end{verbatim}
2418\DefAPI{lua_rawset}
2419
2420You can traverse a table with the function
2421\begin{verbatim}
2422 int lua_next (lua_State *L, int index);
2423\end{verbatim}
2424\DefAPI{lua_next}
2425where \verb|index| points to the table to be traversed.
2426The function pops a key from the stack,
2427and pushes a key-value pair from the table
2428(the \Q{next} pair after the given key).
2429If there are no more elements, then \verb|lua_next| returns 0
2430(and pushes nothing).
2431Use a \nil{} key to signal the start of a traversal.
2432
2433A typical traversal looks like this:
2434\begin{verbatim}
2435 /* table is in the stack at index `t' */
2436 lua_pushnil(L); /* first key */
2437 while (lua_next(L, t) != 0) {
2438 /* `key' is at index -2 and `value' at index -1 */
2439 printf("%s - %s\n",
2440 lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
2441 lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */
2442 }
2443\end{verbatim}
2444
2445NOTE:
2446While traversing a table,
2447do not call \verb|lua_tostring| on a key,
2448unless you know the key is actually a string.
2449Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
2450this confuses the next call to \verb|lua_next|.
2451
2452\subsection{Manipulating Global Variables} \label{globals}
2453
2454All global variables are kept in an ordinary Lua table.
2455This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}.
2456
2457To access and change the value of global variables,
2458you can use regular table operations over the global table.
2459For instance, to access the value of a global variable, do
2460\begin{verbatim}
2461 lua_pushstring(L, varname);
2462 lua_gettable(L, LUA_GLOBALSINDEX);
2463\end{verbatim}
2464
2465You can change the global table of a Lua thread using \verb|lua_replace|.
2466
2467
2468\subsection{Using Tables as Arrays}
2469The API has functions that help to use Lua tables as arrays,
2470that is,
2471tables indexed by numbers only:
2472\begin{verbatim}
2473 void lua_rawgeti (lua_State *L, int index, int n);
2474 void lua_rawseti (lua_State *L, int index, int n);
2475\end{verbatim}
2476\DefAPI{lua_rawgeti}
2477\DefAPI{lua_rawseti}
2478
2479\verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table
2480at stack position \verb|index|.
2481\verb|lua_rawseti| sets the value of the \M{n}-th element of the table
2482at stack position \verb|index| to the value at the top of the stack,
2483removing this value from the stack.
2484
2485
2486\subsection{Calling Functions}
2487
2488Functions defined in Lua
2489and C\Nb{}functions registered in Lua
2490can be called from the host program.
2491This is done using the following protocol:
2492First, the function to be called is pushed onto the stack;
2493then, the arguments to the function are pushed
2494in \emph{direct order}, that is, the first argument is pushed first.
2495Finally, the function is called using
2496\begin{verbatim}
2497 void lua_call (lua_State *L, int nargs, int nresults);
2498\end{verbatim}
2499\DefAPI{lua_call}
2500\verb|nargs| is the number of arguments that you pushed onto the stack.
2501All arguments and the function value are popped from the stack,
2502and the function results are pushed.
2503The number of results are adjusted to \verb|nresults|,
2504unless \verb|nresults| is \IndexAPI{LUA_MULTRET}.
2505In that case, \emph{all} results from the function are pushed.
2506Lua takes care that the returned values fit into the stack space.
2507The function results are pushed onto the stack in direct order
2508(the first result is pushed first),
2509so that after the call the last result is on the top.
2510
2511The following example shows how the host program may do the
2512equivalent to this Lua code:
2513\begin{verbatim}
2514 a = f("how", t.x, 14)
2515\end{verbatim}
2516Here it is in\Nb{}C:
2517\begin{verbatim}
2518 lua_pushstring(L, "t");
2519 lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */
2520 lua_pushstring(L, "a"); /* var name */
2521 lua_pushstring(L, "f"); /* function name */
2522 lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
2523 lua_pushstring(L, "how"); /* 1st argument */
2524 lua_pushstring(L, "x"); /* push the string "x" */
2525 lua_gettable(L, -5); /* push result of t.x (2nd arg) */
2526 lua_pushnumber(L, 14); /* 3rd argument */
2527 lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
2528 lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */
2529 lua_pop(L, 1); /* remove `t' from the stack */
2530\end{verbatim}
2531Notice that the code above is \Q{balanced}:
2532at its end, the stack is back to its original configuration.
2533This is considered good programming practice.
2534
2535(We did this example using only the raw functions provided by Lua's API,
2536to show all the details.
2537Usually programmers use several macros and auxiliary functions that
2538provide higher level access to Lua.)
2539
2540
2541\subsection{Protected Calls}\label{pcall}
2542
2543When you call a function with \verb|lua_call|,
2544any error inside the called function is propagated upwards
2545(with a \verb|longjmp|).
2546If you need to handle errors,
2547then you should use \verb|lua_pcall|:
2548\begin{verbatim}
2549 int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
2550\end{verbatim}
2551Both \verb|nargs| and \verb|nresults| have the same meaning as
2552in \verb|lua_call|.
2553If there are no errors during the call,
2554\verb|lua_pcall| behaves exactly like \verb|lua_call|.
2555Like \verb|lua_call|,
2556\verb|lua_pcall| always removes the function
2557and its arguments from the stack.
2558However, if there is any error,
2559\verb|lua_pcall| catches it,
2560pushes a single value at the stack (the error message),
2561and returns an error code.
2562
2563If \verb|errfunc| is 0,
2564then the error message returned is exactly the original error message.
2565Otherwise, \verb|errfunc| gives the stack index for an
2566\emph{error handler function}.
2567(In the current implementation, that index cannot be a pseudo-index.)
2568In case of runtime errors,
2569that function will be called with the error message,
2570and its return value will be the message returned by \verb|lua_pcall|.
2571
2572Typically, the error handler function is used to add more debug
2573information to the error message, such as a stack traceback.
2574Such information cannot be gathered after the return of \verb|lua_pcall|,
2575since by then the stack has unwound.
2576
2577The \verb|lua_pcall| function returns 0 in case of success,
2578or one of the following error codes
2579(defined in \verb|lua.h|):
2580\begin{itemize}
2581\item \IndexAPI{LUA_ERRRUN} \Em{} a runtime error.
2582\item \IndexAPI{LUA_ERRMEM} \Em{} memory allocation error.
2583For such errors, Lua does not call the error handler function.
2584\item \IndexAPI{LUA_ERRERR} \Em{}
2585error while running the error handler function.
2586\end{itemize}
2587
2588
2589\medskip
2590
2591>>>>
2592\C{ TODO: mover essas 2 para algum lugar melhor.}
2593Some special Lua functions have their own C\Nb{}interfaces.
2594The host program can generate a Lua error calling the function
2595\begin{verbatim}
2596 void lua_error (lua_State *L);
2597\end{verbatim}
2598\DefAPI{lua_error}
2599The error message (which actually can be any type of object)
2600is popped from the stack.
2601This function never returns.
2602If \verb|lua_error| is called from a C\Nb{}function that
2603has been called from Lua,
2604then the corresponding Lua execution terminates,
2605as if an error had occurred inside Lua code.
2606Otherwise, the whole host program terminates with a call to
2607\verb|exit(EXIT_FAILURE)|.
2608\C{ TODO: at_panic}
2609
2610The function
2611\begin{verbatim}
2612 void lua_concat (lua_State *L, int n);
2613\end{verbatim}
2614\DefAPI{lua_concat}
2615concatenates the \verb|n| values at the top of the stack,
2616pops them, and leaves the result at the top.
2617If \verb|n| is 1, the result is that single string
2618(that is, the function does nothing);
2619if \verb|n| is 0, the result is the empty string.
2620Concatenation is done following the usual semantics of Lua
2621\see{concat}.
2622
2623
2624\subsection{Defining C Functions} \label{LuacallC}
2625
2626Lua can be extended with functions written in\Nb{}C.
2627These functions must be of type \verb|lua_CFunction|,
2628which is defined as
2629\begin{verbatim}
2630 typedef int (*lua_CFunction) (lua_State *L);
2631\end{verbatim}
2632\DefAPI{lua_CFunction}
2633A C\Nb{}function receives a Lua environment and returns an integer,
2634the number of values it has returned to Lua.
2635
2636In order to communicate properly with Lua,
2637a C\Nb{}function must follow the following protocol,
2638which defines the way parameters and results are passed:
2639A C\Nb{}function receives its arguments from Lua in its stack,
2640in direct order (the first argument is pushed first).
2641So, when the function starts,
2642its first argument (if any) is at index 1.
2643To return values to Lua, a C\Nb{}function just pushes them onto the stack,
2644in direct order (the first result is pushed first),
2645and returns the number of results.
2646Any other value in the stack below the results will be properly
2647discharged by Lua.
2648Like a Lua function, a C\Nb{}function called by Lua can also return
2649many results.
2650
2651As an example, the following function receives a variable number
2652of numerical arguments and returns their average and sum:
2653\begin{verbatim}
2654 static int foo (lua_State *L) {
2655 int n = lua_gettop(L); /* number of arguments */
2656 lua_Number sum = 0;
2657 int i;
2658 for (i = 1; i <= n; i++) {
2659 if (!lua_isnumber(L, i)) {
2660 lua_pushstring(L, "incorrect argument to function `average'");
2661 lua_error(L);
2662 }
2663 sum += lua_tonumber(L, i);
2664 }
2665 lua_pushnumber(L, sum/n); /* first result */
2666 lua_pushnumber(L, sum); /* second result */
2667 return 2; /* number of results */
2668 }
2669\end{verbatim}
2670
2671To register a C\Nb{}function to Lua,
2672there is the following convenience macro:
2673\begin{verbatim}
2674 #define lua_register(L,n,f) \
2675 (lua_pushstring(L, n), \
2676 lua_pushcfunction(L, f), \
2677 lua_settable(L, LUA_GLOBALSINDEX))
2678 /* const char *n; */
2679 /* lua_CFunction f; */
2680\end{verbatim}
2681\DefAPI{lua_register}
2682which receives the name the function will have in Lua,
2683and a pointer to the function.
2684Thus,
2685the C\Nb{}function `\verb|foo|' above may be registered in Lua as `\verb|average|'
2686by calling
2687\begin{verbatim}
2688 lua_register(L, "average", foo);
2689\end{verbatim}
2690
2691\subsection{Defining C Closures} \label{c-closure}
2692
2693When a C\Nb{}function is created,
2694it is possible to associate some values with it,
2695thus creating a \IndexEmph{C\Nb{}closure};
2696these values are then accessible to the function whenever it is called.
2697To associate values with a C\Nb{}function,
2698first these values should be pushed onto the stack
2699(when there are multiple values, the first value is pushed first).
2700Then the function
2701\begin{verbatim}
2702 void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
2703\end{verbatim}
2704\DefAPI{lua_pushcclosure}
2705is used to push the C\Nb{}function onto the stack,
2706with the argument \verb|n| telling how many values should be
2707associated with the function
2708(\verb|lua_pushcclosure| also pops these values from the stack);
2709in fact, the macro \verb|lua_pushcfunction| is defined as
2710\verb|lua_pushcclosure| with \verb|n| set to 0.
2711
2712Then, whenever the C\Nb{}function is called,
2713those values are located at specific pseudo-indices.
2714Those pseudo-indices are produced by a macro \IndexAPI{lua_upvalueindex}.
2715The first value associated with a function is at position
2716\verb|lua_upvalueindex(1)|, and so on.
2717
2718For examples of C\Nb{}functions and closures, see files
2719\verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c|
2720in the official Lua distribution.
2721
2722
2723\subsubsection*{Registry} \label{registry}
2724
2725Lua provides a pre-defined table that can be used by any C\Nb{}code to
2726store whatever Lua value it needs to store,
2727especially if the C\Nb{}code needs to keep that Lua value
2728outside the life span of a C\Nb{}function.
2729This table is always located at pseudo-index
2730\IndexAPI{LUA_REGISTRYINDEX}.
2731Any C\Nb{}library can store data into this table,
2732as long as it chooses keys different from other libraries.
2733Typically, you should use as key a string containing your library name,
2734or a light userdata with the address of a C object in your code.
2735
2736The integer keys in the registry are used by the reference mechanism,
2737implemented by the auxiliary library,
2738and therefore should not be used by other purposes.
2739
2740
2741\C{-------------------------------------------------------------------------}
2742\section{The Debug Interface} \label{debugI}
2743
2744Lua has no built-in debugging facilities.
2745Instead, it offers a special interface
2746by means of functions and \emph{hooks}.
2747This interface allows the construction of different
2748kinds of debuggers, profilers, and other tools
2749that need \Q{inside information} from the interpreter.
2750
2751\subsection{Stack and Function Information}
2752
2753The main function to get information about the interpreter stack is
2754\begin{verbatim}
2755 int lua_getstack (lua_State *L, int level, lua_Debug *ar);
2756\end{verbatim}
2757\DefAPI{lua_getstack}
2758This function fills parts of a \verb|lua_Debug| structure with
2759an identification of the \emph{activation record}
2760of the function executing at a given level.
2761Level\Nb{}0 is the current running function,
2762whereas level \Math{n+1} is the function that has called level \Math{n}.
2763Usually, \verb|lua_getstack| returns 1;
2764when called with a level greater than the stack depth,
2765it returns 0.
2766
2767The structure \verb|lua_Debug| is used to carry different pieces of
2768information about an active function:
2769\begin{verbatim}
2770 typedef struct lua_Debug {
2771 int event;
2772 const char *name; /* (n) */
2773 const char *namewhat; /* (n) `global', `local', `field', `method' */
2774 const char *what; /* (S) `Lua' function, `C' function, Lua `main' */
2775 const char *source; /* (S) */
2776 int currentline; /* (l) */
2777 int nups; /* (u) number of upvalues */
2778 int linedefined; /* (S) */
2779 char short_src[LUA_IDSIZE]; /* (S) */
2780
2781 /* private part */
2782 ...
2783 } lua_Debug;
2784\end{verbatim}
2785\DefAPI{lua_Debug}
2786\verb|lua_getstack| fills only the private part
2787of this structure, for future use.
2788To fill the other fields of \verb|lua_Debug| with useful information,
2789call
2790\begin{verbatim}
2791 int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
2792\end{verbatim}
2793\DefAPI{lua_getinfo}
2794This function returns 0 on error
2795(for instance, an invalid option in \verb|what|).
2796Each character in the string \verb|what|
2797selects some fields of \verb|ar| to be filled,
2798as indicated by the letter in parentheses in the definition of \verb|lua_Debug|
2799above:
2800`\verb|S|' fills in the fields \verb|source|, \verb|linedefined|,
2801and \verb|what|;
2802`\verb|l|' fills in the field \verb|currentline|, etc.
2803Moreover, `\verb|f|' pushes onto the stack the function that is
2804running at the given level.
2805
2806To get information about a function that is not active (that is,
2807it is not in the stack),
2808you push the function onto the stack,
2809and start the \verb|what| string with the character `\verb|>|'.
2810For instance, to know in which line a function \verb|f| was defined,
2811you can write
2812\begin{verbatim}
2813 lua_Debug ar;
2814 lua_pushstring(L, "f");
2815 lua_gettable(L, LUA_GLOBALSINDEX); /* get global `f' */
2816 lua_getinfo(L, ">S", &ar);
2817 printf("%d\n", ar.linedefined);
2818\end{verbatim}
2819The fields of \verb|lua_Debug| have the following meaning:
2820\begin{description}\leftskip=20pt
2821
2822\item[source]
2823If the function was defined in a string,
2824then \verb|source| is that string;
2825if the function was defined in a file,
2826then \verb|source| starts with a \At{} followed by the file name.
2827
2828\item[short_src]
2829A \Q{printable} version of \verb|source|, to be used in error messages.
2830
2831\item[linedefined]
2832the line number where the definition of the function starts.
2833
2834\item[what] the string \verb|"Lua"| if this is a Lua function,
2835\verb|"C"| if this is a C\Nb{}function,
2836or \verb|"main"| if this is the main part of a chunk.
2837
2838\item[currentline]
2839the current line where the given function is executing.
2840When no line information is available,
2841\verb|currentline| is set to \Math{-1}.
2842
2843\item[name]
2844a reasonable name for the given function.
2845Because functions in Lua are first class values,
2846they do not have a fixed name:
2847Some functions may be the value of many global variables,
2848while others may be stored only in a table field.
2849The \verb|lua_getinfo| function checks how the function was
2850called or whether it is the value of a global variable to
2851find a suitable name.
2852If it cannot find a name,
2853then \verb|name| is set to \verb|NULL|.
2854
2855\item[namewhat]
2856Explains the previous field.
2857It can be \verb|"global"|, \verb|"local"|, \verb|"method"|,
2858\verb|"field"|, or \verb|""| (the empty string),
2859according to how the function was called.
2860(Lua uses the empty string when no other option seems to apply.)
2861
2862\item[nups]
2863Number of upvalues of the function.
2864
2865\end{description}
2866
2867
2868\subsection{Manipulating Local Variables}
2869
2870For the manipulation of local variables,
2871\verb|luadebug.h| uses indices:
2872The first parameter or local variable has index\Nb{}1, and so on,
2873until the last active local variable.
2874
2875The following functions allow the manipulation of the
2876local variables of a given activation record:
2877\begin{verbatim}
2878 const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
2879 const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
2880\end{verbatim}
2881\DefAPI{lua_getlocal}\DefAPI{lua_setlocal}
2882The parameter \verb|ar| must be a valid activation record that was
2883filled by a previous call to \verb|lua_getstack| or
2884was given as argument to a hook \see{sub-hooks}.
2885\verb|lua_getlocal| gets the index \verb|n| of a local variable,
2886pushes the variable's value onto the stack,
2887and returns its name.
2888\verb|lua_setlocal| assigns the value at the top of the stack
2889to the variable and returns its name.
2890Both functions return \verb|NULL|
2891when the index is greater than
2892the number of active local variables.
2893
2894As an example, the following function lists the names of all
2895local variables for a function at a given level of the stack:
2896\begin{verbatim}
2897 int listvars (lua_State *L, int level) {
2898 lua_Debug ar;
2899 int i = 1;
2900 const char *name;
2901 if (lua_getstack(L, level, &ar) == 0)
2902 return 0; /* failure: no such level in the stack */
2903 while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
2904 printf("%s\n", name);
2905 lua_pop(L, 1); /* remove variable value */
2906 }
2907 return 1;
2908 }
2909\end{verbatim}
2910
2911
2912\subsection{Hooks}\label{sub-hooks}
2913
2914The Lua interpreter offers a mechanism of hooks, which are
2915user-defined C functions that are called during the program execution.
2916A hook may be called in four different events:
2917a \emph{call} event, when Lua calls a function;
2918a \emph{return} event, when Lua returns from a function;
2919a \emph{line} event, when Lua starts executing a new line of code;
2920and a \emph{count} event, which happens every \Q{count} instructions.
2921Lua identifies them with the following constants:
2922\verb|LUA_HOOKCALL|\DefAPI{LUA_HOOKCALL},
2923\verb|LUA_HOOKRET|\DefAPI{LUA_HOOKRET},
2924\verb|LUA_HOOKLINE|\DefAPI{LUA_HOOKLINE},
2925and \verb|LUA_HOOKCOUNT|\DefAPI{LUA_HOOKCOUNT}.
2926
2927A hook has type \verb|lua_Hook|, defined as follows:
2928\begin{verbatim}
2929 typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
2930\end{verbatim}
2931\DefAPI{lua_Hook}
2932You can set the hook with the following function:
2933\begin{verbatim}
2934 int lua_sethook (lua_State *L, lua_Hook func, unsigned long mask);
2935\end{verbatim}
2936\DefAPI{lua_sethook}
2937\verb|func| is the hook,
2938and \verb|mask| specifies at which events it will be called.
2939It is formed by a disjunction of the constants
2940\verb|LUA_MASKCALL|,
2941\verb|LUA_MASKRET|,
2942\verb|LUA_MASKLINE|,
2943plus the macro \verb|LUA_MASKCOUNT(count)|.
2944For each event, the hook is called as explained below:
2945\begin{description}
2946\item{The call hook} is called when the interpreter calls a function.
2947The hook is called just after Lua \Q{enters} the new function.
2948\item{The return hook} is called when the interpreter returns from a function.
2949The hook is called just before Lua \Q{leaves} the function.
2950\item{The line hook} is called when the interpreter is about to
2951start the execution of a new line of code,
2952or when it jumps back (even for the same line).
2953(For obvious reasons, this event does not happen while Lua is executing
2954a C function.)
2955\item{The count hook} is called after the interpreter executes every
2956\verb|count| instructions.
2957(For obvious reasons, this event does not happen while Lua is executing
2958a C function.)
2959\end{description}
2960
2961A hook is disabled with the mask zero.
2962
2963You can get the current hook and the current mask with the next functions:
2964\begin{verbatim}
2965 lua_Hook lua_gethook (lua_State *L);
2966 unsigned long lua_gethookmask (lua_State *L);
2967\end{verbatim}
2968\DefAPI{lua_gethook}\DefAPI{lua_gethookmask}
2969You can get the count inside a mask with the macro \verb|lua_getmaskcount|.
2970
2971Whenever a hook is called, its \verb|ar| argument has its field
2972\verb|event| set to the specific event that triggered the hook.
2973Moreover, for line events, the field \verb|currentline| is also set.
2974For the value of any other field, the hook must call \verb|lua_getinfo|.
2975
2976While Lua is running a hook, it disables other calls to hooks.
2977Therefore, if a hook calls Lua to execute a function or a chunk,
2978that execution occurs without any calls to hooks.
2979
2980
2981\C{-------------------------------------------------------------------------}
2982\section{Standard Libraries}\label{libraries}
2983
2984The standard libraries provide useful functions
2985that are implemented directly through the standard C\Nb{}API.
2986Some of these functions provide essential services to the language
2987(e.g. \verb|type| and \verb|getmetatable|);
2988others provide access to \Q{outside} services (e.g. I/O);
2989and others could be implemented in Lua itself,
2990but are quite useful or have critical performance to
2991deserve an implementation in C (e.g. \verb|sort|).
2992
2993All libraries are implemented through the official C API,
2994and are provided as separate C\Nb{}modules.
2995Currently, Lua has the following standard libraries:
2996\begin{itemize}
2997\item basic library;
2998\item string manipulation;
2999\item table manipulation;
3000\item mathematical functions (sin, log, etc.);
3001\item input and output;
3002\item operating system facilities;
3003\item debug facilities.
3004\end{itemize}
3005Except for the basic library,
3006each library provides all its functions as fields of a global table
3007or as methods of its objects.
3008
3009To have access to these libraries,
3010the C\Nb{}host program must call the functions
3011\verb|lua_baselibopen| (for the basic library),
3012\verb|lua_strlibopen| (for the string library),
3013\verb|lua_tablibopen| (for the table library),
3014\verb|lua_mathlibopen| (for the mathematical library),
3015\verb|lua_iolibopen| (for the I/O and the Operating System libraries),
3016and \verb|lua_dblibopen| (for the debug library),
3017which are declared in \verb|lualib.h|.
3018\DefAPI{lua_baselibopen}
3019\DefAPI{lua_strlibopen}
3020\DefAPI{lua_tablibopen}
3021\DefAPI{lua_mathlibopen}
3022\DefAPI{lua_iolibopen}
3023\DefAPI{lua_dblibopen}
3024
3025
3026\subsection{Basic Functions} \label{predefined}
3027
3028The basic library provides some core functions to Lua.
3029If you do not include this library in your application,
3030you should check carefully whether you need to provide some alternative
3031implementation for some facilities.
3032
3033The basic library also defines a global variable \IndexLIB{_VERSION}
3034with a string containing the current interpreter version.
3035The current content of this string is {\tt "Lua \Version"}.
3036
3037\subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert}
3038Issues an \emph{\Q{assertion failed!}} error
3039when its argument \verb|v| is \nil{} or \False{};
3040otherwise, returns this argument.
3041This function is equivalent to the following Lua function:
3042\begin{verbatim}
3043 function assert (v, m)
3044 if not v then
3045 error(m or "assertion failed!")
3046 end
3047 return v
3048 end
3049\end{verbatim}
3050
3051\subsubsection*{\ff \T{collectgarbage ([limit])}}\DefLIB{collectgarbage}
3052
3053Sets the garbage-collection threshold to the given limit
3054(in Kbytes), and checks it against the byte counter.
3055If the new threshold is smaller than the byte counter,
3056then Lua immediately runs the garbage collector \see{GC}.
3057If \verb|limit| is absent, it defaults to zero
3058(thus forcing a garbage-collection cycle).
3059
3060\subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile}
3061Receives a file name,
3062opens the named file, and executes its contents as a Lua chunk.
3063When called without arguments,
3064\verb|dofile| executes the contents of the standard input (\verb|stdin|).
3065Returns any value returned by the chunk.
3066
3067\subsubsection*{\ff \T{error (message [, level])}}
3068\DefLIB{error}\label{pdf-error}
3069Terminates the last protected function called,
3070and returns \verb|message| as the error message.
3071Function \verb|error| never returns.
3072
3073The \verb|level| argument specifies where the error
3074message points the error.
3075With level 1 (the default), the error position is where the
3076\verb|error| function was called.
3077Level 2 points the error to where the function
3078that called \verb|error| was called; and so on.
3079
3080\subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals}
3081Returns the current table of globals in use by the function.
3082\verb|function| can be a Lua function or a number,
3083which specifies the function at that stack level:
3084Level 1 is the function calling \verb|getglobals|.
3085If the given function is not a Lua function,
3086returns the \Q{global} table of globals.
3087The default for \verb|function| is 1.
3088
3089\subsubsection*{\ff \T{getmetatable (object)}}
3090\DefLIB{getmetatable}\label{pdf-getmetatable}
3091
3092Returns the metatable of the given object.
3093If the object does not have a metatable, returns \nil{}.
3094
3095\subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo}
3096Returns the number of Kbytes of dynamic memory Lua is using,
3097and (as a second result) the
3098current garbage collector threshold (also in Kbytes).
3099
3100\subsubsection*{\ff \T{ipairs (t)}}\DefLIB{ipairs}
3101
3102Returns a generator function and the table \verb|t|,
3103so that the construction
3104\begin{verbatim}
3105 for i,v in ipairs(t) do ... end
3106\end{verbatim}
3107will iterate over the pairs \verb|1, t[1]|, \verb|2, t[2]|, \ldots,
3108up to the first nil value of the table.
3109
3110\subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile}
3111Loads a file as a Lua chunk.
3112If there are no errors,
3113returns the compiled chunk as a function;
3114otherwise, returns \nil{} plus an error message.
3115
3116\subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring}
3117Loads a string as a Lua chunk.
3118If there are no errors,
3119returns the compiled chunk as a function;
3120otherwise, returns \nil{} plus an error message.
3121
3122The optional parameter \verb|chunkname|
3123is the \Q{name of the chunk},
3124which is used in error messages and debug information.
3125
3126To load and run a given string, use the idiom
3127\begin{verbatim}
3128 assert(loadstring(s))()
3129\end{verbatim}
3130
3131\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next}
3132Allows a program to traverse all fields of a table.
3133Its first argument is a table and its second argument
3134is an index in this table.
3135\verb|next| returns the next index of the table and the
3136value associated with the index.
3137When called with \nil{} as its second argument,
3138\verb|next| returns the first index
3139of the table and its associated value.
3140When called with the last index,
3141or with \nil{} in an empty table,
3142\verb|next| returns \nil{}.
3143If the second argument is absent, then it is interpreted as \nil{}.
3144
3145Lua has no declaration of fields;
3146semantically, there is no difference between a
3147field not present in a table or a field with value \nil{}.
3148Therefore, \verb|next| only considers fields with non-\nil{} values.
3149The order in which the indices are enumerated is not specified,
3150\emph{even for numeric indices}.
3151(To traverse a table in numeric order,
3152use a numerical \rwd{for} or the function \verb|ipairs|.)
3153
3154The behavior of \verb|next| is \emph{undefined} if you modify
3155the table during the traversal.
3156
3157\subsubsection*{\ff \T{pairs (t)}}\DefLIB{pairs}
3158
3159Returns the function \verb|next| and the table \verb|t| (plus a \nil{}),
3160so that the construction
3161\begin{verbatim}
3162 for k,v in pairs(t) do ... end
3163\end{verbatim}
3164will iterate over all pairs of key\En{}value of table \verb|t|.
3165
3166\subsubsection*{\ff \T{pcall (func, arg1, arg2, ...)}}\DefLIB{pcall}
3167\label{pdf-pcall}
3168Calls function \verb|func| with
3169the given arguments in protected mode.
3170That means that any error inside \verb|func| is not propagated;
3171instead, \verb|pcall| catches the error
3172and returns a status code.
3173Its first result is the status code (a boolean),
3174which is true if the call succeeds without errors.
3175In such case, \verb|pcall| also returns all results from the call,
3176after this first result.
3177In case of any error, \verb|pcall| returns false plus the error message.
3178
3179\subsubsection*{\ff \T{print (e1, e2, ...)}}\DefLIB{print}
3180Receives any number of arguments,
3181and prints their values in \verb|stdout|,
3182using the strings returned by \verb|tostring|.
3183This function is not intended for formatted output,
3184but only as a quick way to show a value,
3185typically for debugging.
3186For formatted output, see \verb|format| \see{format}.
3187
3188\subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget}
3189Gets the real value of \verb|table[index]|,
3190without invoking any metamethod.
3191\verb|table| must be a table;
3192\verb|index| is any value different from \nil{}.
3193
3194\subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset}
3195Sets the real value of \verb|table[index]| to \verb|value|,
3196without invoking any metamethod.
3197\verb|table| must be a table;
3198\verb|index| is any value different from \nil{};
3199and \verb|value| is any Lua value.
3200
3201\subsubsection*{\ff \T{require (packagename)}}\DefLIB{require}
3202
3203Loads the given package.
3204The function starts by looking into the table \IndexVerb{_LOADED}
3205to determine whether \verb|packagename| is already loaded.
3206If it is, then \verb|require| is done.
3207Otherwise, it searches a path looking for a file to load.
3208
3209If the global variable \IndexVerb{LUA_PATH} is a string,
3210this string is the path.
3211Otherwise, \verb|require| tries the environment variable \verb|LUA_PATH|.
3212As a last resort, it uses a predefined path.
3213
3214The path is a sequence of \emph{templates} separated by semicolons.
3215For each template, \verb|require| will change an eventual interrogation
3216mark in the template to \verb|packagename|,
3217and then will try to load the resulting file name.
3218So, for instance, if the path is
3219\begin{verbatim}
3220 "./?.lua;./?.lc;/usr/local/?/init.lua;/lasttry"
3221\end{verbatim}
3222a \verb|require "mod"| will try to load the files
3223\verb|./mod.lua|,
3224\verb|./mod.lc|,
3225\verb|/usr/local/mod/init.lua|,
3226and \verb|/lasttry|, in that order.
3227
3228The function stops the search as soon as it can load a file,
3229and then it runs the file.
3230If there is any error loading or running the file,
3231or if it cannot find any file in the path,
3232then \verb|require| signals an error.
3233Otherwise, it marks in table \verb|_LOADED|
3234that the package is loaded, and returns.
3235
3236While running a packaged file,
3237\verb|require| defines the global variable \IndexVerb{_REQUIREDNAME}
3238with the package name.
3239
3240\subsubsection*{\ff \T{setglobals (function, table)}}\DefLIB{setglobals}
3241Sets the current table of globals to be used by the given function.
3242\verb|function| can be a Lua function or a number,
3243which specifies the function at that stack level:
3244Level 1 is the function calling \verb|setglobals|.
3245
3246\subsubsection*{\ff \T{setmetatable (table, metatable)}}\DefLIB{setmetatable}
3247
3248Sets the metatable for the given table.
3249(You cannot change the metatable of a userdata from Lua.)
3250If \verb|metatable| is \nil{}, removes the metatable of the given table.
3251
3252\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
3253Tries to convert its argument to a number.
3254If the argument is already a number or a string convertible
3255to a number, then \verb|tonumber| returns that number;
3256otherwise, it returns \nil{}.
3257
3258An optional argument specifies the base to interpret the numeral.
3259The base may be any integer between 2 and 36, inclusive.
3260In bases above\Nb{}10, the letter `A' (in either upper or lower case)
3261represents\Nb{}10, `B' represents\Nb{}11, and so forth, with `Z' representing 35.
3262In base 10 (the default), the number may have a decimal part,
3263as well as an optional exponent part \see{coercion}.
3264In other bases, only unsigned integers are accepted.
3265
3266\subsubsection*{\ff \T{tostring (e)}}\DefLIB{tostring}
3267Receives an argument of any type and
3268converts it to a string in a reasonable format.
3269For complete control of how numbers are converted,
3270use \verb|format| \see{format}.
3271
3272\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
3273Returns the type of its only argument, coded as a string.
3274The possible results of this function are
3275\verb|"nil"| (a string, not the value \nil{}),
3276\verb|"number"|,
3277\verb|"string"|,
3278\verb|"table"|,
3279\verb|"function"|,
3280and \verb|"userdata"|.
3281
3282\subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack}
3283Returns all elements from the given list.
3284This function is equivalent to
3285\begin{verbatim}
3286 return list[1], list[2], ..., list[n]
3287\end{verbatim}
3288except that the above code can be valid only for a fixed \M{n}.
3289The number \M{n} of returned values
3290is either the value of \verb|list.n|, if it is a number,
3291or one less the index of the first absent (\nil{}) value.
3292
3293\subsection{String Manipulation}
3294This library provides generic functions for string manipulation,
3295such as finding and extracting substrings and pattern matching.
3296When indexing a string in Lua, the first character is at position\Nb{}1
3297(not at\Nb{}0, as in C).
3298Indices are allowed to be negative and are interpreted as indexing backwards,
3299from the end of the string.
3300Thus, the last character is at position \Math{-1}, and so on.
3301
3302The string library provides all its functions inside the table
3303\IndexLIB{string}.
3304
3305\subsubsection*{\ff \T{string.byte (s [, i])}}\DefLIB{string.byte}
3306Returns the internal numerical code of the \M{i}-th character of \verb|s|.
3307If \verb|i| is absent, then it is assumed to be\Nb{}1.
3308\verb|i| may be negative.
3309
3310\NOTE
3311Numerical codes are not necessarily portable across platforms.
3312
3313\subsubsection*{\ff \T{string.char (i1, i2, \ldots)}}\DefLIB{string.char}
3314Receives 0 or more integers.
3315Returns a string with length equal to the number of arguments,
3316in which each character has the internal numerical code equal
3317to its correspondent argument.
3318
3319\NOTE
3320Numerical codes are not necessarily portable across platforms.
3321
3322\subsubsection*{\ff \T{string.find (s, pattern [, init [, plain]])}}
3323\DefLIB{string.find}
3324Looks for the first \emph{match} of
3325\verb|pattern| in the string \verb|s|.
3326If it finds one, then \verb|find| returns the indices of \verb|s|
3327where this occurrence starts and ends;
3328otherwise, it returns \nil{}.
3329If the pattern specifies captures (see \verb|string.gsub| below),
3330the captured strings are returned as extra results.
3331A third, optional numerical argument \verb|init| specifies
3332where to start the search;
3333its default value is\Nb{}1, and may be negative.
3334A value of \True{} as a fourth, optional argument \verb|plain|
3335turns off the pattern matching facilities,
3336so the function does a plain \Q{find substring} operation,
3337with no characters in \verb|pattern| being considered \Q{magic}.
3338Note that if \verb|plain| is given, then \verb|init| must be given too.
3339
3340\subsubsection*{\ff \T{string.len (s)}}\DefLIB{string.len}
3341Receives a string and returns its length.
3342The empty string \verb|""| has length 0.
3343Embedded zeros are counted,
3344so \verb|"a\000b\000c"| has length 5.
3345
3346\subsubsection*{\ff \T{string.lower (s)}}\DefLIB{string.lower}
3347Receives a string and returns a copy of that string with all
3348uppercase letters changed to lowercase.
3349All other characters are left unchanged.
3350The definition of what is an uppercase letter depends on the current locale.
3351
3352\subsubsection*{\ff \T{string.rep (s, n)}}\DefLIB{string.rep}
3353Returns a string that is the concatenation of \verb|n| copies of
3354the string \verb|s|.
3355
3356\subsubsection*{\ff \T{string.sub (s, i [, j])}}\DefLIB{string.sub}
3357Returns another string, which is the substring of \verb|s| that
3358starts at \verb|i| and continues until \verb|j|;
3359\verb|i| and \verb|j| may be negative.
3360If \verb|j| is absent, then it is assumed to be equal to \Math{-1}
3361(which is the same as the string length).
3362In particular,
3363the call \verb|string.sub(s,1,j)| returns a prefix of \verb|s|
3364with length \verb|j|,
3365and the call \verb|string.sub(s, -i)| returns a suffix of \verb|s|
3366with length \verb|i|.
3367
3368\subsubsection*{\ff \T{string.upper (s)}}\DefLIB{string.upper}
3369Receives a string and returns a copy of that string with all
3370lowercase letters changed to uppercase.
3371All other characters are left unchanged.
3372The definition of what is a lowercase letter depends on the current locale.
3373
3374\subsubsection*{\ff \T{string.format (formatstring, e1, e2, \ldots)}}
3375\DefLIB{string.format}\label{format}
3376Returns a formatted version of its variable number of arguments
3377following the description given in its first argument (which must be a string).
3378The format string follows the same rules as the \verb|printf| family of
3379standard C\Nb{}functions.
3380The only differences are that the options/modifiers
3381\verb|*|, \verb|l|, \verb|L|, \verb|n|, \verb|p|,
3382and \verb|h| are not supported,
3383and there is an extra option, \verb|q|.
3384The \verb|q| option formats a string in a form suitable to be safely read
3385back by the Lua interpreter:
3386The string is written between double quotes,
3387and all double quotes, returns, and backslashes in the string
3388are correctly escaped when written.
3389For instance, the call
3390\begin{verbatim}
3391 string.format('%q', 'a string with "quotes" and \n new line')
3392\end{verbatim}
3393will produce the string:
3394\begin{verbatim}
3395"a string with \"quotes\" and \
3396 new line"
3397\end{verbatim}
3398
3399The options \verb|c|, \verb|d|, \verb|E|, \verb|e|, \verb|f|,
3400\verb|g|, \verb|G|, \verb|i|, \verb|o|, \verb|u|, \verb|X|, and \verb|x| all
3401expect a number as argument,
3402whereas \verb|q| and \verb|s| expect a string.
3403The \verb|*| modifier can be simulated by building
3404the appropriate format string.
3405For example, \verb|"%*g"| can be simulated with
3406\verb|"%"..width.."g"|.
3407
3408\NOTE
3409String values to be formatted with
3410\verb|%s| cannot contain embedded zeros.
3411
3412\subsubsection*{\ff \T{string.gfind (s, pat)}}
3413
3414Returns a generator function that,
3415each time it is called,
3416returns the next captures from pattern \verb|pat| over string \verb|s|.
3417
3418If \verb|pat| specifies no captures,
3419then the whole match is produced in each call.
3420
3421As an example, the following loop
3422\begin{verbatim}
3423 s = "hello world from Lua"
3424 for w in string.gfind(s, "%a+") do
3425 print(w)
3426 end
3427\end{verbatim}
3428will iterate over all the words from string \verb|s|,
3429printing one per line.
3430The next example collects all pairs \verb|key=value| from the
3431given string into a table:
3432\begin{verbatim}
3433 t = {}
3434 s = "from=world, to=Lua"
3435 for k, v in string.gfind(s, "(%w+)=(%w+)") do
3436 t[k] = v
3437 end
3438\end{verbatim}
3439
3440\subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}}
3441\DefLIB{string.gsub}
3442Returns a copy of \verb|s|
3443in which all occurrences of the pattern \verb|pat| have been
3444replaced by a replacement string specified by \verb|repl|.
3445\verb|gsub| also returns, as a second value,
3446the total number of substitutions made.
3447
3448If \verb|repl| is a string, then its value is used for replacement.
3449Any sequence in \verb|repl| of the form \verb|%|\M{n},
3450with \M{n} between 1 and 9,
3451stands for the value of the \M{n}-th captured substring.
3452
3453If \verb|repl| is a function, then this function is called every time a
3454match occurs, with all captured substrings passed as arguments,
3455in order (see below);
3456if the pattern specifies no captures,
3457then the whole match is passed as a sole argument.
3458If the value returned by this function is a string,
3459then it is used as the replacement string;
3460otherwise, the replacement string is the empty string.
3461
3462The last, optional parameter \verb|n| limits
3463the maximum number of substitutions to occur.
3464For instance, when \verb|n| is 1 only the first occurrence of
3465\verb|pat| is replaced.
3466
3467Here are some examples:
3468\begin{verbatim}
3469 x = string.gsub("hello world", "(%w+)", "%1 %1")
3470 --> x="hello hello world world"
3471
3472 x = string.gsub("hello world", "(%w+)", "%1 %1", 1)
3473 --> x="hello hello world"
3474
3475 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
3476 --> x="world hello Lua from"
3477
3478 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
3479 --> x="home = /home/roberto, user = roberto" (for instance)
3480
3481 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
3482 return loadstring(s)()
3483 end)
3484 --> x="4+5 = 9"
3485
3486 local t = {name="Lua", version="5.0"}
3487 x = string.gsub("$name - $version", "%$(%w+)", function (v)
3488 return t[v]
3489 end)
3490 --> x="Lua - 5.0"
3491\end{verbatim}
3492
3493
3494\subsubsection*{Patterns} \label{pm}
3495
3496\paragraph{Character Class:}
3497a \Def{character class} is used to represent a set of characters.
3498The following combinations are allowed in describing a character class:
3499\begin{description}\leftskip=20pt
3500\item[\emph{x}] (where \emph{x} is not one of the magic characters
3501\verb|^$()%.[]*+-?|)
3502\Em{} represents the character \emph{x} itself.
3503\item[\T{.}] \Em{} (a dot) represents all characters.
3504\item[\T{%a}] \Em{} represents all letters.
3505\item[\T{%c}] \Em{} represents all control characters.
3506\item[\T{%d}] \Em{} represents all digits.
3507\item[\T{%l}] \Em{} represents all lowercase letters.
3508\item[\T{%p}] \Em{} represents all punctuation characters.
3509\item[\T{%s}] \Em{} represents all space characters.
3510\item[\T{%u}] \Em{} represents all uppercase letters.
3511\item[\T{%w}] \Em{} represents all alphanumeric characters.
3512\item[\T{%x}] \Em{} represents all hexadecimal digits.
3513\item[\T{%z}] \Em{} represents the character with representation 0.
3514\item[\T{%\M{x}}] (where \M{x} is any non-alphanumeric character) \Em{}
3515represents the character \M{x}.
3516This is the standard way to escape the magic characters.
3517We recommend that any punctuation character (even the non magic)
3518should be preceded by a \verb|%|
3519when used to represent itself in a pattern.
3520
3521\item[\T{[\M{set}]}] \Em{}
3522represents the class which is the union of all
3523characters in \M{set}.
3524A range of characters may be specified by
3525separating the end characters of the range with a \verb|-|.
3526All classes \verb|%|\emph{x} described above may also be used as
3527components in \M{set}.
3528All other characters in \M{set} represent themselves.
3529For example, \verb|[%w_]| (or \verb|[_%w]|)
3530represents all alphanumeric characters plus the underscore,
3531\verb|[0-7]| represents the octal digits,
3532and \verb|[0-7%l%-]| represents the octal digits plus
3533the lowercase letters plus the \verb|-| character.
3534
3535The interaction between ranges and classes is not defined.
3536Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]|
3537have no meaning.
3538
3539\item[\T{[^\M{set}]}] \Em{}
3540represents the complement of \M{set},
3541where \M{set} is interpreted as above.
3542\end{description}
3543For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots),
3544the corresponding uppercase letter represents the complement of the class.
3545For instance, \verb|%S| represents all non-space characters.
3546
3547The definitions of letter, space, etc.{} depend on the current locale.
3548In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|.
3549The second form should be preferred for portability.
3550
3551\paragraph{Pattern Item:}
3552a \Def{pattern item} may be
3553\begin{itemize}
3554\item
3555a single character class,
3556which matches any single character in the class;
3557\item
3558a single character class followed by \verb|*|,
3559which matches 0 or more repetitions of characters in the class.
3560These repetition items will always match the longest possible sequence;
3561\item
3562a single character class followed by \verb|+|,
3563which matches 1 or more repetitions of characters in the class.
3564These repetition items will always match the longest possible sequence;
3565\item
3566a single character class followed by \verb|-|,
3567which also matches 0 or more repetitions of characters in the class.
3568Unlike \verb|*|,
3569these repetition items will always match the \emph{shortest} possible sequence;
3570\item
3571a single character class followed by \verb|?|,
3572which matches 0 or 1 occurrence of a character in the class;
3573\item
3574\T{%\M{n}}, for \M{n} between 1 and 9;
3575such item matches a substring equal to the \M{n}-th captured string
3576(see below);
3577\item
3578\T{%b\M{xy}}, where \M{x} and \M{y} are two distinct characters;
3579such item matches strings that start with\Nb{}\M{x}, end with\Nb{}\M{y},
3580and where the \M{x} and \M{y} are \emph{balanced}.
3581This means that, if one reads the string from left to right,
3582counting \Math{+1} for an \M{x} and \Math{-1} for a \M{y},
3583the ending \M{y} is the first \M{y} where the count reaches 0.
3584For instance, the item \verb|%b()| matches expressions with
3585balanced parentheses.
3586\end{itemize}
3587
3588\paragraph{Pattern:}
3589a \Def{pattern} is a sequence of pattern items.
3590A \verb|^| at the beginning of a pattern anchors the match at the
3591beginning of the subject string.
3592A \verb|$| at the end of a pattern anchors the match at the
3593end of the subject string.
3594At other positions,
3595\verb|^| and \verb|$| have no special meaning and represent themselves.
3596
3597\paragraph{Captures:}
3598A pattern may contain sub-patterns enclosed in parentheses;
3599they describe \Def{captures}.
3600When a match succeeds, the substrings of the subject string
3601that match captures are stored (\emph{captured}) for future use.
3602Captures are numbered according to their left parentheses.
3603For instance, in the pattern \verb|"(a*(.)%w(%s*))"|,
3604the part of the string matching \verb|"a*(.)%w(%s*)"| is
3605stored as the first capture (and therefore has number\Nb{}1);
3606the character matching \verb|.| is captured with number\Nb{}2,
3607and the part matching \verb|%s*| has number\Nb{}3.
3608
3609As a special case, the empty capture \verb|()| captures
3610the current string position (a number).
3611For instance, if we apply the pattern \verb|"()aa()"| on the
3612string \verb|"flaaap"|, there will be two captures: 3 and 5.
3613
3614\NOTE
3615A pattern cannot contain embedded zeros. Use \verb|%z| instead.
3616
3617
3618\subsection{Table Manipulation}
3619This library provides generic functions for table manipulation.
3620It provides all its functions inside the table \IndexLIB{table}.
3621
3622Most functions in the table library assume that the table
3623represents an array or a list.
3624For those functions, an important concept is the \emph{size} of the array.
3625There are three ways to specify that size:
3626\begin{itemize}
3627\item the field \verb|"n"| \Em{}
3628When the table has a field \verb|"n"| with a numerical value,
3629that value is assumed as its size.
3630\item \verb|setn| \Em{}
3631You can call the \verb|table.setn| function to explicitly set
3632the size of a table.
3633\item implicit size \Em{}
3634Otherwise, the size of the object is one less the first integer index
3635with a \nil{} value.
3636\end{itemize}
3637For more details, see the descriptions of the \verb|table.getn| and
3638\verb|table.setn| functions.
3639
3640\subsubsection*{\ff \T{table.concat (table [, sep [, i [, j]]])}}
3641\DefLIB{table.concat}
3642Returns \verb|table[i]..sep..table[i+1] ... sep..table[j]|.
3643The default value for \verb|sep| is the empty string,
3644the default for \verb|i| is 1,
3645and the default for \verb|j| is the size of the table.
3646If \verb|i| is greater than \verb|j|, returns the empty string.
3647
3648\subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach}
3649Executes the given \verb|func| over all elements of \verb|table|.
3650For each element, \verb|func| is called with the index and
3651respective value as arguments.
3652If \verb|func| returns a non-\nil{} value,
3653then the loop is broken, and this value is returned
3654as the final value of \verb|foreach|.
3655
3656The behavior of \verb|foreach| is \emph{undefined} if you change
3657the table \verb|t| during the traversal.
3658
3659
3660\subsubsection*{\ff \T{table.foreachi (table, func)}}\DefLIB{table.foreachi}
3661Executes the given \verb|func| over the
3662numerical indices of \verb|table|.
3663For each index, \verb|func| is called with the index and
3664respective value as arguments.
3665Indices are visited in sequential order,
3666from\Nb{}1 to \verb|n|,
3667where \verb|n| is the size of the table \see{getn}.
3668If \verb|func| returns a non-\nil{} value,
3669then the loop is broken, and this value is returned
3670as the final value of \verb|foreachi|.
3671
3672\subsubsection*{\ff \T{table.getn (table)}}\DefLIB{table.getn}\label{getn}
3673Returns the \Q{size} of a table, when seen as a list.
3674If the table has an \verb|n| field with a numeric value,
3675this value is the \Q{size} of the table.
3676Otherwise, if there was a previous call to
3677\verb|table.getn| or to \verb|table.setn| over this table,
3678the respective value is returned.
3679Otherwise, the \Q{size} is one less the first integer index with
3680a \nil{} value.
3681
3682Notice that the last option happens only once for a table.
3683If you call \verb|table.getn| again over the same table,
3684it will return the same previous result,
3685even if the table has been modified.
3686The only way to change the value of \verb|table.getn| is by calling
3687\verb|table.setn| or assigning to field \verb|"n"| in the table.
3688
3689\subsubsection*{\ff \T{table.sort (table [, comp])}}\DefLIB{table.sort}
3690Sorts table elements in a given order, \emph{in-place},
3691from \verb|table[1]| to \verb|table[n]|,
3692where \verb|n| is the size of the table \see{getn}.
3693If \verb|comp| is given,
3694then it must be a function that receives two table elements,
3695and returns true
3696when the first is less than the second
3697(so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
3698If \verb|comp| is not given,
3699then the standard Lua operator \verb|<| is used instead.
3700
3701The sort algorithm is \emph{not} stable
3702(that is, elements considered equal by the given order
3703may have their relative positions changed by the sort).
3704
3705\subsubsection*{\ff \T{table.insert (table, [pos,] value)}}\DefLIB{table.insert}
3706
3707Inserts element \verb|value| at position \verb|pos| in \verb|table|,
3708shifting other elements up to open space, if necessary.
3709The default value for \verb|pos| is \verb|n+1|,
3710where \verb|n| is the size of the table \see{getn},
3711so that a call \verb|table.insert(t,x)| inserts \verb|x| at the end
3712of table \verb|t|.
3713This function also updates the size of the table by
3714calling \verb|table.setn(table, n+1)|.
3715
3716\subsubsection*{\ff \T{table.remove (table [, pos])}}\DefLIB{table.remove}
3717
3718Removes from \verb|table| the element at position \verb|pos|,
3719shifting other elements down to close the space, if necessary.
3720Returns the value of the removed element.
3721The default value for \verb|pos| is \verb|n|,
3722where \verb|n| is the size of the table \see{getn},
3723so that a call \verb|tremove(t)| removes the last element
3724of table \verb|t|.
3725This function also updates the size of the table by
3726calling \verb|table.setn(table, n-1)|.
3727
3728\subsubsection*{\ff \T{table.setn (table, n)}}\DefLIB{table.setn}
3729
3730Updates the \Q{size} of a table.
3731If the table has a field \verb|"n"| with a numerical value,
3732that value is changed to the given \verb|n|.
3733Otherwise, it updates an internal state of the \verb|table| library
3734so that subsequent calls to \verb|table.getn(table)| return \verb|n|.
3735
3736
3737\subsection{Mathematical Functions} \label{mathlib}
3738
3739This library is an interface to most of the functions of the
3740standard C\Nb{}math library.
3741(Some have slightly different names.)
3742It provides all its functions inside the table \IndexLIB{math}.
3743In addition,
3744it registers a ??tag method for the binary exponentiation operator \verb|^|
3745that returns \Math{x\sp{y}} when applied to numbers \verb|x| and \verb|y|.
3746
3747The library provides the following functions:
3748\DefLIB{math.abs}\DefLIB{math.acos}\DefLIB{math.asin}\DefLIB{math.atan}
3749\DefLIB{math.atan2}\DefLIB{math.ceil}\DefLIB{math.cos}
3750\DefLIB{math.def}\DefLIB{math.exp}
3751\DefLIB{math.floor}\DefLIB{math.log}\DefLIB{math.log10}
3752\DefLIB{math.max}\DefLIB{math.min}
3753\DefLIB{math.mod}\DefLIB{math.rad}\DefLIB{math.sin}
3754\DefLIB{math.sqrt}\DefLIB{math.tan}
3755\DefLIB{math.frexp}\DefLIB{math.ldexp}\DefLIB{math.random}
3756\DefLIB{math.randomseed}
3757\begin{verbatim}
3758 math.abs math.acos math.asin math.atan math.atan2
3759 math.ceil math.cos math.deg math.exp math.floor
3760 math.log math.log10 math.max math.min math.mod
3761 math.rad math.sin math.sqrt math.tan math.frexp
3762 math.ldexp math.random math.randomseed
3763\end{verbatim}
3764plus a variable \IndexLIB{math.pi}.
3765Most of them
3766are only interfaces to the corresponding functions in the C\Nb{}library.
3767All trigonometric functions work in radians.
3768The functions \verb|math.deg| and \verb|math.rad| convert
3769between radians and degrees.
3770
3771The function \verb|math.max| returns the maximum
3772value of its numeric arguments.
3773Similarly, \verb|math.min| computes the minimum.
3774Both can be used with 1, 2, or more arguments.
3775
3776The functions \verb|math.random| and \verb|math.randomseed|
3777are interfaces to the simple random generator functions
3778\verb|rand| and \verb|srand| that are provided by ANSI\Nb{}C.
3779(No guarantees can be given for their statistical properties.)
3780When called without arguments,
3781\verb|math.random| returns a pseudo-random real number
3782in the range \Math{[0,1)}. \C{]}
3783When called with a number \Math{n},
3784\verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}.
3785When called with two arguments, \Math{l} and \Math{u},
3786\verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}.
3787The \verb|math.randomseed| function sets a \Q{seed}
3788for the pseudo-random generator:
3789Equal seeds produce equal sequences of numbers.
3790
3791
3792\subsection{Input and Output Facilities} \label{libio}
3793
3794The I/O library provides two different styles for file manipulation.
3795The first one uses implicit file descriptors;
3796that is, there are operations to set a default input file and a
3797default output file,
3798and all input/output operations are over those default files.
3799The second style uses explicit file descriptors.
3800
3801When using implicit file descriptors,
3802all operations are supplied by table \IndexLIB{io}.
3803When using explicit file descriptors,
3804the operation \IndexLIB{io.open} returns a file descriptor,
3805and then all operations are supplied as methods by the file descriptor.
3806
3807The table \verb|io| also provides
3808three predefined file descriptors with their usual meanings from C:
3809\IndexLIB{io.stdin}, \IndexLIB{io.stdout}, and \IndexLIB{io.stderr}.
3810
3811A file handle is a userdata containing the file stream (\verb|FILE*|),
3812with a distinctive metatable created by the I/O library.
3813
3814Unless otherwise stated,
3815all I/O functions return \nil{} on failure
3816(plus an error message as a second result)
3817and some value different from \nil{} on success.
3818
3819\subsubsection*{\ff \T{io.close ([file])}}\DefLIB{io.close}
3820
3821Equivalent to \verb|file:close()|.
3822Without a \verb|file|, closes the default output file.
3823
3824\subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush}
3825
3826Equivalent to \verb|file:flush| over the default output file.
3827
3828\subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input}
3829
3830When called with a file name, it opens the named file (in text mode),
3831and sets its handle as the default input file
3832(and returns nothing).
3833When called with a file handle,
3834it simply sets that file handle as the default input file.
3835When called without parameters,
3836it returns the current default input file.
3837
3838In case of errors this function raises the error,
3839instead of returning an error code.
3840
3841\subsubsection*{\ff \T{io.lines ([filename])}}\DefLIB{io.lines}
3842
3843Opens the given file name in read mode,
3844and returns a generator function that,
3845each time it is called,
3846returns a new line from the file.
3847Therefore, the construction
3848\begin{verbatim}
3849 for line in io.lines(filename) do ... end
3850\end{verbatim}
3851will iterate over all lines of the file.
3852When the generator function detects the end of file,
3853it returns nil (to finish the loop) and automatically closes the file.
3854
3855The call \verb|io.lines()| (without a file name) is equivalent
3856to \verb|io.input():lines()|, that is, it iterates over the
3857lines of the default input file.
3858
3859\subsubsection*{\ff \T{io.open (filename [, mode])}}\DefLIB{io.open}
3860
3861This function opens a file,
3862in the mode specified in the string \verb|mode|.
3863It returns a new file handle,
3864or, in case of errors, \nil{} plus an error message.
3865
3866The \verb|mode| string can be any of the following:
3867\begin{description}\leftskip=20pt
3868\item[\Q{r}] read mode (the default);
3869\item[\Q{w}] write mode;
3870\item[\Q{a}] append mode;
3871\item[\Q{r+}] update mode, all previous data is preserved;
3872\item[\Q{w+}] update mode, all previous data is erased;
3873\item[\Q{a+}] append update mode, previous data is preserved,
3874 writing is only allowed at the end of file.
3875\end{description}
3876The \verb|mode| string may also have a \verb|b| at the end,
3877which is needed in some systems to open the file in binary mode.
3878This string is exactly what is used in the standard\Nb{}C function \verb|fopen|.
3879
3880\subsubsection*{\ff \T{io.output ([file])}}\DefLIB{io.output}
3881
3882Similar to \verb|io.input|, but operates over the default output file.
3883
3884\subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read}
3885
3886Equivalent to \verb|file:read| over the default input file.
3887
3888\subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile}
3889
3890Returns a handle for a temporary file.
3891This file is open in read/write mode,
3892and it is automatically removed when the program ends.
3893
3894\subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write}
3895
3896Equivalent to \verb|file:write| over the default output file.
3897
3898
3899
3900\subsubsection*{\ff \T{file:close ()}}\DefLIB{file:close}
3901
3902Closes the file \verb|file|.
3903
3904\subsubsection*{\ff \T{file:flush ()}}\DefLIB{file:flush}
3905
3906Saves any written data to the file \verb|file|.
3907
3908\subsubsection*{\ff \T{file:lines ()}}\DefLIB{file:lines}
3909
3910Returns a generator function that,
3911each time it is called,
3912returns a new line from the file.
3913Therefore, the construction
3914\begin{verbatim}
3915 for line in file:lines() do ... end
3916\end{verbatim}
3917will iterate over all lines of the file.
3918(Unlike \verb|io.lines|, this function does not close the file
3919when the loop ends.)
3920
3921\subsubsection*{\ff \T{file:read (format1, ...)}}\DefLIB{file:read}
3922
3923Reads the file \verb|file|,
3924according to the given formats, which specify what to read.
3925For each format,
3926the function returns a string (or a number) with the characters read,
3927or \nil{} if it cannot read data with the specified format.
3928When called without formats,
3929it uses a default format that reads the entire next line
3930(see below).
3931
3932The available formats are
3933\begin{description}\leftskip=20pt
3934\item[\Q{*n}] reads a number;
3935this is the only format that returns a number instead of a string.
3936\item[\Q{*a}] reads the whole file, starting at the current position.
3937On end of file, it returns the empty string.
3938\item[\Q{*l}] reads the next line (skipping the end of line),
3939returning \nil{} on end of file.
3940This is the default format.
3941\item[\emph{number}] reads a string with up to that number of characters,
3942or \nil{} on end of file.
3943If number is zero,
3944it reads nothing and returns an empty string,
3945or \nil{} on end of file.
3946\end{description}
3947
3948\subsubsection*{\ff \T{file:seek ([whence] [, offset])}}\DefLIB{file:seek}
3949
3950Sets and gets the file position,
3951measured in bytes from the beginning of the file,
3952to the position given by \verb|offset| plus a base
3953specified by the string \verb|whence|, as follows:
3954\begin{description}\leftskip=20pt
3955\item[\Q{set}] base is position 0 (beginning of the file);
3956\item[\Q{cur}] base is current position;
3957\item[\Q{end}] base is end of file;
3958\end{description}
3959In case of success, function \verb|seek| returns the final file position,
3960measured in bytes from the beginning of the file.
3961If this function fails, it returns \nil{},
3962plus a string describing the error.
3963
3964The default value for \verb|whence| is \verb|"cur"|,
3965and for \verb|offset| is 0.
3966Therefore, the call \verb|file:seek()| returns the current
3967file position, without changing it;
3968the call \verb|file:seek("set")| sets the position to the
3969beginning of the file (and returns 0);
3970and the call \verb|file:seek("end")| sets the position to the
3971end of the file, and returns its size.
3972
3973\subsubsection*{\ff \T{file:write (value1, ...)}}\DefLIB{file:write}
3974
3975Writes the value of each of its arguments to
3976the filehandle \verb|file|.
3977The arguments must be strings or numbers.
3978To write other values,
3979use \verb|tostring| or \verb|format| before \verb|write|.
3980If this function fails, it returns \nil{},
3981plus a string describing the error.
3982
3983
3984\subsection{Operating System Facilities} \label{libiosys}
3985
3986This library is implemented through table \IndexLIB{os}.
3987
3988\subsubsection*{\ff \T{os.clock ()}}\DefLIB{os.clock}
3989
3990Returns an approximation of the amount of CPU time
3991used by the program, in seconds.
3992
3993\subsubsection*{\ff \T{os.date ([format [, time]])}}\DefLIB{os.date}
3994
3995Returns a string or a table containing date and time,
3996formatted according to the given string \verb|format|.
3997
3998If the \verb|time| argument is present,
3999this is the time to be formatted
4000(see the \verb|time| function for a description of this value).
4001Otherwise, \verb|date| formats the current time.
4002
4003If \verb|format| starts with \verb|!|,
4004then the date is formatted in Coordinated Universal Time.
4005
4006After that optional character,
4007if \verb|format| is \verb|*t|,
4008then \verb|date| returns a table with the following fields:
4009\verb|year| (four digits), \verb|month| (1--12), \verb|day| (1--31),
4010\verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--61),
4011\verb|wday| (weekday, Sunday is 1),
4012\verb|yday| (day of the year),
4013and \verb|isdst| (daylight saving flag, a boolean).
4014
4015If format is not \verb|*t|,
4016then \verb|date| returns the date as a string,
4017formatted according with the same rules as the C\Nb{}function \verb|strftime|.
4018When called without arguments,
4019\verb|date| returns a reasonable date and time representation that depends on
4020the host system and on the current locale
4021(that is, \verb|os.date()| is equivalent to \verb|os.date("%c")|).
4022
4023\subsubsection*{\ff \T{os.difftime (t2, t1)}}\DefLIB{os.difftime}
4024
4025Returns the number of seconds from time \verb|t1| to time \verb|t2|.
4026In Posix, Windows, and some other systems,
4027this value is exactly \verb|t2|\Math{-}\verb|t1|.
4028
4029\subsubsection*{\ff \T{os.execute (command)}}\DefLIB{os.execute}
4030
4031This function is equivalent to the C\Nb{}function \verb|system|.
4032It passes \verb|command| to be executed by an operating system shell.
4033It returns a status code, which is system-dependent.
4034
4035\subsubsection*{\ff \T{os.exit ([code])}}\DefLIB{os.exit}
4036
4037Calls the C\Nb{}function \verb|exit|,
4038with an optional \verb|code|,
4039to terminate the host program.
4040The default value for \verb|code| is the success code.
4041
4042\subsubsection*{\ff \T{os.getenv (varname)}}\DefLIB{os.getenv}
4043
4044Returns the value of the process environment variable \verb|varname|,
4045or \nil{} if the variable is not defined.
4046
4047\subsubsection*{\ff \T{os.remove (filename)}}\DefLIB{os.remove}
4048
4049Deletes the file with the given name.
4050If this function fails, it returns \nil{},
4051plus a string describing the error.
4052
4053\subsubsection*{\ff \T{os.rename (name1, name2)}}\DefLIB{os.rename}
4054
4055Renames file named \verb|name1| to \verb|name2|.
4056If this function fails, it returns \nil{},
4057plus a string describing the error.
4058
4059\subsubsection*{\ff \T{os.setlocale (locale [, category])}}\DefLIB{os.setlocale}
4060
4061This function is an interface to the C\Nb{}function \verb|setlocale|.
4062\verb|locale| is a string specifying a locale;
4063\verb|category| is an optional string describing which category to change:
4064\verb|"all"|, \verb|"collate"|, \verb|"ctype"|,
4065\verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|;
4066the default category is \verb|"all"|.
4067The function returns the name of the new locale,
4068or \nil{} if the request cannot be honored.
4069
4070\subsubsection*{\ff \T{os.time ([table])}}\DefLIB{os.time}
4071
4072Returns the current time when called without arguments,
4073or a time representing the date and time specified by the given table.
4074This table must have fields \verb|year|, \verb|month|, and \verb|day|,
4075and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst|
4076(for a description of these fields, see the \verb|os.date| function).
4077
4078The returned value is a number, whose meaning depends on your system.
4079In Posix, Windows, and some other systems, this number counts the number
4080of seconds since some given start time (the \Q{epoch}).
4081In other systems, the meaning is not specified,
4082and the number returned by \verb|time| can be used only as an argument to
4083\verb|date| and \verb|difftime|.
4084
4085\subsubsection*{\ff \T{os.tmpname ()}}\DefLIB{os.tmpname}
4086
4087Returns a string with a file name that can
4088be used for a temporary file.
4089The file must be explicitly opened before its use
4090and removed when no longer needed.
4091
4092This function is equivalent to the \verb|tmpnam| C\Nb{}function,
4093and many people (and even some compilers!) advise against its use,
4094because between the time you call this function
4095and the time you open the file,
4096it is possible for another process
4097to create a file with the same name.
4098
4099
4100\subsection{The Reflexive Debug Interface}
4101
4102The library \verb|ldblib| provides
4103the functionality of the debug interface to Lua programs.
4104You should exert great care when using this library.
4105The functions provided here should be used exclusively for debugging
4106and similar tasks, such as profiling.
4107Please resist the temptation to use them as a
4108usual programming tool:
4109They can be very slow.
4110Moreover, \verb|setlocal| and \verb|getlocal|
4111violate the privacy of local variables,
4112and therefore can compromise some (otherwise) secure code.
4113
4114All functions in this library are provided
4115inside a \IndexVerb{debug} table.
4116
4117
4118\subsubsection*{\ff \T{debug.getinfo (function, [what])}}\DefLIB{debug.getinfo}
4119
4120This function returns a table with information about a function.
4121You can give the function directly,
4122or you can give a number as the value of \verb|function|,
4123which means the function running at level \verb|function| of the stack:
4124Level 0 is the current function (\verb|getinfo| itself);
4125level 1 is the function that called \verb|getinfo|;
4126and so on.
4127If \verb|function| is a number larger than the number of active functions,
4128then \verb|getinfo| returns \nil{}.
4129
4130The returned table contains all the fields returned by \verb|lua_getinfo|,
4131with the string \verb|what| describing which fields to fill in.
4132The default for \verb|what| is to get all information available.
4133If present,
4134the option \verb|f|
4135adds a field named \verb|func| with the function itself.
4136
4137For instance, the expression \verb|debug.getinfo(1,"n").name| returns
4138the name of the current function, if a reasonable name can be found,
4139and \verb|debug.getinfo(print)| returns a table with all available information
4140about the \verb|print| function.
4141
4142
4143\subsubsection*{\ff \T{debug.getlocal (level, local)}}\DefLIB{debug.getlocal}
4144
4145This function returns the name and the value of the local variable
4146with index \verb|local| of the function at level \verb|level| of the stack.
4147(The first parameter or local variable has index\Nb{}1, and so on,
4148until the last active local variable.)
4149The function returns \nil{} if there is no local
4150variable with the given index,
4151and raises an error when called with a \verb|level| out of range.
4152(You can call \verb|getinfo| to check whether the level is valid.)
4153
4154\subsubsection*{\ff \T{debug.setlocal (level, local, value)}}
4155\DefLIB{debug.setlocal}
4156
4157This function assigns the value \verb|value| to the local variable
4158with index \verb|local| of the function at level \verb|level| of the stack.
4159The function returns \nil{} if there is no local
4160variable with the given index,
4161and raises an error when called with a \verb|level| out of range.
4162(You can call \verb|getinfo| to check whether the level is valid.)
4163
4164\subsubsection*{\ff \T{debug.sethook (hook, mask [, count])}}
4165\DefLIB{debug.sethook}
4166
4167Sets the given function as a hook.
4168The string \verb|mask| and the number \verb|count| describe
4169when the hook will be called.
4170The string mask may have the following characters,
4171with the given meaning:
4172\begin{description}
4173\item[{\tt "c"}] The hook is called every time Lua calls a function;
4174\item[{\tt "r"}] The hook is called every time Lua returns from a function;
4175\item[{\tt "l"}] The hook is called every time Lua enters a new line of code.
4176\end{description}
4177With a \verb|count| different from zero,
4178the hook is called after every \verb|count| instructions.
4179
4180When called without arguments,
4181the \verb|debug.sethook| function turns off the hook.
4182
4183When the hook is called, its first parameter is always a string
4184describing the event that triggered its call:
4185\verb|"call"|, \verb|"return"|, \verb|"line"|, and \verb|"count"|.
4186Moreover, for line events,
4187it also gets as its second parameter the new line number.
4188Inside a hook,
4189you can call \verb|getinfo| with level 2 to get more information about
4190the running function
4191(level\Nb{}0 is the \verb|getinfo| function,
4192and level\Nb{}1 is the hook function).
4193
4194\subsubsection*{\ff \T{debug.gethook ()}}\DefLIB{debug.gethook}
4195
4196Returns the current hook settings, as three values:
4197the current hook function, the current hook mask,
4198and the current hook count (as set by the \verb|debug.sethook| function).
4199
4200
4201\C{-------------------------------------------------------------------------}
4202\section{\Index{Lua Stand-alone}} \label{lua-sa}
4203
4204Although Lua has been designed as an extension language,
4205to be embedded in a host C\Nb{}program,
4206it is also frequently used as a stand-alone language.
4207An interpreter for Lua as a stand-alone language,
4208called simply \verb|lua|,
4209is provided with the standard distribution.
4210The stand-alone interpreter includes
4211all standard libraries plus the reflexive debug interface.
4212Its usage is:
4213\begin{verbatim}
4214 lua [options] [script [args]]
4215\end{verbatim}
4216The options are:
4217\begin{description}\leftskip=20pt
4218\item[\T{-} ] executes \verb|stdin| as a file;
4219\item[\T{-e} \rm\emph{stat}] executes string \emph{stat};
4220\item[\T{-l} \rm\emph{file}] \Q{requires} \emph{file};
4221\item[\T{-i}] enters interactive mode after running \emph{script};
4222\item[\T{-v}] prints version information;
4223\item[\T{--}] stop handling options.
4224\end{description}
4225After handling its options, \verb|lua| runs the given \emph{script},
4226passing to it the given \emph{args}.
4227When called without arguments,
4228\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
4229and as \verb|lua -| otherwise.
4230
4231Before running any argument,
4232the interpreter checks for an environment variable \IndexVerb{LUA_INIT}.
4233If its format is \At{}\emph{filename},
4234then lua executes the file.
4235Otherwise, lua executes the string itself.
4236
4237All options are handled in order, except \verb|-i|.
4238For instance, an invocation like
4239\begin{verbatim}
4240 $ lua -e'a=1' -e 'print(a)' script.lua
4241\end{verbatim}
4242will first set \verb|a| to 1, then print \verb|a|,
4243and finally run the file \verb|script.lua|.
4244(Here, \verb|$| is the shell prompt. Your prompt may be different.)
4245
4246Before starting to run the script,
4247\verb|lua| collects all arguments in the command line
4248in a global table called \verb|arg|.
4249The script name is stored in index 0,
4250the first argument after the script name goes to index 1,
4251and so on.
4252The field \verb|n| gets the number of arguments after the script name.
4253Any arguments before the script name
4254(that is, the interpreter name plus the options)
4255go to negative indices.
4256For instance, in the call
4257\begin{verbatim}
4258 $ lua -la.lua b.lua t1 t2
4259\end{verbatim}
4260the interpreter first runs the file \T{a.lua},
4261then creates a table
4262\begin{verbatim}
4263 arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua",
4264 [1] = "t1", [2] = "t2"; n = 2 }
4265\end{verbatim}
4266and finally runs the file \T{b.lua}.
4267
4268In interactive mode,
4269if you write an incomplete statement,
4270the interpreter waits for its completion.
4271
4272If the global variable \IndexVerb{_PROMPT} is defined as a string,
4273then its value is used as the prompt.
4274Therefore, the prompt can be changed directly on the command line:
4275\begin{verbatim}
4276 $ lua -e"_PROMPT='myprompt> '" -i
4277\end{verbatim}
4278(the first pair of quotes is for the shell,
4279the second is for Lua),
4280or in any Lua programs by assigning to \verb|_PROMPT|.
4281Note the use of \verb|-i| to enter interactive mode; otherwise,
4282the program would end just after the assignment to \verb|_PROMPT|.
4283
4284In Unix systems, Lua scripts can be made into executable programs
4285by using \verb|chmod +x| and the\Nb{}\verb|#!| form,
4286as in
4287\begin{verbatim}
4288#!/usr/local/bin/lua
4289\end{verbatim}
4290(Of course,
4291the location of the Lua interpreter may be different in your machine.
4292If \verb|lua| is in your \verb|PATH|,
4293then
4294\begin{verbatim}
4295#!/usr/bin/env lua
4296\end{verbatim}
4297is a more portable solution.)
4298
4299\C{-------------------------------------------------------------------------}
4300\section*{Acknowledgments}
4301
4302The Lua team is grateful to \tecgraf{} for its continued support to Lua.
4303We thank everyone at \tecgraf{},
4304specially the head of the group, Marcelo Gattass.
4305At the risk of omitting several names,
4306we also thank the following individuals for supporting,
4307contributing to, and spreading the word about Lua:
4308Alan Watson.
4309André Clinio,
4310André Costa,
4311Antonio Scuri,
4312Bret Mogilefsky,
4313Cameron Laird,
4314Carlos Cassino,
4315Carlos Henrique Levy,
4316Claudio Terra,
4317David Jeske,
4318Edgar Toernig,
4319Erik Hougaard,
4320Jim Mathies,
4321John Belmonte,
4322John Passaniti,
4323John Roll,
4324Jon Erickson,
4325Jon Kleiser,
4326Mark Ian Barlow,
4327Nick Trout,
4328Noemi Rodriguez,
4329Norman Ramsey,
4330Philippe Lhoste,
4331Renata Ratton,
4332Renato Borges,
4333Renato Cerqueira,
4334Reuben Thomas,
4335Stephan Herrmann,
4336Steve Dekorte,
4337Thatcher Ulrich,
4338Tomás Gorham,
4339Vincent Penquerc'h,
4340Thank you!
4341
4342
4343\appendix
4344
4345\section*{Incompatibilities with Previous Versions}
4346\addcontentsline{toc}{section}{Incompatibilities with Previous Versions}
4347
4348\subsection*{Incompatibilities with \Index{version 4.0}}
4349
4350\subsubsection*{Changes in the Language}
4351\begin{itemize}
4352
4353\item
4354Function calls written between parentheses result in exactly one value.
4355
4356\item
4357A function call as the last expression in a list constructor
4358(like \verb|{a,b,f()}|) has all its return values inserted in the list.
4359
4360\item
4361The precedence of \rwd{or} is smaller than the precedence of \rwd{and}.
4362
4363\item
4364\rwd{in} is a reserved word.
4365
4366\item
4367The old construction \verb|for k,v in t|, where \verb|t| is a table,
4368is deprecated (although it is still supported).
4369Use \verb|for k,v in pairs(t)| instead.
4370
4371\item
4372When a literal string of the form \verb|[[...]]| starts with a newline,
4373this newline is ignored.
4374
4375\item Old pre-compiled code is obsolete, and must be re-compiled.
4376
4377\end{itemize}
4378
4379
4380\subsubsection*{Changes in the Libraries}
4381\begin{itemize}
4382
4383\item
4384Most library functions now are defined inside tables.
4385There is a compatibility script (\verb|compat.lua|) that
4386redefine most of them as global names.
4387
4388\item
4389In the math library, angles are expressed in radians.
4390With the compatibility script (\verb|compat.lua|),
4391functions still work in degrees.
4392
4393\item
4394The \verb|call| function is deprecated.
4395Use \verb|f(unpack(tab))| instead of \verb|call(f, tab)|
4396for unprotected calls,
4397or the new \verb|pcall| function for protected calls.
4398
4399\item
4400\verb|dofile| do not handle errors, but simply propagates them.
4401
4402\item
4403The \verb|read| option \verb|*w| is obsolete.
4404
4405\item
4406The \verb|format| option \verb|%n$| is obsolete.
4407
4408\end{itemize}
4409
4410
4411\subsubsection*{Changes in the API}
4412\begin{itemize}
4413
4414\item
4415Userdata!!
4416
4417\end{itemize}
4418
4419
4420
4421\C{[===============================================================}
4422\newpage
4423\section*{The Complete Syntax of Lua} \label{BNF}
4424\addcontentsline{toc}{section}{The Complete Syntax of Lua}
4425
4426The notation used here is the usual extended BNF,
4427in which
4428\rep{\emph{a}}\Nb{}means 0 or more \emph{a}'s, and
4429\opt{\emph{a}}\Nb{}means an optional \emph{a}.
4430Non-terminals are shown in \emph{italics},
4431keywords are shown in {\bf bold},
4432and other terminal symbols are shown in {\tt typewriter} font,
4433enclosed in single quotes.
4434
4435
4436\index{grammar}
4437
4438\begin{Produc}
4439
4440\produc{chunk}{\rep{stat \opt{\ter{;}}}}
4441
4442\produc{block}{chunk}
4443
4444\produc{stat}{
4445 varlist1 \ter{=} explist1
4446\OrNL functioncall
4447\OrNL \rwd{do} block \rwd{end}
4448\OrNL \rwd{while} exp \rwd{do} block \rwd{end}
4449\OrNL \rwd{repeat} block \rwd{until} exp
4450\OrNL \rwd{if} exp \rwd{then} block
4451 \rep{\rwd{elseif} exp \rwd{then} block}
4452 \opt{\rwd{else} block} \rwd{end}
4453\OrNL \rwd{return} \opt{explist1}
4454\OrNL \rwd{break}
4455\OrNL \rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
4456 \rwd{do} block \rwd{end}
4457\OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
4458 \rwd{do} block \rwd{end}
4459\OrNL \rwd{function} funcname funcbody
4460\OrNL \rwd{local} \rwd{function} \Nter{Name} funcbody
4461\OrNL \rwd{local} namelist \opt{init}
4462}
4463
4464\produc{funcname}{\Nter{Name} \rep{\ter{.} \Nter{Name}}
4465 \opt{\ter{:} \Nter{Name}}}
4466
4467\produc{varlist1}{var \rep{\ter{,} var}}
4468
4469\produc{var}{
4470 \Nter{Name}
4471\Or prefixexp \ter{[} exp \ter{]}
4472\Or prefixexp \ter{.} \Nter{Name}
4473}
4474
4475\produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
4476
4477\produc{init}{\ter{=} explist1}
4478
4479\produc{explist1}{\rep{exp \ter{,}} exp}
4480
4481\produc{exp}{
4482 \rwd{nil}
4483 \rwd{false}
4484 \rwd{true}
4485\Or \Nter{Number}
4486\OrNL \Nter{Literal}
4487\Or function
4488\Or prefixexp
4489\OrNL tableconstructor
4490\Or exp binop exp
4491\Or unop exp
4492}
4493
4494\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
4495
4496\produc{functioncall}{
4497 prefixexp args
4498\Or prefixexp \ter{:} \Nter{Name} args
4499}
4500
4501\produc{args}{
4502 \ter{(} \opt{explist1} \ter{)}
4503\Or tableconstructor
4504\Or \Nter{Literal}
4505}
4506
4507\produc{function}{\rwd{function} funcbody}
4508
4509\produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
4510
4511\produc{parlist1}{
4512 \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}}
4513\Or \ter{\ldots}
4514}
4515
4516\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
4517\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
4518\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp}
4519\produc{fieldsep}{\ter{,} \Or \ter{;}}
4520
4521\produc{binop}{\ter{+} \Or \ter{-} \Or \ter{*} \Or \ter{/} \Or \ter{^} \Or
4522 \ter{..} \OrNL \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=}
4523 \Or \ter{==} \Or \ter{~=} \OrNL \rwd{and} \Or \rwd{or}}
4524
4525\produc{unop}{\ter{-} \Or \rwd{not}}
4526
4527\end{Produc}
4528
4529\C{]===============================================================}
4530
4531\C{ Index}
4532
4533\newpage
4534\addcontentsline{toc}{section}{Index}
4535\input{manual.id}
4536
4537\end{document}
4538%)]}
4539