aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-04-14 14:47:55 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-04-14 14:47:55 -0300
commit4e90768635d696c3c4d4fefb900c9cd5237f9cc3 (patch)
tree8b95c9fddc9b364066fe800d9d167b7f372f1ff9
parentc1666a13e3cc7aa853a513bc0d739849caf75106 (diff)
downloadlua-4e90768635d696c3c4d4fefb900c9cd5237f9cc3.tar.gz
lua-4e90768635d696c3c4d4fefb900c9cd5237f9cc3.tar.bz2
lua-4e90768635d696c3c4d4fefb900c9cd5237f9cc3.zip
lots of changes (almost ready for 4.0)
-rw-r--r--manual.tex1141
1 files changed, 650 insertions, 491 deletions
diff --git a/manual.tex b/manual.tex
index ba9af4ff..f0fb75df 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.33 1999/05/27 20:21:03 roberto Exp roberto $ 1% $Id: manual.tex,v 1.34 1999/10/04 17:51:04 roberto Exp roberto $
2 2
3\documentclass[11pt]{article} 3\documentclass[11pt]{article}
4\usepackage{fullpage,bnf} 4\usepackage{fullpage,bnf}
@@ -21,7 +21,7 @@
21 21
22\newcommand{\ff}{$\bullet$\ } 22\newcommand{\ff}{$\bullet$\ }
23 23
24\newcommand{\Version}{3.2} 24\newcommand{\Version}{4.0}
25 25
26\makeindex 26\makeindex
27 27
@@ -41,7 +41,7 @@ Waldemar Celes
41\tecgraf\ --- Computer Science Department --- PUC-Rio 41\tecgraf\ --- Computer Science Department --- PUC-Rio
42} 42}
43 43
44\date{{\small \tt\$Date: 1999/05/27 20:21:03 $ $}} 44\date{{\small \tt\$Date: 1999/10/04 17:51:04 $ $}}
45 45
46\maketitle 46\maketitle
47 47
@@ -55,9 +55,9 @@ but also frequently used as a general-purpose, stand-alone language.
55Lua combines simple procedural syntax (similar to Pascal) 55Lua combines simple procedural syntax (similar to Pascal)
56with powerful data description constructs based on associative 56with powerful data description constructs based on associative
57arrays and extensible semantics. 57arrays and extensible semantics.
58Lua is dynamically typed, interpreted from bytecodes, 58Lua is dynamically typed, interpreted from opcodes,
59and has automatic memory management with garbage collection, 59and has automatic memory management with garbage collection,
60making it ideal for configuration, scripting, and rapid prototyping. 60making it ideal for configuration, scripting, and rapid prototyping.
61 61
62This document describes version \Version\ of the Lua programming language 62This document describes version \Version\ of the Lua programming language
63and the API that allows interaction between Lua programs and their 63and the API that allows interaction between Lua programs and their
@@ -75,8 +75,8 @@ e que \'e tamb\'em frequentemente usada como uma linguagem de
75prop\'osito geral. 75prop\'osito geral.
76Lua combina uma sintaxe procedural simples (similar a Pascal) 76Lua combina uma sintaxe procedural simples (similar a Pascal)
77com poderosas facilidades para descri\c{c}\~ao de dados baseadas 77com poderosas facilidades para descri\c{c}\~ao de dados baseadas
78em tabelas associativas e uma sem\^antica estens\'{\i}vel. 78em tabelas associativas e uma sem\^antica estens\'{\i}vel.
79Lua tem tipagem din\^amica, \'e interpretada via bytecodes, 79Lua tem tipagem din\^amica, \'e interpretada via opcodes,
80e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo, 80e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo,
81tornando-se ideal para configura\c{c}\~ao, scripting, 81tornando-se ideal para configura\c{c}\~ao, scripting,
82e prototipagem r\'apida. 82e prototipagem r\'apida.
@@ -92,7 +92,7 @@ a intera\c{c}\~ao entre programas Lua e programas C hospedeiros.
92\parskip=10pt 92\parskip=10pt
93\noindent 93\noindent
94\footnotesize 94\footnotesize
95Copyright \copyright\ 1994--1999 TeCGraf, PUC-Rio. All rights reserved. 95Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved.
96 96
97\noindent 97\noindent
98Permission is hereby granted, without written agreement and without license 98Permission is hereby granted, without written agreement and without license
@@ -121,13 +121,13 @@ incidental, or consequential damages arising out of the use of this software
121and its documentation. 121and its documentation.
122 122
123\noindent 123\noindent
124The Lua language and this implementation have been entirely designed and 124The Lua language and this implementation have been entirely designed and
125written by Waldemar Celes, Roberto Ierusalimschy and Luiz Henrique de 125written by Waldemar Celes, Roberto Ierusalimschy and Luiz Henrique de
126Figueiredo at TeCGraf, PUC-Rio. 126Figueiredo at TeCGraf, PUC-Rio.
127 127
128\noindent 128\noindent
129This implementation contains no third-party code. 129This implementation contains no third-party code.
130\end{quotation} 130\end{quotation}
131 131
132\newpage 132\newpage
133 133
@@ -173,7 +173,7 @@ at the following URL's:
173All statements in Lua are executed in a \Def{global environment}. 173All statements in Lua are executed in a \Def{global environment}.
174This environment, which keeps all global variables, 174This environment, which keeps all global variables,
175is initialized with a call from the embedding program to 175is initialized with a call from the embedding program to
176\verb|lua_open| and 176\verb|lua_newstate| and
177persists until a call to \verb|lua_close|, 177persists until a call to \verb|lua_close|,
178or the end of the embedding program. 178or the end of the embedding program.
179Optionally, a user can create multiple independent global 179Optionally, a user can create multiple independent global
@@ -231,7 +231,7 @@ while \emph{string} has the usual meaning.
231Lua is \Index{eight-bit clean}, 231Lua is \Index{eight-bit clean},
232and so strings may contain any 8-bit character, 232and so strings may contain any 8-bit character,
233\emph{including} embedded zeros (\verb|'\0'|). 233\emph{including} embedded zeros (\verb|'\0'|).
234The function \verb|type| returns a string describing the type 234The \verb|type| function returns a string describing the type
235of a given value \see{pdf-type}. 235of a given value \see{pdf-type}.
236 236
237Functions are considered first-class values in Lua. 237Functions are considered first-class values in Lua.
@@ -243,6 +243,8 @@ They can be distinguished by their tags:
243all Lua functions have the same tag, 243all Lua functions have the same tag,
244and all C functions have the same tag, 244and all C functions have the same tag,
245which is different from the tag of Lua functions. 245which is different from the tag of Lua functions.
246The \verb|tag| function returns the tag
247of a given value \see{pdf-tag}.
246 248
247The type \emph{userdata} is provided to allow 249The type \emph{userdata} is provided to allow
248arbitrary \Index{C pointers} to be stored in Lua variables. 250arbitrary \Index{C pointers} to be stored in Lua variables.
@@ -261,7 +263,7 @@ Tables are the main data structuring mechanism in Lua.
261To represent \Index{records}, Lua uses the field name as an index. 263To represent \Index{records}, Lua uses the field name as an index.
262The language supports this representation by 264The language supports this representation by
263providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. 265providing \verb|a.name| as syntactic sugar for \verb|a["name"]|.
264Tables may also carry methods. 266Tables may also carry methods:
265Because functions are first class values, 267Because functions are first class values,
266table fields may contain functions. 268table fields may contain functions.
267The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, 269The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
@@ -275,7 +277,7 @@ to tables, and do not imply any kind of copy.
275Moreover, tables must be explicitly created before used 277Moreover, tables must be explicitly created before used
276\see{tableconstructor}. 278\see{tableconstructor}.
277 279
278Tags are mainly used to select tag methods when 280Tags are mainly used to select \emph{tag methods} when
279some events occur. 281some events occur.
280Tag methods are the main mechanism for extending the 282Tag methods are the main mechanism for extending the
281semantics of Lua \see{tag-method}. 283semantics of Lua \see{tag-method}.
@@ -284,8 +286,8 @@ All values of each of these types have this same pre-defined tag.
284Values of type \M{function} can have two different tags, 286Values of type \M{function} can have two different tags,
285depending on whether they are Lua functions or C functions. 287depending on whether they are Lua functions or C functions.
286Finally, 288Finally,
287values of type \M{userdata} and \M{table} can have 289values of type \M{userdata} and \M{table} have
288as many different tags as needed \see{tag-method}. 290variable tags, assigned by the program \see{tag-method}.
289Tags are created with the function \verb|newtag|, 291Tags are created with the function \verb|newtag|,
290and the function \verb|tag| returns the tag of a given value. 292and the function \verb|tag| returns the tag of a given value.
291To change the tag of a given table, 293To change the tag of a given table,
@@ -308,16 +310,18 @@ can be used in an identifier.
308The following words are reserved, and cannot be used as identifiers: 310The following words are reserved, and cannot be used as identifiers:
309\index{reserved words} 311\index{reserved words}
310\begin{verbatim} 312\begin{verbatim}
311 and do else elseif 313 and break do else
312 end function if local 314 elseif end for function
313 nil not or repeat 315 if local nil not
314 return then until while 316 or repeat return then
317 until while
315\end{verbatim} 318\end{verbatim}
316Lua is a case-sensitive language: 319Lua is a case-sensitive language:
317\T{and} is a reserved word, but \T{And} and \T{\'and} 320\T{and} is a reserved word, but \T{And} and \T{\'and}
318(if the locale permits) are two other different identifiers. 321(if the locale permits) are two other different identifiers.
319As a convention, identifiers starting with underscore followed by 322As a convention, identifiers starting with underscore followed by
320uppercase letters are reserved for internal variables. 323uppercase letters (such as \verb|_INPUT|)
324are reserved for internal variables.
321 325
322The following strings denote other \Index{tokens}: 326The following strings denote other \Index{tokens}:
323\begin{verbatim} 327\begin{verbatim}
@@ -330,17 +334,19 @@ and can contain the C-like escape sequences
330\verb|'\a'| (bell), 334\verb|'\a'| (bell),
331\verb|'\b'| (backspace), 335\verb|'\b'| (backspace),
332\verb|'\f'| (form feed), 336\verb|'\f'| (form feed),
333\verb|'\n'| (new line), 337\verb|'\n'| (newline),
334\verb|'\r'| (carriage return), 338\verb|'\r'| (carriage return),
335\verb|'\t'| (horizontal tab), 339\verb|'\t'| (horizontal tab),
336\verb|'\v'| (vertical tab), 340\verb|'\v'| (vertical tab),
337\verb|'\\'|, (backslash), 341\verb|'\\'|, (backslash),
338\verb|'\"'|, (double quote), 342\verb|'\"'|, (double quote),
339and \verb|'\''| (single quote). 343\verb|'\''| (single quote),
344and \verb|'\\n'| (that is, a backslash followed by a real newline,
345which results in a newline in the string).
340A character in a string may also be specified by its numerical value, 346A character in a string may also be specified by its numerical value,
341through the escape sequence \verb|'\ddd'|, 347through the escape sequence \verb|'\ddd'|,
342where \verb|ddd| is a sequence of up to three \emph{decimal} digits. 348where \verb|ddd| is a sequence of up to three \emph{decimal} digits.
343Strings in Lua may contain any 8-bit value, including embedded 0. 349Strings in Lua may contain any 8-bit value, including embedded zeros.
344 350
345Literal strings can also be delimited by matching \verb|[[ ... ]]|. 351Literal strings can also be delimited by matching \verb|[[ ... ]]|.
346Literals in this bracketed form may run for several lines, 352Literals in this bracketed form may run for several lines,
@@ -399,7 +405,7 @@ A \M{cond} part may be
399\begin{description} 405\begin{description}
400\item[\T{nil}] --- always false. 406\item[\T{nil}] --- always false.
401\item[\T{1}] --- always true. 407\item[\T{1}] --- always true.
402\item[\M{name}] --- true if the value of the 408\item[\T{\M{name}}] --- true if the value of the
403global variable \M{name} is different from \nil. 409global variable \M{name} is different from \nil.
404Note that \M{name} is evaluated \emph{before} the chunk starts its execution. 410Note that \M{name} is evaluated \emph{before} the chunk starts its execution.
405Therefore, actions in a chunk do not affect its own conditional directives. 411Therefore, actions in a chunk do not affect its own conditional directives.
@@ -445,20 +451,27 @@ and local variable declarations \see{localvar}.
445 451
446\subsubsection{Blocks} 452\subsubsection{Blocks}
447A \Index{block} is a list of statements, which are executed sequentially. 453A \Index{block} is a list of statements, which are executed sequentially.
448A statement may be optionally followed by a semicolon: 454A statement may be have an optional label,
455and can be optionally followed by a semicolon:
449\begin{Produc} 456\begin{Produc}
450\produc{block}{\rep{stat sc} \opt{ret}} 457\produc{block}{\opt{label} \rep{stat sc}}
451\produc{sc}{\opt{\ter{;}}} 458\produc{sc}{\opt{\ter{;}}}
459\produc{label}{\ter{|} name \ter{|}}
452\end{Produc}% 460\end{Produc}%
453For syntactic reasons, a \IndexVerb{return} statement can only be written 461For syntactic reasons, \rwd{return} and
462\rwd{break} statements can only be written
454as the last statement of a block. 463as the last statement of a block.
455This restriction also avoids some ``statement not reached'' conditions.
456 464
457A block may be explicitly delimited: 465A block may be explicitly delimited:
458\begin{Produc} 466\begin{Produc}
459\produc{stat}{\rwd{do} block \rwd{end}} 467\produc{stat}{\rwd{do} block \rwd{end}}
460\end{Produc}% 468\end{Produc}%
461This is useful to control the scope of local variables \see{localvar}. 469This is useful to control the scope of local variables \see{localvar},
470and to add a \rwd{return} or a \rwd{break} statement in the middle
471of another block:
472\begin{verbatim}
473 do return end -- return is the last statement in this block
474\end{verbatim}
462 475
463\subsubsection{\Index{Assignment}} \label{assignment} 476\subsubsection{\Index{Assignment}} \label{assignment}
464The language allows \Index{multiple assignment}. 477The language allows \Index{multiple assignment}.
@@ -526,14 +539,66 @@ only \nil\ is considered false.
526 \opt{\rwd{else} block} \rwd{end}} 539 \opt{\rwd{else} block} \rwd{end}}
527\end{Produc} 540\end{Produc}
528 541
529A \T{return} is used to return values from a function or from a chunk. 542\index{return}
543A \rwd{return} is used to return values from a function or from a chunk.
530\label{return} 544\label{return}
531Because they may return more than one value, 545Because they may return more than one value,
532the syntax for a \Index{return statement} is 546the syntax for a \Index{return statement} is
533\begin{Produc} 547\begin{Produc}
534\produc{ret}{\rwd{return} \opt{explist1} \opt{sc}} 548\produc{stat}{\rwd{return} \opt{explist1}}
535\end{Produc} 549\end{Produc}
536 550
551\index{break}
552A \rwd{break} statement can be used to terminate the execution of a block,
553skipping to the next instruction after the block.
554\begin{Produc}
555\produc{stat}{\rwd{break} \opt{name}}
556\end{Produc}
557A \rwd{break} without a label ends the inner enclosing loop
558(while, repeat, or for).
559A \rwd{break} with a label breaks the inner enclosing
560statement with that label.
561
562For syntactic reasons, \rwd{return} and \rwd{break}
563statements can only be written as the last statement of a block.
564
565\subsubsection{For Statement} \label{for}\index{for}
566
567The \rwd{for} statement has the following syntax:
568\begin{Produc}
569\produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
570 \rwd{do} block \rwd{end}}
571\end{Produc}
572A \rwd{for} statement like
573\begin{verbatim}
574for var=e1,e2,e3 do block end
575\end{verbatim}
576is equivalent to the following code:
577\begin{verbatim}
578do
579 local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
580 if not (var and _limit and _step) then error() end
581 while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do
582 block
583 var = var+_step
584 end
585end
586\end{verbatim}
587Notice the following:
588\begin{itemize}
589\item \verb|_limit| and \verb|_step| are invisible variables.
590\item The behavior is undefined if you assign to \verb|var| inside
591the block.
592\item If the third expression (the step) is absent, it defaults to 1.
593\item Both the limit and the step are evaluated only once,
594before the loop starts.
595\item The variable \verb|var| is local to the statement;
596you cannot use its value after the \rwd{for}.
597\item You can use \rwd{break} to exit a \rwd{for}.
598If you need the value of the index,
599assign it to another variable before breaking.
600\end{itemize}
601
537\subsubsection{Function Calls as Statements} \label{funcstat} 602\subsubsection{Function Calls as Statements} \label{funcstat}
538Because of possible side-effects, 603Because of possible side-effects,
539function calls can be executed as statements: 604function calls can be executed as statements:
@@ -561,7 +626,7 @@ Otherwise, all variables are initialized with \nil.
561\subsection{\Index{Expressions}} 626\subsection{\Index{Expressions}}
562 627
563\subsubsection{\Index{Basic Expressions}} 628\subsubsection{\Index{Basic Expressions}}
564Basic expressions are 629The basic expressions in Lua are
565\begin{Produc} 630\begin{Produc}
566\produc{exp}{\ter{(} exp \ter{)}} 631\produc{exp}{\ter{(} exp \ter{)}}
567\produc{exp}{\rwd{nil}} 632\produc{exp}{\rwd{nil}}
@@ -623,10 +688,11 @@ Equality first compares the tags of its operands.
623If they are different, then the result is \nil. 688If they are different, then the result is \nil.
624Otherwise, their values are compared. 689Otherwise, their values are compared.
625Numbers and strings are compared in the usual way. 690Numbers and strings are compared in the usual way.
626Tables, userdata and functions are compared by reference, 691Tables, userdata, and functions are compared by reference,
627that is, two tables are considered equal only if they are the same table. 692that is, two tables are considered equal only if they are the same table.
628The operator \verb|~=| is exactly the negation of equality (\verb|==|). 693The operator \verb|~=| is exactly the negation of equality (\verb|==|).
629Note that the conversion rules of \See{coercion} 694
695The conversion rules of \See{coercion}
630\emph{do not} apply to equality comparisons. 696\emph{do not} apply to equality comparisons.
631Thus, \verb|"0"==0| evaluates to false, 697Thus, \verb|"0"==0| evaluates to false,
632and \verb|t[0]| and \verb|t["0"]| denote different 698and \verb|t[0]| and \verb|t["0"]| denote different
@@ -636,7 +702,7 @@ The other operators work as follows.
636If both arguments are numbers, then they are compared as such. 702If both arguments are numbers, then they are compared as such.
637Otherwise, if both arguments are strings, 703Otherwise, if both arguments are strings,
638then their values are compared using lexicographical order. 704then their values are compared using lexicographical order.
639Otherwise, the ``order'' tag method is called \see{tag-method}. 705Otherwise, the \verb|"lt"| tag method is called \see{tag-method}.
640 706
641\subsubsection{Logical Operators} 707\subsubsection{Logical Operators}
642The \Index{logical operators} are 708The \Index{logical operators} are
@@ -655,13 +721,20 @@ Both \verb|and| and \verb|or| use \Index{short-cut evaluation},
655that is, 721that is,
656the second operand is evaluated only when necessary. 722the second operand is evaluated only when necessary.
657 723
658A useful Lua idiom is \verb|x = x or v|, 724There are two useful Lua idioms with logical operators.
725The first is \verb|x = x or v|,
659which is equivalent to 726which is equivalent to
660\begin{verbatim} 727\begin{verbatim}
661 if x == nil then x = v end 728 if x == nil then x = v end
662\end{verbatim} 729\end{verbatim}
663i.e., it sets \verb|x| to a default value \verb|v| when 730i.e., it sets \verb|x| to a default value \verb|v| when
664\verb|x| is not set. 731\verb|x| is not set.
732The other is \verb|x = a and b or c|,
733which is equivalent to
734\begin{verbatim}
735 if a then x = b else x = c end
736\end{verbatim}
737provided that \verb|b| is not \nil.
665 738
666\subsubsection{Concatenation} 739\subsubsection{Concatenation}
667The string \Index{concatenation} operator in Lua is 740The string \Index{concatenation} operator in Lua is
@@ -685,6 +758,11 @@ from the lower to the higher priority:
685All binary operators are left associative, 758All binary operators are left associative,
686except for \verb|^| (exponentiation), 759except for \verb|^| (exponentiation),
687which is right associative. 760which is right associative.
761The pre-compiler may rearrange the order of evaluation of
762associative operators (such as \verb|..| or \verb|+|),
763as long as these optimizations do not change normal results.
764However, they may change some results if you define non-associative
765tag methods for these operators.
688 766
689\subsubsection{Table Constructors} \label{tableconstructor} 767\subsubsection{Table Constructors} \label{tableconstructor}
690Table \Index{constructors} are expressions that create tables; 768Table \Index{constructors} are expressions that create tables;
@@ -767,9 +845,9 @@ then this function is called,
767with the given arguments. 845with the given arguments.
768Otherwise, the ``function'' tag method is called, 846Otherwise, the ``function'' tag method is called,
769having as first parameter the value of \M{simpleexp}, 847having as first parameter the value of \M{simpleexp},
770and then the original call parameters. 848and then the original call arguments.
771 849
772The form: 850The form
773\begin{Produc} 851\begin{Produc}
774\produc{functioncall}{simpleexp \ter{:} name args} 852\produc{functioncall}{simpleexp \ter{:} name args}
775\end{Produc}% 853\end{Produc}%
@@ -786,7 +864,7 @@ Arguments have the following syntax:
786\produc{args}{\ter{(} \opt{explist1} \ter{)}} 864\produc{args}{\ter{(} \opt{explist1} \ter{)}}
787\produc{args}{tableconstructor} 865\produc{args}{tableconstructor}
788\produc{args}{\ter{literal}} 866\produc{args}{\ter{literal}}
789\produc{explist1}{exp1 \rep{\ter{,} exp1}} 867\produc{explist1}{\rep{exp1 \ter{,}} exp}
790\end{Produc}% 868\end{Produc}%
791All argument expressions are evaluated before the call. 869All argument expressions are evaluated before the call.
792A call of the form \verb|f{...}| is syntactic sugar for 870A call of the form \verb|f{...}| is syntactic sugar for
@@ -810,12 +888,14 @@ thus discarding all returned values but the first one.
810If the function is called in a place that can hold many values 888If the function is called in a place that can hold many values
811(syntactically denoted by the non-terminal \M{exp}), 889(syntactically denoted by the non-terminal \M{exp}),
812then no adjustment is made. 890then no adjustment is made.
813Note that the only place that can hold many values 891The only places that can hold many values
814is the last (or the only) expression in an assignment 892is the last (or the only) expression in an assignment,
815or in a return statement; see examples below. 893in an argument list, or in a return statement;
894see examples below.
816\begin{verbatim} 895\begin{verbatim}
817 f(); -- adjusted to 0 896 f(); -- adjusted to 0
818 g(x, f()); -- f() is adjusted to 1 897 g(f(), x); -- f() is adjusted to 1 result
898 g(x, f()); -- g gets x plus all values returned by f()
819 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) 899 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
820 a,b,c = x, f(); -- f() is adjusted to 2 900 a,b,c = x, f(); -- f() is adjusted to 2
821 a,b,c = f(); -- f() is adjusted to 3 901 a,b,c = f(); -- f() is adjusted to 3
@@ -844,6 +924,18 @@ is just syntactic sugar for
844 ... 924 ...
845 end 925 end
846\end{verbatim} 926\end{verbatim}
927and
928\begin{verbatim}
929 function o.f (...)
930 ...
931 end
932\end{verbatim}
933is syntactic sugar for
934\begin{verbatim}
935 o.f = function (...)
936 ...
937 end
938\end{verbatim}
847 939
848A function definition is an executable expression, 940A function definition is an executable expression,
849whose value has type \emph{function}. 941whose value has type \emph{function}.
@@ -851,10 +943,10 @@ When Lua pre-compiles a chunk,
851all its function bodies are pre-compiled, too. 943all its function bodies are pre-compiled, too.
852Then, whenever Lua executes the function definition, 944Then, whenever Lua executes the function definition,
853its upvalues are fixed \see{upvalue}, 945its upvalues are fixed \see{upvalue},
854and the function is \emph{instantiated} (or ``closed''). 946and the function is \emph{instantiated} (or \emph{closed}).
855This function instance (or ``closure'') 947This function instance (or \emph{closure})
856is the final value of the expression. 948is the final value of the expression.
857Different instances of a same function 949Different instances of the same function
858may have different upvalues. 950may have different upvalues.
859 951
860Parameters act as local variables, 952Parameters act as local variables,
@@ -874,12 +966,13 @@ instead, it collects any extra arguments into an implicit parameter,
874called \IndexVerb{arg}. 966called \IndexVerb{arg}.
875This parameter is always initialized as a table, 967This parameter is always initialized as a table,
876with a field \verb|n| whose value is the number of extra arguments, 968with a field \verb|n| whose value is the number of extra arguments,
877and the extra arguments at positions 1,~2,~\ldots 969and the extra arguments at positions 1,~2,~\ldots.
878 970
879As an example, suppose definitions like: 971As an example, suppose definitions like:
880\begin{verbatim} 972\begin{verbatim}
881 function f(a, b) end 973 function f(a, b) end
882 function g(a, b, ...) end 974 function g(a, b, ...) end
975 function r() return 1,2,3 end
883\end{verbatim} 976\end{verbatim}
884Then, we have the following mapping from arguments to parameters: 977Then, we have the following mapping from arguments to parameters:
885\begin{verbatim} 978\begin{verbatim}
@@ -888,10 +981,13 @@ Then, we have the following mapping from arguments to parameters:
888 f(3) a=3, b=nil 981 f(3) a=3, b=nil
889 f(3, 4) a=3, b=4 982 f(3, 4) a=3, b=4
890 f(3, 4, 5) a=3, b=4 983 f(3, 4, 5) a=3, b=4
984 f(r(), 10) a=1, b=10
985 f(r()) a=1, b=2
891 986
892 g(3) a=3, b=nil, arg={n=0} 987 g(3) a=3, b=nil, arg={n=0}
893 g(3, 4) a=3, b=4, arg={n=0} 988 g(3, 4) a=3, b=4, arg={n=0}
894 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} 989 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
990 g(5, r()) a=5, b=1, arg={2, 3; n=2}
895\end{verbatim} 991\end{verbatim}
896 992
897Results are returned using the \verb|return| statement \see{return}. 993Results are returned using the \verb|return| statement \see{return}.
@@ -925,7 +1021,7 @@ previously initialized with a table value.
925\index{Visibility} \index{Upvalues} 1021\index{Visibility} \index{Upvalues}
926 1022
927A function body may refer to its own local variables 1023A function body may refer to its own local variables
928(which includes its parameters) and to global variables, 1024(which include its parameters) and to global variables,
929as long as they are not shadowed by local 1025as long as they are not shadowed by local
930variables from enclosing functions. 1026variables from enclosing functions.
931A function \emph{cannot} access a local 1027A function \emph{cannot} access a local
@@ -989,7 +1085,7 @@ identified by the given names.
989The semantics of tag methods is better explained by a Lua function 1085The semantics of tag methods is better explained by a Lua function
990describing the behavior of the interpreter at each event. 1086describing the behavior of the interpreter at each event.
991The function not only shows when a tag method is called, 1087The function not only shows when a tag method is called,
992but also its arguments, its results and the default behavior. 1088but also its arguments, its results, and the default behavior.
993Please notice that the code shown here is only illustrative; 1089Please notice that the code shown here is only illustrative;
994the real behavior is hard coded in the interpreter, 1090the real behavior is hard coded in the interpreter,
995and it is much more efficient than this simulation. 1091and it is much more efficient than this simulation.
@@ -1084,8 +1180,9 @@ called when an unary \verb|-| operation is applied to a non numerical operand.
1084\end{verbatim} 1180\end{verbatim}
1085 1181
1086\item[``lt'':]\index{lt event} 1182\item[``lt'':]\index{lt event}
1087called when a \verb|<| operation is applied to non numerical 1183called when an order operation is applied to non-numerical
1088or non string operands. 1184or non-string operands.
1185It corresponds to the \verb|<| operator.
1089\begin{verbatim} 1186\begin{verbatim}
1090 function lt_event (op1, op2) 1187 function lt_event (op1, op2)
1091 if type(op1) == "number" and type(op2) == "number" then 1188 if type(op1) == "number" and type(op2) == "number" then
@@ -1102,21 +1199,13 @@ or non string operands.
1102 end 1199 end
1103 end 1200 end
1104\end{verbatim} 1201\end{verbatim}
1105 1202The other order operators use this tag method according to the
1106\item[``gt'':]\index{gt event} 1203usual equivalences:
1107called when a \verb|>| operation is applied to non numerical 1204\begin{verbatim}
1108or non string operands. 1205 a>b <=> b<a
1109Behavior similar to the \verb|"lt"| event. 1206 a<=b <=> not (b<a)
1110 1207 a>=b <=> not (a<b)
1111\item[``le'':]\index{le event} 1208\end{verbatim}
1112called when a \verb|<=| operation is applied to non numerical
1113or non string operands.
1114Behavior similar to the \verb|"lt"| event.
1115
1116\item[``ge'':]\index{ge event}
1117called when a \verb|>=| operation is applied to non numerical
1118or non string operands.
1119Behavior similar to the \verb|"lt"| event.
1120 1209
1121\item[``concat'':]\index{concatenation event} 1210\item[``concat'':]\index{concatenation event}
1122called when a concatenation is applied to non string operands. 1211called when a concatenation is applied to non string operands.
@@ -1167,9 +1256,9 @@ userdata with default tags.
1167 local oldvalue = rawgetglobal(varname) 1256 local oldvalue = rawgetglobal(varname)
1168 local tm = gettagmethod(tag(oldvalue), "setglobal") 1257 local tm = gettagmethod(tag(oldvalue), "setglobal")
1169 if not tm then 1258 if not tm then
1170 return rawsetglobal(varname, newvalue) 1259 rawsetglobal(varname, newvalue)
1171 else 1260 else
1172 return tm(varname, oldvalue, newvalue) 1261 tm(varname, oldvalue, newvalue)
1173 end 1262 end
1174 end 1263 end
1175\end{verbatim} 1264\end{verbatim}
@@ -1238,10 +1327,10 @@ called when Lua tries to call a non function value.
1238\end{verbatim} 1327\end{verbatim}
1239 1328
1240\item[``gc'':]\index{gc event} 1329\item[``gc'':]\index{gc event}
1241called when Lua is ``garbage collecting'' an object. 1330called when Lua is ``garbage collecting'' an userdata.
1242This method cannot be set for strings, numbers, functions, 1331This tag method can be set only from C,
1243and userdata with default tag. 1332and cannot be set for an userdata with default tag.
1244For each object to be collected, 1333For each userdata to be collected,
1245Lua does the equivalent of the following function: 1334Lua does the equivalent of the following function:
1246\begin{verbatim} 1335\begin{verbatim}
1247 function gc_event (obj) 1336 function gc_event (obj)
@@ -1285,7 +1374,7 @@ To provide more information about errors,
1285Lua programs should include the compilation pragma \verb|$debug|. 1374Lua programs should include the compilation pragma \verb|$debug|.
1286\index{debug pragma}\label{pragma} 1375\index{debug pragma}\label{pragma}
1287When an error occurs in a chunk compiled with this option, 1376When an error occurs in a chunk compiled with this option,
1288the I/O error routine is able to print the number of the 1377the I/O error-message routine is able to print the number of the
1289lines where the calls (and the error) were made. 1378lines where the calls (and the error) were made.
1290 1379
1291Lua code can explicitly generate an error by calling the built-in 1380Lua code can explicitly generate an error by calling the built-in
@@ -1307,84 +1396,118 @@ The API functions can be classified in the following categories:
1307\item executing Lua code; 1396\item executing Lua code;
1308\item manipulating (reading and writing) Lua objects; 1397\item manipulating (reading and writing) Lua objects;
1309\item calling Lua functions; 1398\item calling Lua functions;
1310\item C functions to be called by Lua; 1399\item defining C functions to be called by Lua;
1311\item manipulating references to Lua Objects. 1400\item manipulating references to Lua Objects.
1312\end{enumerate} 1401\end{enumerate}
1313All API functions and related types and constants 1402All API functions and related types and constants
1314are declared in the header file \verb|lua.h|. 1403are declared in the header file \verb|lua.h|.
1315 1404
1316\subsection{Managing States} \label{mangstate} 1405Even when we use the term \emph{function},
1406\emph{any facility in the API may be provided as a macro instead}.
1407Any of such macros uses once and only once each of its arguments.
1408
1409
1410\subsection{States} \label{mangstate}
1411
1412The Lua library is reentrant.
1413It does not have any global variable.
1317The whole state of the Lua interpreter 1414The whole state of the Lua interpreter
1318(global variables, stack, tag methods, etc) 1415(global variables, stack, tag methods, etc)
1319is stored in a dynamic structure pointed by\Deffunc{lua_state} 1416is stored in a dynamic structure \Deffunc{lua_State};
1320\begin{verbatim} 1417this state must be passed as the first argument to almost
1321typedef struct lua_State lua_State; 1418every function in the library.
1322extern lua_State *lua_state;
1323\end{verbatim}
1324The variable \verb|lua_state| is the only C global variable in
1325the Lua library.
1326 1419
1327Before calling any API function, 1420Before calling any API function,
1328this state must be initialized. 1421you must create a state.
1329This is done by calling\Deffunc{lua_open} 1422This is done by calling\Deffunc{lua_newstate}
1330\begin{verbatim} 1423\begin{verbatim}
1331void lua_open (void); 1424lua_State *lua_newstate (const char *s, ...);
1332\end{verbatim} 1425\end{verbatim}
1333This function allocates and initializes some internal structures, 1426The arguments to this function is a list of name-value options,
1334and defines all pre-defined functions of Lua. 1427terminated with \verb|NULL|.
1335If \verb|lua_state| is already different from \verb|NULL|, 1428Currently, the function accepts the following options:
1336\verb|lua_open| has no effect; 1429\begin{itemize}
1337therefore, it is safe to call this function multiple times. 1430\item \verb|"stack"| - the stack size.
1338All standard libraries call \verb|lua_open| when they are opened. 1431Each function call needs one stack position for each local variable
1339 1432and temporary variables, plus one position.
1340Function \verb|lua_setstate| is used to change the current state 1433The stack must also have at least ten positions available.
1341of Lua:\Deffunc{lua_setstate} 1434For very small implementations, without recursive functions,
1435a size of 100 should be enough.
1436The default is 1K.
1437
1438\item \verb|"builtin"| - the value is a boolean (0 or 1) that
1439indicates whether the predefined functions should be loaded or not.
1440The default is to load those functions.
1441\end{itemize}
1442For instance, the call
1342\begin{verbatim} 1443\begin{verbatim}
1343lua_State *lua_setstate (lua_State *st); 1444lua_State *L = lua_newstate(NULL);
1344\end{verbatim} 1445\end{verbatim}
1345It sets \verb|lua_state| to \verb|st| and returns the old state. 1446creates a new state with a stack of 1K positions,
1346 1447and with the predefined functions loaded;
1347Multiple, independent states may be created. 1448the call
1348For that, you must set \verb|lua_state| back to \verb|NULL| before
1349calling \verb|lua_open|.
1350An easy way to do that is defining an auxiliary function:
1351\begin{verbatim} 1449\begin{verbatim}
1352 lua_State *lua_newstate (void) { 1450lua_State *L = lua_newstate("builtin", 0, "stack", 100, NULL);
1353 lua_State *old = lua_setstate(NULL);
1354 lua_open();
1355 return lua_setstate(old);
1356 }
1357\end{verbatim} 1451\end{verbatim}
1358This function creates a new state without changing the current state 1452creates a new state with a stack of 100 positions,
1359of the interpreter. 1453without the predefined functions.
1360Note that any new state is created with all predefined functions,
1361but any additional library (such as the standard libraries) must be
1362explicitly open in the new state, if needed.
1363 1454
1364If necessary, a state may be released by calling\Deffunc{lua_close} 1455To release a state, you call
1365\begin{verbatim} 1456\begin{verbatim}
1366void lua_close (void); 1457void lua_close (lua_State *L);
1367\end{verbatim} 1458\end{verbatim}
1368This function destroys all objects in the current Lua environment 1459This function destroys all objects in the current Lua environment
1369(calling the correspondent garbage collector tag methods), 1460(calling the correspondent garbage collector tag methods),
1370frees all dynamic memory used by the state, 1461and frees all dynamic memory used by the state.
1371and then sets \verb|lua_state| to \verb|NULL|. 1462Frequently, you do not need to call this function,
1372Usually, there is no need to call this function, 1463because these resources are naturally released when the program ends.
1373since these resources are naturally released when the program ends. 1464
1374If \verb|lua_state| is already \verb|NULL|, 1465With the exception of \verb|lua_newstate|,
1375\verb|lua_close| has no effect. 1466all functions in the API get at its first argument a state.
1467However, most applications use a single state.
1468To avoid the burden of passing this only state explicitly to all
1469functions, and also to keep compatibility with old versions of Lua,
1470the API provides a set of macros and one global variable that
1471take care of this state argument for single-state applications:
1472\begin{verbatim}
1473extern lua_State *lua_state;
1474\end{verbatim}
1475\begin{verbatim}
1476#define lua_close() (lua_close)(lua_state)
1477#define lua_dofile(filename) (lua_dofile)(lua_state, filename)
1478#define lua_dostring(str) (lua_dostring)(lua_state, str)
1479 ...
1480\end{verbatim}
1481For each function in the API, there is a macro with the same name
1482that supplies \verb|lua_state| as the first argument to the call.
1483(The parentheses around the function name is to avoid it being expanded
1484again as a macro.)
1485The only exception is \verb|lua_newstate|;
1486in this case, the corresponding macro is
1487\begin{verbatim}
1488#define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0))))
1489\end{verbatim}
1490It checks whether the global state has been initialized;
1491if not, it then creates a new state with default settings and
1492assigns it to \verb|lua_newstate|.
1376 1493
1377If you are using multiple states, 1494By default, those macros are all active.
1378you may find useful to define the following function, 1495If you will use multiple states,
1379which releases a given state: 1496and therefore will want to provide the state
1497argument explicitly for each call,
1498you should define \IndexVerb{LUA_REENTRANT} before
1499including \verb|lua.h| in your code:
1380\begin{verbatim} 1500\begin{verbatim}
1381 void lua_freestate (lua_State *st) { 1501#define LUA_REENTRANT
1382 lua_State *old = lua_setstate(st); 1502#include "lua.h"
1383 lua_close();
1384 if (old != st) lua_setstate(old);
1385 }
1386\end{verbatim} 1503\end{verbatim}
1387 1504
1505In the sequel, we will show all functions in the single-state form
1506(therefore, they are actually macros).
1507When you define \verb|LUA_REENTRANT|,
1508all of them get a state as the first parameter.
1509
1510
1388\subsection{Exchanging Values between C and Lua} \label{valuesCLua} 1511\subsection{Exchanging Values between C and Lua} \label{valuesCLua}
1389Because Lua has no static type system, 1512Because Lua has no static type system,
1390all values passed between Lua and C have type 1513all values passed between Lua and C have type
@@ -1392,13 +1515,19 @@ all values passed between Lua and C have type
1392which works like an abstract type in C that can hold any Lua value. 1515which works like an abstract type in C that can hold any Lua value.
1393Values of type \verb|lua_Object| have no meaning outside Lua; 1516Values of type \verb|lua_Object| have no meaning outside Lua;
1394for instance, 1517for instance,
1395the comparison of two \verb|lua_Object's| is undefined. 1518you cannot compare two \verb|lua_Object's| directly.
1519Instead, you should use the next function:
1520\Deffunc{lua_equal}
1521\begin{verbatim}
1522int lua_equal (lua_Object o1, lua_Object o2);
1523\end{verbatim}
1396 1524
1397To check the type of a \verb|lua_Object|, 1525To check the type of a \verb|lua_Object|,
1398the following functions are available: 1526the following functions are available:
1399\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} 1527\Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring}
1400\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} 1528\Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata}
1401\Deffunc{lua_isfunction} 1529\Deffunc{lua_isfunction}
1530\Deffunc{lua_type}
1402\begin{verbatim} 1531\begin{verbatim}
1403int lua_isnil (lua_Object object); 1532int lua_isnil (lua_Object object);
1404int lua_isnumber (lua_Object object); 1533int lua_isnumber (lua_Object object);
@@ -1407,13 +1536,21 @@ int lua_istable (lua_Object object);
1407int lua_isfunction (lua_Object object); 1536int lua_isfunction (lua_Object object);
1408int lua_iscfunction (lua_Object object); 1537int lua_iscfunction (lua_Object object);
1409int lua_isuserdata (lua_Object object); 1538int lua_isuserdata (lua_Object object);
1539const char *lua_type (lua_Object obj);
1410\end{verbatim} 1540\end{verbatim}
1411These functions return 1 if the object is compatible with the given type, 1541The \verb|lua_is*| functions return 1 if the object is compatible
1412and 0 otherwise. 1542with the given type, and 0 otherwise.
1413The function \verb|lua_isnumber| accepts numbers and numerical strings, 1543The function \verb|lua_isnumber| accepts numbers and numerical strings,
1414whereas
1415\verb|lua_isstring| accepts strings and numbers \see{coercion}, 1544\verb|lua_isstring| accepts strings and numbers \see{coercion},
1416and \verb|lua_isfunction| accepts Lua functions and C functions. 1545and \verb|lua_isfunction| accepts Lua functions and C functions.
1546To distinguish between Lua functions and C functions,
1547you should use \verb|lua_iscfunction|.
1548To distinguish between numbers and numerical strings,
1549you can use \verb|lua_type|.
1550The \verb|lua_type| returns one of the following strings,
1551describing the type of the given object:
1552\verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|,
1553\verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|.
1417 1554
1418To get the tag of a \verb|lua_Object|, 1555To get the tag of a \verb|lua_Object|,
1419the following function is available: 1556the following function is available:
@@ -1423,12 +1560,12 @@ int lua_tag (lua_Object object);
1423\end{verbatim} 1560\end{verbatim}
1424 1561
1425To translate a value from type \verb|lua_Object| to a specific C type, 1562To translate a value from type \verb|lua_Object| to a specific C type,
1426the programmer can use: 1563you can use
1427\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} 1564\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen}
1428\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} 1565\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata}
1429\begin{verbatim} 1566\begin{verbatim}
1430double lua_getnumber (lua_Object object); 1567double lua_getnumber (lua_Object object);
1431char *lua_getstring (lua_Object object); 1568const char *lua_getstring (lua_Object object);
1432long lua_strlen (lua_Object object); 1569long lua_strlen (lua_Object object);
1433lua_CFunction lua_getcfunction (lua_Object object); 1570lua_CFunction lua_getcfunction (lua_Object object);
1434void *lua_getuserdata (lua_Object object); 1571void *lua_getuserdata (lua_Object object);
@@ -1438,9 +1575,10 @@ void *lua_getuserdata (lua_Object object);
1438This \verb|lua_Object| must be a number or a string convertible to number 1575This \verb|lua_Object| must be a number or a string convertible to number
1439\see{coercion}; otherwise, \verb|lua_getnumber| returns~0. 1576\see{coercion}; otherwise, \verb|lua_getnumber| returns~0.
1440 1577
1441\verb|lua_getstring| converts a \verb|lua_Object| to a string (\verb|char*|). 1578\verb|lua_getstring| converts a \verb|lua_Object| to a string
1579(\verb|const char*|).
1442This \verb|lua_Object| must be a string or a number; 1580This \verb|lua_Object| must be a string or a number;
1443otherwise, the function returns~0 (the \verb|NULL| pointer). 1581otherwise, the function returns \verb|NULL|.
1444This function does not create a new string, 1582This function does not create a new string,
1445but returns a pointer to a string inside the Lua environment. 1583but returns a pointer to a string inside the Lua environment.
1446Those strings always have a 0 after their last character (like in C), 1584Those strings always have a 0 after their last character (like in C),
@@ -1454,12 +1592,12 @@ will be valid after the block ends
1454 1592
1455\verb|lua_getcfunction| converts a \verb|lua_Object| to a C function. 1593\verb|lua_getcfunction| converts a \verb|lua_Object| to a C function.
1456This \verb|lua_Object| must have type \emph{CFunction}; 1594This \verb|lua_Object| must have type \emph{CFunction};
1457otherwise, \verb|lua_getcfunction| returns 0 (the \verb|NULL| pointer). 1595otherwise, \verb|lua_getcfunction| returns \verb|NULL|.
1458The type \verb|lua_CFunction| is explained in \See{LuacallC}. 1596The type \verb|lua_CFunction| is explained in \See{LuacallC}.
1459 1597
1460\verb|lua_getuserdata| converts a \verb|lua_Object| to \verb|void*|. 1598\verb|lua_getuserdata| converts a \verb|lua_Object| to \verb|void*|.
1461This \verb|lua_Object| must have type \emph{userdata}; 1599This \verb|lua_Object| must have type \emph{userdata};
1462otherwise, \verb|lua_getuserdata| returns 0 (the \verb|NULL| pointer). 1600otherwise, \verb|lua_getuserdata| returns \verb|NULL|.
1463 1601
1464\subsection{Garbage Collection}\label{GC} 1602\subsection{Garbage Collection}\label{GC}
1465Because Lua has automatic memory management and garbage collection, 1603Because Lua has automatic memory management and garbage collection,
@@ -1479,7 +1617,8 @@ long lua_collectgarbage (long limit);
1479This function returns the number of objects collected. 1617This function returns the number of objects collected.
1480The argument \verb|limit| makes the next cycle occur only 1618The argument \verb|limit| makes the next cycle occur only
1481after that number of new objects have been created. 1619after that number of new objects have been created.
1482If \verb|limit|=0, then Lua uses an adaptive heuristics to set this limit. 1620If \verb|limit| is 0,
1621then Lua uses an adaptive heuristics to set this limit.
1483 1622
1484 1623
1485All communication between Lua and C is done through two 1624All communication between Lua and C is done through two
@@ -1513,8 +1652,8 @@ is done with the following functions:
1513\Deffunc{lua_pushuserdata}\label{pushing} 1652\Deffunc{lua_pushuserdata}\label{pushing}
1514\begin{verbatim} 1653\begin{verbatim}
1515void lua_pushnumber (double n); 1654void lua_pushnumber (double n);
1516void lua_pushlstring (char *s, long len); 1655void lua_pushlstring (const char *s, long len);
1517void lua_pushstring (char *s); 1656void lua_pushstring (const char *s);
1518void lua_pushusertag (void *u, int tag); 1657void lua_pushusertag (void *u, int tag);
1519void lua_pushnil (void); 1658void lua_pushnil (void);
1520void lua_pushobject (lua_Object object); 1659void lua_pushobject (lua_Object object);
@@ -1526,7 +1665,7 @@ and leave the result on the top of C2lua.
1526In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring| 1665In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring|
1527make an internal copy of the given string. 1666make an internal copy of the given string.
1528Function \verb|lua_pushstring| can only be used to push proper C strings 1667Function \verb|lua_pushstring| can only be used to push proper C strings
1529(that is, strings that do not contain zeros and end with a zero); 1668(that is, strings that end with a zero and do not contain embedded zeros);
1530otherwise you should use the more generic \verb|lua_pushlstring|. 1669otherwise you should use the more generic \verb|lua_pushlstring|.
1531The function 1670The function
1532\Deffunc{lua_pop} 1671\Deffunc{lua_pop}
@@ -1586,9 +1725,9 @@ A host program can execute Lua chunks written in a file or in a string
1586using the following functions:% 1725using the following functions:%
1587\Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer} 1726\Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer}
1588\begin{verbatim} 1727\begin{verbatim}
1589int lua_dofile (char *filename); 1728int lua_dofile (const char *filename);
1590int lua_dostring (char *string); 1729int lua_dostring (const char *string);
1591int lua_dobuffer (char *buff, int size, char *name); 1730int lua_dobuffer (const char *buff, int size, const char *name);
1592\end{verbatim} 1731\end{verbatim}
1593All these functions return an error code: 1732All these functions return an error code:
15940, in case of success; non zero, in case of errors. 17330, in case of success; non zero, in case of errors.
@@ -1618,7 +1757,7 @@ To read the value of any global Lua variable,
1618one uses the function: 1757one uses the function:
1619\Deffunc{lua_getglobal} 1758\Deffunc{lua_getglobal}
1620\begin{verbatim} 1759\begin{verbatim}
1621lua_Object lua_getglobal (char *varname); 1760lua_Object lua_getglobal (const char *varname);
1622\end{verbatim} 1761\end{verbatim}
1623As in Lua, this function may trigger a tag method. 1762As in Lua, this function may trigger a tag method.
1624To read the real value of any global variable, 1763To read the real value of any global variable,
@@ -1626,14 +1765,14 @@ without invoking any tag method,
1626use the \emph{raw} version: 1765use the \emph{raw} version:
1627\Deffunc{lua_rawgetglobal} 1766\Deffunc{lua_rawgetglobal}
1628\begin{verbatim} 1767\begin{verbatim}
1629lua_Object lua_rawgetglobal (char *varname); 1768lua_Object lua_rawgetglobal (const char *varname);
1630\end{verbatim} 1769\end{verbatim}
1631 1770
1632To store a value previously pushed onto C2lua in a global variable, 1771To store a value previously pushed onto C2lua in a global variable,
1633there is the function: 1772there is the function:
1634\Deffunc{lua_setglobal} 1773\Deffunc{lua_setglobal}
1635\begin{verbatim} 1774\begin{verbatim}
1636void lua_setglobal (char *varname); 1775void lua_setglobal (const char *varname);
1637\end{verbatim} 1776\end{verbatim}
1638As in Lua, this function may trigger a tag method. 1777As in Lua, this function may trigger a tag method.
1639To set the real value of any global variable, 1778To set the real value of any global variable,
@@ -1641,7 +1780,7 @@ without invoking any tag method,
1641use the \emph{raw} version: 1780use the \emph{raw} version:
1642\Deffunc{lua_rawgetglobal} 1781\Deffunc{lua_rawgetglobal}
1643\begin{verbatim} 1782\begin{verbatim}
1644void lua_rawsetglobal (char *varname); 1783void lua_rawsetglobal (const char *varname);
1645\end{verbatim} 1784\end{verbatim}
1646 1785
1647Tables can also be manipulated via the API. 1786Tables can also be manipulated via the API.
@@ -1699,8 +1838,8 @@ int lua_callfunction (lua_Object function);
1699\end{verbatim} 1838\end{verbatim}
1700This function returns an error code: 1839This function returns an error code:
17010, in case of success; non zero, in case of errors. 18400, in case of success; non zero, in case of errors.
1702Finally, the results (a Lua function may return many values) 1841Finally, the results are returned in structure lua2C
1703are returned in structure lua2C, 1842(recall that a Lua function may return many values),
1704and can be retrieved with the macro \verb|lua_getresult|, 1843and can be retrieved with the macro \verb|lua_getresult|,
1705\Deffunc{lua_getresult} 1844\Deffunc{lua_getresult}
1706which is just another name to function \verb|lua_lua2C|. 1845which is just another name to function \verb|lua_lua2C|.
@@ -1729,7 +1868,7 @@ Some special Lua functions have exclusive interfaces.
1729A C function can generate a Lua error calling the function 1868A C function can generate a Lua error calling the function
1730\Deffunc{lua_error} 1869\Deffunc{lua_error}
1731\begin{verbatim} 1870\begin{verbatim}
1732void lua_error (char *message); 1871void lua_error (const char *message);
1733\end{verbatim} 1872\end{verbatim}
1734This function never returns. 1873This function never returns.
1735If the C function has been called from Lua, 1874If the C function has been called from Lua,
@@ -1743,7 +1882,7 @@ then \verb|_ERRORMESSAGE| is not called.
1743 1882
1744Tag methods can be changed with: \Deffunc{lua_settagmethod} 1883Tag methods can be changed with: \Deffunc{lua_settagmethod}
1745\begin{verbatim} 1884\begin{verbatim}
1746lua_Object lua_settagmethod (int tag, char *event); 1885lua_Object lua_settagmethod (int tag, const char *event);
1747\end{verbatim} 1886\end{verbatim}
1748The first parameter is the tag, 1887The first parameter is the tag,
1749and the second is the event name \see{tag-method}; 1888and the second is the event name \see{tag-method};
@@ -1753,7 +1892,7 @@ which is the old tag method value.
1753To get just the current value of a tag method, 1892To get just the current value of a tag method,
1754use the function \Deffunc{lua_gettagmethod} 1893use the function \Deffunc{lua_gettagmethod}
1755\begin{verbatim} 1894\begin{verbatim}
1756lua_Object lua_gettagmethod (int tag, char *event); 1895lua_Object lua_gettagmethod (int tag, const char *event);
1757\end{verbatim} 1896\end{verbatim}
1758 1897
1759It is also possible to copy all tag methods from one tag 1898It is also possible to copy all tag methods from one tag
@@ -1763,14 +1902,70 @@ int lua_copytagmethods (int tagto, int tagfrom);
1763\end{verbatim} 1902\end{verbatim}
1764This function returns \verb|tagto|. 1903This function returns \verb|tagto|.
1765 1904
1766 1905You can traverse a table with the function \Deffunc{lua_next}
1767\subsection{C Functions} \label{LuacallC} 1906\begin{verbatim}
1907int lua_next (lua_Object t, int i);
1908\end{verbatim}
1909Its first argument is the table to be traversed,
1910and the second is a \emph{cursor};
1911this cursor starts in 0,
1912and for each call the function returns a value to
1913be used in the next call,
1914or 0 to signal the end of the traverse.
1915The function also returns, in the Lua2C array,
1916a key-value pair from the table.
1917A typical traversal looks like the following code:
1918\begin{verbatim}
1919 int i;
1920 lua_Object t;
1921 ... /* gets the table at `t' */
1922 i = 0;
1923 lua_beginblock();
1924 while ((i = lua_next(t, i)) != 0) {
1925 lua_Object key = lua_getresult(1);
1926 lua_Object value = lua_getresult(2);
1927 ... /* uses `key' and `value' */
1928 lua_endblock();
1929 lua_beginblock(); /* reopens a block */
1930 }
1931 lua_endblock();
1932\end{verbatim}
1933The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the
1934results of each iteration from the stack.
1935Without them, a traversal of a large table will overflow the stack.
1936
1937To traverse the global variables, you use \Deffunc{lua_nextvar}
1938\begin{verbatim}
1939const char *lua_nextvar (const char *varname);
1940\end{verbatim}
1941Here, the cursor is a string;
1942in the first call you set it to \verb|NULL|;
1943for each call the function returns the name of a global variable,
1944to be used in the next call,
1945or \verb|NULL| to signal the end of the traverse.
1946The function also returns, in the Lua2C array,
1947the name (again) and the value of the global variable.
1948A typical traversal looks like the following code:
1949\begin{verbatim}
1950 const char *name = NULL;
1951 lua_beginblock();
1952 while ((name = lua_nextvar(name)) != NULL) {
1953 lua_Object value = lua_getresult(2);
1954 ... /* uses `name' and `value' */
1955 lua_endblock();
1956 lua_beginblock(); /* reopens a block */
1957 }
1958 lua_endblock();
1959\end{verbatim}
1960
1961
1962\subsection{Defining C Functions} \label{LuacallC}
1768To register a C function to Lua, 1963To register a C function to Lua,
1769there is the following macro: 1964there is the following macro:
1770\Deffunc{lua_register} 1965\Deffunc{lua_register}
1771\begin{verbatim} 1966\begin{verbatim}
1772#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n)) 1967#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
1773/* char *n; */ 1968/* const char *n; */
1774/* lua_CFunction f; */ 1969/* lua_CFunction f; */
1775\end{verbatim} 1970\end{verbatim}
1776which receives the name the function will have in Lua, 1971which receives the name the function will have in Lua,
@@ -1802,8 +1997,7 @@ then these values are passed to the function whenever it is called,
1802as common arguments. 1997as common arguments.
1803To associate upvalues to a function, 1998To associate upvalues to a function,
1804first these values must be pushed on C2lua. 1999first these values must be pushed on C2lua.
1805Then the function 2000Then the function \Deffunc{lua_pushcclosure}
1806\Deffunc{lua_pushcclosure}
1807\begin{verbatim} 2001\begin{verbatim}
1808void lua_pushcclosure (lua_CFunction fn, int n); 2002void lua_pushcclosure (lua_CFunction fn, int n);
1809\end{verbatim} 2003\end{verbatim}
@@ -1962,7 +2156,7 @@ used in error messages and debug information.
1962Returns a new tag. 2156Returns a new tag.
1963\verb|newtag| is equivalent to the API function \verb|lua_newtag|. 2157\verb|newtag| is equivalent to the API function \verb|lua_newtag|.
1964 2158
1965\subsubsection*{\ff \T{next (table, index)}}\Deffunc{next} 2159\subsubsection*{\ff \T{next (table, [index])}}\Deffunc{next}
1966Allows a program to traverse all fields of a table. 2160Allows a program to traverse all fields of a table.
1967Its first argument is a table and its second argument 2161Its first argument is a table and its second argument
1968is an index in this table. 2162is an index in this table.
@@ -1974,6 +2168,7 @@ of the table (and its associated value).
1974When called with the last index, 2168When called with the last index,
1975or with \nil\ in an empty table, 2169or with \nil\ in an empty table,
1976it returns \nil. 2170it returns \nil.
2171If the second argument is absent, it is interpreted as \nil.
1977 2172
1978Lua has no declaration of fields; 2173Lua has no declaration of fields;
1979semantically, there is no difference between a 2174semantically, there is no difference between a
@@ -1983,23 +2178,21 @@ The order in which the indices are enumerated is not specified,
1983\emph{even for numeric indices} 2178\emph{even for numeric indices}
1984(to traverse a table in numeric order, 2179(to traverse a table in numeric order,
1985use a counter or the function \verb|foreachi|). 2180use a counter or the function \verb|foreachi|).
1986If the table indices are modified in any way during a traversal, 2181If you create new indices in a table while
2182traversing it,
1987the semantics of \verb|next| is undefined. 2183the semantics of \verb|next| is undefined.
1988 2184
1989This function cannot be written with the standard API.
1990
1991\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} 2185\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar}
1992This function is similar to the function \verb|next|, 2186This function is similar to the function \verb|next|,
1993but iterates instead over the global variables. 2187but iterates instead over the global variables.
1994Its single argument is the name of a global variable, 2188Its single argument is the name of a global variable,
1995or \nil\ to get a first name. 2189or \nil\ to get a first name.
2190If this argument is absent, it is interpreted as \nil.
1996Similarly to \verb|next|, it returns the name of another variable 2191Similarly to \verb|next|, it returns the name of another variable
1997and its value, 2192and its value,
1998or \nil\ if there are no more variables. 2193or \nil\ if there are no more variables.
1999There can be no creation of new global variables during the traversal; 2194If you create new global variables during the traversal,
2000otherwise the semantics of \verb|nextvar| is undefined. 2195the semantics of \verb|nextvar| is undefined.
2001
2002This function cannot be written with the standard API.
2003 2196
2004\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring} 2197\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring}
2005Receives an argument of any type and 2198Receives an argument of any type and
@@ -2017,8 +2210,9 @@ See \See{libio} for functions for formatted output.
2017 2210
2018\subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} 2211\subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert}
2019Prints its only string argument to \IndexVerb{stderr}. 2212Prints its only string argument to \IndexVerb{stderr}.
2020All error messages in Lua are printed through this function. 2213All error messages in Lua are printed through the function stored
2021Therefore, a program may redefine it 2214in the \verb|_ALERT| global variable.
2215Therefore, a program may assign another function to this variable
2022to change the way such messages are shown 2216to change the way such messages are shown
2023(for instance, for systems without \verb|stderr|). 2217(for instance, for systems without \verb|stderr|).
2024 2218
@@ -2036,7 +2230,7 @@ represents 10, `B' represents 11, and so forth, with `Z' representing 35.
2036 2230
2037In base 10 (the default), the number may have a decimal part, 2231In base 10 (the default), the number may have a decimal part,
2038as well as an optional exponent part \see{coercion}. 2232as well as an optional exponent part \see{coercion}.
2039In other bases, only integers are accepted. 2233In other bases, only unsigned integers are accepted.
2040 2234
2041\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} 2235\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type}
2042Allows Lua to test the type of a value. 2236Allows Lua to test the type of a value.
@@ -2049,7 +2243,7 @@ The possible results of this function are
2049\verb|"function"|, 2243\verb|"function"|,
2050and \verb|"userdata"|. 2244and \verb|"userdata"|.
2051 2245
2052\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag} 2246\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag}
2053Allows Lua to test the tag of a value \see{TypesSec}. 2247Allows Lua to test the tag of a value \see{TypesSec}.
2054It receives one argument, and returns its tag (a number). 2248It receives one argument, and returns its tag (a number).
2055\verb|tag| is equivalent to the API function \verb|lua_tag|. 2249\verb|tag| is equivalent to the API function \verb|lua_tag|.
@@ -2106,7 +2300,6 @@ syntactically valid variable name.
2106Therefore, 2300Therefore,
2107this function can set global variables with strange names like 2301this function can set global variables with strange names like
2108\verb|"m v 1"| or \verb|34|. 2302\verb|"m v 1"| or \verb|34|.
2109Function \verb|rawsetglobal| returns the value of its second argument.
2110 2303
2111\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} 2304\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal}
2112Assigns the given value to a global variable, 2305Assigns the given value to a global variable,
@@ -2114,7 +2307,6 @@ or calls a tag method.
2114Its full semantics is explained in \See{tag-method}. 2307Its full semantics is explained in \See{tag-method}.
2115The string \verb|name| does not need to be a 2308The string \verb|name| does not need to be a
2116syntactically valid variable name. 2309syntactically valid variable name.
2117Function \verb|setglobal| returns the value of its second argument.
2118 2310
2119\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} 2311\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
2120Retrieves the value of a global variable. 2312Retrieves the value of a global variable.
@@ -2186,6 +2378,10 @@ This function could be defined in Lua:
2186 end 2378 end
2187\end{verbatim} 2379\end{verbatim}
2188 2380
2381If you create new indices in a table while
2382traversing it,
2383the semantics of \verb|foreach| is undefined.
2384
2189 2385
2190\subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi} 2386\subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi}
2191Executes the given \verb|function| over the 2387Executes the given \verb|function| over the
@@ -2231,12 +2427,15 @@ This function could be defined in Lua:
2231 end 2427 end
2232\end{verbatim} 2428\end{verbatim}
2233 2429
2430If you create new global variables during the traversal,
2431the semantics of \verb|foreachvar| is undefined.
2432
2234\subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert} 2433\subsubsection*{\ff \T{tinsert (table [, pos] , value)}}\Deffunc{tinsert}
2235 2434
2236Inserts element \verb|value| at table position \verb|pos|, 2435Inserts element \verb|value| at table position \verb|pos|,
2237shifting other elements to open space. 2436shifting other elements to open space, if necessary.
2238The default value for \verb|pos| is \verb|n+1| 2437The default value for \verb|pos| is \verb|n+1|,
2239(where \verb|n| is the result of \verb|getn(table)| \see{getn}) 2438where \verb|n| is the result of \verb|getn(table)| \see{getn},
2240so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end 2439so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end
2241of table \verb|t|. 2440of table \verb|t|.
2242 2441
@@ -2250,9 +2449,9 @@ except that the table accesses are all raw (that is, without tag methods):
2250 local pos, value 2449 local pos, value
2251 local n = getn(t) 2450 local n = getn(t)
2252 if arg.n == 1 then 2451 if arg.n == 1 then
2253 pos = n+1; value = arg[1] 2452 pos, value = n+1, arg[1]
2254 else 2453 else
2255 pos = arg[1]; value = arg[2] 2454 pos, value = arg[1], arg[2]
2256 end 2455 end
2257 t.n = n+1; 2456 t.n = n+1;
2258 while n >= pos do 2457 while n >= pos do
@@ -2266,7 +2465,7 @@ except that the table accesses are all raw (that is, without tag methods):
2266\subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove} 2465\subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove}
2267 2466
2268Removes from \verb|table| the element at position \verb|pos|, 2467Removes from \verb|table| the element at position \verb|pos|,
2269shifting other elements to close the space. 2468shifting other elements to close the space, if necessary.
2270Returns the value of the removed element. 2469Returns the value of the removed element.
2271The default value for \verb|pos| is \verb|n| 2470The default value for \verb|pos| is \verb|n|
2272(where \verb|n| is the result of \verb|getn(table)| \see{getn}), 2471(where \verb|n| is the result of \verb|getn(table)| \see{getn}),
@@ -2303,9 +2502,7 @@ it must be a function that receives two table elements,
2303and returns true when the first is less than the second 2502and returns true when the first is less than the second
2304(so that \verb|not comp(a[i+1], a[i])| will be true after the sort). 2503(so that \verb|not comp(a[i+1], a[i])| will be true after the sort).
2305If \verb|comp| is not given, 2504If \verb|comp| is not given,
2306the standard \verb|<| Lua operator is used instead. 2505the standard Lua operator \verb|<| is used instead.
2307
2308Function \verb|sort| returns the (sorted) table.
2309 2506
2310 2507
2311\subsection{String Manipulation} 2508\subsection{String Manipulation}
@@ -2434,7 +2631,7 @@ For example, \verb|"%*g"| can be simulated with
2434\verb|"%"..width.."g"|. 2631\verb|"%"..width.."g"|.
2435 2632
2436\emph{Note: function \T{format} can only be used with strings that do not 2633\emph{Note: function \T{format} can only be used with strings that do not
2437contain zeros.} 2634contain zeros (0).}
2438 2635
2439\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} 2636\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}}
2440\Deffunc{gsub} 2637\Deffunc{gsub}
@@ -2542,7 +2739,7 @@ For instance, \verb|%S| represents all non-space characters.
2542 2739
2543The definitions of letter, space, etc. depend on the current locale. 2740The definitions of letter, space, etc. depend on the current locale.
2544In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|. 2741In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|.
2545The second form should be preferred for more portable programs. 2742The second form should be preferred for portability.
2546 2743
2547\paragraph{Pattern Item:} 2744\paragraph{Pattern Item:}
2548a \Def{pattern item} may be 2745a \Def{pattern item} may be
@@ -2600,6 +2797,9 @@ stored as the first capture (and therefore has number~1);
2600the character matching \verb|.| is captured with number~2, 2797the character matching \verb|.| is captured with number~2,
2601and the part matching \verb|%s*| has number~3. 2798and the part matching \verb|%s*| has number~3.
2602 2799
2800{\em Note: A pattern cannot contain zeros (\verb|'\0'|).
2801Use \verb|'%z'| instead.}
2802
2603 2803
2604\subsection{Mathematical Functions} \label{mathlib} 2804\subsection{Mathematical Functions} \label{mathlib}
2605 2805
@@ -2659,8 +2859,6 @@ Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|.
2659 2859
2660A file handle is a userdata containing the file stream \verb|FILE*|, 2860A file handle is a userdata containing the file stream \verb|FILE*|,
2661and with a distinctive tag created by the I/O library. 2861and with a distinctive tag created by the I/O library.
2662Whenever a file handle is collected by the garbage collector,
2663its correspondent stream is automatically closed.
2664 2862
2665Unless otherwise stated, 2863Unless otherwise stated,
2666all I/O functions return \nil\ on failure and 2864all I/O functions return \nil\ on failure and
@@ -2676,12 +2874,12 @@ This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
2676 2874
2677The string mode can be any of the following: 2875The string mode can be any of the following:
2678\begin{description} 2876\begin{description}
2679\item["r"] read mode; 2877\item[``r''] read mode;
2680\item["w"] write mode; 2878\item[``w''] write mode;
2681\item["a"] append mode; 2879\item[``a''] append mode;
2682\item["r+"] update mode, all previous data is preserved; 2880\item[``r+''] update mode, all previous data is preserved;
2683\item["w+"] update mode, all previous data is erased; 2881\item[``w+''] update mode, all previous data is erased;
2684\item["a+"] append update mode, previous data is preserved, 2882\item[``a+''] append update mode, previous data is preserved,
2685 writing is only allowed at the end of file. 2883 writing is only allowed at the end of file.
2686\end{description} 2884\end{description}
2687The string mode may also have a \verb|b| at the end, 2885The string mode may also have a \verb|b| at the end,
@@ -2749,7 +2947,7 @@ usually limited and depends on the system.
2749Opens a file named \verb|filename| and sets it as the 2947Opens a file named \verb|filename| and sets it as the
2750value of \verb|_OUTPUT|. 2948value of \verb|_OUTPUT|.
2751Unlike the \verb|writeto| operation, 2949Unlike the \verb|writeto| operation,
2752this function does not erase any previous content of the file. 2950this function does not erase any previous contents of the file.
2753If this function fails, it returns \nil, 2951If this function fails, it returns \nil,
2754plus a string describing the error. 2952plus a string describing the error.
2755 2953
@@ -2780,9 +2978,9 @@ measured in bytes from the beginning of the file,
2780to the position given by \verb|offset| plus a base 2978to the position given by \verb|offset| plus a base
2781specified by the string \verb|whence|, as follows: 2979specified by the string \verb|whence|, as follows:
2782\begin{description} 2980\begin{description}
2783\item["set"] base is position 0 (beginning of the file); 2981\item[``set''] base is position 0 (beginning of the file);
2784\item["cur"] base is current position; 2982\item[``cur''] base is current position;
2785\item["end"] base is end of file; 2983\item[``end''] base is end of file;
2786\end{description} 2984\end{description}
2787In case of success, function \verb|seek| returns the final file position, 2985In case of success, function \verb|seek| returns the final file position,
2788measured in bytes from the beginning of the file. 2986measured in bytes from the beginning of the file.
@@ -2802,62 +3000,33 @@ end of the file, and returns its size.
2802 3000
2803Returns a string with a file name that can safely 3001Returns a string with a file name that can safely
2804be used for a temporary file. 3002be used for a temporary file.
2805The file must be explicitly removed when no longer needed. 3003The file must be explicitly opened before its use
3004and removed when no longer needed.
2806 3005
2807\subsubsection*{\ff \T{read ([filehandle,] readpattern1, ...)}}\Deffunc{read} 3006\subsubsection*{\ff \T{read ([filehandle,] format1, ...)}}\Deffunc{read}
2808 3007
2809Reads file \verb|_INPUT|, 3008Reads file \verb|_INPUT|,
2810or \verb|filehandle| if this argument is given, 3009or \verb|filehandle| if this argument is given,
2811according to read patterns, which specify how much to read. 3010according to the given formats, which specify what to read.
2812For each pattern, 3011For each format,
2813the function returns a string with the characters read, 3012the function returns a string (or a number) with the characters read,
2814even if the pattern succeeds only partially, 3013or \nil\ if it cannot read data with the specified format.
2815or \nil\ if the read pattern fails \emph{and}
2816the result string would be empty.
2817When called without patterns, 3014When called without patterns,
2818it uses a default pattern that reads the next line 3015it uses a default format that reads the next line
2819(see below). 3016(see below).
2820 3017
2821A \Def{read pattern} is a sequence of read pattern items. 3018The available formats are
2822An item may be a single character class
2823or a character class followed by \verb|?|, by \verb|*|, or by \verb|+|.
2824A single character class reads the next character from the input
2825if it belongs to the class, otherwise it fails.
2826A character class followed by \verb|?| reads the next character
2827from the input if it belongs to the class;
2828it never fails.
2829A character class followed by \verb|*| reads until a character that
2830does not belong to the class, or end of file;
2831since it can match a sequence of zero characters, it never fails.
2832A character class followed by \verb|+| reads until a character that
2833does not belong to the class, or end of file;
2834it fails if it cannot read at least one character.
2835Note that the behavior of read patterns is slightly different from
2836the regular pattern matching behavior,
2837where a \verb|*| expands to the maximum length \emph{such that}
2838the rest of the pattern does not fail.
2839With the read pattern behavior
2840there is no need for backtracking the reading.
2841
2842A pattern item may contain sub-patterns enclosed in curly brackets,
2843that describe \Def{skips}.
2844Characters matching a skip are read,
2845but are not included in the resulting string.
2846
2847There are some predefined patterns, as follows:
2848\begin{description} 3019\begin{description}
2849\item[``*n''] reads a number; 3020\item[``*n''] reads a number;
2850this is the only pattern that returns a number instead of a string. 3021this is the only format that returns a number instead of a string.
2851\item[``*l''] returns the next line 3022\item[``*l''] reads the next line
2852(skipping the end of line), or \nil\ on end of file. 3023(skipping the end of line), or \nil\ on end of file.
2853This is the default pattern. 3024This is the default format.
2854It is equivalent to the pattern \verb|"[^\n]*{\n}"|. 3025\item[``*a''] reads the whole file, starting at the current position.
2855\item[``*a''] reads the whole file. 3026On end of file, it returns the empty string.
2856It is equivalent to the pattern \verb|".*"|. 3027\item[``*w''] reads the next word
2857\item[``*w''] returns the next word
2858(maximal sequence of non white-space characters), 3028(maximal sequence of non white-space characters),
2859skipping spaces if necessary, or \nil\ on end of file. 3029skipping spaces if necessary, or \nil\ on end of file.
2860It is equivalent to the pattern \verb|"{%s*}%S+"|.
2861\end{description} 3030\end{description}
2862 3031
2863\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write} 3032\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write}
@@ -2878,7 +3047,7 @@ formatted according to the given string \verb|format|,
2878following the same rules of the ANSI C function \verb|strftime|. 3047following the same rules of the ANSI C function \verb|strftime|.
2879When called without arguments, 3048When called without arguments,
2880it returns a reasonable date and time representation that depends on 3049it returns a reasonable date and time representation that depends on
2881the host system and on the locale. 3050the host system and on the current locale.
2882 3051
2883\subsubsection*{\ff \T{clock ()}}\Deffunc{clock} 3052\subsubsection*{\ff \T{clock ()}}\Deffunc{clock}
2884 3053
@@ -2890,7 +3059,7 @@ used by the program, in seconds.
2890Calls the C function \verb|exit|, 3059Calls the C function \verb|exit|,
2891with an optional \verb|code|, 3060with an optional \verb|code|,
2892to terminate the program. 3061to terminate the program.
2893The default value for \verb|code| is 1. 3062The default value for \verb|code| is the success code.
2894 3063
2895\subsubsection*{\ff \T{getenv (varname)}}\Deffunc{getenv} 3064\subsubsection*{\ff \T{getenv (varname)}}\Deffunc{getenv}
2896 3065
@@ -2901,7 +3070,7 @@ or \nil\ if the variable is not defined.
2901 3070
2902This function is equivalent to the C function \verb|system|. 3071This function is equivalent to the C function \verb|system|.
2903It passes \verb|command| to be executed by an operating system shell. 3072It passes \verb|command| to be executed by an operating system shell.
2904It returns an error code, which is system-dependent. 3073It returns a status code, which is system-dependent.
2905 3074
2906\subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} 3075\subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale}
2907 3076
@@ -2927,240 +3096,281 @@ This interface is declared in the header file \verb|luadebug.h|.
2927 3096
2928\subsection{Stack and Function Information} 3097\subsection{Stack and Function Information}
2929 3098
2930The main function to get information about the interpreter stack 3099\Deffunc{lua_getstack}
2931is 3100The main function to get information about the interpreter stack is
2932\begin{verbatim} 3101\begin{verbatim}
2933lua_Function lua_stackedfunction (int level); 3102int lua_getstack (lua_State *L, int level, lua_Debug *ar);
2934\end{verbatim} 3103\end{verbatim}
2935It returns a handle (\verb|lua_Function|) to the \emph{activation record} 3104It fills parts of a structure (\verb|lua_Debug|) with
3105an identification of the \emph{activation record}
2936of the function executing at a given level. 3106of the function executing at a given level.
2937Level~0 is the current running function, 3107Level~0 is the current running function,
2938while level \Math{n+1} is the function that has called level \Math{n}. 3108while level \Math{n+1} is the function that has called level \Math{n}.
2939When called with a level greater than the stack depth, 3109Usually, \verb|lua_getstack| returns 1;
2940\verb|lua_stackedfunction| returns \verb|LUA_NOOBJECT|. 3110when called with a level greater than the stack depth,
2941 3111it returns 0.
2942The type \verb|lua_Function| is just another name 3112
2943to \verb|lua_Object|. 3113The structure \verb|lua_Debug| is used to carry different informations
2944Although, in this library, 3114about an active function: \Deffunc{lua_Debug}
2945a \verb|lua_Function| can be used wherever a \verb|lua_Object| is required, 3115\begin{verbatim}
2946when a parameter has type \verb|lua_Function| 3116struct lua_Debug {
2947it accepts only a handle returned by 3117 const char *event; /* `call', `return' */
2948\verb|lua_stackedfunction|. 3118 const char *source; /* (S) */
3119 int linedefined; /* (S) */
3120 const char *what; /* (S) `Lua' function, `C' function, Lua `main' */
3121 int currentline; /* (l) */
3122 const char *name; /* (n) */
3123 const char *namewhat; /* (n) global, tag method, local, field */
3124 int nups; /* (u) number of upvalues */
3125 lua_Object func; /* (f) function being executed */
3126 /* private part */
3127 ...
3128};
3129\end{verbatim}
3130The \verb|lua_getstack| function fills only the private part
3131of this structure, for future use.
3132To fill in the other fields of \verb|lua_Debug| with useful information,
3133you call \Deffunc{lua_getinfo}
3134\begin{verbatim}
3135int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
3136\end{verbatim}
3137Each character in string \verb|what| selects some fields to be filled,
3138as indicated by the letter in parentheses in the structure definition;
3139that is, an \verb|S| fills the fields \verb|source| and \verb|linedefined|,
3140and \verb|l| fills the field \verb|currentline|, etc.
3141Next we describe each field:
3142\begin{description}
2949 3143
2950Three other functions produce extra information about a function: 3144\item[source]
2951\begin{verbatim}
2952void lua_funcinfo (lua_Object func, char **source, int *linedefined);
2953int lua_currentline (lua_Function func);
2954char *lua_getobjname (lua_Object o, char **name);
2955\end{verbatim}
2956\verb|lua_funcinfo| gives the source and the line where the
2957given function has been defined:
2958If the function was defined in a string, 3145If the function was defined in a string,
2959\verb|source| is that string; 3146\verb|source| is that string;
2960If the function was defined in a file, 3147if the function was defined in a file,
2961\verb|source| starts with a \verb|@| followed by the file name. 3148\verb|source| starts with a \verb|@| followed by the file name.
2962If the ``function'' is in fact the main code of a chunk,
2963then \verb|linedefined| is 0.
2964If the function is a C function,
2965then \verb|linedefined| is \Math{-1}, and \verb|filename| is \verb|"(C)"|.
2966 3149
2967The function \verb|lua_currentline| gives the current line where 3150\item[linedefined]
2968a given function is executing. 3151the line number where starts the definition of the function.
3152
3153\item[what] the string \verb|"Lua"| if this is a Lua function,
3154\verb|"C"| if this is a C function,
3155or \verb|"main"| if this is the main part of a chunk.
3156
3157\item[currentline]
3158the current line where the given function is executing.
2969It only works if the function has been compiled with debug 3159It only works if the function has been compiled with debug
2970information. 3160information.
2971When no line information is available, 3161When no line information is available,
2972\verb|lua_currentline| returns \Math{-1}. 3162\verb|currentline| is set to \Math{-1}.
2973 3163
2974The generation of debug information is controled by an internal flag, 3164\item[name]
2975which can be switched with 3165a reasonable name for the given function.
2976\begin{verbatim}
2977int lua_setdebug (int debug);
2978\end{verbatim}
2979This function sets the flag and returns its previous value.
2980This flag can also be set from Lua~\see{pragma}.
2981
2982Function \verb|lua_getobjname| tries to find a reasonable name for
2983a given function.
2984Because functions in Lua are first class values, 3166Because functions in Lua are first class values,
2985they do not have a fixed name: 3167they do not have a fixed name:
2986Some functions may be the value of many global variables, 3168Some functions may be the value of many global variables,
2987while others may be stored only in a table field. 3169while others may be stored only in a table field.
2988Function \verb|lua_getobjname| checks whether the given 3170The \verb|lua_getinfo| function checks whether the given
2989function is a tag method or the value of a global variable. 3171function is a tag method or the value of a global variable.
2990If the given function is a tag method, then \verb|lua_getobjname| 3172If the given function is a tag method,
2991returns the string \verb|"tag-method"|, 3173\verb|name| points to the event name.
2992and \verb|name| is set to point to the event name.
2993If the given function is the value of a global variable, 3174If the given function is the value of a global variable,
2994then \verb|lua_getobjname| returns the string \verb|"global"|, 3175\verb|name| points to the variable name.
2995and \verb|name| points to the variable name.
2996If the given function is neither a tag method nor a global variable, 3176If the given function is neither a tag method nor a global variable,
2997then \verb|lua_getobjname| returns the empty string, 3177\verb|name| is set to \verb|NULL|.
2998and \verb|name| is set to \verb|NULL|. 3178
3179\item[namewhat]
3180Explains the previous field.
3181If the function is a global variable,
3182\verb|namewhat| is \verb|"global"|;
3183if the function is a tag method,
3184\verb|namewhat| is \verb|"tag-method"|;
3185otherwise \verb|namewhat| is \verb|""| (the empty string).
3186
3187\item[nups]
3188Number of upvalues of a C function.
3189If the function is not a C function,
3190\verb|nups| is set to 0.
3191
3192\item[func]
3193The function being executed, as a \verb|lua_Object|.
3194
3195\end{description}
3196
3197The generation of debug information is controlled by an internal flag,
3198which can be switched with
3199\begin{verbatim}
3200int lua_setdebug (lua_State *L, int debug);
3201\end{verbatim}
3202This function sets the flag and returns its previous value.
3203This flag can also be set from Lua~\see{pragma}.
2999 3204
3000\subsection{Manipulating Local Variables} 3205\subsection{Manipulating Local Variables}
3001 3206
3207For the manipulation of local variables,
3208\verb|luadebug.h| defines the following record:
3209\begin{verbatim}
3210struct lua_Localvar {
3211 int index;
3212 const char *name;
3213 lua_Object value;
3214};
3215\end{verbatim}
3216where \verb|index| is an index for local variables
3217(the first parameter has index 1, and so on,
3218until the last active local variable).
3219
3220\Deffunc{lua_getlocal}\Deffunc{lua_setlocal}
3002The following functions allow the manipulation of the 3221The following functions allow the manipulation of the
3003local variables of a given activation record. 3222local variables of a given activation record.
3004They only work if the function has been compiled with debug 3223They only work if the function has been compiled with debug
3005information \see{pragma}. 3224information \see{pragma}.
3006Moreover, for these functions, a local variable becomes 3225For these functions, a local variable becomes
3007visible in the line after its definition. 3226visible in the line after its definition.
3008\begin{verbatim} 3227\begin{verbatim}
3009lua_Object lua_getlocal (lua_Function func, int local_number, char **name); 3228int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
3010int lua_setlocal (lua_Function func, int local_number); 3229int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
3011\end{verbatim} 3230\end{verbatim}
3012\verb|lua_getlocal| returns the value of a local variable, 3231The parameter \verb|ar| must be a valid activation record,
3013and sets \verb|name| to point to the variable name. 3232filled by a previous call to \verb|lua_getstack| or
3014\verb|local_number| is an index for local variables. 3233given as argument to a hook (see next section).
3015The first parameter has index 1, and so on, until the 3234To use \verb|lua_getlocal|,
3016last active local variable. 3235you fill the \verb|index| field of \verb|v| with the index
3017When called with a \verb|local_number| greater than the 3236of a local variable; then the function fills the fields
3018number of active local variables, 3237\verb|name| and \verb|value| with the name and the current
3019or if the activation record has no debug information, 3238value of that variable.
3020\verb|lua_getlocal| returns \verb|LUA_NOOBJECT|. 3239For \verb|lua_setlocal|,
3021Formal parameters are the first local variables. 3240you fill the \verb|index| and the \verb|value| fields of \verb|v|,
3022 3241and the function assigns that value to the variable.
3023The function \verb|lua_setlocal| sets the local variable 3242Both functions return 0 on failure, that happens
3024\verb|local_number| to the value previously pushed on the stack 3243if the index is greater than the number of active local variables,
3025\see{valuesCLua}. 3244or if the activation record has no debug information.
3026If the function succeeds, then it returns 1. 3245
3027If \verb|local_number| is greater than the number 3246As an example, the following function lists the names of all
3028of active local variables, 3247local variables for a function in a given level of the stack:
3029or if the activation record has no debug information, 3248\begin{verbatim}
3030then this function fails and returns 0. 3249int listvars (lua_State *L, int level) {
3250 lua_Debug ar;
3251 int i;
3252 if (lua_getstack(L, level, &ar) == 0)
3253 return 0; /* failure: no such level on the stack */
3254 for (i=1; ;i++) {
3255 lua_Localvar v;
3256 v.index = i;
3257 if (lua_getlocal(L, &ar, &v) == 0)
3258 return 1; /* no more locals, or no debug information */
3259 printf("%s\n", v.name);
3260 }
3261}
3262\end{verbatim}
3263
3031 3264
3032\subsection{Hooks} 3265\subsection{Hooks}
3033 3266
3034The Lua interpreter offers two hooks for debugging purposes: 3267The Lua interpreter offers two hooks for debugging purposes:
3268a \emph{call} hook and a \emph{line} hook.
3269Both have the same type, and you can set them with the
3270following functions:
3271\Deffunc{lua_Hook}\Deffunc{lua_setcallhook}\Deffunc{lua_setlinehook}
3035\begin{verbatim} 3272\begin{verbatim}
3036typedef void (*lua_CHFunction) (lua_Function func, char *file, int line); 3273typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
3037lua_CHFunction lua_setcallhook (lua_CHFunction func);
3038 3274
3039typedef void (*lua_LHFunction) (int line); 3275lua_Hook lua_setcallhook (lua_State *L, lua_Hook func);
3040lua_LHFunction lua_setlinehook (lua_LHFunction func); 3276lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);
3041\end{verbatim} 3277\end{verbatim}
3042The first hook is called whenever the interpreter enters or leaves a
3043function.
3044When entering a function,
3045its parameters are a handle to the function activation record,
3046plus the file and the line where the function is defined
3047(the same information which is provided by \verb|lua_funcinfo|);
3048when leaving a function, \verb|func| is \verb|LUA_NOOBJECT|,
3049\verb|file| is \verb|"(return)"|, and \verb|line| is 0.
3050
3051The other hook is called every time the interpreter changes
3052the line of code it is executing.
3053Its only parameter is the line number
3054(the same information which is provided by the call
3055\verb|lua_currentline(lua_stackedfunction(0))|).
3056This second hook is called only if the active function
3057has been compiled with debug information \see{pragma}.
3058
3059A hook is disabled when its value is \verb|NULL|, 3278A hook is disabled when its value is \verb|NULL|,
3060which is the initial value of both hooks. 3279which is the initial value of both hooks.
3061Both \verb|lua_setcallhook| and \verb|lua_setlinehook| 3280Both \verb|lua_setcallhook| and \verb|lua_setlinehook|
3062set their corresponding hooks and return their previous values. 3281set their corresponding hooks and return their previous values.
3063 3282
3283The call hook is called whenever the
3284interpreter enters or leaves a function.
3285The \verb|event| field of \verb|ar| has the strings \verb|"call"|
3286or \verb|"return"|.
3287This \verb|ar| can then be used in calls to \verb|lua_getinfo|,
3288\verb|lua_getlocal|, and \verb|lua_setlocal|,
3289to get more information about the function and to manipulate its
3290local variables.
3291
3292The line hook is called every time the interpreter changes
3293the line of code it is executing.
3294The \verb|currentline| field of \verb|ar| has the line number.
3295Again, you can use this \verb|ar| in other calls to the API.
3296This hook is called only if the active function
3297has been compiled with debug information~\see{pragma}.
3298
3299While Lua is running a hook, it disables other calls to hooks.
3300Therefore, if a hook calls Lua to execute a function or a chunk,
3301this execution ocurrs without any calls to hooks.
3302
3303A hook cannot call \T{lua_error}.
3304It must return to Lua through a regular return.
3305(There is no problem if the error is inside a chunk or a Lua function
3306called by the hook, because those errors are protected;
3307the control returns to the hook anyway.)
3064 3308
3065 3309
3066\subsection{The Reflexive Debugger Interface} 3310\subsection{The Reflexive Debugger Interface}
3067 3311
3068The library \verb|ldblib| provides 3312The library \verb|ldblib| provides
3069the functionallity of the debugger interface to Lua programs. 3313the functionality of the debugger interface to Lua programs.
3070If you want to use this library, 3314If you want to use this library,
3071your host application must open it, 3315your host application must open it,
3072calling \verb|lua_dblibopen|. 3316by calling \verb|lua_dblibopen|.
3073 3317
3074You should exert great care when using this library. 3318You should exert great care when using this library.
3075The functions provided here should be used exclusively for debugging 3319The functions provided here should be used exclusively for debugging
3076and similar tasks (e.g. profiling). 3320and similar tasks (e.g., profiling).
3077Please resist the temptation to use them as a 3321Please resist the temptation to use them as a
3078usual programming tool. 3322usual programming tool.
3079They are slow and violate some (otherwise) secure aspects of the 3323They are slow and violate some (otherwise) secure aspects of the
3080language (e.g. privacy of local variables). 3324language (e.g., privacy of local variables).
3081As a general rule, if your program does not need this library, 3325As a general rule, if your program does not need this library,
3082do not open it. 3326do not open it.
3083 3327
3084 3328
3085\subsubsection*{\ff \T{funcinfo (function)}}\Deffunc{funcinfo} 3329\subsubsection*{\ff \T{getstack (level, what)}}\Deffunc{getstack}
3086
3087This function returns a table with information about the given function.
3088The table contains the following fields:
3089\begin{description}
3090\item[kind]: may be \verb|"C"|, if this is a C function,
3091\verb|"chunk"|, if this is the main part of a chunk,
3092or \verb|"Lua"| if this is a Lua function.
3093
3094\item[source] the source where the function was defined.
3095If the function was defined in a string,
3096\verb|source| is that string;
3097If the function was defined in a file,
3098\verb|source| starts with a \verb|@| followed by the file name.
3099
3100\item[def\_line] the line where the function was defined in the source
3101(only valid if this is a Lua function).
3102 3330
3103\item[where] can be \verb|"global"| if this function has a global name, 3331This function returns a table with informations about the function
3104or \verb|"tag-method"| if this function is a tag method handler. 3332running at level \verb|level| of the stack.
3333Level 0 is the current function (\verb|getstack| itself);
3334level 1 is the function that called \verb|getstack|.
3335If \verb|level| is larger than the number of active functions,
3336the function returns \nil.
3337The table contains all the fields returned by \verb|lua_getinfo|,
3338with the string \verb|what| describing what to get.
3105 3339
3106\item[name] if \verb|where| = \verb|global|, 3340For instance, the expression \verb|getstack(1, 'n').name| returns
3107\verb|name| is the global name of the function; 3341the name of the current function.
3108if \verb|where| = \verb|tag-method|,
3109\verb|name| is the event name of the tag method.
3110\end{description}
3111 3342
3112\subsubsection*{\ff \T{getstack (index)}}\Deffunc{getstack}
3113 3343
3114This function returns a table with informations about the function 3344\subsubsection*{\ff \T{getlocal (level, local)}}\Deffunc{getlocal}
3115running at level \verb|index| of the stack.
3116Index 0 is the current function (\verb|getstack| itself).
3117If \verb|index| is bigger than the number of active functions,
3118the function returns \nil.
3119The table contains all the fields returned by \verb|funcinfo|,
3120plus the following:
3121\begin{description}
3122\item[func] the function at that level.
3123\item[current] the current line on the function execution;
3124this will be available only when the function is
3125precompiled with debug information.
3126\end{description}
3127 3345
3128\subsubsection*{\ff \T{getlocal (index [, local])}}\Deffunc{getlocal} 3346This function returns the name and the value of the local variable
3129 3347with index \verb|local| of the function at level \verb|level| of the stack.
3130This function returns information about the local variables of the
3131function at level \verb|index| of the stack.
3132It can be called in three ways.
3133When called without a \verb|local| argument,
3134it returns a table, which associates variable names to their values.
3135When called with a name (a string) as \verb|local|,
3136it returns the value of the local variable with that name.
3137Finally, when called with an index (a number),
3138it returns the value and the name of the local variable
3139with that index.
3140(The first parameter has index 1, and so on, 3348(The first parameter has index 1, and so on,
3141until the last active local variable.) 3349until the last active local variable.)
3142In that case, the function returns \nil\ if there is no local 3350The function returns \nil\ if there is no local
3143variable with the given index. 3351variable with the given index,
3144The specification by index is the only way to distinguish 3352and raises an error when called with a \verb|level| out of range.
3145homonym variables in a function. 3353(You can call \verb|getstack| to check wheter the level is valid.)
3146 3354
3147\subsubsection*{\ff \T{setlocal (index, local, newvalue)}}\Deffunc{setlocal} 3355\subsubsection*{\ff \T{setlocal (level, local, value)}}\Deffunc{setlocal}
3148 3356
3149This function changes the values of the local variables of the 3357This function assigns the value \verb|value| to the local variable
3150function at level \verb|index| of the stack. 3358with index \verb|local| of the function at level \verb|level| of the stack.
3151The local variable can be specified by name or by index; 3359The function returns \nil\ if there is no local
3152see function \verb|getlocal|. 3360variable with the given index,
3361and raises an error when called with a \verb|level| out of range.
3153 3362
3154\subsubsection*{\ff \T{setcallhook (hook)}}\Deffunc{setcallhook} 3363\subsubsection*{\ff \T{setcallhook (hook)}}\Deffunc{setcallhook}
3155 3364
3156Sets the function \verb|hook| as the call hook; 3365Sets the function \verb|hook| as the call hook;
3157this hook will be called every time the interpreter starts and 3366this hook will be called every time the interpreter starts and
3158exits the execution of a function. 3367exits the execution of a function.
3159When Lua enters a function, 3368The only argument to this hook is the event name (\verb|"call"| or
3160the hook is called with the function been called, 3369\verb|"return"|).
3161plus the source and the line where the function is defined. 3370You can call \verb|getstack| with level 2 to get more information about
3162When Lua exits a function, 3371the function being called or returning
3163the hook is called with no arguments. 3372(level 0 is the \verb|getstack| function,
3373and level 1 is the hook function).
3164 3374
3165When called without arguments, 3375When called without arguments,
3166this function turns off call hooks. 3376this function turns off call hooks.
@@ -3171,9 +3381,9 @@ Sets the function \verb|hook| as the line hook;
3171this hook will be called every time the interpreter changes 3381this hook will be called every time the interpreter changes
3172the line of code it is executing. 3382the line of code it is executing.
3173The only argument to the hook is the line number the interpreter 3383The only argument to the hook is the line number the interpreter
3174is about to execut. 3384is about to execute.
3175This hook is called only if the active function 3385This hook is called only if the active function
3176has been compiled with debug information \see{pragma}. 3386has been compiled with debug information~\see{pragma}.
3177 3387
3178When called without arguments, 3388When called without arguments,
3179this function turns off line hooks. 3389this function turns off line hooks.
@@ -3182,24 +3392,22 @@ this function turns off line hooks.
3182\section{\Index{Lua Stand-alone}} \label{lua-sa} 3392\section{\Index{Lua Stand-alone}} \label{lua-sa}
3183 3393
3184Although Lua has been designed as an extension language, 3394Although Lua has been designed as an extension language,
3185the language can also be used as a stand-alone interpreter. 3395the language is frequently used as a stand-alone interpreter.
3186An implementation of such an interpreter, 3396An implementation of such an interpreter,
3187called simply \verb|lua|, 3397called simply \verb|lua|,
3188is provided with the standard distribution. 3398is provided with the standard distribution.
3189This program can be called with any sequence of the following arguments: 3399This program can be called with any sequence of the following arguments:
3190\begin{description} 3400\begin{description}
3191\item[\T{-v}] prints version information. 3401\item[\T{-}] executes \verb|stdin| as a file;
3192\item[\T{-d}] turns on debug information. 3402\item[\T{-d}] turns on debug information;
3193\item[\T{-e stat}] executes \verb|stat| as a Lua chunk. 3403\item[\T{-e stat}] executes string \verb|stat|;
3194\item[\T{-i}] runs interactively, 3404\item[\T{-f filename}] executes file \verb|filename| with the
3195accepting commands from standard input until an \verb|EOF|. 3405remaining arguments in table \verb|arg|;
3196Each line entered is immediately executed. 3406\item[\T{-i}] enters interactive mode with prompt;
3197\item[\T{-q}] same as \T{-i}, but without a prompt (quiet mode). 3407\item[\T{-q}] enters interactive mode without prompt;
3198\item[\T{-}] executes \verb|stdin| as a file. 3408\item[\T{-v}] prints version information;
3199\item[\T{--}] stops the execution of arguments; 3409\item[\T{var=value}] sets global \verb|var| to string \verb|"value"|;
3200all arguments after it are simply passed to the Lua script. 3410\item[\T{filename}] executes file \verb|filename|.
3201\item[\T{var=value}] sets global \verb|var| with string \verb|"value"|.
3202\item[\T{filename}] executes file \verb|filename| as a Lua chunk.
3203\end{description} 3411\end{description}
3204When called without arguments, 3412When called without arguments,
3205Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, 3413Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
@@ -3214,41 +3422,27 @@ will first interact with the user until an \verb|EOF|,
3214then will set \verb|a| to \verb|"test"|, 3422then will set \verb|a| to \verb|"test"|,
3215and finally will run the file \verb|prog.lua|. 3423and finally will run the file \verb|prog.lua|.
3216 3424
3217All arguments from the command line are passed to the Lua program in 3425When the option \T{-f filename} is used,
3218a table called \verb|arg|. 3426all following arguments from the command line
3219If the command line has the \verb|--| argument, 3427are passed to the Lua program in a table called \verb|arg|.
3220this argument is at index 0;
3221the arguments after it get indices 1, 2, \ldots;
3222and the arguments before it get negative indices.
3223The field \verb|n| gets the index of the last argument, 3428The field \verb|n| gets the index of the last argument,
3224and the field \verb|nn| gets the index of the first argument 3429and the field 0 gets the \T{filename}.
3225(always a negative number). 3430For instance, in the call
3226For instance: 3431\begin{verbatim}
3227\begin{verbatim} 3432$ lua a.lua -f b.lua t1 t3
3228$ lua -e "foreach(arg, print)" -- a b 3433\end{verbatim}
3229-1 foreach(arg, print) 3434the interpreter first runs the file \T{a.lua},
3230-2 -e 3435then creates a table \T{arg},
3231-3 lua 3436\begin{verbatim}
32320 -- 3437 arg = {"t1", "t3"; n = 2, [0] = "b.lua"}
32331 a 3438\end{verbatim}
32342 b 3439and then runs the file \T{b.lua}.
3235nn -3 3440
3236n 2 3441In interactive mode,
3237\end{verbatim}
3238If the command line has no \verb|--| argument,
3239all arguments have negative indices, with the last one at position -1.
3240As a general rule, if you want to traverse all the
3241arguments after the \verb|--|, you loop from 1 to \verb|arg.n|
3242(you can use the \verb|foreachi| function, for instance).
3243If you want to traverse all arguments,
3244you loop from \verb|arg.nn| until \verb|arg.n|.
3245In any case, you may call \verb|exit| at the end of a script,
3246to stop Lua from running the other arguments.
3247
3248When in interactive mode,
3249a multi-line statement can be written finishing intermediate 3442a multi-line statement can be written finishing intermediate
3250lines with a backslash (\verb|\|). 3443lines with a backslash (\verb|\|).
3251The prompt presented is the value of the global variable \verb|_PROMPT|. 3444If the global variable \verb|_PROMPT| is defined as a string,
3445its value is used as the prompt. \Index{_PROMPT}
3252Therefore, the prompt can be changed like below: 3446Therefore, the prompt can be changed like below:
3253\begin{verbatim} 3447\begin{verbatim}
3254$ lua _PROMPT='myprompt> ' -i 3448$ lua _PROMPT='myprompt> ' -i
@@ -3256,7 +3450,8 @@ $ lua _PROMPT='myprompt> ' -i
3256 3450
3257In Unix systems, Lua scripts can be made into executable programs 3451In Unix systems, Lua scripts can be made into executable programs
3258by using the \verb|#!| form, 3452by using the \verb|#!| form,
3259as in \verb|#!/usr/local/bin/lua|. 3453as in \verb|#!/usr/local/bin/lua|,
3454or \verb|#!/usr/local/bin/lua -f| to get other arguments.
3260 3455
3261 3456
3262\section*{Acknowledgments} 3457\section*{Acknowledgments}
@@ -3279,48 +3474,12 @@ the previous public versions of Lua,
3279some differences had to be introduced. 3474some differences had to be introduced.
3280Here is a list of all these incompatibilities. 3475Here is a list of all these incompatibilities.
3281 3476
3282\subsection*{Incompatibilities with \Index{version 3.1}} 3477\subsection*{Incompatibilities with \Index{version 3.2}}
3283\begin{itemize} 3478\begin{itemize}
3284\item 3479\item
3285In the debug API, the old variables \verb|lua_debug|,
3286\verb|lua_callhook| and \verb|lua_linehook| now live inside \verb|lua_state|.
3287Therefore, they are no longer directly accessible, and must be
3288manipulated only through the new functions \verb|lua_setdebug|,
3289\verb|lua_setcallhook| and \verb|lua_setlinehook|.
3290
3291\item Old pre-compiled code is obsolete, and must be re-compiled.
3292\end{itemize}
3293
3294\subsection*{Incompatibilities with \Index{version 3.0}}
3295\begin{itemize}
3296
3297\item To support multiple contexts,
3298Lua 3.1 must be explicitly opened before used,
3299with function \verb|lua_open|.
3300However, all standard libraries check whether Lua is already opened,
3301so any existing program that opens at least one standard
3302library before calling Lua does not need to be modified.
3303
3304\item Function \verb|dostring| no longer accepts an optional second argument,
3305with a temporary error handler.
3306This facility is now provided by function \verb|call|.
3307
3308\item Function \verb|gsub| no longer accepts an optional fourth argument
3309(a callback data, a table).
3310Closures replace this feature with advantage.
3311
3312\item The syntax for function declaration is now more restricted;
3313for instance, the old syntax \verb|function f[exp] (x) ... end| is not
3314accepted in Lua 3.1.
3315In these cases,
3316programs should use an explicit assignment instead, such as
3317\verb|f[exp] = function (x) ... end|.
3318 3480
3319\item Old pre-compiled code is obsolete, and must be re-compiled. 3481\item Old pre-compiled code is obsolete, and must be re-compiled.
3320 3482
3321\item The option \verb|a=b| in Lua stand-alone now sets \verb|a| to the
3322\M{string} \verb|b|, and not to the value of \verb|b|.
3323
3324\end{itemize} 3483\end{itemize}
3325 3484
3326% restore underscore to usual meaning 3485% restore underscore to usual meaning