aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-09-18 16:41:16 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-09-18 16:41:16 -0300
commit6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117 (patch)
tree29b1976e0a5895051a1838f283565e5d91f67e1d
parent42ca3105acab0eab0bd99af58e2bbdff111325f1 (diff)
downloadlua-6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117.tar.gz
lua-6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117.tar.bz2
lua-6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117.zip
updates by lhf
-rw-r--r--manual.tex2183
1 files changed, 1154 insertions, 1029 deletions
diff --git a/manual.tex b/manual.tex
index 64f18c50..5d86a188 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.41 2000/08/14 19:18:14 roberto Exp roberto $ 1% $Id: manual.tex,v 1.42 2000/08/30 18:58:46 roberto Exp roberto $
2 2
3\documentclass[11pt]{article} 3\documentclass[11pt]{article}
4\usepackage{fullpage,bnf} 4\usepackage{fullpage,bnf}
@@ -28,7 +28,7 @@
28% LHF 28% LHF
29\renewcommand{\ter}[1]{{\rm`{\tt#1}'}} 29\renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
30\newcommand{\Nter}[1]{{\rm{\tt#1}}} 30\newcommand{\Nter}[1]{{\rm{\tt#1}}}
31\newcommand{\NOTE}{\par\noindent\emph{NOTE}: } 31\newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: }
32 32
33\makeindex 33\makeindex
34 34
@@ -70,28 +70,29 @@ Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved.
70 70
71\noindent 71\noindent
72Permission is hereby granted, without written agreement and without license 72Permission is hereby granted, without written agreement and without license
73or royalty fees, to use, copy, modify, and distribute this software and its 73or royalty fees, to use, copy, modify, translate, and distribute
74documentation for any purpose, including commercial applications, subject to 74this software and its documentation (hereby called the "package")
75for any purpose, including commercial applications, subject to
75the following conditions: 76the following conditions:
76\begin{itemize} 77\begin{itemize}
77\item The above copyright notice and this permission notice shall appear in all 78\item The above copyright notice and this permission notice shall appear in all
78 copies or substantial portions of this software. 79 copies or substantial portions of this package.
79 80
80\item The origin of this software must not be misrepresented; you must not 81\item The origin of this package must not be misrepresented; you must not
81 claim that you wrote the original software. If you use this software in a 82 claim that you wrote the original package. If you use this package in a
82 product, an acknowledgment in the product documentation would be greatly 83 product, an acknowledgment in the product documentation would be greatly
83 appreciated (but it is not required). 84 appreciated (but it is not required).
84 85
85\item Altered source versions must be plainly marked as such, and must not be 86\item Altered source versions must be plainly marked as such, and must not be
86 misrepresented as being the original software. 87 misrepresented as being the original package.
87\end{itemize} 88\end{itemize}
88The authors specifically disclaim any warranties, including, but not limited 89The authors specifically disclaim any warranties, including, but not limited
89to, the implied warranties of merchantability and fitness for a particular 90to, the implied warranties of merchantability and fitness for a particular
90purpose. The software provided hereunder is on an ``as is'' basis, and the 91purpose. The package provided hereunder is on an ``as is'' basis, and the
91authors have no obligation to provide maintenance, support, updates, 92authors have no obligation to provide maintenance, support, updates,
92enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the 93enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the
93authors be held liable to any party for direct, indirect, special, 94authors be held liable to any party for direct, indirect, special,
94incidental, or consequential damages arising out of the use of this software 95incidental, or consequential damages arising out of the use of this package
95and its documentation. 96and its documentation.
96 97
97\noindent 98\noindent
@@ -105,11 +106,16 @@ This implementation contains no third-party code.
105\noindent 106\noindent
106Copies of this manual can be obtained at 107Copies of this manual can be obtained at
107\verb|http://www.tecgraf.puc-rio.br/lua/|. 108\verb|http://www.tecgraf.puc-rio.br/lua/|.
109
110\bigskip
111\noindent
112The Lua logo was designed by A. Nakonechny.
113Copyright \copyright\ 1998. All rights reserved.
108\end{quotation} 114\end{quotation}
109%}=============================================================== 115%}===============================================================
110\newpage 116\newpage
111 117
112\title{Reference Manual of the Programming Language Lua \Version} 118\title{\Large\bf Reference Manual of the Programming Language Lua \Version}
113 119
114\author{% 120\author{%
115Roberto Ierusalimschy\quad 121Roberto Ierusalimschy\quad
@@ -123,12 +129,15 @@ Waldemar Celes
123\tecgraf\ --- Computer Science Department --- PUC-Rio 129\tecgraf\ --- Computer Science Department --- PUC-Rio
124} 130}
125 131
126\date{{\small \tt\$Date: 2000/08/14 19:18:14 $ $}} 132\date{{\small \tt\$Date: 2000/08/30 18:58:46 $ $}}
127 133
128\maketitle 134\maketitle
129 135
130\thispagestyle{empty} 136\pagestyle{plain}
131\pagestyle{empty} 137\pagenumbering{roman}
138
139%\thispagestyle{empty}
140%\pagestyle{empty}
132 141
133\begin{abstract} 142\begin{abstract}
134\noindent 143\noindent
@@ -151,8 +160,8 @@ and
151rapid prototyping. 160rapid prototyping.
152 161
153This document describes version \Version\ of the Lua programming language 162This document describes version \Version\ of the Lua programming language
154and the API that allows interaction between Lua programs and their 163and the Application Program Interface (API)
155host C programs. 164that allows interaction between Lua programs and their host C~programs.
156\end{abstract} 165\end{abstract}
157 166
158\def\abstractname{Resumo} 167\def\abstractname{Resumo}
@@ -160,7 +169,7 @@ host C programs.
160\noindent 169\noindent
161Lua \'e uma linguagem de programa\c{c}\~ao 170Lua \'e uma linguagem de programa\c{c}\~ao
162poderosa e leve, 171poderosa e leve,
163projetada para extender aplica\c{c}\~oes. 172projetada para estender aplica\c{c}\~oes.
164Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral. 173Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral.
165Lua combina programa\c{c}\~ao procedural 174Lua combina programa\c{c}\~ao procedural
166(com sintaxe semelhante \`a de Pascal) 175(com sintaxe semelhante \`a de Pascal)
@@ -178,7 +187,7 @@ e prototipagem r\'apida.
178 187
179Este documento descreve a vers\~ao \Version\ da linguagem de 188Este documento descreve a vers\~ao \Version\ da linguagem de
180programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite 189programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite
181a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. 190a intera\c{c}\~ao entre programas Lua e programas C~hospedeiros.
182\end{abstract} 191\end{abstract}
183 192
184\newpage 193\newpage
@@ -188,6 +197,7 @@ a intera\c{c}\~ao entre programas Lua e programas C hospedeiros.
188 197
189\newpage 198\newpage
190\setcounter{page}{1} 199\setcounter{page}{1}
200\pagenumbering{arabic}
191\pagestyle{plain} 201\pagestyle{plain}
192 202
193 203
@@ -211,13 +221,13 @@ a wide range of different domains,
211thus creating customized programming languages sharing a syntactical framework. 221thus creating customized programming languages sharing a syntactical framework.
212 222
213Lua is free-distribution software, 223Lua is free-distribution software,
214and provided as usual with no guarantees, 224and is provided as usual with no guarantees,
215as stated in its copyright notice. 225as stated in its copyright notice.
216The implementation described in this manual is available 226The implementation described in this manual is available
217at the following URL's: 227at the following URL's:
218\begin{verbatim} 228\begin{verbatim}
219 http://www.tecgraf.puc-rio.br/lua/ 229 http://www.tecgraf.puc-rio.br/lua/
220 ftp://ftp.tecgraf.puc-rio.br/pub/lua/ 230 ftp://ftp.tecgraf.puc-rio.br/pub/lua/
221\end{verbatim} 231\end{verbatim}
222 232
223Like any other reference manual, 233Like any other reference manual,
@@ -244,10 +254,11 @@ Lua: an extensible embedded language.
244 254
245All statements in Lua are executed in a \Def{global environment}. 255All statements in Lua are executed in a \Def{global environment}.
246This environment is initialized with a call from the embedding program to 256This environment is initialized with a call from the embedding program to
247\verb|lua_newstate| and 257\verb|lua_open| and
248persists until a call to \verb|lua_close|, 258persists until a call to \verb|lua_close|,
249or the end of the embedding program. 259or the end of the embedding program.
250Optionally, a user can create multiple independent global 260If necessary,
261the host programmer can create multiple independent global
251environments, and freely switch between them \see{mangstate}. 262environments, and freely switch between them \see{mangstate}.
252 263
253The global environment can be manipulated by Lua code or 264The global environment can be manipulated by Lua code or
@@ -255,13 +266,13 @@ by the embedding program,
255which can read and write global variables 266which can read and write global variables
256using API functions from the library that implements Lua. 267using API functions from the library that implements Lua.
257 268
258\Index{Global variables} do not need declaration. 269\Index{Global variables} in Lua do not need to be declared.
259Any variable is assumed to be global unless explicitly declared local 270Any variable is assumed to be global unless explicitly declared local
260\see{localvar}. 271\see{localvar}.
261Before the first assignment, the value of a global variable is \nil; 272Before the first assignment, the value of a global variable is \nil;
262this default can be changed \see{tag-method}. 273this default can be changed \see{tag-method}.
263A ``table of globals'' (called \emph{tog}) is used to keep all 274A table is used to keep all global names and values
264global names and values. 275(tables are explained in \See{TypesSec}).
265 276
266The unit of execution of Lua is called a \Def{chunk}. 277The unit of execution of Lua is called a \Def{chunk}.
267A chunk is simply a sequence of statements, 278A chunk is simply a sequence of statements,
@@ -275,11 +286,12 @@ Statements are described in \See{stats}.
275in which 286in which
276\rep{\emph{a}} means 0 or more \emph{a}'s, 287\rep{\emph{a}} means 0 or more \emph{a}'s,
277\opt{\emph{a}} means an optional \emph{a}, and 288\opt{\emph{a}} means an optional \emph{a}, and
278\oneormore{\emph{a}} means one or more \emph{a}'s.) 289\oneormore{\emph{a}} means one or more \emph{a}'s.
290The complete syntax of Lua is given on page~\pageref{BNF}.)
279 291
280A chunk may be in a file or in a string inside the host program. 292A chunk may be stored in a file or in a string inside the host program.
281When a chunk is executed, first all its code is pre-compiled, 293When a chunk is executed, first it is pre-compiled into bytecodes for
282and then the statements are executed in sequential order. 294a virtual machine, and then the statements are executed in sequential order.
283All modifications a chunk effects on the global environment persist 295All modifications a chunk effects on the global environment persist
284after the chunk ends. 296after the chunk ends.
285 297
@@ -305,7 +317,8 @@ There are six \Index{basic types} in Lua: \Def{nil}, \Def{number},
305whose main property is to be different from any other value. 317whose main property is to be different from any other value.
306\emph{Number} represents real (double-precision floating-point) numbers, 318\emph{Number} represents real (double-precision floating-point) numbers,
307while \emph{string} has the usual meaning. 319while \emph{string} has the usual meaning.
308Lua is \Index{eight-bit clean}, 320\index{eight-bit clean}
321Lua is 8-bit clean,
309and so strings may contain any 8-bit character, 322and so strings may contain any 8-bit character,
310\emph{including} embedded zeros (\verb|'\0'|) \see{lexical}. 323\emph{including} embedded zeros (\verb|'\0'|) \see{lexical}.
311The \verb|type| function returns a string describing the type 324The \verb|type| function returns a string describing the type
@@ -325,8 +338,9 @@ of a given value \see{pdf-tag}.
325 338
326The type \emph{userdata} is provided to allow 339The type \emph{userdata} is provided to allow
327arbitrary \Index{C pointers} to be stored in Lua variables. 340arbitrary \Index{C pointers} to be stored in Lua variables.
328It corresponds to a \verb|void*| and has no pre-defined operations in Lua, 341This type corresponds to a \verb|void*|
329besides assignment and equality test. 342and has no pre-defined operations in Lua,
343except for assignment and equality test.
330However, by using \emph{tag methods}, 344However, by using \emph{tag methods},
331the programmer can define operations for \emph{userdata} values 345the programmer can define operations for \emph{userdata} values
332\see{tag-method}. 346\see{tag-method}.
@@ -345,31 +359,32 @@ Because functions are first class values,
345table fields may contain functions. 359table fields may contain functions.
346The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, 360The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
347which calls the method \verb|f| from the table \verb|t| passing 361which calls the method \verb|f| from the table \verb|t| passing
348itself as the first parameter \see{func-def}. 362the table itself as the first parameter \see{func-def}.
349 363
350Note that tables are \emph{objects}, and not values. 364Note that tables are \emph{objects}, and not values.
351Variables cannot contain tables, only \emph{references} to them. 365Variables do not contain tables, only \emph{references} to them.
352Assignment, parameter passing, and returns always manipulate references 366Assignment, parameter passing, and returns always manipulate references
353to tables, and do not imply any kind of copy. 367to tables, and do not imply any kind of copy.
354Moreover, tables must be explicitly created before used 368Moreover, tables must be explicitly created before used
355\see{tableconstructor}. 369\see{tableconstructor}.
356 370
357Tags are mainly used to select \emph{tag methods} when
358some events occur.
359Tag methods are the main mechanism for extending the
360semantics of Lua \see{tag-method}.
361Each of the types \M{nil}, \M{number}, and \M{string} has a different tag. 371Each of the types \M{nil}, \M{number}, and \M{string} has a different tag.
362All values of each of these types have the same pre-defined tag. 372All values of each of these types have the same pre-defined tag.
363Values of type \M{function} can have two different tags, 373Values of type \M{function} can have two different tags,
364depending on whether they are Lua functions or C~functions. 374depending on whether they are Lua functions or C~functions.
365Finally, 375Finally,
366values of type \M{userdata} and \M{table} have 376values of type \M{userdata} and \M{table} can have variable tags,
367variable tags, assigned by the program \see{tag-method}. 377assigned by the programmer \see{tag-method}.
368Tags are created with the function \verb|newtag|, 378The function \verb|tag| returns the tag of a given value.
369and the function \verb|tag| returns the tag of a given value. 379User tags are created with the function \verb|newtag|,
370To change the tag of a given table, 380The function \verb|settag| \see{pdf-newtag}
371there is the function \verb|settag| \see{pdf-newtag}. 381is used to change the tag of a table.
382The data of userdata can only be set from~C.
372 383
384Tags are mainly used to select \emph{tag methods} when
385some events occur.
386Tag methods are the main mechanism for extending the
387semantics of Lua \see{tag-method}.
373 388
374\section{The Language} 389\section{The Language}
375 390
@@ -389,12 +404,12 @@ can be used in an identifier.
389The following words are \emph{reserved}, and cannot be used as identifiers: 404The following words are \emph{reserved}, and cannot be used as identifiers:
390\index{reserved words} 405\index{reserved words}
391\begin{verbatim} 406\begin{verbatim}
392 and break do else 407 and break do else elseif
393 elseif end for function 408 end for function if in
394 if local nil not 409 local nil not or repeat
395 or repeat return then 410 return then until while
396 until while
397\end{verbatim} 411\end{verbatim}
412
398Lua is a case-sensitive language: 413Lua is a case-sensitive language:
399\T{and} is a reserved word, but \T{And} and \T{\'and} 414\T{and} is a reserved word, but \T{And} and \T{\'and}
400(if the locale permits) are two different, valid identifiers. 415(if the locale permits) are two different, valid identifiers.
@@ -404,34 +419,34 @@ are reserved for internal variables.
404 419
405The following strings denote other \Index{tokens}: 420The following strings denote other \Index{tokens}:
406\begin{verbatim} 421\begin{verbatim}
407 ~= <= >= < > == = + - * / % 422 ~= <= >= < > == = + - * / %
408 ( ) { } [ ] ; , . .. ... 423 ( ) { } [ ] ; , . .. ...
409\end{verbatim} 424\end{verbatim}
410 425
411\IndexEmph{Literal strings} 426\IndexEmph{Literal strings}
412can be delimited by matching single or double quotes, 427can be delimited by matching single or double quotes,
413and can contain the C-like escape sequences 428and can contain the C-like escape sequences
414\verb|'\a'| (bell), 429`\verb|\a|' (bell),
415\verb|'\b'| (backspace), 430`\verb|\b|' (backspace),
416\verb|'\f'| (form feed), 431`\verb|\f|' (form feed),
417\verb|'\n'| (newline), 432`\verb|\n|' (newline),
418\verb|'\r'| (carriage return), 433`\verb|\r|' (carriage return),
419\verb|'\t'| (horizontal tab), 434`\verb|\t|' (horizontal tab),
420\verb|'\v'| (vertical tab), 435`\verb|\v|' (vertical tab),
421\verb|'\\'|, (backslash), 436`\verb|\\|' (backslash),
422\verb|'\"'|, (double quote), 437`\verb|\"|' (double quote),
423\verb|'\''| (single quote), 438`\verb|\'|' (single quote),
424and \verb|'\|\emph{newline}\verb|'| (that is, a backslash followed by a real newline, 439and `\verb|\|\emph{newline}' (that is, a backslash followed by a real newline,
425which results in a newline in the string). 440which results in a newline in the string).
426A character in a string may also be specified by its numerical value, 441A character in a string may also be specified by its numerical value,
427through the escape sequence \verb|'\ddd'|, 442through the escape sequence `\verb|\|\emph{ddd}',
428where \verb|ddd| is a sequence of up to three \emph{decimal} digits. 443where \emph{ddd} is a sequence of up to three \emph{decimal} digits.
429Strings in Lua may contain any 8-bit value, including embedded zeros, 444Strings in Lua may contain any 8-bit value, including embedded zeros,
430which can be specified as \verb|'\000'|. 445which can be specified as `\verb|\000|'.
431 446
432Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|. 447Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|.
433Literals in this bracketed form may run for several lines, 448Literals in this bracketed form may run for several lines,
434may contain nested \verb|[[ ... ]]| pairs, 449may contain nested \verb|[[| \dots\ \verb|]]| pairs,
435and do not interpret escape sequences. 450and do not interpret escape sequences.
436This form is specially convenient for 451This form is specially convenient for
437writing strings that contain program pieces or 452writing strings that contain program pieces or
@@ -439,25 +454,24 @@ other quoted strings.
439As an example, in a system using ASCII, 454As an example, in a system using ASCII,
440the following three literals are equivalent: 455the following three literals are equivalent:
441\begin{verbatim} 456\begin{verbatim}
4421) "alo\n123\"" 457 1) "alo\n123\""
4432) '\97lo\10\04923"' 458 2) '\97lo\10\04923"'
4443) [[alo 459 3) [[alo
445 123"]] 460 123"]]
446\end{verbatim} 461\end{verbatim}
447 462
448 463\IndexEmph{Comments} start anywhere outside a string with a
449\Index{Comments} start anywhere outside a string with a
450double hyphen (\verb|--|) and run until the end of the line. 464double hyphen (\verb|--|) and run until the end of the line.
451Moreover, 465Moreover,
452the first line of a chunk is skipped if it starts with \verb|#|. 466the first line of a chunk is skipped if it starts with \verb|#|.
453This facility allows the use of Lua as a script interpreter 467This facility allows the use of Lua as a script interpreter
454in Unix systems \see{lua-sa}. 468in Unix systems \see{lua-sa}.
455 469
456\Index{Numerical constants} may be written with an optional decimal part, 470\IndexEmph{Numerical constants} may be written with an optional decimal part
457and an optional decimal exponent. 471and an optional decimal exponent.
458Examples of valid numerical constants are 472Examples of valid numerical constants are
459\begin{verbatim} 473\begin{verbatim}
460 3 3.0 3.1416 314.16e-2 0.31416E1 474 3 3.0 3.1416 314.16e-2 0.31416E1
461\end{verbatim} 475\end{verbatim}
462 476
463\subsection{\Index{Coercion}} \label{coercion} 477\subsection{\Index{Coercion}} \label{coercion}
@@ -490,7 +504,7 @@ then the excess values are thrown away.
490If there are less values than are needed, 504If there are less values than are needed,
491then the list is extended with as many \nil's as needed. 505then the list is extended with as many \nil's as needed.
492This adjustment occurs in multiple assignments \see{assignment} 506This adjustment occurs in multiple assignments \see{assignment}
493and function calls \see{functioncall}. 507and in function calls \see{functioncall}.
494 508
495 509
496\subsection{Statements}\label{stats} 510\subsection{Statements}\label{stats}
@@ -505,7 +519,7 @@ and local variable declarations \see{localvar}.
505 519
506\subsubsection{Blocks} 520\subsubsection{Blocks}
507A \Index{block} is a list of statements; 521A \Index{block} is a list of statements;
508syntatically, this is equal to a chunk: 522syntactically, a block is equal to a chunk:
509\begin{Produc} 523\begin{Produc}
510\produc{block}{chunk} 524\produc{block}{chunk}
511\end{Produc}% 525\end{Produc}%
@@ -518,15 +532,15 @@ This is useful to control the scope of local variables \see{localvar},
518and to add a \rwd{return} or \rwd{break} statement in the middle 532and to add a \rwd{return} or \rwd{break} statement in the middle
519of another block; for instance, 533of another block; for instance,
520\begin{verbatim} 534\begin{verbatim}
521 do return end -- return is the last statement in this block 535 do return end -- return is the last statement in this block
522\end{verbatim} 536\end{verbatim}
523 537
524\subsubsection{\Index{Assignment}} \label{assignment} 538\subsubsection{\Index{Assignment}} \label{assignment}
525The language allows \Index{multiple assignment}. 539Lua allows \Index{multiple assignment}.
526Therefore, the syntax for assignment 540Therefore, the syntax for assignment
527defines a list of variables on the left side 541defines a list of variables on the left side
528and a list of expressions on the right side. 542and a list of expressions on the right side.
529Both lists have their elements separated by commas: 543The elements in both lists are separated by commas:
530\begin{Produc} 544\begin{Produc}
531\produc{stat}{varlist1 \ter{=} explist1} 545\produc{stat}{varlist1 \ter{=} explist1}
532\produc{varlist1}{var \rep{\ter{,} var}} 546\produc{varlist1}{var \rep{\ter{,} var}}
@@ -536,14 +550,16 @@ and eventual indices on the left side,
536and then makes the assignments. 550and then makes the assignments.
537So 551So
538\begin{verbatim} 552\begin{verbatim}
539 i = 3 553 i = 3
540 i, a[i] = 4, 20 554 i, a[i] = 4, 20
541\end{verbatim} 555\end{verbatim}
542sets \verb|a[3]| to 20, but does not affect \verb|a[4]|. 556sets \verb|a[3]| to 20, but does not affect \verb|a[4]|
557because the \verb|i| in \verb|a[i]| is evaluated
558before it is assigned \verb|4|.
543 559
544Multiple assignment can be used to exchange two values, as in 560Multiple assignment can be used to exchange two values, as in
545\begin{verbatim} 561\begin{verbatim}
546 x, y = y, x 562 x, y = y, x
547\end{verbatim} 563\end{verbatim}
548 564
549The two lists in a multiple assignment may have different lengths. 565The two lists in a multiple assignment may have different lengths.
@@ -578,11 +594,11 @@ is equivalent to a call \verb|setglobal("x", val)|;
578an assignment \verb|t[i] = val| is equivalent to 594an assignment \verb|t[i] = val| is equivalent to
579\verb|settable_event(t,i,val)|. 595\verb|settable_event(t,i,val)|.
580See \See{tag-method} for a complete description of these functions. 596See \See{tag-method} for a complete description of these functions.
581(The function \verb|setglobal| is pre-defined in Lua. 597(The function \verb|setglobal| is defined in the basic library.
582The function \T{settable\_event} is used only for explanatory purposes.) 598The function \T{settable\_event} is used only for explanatory purposes.)
583 599
584\subsubsection{Control Structures} 600\subsubsection{Control Structures}
585The control structures 601The control structures
586\index{while-do}\index{repeat-until}\index{if-then-else}% 602\index{while-do}\index{repeat-until}\index{if-then-else}%
587\T{if}, \T{while}, and \T{repeat} have the usual meaning and 603\T{if}, \T{while}, and \T{repeat} have the usual meaning and
588familiar syntax: 604familiar syntax:
@@ -632,20 +648,20 @@ The numerical \rwd{for} loop has the following syntax:
632\end{Produc}% 648\end{Produc}%
633A \rwd{for} statement like 649A \rwd{for} statement like
634\begin{verbatim} 650\begin{verbatim}
635 for var=e1,e2,e3 do block end 651 for var = e1 ,e2, e3 do block end
636\end{verbatim} 652\end{verbatim}
637is equivalent to the following code: 653is equivalent to the code:
638\begin{verbatim} 654\begin{verbatim}
639 do 655 do
640 local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) 656 local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
641 if not (var and _limit and _step) then error() end 657 if not (var and _limit and _step) then error() end
642 while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do 658 while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
643 block 659 block
644 var = var+_step 660 var = var+_step
645 end 661 end
646 end 662 end
647\end{verbatim} 663\end{verbatim}
648Notice the following: 664Note the following:
649\begin{itemize}\itemsep=0pt 665\begin{itemize}\itemsep=0pt
650\item \verb|_limit| and \verb|_step| are invisible variables. 666\item \verb|_limit| and \verb|_step| are invisible variables.
651The names are here for explanatory purposes only. 667The names are here for explanatory purposes only.
@@ -662,7 +678,7 @@ assign it to another variable before breaking.
662\end{itemize} 678\end{itemize}
663 679
664The table \rwd{for} statement traverses all pairs 680The table \rwd{for} statement traverses all pairs
665index--value of a given table. 681(index,value) of a given table.
666It has the following syntax: 682It has the following syntax:
667\begin{Produc} 683\begin{Produc}
668\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp1 684\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp1
@@ -670,34 +686,33 @@ It has the following syntax:
670\end{Produc}% 686\end{Produc}%
671A \rwd{for} statement like 687A \rwd{for} statement like
672\begin{verbatim} 688\begin{verbatim}
673 for index, value in exp do block end 689 for index, value in exp do block end
674\end{verbatim} 690\end{verbatim}
675is equivalent to the following code: 691is equivalent to the code:
676\begin{verbatim} 692\begin{verbatim}
677 do 693 do
678 local _t = exp 694 local _t = exp
679 local index, value = next(t, nil) 695 local index, value = next(t, nil)
680 while index do 696 while index do
681 block 697 block
682 index, value = next(t, index) 698 index, value = next(t, index)
683 end 699 end
684 end 700 end
685\end{verbatim} 701\end{verbatim}
686Notice the following: 702Note the following:
687\begin{itemize}\itemsep=0pt 703\begin{itemize}\itemsep=0pt
688\item \verb|_t| is an invisible variable. 704\item \verb|_t| is an invisible variable.
689The name is here for explanatory purposes only. 705The name is here for explanatory purposes only.
690\item The behavior is undefined if you assign to \verb|index| inside 706\item The behavior is \emph{undefined} if you assign to \verb|index| inside
691the block. 707the block.
692\item The behavior is undefined if you create 708\item The behavior is \emph{undefined} if you change
693new indices in table \verb|_t| during the traversal. 709the table \verb|_t| during the traversal.
694However, it is safe to change the values associated with present indices.
695\item The variables \verb|index| and \verb|value| are local to the statement; 710\item The variables \verb|index| and \verb|value| are local to the statement;
696you cannot use their values after the \rwd{for} ends. 711you cannot use their values after the \rwd{for} ends.
697\item You can use \rwd{break} to exit a \rwd{for}. 712\item You can use \rwd{break} to exit a \rwd{for}.
698If you need the value of \verb|index| or \verb|value|, 713If you need the value of \verb|index| or \verb|value|,
699assign them to other variables before breaking. 714assign them to other variables before breaking.
700\item The order that table elements are traversed is completely undefined, 715\item The order that table elements are traversed is undefined,
701\emph{even for numerical indices}. 716\emph{even for numerical indices}.
702If you want to traverse indices in numerical order, 717If you want to traverse indices in numerical order,
703use a numerical \rwd{for}. 718use a numerical \rwd{for}.
@@ -725,6 +740,9 @@ If present, an initial assignment has the same semantics
725of a multiple assignment. 740of a multiple assignment.
726Otherwise, all variables are initialized with \nil. 741Otherwise, all variables are initialized with \nil.
727 742
743A chunk is also a block,
744so local variables can be declared outside any explicit block.
745
728The scope of local variables begins \emph{after} 746The scope of local variables begins \emph{after}
729the declaration and lasts until the end of the block. 747the declaration and lasts until the end of the block.
730Thus, the code 748Thus, the code
@@ -762,7 +780,7 @@ call \verb|getglobal("x")|;
762an access to an indexed variable \verb|t[i]| is equivalent to 780an access to an indexed variable \verb|t[i]| is equivalent to
763a call \verb|gettable_event(t,i)|. 781a call \verb|gettable_event(t,i)|.
764See \See{tag-method} for a description of these functions. 782See \See{tag-method} for a description of these functions.
765(Function \verb|getglobal| is pre-defined in Lua. 783(Function \verb|getglobal| is defined in the basic library.
766Function \T{gettable\_event} is used only for explanatory purposes.) 784Function \T{gettable\_event} is used only for explanatory purposes.)
767 785
768The non-terminal \M{exp1} is used to indicate that the values 786The non-terminal \M{exp1} is used to indicate that the values
@@ -775,7 +793,7 @@ returned by an expression must be adjusted to one single value:
775Lua supports the usual \Index{arithmetic operators}: 793Lua supports the usual \Index{arithmetic operators}:
776the binary \verb|+| (addition), 794the binary \verb|+| (addition),
777\verb|-| (subtraction), \verb|*| (multiplication), 795\verb|-| (subtraction), \verb|*| (multiplication),
778\verb|/| (division) and \verb|^| (exponentiation), 796\verb|/| (division), and \verb|^| (exponentiation);
779and unary \verb|-| (negation). 797and unary \verb|-| (negation).
780If the operands are numbers, or strings that can be converted to 798If the operands are numbers, or strings that can be converted to
781numbers (according to the rules given in \See{coercion}), 799numbers (according to the rules given in \See{coercion}),
@@ -787,13 +805,13 @@ giving the expected meaning to \Index{exponentiation}
787\see{mathlib}. 805\see{mathlib}.
788 806
789\subsubsection{Relational Operators} 807\subsubsection{Relational Operators}
790Lua provides the following \Index{relational operators}: 808The \Index{relational operators} in Lua are
791\begin{verbatim} 809\begin{verbatim}
792 == ~= < > <= >= 810 == ~= < > <= >=
793\end{verbatim} 811\end{verbatim}
794All these return \nil\ as false and a value different from \nil\ as true. 812These operators return \nil\ as false and a value different from \nil\ as true.
795 813
796Equality first compares the tags of its operands. 814Equality (\verb|==|) first compares the tags of its operands.
797If they are different, then the result is \nil. 815If they are different, then the result is \nil.
798Otherwise, their values are compared. 816Otherwise, their values are compared.
799Numbers and strings are compared in the usual way. 817Numbers and strings are compared in the usual way.
@@ -807,6 +825,7 @@ The conversion rules of \See{coercion}
807Thus, \verb|"0"==0| evaluates to \emph{false}, 825Thus, \verb|"0"==0| evaluates to \emph{false},
808and \verb|t[0]| and \verb|t["0"]| denote different 826and \verb|t[0]| and \verb|t["0"]| denote different
809entries in a table. 827entries in a table.
828\medskip
810 829
811The order operators work as follows. 830The order operators work as follows.
812If both arguments are numbers, then they are compared as such. 831If both arguments are numbers, then they are compared as such.
@@ -815,13 +834,14 @@ then their values are compared using lexicographical order.
815Otherwise, the ``lt'' tag method is called \see{tag-method}. 834Otherwise, the ``lt'' tag method is called \see{tag-method}.
816 835
817\subsubsection{Logical Operators} 836\subsubsection{Logical Operators}
818The \Index{logical operators} are 837The \Index{logical operators} in Lua are
819\index{and}\index{or}\index{not} 838\index{and}\index{or}\index{not}
820\begin{verbatim} 839\begin{verbatim}
821 and or not 840 and or not
822\end{verbatim} 841\end{verbatim}
823Like control structures, all logical operators 842Like the control structures, all logical operators
824consider \nil\ as false and anything else as true. 843consider \nil\ as false and anything else as true.
844
825The conjunction operator \verb|and| returns \nil\ if its first argument is \nil; 845The conjunction operator \verb|and| returns \nil\ if its first argument is \nil;
826otherwise, it returns its second argument. 846otherwise, it returns its second argument.
827The disjunction operator \verb|or| returns its first argument 847The disjunction operator \verb|or| returns its first argument
@@ -831,40 +851,46 @@ Both \verb|and| and \verb|or| use \Index{short-cut evaluation},
831that is, 851that is,
832the second operand is evaluated only when necessary. 852the second operand is evaluated only when necessary.
833 853
834There are two useful Lua idioms with logical operators. 854There are two useful Lua idioms that use logical operators.
835The first idiom is \verb|x = x or v|, 855The first idiom is
856\begin{verbatim}
857 x = x or v
858\end{verbatim}
836which is equivalent to 859which is equivalent to
837\begin{verbatim} 860\begin{verbatim}
838 if x == nil then x = v end 861 if x == nil then x = v end
839\end{verbatim} 862\end{verbatim}
840i.e., it sets \verb|x| to a default value \verb|v| when 863This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set.
841\verb|x| is not set. 864
842The other idiom is \verb|x = a and b or c|, 865The second idiom is
843which should be read as \verb|x = a and (b or c)|, 866\begin{verbatim}
844is equivalent to 867 x = a and b or c
868\end{verbatim}
869which should be read as \verb|x = a and (b or c)|.
870This idiom is equivalent to
845\begin{verbatim} 871\begin{verbatim}
846 if a then x = b else x = c end 872 if a then x = b else x = c end
847\end{verbatim} 873\end{verbatim}
848provided that \verb|b| is not \nil. 874provided that \verb|b| is not \nil.
849 875
850\subsubsection{Concatenation} 876\subsubsection{Concatenation} \label{concat}
851The string \Index{concatenation} operator in Lua is 877The string \Index{concatenation} operator in Lua is
852denoted by ``\IndexVerb{..}''. 878denoted by two dots (`\IndexVerb{..}').
853If both operands are strings or numbers, they are converted to 879If both operands are strings or numbers, then they are converted to
854strings according to the rules in \See{coercion}. 880strings according to the rules in \See{coercion}.
855Otherwise, the ``concat'' tag method is called \see{tag-method}. 881Otherwise, the ``concat'' tag method is called \see{tag-method}.
856 882
857\subsubsection{Precedence} 883\subsubsection{Precedence}
858\Index{Operator precedence} follows the table below, 884\Index{Operator precedence} in Lua follows the table below,
859from the lower to the higher priority: 885from the lower to the higher priority:
860\begin{verbatim} 886\begin{verbatim}
861 and or 887 and or
862 < > <= >= ~= == 888 < > <= >= ~= ==
863 .. 889 ..
864 + - 890 + -
865 * / 891 * /
866 not - (unary) 892 not - (unary)
867 ^ 893 ^
868\end{verbatim} 894\end{verbatim}
869All binary operators are left associative, 895All binary operators are left associative,
870except for \verb|^| (exponentiation), 896except for \verb|^| (exponentiation),
@@ -899,17 +925,17 @@ The expressions in the list are assigned to consecutive numerical indices,
899starting with 1. 925starting with 1.
900For example, 926For example,
901\begin{verbatim} 927\begin{verbatim}
902 a = {"v1", "v2", 34} 928 a = {"v1", "v2", 34}
903\end{verbatim} 929\end{verbatim}
904is equivalent to 930is equivalent to
905\begin{verbatim} 931\begin{verbatim}
906 do 932 do
907 local temp = {} 933 local temp = {}
908 temp[1] = "v1" 934 temp[1] = "v1"
909 temp[2] = "v2" 935 temp[2] = "v2"
910 temp[3] = 34 936 temp[3] = 34
911 a = temp 937 a = temp
912 end 938 end
913\end{verbatim} 939\end{verbatim}
914 940
915The form \emph{ffieldlist1} initializes other fields in a table: 941The form \emph{ffieldlist1} initializes other fields in a table:
@@ -919,18 +945,18 @@ The form \emph{ffieldlist1} initializes other fields in a table:
919\end{Produc}% 945\end{Produc}%
920For example, 946For example,
921\begin{verbatim} 947\begin{verbatim}
922 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c} 948 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
923\end{verbatim} 949\end{verbatim}
924is equivalent to 950is equivalent to
925\begin{verbatim} 951\begin{verbatim}
926 do 952 do
927 local temp = {} 953 local temp = {}
928 temp[f(k)] = g(y) 954 temp[f(k)] = g(y)
929 temp.x = 1 -- or temp["x"] = 1 955 temp.x = 1 -- or temp["x"] = 1
930 temp.y = 3 -- or temp["y"] = 3 956 temp.y = 3 -- or temp["y"] = 3
931 temp[0] = b+c 957 temp[0] = b+c
932 a = temp 958 a = temp
933 end 959 end
934\end{verbatim} 960\end{verbatim}
935An expression like \verb|{x = 1, y = 4}| is 961An expression like \verb|{x = 1, y = 4}| is
936in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. 962in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
@@ -940,14 +966,14 @@ and can be used in the same constructor separated by
940a semi-colon. 966a semi-colon.
941For example, all forms below are correct. 967For example, all forms below are correct.
942\begin{verbatim} 968\begin{verbatim}
943 x = {;} 969 x = {;}
944 x = {"a", "b",} 970 x = {"a", "b",}
945 x = {type="list"; "a", "b"} 971 x = {type="list"; "a", "b"}
946 x = {f(0), f(1), f(2),; n=3,} 972 x = {f(0), f(1), f(2),; n=3,}
947\end{verbatim} 973\end{verbatim}
948 974
949\subsubsection{Function Calls} \label{functioncall} 975\subsubsection{Function Calls} \label{functioncall}
950A \Index{function call} has the following syntax: 976A \Index{function call} in Lua has the following syntax:
951\begin{Produc} 977\begin{Produc}
952\produc{functioncall}{varorfunc args} 978\produc{functioncall}{varorfunc args}
953\end{Produc}% 979\end{Produc}%
@@ -964,12 +990,9 @@ The form
964\produc{functioncall}{varorfunc \ter{:} name args} 990\produc{functioncall}{varorfunc \ter{:} name args}
965\end{Produc}% 991\end{Produc}%
966can be used to call ``methods''. 992can be used to call ``methods''.
967A call \verb|varorfunc:name(...)| 993A call \verb|v:name(...)|
968is syntactic sugar for 994is syntactic sugar for \verb|v.name(v, ...)|,
969\begin{verbatim} 995except that \verb|v| is evaluated only once.
970 varorfunc.name(varorfunc, ...)
971\end{verbatim}
972except that \verb|varorfunc| is evaluated only once.
973 996
974Arguments have the following syntax: 997Arguments have the following syntax:
975\begin{Produc} 998\begin{Produc}
@@ -1003,16 +1026,16 @@ then no adjustment is made.
1003The only places that can hold many values 1026The only places that can hold many values
1004is the last (or the only) expression in an assignment, 1027is the last (or the only) expression in an assignment,
1005in an argument list, or in a return statement. 1028in an argument list, or in a return statement.
1006Here are some examples. 1029Here are some examples:
1007\begin{verbatim} 1030\begin{verbatim}
1008 f(); -- adjusted to 0 results 1031 f(); -- adjusted to 0 results
1009 g(f(), x); -- f() is adjusted to 1 result 1032 g(f(), x); -- f() is adjusted to 1 result
1010 g(x, f()); -- g gets x plus all values returned by f() 1033 g(x, f()); -- g gets x plus all values returned by f()
1011 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) 1034 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
1012 a,b,c = x, f(); -- f() is adjusted to 2 1035 a,b,c = x, f(); -- f() is adjusted to 2
1013 a,b,c = f(); -- f() is adjusted to 3 1036 a,b,c = f(); -- f() is adjusted to 3
1014 return f(); -- returns all values returned by f() 1037 return f(); -- returns all values returned by f()
1015 return x,y,f(); -- returns a, b, and all values returned by f() 1038 return x,y,f(); -- returns a, b, and all values returned by f()
1016\end{verbatim} 1039\end{verbatim}
1017 1040
1018\subsubsection{\Index{Function Definitions}} \label{func-def} 1041\subsubsection{\Index{Function Definitions}} \label{func-def}
@@ -1027,33 +1050,25 @@ The syntax for function definition is
1027\end{Produc}% 1050\end{Produc}%
1028The statement 1051The statement
1029\begin{verbatim} 1052\begin{verbatim}
1030 function f () 1053 function f () ... end
1031 ...
1032 end
1033\end{verbatim} 1054\end{verbatim}
1034is just syntactic sugar for 1055is just syntactic sugar for
1035\begin{verbatim} 1056\begin{verbatim}
1036 f = function () 1057 f = function () ... end
1037 ...
1038 end
1039\end{verbatim} 1058\end{verbatim}
1040and the statement 1059and the statement
1041\begin{verbatim} 1060\begin{verbatim}
1042 function o.f () 1061 function v.f () ... end
1043 ...
1044 end
1045\end{verbatim} 1062\end{verbatim}
1046is syntactic sugar for 1063is syntactic sugar for
1047\begin{verbatim} 1064\begin{verbatim}
1048 o.f = function () 1065 v.f = function () ... end
1049 ...
1050 end
1051\end{verbatim} 1066\end{verbatim}
1052 1067
1053A function definition is an executable expression, 1068A function definition is an executable expression,
1054whose value has type \emph{function}. 1069whose value has type \emph{function}.
1055When Lua pre-compiles a chunk, 1070When Lua pre-compiles a chunk,
1056all its function bodies are pre-compiled, too. 1071all its function bodies are pre-compiled too.
1057Then, whenever Lua executes the function definition, 1072Then, whenever Lua executes the function definition,
1058its upvalues are fixed \see{upvalue}, 1073its upvalues are fixed \see{upvalue},
1059and the function is \emph{instantiated} (or \emph{closed}). 1074and the function is \emph{instantiated} (or \emph{closed}).
@@ -1074,7 +1089,7 @@ the list of \Index{arguments} is adjusted to
1074the length of the list of parameters \see{adjust}, 1089the length of the list of parameters \see{adjust},
1075unless the function is a \Def{vararg} function, 1090unless the function is a \Def{vararg} function,
1076which is 1091which is
1077indicated by the dots (\ldots) at the end of its parameter list. 1092indicated by three dots (`\verb|...|') at the end of its parameter list.
1078A vararg function does not adjust its argument list; 1093A vararg function does not adjust its argument list;
1079instead, it collects all extra arguments into an implicit parameter, 1094instead, it collects all extra arguments into an implicit parameter,
1080called \IndexVerb{arg}. 1095called \IndexVerb{arg}.
@@ -1084,24 +1099,24 @@ and the extra arguments at positions 1,~2,~\ldots,\M{n}.
1084 1099
1085As an example, consider the following definitions: 1100As an example, consider the following definitions:
1086\begin{verbatim} 1101\begin{verbatim}
1087 function f(a, b) end 1102 function f(a, b) end
1088 function g(a, b, ...) end 1103 function g(a, b, ...) end
1089 function r() return 1,2,3 end 1104 function r() return 1,2,3 end
1090\end{verbatim} 1105\end{verbatim}
1091Then, we have the following mapping from arguments to parameters: 1106Then, we have the following mapping from arguments to parameters:
1092\begin{verbatim} 1107\begin{verbatim}
1093 CALL PARAMETERS 1108 CALL PARAMETERS
1094 1109
1095 f(3) a=3, b=nil 1110 f(3) a=3, b=nil
1096 f(3, 4) a=3, b=4 1111 f(3, 4) a=3, b=4
1097 f(3, 4, 5) a=3, b=4 1112 f(3, 4, 5) a=3, b=4
1098 f(r(), 10) a=1, b=10 1113 f(r(), 10) a=1, b=10
1099 f(r()) a=1, b=2 1114 f(r()) a=1, b=2
1100 1115
1101 g(3) a=3, b=nil, arg={n=0} 1116 g(3) a=3, b=nil, arg={n=0}
1102 g(3, 4) a=3, b=4, arg={n=0} 1117 g(3, 4) a=3, b=4, arg={n=0}
1103 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} 1118 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
1104 g(5, r()) a=5, b=1, arg={2, 3; n=2} 1119 g(5, r()) a=5, b=1, arg={2, 3; n=2}
1105\end{verbatim} 1120\end{verbatim}
1106 1121
1107Results are returned using the \rwd{return} statement \see{return}. 1122Results are returned using the \rwd{return} statement \see{return}.
@@ -1113,22 +1128,18 @@ The syntax
1113\begin{Produc} 1128\begin{Produc}
1114\produc{funcname}{name \ter{:} name} 1129\produc{funcname}{name \ter{:} name}
1115\end{Produc}% 1130\end{Produc}%
1116is used for defining \Index{methods}, 1131is used for defining \IndexEmph{methods},
1117that is, functions that have an implicit extra parameter \IndexVerb{self}: 1132that is, functions that have an implicit extra parameter \IndexVerb{self}:
1118Thus, the statement 1133Thus, the statement
1119\begin{verbatim} 1134\begin{verbatim}
1120 function v:f (...) 1135 function v:f (...) ... end
1121 ...
1122 end
1123\end{verbatim} 1136\end{verbatim}
1124is equivalent to 1137is equivalent to
1125\begin{verbatim} 1138\begin{verbatim}
1126 v.f = function (self, ...) 1139 v.f = function (self, ...) ... end
1127 ...
1128 end
1129\end{verbatim} 1140\end{verbatim}
1130that is, the function gets an extra formal parameter called \verb|self|. 1141Note that the function gets an extra formal parameter called \verb|self|.
1131Note that the variable \verb|v| must have been 1142Note also that \verb|v| must have been
1132previously initialized with a table value. 1143previously initialized with a table value.
1133 1144
1134 1145
@@ -1153,32 +1164,34 @@ but whose value is \emph{frozen} when the function wherein it
1153appears is instantiated. 1164appears is instantiated.
1154The name used in an upvalue may be the name of any variable visible 1165The name used in an upvalue may be the name of any variable visible
1155at the point where the function is defined, 1166at the point where the function is defined,
1156that is 1167that is,
1157global variables and local variables from the immediately enclosing function. 1168global variables and local variables from the immediately enclosing function.
1158Notice that when the upvalue is a table, 1169Note that when the upvalue is a table,
1159only the reference to that table 1170only the \emph{reference} to that table
1160(which is the value of the upvalue) is frozen; 1171(which is the value of the upvalue) is frozen;
1161the table contents can be changed at will. 1172the table contents can be changed at will.
1173Using table values as upvalues is a technique for having
1174writable but private state attached to functions.
1162 1175
1163Here are some examples: 1176Here are some examples:
1164\begin{verbatim} 1177\begin{verbatim}
1165 a,b,c = 1,2,3 -- global variables 1178 a,b,c = 1,2,3 -- global variables
1166 local d 1179 local d
1167 function f (x) 1180 function f (x)
1168 local b = {} -- x and b are local to f; b shadows the global b 1181 local b = {} -- x and b are local to f; b shadows the global b
1169 local g = function (a) 1182 local g = function (a)
1170 local y -- a and y are local to g 1183 local y -- a and y are local to g
1171 p = a -- OK, access local 'a' 1184 p = a -- OK, access local `a'
1172 p = c -- OK, access global 'c' 1185 p = c -- OK, access global `c'
1173 p = b -- ERROR: cannot access a variable in outer scope 1186 p = b -- ERROR: cannot access a variable in outer scope
1174 p = %b -- OK, access frozen value of 'b' (local to 'f') 1187 p = %b -- OK, access frozen value of `b' (local to `f')
1175 %b = 3 -- ERROR: cannot change an upvalue 1188 %b = 3 -- ERROR: cannot change an upvalue
1176 %b.x = 3 -- OK, change the table contents 1189 %b.x = 3 -- OK, change the table contents
1177 p = %c -- OK, access frozen value of global 'c' 1190 p = %c -- OK, access frozen value of global `c'
1178 p = %y -- ERROR: 'y' is not visible where 'g' is defined 1191 p = %y -- ERROR: `y' is not visible where `g' is defined
1179 p = %d -- ERROR: 'd' is not visible where 'g' is defined 1192 p = %d -- ERROR: `d' is not visible where `g' is defined
1180 end -- g 1193 end -- g
1181 end -- f 1194 end -- f
1182\end{verbatim} 1195\end{verbatim}
1183 1196
1184 1197
@@ -1195,27 +1208,28 @@ and then the corresponding function from the library
1195\verb|lua_dobuffer|, or \verb|lua_callfunction|) 1208\verb|lua_dobuffer|, or \verb|lua_callfunction|)
1196is terminated, returning an error condition. 1209is terminated, returning an error condition.
1197 1210
1198Memory allocation error is an exception to the previous rule. 1211Memory allocation errors are an exception to the previous rule.
1199When a \verb|malloc| fails, Lua may not be able to execute the 1212When memory allocation fails, Lua may not be able to execute the
1200\verb|_ERRORMESSAGE| function. 1213\verb|_ERRORMESSAGE| function.
1201So, for this kind of error, Lua does not call 1214So, for this kind of error, Lua does not call
1202the \verb|_ERRORMESSAGE| function; 1215the \verb|_ERRORMESSAGE| function;
1203instead, the corresponding function from the library 1216instead, the corresponding function from the library
1204returns immeditely with a special error code. 1217returns immediately with a special error code (\verb|LUA_ERRMEM|).
1218This and other error codes are defined in \verb|lua.h|.
1205 1219
1206The only argument to \verb|_ERRORMESSAGE| is a string 1220The only argument to \verb|_ERRORMESSAGE| is a string
1207describing the error. 1221describing the error.
1208The default definition for 1222The default definition for
1209this function calls \verb|_ALERT|, \Deffunc{_ALERT} 1223this function calls \verb|_ALERT|, \Deffunc{_ALERT}
1210which prints the message to \verb|stderr| \see{alert}. 1224which prints the message to \verb|stderr| \see{alert}.
1211The standard I/O library redefines \verb|_ERRORMESSAGE|, 1225The standard I/O library redefines \verb|_ERRORMESSAGE|
1212and uses the debug facilities \see{debugI} 1226and uses the debug facilities \see{debugI}
1213to print some extra information, 1227to print some extra information,
1214such as a call stack traceback. 1228such as a call stack traceback.
1215 1229
1216Lua code can explicitly generate an error by calling the built-in 1230Lua code can explicitly generate an error by calling the
1217function \verb|error| \see{pdf-error}. 1231function \verb|error| \see{pdf-error}.
1218Lua code can ``catch'' an error using the built-in function 1232Lua code can ``catch'' an error using the function
1219\verb|call| \see{pdf-call}. 1233\verb|call| \see{pdf-call}.
1220 1234
1221 1235
@@ -1238,7 +1252,7 @@ Its first parameter is the tag, the second parameter is the event name
1238and the third parameter is the new method (a function), 1252and the third parameter is the new method (a function),
1239or \nil\ to restore the default behavior for the pair. 1253or \nil\ to restore the default behavior for the pair.
1240The \verb|settagmethod| function returns the previous tag method for that pair. 1254The \verb|settagmethod| function returns the previous tag method for that pair.
1241Another function, \IndexVerb{gettagmethod}, 1255A companion function \IndexVerb{gettagmethod}
1242receives a tag and an event name and returns the 1256receives a tag and an event name and returns the
1243current method associated with the pair. 1257current method associated with the pair.
1244 1258
@@ -1260,41 +1274,38 @@ are described in \See{predefined}.
1260\item[``add'':]\index{add event} 1274\item[``add'':]\index{add event}
1261called when a \verb|+| operation is applied to non-numerical operands. 1275called when a \verb|+| operation is applied to non-numerical operands.
1262 1276
1263The function \verb|getbinmethod| defines how Lua chooses a tag method 1277The function \verb|getbinmethod| below defines how Lua chooses a tag method
1264for a binary operation. 1278for a binary operation.
1265First, Lua tries the first operand. 1279First, Lua tries the first operand.
1266If its tag does not define a tag method for the operation, 1280If its tag does not define a tag method for the operation,
1267then Lua tries the second operand. 1281then Lua tries the second operand.
1268If it also fails, then it gets a tag method from tag~0: 1282If it also fails, then it gets a tag method from tag~0.
1269\begin{verbatim} 1283\begin{verbatim}
1270 function getbinmethod (op1, op2, event) 1284 function getbinmethod (op1, op2, event)
1271 return gettagmethod(tag(op1), event) or 1285 return gettagmethod(tag(op1), event) or
1272 gettagmethod(tag(op2), event) or 1286 gettagmethod(tag(op2), event) or
1273 gettagmethod(0, event) 1287 gettagmethod(0, event)
1274 end 1288 end
1275\end{verbatim} 1289\end{verbatim}
1276Using this function, 1290Using this function,
1277the tag method for the ``add' event is 1291the tag method for the ``add'' event is
1278\begin{verbatim} 1292\begin{verbatim}
1279 function add_event (op1, op2) 1293 function add_event (op1, op2)
1280 local o1, o2 = tonumber(op1), tonumber(op2) 1294 local o1, o2 = tonumber(op1), tonumber(op2)
1281 if o1 and o2 then -- both operands are numeric 1295 if o1 and o2 then -- both operands are numeric
1282 return o1+o2 -- '+' here is the primitive 'add' 1296 return o1+o2 -- '+' here is the primitive 'add'
1283 else -- at least one of the operands is not numeric 1297 else -- at least one of the operands is not numeric
1284 local tm = getbinmethod(op1, op2, "add") 1298 local tm = getbinmethod(op1, op2, "add")
1285 if tm then 1299 if tm then
1286 -- call the method with both operands and an extra 1300 -- call the method with both operands and an extra
1287 -- argument with the event name 1301 -- argument with the event name
1288 return tm(op1, op2, "add") 1302 return tm(op1, op2, "add")
1289 else -- no tag method available: default behavior 1303 else -- no tag method available: default behavior
1290 error("unexpected type at arithmetic operation") 1304 error("unexpected type at arithmetic operation")
1291 end 1305 end
1292 end 1306 end
1293 end 1307 end
1294\end{verbatim} 1308\end{verbatim}
1295
1296All global variables are kept in a table.
1297You can get this table calling the \verb|globals| function.
1298 1309
1299\item[``sub'':]\index{sub event} 1310\item[``sub'':]\index{sub event}
1300called when a \verb|-| operation is applied to non-numerical operands. 1311called when a \verb|-| operation is applied to non-numerical operands.
@@ -1309,41 +1320,42 @@ called when a \verb|/| operation is applied to non-numerical operands.
1309Behavior similar to the ``add'' event. 1320Behavior similar to the ``add'' event.
1310 1321
1311\item[``pow'':]\index{pow event} 1322\item[``pow'':]\index{pow event}
1312called when a \verb|^| operation (exponentiation) is applied. 1323called when a \verb|^| operation (exponentiation) is applied,
1324even for numerical operands.
1313\begin{verbatim} 1325\begin{verbatim}
1314 function pow_event (op1, op2) 1326 function pow_event (op1, op2)
1315 local tm = getbinmethod(op1, op2, "pow") 1327 local tm = getbinmethod(op1, op2, "pow")
1316 if tm then 1328 if tm then
1317 -- call the method with both operands and an extra 1329 -- call the method with both operands and an extra
1318 -- argument with the event name 1330 -- argument with the event name
1319 return tm(op1, op2, "pow") 1331 return tm(op1, op2, "pow")
1320 else -- no tag method available: default behavior 1332 else -- no tag method available: default behavior
1321 error("unexpected type at arithmetic operation") 1333 error("unexpected type at arithmetic operation")
1322 end 1334 end
1323 end 1335 end
1324\end{verbatim} 1336\end{verbatim}
1325 1337
1326\item[``unm'':]\index{unm event} 1338\item[``unm'':]\index{unm event}
1327called when a unary \verb|-| operation is applied to a non-numerical operand. 1339called when a unary \verb|-| operation is applied to a non-numerical operand.
1328\begin{verbatim} 1340\begin{verbatim}
1329 function unm_event (op) 1341 function unm_event (op)
1330 local o = tonumber(op) 1342 local o = tonumber(op)
1331 if o then -- operand is numeric 1343 if o then -- operand is numeric
1332 return -o -- '-' here is the primitive 'unm' 1344 return -o -- '-' here is the primitive 'unm'
1333 else -- the operand is not numeric. 1345 else -- the operand is not numeric.
1334 -- Try to get a tag method from the operand; 1346 -- Try to get a tag method from the operand;
1335 -- if it does not have one, try a "global" one (tag 0) 1347 -- if it does not have one, try a "global" one (tag 0)
1336 local tm = gettagmethod(tag(op), "unm") or 1348 local tm = gettagmethod(tag(op), "unm") or
1337 gettagmethod(0, "unm") 1349 gettagmethod(0, "unm")
1338 if tm then 1350 if tm then
1339 -- call the method with the operand, nil, and an extra 1351 -- call the method with the operand, nil, and an extra
1340 -- argument with the event name 1352 -- argument with the event name
1341 return tm(op, nil, "unm") 1353 return tm(op, nil, "unm")
1342 else -- no tag method available: default behavior 1354 else -- no tag method available: default behavior
1343 error("unexpected type at arithmetic operation") 1355 error("unexpected type at arithmetic operation")
1344 end 1356 end
1345 end 1357 end
1346 end 1358 end
1347\end{verbatim} 1359\end{verbatim}
1348 1360
1349\item[``lt'':]\index{lt event} 1361\item[``lt'':]\index{lt event}
@@ -1351,51 +1363,51 @@ called when an order operation is applied to non-numerical
1351or non-string operands. 1363or non-string operands.
1352It corresponds to the \verb|<| operator. 1364It corresponds to the \verb|<| operator.
1353\begin{verbatim} 1365\begin{verbatim}
1354 function lt_event (op1, op2) 1366 function lt_event (op1, op2)
1355 if type(op1) == "number" and type(op2) == "number" then 1367 if type(op1) == "number" and type(op2) == "number" then
1356 return op1 < op2 -- numeric comparison 1368 return op1 < op2 -- numeric comparison
1357 elseif type(op1) == "string" and type(op2) == "string" then 1369 elseif type(op1) == "string" and type(op2) == "string" then
1358 return op1 < op2 -- lexicographic comparison 1370 return op1 < op2 -- lexicographic comparison
1359 else 1371 else
1360 local tm = getbinmethod(op1, op2, "lt") 1372 local tm = getbinmethod(op1, op2, "lt")
1361 if tm then 1373 if tm then
1362 return tm(op1, op2, "lt") 1374 return tm(op1, op2, "lt")
1363 else 1375 else
1364 error("unexpected type at comparison"); 1376 error("unexpected type at comparison");
1365 end 1377 end
1366 end 1378 end
1367 end 1379 end
1368\end{verbatim} 1380\end{verbatim}
1369The other order operators use this tag method according to the 1381The other order operators use this tag method according to the
1370usual equivalences: 1382usual equivalences:
1371\begin{verbatim} 1383\begin{verbatim}
1372 a>b <=> b<a 1384 a>b <=> b<a
1373 a<=b <=> not (b<a) 1385 a<=b <=> not (b<a)
1374 a>=b <=> not (a<b) 1386 a>=b <=> not (a<b)
1375\end{verbatim} 1387\end{verbatim}
1376 1388
1377\item[``concat'':]\index{concatenation event} 1389\item[``concat'':]\index{concatenation event}
1378called when a concatenation is applied to non-string operands. 1390called when a concatenation is applied to non-string operands.
1379\begin{verbatim} 1391\begin{verbatim}
1380 function concat_event (op1, op2) 1392 function concat_event (op1, op2)
1381 if (type(op1) == "string" or type(op1) == "number") and 1393 if (type(op1) == "string" or type(op1) == "number") and
1382 (type(op2) == "string" or type(op2) == "number") then 1394 (type(op2) == "string" or type(op2) == "number") then
1383 return op1..op2 -- primitive string concatenation 1395 return op1..op2 -- primitive string concatenation
1384 else 1396 else
1385 local tm = getbinmethod(op1, op2, "concat") 1397 local tm = getbinmethod(op1, op2, "concat")
1386 if tm then 1398 if tm then
1387 return tm(op1, op2, "concat") 1399 return tm(op1, op2, "concat")
1388 else 1400 else
1389 error("unexpected type for concatenation") 1401 error("unexpected type for concatenation")
1390 end 1402 end
1391 end 1403 end
1392 end 1404 end
1393\end{verbatim} 1405\end{verbatim}
1394 1406
1395\item[``index'':]\index{index event} 1407\item[``index'':]\index{index event}
1396called when Lua tries to retrieve the value of an index 1408called when Lua tries to retrieve the value of an index
1397not present in a table. 1409not present in a table.
1398See event ``gettable'' for its semantics. 1410See the ``gettable'' event for its semantics.
1399 1411
1400\item[``getglobal'':]\index{getglobal event} 1412\item[``getglobal'':]\index{getglobal event}
1401called whenever Lua needs the value of a global variable. 1413called whenever Lua needs the value of a global variable.
@@ -1404,112 +1416,113 @@ created by \verb|newtag|.
1404Note that 1416Note that
1405the tag is that of the \emph{current value} of the global variable. 1417the tag is that of the \emph{current value} of the global variable.
1406\begin{verbatim} 1418\begin{verbatim}
1407 function getglobal (varname) 1419 function getglobal (varname)
1408 -- access the table of globals 1420 -- access the table of globals
1409 local value = rawget(globals(), varname) 1421 local value = rawget(globals(), varname)
1410 local tm = gettagmethod(tag(value), "getglobal") 1422 local tm = gettagmethod(tag(value), "getglobal")
1411 if not tm then 1423 if not tm then
1412 return value 1424 return value
1413 else 1425 else
1414 return tm(varname, value) 1426 return tm(varname, value)
1415 end 1427 end
1416 end 1428 end
1417\end{verbatim} 1429\end{verbatim}
1418The function \verb|getglobal| is pre-defined in Lua \see{predefined}. 1430The function \verb|getglobal| is defined in the basic library~\see{predefined}.
1419 1431
1420\item[``setglobal'':]\index{setglobal event} 1432\item[``setglobal'':]\index{setglobal event}
1421called whenever Lua assigns to a global variable. 1433called whenever Lua assigns to a global variable.
1422This method cannot be set for numbers, strings, and tables and 1434This method cannot be set for numbers, strings, and tables and
1423userdata with default tags. 1435userdata with the default tag.
1424\begin{verbatim} 1436\begin{verbatim}
1425 function setglobal (varname, newvalue) 1437 function setglobal (varname, newvalue)
1426 local oldvalue = rawget(globals(), varname) 1438 local oldvalue = rawget(globals(), varname)
1427 local tm = gettagmethod(tag(oldvalue), "setglobal") 1439 local tm = gettagmethod(tag(oldvalue), "setglobal")
1428 if not tm then 1440 if not tm then
1429 rawset(globals(), varname, newvalue) 1441 rawset(globals(), varname, newvalue)
1430 else 1442 else
1431 tm(varname, oldvalue, newvalue) 1443 tm(varname, oldvalue, newvalue)
1432 end 1444 end
1433 end 1445 end
1434\end{verbatim} 1446\end{verbatim}
1435The function \verb|setglobal| is pre-defined in Lua \see{predefined}. 1447The function \verb|setglobal| is defined in the basic library~\see{predefined}.
1436 1448
1437\item[``gettable'':]\index{gettable event} 1449\item[``gettable'':]\index{gettable event}
1438called whenever Lua accesses an indexed variable. 1450called whenever Lua accesses an indexed variable.
1439This method cannot be set for tables with default tag. 1451This method cannot be set for tables with the default tag.
1440\begin{verbatim} 1452\begin{verbatim}
1441 function gettable_event (table, index) 1453 function gettable_event (table, index)
1442 local tm = gettagmethod(tag(table), "gettable") 1454 local tm = gettagmethod(tag(table), "gettable")
1443 if tm then 1455 if tm then
1444 return tm(table, index) 1456 return tm(table, index)
1445 elseif type(table) ~= "table" then 1457 elseif type(table) ~= "table" then
1446 error("indexed expression not a table"); 1458 error("indexed expression not a table");
1447 else 1459 else
1448 local v = rawget(table, index) 1460 local v = rawget(table, index)
1449 tm = gettagmethod(tag(table), "index") 1461 tm = gettagmethod(tag(table), "index")
1450 if v == nil and tm then 1462 if v == nil and tm then
1451 return tm(table, index) 1463 return tm(table, index)
1452 else 1464 else
1453 return v 1465 return v
1454 end 1466 end
1455 end 1467 end
1456 end 1468 end
1457\end{verbatim} 1469\end{verbatim}
1458 1470
1459\item[``settable'':]\index{settable event} 1471\item[``settable'':]\index{settable event}
1460called when Lua assigns to an indexed variable. 1472called when Lua assigns to an indexed variable.
1461This method cannot be set for tables with default tag. 1473This method cannot be set for tables with the default tag.
1462\begin{verbatim} 1474\begin{verbatim}
1463 function settable_event (table, index, value) 1475 function settable_event (table, index, value)
1464 local tm = gettagmethod(tag(table), "settable") 1476 local tm = gettagmethod(tag(table), "settable")
1465 if tm then 1477 if tm then
1466 tm(table, index, value) 1478 tm(table, index, value)
1467 elseif type(table) ~= "table" then 1479 elseif type(table) ~= "table" then
1468 error("indexed expression not a table") 1480 error("indexed expression not a table")
1469 else 1481 else
1470 rawset(table, index, value) 1482 rawset(table, index, value)
1471 end 1483 end
1472 end 1484 end
1473\end{verbatim} 1485\end{verbatim}
1474 1486
1475\item[``function'':]\index{function event} 1487\item[``function'':]\index{function event}
1476called when Lua tries to call a non-function value. 1488called when Lua tries to call a non-function value.
1477\begin{verbatim} 1489\begin{verbatim}
1478 function function_event (func, ...) 1490 function function_event (func, ...)
1479 if type(func) == "function" then 1491 if type(func) == "function" then
1480 return call(func, arg) 1492 return call(func, arg)
1481 else 1493 else
1482 local tm = gettagmethod(tag(func), "function") 1494 local tm = gettagmethod(tag(func), "function")
1483 if tm then 1495 if tm then
1484 for i=arg.n,1,-1 do 1496 for i=arg.n,1,-1 do
1485 arg[i+1] = arg[i] 1497 arg[i+1] = arg[i]
1486 end 1498 end
1487 arg.n = arg.n+1 1499 arg.n = arg.n+1
1488 arg[1] = func 1500 arg[1] = func
1489 return call(tm, arg) 1501 return call(tm, arg)
1490 else 1502 else
1491 error("call expression not a function") 1503 error("call expression not a function")
1492 end 1504 end
1493 end 1505 end
1494 end 1506 end
1495\end{verbatim} 1507\end{verbatim}
1496 1508
1497\item[``gc'':]\index{gc event} 1509\item[``gc'':]\index{gc event}
1498called when Lua is ``garbage collecting'' a userdata. 1510called when Lua is ``garbage collecting'' a userdata.
1499This tag method can be set only from~C, 1511This tag method can be set only from~C,
1500and cannot be set for a userdata with default tag. 1512and cannot be set for a userdata with the default tag.
1501For each userdata to be collected, 1513For each userdata to be collected,
1502Lua does the equivalent of the following function: 1514Lua does the equivalent of the following function:
1503\begin{verbatim} 1515\begin{verbatim}
1504 function gc_event (obj) 1516 function gc_event (obj)
1505 local tm = gettagmethod(tag(obj), "gc") 1517 local tm = gettagmethod(tag(obj), "gc")
1506 if tm then 1518 if tm then
1507 tm(obj) 1519 tm(obj)
1508 end 1520 end
1509 end 1521 end
1510\end{verbatim} 1522\end{verbatim}
1511Moreover, at the end of a garbage collection cycle, 1523Moreover, at the end of a garbage collection cycle,
1512Lua does the equivalent of the call \verb|gc_event(nil)|. 1524Lua does the equivalent of the call \verb|gc_event(nil)|.
1525(This may change in the final 4.0 version.)
1513 1526
1514\end{description} 1527\end{description}
1515 1528
@@ -1520,261 +1533,293 @@ Lua does the equivalent of the call \verb|gc_event(nil)|.
1520 1533
1521This section describes the API for Lua, that is, 1534This section describes the API for Lua, that is,
1522the set of C~functions available to the host program to communicate 1535the set of C~functions available to the host program to communicate
1523with the Lua library. 1536with Lua.
1524The API functions can be classified into the following categories:
1525\begin{enumerate}
1526\item managing states;
1527\item exchanging values between C and Lua;
1528\item executing Lua code;
1529\item manipulating (reading and writing) Lua objects;
1530\item calling Lua functions;
1531\item defining C~functions to be called by Lua;
1532\item manipulating references to Lua Objects.
1533\end{enumerate}
1534All API functions and related types and constants 1537All API functions and related types and constants
1535are declared in the header file \verb|lua.h|. 1538are declared in the header file \verb|lua.h|.
1536 1539
1537\NOTE 1540\NOTE
1538Even when we use the term \emph{function}, 1541Even when we use the term ``function'',
1539\emph{any facility in the API may be provided as a macro instead}. 1542any facility in the API may be provided as a \emph{macro} instead.
1540All such macros use each of its arguments exactly once, 1543All such macros use each of its arguments exactly once,
1541and so do not generate hidden side-effects. 1544and so do not generate hidden side-effects.
1542 1545
1543 1546
1544\subsection{States} \label{mangstate} 1547\subsection{States} \label{mangstate}
1545 1548
1546The Lua library is reentrant: 1549The Lua library is fully reentrant:
1547it does not have any global variable. 1550it does not have any global variable.
1548The whole state of the Lua interpreter 1551The whole state of the Lua interpreter
1549(global variables, stack, tag methods, etc.) 1552(global variables, stack, tag methods, etc.)
1550is stored in a dynamic structure; \Deffunc{lua_State} 1553is stored in a dynamically allocated structure; \Deffunc{lua_State}
1551this state must be passed as the first argument to almost 1554this state must be passed as the first argument to
1552every function in the library. 1555every function in the library (except \verb|lua_open| below).
1553 1556
1554Before calling any API function, 1557Before calling any API function,
1555you must create a state. 1558you must create a state.
1556This is done by calling\Deffunc{lua_newstate} 1559This is done by calling\Deffunc{lua_open}
1557\begin{verbatim} 1560\begin{verbatim}
1558lua_State *lua_newstate (int stacksize, int builtin); 1561 lua_State *lua_open (int stacksize);
1559\end{verbatim} 1562\end{verbatim}
1560The arguments to this function are 1563The sole argument to this function is the stack size for the interpreter.
1561the stack size for the interpreter and a boolean that 1564(Each function call needs one stack position for each argument, local variable
1562indicates whether the predefined functions should be loaded or not. 1565and temporary values, plus one position for book-keeping.
1563Each function call needs one stack position for each local variable
1564and temporary variables, plus one position for book-keeping.
1565The stack must also have some 20 extra positions available. 1566The stack must also have some 20 extra positions available.
1566For very small implementations, without recursive functions, 1567For very small implementations, without recursive functions,
1567a stack size of 100 should be enough. 1568a stack size of 100 should be enough.)
1568A value 0 for \verb|stacksize| uses a default size of 1024 positions. 1569If \verb|stacksize| is zero,
1569For instance, the call 1570then a default size is used (the default is 1024).
1570\begin{verbatim}
1571lua_State *L = lua_newstate(0, 1);
1572\end{verbatim}
1573creates a new state with a stack of 1024 positions
1574and with the predefined functions loaded;
1575the call
1576\begin{verbatim}
1577lua_State *L = lua_newstate(100, 0)
1578\end{verbatim}
1579creates a new state with a stack of 100 positions,
1580without the predefined functions.
1581When you create a state without the builtin function,
1582you must provide by yourself any function that your interpreter may need
1583(such as \verb|_ALERT| and \verb|_ERRORMESSAGE| for error report, etc.).
1584 1571
1585To release a state, you call 1572To release a state created with \verb|lua_open|, call
1586\begin{verbatim} 1573\begin{verbatim}
1587void lua_close (lua_State *L); 1574 void lua_close (lua_State *L);
1588\end{verbatim} 1575\end{verbatim}
1589This function destroys all objects in the current Lua environment 1576This function destroys all objects in the given Lua environment
1590(calling the corresponding garbage collection tag methods) 1577(calling the corresponding garbage-collection tag methods)
1591and frees all dynamic memory used by the state. 1578and frees all dynamic memory used by that state.
1592Frequently, you do not need to call this function, 1579Usually, you do not need to call this function,
1593because all resources are naturally released when the program ends. 1580because all resources are naturally released when your program ends.
1594On the other hand, 1581On the other hand,
1595long-running programs --- 1582long-running programs ---
1596like a daemon or web server, for example --- 1583like a daemon or a web server ---
1597might need to release states as soon as they are not needed, 1584might need to release states as soon as they are not needed,
1598to avoid growing too big. 1585to avoid growing too big.
1599 1586
1600With the exception of \verb|lua_newstate|, 1587With the exception of \verb|lua_open|,
1601all functions in the API need a state as their first argument. 1588all functions in the API need a state as their first argument.
1602 1589
1603 1590
1604\subsection{Exchanging Values between C and Lua} \label{valuesCLua} 1591\subsection{The Stack and Indices}
1605Because Lua has no static type system, 1592
1606all values passed between Lua and C have type 1593Lua uses a \emph{stack} to pass values to and from C.
1607\verb|lua_Object|\Deffunc{lua_Object}, 1594Each element in this stack represents a Lua value
1608which works like an abstract type in C that can hold any Lua value. 1595(nil, number, string, etc.).
1609Values of type \verb|lua_Object| have no meaning outside Lua; 1596
1610for instance, 1597For convenience,
1611you cannot compare two \verb|lua_Object|s directly. 1598most query operations in the API do not follow a strict stack discipline.
1612Instead, you should use the following function: 1599Instead, they can refer to any element in the stack by using an \emph{index}:
1613\Deffunc{lua_equal} 1600A positive index represents an \emph{absolute} stack position
1614\begin{verbatim} 1601(starting at 1, not 0 as in C);
1615int lua_equal (lua_State *L, lua_Object o1, lua_Object o2); 1602a negative index represents an \emph{offset} from the top of the stack.
1616\end{verbatim} 1603More specifically, if the stack has \M{n} elements,
1617 1604index 1 represents the first element
1618To check the type of a \verb|lua_Object|, 1605(that is, the first element pushed onto the stack),
1606index \M{n} represents the last element;
1607index \Math{-1} also represents the last element
1608(that is, the element at the top),
1609and index \Math{-n} represents the first element.
1610We say that an index is \emph{valid}
1611if it lays between 1 and the stack top
1612(that is, \verb|(1 <= abs(index) <= top)|).
1613\index{stack index} \index{valid index}
1614
1615At any time, you can get the index of the top element by calling
1616\Deffunc{lua_gettop}
1617\begin{verbatim}
1618 int lua_gettop (lua_State *L);
1619\end{verbatim}
1620Because indices start at 1,
1621the result of \verb|lua_gettop| is equal to the number of elements in the stack
1622(0 means an empty stack).
1623
1624When you interact with Lua API,
1625\emph{you are responsible for controlling stack overflow}.
1626The function \Deffunc{lua_stackspace}
1627\begin{verbatim}
1628 int lua_stackspace (lua_State *L);
1629\end{verbatim}
1630returns the number of stack positions still available.
1631Whenever Lua calls C, \Deffunc{LUA_MINSTACK}
1632it ensures that
1633at least \verb|LUA_MINSTACK| positions are still available.
1634\verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16,
1635and so you have to worry about stack space only
1636when your code has loops pushing elements onto the stack.
1637
1638Most query functions accept as indices any value inside the
1639available stack space.
1640Such indices are called \emph{acceptable indices}.
1641More formally, we can define an \IndexEmph{acceptable index}
1642as
1643\begin{verbatim}
1644 (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace)
1645\end{verbatim}
1646(Note that 0 is not an acceptable index.)
1647
1648\subsection{Stack Manipulation}
1649The API offers the following functions for basic stack manipulation:
1650\Deffunc{lua_settop}\Deffunc{lua_pushvalue}
1651\Deffunc{lua_remove}\Deffunc{lua_insert}
1652\begin{verbatim}
1653 void lua_settop (lua_State *L, int index);
1654 void lua_pushvalue (lua_State *L, int index);
1655 void lua_remove (lua_State *L, int index);
1656 void lua_insert (lua_State *L, int index);
1657\end{verbatim}
1658
1659\verb|lua_settop| accepts any acceptable index,
1660or 0,
1661and sets the stack top to that index.
1662If the new top is larger than the old one,
1663then the new elements are filled with \nil.
1664If \verb|index| is 0, then all stack elements are removed.
1665A useful macro defined in the API is
1666\begin{verbatim}
1667 #define lua_pop(L,n) lua_settop(L, -(n)-1)
1668\end{verbatim}
1669which pops \verb|n| elements from the stack.
1670
1671\verb|lua_pushvalue| pushes onto the stack a copy of the element
1672at the given index.
1673\verb|lua_remove| removes the element at the given position,
1674shifting down the elements on top of that position to fill in the gap.
1675\verb|lua_insert| moves the top element into the given position,
1676shifting up the elements on top of that position to open space.
1677These functions accept only valid indices.
1678As an example, if the stack starts as \verb|10 20 30 40 50|
1679(from bottom to top),
1680then
1681\begin{verbatim}
1682 lua_pushvalue(L, 3) --> 10 20 30 40 50 30
1683 lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30
1684 lua_remove(L, -3) --> 10 20 30 40 30 30
1685 lua_remove(L, 6) --> 10 20 30 40 30
1686 lua_insert(L, 1) --> 30 10 20 30 40
1687 lua_insert(L, -1) --> 30 10 20 30 40 (no effect)
1688 lua_settop(L, -3) --> 30 10 20
1689 lua_settop(L, 6) --> 30 10 20 nil nil nil
1690\end{verbatim}
1691
1692
1693\subsection{Querying the Stack}
1694
1695To check the type of a stack element,
1619the following functions are available: 1696the following functions are available:
1620\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} 1697\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring}
1621\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} 1698\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata}
1622\Deffunc{lua_isfunction} 1699\Deffunc{lua_isfunction}\Deffunc{lua_type}
1623\Deffunc{lua_type} 1700\begin{verbatim}
1624\begin{verbatim} 1701 const char *lua_type (lua_State *L, int index);
1625int lua_isnil (lua_State *L, lua_Object object); 1702 int lua_tag (lua_State *L, int index);
1626int lua_isnumber (lua_State *L, lua_Object object); 1703 int lua_isnil (lua_State *L, int index);
1627int lua_isstring (lua_State *L, lua_Object object); 1704 int lua_isnumber (lua_State *L, int index);
1628int lua_istable (lua_State *L, lua_Object object); 1705 int lua_isstring (lua_State *L, int index);
1629int lua_isfunction (lua_State *L, lua_Object object); 1706 int lua_istable (lua_State *L, int index);
1630int lua_iscfunction (lua_State *L, lua_Object object); 1707 int lua_isfunction (lua_State *L, int index);
1631int lua_isuserdata (lua_State *L, lua_Object object); 1708 int lua_iscfunction (lua_State *L, int index);
1632const char *lua_type (lua_State *L, lua_Object object); 1709 int lua_isuserdata (lua_State *L, int index);
1633\end{verbatim} 1710\end{verbatim}
1711These functions can be called with any acceptable index.
1712
1713\verb|lua_type| returns one of the following strings,
1714describing the type of the given object:
1715\verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|,
1716\verb|"function"|, \verb|"userdata"|; or \verb|"NO VALUE"|,
1717if the index is non-valid (that is, if that stack position is ``empty'').
1718
1719\verb|lua_tag| returns the tag of a value,
1720or \verb|LUA_NOTAG| for a non-valid index.
1721(Very dirty trick: some type names start with the same letter (Number-Nil);
1722others have the second letter in common (nUmber-fUnction).
1723However, you can use the emph{third} letter as a unique scalar
1724identification for each type.)
1725
1634The \verb|lua_is*| functions return 1 if the object is compatible 1726The \verb|lua_is*| functions return 1 if the object is compatible
1635with the given type, and 0 otherwise. 1727with the given type, and 0 otherwise.
1636The function \verb|lua_isnumber| accepts numbers and numerical strings, 1728They always return 0 for a non-valid index.
1729\verb|lua_isnumber| accepts numbers and numerical strings,
1637\verb|lua_isstring| accepts strings and numbers \see{coercion}, 1730\verb|lua_isstring| accepts strings and numbers \see{coercion},
1638and \verb|lua_isfunction| accepts Lua functions and C~functions. 1731and \verb|lua_isfunction| accepts both Lua functions and C~functions.
1639To distinguish between Lua functions and C~functions, 1732To distinguish between Lua functions and C~functions,
1640you should use \verb|lua_iscfunction|. 1733you should use \verb|lua_iscfunction|.
1641To distinguish between numbers and numerical strings, 1734To distinguish between numbers and numerical strings,
1642you can use \verb|lua_type|. 1735you can use \verb|lua_type|.
1643The \verb|lua_type| returns one of the following strings,
1644describing the type of the given object:
1645\verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|,
1646\verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|.
1647 1736
1648To get the tag of a \verb|lua_Object|, 1737The API also has functions to compare two values in the stack:
1649use the following function:
1650\Deffunc{lua_tag}
1651\begin{verbatim} 1738\begin{verbatim}
1652int lua_tag (lua_State *L, lua_Object object); 1739 int lua_equal (lua_State *L, int index1, int index2);
1740 int lua_lessthan (lua_State *L, int index1, int index2);
1653\end{verbatim} 1741\end{verbatim}
1742These functions are equivalent to their counterparts in Lua.
1743Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event|
1744described in~\ref{tag-method}.
1745Both functions return 0 if any of the indices are non-valid.
1654 1746
1655To translate a value from type \verb|lua_Object| to a specific C type, 1747To translate a value in the stack to a specific C~type,
1656you can use the following conversion functions: 1748you can use the following conversion functions:
1657\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} 1749\Deffunc{lua_tonumber}\Deffunc{lua_tostring}\Deffunc{lua_strlen}
1658\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} 1750\Deffunc{lua_tocfunction}\Deffunc{lua_touserdata}
1659\begin{verbatim} 1751\begin{verbatim}
1660double lua_getnumber (lua_State *L, lua_Object object); 1752 double lua_tonumber (lua_State *L, int index);
1661const char *lua_getstring (lua_State *L, lua_Object object); 1753 const char *lua_tostring (lua_State *L, int index);
1662size_t lua_strlen (lua_State *L, lua_Object object); 1754 size_t lua_strlen (lua_State *L, int index);
1663lua_CFunction lua_getcfunction (lua_State *L, lua_Object object); 1755 lua_CFunction lua_tocfunction (lua_State *L, int index);
1664void *lua_getuserdata (lua_State *L, lua_Object object); 1756 void *lua_touserdata (lua_State *L, int index);
1665\end{verbatim} 1757\end{verbatim}
1758These functions can be called with any acceptable index.
1759When called with a non-valid index,
1760they act as if the given value had an incorrect type.
1666 1761
1667\verb|lua_getnumber| converts a \verb|lua_Object| to a floating-point number. 1762\verb|lua_tonumber| converts the value at the given index
1668This \verb|lua_Object| must be a number or a string convertible to number 1763to a floating-point number.
1669\see{coercion}; otherwise, \verb|lua_getnumber| returns~0. 1764This value must be a number or a string convertible to number
1765\see{coercion}; otherwise, \verb|lua_tonumber| returns~0.
1670 1766
1671\verb|lua_getstring| converts a \verb|lua_Object| to a string 1767\verb|lua_tostring| converts a Lua value to a string
1672(\verb|const char*|). 1768(\verb|const char*|).
1673This \verb|lua_Object| must be a string or a number; 1769This value must be a string or a number;
1674otherwise, the function returns \verb|NULL|. 1770otherwise, the function returns \verb|NULL|.
1675This function does not create a new string, 1771This function returns a pointer to a string inside the Lua environment.
1676but returns a pointer to a string inside the Lua environment.
1677Those strings always have a 0 after their last character (like in C), 1772Those strings always have a 0 after their last character (like in C),
1678but may contain other zeros in their body. 1773but may contain other zeros in their body.
1679If you do not know whether a string may contain zeros, 1774If you do not know whether a string may contain zeros,
1680you should use \verb|lua_strlen| to get the actual length. 1775you should use \verb|lua_strlen| to get its actual length.
1681Because Lua has garbage collection, 1776Because Lua has garbage collection,
1682there is no guarantee that the pointer returned by \verb|lua_getstring| 1777there is no guarantee that the pointer returned by \verb|lua_tostring|
1683will be valid after the block ends 1778will be valid after the respective value is removed from the stack.
1684\see{GC}.
1685 1779
1686\verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function. 1780\verb|lua_tocfunction| converts a value in the stack to a C~function.
1687This \verb|lua_Object| must be a C~function; 1781This value must be a C~function;
1688otherwise, \verb|lua_getcfunction| returns \verb|NULL|. 1782otherwise, \verb|lua_tocfunction| returns \verb|NULL|.
1689The type \verb|lua_CFunction| is explained in \See{LuacallC}. 1783The type \verb|lua_CFunction| is explained in \See{LuacallC}.
1690 1784
1691\verb|lua_getuserdata| converts a \verb|lua_Object| to \verb|void*|. 1785\verb|lua_touserdata| converts a value to \verb|void*|.
1692This \verb|lua_Object| must have type \emph{userdata}; 1786This value must have type \emph{userdata};
1693otherwise, \verb|lua_getuserdata| returns \verb|NULL|. 1787otherwise, \verb|lua_touserdata| returns \verb|NULL|.
1694 1788
1695\subsection{Communication between Lua and C}\label{Lua-C-protocol} 1789
1696 1790
1697All communication between Lua and C is done through two 1791\subsection{Pushing values onto the Stack}
1698abstract data types, called \Def{lua2C} and \Def{C2lua}. 1792
1699The first one, as the name implies, is used to pass values 1793The API has the following functions to
1700from Lua to C: 1794push C~values onto the stack:
1701parameters when Lua calls C and results when C calls Lua.
1702The structure C2lua is used in the reverse direction:
1703parameters when C calls Lua and results when Lua calls C.
1704
1705The structure lua2C is an \emph{abstract array}
1706that can be indexed with the function:
1707\Deffunc{lua_lua2C}
1708\begin{verbatim}
1709lua_Object lua_lua2C (lua_State *L, int number);
1710\end{verbatim}
1711where \verb|number| starts with 1.
1712When called with a number larger than the array size,
1713this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}.
1714In this way, it is possible to write C~functions that receive
1715a variable number of parameters,
1716and to call Lua functions that return a variable number of results.
1717Note that the structure lua2C cannot be directly modified by C code.
1718
1719The structure C2lua is an \emph{abstract stack}.
1720Pushing elements into this stack
1721is done with the following functions:
1722\Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} 1795\Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring}
1723\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag} 1796\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag}
1724\Deffunc{lua_pushnil}\Deffunc{lua_pushobject} 1797\Deffunc{lua_pushnil}\Deffunc{lua_pushuserdata}\label{pushing}
1725\Deffunc{lua_pushuserdata}\label{pushing} 1798\begin{verbatim}
1726\begin{verbatim} 1799 void lua_pushnumber (lua_State *L, double n);
1727void lua_pushnumber (lua_State *L, double n); 1800 void lua_pushlstring (lua_State *L, const char *s, size_t len);
1728void lua_pushlstring (lua_State *L, const char *s, size_t len); 1801 void lua_pushstring (lua_State *L, const char *s);
1729void lua_pushstring (lua_State *L, const char *s); 1802 void lua_pushusertag (lua_State *L, void *u, int tag);
1730void lua_pushusertag (lua_State *L, void *u, int tag); 1803 void lua_pushnil (lua_State *L);
1731void lua_pushnil (lua_State *L); 1804 void lua_pushcfunction (lua_State *L, lua_CFunction f);
1732void lua_pushobject (lua_State *L, lua_Object object); 1805\end{verbatim}
1733void lua_pushcfunction (lua_State *L, lua_CFunction f); /* macro */ 1806These functions receive a C~value,
1734\end{verbatim} 1807convert it to a corresponding Lua value,
1735All of them receive a C value, 1808and push the result onto the stack.
1736convert it to a corresponding \verb|lua_Object|, 1809In particular, \verb|lua_pushlstring| and \verb|lua_pushstring|
1737and leave the result on the top of C2lua. 1810make an \emph{internal copy} of the given string.
1738In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring| 1811\verb|lua_pushstring| can only be used to push proper C~strings
1739make an internal copy of the given string.
1740Function \verb|lua_pushstring| can only be used to push proper C strings
1741(that is, strings that end with a zero and do not contain embedded zeros); 1812(that is, strings that end with a zero and do not contain embedded zeros);
1742otherwise you should use the more general \verb|lua_pushlstring|. 1813otherwise you should use the more general \verb|lua_pushlstring|,
1743The function 1814which accepts an explicit size.
1744\Deffunc{lua_pop}
1745\begin{verbatim}
1746lua_Object lua_pop (lua_State *L);
1747\end{verbatim}
1748returns a reference to the object at the top of the C2lua stack,
1749and pops it.
1750 1815
1751When C code calls Lua repeatedly, as in a loop,
1752objects returned by these calls accumulate,
1753and may cause a stack overflow.
1754To avoid this,
1755nested blocks can be defined with the functions
1756\begin{verbatim}
1757void lua_beginblock (lua_State *L);
1758void lua_endblock (lua_State *L);
1759\end{verbatim}
1760At the end of a block,
1761Lua releases all \verb|lua_Object|s created inside the block,
1762and empties the C2lua stack.
1763 1816
1764\subsection{Garbage Collection}\label{GC} 1817\subsection{Garbage Collection}\label{GC}
1765Because Lua has automatic memory management and garbage collection,
1766a \verb|lua_Object| has a limited scope,
1767and is only valid inside the \emph{block} where it has been created.
1768A C~function called from Lua is a block,
1769and its parameters are valid only until its end.
1770It is good programming practice to convert Lua objects to C values
1771as soon as they are available,
1772and never to store \verb|lua_Object|s in C global variables.
1773 1818
1774A garbage collection cycle can be forced by: 1819A garbage collection cycle can be forced by:
1775\Deffunc{lua_collectgarbage} 1820\Deffunc{lua_collectgarbage}
1776\begin{verbatim} 1821\begin{verbatim}
1777long lua_collectgarbage (lua_State *L, long limit); 1822 long lua_collectgarbage (lua_State *L, long limit);
1778\end{verbatim} 1823\end{verbatim}
1779This function returns the number of objects collected. 1824This function returns the number of objects collected.
1780The argument \verb|limit| makes the next cycle occur only 1825The argument \verb|limit| makes the next cycle occur only
@@ -1802,37 +1847,39 @@ whose semantics are only known to the host program.
1802Tags are created with the function 1847Tags are created with the function
1803\Deffunc{lua_newtag} 1848\Deffunc{lua_newtag}
1804\begin{verbatim} 1849\begin{verbatim}
1805int lua_newtag (lua_State *L); 1850 int lua_newtag (lua_State *L);
1806\end{verbatim} 1851\end{verbatim}
1807The function \verb|lua_settag| changes the tag of 1852The function \verb|lua_settag| changes the tag of
1808the object on the top of C2lua (and pops it); 1853the object on top of the stack (and pops it):
1809the object must be a userdata or a table:
1810\Deffunc{lua_settag} 1854\Deffunc{lua_settag}
1811\begin{verbatim} 1855\begin{verbatim}
1812void lua_settag (lua_State *L, int tag); 1856 void lua_settag (lua_State *L, int tag);
1813\end{verbatim} 1857\end{verbatim}
1814The given \verb|tag| must be a value created with \verb|lua_newtag|. 1858The object must be a userdata or a table;
1859the given \verb|tag| must be a value created with \verb|lua_newtag|.
1815 1860
1816\subsection{Executing Lua Code} 1861\subsection{Executing Lua Code}
1817A host program can execute Lua chunks written in a file or in a string 1862A host program can execute Lua chunks written in a file or in a string
1818using the following functions:% 1863by using the following functions:%
1819\Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer} 1864\Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer}%
1820\begin{verbatim} 1865\begin{verbatim}
1821int lua_dofile (lua_State *L, const char *filename); 1866 int lua_dofile (lua_State *L, const char *filename);
1822int lua_dostring (lua_State *L, const char *string); 1867 int lua_dostring (lua_State *L, const char *string);
1823int lua_dobuffer (lua_State *L, const char *buff, 1868 int lua_dobuffer (lua_State *L, const char *buff,
1824 size_t size, const char *name); 1869 size_t size, const char *name);
1825\end{verbatim} 1870\end{verbatim}
1826All these functions return 1871These functions return
18270, in case of success, or one of the following error codes: 18720 in case of success, or one of the following error codes if they fail
1873(these constants are defined in \verb|lua.h|.):
1828\begin{itemize} 1874\begin{itemize}
1829\item \verb|LUA_ERRRUN| --- 1875\item \verb|LUA_ERRRUN| ---
1830error while running the chunk. 1876error while running the chunk.
1831\item \verb|LUA_ERRSYNTAX| --- 1877\item \verb|LUA_ERRSYNTAX| ---
1832syntax error during pre-compilation. 1878syntax error during pre-compilation.
1833\item \verb|LUA_ERRMEM| --- 1879\item \verb|LUA_ERRMEM| ---
1834memory allocation error; 1880memory allocation error.
1835for such errors, Lua does not call the \verb|LUA_ERRORMESSAGE| function. 1881For such errors, Lua does not call the \verb|_ERRORMESSAGE| function
1882\see{error}.
1836\item \verb|LUA_ERRFILE| --- 1883\item \verb|LUA_ERRFILE| ---
1837error opening the file (only for \verb|lua_dofile|). 1884error opening the file (only for \verb|lua_dofile|).
1838In this case, 1885In this case,
@@ -1844,88 +1891,118 @@ or call \verb|perror| to tell the user what went wrong.
1844 1891
1845When called with argument \verb|NULL|, 1892When called with argument \verb|NULL|,
1846\verb|lua_dofile| executes the \verb|stdin| stream. 1893\verb|lua_dofile| executes the \verb|stdin| stream.
1847Functions \verb|lua_dofile| and \verb|lua_dobuffer| 1894\verb|lua_dofile| and \verb|lua_dobuffer|
1848are both able to execute pre-compiled chunks. 1895are both able to execute pre-compiled chunks.
1849They automatically detect whether the chunk is text or binary, 1896They automatically detect whether the chunk is text or binary,
1850and load it accordingly (see program \IndexVerb{luac}). 1897and load it accordingly (see program \IndexVerb{luac}).
1851Function \verb|lua_dostring| executes only source code, 1898\verb|lua_dostring| executes only source code,
1852given in textual form. 1899given in textual form.
1853 1900
1854The third parameter to \verb|lua_dobuffer| (\verb|name|) 1901The third parameter to \verb|lua_dobuffer|
1855is the ``name of the chunk'', 1902is the ``name of the chunk'',
1856used in error messages and debug information. 1903used in error messages and debug information.
1857If \verb|name| is \verb|NULL|, 1904If \verb|name| is \verb|NULL|,
1858then Lua gives a default name to the chunk. 1905then Lua gives a default name to the chunk.
1859 1906
1860These functions return, in structure lua2C, 1907These functions push onto the stack
1861any values eventually returned by the chunks. 1908any values eventually returned by the chunks.
1862They also empty the stack C2lua. 1909A chunk may return any number of values;
1910Lua takes care that these values fit into the stack space,
1911but after the call the responsibility is back with you.
1912If you need to push other elements after calling any of these functions,
1913and you want to play safe,
1914you must either check the stack space or remove the returned elements
1915from the stack (if you do not need them).
1916For instance, the following code
1917loads a chunk in a file and discards all results returned by this chunk,
1918leaving the stack as it was before the call:
1919\begin{verbatim}
1920 {
1921 int oldtop = lua_gettop(L);
1922 lua_dofile(L, filename);
1923 lua_settop(L, oldtop);
1924 }
1925\end{verbatim}
1926
1863 1927
1928\subsection{Manipulating Global Variables in Lua}
1864 1929
1865\subsection{Manipulating Lua Objects} 1930To read the value of a global Lua variable,
1866To read the value of any global Lua variable, 1931you call
1867one uses the function
1868\Deffunc{lua_getglobal} 1932\Deffunc{lua_getglobal}
1869\begin{verbatim} 1933\begin{verbatim}
1870lua_Object lua_getglobal (lua_State *L, const char *varname); 1934 void lua_getglobal (lua_State *L, const char *varname);
1871\end{verbatim} 1935\end{verbatim}
1936which pushes onto the stack the value of the given variable.
1872As in Lua, this function may trigger a tag method 1937As in Lua, this function may trigger a tag method
1873for the ``getglobal'' event. 1938for the ``getglobal'' event.
1874To read the real value of a global variable, 1939To read the real value of a global variable,
1875without invoking any tag method, 1940without invoking any tag method,
1876use the \emph{lua_rawget} function over the table of globals. 1941use the \verb|lua_rawget| function over the table of globals
1942(see below).
1877 1943
1878To store a value previously pushed onto C2lua in a global variable, 1944To store a value in a global variable,
1879there is the function 1945you call
1880\Deffunc{lua_setglobal} 1946\Deffunc{lua_setglobal}
1881\begin{verbatim} 1947\begin{verbatim}
1882void lua_setglobal (lua_State *L, const char *varname); 1948 void lua_setglobal (lua_State *L, const char *varname);
1883\end{verbatim} 1949\end{verbatim}
1950which pops from the stack the value to be stored in the given variable.
1884As in Lua, this function may trigger a tag method 1951As in Lua, this function may trigger a tag method
1885for the ``setglobal'' event. 1952for the ``setglobal'' event.
1886To set the real value of a global variable, 1953To set the real value of a global variable,
1887without invoking any tag method, 1954without invoking any tag method,
1888use the \emph{lua_rawset} function over the table of globals. 1955use the \verb|lua_rawset| function over the table of globals.
1889 1956
1890To get the table of globals, 1957All global variables are kept in an ordinary Lua table.
1891you should call 1958You can get this table calling
1892\Deffunc{lua_pushglobals} 1959\Deffunc{lua_getglobals}
1893\begin{verbatim} 1960\begin{verbatim}
1894void lua_pushglobals (lua_State *L); 1961 void lua_getglobals (lua_State *L);
1895\end{verbatim} 1962\end{verbatim}
1963which pushes the current table of globals onto the stack.
1896To set another table as the table of globals, 1964To set another table as the table of globals,
1897you use 1965you call
1898\Deffunc{lua_setglobals} 1966\Deffunc{lua_setglobals}
1899\begin{verbatim} 1967\begin{verbatim}
1900void lua_setglobals (lua_State *L, lua_Object newtable); 1968 void lua_setglobals (lua_State *L);
1901\end{verbatim} 1969\end{verbatim}
1970The table to be used is popped from the stack.
1971
1972\subsection{Manipulating Tables in Lua}
1973Lua tables can also be manipulated through the API.
1902 1974
1903Tables can also be manipulated via the API. 1975To read the value of in a table,
1904The function 1976the table must reside somewhere in the stack.
1977With this set,
1978you call
1905\Deffunc{lua_gettable} 1979\Deffunc{lua_gettable}
1906\begin{verbatim} 1980\begin{verbatim}
1907lua_Object lua_gettable (lua_State *L); 1981 void lua_gettable (lua_State *L, int index);
1908\end{verbatim} 1982\end{verbatim}
1909pops a table and an index from the stack C2lua, 1983where \verb|index| refers to the table.
1910and returns the contents of the table at that index. 1984\verb|lua_gettable| pops a key from the stack,
1985and returns (on the stack) the contents of the table at that key.
1911As in Lua, this operation may trigger a tag method 1986As in Lua, this operation may trigger a tag method
1912for the ``gettable'' event. 1987for the ``gettable'' event.
1913To get the real value of any table index, 1988To get the real value of any table key,
1914without invoking any tag method, 1989without invoking any tag method,
1915use the \emph{raw} version: 1990use the \emph{raw} version:
1916\Deffunc{lua_rawget} 1991\Deffunc{lua_rawget}
1917\begin{verbatim} 1992\begin{verbatim}
1918lua_Object lua_rawget (lua_State *L); 1993 void lua_rawget (lua_State *L, int index);
1919\end{verbatim} 1994\end{verbatim}
1920 1995
1921To store a value in an index, 1996To store a value into a table that resides somewhere in the stack,
1922the program must push the table, the index, and the value onto C2lua 1997you push the key and the value onto the stack
1923(in this order), 1998(in this order),
1924and then call the function 1999and then call
1925\Deffunc{lua_settable} 2000\Deffunc{lua_settable}
1926\begin{verbatim} 2001\begin{verbatim}
1927void lua_settable (lua_State *L); 2002 void lua_settable (lua_State *L, int index);
1928\end{verbatim} 2003\end{verbatim}
2004where \verb|index| refers to the table.
2005\verb|lua_settable| pops from the stack both the key and the value.
1929As in Lua, this operation may trigger a tag method 2006As in Lua, this operation may trigger a tag method
1930for the ``settable'' event. 2007for the ``settable'' event.
1931To set the real value of any table index, 2008To set the real value of any table index,
@@ -1933,125 +2010,158 @@ without invoking any tag method,
1933use the \emph{raw} version: 2010use the \emph{raw} version:
1934\Deffunc{lua_rawset} 2011\Deffunc{lua_rawset}
1935\begin{verbatim} 2012\begin{verbatim}
1936void lua_rawset (lua_State *L); 2013 void lua_rawset (lua_State *L, int index);
1937\end{verbatim} 2014\end{verbatim}
1938 2015
1939Finally, the function 2016Finally, the function
1940\Deffunc{lua_createtable} 2017\Deffunc{lua_newtable}
2018\begin{verbatim}
2019 void lua_newtable (lua_State *L);
2020\end{verbatim}
2021creates a new, empty table and and pushes it onto the stack.
2022
2023\subsection{Using Tables as Arrays}
2024The API has functions that help to use Lua tables as arrays,
2025that is,
2026tables indexed by numbers only:
2027\Deffunc{lua_rawgeti}
2028\Deffunc{lua_rawseti}
2029\Deffunc{lua_getn}
1941\begin{verbatim} 2030\begin{verbatim}
1942lua_Object lua_createtable (lua_State *L); 2031 void lua_rawgeti (lua_State *L, int index, int n);
2032 void lua_rawseti (lua_State *L, int index, int n);
2033 int lua_getn (lua_State *L, int index);
1943\end{verbatim} 2034\end{verbatim}
1944creates and returns a new, empty table.
1945 2035
2036\verb|lua_rawgeti| gets the value of the \verb|n|-th element of the table
2037at stack position \verb|index|.
2038
2039\verb|lua_rawseti| sets the value of the \verb|n|-th element of the table
2040at stack position \verb|index| to the value at the top of the stack.
2041
2042\verb|lua_getn| returns the number of elements in the table
2043at stack position \verb|index|.
2044This number is the value of the table field \verb|n|,
2045if it has a numeric value,
2046or
2047the largest numerical index with a non-nil value in the table.
1946 2048
1947\subsection{Calling Lua Functions} 2049\subsection{Calling Lua Functions}
1948Functions defined in Lua by a chunk 2050
2051Functions defined in Lua
1949can be called from the host program. 2052can be called from the host program.
1950This is done using the following protocol: 2053This is done using the following protocol:
1951first, the arguments to the function are pushed onto C2lua 2054First, the function to be called is pushed onto the stack;
1952\see{pushing}, in direct order, i.e., the first argument is pushed first. 2055then, the arguments to the function are pushed
1953Then, the function is called using 2056\see{pushing} in direct order, i.e., the first argument is pushed first.
1954\Deffunc{lua_callfunction} 2057Finally, the function is called using
1955\begin{verbatim} 2058\Deffunc{lua_call}
1956int lua_callfunction (lua_State *L, lua_Object function); 2059\begin{verbatim}
1957\end{verbatim} 2060 int lua_call (lua_State *L, int nargs, int nresults);
1958This function returns the same error codes that \verb|lua_dostring|. 2061\end{verbatim}
1959Finally, the results are returned in structure lua2C 2062This function returns the same error codes as \verb|lua_dostring|.
1960(recall that a Lua function may return many values), 2063Here,
1961and can be retrieved with the macro \verb|lua_getresult|, 2064\verb|nargs| is the number of arguments that you pushed onto the stack.
1962\Deffunc{lua_getresult} 2065All arguments and the function value are popped from the stack,
1963which is just another name for the function \verb|lua_lua2C|. 2066and the function results are pushed.
1964Note that \verb|lua_callfunction| 2067The number of results are adjusted \see{adjust} to \verb|nresults|,
1965pops all elements from the C2lua stack. 2068unless \verb|nresults| is \IndexVerb{LUA_MULTRET}.
2069In that case, \emph{all} results from the function are pushed.
2070The function results are pushed in direct order
2071(the first result is pushed first),
2072so that after the call the last result is on the top.
1966 2073
1967The following example shows how the host program may do the 2074The following example shows how the host program may do the
1968equivalent to the Lua code: 2075equivalent to the Lua code:
1969\begin{verbatim} 2076\begin{verbatim}
1970 a,b = f("how", t.x, 4) 2077 a,b = f("how", t.x, 4)
1971\end{verbatim} 2078\end{verbatim}
2079Here it is in~C:
1972\begin{verbatim} 2080\begin{verbatim}
1973 lua_pushstring(L, "how"); /* 1st argument */ 2081 lua_getglobal(L, "t"); /* global `t' (for later use) */
1974 lua_pushobject(L, lua_getglobal(L, "t")) /* push value of global 't' */ 2082 lua_getglobal(L, "f"); /* function to be called */
1975 lua_pushstring(L, "x"); /* push the string 'x' */ 2083 lua_pushstring(L, "how"); /* 1st argument */
1976 lua_pushobject(L, lua_gettable(L)); /* push result of t.x (2nd arg) */ 2084 lua_pushstring(L, "x"); /* push the string `x' */
1977 lua_pushnumber(L, 4); /* 3rd argument */ 2085 lua_gettable(L, -4); /* push result of t.x (2nd arg) */
1978 lua_callfunction(L, lua_getglobal(L, "f")); /* call `f' */ 2086 lua_pushnumber(L, 4); /* 3rd argument */
1979 lua_pushobject(L, lua_getresult(L, 1)); /* push first result of the call */ 2087 lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */
1980 lua_setglobal(L, "a"); /* set global variable 'a' */ 2088 lua_setglobal(L, "b"); /* set global variable `b' */
1981 lua_pushobject(L, lua_getresult(L, 2)); /* push second result of the call */ 2089 lua_setglobal(L, "a"); /* set global variable `a' */
1982 lua_setglobal(L, "b"); /* set global variable 'b' */ 2090 lua_pop(L, 1); /* remove `t' from the stack */
1983\end{verbatim} 2091\end{verbatim}
2092Notice that the code above is ``balanced'':
2093at its end the stack is back to its original configuration.
2094This is considered good programming practice.
1984 2095
1985Some special Lua functions have direct interfaces. 2096Some special Lua functions have their own C~interfaces.
1986The host program can generate a Lua error calling the function 2097The host program can generate a Lua error calling the function
1987\Deffunc{lua_error} 2098\Deffunc{lua_error}
1988\begin{verbatim} 2099\begin{verbatim}
1989void lua_error (lua_State *L, const char *message); 2100 void lua_error (lua_State *L, const char *message);
1990\end{verbatim} 2101\end{verbatim}
1991This function never returns. 2102This function never returns.
1992If \verb|lua_error| is called from a C~function that has been called from Lua, 2103If \verb|lua_error| is called from a C~function that has been called from Lua,
1993then the corresponding Lua execution terminates, 2104then the corresponding Lua execution terminates,
1994as if an error had occurred inside Lua code. 2105as if an error had occurred inside Lua code.
1995Otherwise, the whole host program terminates with a call to \verb|exit(1)|. 2106Otherwise, the whole host program terminates with a call to
2107\verb|exit(EXIT_FAILURE)|.
1996Before terminating execution, 2108Before terminating execution,
1997the \verb|message| is passed to the error handler function, 2109the \verb|message| is passed to the error handler function,
1998\verb|_ERRORMESSAGE| \see{error}. 2110\verb|_ERRORMESSAGE| \see{error}.
1999If \verb|message| is \verb|NULL|, 2111If \verb|message| is \verb|NULL|,
2000then \verb|_ERRORMESSAGE| is not called. 2112then \verb|_ERRORMESSAGE| is not called.
2001 2113
2002Tag methods can be changed with: \Deffunc{lua_settagmethod} 2114Tag methods can be changed with \Deffunc{lua_settagmethod}
2003\begin{verbatim} 2115\begin{verbatim}
2004lua_Object lua_settagmethod (lua_State *L, int tag, const char *event); 2116 void lua_settagmethod (lua_State *L, int tag, const char *event);
2005\end{verbatim} 2117\end{verbatim}
2006The first parameter is the tag, 2118The second parameter is the tag,
2007and the second is the event name \see{tag-method}; 2119and the third is the event name \see{tag-method};
2008the new method is pushed from C2lua. 2120the new method is popped from the stack,
2009This function returns a \verb|lua_Object|, 2121and the old one is pushed in its place.
2010which is the old tag method value. 2122To just get the current value of a tag method,
2011To get just the current value of a tag method,
2012use the function \Deffunc{lua_gettagmethod} 2123use the function \Deffunc{lua_gettagmethod}
2013\begin{verbatim} 2124\begin{verbatim}
2014lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event); 2125 void lua_gettagmethod (lua_State *L, int tag, const char *event);
2015\end{verbatim} 2126\end{verbatim}
2016 2127
2017It is also possible to copy all tag methods from one tag 2128It is also possible to copy all tag methods from one tag
2018to another: \Deffunc{lua_copytagmethods} 2129to another: \Deffunc{lua_copytagmethods}
2019\begin{verbatim} 2130\begin{verbatim}
2020int lua_copytagmethods (lua_State *L, int tagto, int tagfrom); 2131 int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
2021\end{verbatim} 2132\end{verbatim}
2022This function returns \verb|tagto|. 2133This function returns \verb|tagto|.
2023 2134
2024You can traverse a table with the function \Deffunc{lua_next} 2135You can traverse a table with the function \Deffunc{lua_next}
2025\begin{verbatim} 2136\begin{verbatim}
2026int lua_next (lua_State *L, lua_Object t, int i); 2137 int lua_next (lua_State *L, int index);
2027\end{verbatim} 2138\end{verbatim}
2028Its first argument is the table to be traversed, 2139\verb|index| refers to the table to be traversed.
2029and the second is a \emph{cursor}; 2140The function pops a key from the stack,
2030this cursor starts at 0, 2141and pushes a key-value pair from the table
2031and for each call the function returns a value to 2142(the ``next'' pair after the given key).
2032be used in the next call, 2143If there are no more elements, then the function returns 0
2033or 0 to signal the end of the traversal. 2144(and pushes nothing).
2034The function also returns, in the lua2C array,
2035a key-value pair from the table.
2036A typical traversal looks like this: 2145A typical traversal looks like this:
2037\begin{verbatim} 2146\begin{verbatim}
2038 int i; 2147 /* table is in the stack at index `t' */
2039 lua_Object t; 2148 lua_pushnil(L); /* first key */
2040 ... /* gets the table at `t' */ 2149 while (lua_next(L, t) != 0) {
2041 i = 0; 2150 /* `key' is at index -2 and `value' at index -1 */
2042 lua_beginblock(L); 2151 printf("%s - %s\n", lua_type(L, -2), lua_type(L, -1));
2043 while ((i = lua_next(L, t, i)) != 0) { 2152 lua_pop(L, 1); /* removes `value'; keeps `index' for next iteration */
2044 lua_Object key = lua_getresult(L, 1); 2153 }
2045 lua_Object value = lua_getresult(L, 2); 2154\end{verbatim}
2046 ... /* uses `key' and `value' */ 2155
2047 lua_endblock(L); 2156The function \Deffunc{lua_concat}
2048 lua_beginblock(L); /* reopens a block */ 2157\begin{verbatim}
2049 } 2158 void lua_concat (lua_State *L, int n);
2050 lua_endblock(L); 2159\end{verbatim}
2051\end{verbatim} 2160concatenates the \verb|n| values at the top of the stack,
2052The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the 2161pops them, and leaves the result at the top.
2053results of each iteration from the stack. 2162\verb|n|~must be at least 2.
2054Without them, a traversal of a large table may overflow the stack. 2163Concatenation is done following the usual semantics of Lua
2164\see{concat}.
2055 2165
2056 2166
2057\subsection{Defining C Functions} \label{LuacallC} 2167\subsection{Defining C Functions} \label{LuacallC}
@@ -2059,9 +2169,9 @@ To register a C~function to Lua,
2059there is the following convenience macro: 2169there is the following convenience macro:
2060\Deffunc{lua_register} 2170\Deffunc{lua_register}
2061\begin{verbatim} 2171\begin{verbatim}
2062#define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) 2172 #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
2063/* const char *n; */ 2173 /* const char *n; */
2064/* lua_CFunction f; */ 2174 /* lua_CFunction f; */
2065\end{verbatim} 2175\end{verbatim}
2066which receives the name the function will have in Lua, 2176which receives the name the function will have in Lua,
2067and a pointer to the function. 2177and a pointer to the function.
@@ -2069,110 +2179,142 @@ This pointer must have type \verb|lua_CFunction|,
2069which is defined as 2179which is defined as
2070\Deffunc{lua_CFunction} 2180\Deffunc{lua_CFunction}
2071\begin{verbatim} 2181\begin{verbatim}
2072typedef void (*lua_CFunction) (lua_State *L); 2182 typedef int (*lua_CFunction) (lua_State *L);
2073\end{verbatim} 2183\end{verbatim}
2074that is, a pointer to a function with no results and a single argument, 2184that is, a pointer to a function with integer result and a single argument,
2075a Lua environment. 2185a Lua environment.
2076 2186
2077In order to communicate properly with Lua, 2187In order to communicate properly with Lua,
2078a C~function must follow a protocol, 2188a C~function must follow the following protocol,
2079which defines the way parameters and results are passed. 2189which defines the way parameters and results are passed:
2080 2190A C~function receives its arguments from Lua in the stack,
2081A C~function receives its arguments in structure lua2C; 2191in direct order (first argument is pushed first).
2082to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} 2192To return values to Lua, a C~function just pushes them onto the stack,
2083again just another name for \verb|lua_lua2C|. 2193in direct order,
2084To return values, a C~function just pushes them onto the stack C2lua, 2194%\see{valuesCLua},
2085in direct order \see{valuesCLua}. 2195and returns the number of results.
2086Like a Lua function, a C~function called by Lua can also return 2196Like a Lua function, a C~function called by Lua can also return
2087many results. 2197many results.
2088 2198
2199As an example, the following function receives a variable number
2200of numerical arguments and returns their average and sum:
2201\begin{verbatim}
2202 static int foo (lua_State *L) {
2203 int n = lua_gettop(L); /* number of arguments */
2204 double sum = 0;
2205 int i;
2206 for (i = 1; i <= n; i++) {
2207 if (!lua_isnumber(L, i))
2208 lua_error(L, "incorrect argument to function `foo'");
2209 sum += lua_tonumber(L, i);
2210 }
2211 lua_pushnumber(L, sum/n); /* first result */
2212 lua_pushnumber(L, sum); /* second result */
2213 return 2; /* number of results */
2214 }
2215\end{verbatim}
2216This function may be registered in Lua as \verb|average| by calling
2217\begin{verbatim}
2218 lua_register(L, "average", foo);
2219\end{verbatim}
2220
2221
2089When a C~function is created, 2222When a C~function is created,
2090it is possible to associate some \emph{upvalues} to it 2223it is possible to associate some \emph{upvalues} to it
2091\see{upvalue}, 2224\see{upvalue},
2092thus creating a C closure; 2225thus creating a \IndexEmph{C~closure};
2093these values are passed to the function whenever it is called, 2226these values are passed to the function whenever it is called,
2094as common arguments. 2227as common arguments.
2095To associate upvalues to a C~function, 2228To associate upvalues to a C~function,
2096first these values must be pushed on C2lua. 2229first these values should be pushed onto the stack.
2097Then the function \Deffunc{lua_pushcclosure} 2230Then the function \Deffunc{lua_pushcclosure}
2098\begin{verbatim} 2231\begin{verbatim}
2099void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); 2232 void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
2100\end{verbatim} 2233\end{verbatim}
2101is used to put the C~function on C2lua, 2234is used to push the C~function onto the stack,
2102with the argument \verb|n| telling how many upvalues must be 2235with the argument \verb|n| telling how many upvalues should be
2103associated with the function; 2236associated with the function
2237(these upvalues are popped from the stack);
2104in fact, the macro \verb|lua_pushcfunction| is defined as 2238in fact, the macro \verb|lua_pushcfunction| is defined as
2105\verb|lua_pushcclosure| with \verb|n| set to 0. 2239\verb|lua_pushcclosure| with \verb|n| set to 0.
2106Then, whenever the C~function is called, 2240Then, whenever the C~function is called,
2107these upvalues are inserted as the first arguments \M{n} to the function, 2241these upvalues are inserted as the \emph{last} arguments to the function,
2108before the actual arguments provided in the call. 2242after the actual arguments provided in the call.
2243This makes it easy to get the upvalues without knowing how many arguments
2244the function received (recall that functions in Lua can receive any number of
2245arguments): The \M{i}-th upvalue is in the stack at index \Math{i-n+1},
2246where \M{n} is the number of upvalues.
2109 2247
2110For some examples of C~functions, see files \verb|lstrlib.c|, 2248For more examples of C~functions and closures, see files
2111\verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. 2249\verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c|
2250in the official Lua distribution.
2112 2251
2113\subsection{References to Lua Objects} 2252\subsection{References to Lua Objects}
2114 2253
2115As noted in \See{GC}, \verb|lua_Object|s are volatile. 2254As noted in \See{GC}, Lua values are volatile.
2116If the C code needs to keep a \verb|lua_Object| 2255If the C~code needs to keep a Lua value
2117outside block boundaries, 2256outside the life span of a C~function,
2118then it must create a \Def{reference} to the object. 2257then it must create a \Def{reference} to the value.
2119The routines to manipulate references are the following: 2258The routines to manipulate references are the following:
2120\Deffunc{lua_ref}\Deffunc{lua_pushref} 2259\Deffunc{lua_ref}\Deffunc{lua_getref}
2121\Deffunc{lua_unref} 2260\Deffunc{lua_unref}
2122\begin{verbatim} 2261\begin{verbatim}
2123int lua_ref (lua_State *L, int lock); 2262 int lua_ref (lua_State *L, int lock);
2124int lua_pushref (lua_State *L, int ref); 2263 int lua_getref (lua_State *L, int ref);
2125void lua_unref (lua_State *L, int ref); 2264 void lua_unref (lua_State *L, int ref);
2126\end{verbatim} 2265\end{verbatim}
2127The function \verb|lua_ref| creates a reference 2266
2128to the object that is on the top of the stack, 2267\verb|lua_ref| pops a value from
2268the stack, creates a reference to it,
2129and returns this reference. 2269and returns this reference.
2130For a \nil\ object, 2270For a \nil\ value,
2131the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL} 2271the reference is always \verb|LUA_REFNIL|.\Deffunc{LUA_REFNIL}
2132otherwise, it is a non-negative integer.
2133The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF} 2272The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF}
2134is different from any valid reference. 2273is different from any valid reference.
2135If \verb|lock| is true, then the object is \emph{locked}: 2274If \verb|lock| is true, then the object is \emph{locked}:
2136this means the object will not be garbage collected. 2275this means the object will not be garbage collected.
2137\emph{Unlocked references may be garbage collected}. 2276\emph{Unlocked references may be garbage collected}.
2277
2138Whenever the referenced object is needed in~C, 2278Whenever the referenced object is needed in~C,
2139a call to \verb|lua_pushref| 2279a call to \verb|lua_getref|
2140pushes that object into the C2lua stack; 2280pushes that object onto the stack;
2141if the object has been collected, 2281if the object has been collected,
2142\verb|lua_getref| returns 0 (and does not push anything). 2282\verb|lua_getref| returns 0 (and does not push anything).
2143 2283
2144When a reference is no longer needed, 2284When a reference is no longer needed,
2145it can be released with a call to \verb|lua_unref|. 2285it should be released with a call to \verb|lua_unref|.
2146
2147 2286
2148 2287
2149\section{Predefined Functions and Libraries}
2150 2288
2151The set of \Index{predefined functions} in Lua is small but powerful. 2289\section{Standard Libraries}
2152Most of them provide features that allow some degree of
2153\Index{reflexivity} in the language.
2154Some of these features cannot be simulated with the rest of the
2155language nor with the standard Lua API.
2156Others are just convenient interfaces to common API functions.
2157 2290
2158The libraries, on the other hand, provide useful routines 2291The standard libraries provide useful routines
2159that are implemented directly through the standard API. 2292that are implemented directly through the standard API.
2160Therefore, they are not necessary to the language, 2293Therefore, they are not necessary to the language,
2161and are provided as separate C modules. 2294and are provided as separate C~modules.
2162Currently, there are three standard libraries: 2295Currently, Lua has the following standard libraries:
2163\begin{itemize} 2296\begin{itemize}
2297\item basic library;
2164\item string manipulation; 2298\item string manipulation;
2165\item mathematical functions (sin, log, etc); 2299\item mathematical functions (sin, log, etc);
2166\item input and output (plus some system facilities). 2300\item input and output (plus some system facilities).
2167\end{itemize} 2301\end{itemize}
2168To have access to these libraries, 2302To have access to these libraries,
2169the C host program must call the functions 2303the C~host program must call the functions
2304\verb|lua_baselibopen|,
2170\verb|lua_strlibopen|, \verb|lua_mathlibopen|, 2305\verb|lua_strlibopen|, \verb|lua_mathlibopen|,
2171and \verb|lua_iolibopen|, declared in \verb|lualib.h|. 2306and \verb|lua_iolibopen|, declared in \verb|lualib.h|.
2172\Deffunc{lua_strlibopen}\Deffunc{lua_mathlibopen}\Deffunc{lua_iolibopen} 2307\Deffunc{lua_strlibopen}\Deffunc{lua_mathlibopen}\Deffunc{lua_iolibopen}
2173 2308
2309The basic library provides some core functions to Lua.
2310Therefore, if you do not include this library in your application,
2311you should check carefully whether you need to provide some alternative
2312implementation for some facilities.
2313(For instance, without function \verb|_ERRORMESSAGE|,
2314defined in the basic library, Lua is unable to show error messages.)
2315
2174 2316
2175\subsection{Predefined Functions} \label{predefined} 2317\subsection{Basic Functions} \label{predefined}
2176 2318
2177\subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} 2319\subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert}
2178Prints its only string argument to \IndexVerb{stderr}. 2320Prints its only string argument to \IndexVerb{stderr}.
@@ -2188,12 +2330,12 @@ Issues an \emph{``assertion failed!''} error
2188when its argument \verb|v| is \nil. 2330when its argument \verb|v| is \nil.
2189This function is equivalent to the following Lua function: 2331This function is equivalent to the following Lua function:
2190\begin{verbatim} 2332\begin{verbatim}
2191 function assert (v, m) 2333 function assert (v, m)
2192 if not v then 2334 if not v then
2193 m = m or "" 2335 m = m or ""
2194 error("assertion failed! " .. m) 2336 error("assertion failed! " .. m)
2195 end 2337 end
2196 end 2338 end
2197\end{verbatim} 2339\end{verbatim}
2198 2340
2199\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call} 2341\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call}
@@ -2202,26 +2344,10 @@ Calls function \verb|func| with
2202the arguments given by the table \verb|arg|. 2344the arguments given by the table \verb|arg|.
2203The call is equivalent to 2345The call is equivalent to
2204\begin{verbatim} 2346\begin{verbatim}
2205 func(arg[1], arg[2], ..., arg[n]) 2347 func(arg[1], arg[2], ..., arg[n])
2206\end{verbatim} 2348\end{verbatim}
2207where \verb|n| is the result of \verb|getn(arg)| \see{getn}. 2349where \verb|n| is the result of \verb|getn(arg)| \see{getn}.
2208 2350All results from \verb|func| are simply returned by \verb|call|.
2209By default,
2210all results from \verb|func| are simply returned by \verb|call|.
2211If the string \verb|mode| contains \verb|"p"|,
2212then the results are \emph{packed} in a single table.\index{packed results}
2213That is, \verb|call| returns just one table;
2214at index \verb|n|, the table has the total number of results
2215from the call;
2216the first result is at index 1, etc.
2217For instance, the following calls produce the following results:
2218\begin{verbatim}
2219 a = call(sin, {5}) --> a = 0.0871557 = sin(5)
2220 a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments)
2221 a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1}
2222 t = {x=1}
2223 a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2}
2224\end{verbatim}
2225 2351
2226By default, 2352By default,
2227if an error occurs during the call to \verb|func|, 2353if an error occurs during the call to \verb|func|,
@@ -2289,8 +2415,8 @@ If \verb|message| is \nil, then the error handler is not called.
2289Function \verb|error| never returns. 2415Function \verb|error| never returns.
2290\verb|error| is equivalent to the API function \verb|lua_error|. 2416\verb|error| is equivalent to the API function \verb|lua_error|.
2291 2417
2292\subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach} 2418\subsubsection*{\ff \T{foreach (table, func)}}\Deffunc{foreach}
2293Executes the given \verb|function| over all elements of \verb|table|. 2419Executes the given \verb|func| over all elements of \verb|table|.
2294For each element, the function is called with the index and 2420For each element, the function is called with the index and
2295respective value as arguments. 2421respective value as arguments.
2296If the function returns any non-\nil\ value, 2422If the function returns any non-\nil\ value,
@@ -2299,22 +2425,20 @@ as the final value of \verb|foreach|.
2299 2425
2300This function could be defined in Lua: 2426This function could be defined in Lua:
2301\begin{verbatim} 2427\begin{verbatim}
2302 function foreach (t, f) 2428 function foreach (t, f)
2303 for i, v in t do 2429 for i, v in t do
2304 local res = f(i, v) 2430 local res = f(i, v)
2305 if res then return res end 2431 if res then return res end
2306 end 2432 end
2307 end 2433 end
2308\end{verbatim} 2434\end{verbatim}
2309 2435
2310You may change the \emph{values} of existing 2436The behavior of \verb|foreach| is \emph{undefined} if you change
2311fields in the table during the traversal, 2437the table \verb|_t| during the traversal.
2312but if you create new indices,
2313the semantics of \verb|foreach| is undefined.
2314 2438
2315 2439
2316\subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi} 2440\subsubsection*{\ff \T{foreachi (table, func)}}\Deffunc{foreachi}
2317Executes the given \verb|function| over the 2441Executes the given \verb|func| over the
2318numerical indices of \verb|table|. 2442numerical indices of \verb|table|.
2319For each index, the function is called with the index and 2443For each index, the function is called with the index and
2320respective value as arguments. 2444respective value as arguments.
@@ -2327,18 +2451,14 @@ as the final value of \verb|foreachi|.
2327 2451
2328This function could be defined in Lua: 2452This function could be defined in Lua:
2329\begin{verbatim} 2453\begin{verbatim}
2330 function foreachi (t, f) 2454 function foreachi (t, f)
2331 for i=1,getn(t) do 2455 for i=1,getn(t) do
2332 local res = f(i, t[i]) 2456 local res = f(i, t[i])
2333 if res then return res end 2457 if res then return res end
2334 end 2458 end
2335 end 2459 end
2336\end{verbatim} 2460\end{verbatim}
2337 2461
2338You may change the \emph{values} of existing fields in the
2339table during the traversal,
2340but if you create new indices (even non-numeric),
2341the semantics of \verb|foreachi| is undefined.
2342 2462
2343\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} 2463\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar}
2344This function is obsolete. 2464This function is obsolete.
@@ -2360,14 +2480,14 @@ Otherwise, the size is the largest numerical index with a non-nil
2360value in the table. 2480value in the table.
2361This function could be defined in Lua: 2481This function could be defined in Lua:
2362\begin{verbatim} 2482\begin{verbatim}
2363 function getn (t) 2483 function getn (t)
2364 if type(t.n) == 'number' then return t.n end 2484 if type(t.n) == 'number' then return t.n end
2365 local max = 0 2485 local max = 0
2366 for i, _ in t do 2486 for i, _ in t do
2367 if type(i) == 'number' and i>max then max=i end 2487 if type(i) == 'number' and i>max then max=i end
2368 end 2488 end
2369 return max 2489 return max
2370 end 2490 end
2371\end{verbatim} 2491\end{verbatim}
2372 2492
2373\subsubsection*{\ff \T{gettagmethod (tag, event)}} 2493\subsubsection*{\ff \T{gettagmethod (tag, event)}}
@@ -2375,10 +2495,10 @@ This function could be defined in Lua:
2375Returns the current tag method 2495Returns the current tag method
2376for a given pair \M{(tag, event)}. 2496for a given pair \M{(tag, event)}.
2377 2497
2378\subsubsection*{\ff \T{globals ([newtable])}}\Deffunc{globals} 2498\subsubsection*{\ff \T{globals ([table])}}\Deffunc{globals}
2379Returns the current table of globals. 2499Returns the current table of globals.
2380If the argument \verb|newtable| is given, 2500If the argument \verb|table| is given,
2381set this table as the new table of globals. 2501then it sets this table as the table of globals.
2382 2502
2383\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} 2503\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag}
2384Returns a new tag. 2504Returns a new tag.
@@ -2395,7 +2515,7 @@ When called with \nil\ as its second argument,
2395of the table and its associated value. 2515of the table and its associated value.
2396When called with the last index, 2516When called with the last index,
2397or with \nil\ in an empty table, 2517or with \nil\ in an empty table,
2398it returns \nil. 2518\verb|next| returns \nil.
2399If the second argument is absent, then it is interpreted as \nil. 2519If the second argument is absent, then it is interpreted as \nil.
2400 2520
2401Lua has no declaration of fields; 2521Lua has no declaration of fields;
@@ -2407,10 +2527,8 @@ The order in which the indices are enumerated is not specified,
2407(to traverse a table in numeric order, 2527(to traverse a table in numeric order,
2408use a counter or the function \verb|foreachi|). 2528use a counter or the function \verb|foreachi|).
2409 2529
2410You may change the \emph{values} of existing fields in the 2530The behavior of \verb|next| is \emph{undefined} if you change
2411table during the traversal, 2531the table during the traversal.
2412but if you create new indices,
2413the semantics of \verb|next| is undefined.
2414 2532
2415\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} 2533\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar}
2416This function is obsolete. 2534This function is obsolete.
@@ -2424,25 +2542,18 @@ but only as a quick way to show a value,
2424for instance for debugging. 2542for instance for debugging.
2425See \See{libio} for functions for formatted output. 2543See \See{libio} for functions for formatted output.
2426 2544
2427\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
2428This function is obsolete.
2429Use \verb|rawget(globals(), name)| instead.
2430
2431\subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable}
2432This function was renamed to \verb|rawget|.
2433
2434\subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget} 2545\subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget}
2435Gets the real value of \verb|table[index]|, 2546Gets the real value of \verb|table[index]|,
2436without invoking any tag method. 2547without invoking any tag method.
2437\verb|table| must be a table, 2548\verb|table| must be a table,
2438and \verb|index| is any value different from \nil. 2549and \verb|index| is any value different from \nil.
2439 2550
2440\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} 2551\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
2441This function is obsolete. 2552This function is obsolete.
2442Use \verb|rawset(globals(), name, value)| instead. 2553Use \verb|rawget(globals(), name)| instead.
2443 2554
2444\subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} 2555\subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable}
2445This function was renamed to \verb|rawset|. 2556This function has been renamed to \verb|rawget|.
2446 2557
2447\subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset} 2558\subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset}
2448Sets the real value of \verb|table[index]| to \verb|value|, 2559Sets the real value of \verb|table[index]| to \verb|value|,
@@ -2451,6 +2562,13 @@ without invoking any tag method.
2451\verb|index| is any value different from \nil, 2562\verb|index| is any value different from \nil,
2452and \verb|value| is any Lua value. 2563and \verb|value| is any Lua value.
2453 2564
2565\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
2566This function is obsolete.
2567Use \verb|rawset(globals(), name, value)| instead.
2568
2569\subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable}
2570This function has been renamed to \verb|rawset|.
2571
2454\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} 2572\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal}
2455Sets the named global variable to the given value, 2573Sets the named global variable to the given value,
2456or calls a tag method for ``setglobal''. 2574or calls a tag method for ``setglobal''.
@@ -2529,22 +2647,23 @@ This function also sets or increments the field \verb|n| of the table
2529to \verb|n+1|. 2647to \verb|n+1|.
2530 2648
2531This function is equivalent to the following Lua function, 2649This function is equivalent to the following Lua function,
2532except that the table accesses are all \emph{raw} (that is, without tag methods): 2650except that the table accesses are all \emph{raw}
2533\begin{verbatim} 2651(that is, without tag methods):
2534 function tinsert (t, ...) 2652\begin{verbatim}
2535 local pos, value 2653 function tinsert (t, ...)
2536 local n = getn(t) 2654 local pos, value
2537 if arg.n == 1 then 2655 local n = getn(t)
2538 pos, value = n+1, arg[1] 2656 if arg.n == 1 then
2539 else 2657 pos, value = n+1, arg[1]
2540 pos, value = arg[1], arg[2] 2658 else
2541 end 2659 pos, value = arg[1], arg[2]
2542 t.n = n+1; 2660 end
2543 for i=n,pos,-1 do 2661 t.n = n+1;
2544 t[i+1] = t[i] 2662 for i=n,pos,-1 do
2545 end 2663 t[i+1] = t[i]
2546 t[pos] = value 2664 end
2547 end 2665 t[pos] = value
2666 end
2548\end{verbatim} 2667\end{verbatim}
2549 2668
2550\subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove} 2669\subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove}
@@ -2560,20 +2679,21 @@ This function also sets or decrements the field \verb|n| of the table
2560to \verb|n-1|. 2679to \verb|n-1|.
2561 2680
2562This function is equivalent to the following Lua function, 2681This function is equivalent to the following Lua function,
2563except that the table accesses are all \emph{raw} (that is, without tag methods): 2682except that the table accesses are all \emph{raw}
2564\begin{verbatim} 2683(that is, without tag methods):
2565 function tremove (t, pos) 2684\begin{verbatim}
2566 local n = getn(t) 2685 function tremove (t, pos)
2567 if n<=0 then return end 2686 local n = getn(t)
2568 pos = pos or n 2687 if n<=0 then return end
2569 local value = t[pos] 2688 pos = pos or n
2570 for i=pos,n-1 do 2689 local value = t[pos]
2571 t[i] = t[i+1] 2690 for i=pos,n-1 do
2572 end 2691 t[i] = t[i+1]
2573 t[n] = nil 2692 end
2574 t.n = n-1 2693 t[n] = nil
2575 return value 2694 t.n = n-1
2576 end 2695 return value
2696 end
2577\end{verbatim} 2697\end{verbatim}
2578 2698
2579\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} 2699\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type}
@@ -2592,7 +2712,7 @@ and \verb|"userdata"|.
2592\subsection{String Manipulation} 2712\subsection{String Manipulation}
2593This library provides generic functions for string manipulation, 2713This library provides generic functions for string manipulation,
2594such as finding and extracting substrings and pattern matching. 2714such as finding and extracting substrings and pattern matching.
2595When indexing a string, the first character is at position~1 2715When indexing a string in Lua, the first character is at position~1
2596(not at~0, as in C). 2716(not at~0, as in C).
2597 2717
2598\subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte} 2718\subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte}
@@ -2604,7 +2724,7 @@ absolute value plus 1.
2604Therefore, \Math{-1} points to the last character of \verb|s|. 2724Therefore, \Math{-1} points to the last character of \verb|s|.
2605 2725
2606\NOTE 2726\NOTE
2607\emph{numerical codes are not necessarily portable across platforms}. 2727Numerical codes are not necessarily portable across platforms.
2608 2728
2609\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar} 2729\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar}
2610Receives 0 or more integers. 2730Receives 0 or more integers.
@@ -2613,7 +2733,7 @@ wherein each character has the internal numerical code equal
2613to its correspondent argument. 2733to its correspondent argument.
2614 2734
2615\NOTE 2735\NOTE
2616\emph{numerical codes are not necessarily portable across platforms}. 2736Numerical codes are not necessarily portable across platforms.
2617 2737
2618\subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} 2738\subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}}
2619\Deffunc{strfind} 2739\Deffunc{strfind}
@@ -2638,7 +2758,8 @@ with no characters in \verb|pattern| being considered ``magic''.
2638\subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen} 2758\subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen}
2639Receives a string and returns its length. 2759Receives a string and returns its length.
2640The empty string \verb|""| has length 0. 2760The empty string \verb|""| has length 0.
2641Embedded zeros are counted. 2761Embedded zeros are counted,
2762and so \verb|"a\000b\000c"| has length 5.
2642 2763
2643\subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower} 2764\subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower}
2644Receives a string and returns a copy of that string with all 2765Receives a string and returns a copy of that string with all
@@ -2691,7 +2812,7 @@ and all double quotes, returns, and backslashes in the string
2691are correctly escaped when written. 2812are correctly escaped when written.
2692For instance, the call 2813For instance, the call
2693\begin{verbatim} 2814\begin{verbatim}
2694format('%q', 'a string with "quotes" and \n new line') 2815 format('%q', 'a string with "quotes" and \n new line')
2695\end{verbatim} 2816\end{verbatim}
2696will produce the string: 2817will produce the string:
2697\begin{verbatim} 2818\begin{verbatim}
@@ -2719,8 +2840,8 @@ For example, \verb|"%*g"| can be simulated with
2719\verb|"%"..width.."g"|. 2840\verb|"%"..width.."g"|.
2720 2841
2721\NOTE 2842\NOTE
2722\emph{Neither the format string nor the string values to be formatted with 2843Neither the format string nor the string values to be formatted with
2723\T{format} can contain embedded zeros.} 2844\T{format} can contain embedded zeros.
2724 2845
2725\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} 2846\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}}
2726\Deffunc{gsub} 2847\Deffunc{gsub}
@@ -2749,28 +2870,28 @@ For instance, when \verb|n| is 1 only the first occurrence of
2749 2870
2750Here are some examples: 2871Here are some examples:
2751\begin{verbatim} 2872\begin{verbatim}
2752 x = gsub("hello world", "(%w+)", "%1 %1") 2873 x = gsub("hello world", "(%w+)", "%1 %1")
2753 --> x="hello hello world world" 2874 --> x="hello hello world world"
2754 2875
2755 x = gsub("hello world", "(%w+)", "%1 %1", 1) 2876 x = gsub("hello world", "(%w+)", "%1 %1", 1)
2756 --> x="hello hello world" 2877 --> x="hello hello world"
2757 2878
2758 x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") 2879 x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
2759 --> x="world hello Lua from" 2880 --> x="world hello Lua from"
2760 2881
2761 x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv) 2882 x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
2762 --> x="home = /home/roberto, user = roberto" (for instance) 2883 --> x="home = /home/roberto, user = roberto" (for instance)
2763 2884
2764 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) 2885 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
2765 --> x="4+5 = 9" 2886 --> x="4+5 = 9"
2766 2887
2767 local t = {name="lua", version="4.0"} 2888 local t = {name="lua", version="4.0"}
2768 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) 2889 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
2769 --> x="lua - 4.0" 2890 --> x="lua - 4.0"
2770 2891
2771 t = {n=0} 2892 t = {n=0}
2772 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) 2893 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
2773 --> t={"first", "second", "word"; n=3} 2894 --> t={"first", "second", "word"; n=3}
2774\end{verbatim} 2895\end{verbatim}
2775 2896
2776 2897
@@ -2896,7 +3017,7 @@ Use \verb|%z| instead.}
2896 3017
2897\subsection{Mathematical Functions} \label{mathlib} 3018\subsection{Mathematical Functions} \label{mathlib}
2898 3019
2899This library is an interface to some functions of the standard C math library. 3020This library is an interface to some functions of the standard C~math library.
2900In addition, it registers a tag method for the binary operator \verb|^| that 3021In addition, it registers a tag method for the binary operator \verb|^| that
2901returns \Math{x^y} when applied to numbers \verb|x^y|. 3022returns \Math{x^y} when applied to numbers \verb|x^y|.
2902 3023
@@ -2908,9 +3029,8 @@ The library provides the following functions:
2908\Deffunc{frexp}\Deffunc{ldexp} 3029\Deffunc{frexp}\Deffunc{ldexp}
2909\Deffunc{random}\Deffunc{randomseed} 3030\Deffunc{random}\Deffunc{randomseed}
2910\begin{verbatim} 3031\begin{verbatim}
2911 abs acos asin atan atan2 ceil cos deg floor log log10 3032 abs acos asin atan atan2 ceil cos deg floor log log10
2912 max min mod rad sin sqrt tan frexp ldexp 3033 max min mod rad sin sqrt tan frexp ldexp random randomseed
2913 random randomseed
2914\end{verbatim} 3034\end{verbatim}
2915plus a global variable \IndexVerb{PI}. 3035plus a global variable \IndexVerb{PI}.
2916Most of them 3036Most of them
@@ -2999,15 +3119,14 @@ and restores \verb|stdin| as the value of \verb|_INPUT|.
2999If this function fails, it returns \nil, 3119If this function fails, it returns \nil,
3000plus a string describing the error. 3120plus a string describing the error.
3001 3121
3002\begin{quotation} 3122\NOTE
3003\noindent 3123(system dependency)
3004\emph{System dependent}: if \verb|filename| starts with a \verb-|-, 3124if \verb|filename| starts with a \verb-|-,
3005then a \Index{piped input} is opened, via function \IndexVerb{popen}. 3125then a \Index{piped input} is opened, via function \IndexVerb{popen}.
3006Not all systems implement pipes. 3126Not all systems implement pipes.
3007Moreover, 3127Moreover,
3008the number of files that can be open at the same time is 3128the number of files that can be open at the same time is
3009usually limited and depends on the system. 3129usually limited and depends on the system.
3010\end{quotation}
3011 3130
3012\subsubsection*{\ff \T{writeto (filename)}}\Deffunc{writeto} 3131\subsubsection*{\ff \T{writeto (filename)}}\Deffunc{writeto}
3013 3132
@@ -3027,15 +3146,14 @@ and restores \verb|stdout| as the value of \verb|_OUTPUT|.
3027If this function fails, it returns \nil, 3146If this function fails, it returns \nil,
3028plus a string describing the error. 3147plus a string describing the error.
3029 3148
3030\begin{quotation} 3149\NOTE
3031\noindent 3150(system dependency)
3032\emph{System dependent}: if \verb|filename| starts with a \verb-|-, 3151if \verb|filename| starts with a \verb-|-,
3033then a \Index{piped output} is opened, via function \IndexVerb{popen}. 3152then a \Index{piped input} is opened, via function \IndexVerb{popen}.
3034Not all systems implement pipes. 3153Not all systems implement pipes.
3035Moreover, 3154Moreover,
3036the number of files that can be open at the same time is 3155the number of files that can be open at the same time is
3037usually limited and depends on the system. 3156usually limited and depends on the system.
3038\end{quotation}
3039 3157
3040\subsubsection*{\ff \T{appendto (filename)}}\Deffunc{appendto} 3158\subsubsection*{\ff \T{appendto (filename)}}\Deffunc{appendto}
3041 3159
@@ -3138,6 +3256,13 @@ use \verb|tostring| or \verb|format| before \verb|write|.
3138If this function fails, it returns \nil, 3256If this function fails, it returns \nil,
3139plus a string describing the error. 3257plus a string describing the error.
3140 3258
3259\subsection{System Facilities} \label{libiosys}
3260
3261\subsubsection*{\ff \T{clock ()}}\Deffunc{clock}
3262
3263Returns an approximation of the amount of CPU time
3264used by the program, in seconds.
3265
3141\subsubsection*{\ff \T{date ([format])}}\Deffunc{date} 3266\subsubsection*{\ff \T{date ([format])}}\Deffunc{date}
3142 3267
3143Returns a string containing date and time 3268Returns a string containing date and time
@@ -3147,10 +3272,11 @@ When called without arguments,
3147it returns a reasonable date and time representation that depends on 3272it returns a reasonable date and time representation that depends on
3148the host system and on the current locale. 3273the host system and on the current locale.
3149 3274
3150\subsubsection*{\ff \T{clock ()}}\Deffunc{clock} 3275\subsubsection*{\ff \T{execute (command)}}\Deffunc{execute}
3151 3276
3152Returns an approximation of the amount of CPU time 3277This function is equivalent to the C~function \verb|system|.
3153used by the program, in seconds. 3278It passes \verb|command| to be executed by an operating system shell.
3279It returns a status code, which is system-dependent.
3154 3280
3155\subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit} 3281\subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit}
3156 3282
@@ -3164,12 +3290,6 @@ The default value for \verb|code| is the success code.
3164Returns the value of the process environment variable \verb|varname|, 3290Returns the value of the process environment variable \verb|varname|,
3165or \nil\ if the variable is not defined. 3291or \nil\ if the variable is not defined.
3166 3292
3167\subsubsection*{\ff \T{execute (command)}}\Deffunc{execute}
3168
3169This function is equivalent to the C~function \verb|system|.
3170It passes \verb|command| to be executed by an operating system shell.
3171It returns a status code, which is system-dependent.
3172
3173\subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} 3293\subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale}
3174 3294
3175This function is an interface to the ANSI~C function \verb|setlocale|. 3295This function is an interface to the ANSI~C function \verb|setlocale|.
@@ -3190,15 +3310,14 @@ by means of functions and \emph{hooks},
3190which allows the construction of different 3310which allows the construction of different
3191kinds of debuggers, profilers, and other tools 3311kinds of debuggers, profilers, and other tools
3192that need ``inside information'' from the interpreter. 3312that need ``inside information'' from the interpreter.
3193This interface is declared in the header file \verb|luadebug.h|, 3313This interface is declared in \verb|luadebug.h|.
3194and has \emph{no} single-state variant.
3195 3314
3196\subsection{Stack and Function Information} 3315\subsection{Stack and Function Information}
3197 3316
3198\Deffunc{lua_getstack} 3317\Deffunc{lua_getstack}
3199The main function to get information about the interpreter stack is 3318The main function to get information about the interpreter stack is
3200\begin{verbatim} 3319\begin{verbatim}
3201int lua_getstack (lua_State *L, int level, lua_Debug *ar); 3320 int lua_getstack (lua_State *L, int level, lua_Debug *ar);
3202\end{verbatim} 3321\end{verbatim}
3203It fills parts of a \verb|lua_Debug| structure with 3322It fills parts of a \verb|lua_Debug| structure with
3204an identification of the \emph{activation record} 3323an identification of the \emph{activation record}
@@ -3210,29 +3329,30 @@ when called with a level greater than the stack depth,
3210it returns 0. 3329it returns 0.
3211 3330
3212\Deffunc{lua_Debug} 3331\Deffunc{lua_Debug}
3213The structure \verb|lua_Debug| is used to carry different pieces of information 3332The structure \verb|lua_Debug| is used to carry different pieces of
3214about an active function: 3333information about an active function:
3215\begin{verbatim} 3334\begin{verbatim}
3216typedef struct lua_Debug { 3335 typedef struct lua_Debug {
3217 const char *event; /* "call", "return" */ 3336 const char *event; /* "call", "return" */
3218 const char *source; /* (S) */ 3337 int currentline; /* (l) */
3219 int linedefined; /* (S) */ 3338 const char *name; /* (n) */
3220 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ 3339 const char *namewhat; /* (n) global, tag method, local, field */
3221 int currentline; /* (l) */ 3340 int nups; /* (u) number of upvalues */
3222 const char *name; /* (n) */ 3341 int linedefined; /* (S) */
3223 const char *namewhat; /* (n) global, tag method, local, field */ 3342 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */
3224 int nups; /* (u) number of upvalues */ 3343 const char *source; /* (S) */
3225 lua_Object func; /* (f) function being executed */ 3344 char short_src[LUA_IDSIZE]; /* (S) */
3226 /* private part */ 3345
3227 ... 3346 /* private part */
3228} lua_Debug; 3347 ...
3229\end{verbatim} 3348 } lua_Debug;
3230The \verb|lua_getstack| function fills only the private part 3349\end{verbatim}
3350\verb|lua_getstack| fills only the private part
3231of this structure, for future use. 3351of this structure, for future use.
3232To fill in the other fields of \verb|lua_Debug| with useful information, 3352To fill in the other fields of \verb|lua_Debug| with useful information,
3233call \Deffunc{lua_getinfo} 3353call \Deffunc{lua_getinfo}
3234\begin{verbatim} 3354\begin{verbatim}
3235int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); 3355 int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
3236\end{verbatim} 3356\end{verbatim}
3237This function returns 0 on error 3357This function returns 0 on error
3238(e.g., an invalid option in \verb|what|). 3358(e.g., an invalid option in \verb|what|).
@@ -3242,19 +3362,20 @@ as indicated by the letter in parentheses in the definition of \verb|lua_Debug|:
3242An \verb|S| fills in the fields \verb|source|, \verb|linedefined|, 3362An \verb|S| fills in the fields \verb|source|, \verb|linedefined|,
3243and \verb|what|; 3363and \verb|what|;
3244\verb|l| fills in the field \verb|currentline|, etc. 3364\verb|l| fills in the field \verb|currentline|, etc.
3365Moreover, character \verb|f| pushes onto the stack the function that is
3366running at the given level.
3245 3367
3246To get information about a function that is not active (that is, 3368To get information about a function that is not active (that is,
3247it is not in the stack), 3369it is not in the stack),
3248you set the \verb|func| field of the \verb|lua_Debug| structure 3370you push the function onto the stack,
3249with the function,
3250and start the \verb|what| string with the character \verb|>|. 3371and start the \verb|what| string with the character \verb|>|.
3251For instance, to know in which line a function \verb|f| was defined, 3372For instance, to know in which line a function \verb|f| was defined,
3252you can write 3373you can write
3253\begin{verbatim} 3374\begin{verbatim}
3254 lua_Debug ar; 3375 lua_Debug ar;
3255 ar.func = lua_getglobal(L, "f"); 3376 lua_getglobal(L, "f");
3256 lua_getinfo(L, ">S", &ar); 3377 lua_getinfo(L, ">S", &ar);
3257 printf("%d\n", ar.linedefined); 3378 printf("%d\n", ar.linedefined);
3258\end{verbatim} 3379\end{verbatim}
3259 3380
3260The fields of \verb|lua_Debug| have the following meaning: 3381The fields of \verb|lua_Debug| have the following meaning:
@@ -3266,6 +3387,9 @@ If the function was defined in a string,
3266if the function was defined in a file, 3387if the function was defined in a file,
3267\verb|source| starts with a \verb|@| followed by the file name. 3388\verb|source| starts with a \verb|@| followed by the file name.
3268 3389
3390\item[short_src]
3391A ``printable'' version of \verb|source|, to be used in error messages.
3392
3269\item[linedefined] 3393\item[linedefined]
3270the line number where the definition of the function starts. 3394the line number where the definition of the function starts.
3271 3395
@@ -3304,60 +3428,51 @@ otherwise \verb|namewhat| is \verb|""| (the empty string).
3304\item[nups] 3428\item[nups]
3305Number of upvalues of a function. 3429Number of upvalues of a function.
3306 3430
3307\item[func]
3308The function being executed, as a \verb|lua_Object|.
3309
3310\end{description} 3431\end{description}
3311 3432
3312 3433
3313\subsection{Manipulating Local Variables} 3434\subsection{Manipulating Local Variables}
3314 3435
3315For the manipulation of local variables, 3436For the manipulation of local variables,
3316\verb|luadebug.h| defines the following record: 3437\verb|luadebug.h| uses indices:
3317\begin{verbatim} 3438The first parameter has index 1, and so on,
3318struct lua_Localvar { 3439until the last active local variable.
3319 int index;
3320 const char *name;
3321 lua_Object value;
3322};
3323\end{verbatim}
3324where \verb|index| is an index for local variables
3325(the first parameter has index 1, and so on,
3326until the last active local variable).
3327 3440
3328\Deffunc{lua_getlocal}\Deffunc{lua_setlocal} 3441\Deffunc{lua_getlocal}\Deffunc{lua_setlocal}
3329The following functions allow the manipulation of the 3442The following functions allow the manipulation of the
3330local variables of a given activation record. 3443local variables of a given activation record.
3331\begin{verbatim} 3444\begin{verbatim}
3332int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); 3445 const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
3333int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); 3446 const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
3334\end{verbatim} 3447\end{verbatim}
3335The parameter \verb|ar| must be a valid activation record, 3448The parameter \verb|ar| must be a valid activation record,
3336filled by a previous call to \verb|lua_getstack| or 3449filled by a previous call to \verb|lua_getstack| or
3337given as argument to a hook \see{sub-hooks}. 3450given as argument to a hook \see{sub-hooks}.
3338To use \verb|lua_getlocal|, 3451Function \verb|lua_getlocal| gets the index of a local variable
3339you fill the \verb|index| field of \verb|v| with the index 3452(\verb|n|), pushes its value onto the stack,
3340of a local variable; then the function fills the fields 3453and returns its name.
3341\verb|name| and \verb|value| with the name and the current
3342value of that variable.
3343For \verb|lua_setlocal|, 3454For \verb|lua_setlocal|,
3344you fill the \verb|index| and the \verb|value| fields of \verb|v|, 3455you push the new value onto the stack,
3345and the function assigns that value to the variable. 3456and the function assigns that value to the variable and returns its name.
3346Both functions return 0 on failure; 3457Both functions return NULL on failure;
3347that happens if the index is greater than the number of active local variables. 3458that happens if the index is greater than
3459the number of active local variables.
3348 3460
3349As an example, the following function lists the names of all 3461As an example, the following function lists the names of all
3350local variables for a function in a given level of the stack: 3462local variables for a function in a given level of the stack:
3351\begin{verbatim} 3463\begin{verbatim}
3352int listvars (lua_State *L, int level) { 3464 int listvars (lua_State *L, int level) {
3353 lua_Debug ar; 3465 lua_Debug ar;
3354 lua_Localvar v; 3466 int i = 1;
3355 if (lua_getstack(L, level, &ar) == 0) 3467 const char *name;
3356 return 0; /* failure: no such level on the stack */ 3468 if (lua_getstack(L, level, &ar) == 0)
3357 for (v.index = 1; lua_getlocal(L, &ar, &v); v.index++) 3469 return 0; /* failure: no such level in the stack */
3358 printf("%s\n", v.name); 3470 while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
3359 return 1; 3471 printf("%s\n", name);
3360} 3472 lua_pop(L, 1); /* remove variable value */
3473 }
3474 return 1;
3475 }
3361\end{verbatim} 3476\end{verbatim}
3362 3477
3363 3478
@@ -3367,13 +3482,13 @@ The Lua interpreter offers two hooks for debugging purposes:
3367a \emph{call} hook and a \emph{line} hook. 3482a \emph{call} hook and a \emph{line} hook.
3368Both have the same type, 3483Both have the same type,
3369\begin{verbatim} 3484\begin{verbatim}
3370typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); 3485 typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
3371\end{verbatim} 3486\end{verbatim}
3372and you can set them with the following functions: 3487and you can set them with the following functions:
3373\Deffunc{lua_Hook}\Deffunc{lua_setcallhook}\Deffunc{lua_setlinehook} 3488\Deffunc{lua_Hook}\Deffunc{lua_setcallhook}\Deffunc{lua_setlinehook}
3374\begin{verbatim} 3489\begin{verbatim}
3375lua_Hook lua_setcallhook (lua_State *L, lua_Hook func); 3490 lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
3376lua_Hook lua_setlinehook (lua_State *L, lua_Hook func); 3491 lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
3377\end{verbatim} 3492\end{verbatim}
3378A hook is disabled when its value is \verb|NULL|, 3493A hook is disabled when its value is \verb|NULL|,
3379which is the initial value of both hooks. 3494which is the initial value of both hooks.
@@ -3496,14 +3611,14 @@ this function turns off line hooks.
3496\section{\Index{Lua Stand-alone}} \label{lua-sa} 3611\section{\Index{Lua Stand-alone}} \label{lua-sa}
3497 3612
3498Although Lua has been designed as an extension language, 3613Although Lua has been designed as an extension language,
3499the language is frequently used as a stand-alone interpreter. 3614it is frequently used as a stand-alone language.
3500An implementation of such an interpreter, 3615An interpreter for Lua as a stand-alone language,
3501called simply \verb|lua|, 3616called simply \verb|lua|,
3502is provided with the standard distribution. 3617is provided with the standard distribution.
3503 3618
3504This program can be called with any sequence of the following arguments: 3619This program can be called with any sequence of the following arguments:
3505\begin{description} 3620\begin{description}\leftskip=20pt
3506\item[\T{-}] executes \verb|stdin| as a file; 3621\item[\T{-} ] executes \verb|stdin| as a file;
3507\item[\T{-c}] calls \verb|lua_close| after running all arguments; 3622\item[\T{-c}] calls \verb|lua_close| after running all arguments;
3508\item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; 3623\item[\T{-e} \rm\emph{stat}] executes string \verb|stat|;
3509\item[\T{-f filename}] executes file \verb|filename| with the 3624\item[\T{-f filename}] executes file \verb|filename| with the
@@ -3518,49 +3633,54 @@ When called without arguments,
3518Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, 3633Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
3519and as \verb|lua -| otherwise. 3634and as \verb|lua -| otherwise.
3520 3635
3521All arguments are handled in order. 3636All arguments are handled in order, except \verb|-c|.
3522For instance, an invocation like 3637For instance, an invocation like
3523\begin{verbatim} 3638\begin{verbatim}
3524$ lua -i a=test prog.lua 3639 $ lua -i a=test prog.lua
3525\end{verbatim} 3640\end{verbatim}
3526will first interact with the user until an \verb|EOF| in \verb|stdin|, 3641will first interact with the user until an \verb|EOF| in \verb|stdin|,
3527then will set \verb|a| to \verb|"test"|, 3642then will set \verb|a| to \verb|"test"|,
3528and finally will run the file \verb|prog.lua|. 3643and finally will run the file \verb|prog.lua|.
3644(Here,
3645\verb|$| is the shell prompt. Your prompt may be different.)
3529 3646
3530When the option \T{-f filename} is used, 3647When the option \T{-f filename} is used,
3531all following arguments from the command line 3648all remaining arguments in the command line
3532are passed to the Lua program in a table called \verb|arg|. 3649are passed to the Lua program in a table called \verb|arg|.
3533The field \verb|n| gets the index of the last argument, 3650In this table,
3651the field \verb|n| gets the index of the last argument,
3534and the field 0 gets the \T{filename}. 3652and the field 0 gets the \T{filename}.
3535For instance, in the call 3653For instance, in the call
3536\begin{verbatim} 3654\begin{verbatim}
3537$ lua a.lua -f b.lua t1 t3 3655 $ lua a.lua -f b.lua t1 t3
3538\end{verbatim} 3656\end{verbatim}
3539the interpreter first runs the file \T{a.lua}, 3657the interpreter first runs the file \T{a.lua},
3540then creates a table \T{arg}, 3658then creates a table \T{arg},
3541\begin{verbatim} 3659\begin{verbatim}
3542 arg = {"t1", "t3"; n = 2, [0] = "b.lua"} 3660 arg = {"t1", "t3"; n = 2, [0] = "b.lua"}
3543\end{verbatim} 3661\end{verbatim}
3544and then runs the file \T{b.lua}. 3662and then runs the file \T{b.lua}.
3663\Deffunc{getargs}
3545The stand-alone interpreter also provides a \verb|getargs| function that 3664The stand-alone interpreter also provides a \verb|getargs| function that
3546can be used to access \emph{all} command line arguments. 3665can be used to access \emph{all} command line arguments.
3547For instance, if you call Lua with the line 3666For instance, if you call Lua with the line
3548\begin{verbatim} 3667\begin{verbatim}
3549> lua -d a b 3668 $ lua -c a b
3550\end{verbatim} 3669\end{verbatim}
3551and the file \verb|a| (or \verb|b|) calls \verb|getargs|, 3670and the file \verb|a| (or \verb|b|) calls \verb|getargs|,
3552the call will return the table 3671the call will return the table
3553\verb|{[0] = "lua", [1] = "-d", [2] = "a", [3] = "b", n = 3}|. 3672\begin{verbatim}
3554\Deffunc{getargs} 3673 {[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3}
3674\end{verbatim}
3555 3675
3556In interactive mode, 3676In interactive mode,
3557a multi-line statement can be written finishing intermediate 3677a multi-line statement can be written finishing intermediate
3558lines with a backslash (\verb|\|). 3678lines with a backslash (`\verb|\|').
3559If the global variable \verb|_PROMPT| is defined as a string, 3679If the global variable \verb|_PROMPT| is defined as a string,
3560its value is used as the prompt. \index{_PROMPT} 3680then its value is used as the prompt. \index{_PROMPT}
3561Therefore, the prompt can be changed like below: 3681Therefore, the prompt can be changed directly on the command line:
3562\begin{verbatim} 3682\begin{verbatim}
3563$ lua _PROMPT='myprompt> ' -i 3683 $ lua _PROMPT='myprompt> ' -i
3564\end{verbatim} 3684\end{verbatim}
3565 3685
3566In Unix systems, Lua scripts can be made into executable programs 3686In Unix systems, Lua scripts can be made into executable programs
@@ -3582,21 +3702,25 @@ Lua means ``moon'' in Portuguese.
3582\appendix 3702\appendix
3583 3703
3584\section*{Incompatibilities with Previous Versions} 3704\section*{Incompatibilities with Previous Versions}
3705\addcontentsline{toc}{section}{Incompatibilities with Previous Versions}
3585 3706
3586Although great care has been taken to avoid incompatibilities with 3707Lua 4.0 is a major revision of the language.
3708We took a great care to avoid incompatibilities with
3587the previous public versions of Lua, 3709the previous public versions of Lua,
3588some differences had to be introduced. 3710some differences had to be introduced.
3589Here is a list of all these incompatibilities. 3711Here is a list of all these incompatibilities.
3590 3712
3713
3591\subsection*{Incompatibilities with \Index{version 3.2}} 3714\subsection*{Incompatibilities with \Index{version 3.2}}
3592 3715
3593\subsubsection*{Changes in the Language} 3716\subsubsection*{Changes in the Language}
3594\begin{itemize} 3717\begin{itemize}
3595 3718
3596\item 3719\item
3597All pragmas (\verb|$debug|, \verb|$if|, \ldots) are deprecated. 3720All pragmas (\verb|$debug|, \verb|$if|, \ldots) have been removed.
3598 3721
3599\item \rwd{for}, \rwd{break}, and \rwd{in} now are reserved words. 3722\item
3723\rwd{for}, \rwd{break}, and \rwd{in} now are reserved words.
3600 3724
3601\item 3725\item
3602Garbage-collection tag methods for tables is now deprecated. 3726Garbage-collection tag methods for tables is now deprecated.
@@ -3607,8 +3731,8 @@ There is now only one tag method for order operators.
3607\item 3731\item
3608In nested function calls like \verb|f(g(x))| 3732In nested function calls like \verb|f(g(x))|
3609\emph{all} return values from \verb|g| are passed as arguments to \verb|f|. 3733\emph{all} return values from \verb|g| are passed as arguments to \verb|f|.
3610(This only happens when \verb|g| is the last 3734This only happens when \verb|g| is the last
3611[or the only] argument to \verb|f|.) 3735or the only argument to \verb|f|.
3612 3736
3613\item 3737\item
3614The pre-compiler may assume that some operators are associative, 3738The pre-compiler may assume that some operators are associative,
@@ -3625,22 +3749,30 @@ have non-associative tag methods.
3625\begin{itemize} 3749\begin{itemize}
3626 3750
3627\item 3751\item
3752When traversing a table with \verb|next| or \verb|foreach|,
3753the table cannot be modified in any way.
3754
3755\item
3628General read patterns are now deprecated. 3756General read patterns are now deprecated.
3629 3757
3630\item 3758\item
3631The functions \verb|rawgettable| and \verb|rawsettable| 3759The functions \verb|rawgettable| and \verb|rawsettable|
3632were renamed to \verb|rawget| and \verb|rawset|. 3760have been renamed to \verb|rawget| and \verb|rawset|.
3633 3761
3634\item 3762\item
3635The functions \verb|foreachvar|, \verb|nextvar|, 3763The functions \verb|foreachvar|, \verb|nextvar|,
3636\verb|rawsetglobal|, and \verb|rawgetglobal| are deprecated. 3764\verb|rawsetglobal|, and \verb|rawgetglobal| are deprecated.
3637You can get their functionality using table operations 3765You can get their functionality using table operations
3638over the table of globals. 3766over the table of globals,
3767which is returned by \verb|globals|.
3639 3768
3640\item 3769\item
3641\verb|setglobal| and \verb|sort| no longer return a value; 3770\verb|setglobal| and \verb|sort| no longer return a value;
3642\verb|type| no longer returns a second value. 3771\verb|type| no longer returns a second value.
3643 3772
3773\item
3774The \verb|p| option in function \verb|call| is deprecated.
3775
3644\end{itemize} 3776\end{itemize}
3645 3777
3646 3778
@@ -3648,42 +3780,35 @@ over the table of globals.
3648\begin{itemize} 3780\begin{itemize}
3649 3781
3650\item 3782\item
3651The whole API is now reentrant, 3783The API has been completely rewritten:
3652which means that all functions have 3784It is now fully reentrant and much clearer.
3653an extra first argument, a Lua state.
3654You can still use the old format:
3655If you define \verb|LUA_SINGLESTATE| before including \verb|lua.h|,
3656all functions from the old API are defined as macros.
3657You will also have to define a variable
3658\begin{verbatim}
3659lua_State *lua_state = NULL;
3660\end{verbatim}
3661somewhere in your program.
3662 3785
3663\item 3786\item
3664The debug API has been completely rewritten. 3787The debug API has been completely rewritten.
3665 3788
3666\item 3789%\item
3667A \verb|const| qualifier has been added to \verb|char *| 3790%A \verb|const| qualifier has been added to \verb|char*|
3668in all API functions that handle C~strings. 3791%in all API functions that handle C~strings.
3669 3792%
3670\item 3793%\item
3671Some types \verb|long| were changed to \verb|size_t|. 3794%Some variables of type \verb|long| were changed to \verb|size_t|.
3672 3795%
3673\item 3796%\item
3674\verb|luaL_openlib| no longer automatically calls \verb|lua_open|. 3797%\verb|luaL_openlib| no longer automatically calls \verb|lua_open|.
3675So, 3798%So,
3676you must now explicitly call \verb|lua_open| before opening 3799%you must now explicitly call \verb|lua_open| before opening
3677the standard libraries. 3800%the standard libraries.
3678 3801%
3679\item 3802%\item
3680\verb|lua_type| now returns a string describing the type, 3803%\verb|lua_type| now returns a string describing the type,
3681and is no longer a synonym for \verb|lua_tag|. 3804%and is no longer a synonym for \verb|lua_tag|.
3682 3805
3683\end{itemize} 3806\end{itemize}
3684 3807
3685%{=============================================================== 3808%{===============================================================
3686\section*{The complete syntax of Lua} 3809\section*{The Complete Syntax of Lua} \label{BNF}
3810
3811\addcontentsline{toc}{section}{The complete syntax of Lua}
3687 3812
3688\renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} 3813\renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent}
3689 3814
@@ -3803,8 +3928,8 @@ and is no longer a synonym for \verb|lua_tag|.
3803 3928
3804\newcommand{\indexentry}[2]{\item {#1} #2} 3929\newcommand{\indexentry}[2]{\item {#1} #2}
3805\begin{theindex} 3930\begin{theindex}
3931\addcontentsline{toc}{section}{Index}
3806\input{manual.id} 3932\input{manual.id}
3807\end{theindex} 3933\end{theindex}
3808 3934
3809
3810\end{document} 3935\end{document}