aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-08-06 16:10:44 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-08-06 16:10:44 -0300
commita56e01a9a04be72d05987fb7610b60b9bd047234 (patch)
tree7806070e048b4752a859ea18c2a2f14803a485c9
parent4664f2e9270a956f6175481abe590ba4931b7477 (diff)
downloadlua-a56e01a9a04be72d05987fb7610b60b9bd047234.tar.gz
lua-a56e01a9a04be72d05987fb7610b60b9bd047234.tar.bz2
lua-a56e01a9a04be72d05987fb7610b60b9bd047234.zip
towards 5.0 alpha...
-rw-r--r--manual.tex1537
1 files changed, 811 insertions, 726 deletions
diff --git a/manual.tex b/manual.tex
index 883dd0c8..cbaf42df 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.55 2002/02/14 21:48:32 roberto Exp roberto $ 1% $Id: manual.tex,v 1.56 2002/06/06 12:49:28 roberto Exp roberto $
2 2
3\documentclass[11pt,twoside,draft]{article} 3\documentclass[11pt,twoside,draft]{article}
4\usepackage{fullpage} 4\usepackage{fullpage}
@@ -35,13 +35,14 @@
35 35
36\newcommand{\ff}{$\bullet$\ } 36\newcommand{\ff}{$\bullet$\ }
37 37
38\newcommand{\Version}{4.1 (beta)} 38\newcommand{\Version}{5.0 (alpha)}
39 39
40% changes to bnf.sty by LHF 40% changes to bnf.sty by LHF
41\renewcommand{\Or}{$|$ } 41\renewcommand{\Or}{$|$ }
42\renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}} 42\renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}}
43\renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}} 43\renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}}
44\renewcommand{\ter}[1]{{\rm`{\tt#1}'}} 44\renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
45\newcommand{\Nter}[1]{{\tt#1}}
45\newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } 46\newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: }
46 47
47\makeindex 48\makeindex
@@ -132,7 +133,7 @@ Waldemar Celes
132\tecgraf\ --- Computer Science Department --- PUC-Rio 133\tecgraf\ --- Computer Science Department --- PUC-Rio
133} 134}
134 135
135%\date{{\small \tt\$Date: 2002/02/14 21:48:32 $ $}} 136%\date{{\small \tt\$Date: 2002/06/06 12:49:28 $ $}}
136 137
137\maketitle 138\maketitle
138 139
@@ -272,10 +273,6 @@ If necessary,
272the host programmer can create multiple independent global 273the host programmer can create multiple independent global
273environments, and freely switch between them \see{mangstate}. 274environments, and freely switch between them \see{mangstate}.
274 275
275The global environment can be manipulated by Lua code or
276by the embedding program,
277using the API functions from the library that implements Lua.
278
279The unit of execution of Lua is called a \Def{chunk}. 276The unit of execution of Lua is called a \Def{chunk}.
280A chunk is simply a sequence of statements. 277A chunk is simply a sequence of statements.
281Statements are described in \See{stats}. 278Statements are described in \See{stats}.
@@ -299,9 +296,9 @@ Lua automatically detects the file type and acts accordingly.
299\subsection{\Index{Values and Types}} \label{TypesSec} 296\subsection{\Index{Values and Types}} \label{TypesSec}
300 297
301Lua is a \emph{dynamically typed language}. 298Lua is a \emph{dynamically typed language}.
302This means that 299That means that
303variables do not have types; only values do. 300variables do not have types; only values do.
304Therefore, there are no type definitions in the language. 301There are no type definitions in the language.
305All values carry their own type. 302All values carry their own type.
306 303
307There are seven \Index{basic types} in Lua: 304There are seven \Index{basic types} in Lua:
@@ -310,8 +307,8 @@ There are seven \Index{basic types} in Lua:
310\emph{Nil} is the type of the value \nil, 307\emph{Nil} is the type of the value \nil,
311whose main property is to be different from any other value; 308whose main property is to be different from any other value;
312usually it represents the absence of a useful value. 309usually it represents the absence of a useful value.
313\emph{Boolean} is the type of the values \False and \True. 310\emph{Boolean} is the type of the values \False{} and \True.
314In Lua, both \nil{} and \False make a condition fails, 311In Lua, both \nil{} and \False{} make a condition fails,
315and any other value makes it succeeds. 312and any other value makes it succeeds.
316\emph{Number} represents real (double-precision floating-point) numbers. 313\emph{Number} represents real (double-precision floating-point) numbers.
317\emph{String} represents arrays of characters. 314\emph{String} represents arrays of characters.
@@ -321,17 +318,17 @@ and so strings may contain any 8-bit character,
321including embedded zeros (\verb|'\0'|) \see{lexical}. 318including embedded zeros (\verb|'\0'|) \see{lexical}.
322 319
323Functions are \emph{first-class values} in Lua. 320Functions are \emph{first-class values} in Lua.
324This means that functions can be stored in variables, 321That means that functions can be stored in variables,
325passed as arguments to other functions, and returned as results. 322passed as arguments to other functions, and returned as results.
326Lua can call (and manipulate) functions written in Lua and 323Lua can call (and manipulate) functions written in Lua and
327functions written in C 324functions written in C
328\see{functioncall}. 325\see{functioncall}.
329 326
330The type \emph{userdata} is provided to allow 327The type \emph{userdata} is provided to allow the store of
331arbitrary \Index{C~pointers} to be stored in Lua variables. 328arbitrary C data in Lua variables.
332This type corresponds to a \verb|void*| 329This type corresponds to a block of raw memory
333and has no pre-defined operations in Lua, 330and has no pre-defined operations in Lua,
334except assignment and equality test. 331except assignment and identity test.
335However, by using \emph{metatables}, 332However, by using \emph{metatables},
336the programmer can define operations for userdata values 333the programmer can define operations for userdata values
337\see{metatables}. 334\see{metatables}.
@@ -370,6 +367,7 @@ and do not imply any kind of copy.
370The library function \verb|type| returns a string describing the type 367The library function \verb|type| returns a string describing the type
371of a given value \see{pdf-type}. 368of a given value \see{pdf-type}.
372 369
370
373\subsubsection{Metatables} 371\subsubsection{Metatables}
374 372
375Each table or userdata object in Lua may have a \Index{metatable}. 373Each table or userdata object in Lua may have a \Index{metatable}.
@@ -377,28 +375,29 @@ Each table or userdata object in Lua may have a \Index{metatable}.
377You can change several aspects of the behavior 375You can change several aspects of the behavior
378of an object by setting specific fields in its metatable. 376of an object by setting specific fields in its metatable.
379For instance, when an object is the operand of an addition, 377For instance, when an object is the operand of an addition,
380Lua checks for a function in the field \verb|"add"| in its metatable. 378Lua checks for a function in the field \verb|"__add"| in its metatable.
381If it finds one, 379If it finds one,
382Lua calls that function to perform the addition. 380Lua calls that function to perform the addition.
383 381
384A metatable works as a kind of an extended ``type'' for the object: 382We call the keys in a metatable \Index{events},
385Objects that share a metatable has identical behavior. 383and the values \Index{metamethods}.
384In the previous example, \verb|"add"| is the event,
385and the metamethod is the function that performs the addition.
386 386
387A metatable controls how an object behaves in arithmetic operations, 387A metatable controls how an object behaves in arithmetic operations,
388order comparisons, concatenation, and indexing. 388order comparisons, concatenation, and indexing.
389A metatable can also defines a function to be called when a userdata 389A metatable can also defines a function to be called when a userdata
390is garbage collected, 390is garbage collected.
391and how the garbage collector treats entries in a table
392\see{weak-table}.
393\See{metatable} gives a detailed description of which events you 391\See{metatable} gives a detailed description of which events you
394can control with metatables. 392can control with metatables.
395 393
396You can query and change the metatable of an object 394You can query and change the metatable of an object
397through the \verb|metatable| function \see{pdf-metatable}. 395through the \verb|setmetatable| and \verb|getmetatable|
396functions \see{pdf-getmetatable}.
398 397
399 398
400 399
401\subsection{\Index{Coercion}} \label{coercion} 400\subsection{Coercion} \label{coercion}
402 401
403Lua provides automatic conversion between 402Lua provides automatic conversion between
404string and number values at run time. 403string and number values at run time.
@@ -437,7 +436,7 @@ defined inside their scope \see{visibility}.
437\subsection{Garbage Collection}\label{GC} 436\subsection{Garbage Collection}\label{GC}
438 437
439Lua does automatic memory management. 438Lua does automatic memory management.
440This means that 439That means that
441you do not have to worry about allocating memory for new objects 440you do not have to worry about allocating memory for new objects
442and freeing it when the objects are no longer needed. 441and freeing it when the objects are no longer needed.
443Lua manages memory automatically by running 442Lua manages memory automatically by running
@@ -449,11 +448,11 @@ All objects in Lua are subject to automatic management:
449tables, userdata, functions, and strings. 448tables, userdata, functions, and strings.
450 449
451Using the C~API, 450Using the C~API,
452you can set garbage-collector tag methods for user-defined 451you can set garbage-collector metamethods for userdata \see{metatable}.
453types based on userdata \see{tag-method}. 452When it is about to free a userdata,
454Lua calls those functions when it is about to free a userdata 453Lua calls the metamethod associated with event \verb|gc| in the
455of the corresponding type. 454userdata's metatable.
456Using this facility, you can coordinate Lua's garbage collection 455Using such facility, you can coordinate Lua's garbage collection
457with external resource management 456with external resource management
458(such as closing files, network or database connections, 457(such as closing files, network or database connections,
459or freeing your own memory). 458or freeing your own memory).
@@ -493,8 +492,7 @@ A table with both weak keys and weak values allows the collection of
493both keys and values. 492both keys and values.
494In any case, if either the key or the value is collected, 493In any case, if either the key or the value is collected,
495the whole pair is removed from the table. 494the whole pair is removed from the table.
496The weakness of a table is controled by the 495The weakness of a table is set with the \verb|setmode| function.
497\verb|__weakmode| field in its metatable \see{weakmode}.
498 496
499 497
500%------------------------------------------------------------------------------ 498%------------------------------------------------------------------------------
@@ -570,8 +568,8 @@ may contain nested \verb|[[| $\ldots$ \verb|]]| pairs,
570and do not interpret escape sequences. 568and do not interpret escape sequences.
571For convenience, 569For convenience,
572when the opening \verb|[[| is immediately followed by a newline, 570when the opening \verb|[[| is immediately followed by a newline,
573this newline is not included in the string. 571the newline is not included in the string.
574This form is specially convenient for 572That form is specially convenient for
575writing strings that contain program pieces or 573writing strings that contain program pieces or
576other quoted strings. 574other quoted strings.
577As an example, in a system using ASCII 575As an example, in a system using ASCII
@@ -619,9 +617,8 @@ A single name can denote a global variable, a local variable,
619or a formal parameter in a function 617or a formal parameter in a function
620(formal parameters are just local variables): 618(formal parameters are just local variables):
621\begin{Produc} 619\begin{Produc}
622\produc{var}{name} 620\produc{var}{\Nter{Name}}
623\end{Produc}% 621\end{Produc}%
624
625Square brackets are used to index a table: 622Square brackets are used to index a table:
626\begin{Produc} 623\begin{Produc}
627\produc{var}{prefixexp \ter{[} exp \ter{]}} 624\produc{var}{prefixexp \ter{[} exp \ter{]}}
@@ -632,7 +629,7 @@ and the second expression identifies a specific entry inside that table.
632The syntax \verb|var.NAME| is just syntactic sugar for 629The syntax \verb|var.NAME| is just syntactic sugar for
633\verb|var["NAME"]|: 630\verb|var["NAME"]|:
634\begin{Produc} 631\begin{Produc}
635\produc{var}{prefixexp \ter{.} name} 632\produc{var}{prefixexp \ter{.} \Nter{Name}}
636\end{Produc}% 633\end{Produc}%
637 634
638The expression denoting the table to be indexed has a restricted syntax; 635The expression denoting the table to be indexed has a restricted syntax;
@@ -676,16 +673,6 @@ Each statement can be optionally followed by a semicolon:
676\produc{chunk}{\rep{stat \opt{\ter{;}}}} 673\produc{chunk}{\rep{stat \opt{\ter{;}}}}
677\end{Produc}% 674\end{Produc}%
678 675
679The notation used above is the usual extended BNF,
680in which
681\rep{\emph{a}}~means 0 or more \emph{a}'s, and
682\opt{\emph{a}}~means an optional \emph{a}.
683Non-terminals are shown in \emph{italics},
684keywords are shown in {\bf bold},
685and other terminal symbols are shown in {\tt typewriter} font,
686enclosed in single quotes.
687The complete syntax of Lua in extended BNF is given on page~\pageref{BNF}.
688
689\subsubsection{Blocks} 676\subsubsection{Blocks}
690A \Index{block} is a list of statements; 677A \Index{block} is a list of statements;
691syntactically, a block is equal to a chunk: 678syntactically, a block is equal to a chunk:
@@ -693,7 +680,7 @@ syntactically, a block is equal to a chunk:
693\produc{block}{chunk} 680\produc{block}{chunk}
694\end{Produc}% 681\end{Produc}%
695 682
696A block may be explicitly delimited: 683A block may be explicitly delimited to produce a single statement:
697\begin{Produc} 684\begin{Produc}
698\produc{stat}{\rwd{do} block \rwd{end}} 685\produc{stat}{\rwd{do} block \rwd{end}}
699\end{Produc}% 686\end{Produc}%
@@ -763,9 +750,9 @@ Lua also has a \rwd{for} statement, in two flavors \see{for}.
763 750
764The \Index{condition expression} \M{exp} of a 751The \Index{condition expression} \M{exp} of a
765control structure may return any value. 752control structure may return any value.
766All values different from \nil\ and \False\ are considered true 753All values different from \nil{} and \False{} are considered true
767(in particular, the number 0 and the empty string are also true); 754(in particular, the number 0 and the empty string are also true);
768both \False\ and \nil\ are considered false. 755both \False{} and \nil{} are considered false.
769 756
770The \rwd{return} statement is used to return values 757The \rwd{return} statement is used to return values
771from a function or from a chunk.\IndexKW{return} 758from a function or from a chunk.\IndexKW{return}
@@ -798,7 +785,7 @@ as in the idioms
798because now \rwd{return} and \rwd{break} are the last statements in 785because now \rwd{return} and \rwd{break} are the last statements in
799their (inner) blocks. 786their (inner) blocks.
800In practice, 787In practice,
801these idioms are only used during debugging. 788those idioms are only used during debugging.
802(For instance, a line `\verb|do return end|' can be added at the 789(For instance, a line `\verb|do return end|' can be added at the
803beginning of a chunk for syntax checking only.) 790beginning of a chunk for syntax checking only.)
804 791
@@ -809,10 +796,10 @@ one for numbers and one generic.
809\IndexKW{for}\IndexKW{in} 796\IndexKW{for}\IndexKW{in}
810 797
811The numerical \rwd{for} loop repeats a block of code while a 798The numerical \rwd{for} loop repeats a block of code while a
812control variables runs through an arithmetic progression. 799control variable runs through an arithmetic progression.
813It has the following syntax: 800It has the following syntax:
814\begin{Produc} 801\begin{Produc}
815\produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp} 802\produc{stat}{\rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
816 \rwd{do} block \rwd{end}} 803 \rwd{do} block \rwd{end}}
817\end{Produc}% 804\end{Produc}%
818The \emph{block} is repeated for \emph{name} starting at the value of 805The \emph{block} is repeated for \emph{name} starting at the value of
@@ -849,14 +836,13 @@ If you need the value of the loop variable \verb|var|,
849then assign it to another variable before breaking or exiting the loop. 836then assign it to another variable before breaking or exiting the loop.
850\end{itemize} 837\end{itemize}
851 838
852The generic \rwd{for} statement works both over tables 839The generic \rwd{for} statement works over functions,
853and over functions. 840called \Index{generators}.
854When used with a \IndexEmph{generator function}, 841It calls its generator to produce a new value for each iteration,
855it calls this function to produce a new value for each iteration,
856stopping when the new value is \nil. 842stopping when the new value is \nil.
857It has the following syntax: 843It has the following syntax:
858\begin{Produc} 844\begin{Produc}
859\produc{stat}{\rwd{for} name \rep{\ter{,} name} \rwd{in} explist1 845\produc{stat}{\rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
860 \rwd{do} block \rwd{end}} 846 \rwd{do} block \rwd{end}}
861\end{Produc}% 847\end{Produc}%
862A \rwd{for} statement like 848A \rwd{for} statement like
@@ -891,12 +877,6 @@ If you need these values,
891then assign them to other variables before breaking or exiting the loop. 877then assign them to other variables before breaking or exiting the loop.
892\end{itemize} 878\end{itemize}
893 879
894If the first result of the expression list is a table \verb|t|
895(instead of a function),
896then the loop works as if it has received \verb|next, t| as its
897expression list.
898That is, the loop iterates over the (key,value) pairs of the table.
899
900 880
901\subsubsection{Function Calls as Statements} \label{funcstat} 881\subsubsection{Function Calls as Statements} \label{funcstat}
902Because of possible side-effects, 882Because of possible side-effects,
@@ -912,7 +892,7 @@ Function calls are explained in \See{functioncall}.
912The declaration may include an initial assignment:\IndexKW{local} 892The declaration may include an initial assignment:\IndexKW{local}
913\begin{Produc} 893\begin{Produc}
914\produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}} 894\produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}}
915\produc{namelist}{name \rep{\ter{,} name}} 895\produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
916\end{Produc}% 896\end{Produc}%
917If present, an initial assignment has the same semantics 897If present, an initial assignment has the same semantics
918of a multiple assignment \see{assignment}. 898of a multiple assignment \see{assignment}.
@@ -938,14 +918,14 @@ The basic expressions in Lua are the following:
938\produc{exp}{tableconstructor} 918\produc{exp}{tableconstructor}
939\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}} 919\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
940\end{Produc}% 920\end{Produc}%
941\IndexKW{nil} 921\IndexKW{nil}\IndexKW{false}\IndexKW{true}
942 922
943An expression enclosed in parentheses always results in only one value. 923An expression enclosed in parentheses always results in only one value.
944Thus, 924Thus,
945\verb|(f(x,y,z))| is always a single value, 925\verb|(f(x,y,z))| is always a single value,
946even if \verb|f| returns several values. 926even if \verb|f| returns several values.
947(The value of \verb|(f(x,y,z))| is the first value returned by \verb|f| 927(The value of \verb|(f(x,y,z))| is the first value returned by \verb|f|
948or \nil\ if \verb|f| does not return any values.) 928or \nil{} if \verb|f| does not return any values.)
949 929
950\emph{Numbers} and \emph{literal strings} are explained in \See{lexical}; 930\emph{Numbers} and \emph{literal strings} are explained in \See{lexical};
951variables are explained in \See{variables}; 931variables are explained in \See{variables};
@@ -965,8 +945,8 @@ and unary \verb|-| (negation).
965If the operands are numbers, or strings that can be converted to 945If the operands are numbers, or strings that can be converted to
966numbers \see{coercion}, 946numbers \see{coercion},
967then all operations except exponentiation have the usual meaning, 947then all operations except exponentiation have the usual meaning,
968while exponentiation calls a global function \verb|pow|; 948while exponentiation calls a global function \verb|pow|; ??
969otherwise, an appropriate tag method is called \see{tag-method}. 949otherwise, an appropriate metamethod is called \see{metatable}.
970The standard mathematical library defines function \verb|pow|, 950The standard mathematical library defines function \verb|pow|,
971giving the expected meaning to \Index{exponentiation} 951giving the expected meaning to \Index{exponentiation}
972\see{mathlib}. 952\see{mathlib}.
@@ -976,7 +956,7 @@ The \Index{relational operators} in Lua are
976\begin{verbatim} 956\begin{verbatim}
977 == ~= < > <= >= 957 == ~= < > <= >=
978\end{verbatim} 958\end{verbatim}
979These operators always result in \False\ or \True. 959These operators always result in \False{} or \True.
980 960
981Equality (\verb|==|) first compares the type of its operands. 961Equality (\verb|==|) first compares the type of its operands.
982If the types are different, then the result is \False. 962If the types are different, then the result is \False.
@@ -986,6 +966,8 @@ Tables, userdata, and functions are compared \emph{by reference},
986that is, 966that is,
987two tables are considered equal only if they are the \emph{same} table. 967two tables are considered equal only if they are the \emph{same} table.
988 968
969??eq metamethod??
970
989Every time you create a new table (or userdata, or function), 971Every time you create a new table (or userdata, or function),
990this new value is different from any previously existing value. 972this new value is different from any previously existing value.
991 973
@@ -1003,7 +985,7 @@ The order operators work as follows.
1003If both arguments are numbers, then they are compared as such. 985If both arguments are numbers, then they are compared as such.
1004Otherwise, if both arguments are strings, 986Otherwise, if both arguments are strings,
1005then their values are compared according to the current locale. 987then their values are compared according to the current locale.
1006Otherwise, the ``lt'' tag method is called \see{tag-method}. 988Otherwise, the ``lt'' or the ``le'' metamethod is called \see{metatable}.
1007 989
1008 990
1009\subsubsection{Logical Operators} 991\subsubsection{Logical Operators}
@@ -1013,14 +995,14 @@ The \Index{logical operators} in Lua are
1013 and or not 995 and or not
1014\end{verbatim} 996\end{verbatim}
1015Like the control structures \see{control}, 997Like the control structures \see{control},
1016all logical operators consider both \False\ and \nil\ as false 998all logical operators consider both \False{} and \nil{} as false
1017and anything else as true. 999and anything else as true.
1018\IndexKW{and}\IndexKW{or}\IndexKW{not} 1000\IndexKW{and}\IndexKW{or}\IndexKW{not}
1019 1001
1020The operator \rwd{not} always return \False\ or \True. 1002The operator \rwd{not} always return \False{} or \True.
1021 1003
1022The conjunction operator \rwd{and} returns its first argument 1004The conjunction operator \rwd{and} returns its first argument
1023if its value is \False\ or \nil; 1005if its value is \False{} or \nil;
1024otherwise, \rwd{and} returns its second argument. 1006otherwise, \rwd{and} returns its second argument.
1025The disjunction operator \rwd{or} returns its first argument 1007The disjunction operator \rwd{or} returns its first argument
1026if it is different from \nil and \False; 1008if it is different from \nil and \False;
@@ -1039,41 +1021,19 @@ For example,
1039 10 and 20 -> 20 1021 10 and 20 -> 20
1040\end{verbatim} 1022\end{verbatim}
1041 1023
1042%There are two useful Lua idioms that use logical operators.
1043%The first idiom is
1044%\begin{verbatim}
1045% x = x or v
1046%\end{verbatim}
1047%which is equivalent to
1048%\begin{verbatim}
1049% if not x then x = v end
1050%\end{verbatim}
1051%This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set
1052%(provided that \verb|x| is not a boolean value).
1053
1054%The second idiom is
1055%\begin{verbatim}
1056% x = a and b or c
1057%\end{verbatim}
1058%which should be read as \verb|x = (a and b) or c|.
1059%This idiom is equivalent to
1060%\begin{verbatim}
1061% if a then x = b else x = c end
1062%\end{verbatim}
1063%provided that \verb|b| is not \nil.
1064
1065\subsubsection{Concatenation} \label{concat} 1024\subsubsection{Concatenation} \label{concat}
1066The string \Index{concatenation} operator in Lua is 1025The string \Index{concatenation} operator in Lua is
1067denoted by two dots (`\verb|..|'). 1026denoted by two dots (`\verb|..|').
1068If both operands are strings or numbers, then they are converted to 1027If both operands are strings or numbers, then they are converted to
1069strings according to the rules mentioned in \See{coercion}. 1028strings according to the rules mentioned in \See{coercion}.
1070Otherwise, the ``concat'' tag method is called \see{tag-method}. 1029Otherwise, the ``concat'' metamethod is called \see{metatable}.
1071 1030
1072\subsubsection{Precedence} 1031\subsubsection{Precedence}
1073\Index{Operator precedence} in Lua follows the table below, 1032\Index{Operator precedence} in Lua follows the table below,
1074from lower to higher priority: 1033from lower to higher priority:
1075\begin{verbatim} 1034\begin{verbatim}
1076 and or 1035 or
1036 and
1077 < > <= >= ~= == 1037 < > <= >= ~= ==
1078 .. 1038 ..
1079 + - 1039 + -
@@ -1091,7 +1051,7 @@ and may exchange the operands of commutative operators,
1091as long as these optimizations do not change normal results. 1051as long as these optimizations do not change normal results.
1092However, these optimizations may change some results 1052However, these optimizations may change some results
1093if you define non-associative (or non-commutative) 1053if you define non-associative (or non-commutative)
1094tag methods for these operators. 1054metamethods for those operators.
1095 1055
1096\subsubsection{Table Constructors} \label{tableconstructor} 1056\subsubsection{Table Constructors} \label{tableconstructor}
1097Table \Index{constructors} are expressions that create tables; 1057Table \Index{constructors} are expressions that create tables;
@@ -1102,7 +1062,8 @@ The general syntax for constructors is
1102\begin{Produc} 1062\begin{Produc}
1103\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}} 1063\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
1104\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}} 1064\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
1105\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp} 1065\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or
1066 \Nter{Name} \ter{=} exp \Or exp}
1106\produc{fieldsep}{\ter{,} \Or \ter{;}} 1067\produc{fieldsep}{\ter{,} \Or \ter{;}}
1107\end{Produc}% 1068\end{Produc}%
1108 1069
@@ -1110,8 +1071,8 @@ Each field of the form \verb|[exp1] = exp2| adds to the new table an entry
1110with key \verb|exp1| and value \verb|exp2|. 1071with key \verb|exp1| and value \verb|exp2|.
1111A field of the form \verb|name = exp| is equivalent to 1072A field of the form \verb|name = exp| is equivalent to
1112\verb|["name"] = exp|. 1073\verb|["name"] = exp|.
1113Finally, fields of the form \verb|exp| add to the new table entries 1074Finally, fields of the form \verb|exp| are equivalent to
1114with the given expression indexed by consecutive numerical integers, 1075\verb|[i] = exp|, where \verb|i| are consecutive numerical integers,
1115starting with 1. 1076starting with 1.
1116Fields in the other formats do not affect this counting. 1077Fields in the other formats do not affect this counting.
1117For example, 1078For example,
@@ -1151,16 +1112,16 @@ A \Index{function call} in Lua has the following syntax:
1151In a function call, 1112In a function call,
1152first \M{prefixexp} and \M{args} are evaluated. 1113first \M{prefixexp} and \M{args} are evaluated.
1153If the value of \M{prefixexp} has type \emph{function}, 1114If the value of \M{prefixexp} has type \emph{function},
1154then this function is called, 1115then that function is called,
1155with the given arguments. 1116with the given arguments.
1156Otherwise, the ``function'' tag method is called, 1117Otherwise, its ``call'' metamethod is called,
1157having as first parameter the value of \M{prefixexp}, 1118having as first parameter the value of \M{prefixexp},
1158followed by the original call arguments 1119followed by the original call arguments
1159\see{tag-method}. 1120\see{metatable}.
1160 1121
1161The form 1122The form
1162\begin{Produc} 1123\begin{Produc}
1163\produc{functioncall}{prefixexp \ter{:} name args} 1124\produc{functioncall}{prefixexp \ter{:} \Nter{name} args}
1164\end{Produc}% 1125\end{Produc}%
1165can be used to call ``methods''. 1126can be used to call ``methods''.
1166A call \verb|v:name(...)| 1127A call \verb|v:name(...)|
@@ -1235,28 +1196,40 @@ you must remove the line break before \verb|(g)|.
1235 1196
1236The syntax for function definition is\IndexKW{function} 1197The syntax for function definition is\IndexKW{function}
1237\begin{Produc} 1198\begin{Produc}
1238\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} 1199\produc{function}{\rwd{function} funcbody}
1239 block \rwd{end}} 1200\produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
1240\produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} 1201\end{Produc}%
1241 block \rwd{end}} 1202
1242\produc{funcname}{name \rep{\ter{.} name} \opt{\ter{:} name}} 1203The following syntactic sugar simplifies function definitions:
1204\begin{Produc}
1205\produc{stat}{\rwd{function} funcname funcbody}
1206\produc{stat}{\rwd{local} \rwd{function} \Nter{name} funcbody}
1207\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} \opt{\ter{:} \Nter{name}}}
1243\end{Produc}% 1208\end{Produc}%
1244The statement 1209The statement
1245\begin{verbatim} 1210\begin{verbatim}
1246 function f () ... end 1211 function f () ... end
1247\end{verbatim} 1212\end{verbatim}
1248is syntactic sugar for 1213translates to
1249\begin{verbatim} 1214\begin{verbatim}
1250 f = function () ... end 1215 f = function () ... end
1251\end{verbatim} 1216\end{verbatim}
1252and the statement 1217The statement
1253\begin{verbatim} 1218\begin{verbatim}
1254 function t.a.b.c.f () ... end 1219 function t.a.b.c.f () ... end
1255\end{verbatim} 1220\end{verbatim}
1256is syntactic sugar for 1221translates to
1257\begin{verbatim} 1222\begin{verbatim}
1258 t.a.b.c.f = function () ... end 1223 t.a.b.c.f = function () ... end
1259\end{verbatim} 1224\end{verbatim}
1225The statement
1226\begin{verbatim}
1227 local function f () ... end
1228\end{verbatim}
1229translates to
1230\begin{verbatim}
1231 local f; f = function () ... end
1232\end{verbatim}
1260 1233
1261A function definition is an executable expression, 1234A function definition is an executable expression,
1262whose value has type \emph{function}. 1235whose value has type \emph{function}.
@@ -1267,7 +1240,8 @@ the function is \emph{instantiated} (or \emph{closed}).
1267This function instance (or \emph{closure}) 1240This function instance (or \emph{closure})
1268is the final value of the expression. 1241is the final value of the expression.
1269Different instances of the same function 1242Different instances of the same function
1270may refer to different non-local variables \see{visibility}. 1243may refer to different non-local variables \see{visibility}
1244and may have different tables of globals \see{global-table}.
1271 1245
1272Parameters act as local variables, 1246Parameters act as local variables,
1273initialized with the argument values: 1247initialized with the argument values:
@@ -1355,7 +1329,7 @@ Notice that, in a declaration like \verb|local x = x|,
1355the new \verb|x| being declared is not in scope yet, 1329the new \verb|x| being declared is not in scope yet,
1356so the second \verb|x| refers to the ``outside'' variable. 1330so the second \verb|x| refers to the ``outside'' variable.
1357 1331
1358Because of this \Index{lexical scoping} rules, 1332Because of those \Index{lexical scoping} rules,
1359local variables can be freely accessed by functions 1333local variables can be freely accessed by functions
1360defined inside their scope. 1334defined inside their scope.
1361For instance: 1335For instance:
@@ -1384,6 +1358,8 @@ while all of them share the same \verb|x|.
1384 1358
1385\subsection{Error Handling} \label{error} 1359\subsection{Error Handling} \label{error}
1386 1360
1361%% TODO Must be rewritten!!!
1362
1387Because Lua is an extension language, 1363Because Lua is an extension language,
1388all Lua actions start from C~code in the host program 1364all Lua actions start from C~code in the host program
1389calling a function from the Lua library. 1365calling a function from the Lua library.
@@ -1427,12 +1403,13 @@ Every table and userdata value in Lua may have a \emph{metatable}.
1427This \IndexEmph{metatable} is a table that defines the behavior of 1403This \IndexEmph{metatable} is a table that defines the behavior of
1428the original table and userdata under some operations. 1404the original table and userdata under some operations.
1429You can query and change the metatable of an object with 1405You can query and change the metatable of an object with
1430function \verb|metatable| \see{pdf-metatable}. 1406functions \verb|setmetatable| and \verb|getmetatable| \see{pdf-getmetatable}.
1431 1407
1432For each of these operations Lua associates a specific key. 1408For each of those operations Lua associates a specific key,
1433When Lua performs one of these operations over a table or a userdata, 1409called an \emph{event}.
1434if checks whether that object has a metatable with the corresponding key. 1410When Lua performs one of those operations over a table or a userdata,
1435If so, the value associated with that key (the \IndexEmph{handler}) 1411if checks whether that object has a metatable with the corresponding event.
1412If so, the value associated with that key (the \IndexEmph{metamethod})
1436controls how Lua will perform the operation. 1413controls how Lua will perform the operation.
1437 1414
1438Metatables control the operations listed next. 1415Metatables control the operations listed next.
@@ -1451,7 +1428,7 @@ The code shown here in Lua is only illustrative;
1451the real behavior is hard coded in the interpreter, 1428the real behavior is hard coded in the interpreter,
1452and it is much more efficient than this simulation. 1429and it is much more efficient than this simulation.
1453All functions used in these descriptions 1430All functions used in these descriptions
1454(\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)\ 1431(\verb|rawget|, \verb|tonumber|, etc.)
1455are described in \See{predefined}. 1432are described in \See{predefined}.
1456 1433
1457\begin{description} 1434\begin{description}
@@ -1469,10 +1446,10 @@ then Lua tries the second operand.
1469 return metatable(op1)[event] or metatable(op2)[event] 1446 return metatable(op1)[event] or metatable(op2)[event]
1470 end 1447 end
1471\end{verbatim} 1448\end{verbatim}
1472Using this function, 1449Using that function,
1473the behavior of the ``add'' operation is 1450the behavior of the ``add'' operation is
1474\begin{verbatim} 1451\begin{verbatim}
1475 function add_op (op1, op2) 1452 function add_event (op1, op2)
1476 local o1, o2 = tonumber(op1), tonumber(op2) 1453 local o1, o2 = tonumber(op1), tonumber(op2)
1477 if o1 and o2 then -- both operands are numeric 1454 if o1 and o2 then -- both operands are numeric
1478 return o1+o2 -- '+' here is the primitive 'add' 1455 return o1+o2 -- '+' here is the primitive 'add'
@@ -1503,8 +1480,8 @@ Behavior similar to the ``add'' operation.
1503\item[``pow'':]\IndexTM{pow} 1480\item[``pow'':]\IndexTM{pow}
1504the \verb|^| operation (exponentiation) operation. 1481the \verb|^| operation (exponentiation) operation.
1505\begin{verbatim} ?? 1482\begin{verbatim} ??
1506 function pow_op (op1, op2) 1483 function pow_event (op1, op2)
1507 local h = getbinhandler(op1, op2, "__pow") 1484 local h = getbinhandler(op1, op2, "__pow") ???
1508 if h then 1485 if h then
1509 -- call the handler with both operands 1486 -- call the handler with both operands
1510 return h(op1, op2) 1487 return h(op1, op2)
@@ -1517,7 +1494,7 @@ the \verb|^| operation (exponentiation) operation.
1517\item[``unm'':]\IndexTM{unm} 1494\item[``unm'':]\IndexTM{unm}
1518the unary \verb|-| operation. 1495the unary \verb|-| operation.
1519\begin{verbatim} 1496\begin{verbatim}
1520 function unm_op (op) 1497 function unm_event (op)
1521 local o = tonumber(op) 1498 local o = tonumber(op)
1522 if o then -- operand is numeric 1499 if o then -- operand is numeric
1523 return -o -- '-' here is the primitive 'unm' 1500 return -o -- '-' here is the primitive 'unm'
@@ -1537,7 +1514,7 @@ the unary \verb|-| operation.
1537\item[``lt'':]\IndexTM{lt} 1514\item[``lt'':]\IndexTM{lt}
1538the \verb|<| operation. 1515the \verb|<| operation.
1539\begin{verbatim} 1516\begin{verbatim}
1540 function lt_op (op1, op2) 1517 function lt_event (op1, op2)
1541 if type(op1) == "number" and type(op2) == "number" then 1518 if type(op1) == "number" and type(op2) == "number" then
1542 return op1 < op2 -- numeric comparison 1519 return op1 < op2 -- numeric comparison
1543 elseif type(op1) == "string" and type(op2) == "string" then 1520 elseif type(op1) == "string" and type(op2) == "string" then
@@ -1552,18 +1529,41 @@ the \verb|<| operation.
1552 end 1529 end
1553 end 1530 end
1554\end{verbatim} 1531\end{verbatim}
1555The other order operators also use the \verb|lt_op| function, 1532\verb|a>b| is equivalent to \verb|b<a|.
1556according to the usual equivalences: 1533
1534\item[``le'':]\IndexTM{lt}
1535the \verb|<=| operation.
1557\begin{verbatim} 1536\begin{verbatim}
1558 a>b <=> b<a 1537 function lt_event (op1, op2)
1559 a<=b <=> not (b<a) 1538 if type(op1) == "number" and type(op2) == "number" then
1560 a>=b <=> not (a<b) 1539 return op1 < op2 -- numeric comparison
1540 elseif type(op1) == "string" and type(op2) == "string" then
1541 return op1 < op2 -- lexicographic comparison
1542 else
1543 local h = getbinhandler(op1, op2, "__le")
1544 if h then
1545 return h(op1, op2)
1546 else
1547 h = getbinhandler(op1, op2, "__lt")
1548 if h then
1549 return not h(op2, op1)
1550 else
1551 error("unexpected type at comparison");
1552 end
1553 end
1554 end
1555 end
1561\end{verbatim} 1556\end{verbatim}
1557\verb|a>=b| is equivalent to \verb|b<=a|.
1558Notice that, in the absence of a ``le'' metamethod,
1559Lua tries the ``lt'', assuming that \verb|a<=b| is
1560equivalent to \verb|not (b<a)|.
1561
1562 1562
1563\item[``concat'':]\IndexTM{concatenation} 1563\item[``concat'':]\IndexTM{concatenation}
1564the \verb|..| (concatenation) operation. 1564the \verb|..| (concatenation) operation.
1565\begin{verbatim} 1565\begin{verbatim}
1566 function concat_op (op1, op2) 1566 function concat_event (op1, op2)
1567 if (type(op1) == "string" or type(op1) == "number") and 1567 if (type(op1) == "string" or type(op1) == "number") and
1568 (type(op2) == "string" or type(op2) == "number") then 1568 (type(op2) == "string" or type(op2) == "number") then
1569 return op1..op2 -- primitive string concatenation 1569 return op1..op2 -- primitive string concatenation
@@ -1586,45 +1586,57 @@ See the ``gettable'' operation for its semantics.
1586\item[``gettable'':]\IndexTM{gettable} 1586\item[``gettable'':]\IndexTM{gettable}
1587called whenever Lua accesses an indexed variable. 1587called whenever Lua accesses an indexed variable.
1588\begin{verbatim} 1588\begin{verbatim}
1589 function gettable_op (table, key) 1589 function gettable_event (table, key)
1590 local h = metatable(table).__gettable 1590 local h
1591 if h == nil then 1591 if type(table) == "table" then
1592 if type(table) ~= "table" then 1592 local v = rawget(table, key)
1593 if v ~= nil then return v end
1594 h = metatable(table).__index
1595 if h == nil then return nil end
1596 else
1597 h = metatable(table).__gettable
1598 if h == nil then
1593 error("indexed expression not a table"); 1599 error("indexed expression not a table");
1594 else
1595 local v = rawget(table, key)
1596 if v ~= nil then return v end
1597 h = metatable(table).__index
1598 if h == nil then return nil end
1599 end 1600 end
1600 end 1601 end
1601 if type(h) == 'function' then 1602 if type(h) == "function" then
1602 return h(table, key) -- call the handler 1603 return h(table, key) -- call the handler
1603 else return h[key] -- or repeat operation with it 1604 else return h[key] -- or repeat operation with it
1604 end 1605 end
1605\end{verbatim} 1606\end{verbatim}
1606 1607
1608\item[``newindex'':]\IndexTM{index}
1609This handler is called when Lua tries to insert the value of an index
1610not present in a table.
1611See the ``settable'' operation for its semantics.
1612
1607\item[``settable'':]\IndexTM{settable} 1613\item[``settable'':]\IndexTM{settable}
1608called when Lua assigns to an indexed variable. 1614called when Lua assigns to an indexed variable.
1609\begin{verbatim} 1615\begin{verbatim}
1610 function settable_event (table, key, value) 1616 function settable_event (table, key, value)
1611 local h = metatable(table).__settable 1617 local h
1612 if h == nil then 1618 if type(table) == "table" then
1613 if type(table) ~= "table" then 1619 local v = rawget(table, key)
1614 error("indexed expression not a table") 1620 if v ~= nil then rawset(table, key, value); return end
1615 rawset(table, key, value) 1621 h = metatable(table).__newindex
1622 if h == nil then rawset(table, key, value); return end
1616 else 1623 else
1617 if type(h) == 'function' then 1624 h = metatable(table).__settable
1618 h(table, key, value) -- call the handler 1625 if h == nil then
1619 else h[key] = value -- or repeat operation with it 1626 error("indexed expression not a table");
1627 end
1620 end 1628 end
1629 if type(h) == "function" then
1630 return h(table, key,value) -- call the handler
1631 else h[key] = value -- or repeat operation with it
1621 end 1632 end
1622\end{verbatim} 1633\end{verbatim}
1623 1634
1635
1624\item[``call'':]\IndexTM{call} 1636\item[``call'':]\IndexTM{call}
1625called when Lua calls a value. 1637called when Lua calls a value.
1626\begin{verbatim} 1638\begin{verbatim}
1627 function function_op (func, ...) 1639 function function_event (func, ...)
1628 if type(func) == "function" then 1640 if type(func) == "function" then
1629 return func(unpack(arg)) -- regular call 1641 return func(unpack(arg)) -- regular call
1630 else 1642 else
@@ -1643,13 +1655,12 @@ called when Lua calls a value.
1643 1655
1644\subsubsection{Metatables and Garbage collection} 1656\subsubsection{Metatables and Garbage collection}
1645 1657
1646Metatables also control some aspects of the garbage collector. 1658Metatables may also define \IndexEmph{finalizer} methods
1647First, they are used to define \IndexEmph{finalizer} methods
1648for userdata values. 1659for userdata values.
1649For each userdata to be collected, 1660For each userdata to be collected,
1650Lua does the equivalent of the following function: 1661Lua does the equivalent of the following function:
1651\begin{verbatim} 1662\begin{verbatim}
1652 function gc_op (obj) 1663 function gc_event (obj)
1653 local h = metatable(obj).__gc 1664 local h = metatable(obj).__gc
1654 if h then 1665 if h then
1655 h(obj) 1666 h(obj)
@@ -1661,23 +1672,14 @@ the finalizers for userdata are called in \emph{reverse}
1661order of their creation, 1672order of their creation,
1662that is, the first finalizer to be called is the one associated 1673that is, the first finalizer to be called is the one associated
1663with the last userdata created in the program 1674with the last userdata created in the program
1664(among those to be collected in this cycle). 1675(among those to be collected in the same cycle).
1665
1666Second, metatables control the weakmode of tables \see{weak-table}.
1667The weakmode of a table \verb|t| is defined by a string:
1668\label{weakmode}
1669\begin{verbatim}
1670 s = metatable(t).__weakmode
1671\end{verbatim}
1672Valid values for this string are \verb|"k"| for weak keys,
1673\verb|"v"| for weak values,
1674and \verb|"kv"| for both.
1675 1676
1676 1677
1677 1678
1678%------------------------------------------------------------------------------ 1679%------------------------------------------------------------------------------
1679\section{The Application Program Interface}\label{API} 1680\section{The Application Program Interface}\label{API}
1680\index{C API} 1681\index{C API}
1682
1681This section describes the API for Lua, that is, 1683This section describes the API for Lua, that is,
1682the set of C~functions available to the host program to communicate 1684the set of C~functions available to the host program to communicate
1683with Lua. 1685with Lua.
@@ -1717,7 +1719,7 @@ To release a state created with \verb|lua_open|, call
1717\end{verbatim} 1719\end{verbatim}
1718\DefAPI{lua_close} 1720\DefAPI{lua_close}
1719This function destroys all objects in the given Lua environment 1721This function destroys all objects in the given Lua environment
1720(calling the corresponding garbage-collection tag methods, if any) 1722(calling the corresponding garbage-collection metamethods, if any)
1721and frees all dynamic memory used by that state. 1723and frees all dynamic memory used by that state.
1722Usually, you do not need to call this function, 1724Usually, you do not need to call this function,
1723because all resources are naturally released when your program ends. 1725because all resources are naturally released when your program ends.
@@ -1734,8 +1736,9 @@ all functions in the Lua API need a state as their first argument.
1734\subsection{Threads} 1736\subsection{Threads}
1735 1737
1736Lua offers a partial support for multiple threads of execution. 1738Lua offers a partial support for multiple threads of execution.
1737If you have a C~library that offers multi-threading or co-routines, 1739If you have a C~library that offers multi-threading,
1738then Lua can cooperate with it to implement the equivalent facility in Lua. 1740then Lua can cooperate with it to implement the equivalent facility in Lua.
1741Also, Lua implements its own coroutine system on top of threads.
1739The following function creates a new ``thread'' in Lua: 1742The following function creates a new ``thread'' in Lua:
1740\begin{verbatim} 1743\begin{verbatim}
1741 lua_State *lua_newthread (lua_State *L); 1744 lua_State *lua_newthread (lua_State *L);
@@ -1761,10 +1764,15 @@ Instead, you must close the state itself.
1761 1764
1762\subsection{The Stack and Indices} 1765\subsection{The Stack and Indices}
1763 1766
1764Lua uses a \emph{stack} to pass values to and from C. 1767Lua uses a virtual \emph{stack} to pass values to and from C.
1765Each element in this stack represents a Lua value 1768Each element in this stack represents a Lua value
1766(\nil, number, string, etc.). 1769(\nil, number, string, etc.).
1767 1770
1771Each C invocation has its own stack.
1772Whenever Lua calls C, the called function gets a new stack,
1773which is independent of previous stacks or of stacks of still
1774active C functions.
1775
1768For convenience, 1776For convenience,
1769most query operations in the API do not follow a strict stack discipline. 1777most query operations in the API do not follow a strict stack discipline.
1770Instead, they can refer to any element in the stack by using an \emph{index}: 1778Instead, they can refer to any element in the stack by using an \emph{index}:
@@ -1797,14 +1805,18 @@ When you interact with Lua API,
1797\emph{you are responsible for controlling stack overflow}. 1805\emph{you are responsible for controlling stack overflow}.
1798The function 1806The function
1799\begin{verbatim} 1807\begin{verbatim}
1800 int lua_checkstack (lua_State *L, int size); 1808 int lua_checkstack (lua_State *L, int extra);
1801\end{verbatim} 1809\end{verbatim}
1802\DefAPI{lua_checkstack} 1810\DefAPI{lua_checkstack}
1803returns true if there is at lease \verb|size| 1811grows the stack size to \verb|top + extra| elements;
1804stack positions still available. 1812it returns false if it cannot grow the stack to that size.
1813This function never shrinks the stack;
1814if the stack is already bigger than the new size,
1815it is left unchanged.
1816
1805Whenever Lua calls C, \DefAPI{LUA_MINSTACK} 1817Whenever Lua calls C, \DefAPI{LUA_MINSTACK}
1806it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true, 1818it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true,
1807that is, that 1819that is,
1808at least \verb|LUA_MINSTACK| positions are still available. 1820at least \verb|LUA_MINSTACK| positions are still available.
1809\verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20, 1821\verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20,
1810so that usually you do not have to worry about stack space 1822so that usually you do not have to worry about stack space
@@ -1812,21 +1824,20 @@ unless your code has loops pushing elements onto the stack.
1812 1824
1813Most query functions accept as indices any value inside the 1825Most query functions accept as indices any value inside the
1814available stack space, that is, indices up to the maximum stack size 1826available stack space, that is, indices up to the maximum stack size
1815you (or Lua) have checked through \verb|lua_checkstack|. 1827you (or Lua) have set through \verb|lua_checkstack|.
1816Such indices are called \emph{acceptable indices}. 1828Such indices are called \emph{acceptable indices}.
1817More formally, we define an \IndexEmph{acceptable index} 1829More formally, we define an \IndexEmph{acceptable index}
1818as follows: 1830as follows:
1819\begin{verbatim} 1831\begin{verbatim}
1820 (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) 1832 (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace)
1821\end{verbatim} 1833\end{verbatim}
1822Note that 0 is not an acceptable index. 1834Note that 0 is never an acceptable index.
1823 1835
1824Unless otherwise noticed, 1836Unless otherwise noticed,
1825any function that accepts valid indices can also be called with 1837any function that accepts valid indices can also be called with
1826\Index{pseudo-indices}, 1838\Index{pseudo-indices},
1827which represent some Lua values that are accessible to the C~code 1839which represent some Lua values that are accessible to the C~code
1828but are not in the stack. 1840but are not in the stack.
1829
1830Pseudo-indices are used to access the table of globals \see{globals}, 1841Pseudo-indices are used to access the table of globals \see{globals},
1831the registry, and the upvalues of a C function \see{c-closure}. 1842the registry, and the upvalues of a C function \see{c-closure}.
1832 1843
@@ -1855,14 +1866,14 @@ A useful macro defined in the \verb|lua.h| is
1855\DefAPI{lua_pop} 1866\DefAPI{lua_pop}
1856which pops \verb|n| elements from the stack. 1867which pops \verb|n| elements from the stack.
1857 1868
1858\verb|lua_pushvalue| pushes onto the stack a \emph{copy} of the element 1869\verb|lua_pushvalue| pushes onto the stack a copy of the element
1859at the given index. 1870at the given index.
1860\verb|lua_remove| removes the element at the given position, 1871\verb|lua_remove| removes the element at the given position,
1861shifting down the elements above that position to fill the gap. 1872shifting down the elements above that position to fill the gap.
1862\verb|lua_insert| moves the top element into the given position, 1873\verb|lua_insert| moves the top element into the given position,
1863shifting up the elements above that position to open space. 1874shifting up the elements above that position to open space.
1864\verb|lua_replace| moves the top element into the given position, 1875\verb|lua_replace| moves the top element into the given position,
1865without shifting any element (therefore it replaces the value at 1876without shifting any element (therefore replacing the value at
1866the given position). 1877the given position).
1867These functions accept only valid indices. 1878These functions accept only valid indices.
1868(Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with 1879(Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with
@@ -1899,11 +1910,13 @@ the following functions are available:
1899 int lua_isfunction (lua_State *L, int index); 1910 int lua_isfunction (lua_State *L, int index);
1900 int lua_iscfunction (lua_State *L, int index); 1911 int lua_iscfunction (lua_State *L, int index);
1901 int lua_isuserdata (lua_State *L, int index); 1912 int lua_isuserdata (lua_State *L, int index);
1913 int lua_isdataval (lua_State *L, int index);
1902\end{verbatim} 1914\end{verbatim}
1903\DefAPI{lua_type} 1915\DefAPI{lua_type}
1904\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring} 1916\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
1905\DefAPI{lua_istable}\DefAPI{lua_isboolean} 1917\DefAPI{lua_istable}\DefAPI{lua_isboolean}
1906\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata} 1918\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}
1919\DefAPI{lua_isuserdata}\DefAPI{lua_isdataval}
1907These functions can be called with any acceptable index. 1920These functions can be called with any acceptable index.
1908 1921
1909\verb|lua_type| returns the type of a value in the stack, 1922\verb|lua_type| returns the type of a value in the stack,
@@ -1917,19 +1930,20 @@ defined in \verb|lua.h|:
1917\verb|LUA_TSTRING|, 1930\verb|LUA_TSTRING|,
1918\verb|LUA_TTABLE|, 1931\verb|LUA_TTABLE|,
1919\verb|LUA_TFUNCTION|, 1932\verb|LUA_TFUNCTION|,
1920\verb|LUA_TUSERDATA|. 1933\verb|LUA_TUSERDATA|,
1921The following function translates a tag to a type name: 1934\verb|LUA_TLIGHTUSERDATA|.
1935The following function translates such constants to a type name:
1922\begin{verbatim} 1936\begin{verbatim}
1923 const char *lua_type (lua_State *L, int index); 1937 const char *lua_typename (lua_State *L, int type);
1924\end{verbatim} 1938\end{verbatim}
1925\DefAPI{lua_typename} 1939\DefAPI{lua_typename}
1926 1940
1927The \verb|lua_is*| functions return~1 if the object is compatible 1941The \verb|lua_is*| functions return~1 if the object is compatible
1928with the given type, and 0 otherwise. 1942with the given type, and 0 otherwise.
1929(\verb|lua_isboolean| is an exception to this rule, 1943\verb|lua_isboolean| is an exception to this rule,
1930and it succeeds only for boolean values; 1944and it succeeds only for boolean values
1931otherwise it would be useless, 1945(otherwise it would be useless,
1932as any value is compatible with a boolean.) 1946as any value is compatible with a boolean).
1933They always return 0 for a non-valid index. 1947They always return 0 for a non-valid index.
1934\verb|lua_isnumber| accepts numbers and numerical strings, 1948\verb|lua_isnumber| accepts numbers and numerical strings,
1935\verb|lua_isstring| accepts strings and numbers \see{coercion}, 1949\verb|lua_isstring| accepts strings and numbers \see{coercion},
@@ -1937,7 +1951,7 @@ and \verb|lua_isfunction| accepts both Lua functions and C~functions.
1937To distinguish between Lua functions and C~functions, 1951To distinguish between Lua functions and C~functions,
1938you should use \verb|lua_iscfunction|. 1952you should use \verb|lua_iscfunction|.
1939To distinguish between numbers and numerical strings, 1953To distinguish between numbers and numerical strings,
1940you can use \verb|lua_rawtag| (or \verb|lua_tag|). 1954you can use \verb|lua_type|.
1941 1955
1942The API also has functions to compare two values in the stack: 1956The API also has functions to compare two values in the stack:
1943\begin{verbatim} 1957\begin{verbatim}
@@ -1946,11 +1960,9 @@ The API also has functions to compare two values in the stack:
1946\end{verbatim} 1960\end{verbatim}
1947\DefAPI{lua_equal} \DefAPI{lua_lessthan} 1961\DefAPI{lua_equal} \DefAPI{lua_lessthan}
1948These functions are equivalent to their counterparts in Lua \see{rel-ops}. 1962These functions are equivalent to their counterparts in Lua \see{rel-ops}.
1949Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event|
1950described in \See{tag-method}.
1951Both functions return 0 if any of the indices are non-valid. 1963Both functions return 0 if any of the indices are non-valid.
1952 1964
1953\subsection{Getting Values from the Stack} 1965\subsection{Getting Values from the Stack}\label{lua-to}
1954 1966
1955To translate a value in the stack to a specific C~type, 1967To translate a value in the stack to a specific C~type,
1956you can use the following conversion functions: 1968you can use the following conversion functions:
@@ -1969,9 +1981,9 @@ When called with a non-valid index,
1969they act as if the given value had an incorrect type. 1981they act as if the given value had an incorrect type.
1970 1982
1971\verb|lua_toboolean| converts the Lua value at the given index 1983\verb|lua_toboolean| converts the Lua value at the given index
1972to a C ``boolean'' value (that is, (int)0 or (int)1). 1984to a C ``boolean'' value (that is, 0 or 1).
1973Like all tests in Lua, it returns 1 for any Lua value different from 1985Like all tests in Lua, it returns 1 for any Lua value different from
1974\False\ and \nil; 1986\False{} and \nil;
1975otherwise it returns 0. 1987otherwise it returns 0.
1976It also returns 0 when called with a non-valid index. 1988It also returns 0 when called with a non-valid index.
1977(If you want to accept only real boolean values, 1989(If you want to accept only real boolean values,
@@ -2010,10 +2022,7 @@ This value must be a C~function;
2010otherwise, \verb|lua_tocfunction| returns \verb|NULL|. 2022otherwise, \verb|lua_tocfunction| returns \verb|NULL|.
2011The type \verb|lua_CFunction| is explained in \See{LuacallC}. 2023The type \verb|lua_CFunction| is explained in \See{LuacallC}.
2012 2024
2013\verb|lua_touserdata| converts a value to \verb|void*|. 2025\verb|lua_touserdata| is explained in \See{userdata}.
2014This value must have type \emph{userdata};
2015otherwise, \verb|lua_touserdata| returns \verb|NULL|.
2016
2017 2026
2018 2027
2019\subsection{Pushing Values onto the Stack} 2028\subsection{Pushing Values onto the Stack}
@@ -2027,9 +2036,11 @@ push C~values onto the stack:
2027 void lua_pushstring (lua_State *L, const char *s); 2036 void lua_pushstring (lua_State *L, const char *s);
2028 void lua_pushnil (lua_State *L); 2037 void lua_pushnil (lua_State *L);
2029 void lua_pushcfunction (lua_State *L, lua_CFunction f); 2038 void lua_pushcfunction (lua_State *L, lua_CFunction f);
2039 void lua_pushlightuserdata (lua_State *L, void *p);
2030\end{verbatim} 2040\end{verbatim}
2041
2031\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring} 2042\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring}
2032\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag}\DefAPI{lua_pushboolean} 2043\DefAPI{lua_pushcfunction}\DefAPI{lua_pushlightuserdata}\DefAPI{lua_pushboolean}
2033\DefAPI{lua_pushnil}\label{pushing} 2044\DefAPI{lua_pushnil}\label{pushing}
2034These functions receive a C~value, 2045These functions receive a C~value,
2035convert it to a corresponding Lua value, 2046convert it to a corresponding Lua value,
@@ -2041,12 +2052,42 @@ make an internal copy of the given string.
2041otherwise, you should use the more general \verb|lua_pushlstring|, 2052otherwise, you should use the more general \verb|lua_pushlstring|,
2042which accepts an explicit size. 2053which accepts an explicit size.
2043 2054
2055You can also push ``formatted'' strings:
2056\begin{verbatim}
2057 const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
2058 const char *lua_pushvfstring (lua_State *L, const char *fmt,
2059 va_list argp);
2060\end{verbatim}
2061\DefAPI{lua_pushfstring}\DefAPI{lua_pushvfstring}
2062Both functions push onto the stack a formatted string,
2063and return a pointer to that string.
2064These functions are similar to \verb|sprintf| and \verb|vsprintf|,
2065but with some important differences:
2066\begin{itemize}
2067\item You do not have to allocate the space for the result;
2068the result is a Lua string, and Lua takes care of memory allocation
2069(and deallocation, later).
2070\item The conversion specifiers are quite restricted.
2071There are no flags, widths, or precisions.
2072The conversion specifiers can be simply
2073\verb|%%| (inserts a \verb|%| in the string),
2074\verb|%s| (inserts a zero-terminated string, with no size restrictions),
2075\verb|%f| (inserts a \verb|lua_Number|),
2076\verb|%d| (inserts an \verb|int|),
2077\verb|%c| (inserts an \verb|int| as a character).
2078\end{itemize}
2079
2044 2080
2045\subsection{Controlling Garbage Collection}\label{GC-API} 2081\subsection{Controlling Garbage Collection}\label{GC-API}
2046 2082
2047Lua uses two numbers to control its garbage collection: 2083Lua uses two numbers to control its garbage collection:
2048the \emph{count} and the \emph{threshold} 2084the \emph{count} and the \emph{threshold} \see{GC}.
2049\see{GC}. 2085The first counts the ammount of memory in use by Lua;
2086when the count reaches the threshold,
2087Lua runs its garbage collector.
2088After the collection, the count is updated,
2089and the threshold is set to twice the count value.
2090
2050You can access the current values of these two numbers through the 2091You can access the current values of these two numbers through the
2051following functions: 2092following functions:
2052\begin{verbatim} 2093\begin{verbatim}
@@ -2069,47 +2110,113 @@ In particular
2069\verb|lua_setgcthreshold(L,0)| forces a garbage collectiion. 2110\verb|lua_setgcthreshold(L,0)| forces a garbage collectiion.
2070After the collection, 2111After the collection,
2071a new threshold is set according to the previous rule. 2112a new threshold is set according to the previous rule.
2072%% TODO: What `previous rule'?
2073 2113
2074If you want to change the adaptive behavior of the garbage collector, 2114%% TODO do we need a new way to do that??
2075you can use the garbage-collection tag method for \nil\ % 2115% If you want to change the adaptive behavior of the garbage collector,
2076to set your own threshold 2116% you can use the garbage-collection tag method for \nil{} %
2077(the tag method is called after Lua resets the threshold). 2117% to set your own threshold
2118% (the tag method is called after Lua resets the threshold).
2119
2120
2121\subsection{Userdata}\label{userdata}
2078 2122
2123Userdata represents C values in Lua.
2124Lua supports two types of userdata:
2125\Def{full userdata} and \Def{light userdata}.
2079 2126
2080\subsection{Userdata} 2127A full userdata represents a block of memory.
2128It is an object (like a table):
2129You must create it, it can have its own metatable,
2130you can detect when it is being collected.
2131A full userdata is only equal to itself.
2081 2132
2082You can create new userdata with the following functions: 2133A light userdata represents a pointer.
2134It is a value (like a number):
2135You do not create it, it has no metatables,
2136it is not collected (as it was never created).
2137A light userdata is equal to ``any''
2138light userdata with the same address.
2139
2140In Lua code, there is no way to test whether a userdata is full or light;
2141both have type \verb|userdata|.
2142In C code, \verb|lua_type| returns \verb|LUA_TUSERDATA| for full userdata,
2143and \verb|LUA_LIGHTUSERDATA| for light userdata.
2144
2145You can create new full userdata with the following function:
2083\begin{verbatim} 2146\begin{verbatim}
2084 void *lua_newuserdata (lua_State *L, size_t size); 2147 void *lua_newuserdata (lua_State *L, size_t size);
2085 void lua_newuserdatabox (lua_State *L, void *u);
2086\end{verbatim} 2148\end{verbatim}
2087\DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox} 2149\DefAPI{lua_newuserdata}
2088The first function, \verb|lua_newuserdata|, 2150It allocates a new block of memory with the given size,
2089allocates a new block of memory with the given size,
2090pushes on the stack a new userdata with the block address, 2151pushes on the stack a new userdata with the block address,
2091and returns this address. 2152and returns this address.
2092The second function, \verb|lua_newuserdatabox|,
2093gets a pointer and pushes on the stack a new userdata
2094with that pointer.
2095In this case, Lua does not care about the pointer's value.
2096By default, all userdata are created with a standard tag,
2097\verb|LUA_TUSERDATA|, which is defined in \verb|lua.h|.
2098 2153
2099When Lua collects a userdata created by \verb|lua_newuserdata|, 2154To push a light userdata into the stack you use
2100it automatically frees its corresponding memory. 2155\verb|lua_pushlightuserdata| \see{pushing}.
2101On the other hand, Lua never accesses pointers in 2156
2102userdata created with \verb|lua_newuserdatabox|; 2157\verb|lua_touserdata| \see{lua-to} retrieves the value of a userdata.
2103it is up to you to free any associated memory, 2158When applied on a full userdata, it returns the address of its block;
2104setting a garbage-collection tag method, for instance. 2159when applied on a light userdata, it returns its pointer;
2160when applied on a non-userdata value, it returns \verb|NULL|.
2161
2162When Lua collects a full userdata,
2163it calls its \verb|gc| metamethod, if any,
2164and then it automatically frees its corresponding memory.
2105 2165
2106 2166
2107\subsection{Metatables} 2167\subsection{Metatables}
2108 2168
2109%% TODO 2169%% TODO
2110 2170
2171\subsection{Loading Lua Chunks}
2172You can load a Lua chunk with
2173\begin{verbatim}
2174 typedef const char * (*lua_Chunkreader)
2175 (lua_State *L, void *data, size_t *size);
2176
2177 int lua_load (lua_State *L, lua_Chunkreader reader, void *data,
2178 const char *chunkname);
2179\end{verbatim}
2180\DefAPI{Chunkreader}\DefAPI{lua_load}
2181\verb|lua_load| uses the \emph{reader} to read the chunk.
2182Everytime it needs another piece of the chunk,
2183it calls the reader,
2184passing along its \verb|data| parameter.
2185The reader must return a pointer to a block of memory
2186with the part of the chunk,
2187and set \verb|size| to the block size.
2188To signal the end of the chunk, the reader must return \verb|NULL|.
2189
2190In the current implementation,
2191the reader function cannot call any Lua function;
2192to ensure that, it always receives \verb|NULL| as the Lua state.
2193
2194\verb|lua_load| automatically detects whether the chunk is text or binary,
2195and loads it accordingly (see program \IndexVerb{luac}).
2196
2197The return values of \verb|lua_load| are:
2198\begin{itemize}
2199\item 0 --- no errors;
2200\item \IndexAPI{LUA_ERRSYNTAX} ---
2201syntax error during pre-compilation.
2202\item \IndexAPI{LUA_ERRMEM} ---
2203memory allocation error.
2204\end{itemize}
2205If there are no errors,
2206the compiled chunk is pushed as a Lua function on top of the stack.
2207Otherwise, an error message is pushed.
2208
2209The \emph{chunkname} is used for error messages
2210and debug information \see{debugI}.
2211
2212See the auxiliar library (\verb|lauxlib|)
2213for examples of how to use \verb|lua_load|,
2214and for some ready-to-use functions to load chunks
2215from files and from strings.
2216
2111 2217
2112\subsection{Executing Lua Chunks}\label{luado} 2218\subsection{Executing Lua Chunks}\label{luado}
2219>>>>
2113A host program can execute Lua chunks written in a file or in a string 2220A host program can execute Lua chunks written in a file or in a string
2114by using the following functions: 2221by using the following functions:
2115\begin{verbatim} 2222\begin{verbatim}
@@ -2143,59 +2250,11 @@ call \verb|strerror|,
2143or call \verb|perror| to tell the user what went wrong. 2250or call \verb|perror| to tell the user what went wrong.
2144\end{itemize} 2251\end{itemize}
2145 2252
2146When called with argument \verb|NULL|,
2147\verb|lua_dofile| executes the \verb|stdin| stream.
2148\verb|lua_dofile| and \verb|lua_dobuffer|
2149are both able to execute pre-compiled chunks.
2150They automatically detect whether the chunk is text or binary,
2151and load it accordingly (see program \IndexVerb{luac}).
2152\verb|lua_dostring| executes only source code,
2153given in textual form.
2154
2155The fourth parameter to \verb|lua_dobuffer|
2156is the ``name of the chunk'',
2157which is used in error messages and debug information.
2158If \verb|name| is \verb|NULL|,
2159then Lua gives a default name to the chunk.
2160
2161These functions push onto the stack
2162any values eventually returned by the chunk.
2163A chunk may return any number of values;
2164Lua takes care that these values fit into the stack space,
2165%% TODO: how? o que acontece se nao da'?
2166but after the call the responsibility is back to you.
2167If you need to push other elements after calling any of these functions,
2168and you want to ``play safe'',
2169you must either check the stack space
2170with \verb|lua_checkstack|
2171or remove the returned elements
2172from the stack (if you do not need them).
2173For instance, the following code
2174executes a chunk from a file and discards all results returned by this chunk,
2175leaving the stack as it was before the call:
2176\begin{verbatim}
2177 {
2178 int oldtop = lua_gettop(L);
2179 lua_dofile(L, filename);
2180 lua_settop(L, oldtop);
2181 }
2182\end{verbatim}
2183
2184\subsection{Loading Lua Chunks}
2185You can load Lua chunks without executing them with
2186\begin{verbatim}
2187 int lua_loadfile (lua_State *L, const char *filename);
2188 int lua_loadbuffer (lua_State *L, const char *buff,
2189 size_t size, const char *name);
2190\end{verbatim}
2191The compiled chunk is left as a function on top of the stack.
2192The return values are the same as those of
2193\verb|lua_dofile| and \verb|lua_dobuffer|.
2194 2253
2195\subsection{Manipulating Tables} 2254\subsection{Manipulating Tables}
2196 2255
2197Tables are created by calling 2256Tables are created by calling
2198The function 2257the function
2199\begin{verbatim} 2258\begin{verbatim}
2200 void lua_newtable (lua_State *L); 2259 void lua_newtable (lua_State *L);
2201\end{verbatim} 2260\end{verbatim}
@@ -2208,16 +2267,16 @@ call
2208 void lua_gettable (lua_State *L, int index); 2267 void lua_gettable (lua_State *L, int index);
2209\end{verbatim} 2268\end{verbatim}
2210\DefAPI{lua_gettable} 2269\DefAPI{lua_gettable}
2211where \verb|index| refers to the table. 2270where \verb|index| points to the table.
2212\verb|lua_gettable| pops a key from the stack 2271\verb|lua_gettable| pops a key from the stack
2213and returns (on the stack) the contents of the table at that key. 2272and returns (on the stack) the contents of the table at that key.
2214The table is left where it was in the stack; 2273The table is left where it was in the stack;
2215this is convenient for getting multiple values from a table. 2274this is convenient for getting multiple values from a table.
2216 2275
2217As in Lua, this function may trigger a tag method 2276As in Lua, this function may trigger a metamethod
2218for the ``gettable'' event \see{tag-method}. 2277for the ``gettable'' or ``index'' events \see{metatable}.
2219To get the real value of any table key, 2278To get the real value of any table key,
2220without invoking any tag method, 2279without invoking any metamethod,
2221use the \emph{raw} version: 2280use the \emph{raw} version:
2222\begin{verbatim} 2281\begin{verbatim}
2223 void lua_rawget (lua_State *L, int index); 2282 void lua_rawget (lua_State *L, int index);
@@ -2232,15 +2291,15 @@ and then call
2232 void lua_settable (lua_State *L, int index); 2291 void lua_settable (lua_State *L, int index);
2233\end{verbatim} 2292\end{verbatim}
2234\DefAPI{lua_settable} 2293\DefAPI{lua_settable}
2235where \verb|index| refers to the table. 2294where \verb|index| points to the table.
2236\verb|lua_settable| pops from the stack both the key and the value. 2295\verb|lua_settable| pops from the stack both the key and the value.
2237The table is left where it was in the stack; 2296The table is left where it was in the stack;
2238this is convenient for setting multiple values in a table. 2297this is convenient for setting multiple values in a table.
2239 2298
2240As in Lua, this operation may trigger a tag method 2299As in Lua, this operation may trigger a metamethod
2241for the ``settable'' event. 2300for the ``settable'' or ``newindex'' events.
2242To set the real value of any table index, 2301To set the real value of any table index,
2243without invoking any tag method, 2302without invoking any metamethod,
2244use the \emph{raw} version: 2303use the \emph{raw} version:
2245\begin{verbatim} 2304\begin{verbatim}
2246 void lua_rawset (lua_State *L, int index); 2305 void lua_rawset (lua_State *L, int index);
@@ -2252,13 +2311,13 @@ You can traverse a table with the function
2252 int lua_next (lua_State *L, int index); 2311 int lua_next (lua_State *L, int index);
2253\end{verbatim} 2312\end{verbatim}
2254\DefAPI{lua_next} 2313\DefAPI{lua_next}
2255where \verb|index| refers to the table to be traversed. 2314where \verb|index| points to the table to be traversed.
2256The function pops a key from the stack, 2315The function pops a key from the stack,
2257and pushes a key-value pair from the table 2316and pushes a key-value pair from the table
2258(the ``next'' pair after the given key). 2317(the ``next'' pair after the given key).
2259If there are no more elements, then \verb|lua_next| returns 0 2318If there are no more elements, then \verb|lua_next| returns 0
2260(and pushes nothing). 2319(and pushes nothing).
2261Use a \nil\ key to signal the start of a traversal. 2320Use a \nil{} key to signal the start of a traversal.
2262 2321
2263A typical traversal looks like this: 2322A typical traversal looks like this:
2264\begin{verbatim} 2323\begin{verbatim}
@@ -2277,7 +2336,7 @@ While traversing a table,
2277do not call \verb|lua_tostring| on a key, 2336do not call \verb|lua_tostring| on a key,
2278unless you know the key is actually a string. 2337unless you know the key is actually a string.
2279Recall that \verb|lua_tostring| \emph{changes} the value at the given index; 2338Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
2280this confuses \verb|lua_next|. 2339this confuses the next call to \verb|lua_next|.
2281 2340
2282\subsection{Manipulating Global Variables} \label{globals} 2341\subsection{Manipulating Global Variables} \label{globals}
2283 2342
@@ -2302,29 +2361,21 @@ tables indexed by numbers only:
2302\begin{verbatim} 2361\begin{verbatim}
2303 void lua_rawgeti (lua_State *L, int index, int n); 2362 void lua_rawgeti (lua_State *L, int index, int n);
2304 void lua_rawseti (lua_State *L, int index, int n); 2363 void lua_rawseti (lua_State *L, int index, int n);
2305 int lua_getn (lua_State *L, int index);
2306\end{verbatim} 2364\end{verbatim}
2307\DefAPI{lua_rawgeti} 2365\DefAPI{lua_rawgeti}
2308\DefAPI{lua_rawseti} 2366\DefAPI{lua_rawseti}
2309\DefAPI{lua_getn}
2310 2367
2311\verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table 2368\verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table
2312at stack position \verb|index|. 2369at stack position \verb|index|.
2313
2314\verb|lua_rawseti| sets the value of the \M{n}-th element of the table 2370\verb|lua_rawseti| sets the value of the \M{n}-th element of the table
2315at stack position \verb|index| to the value at the top of the stack, 2371at stack position \verb|index| to the value at the top of the stack,
2316removing this value from the stack. 2372removing this value from the stack.
2317 2373
2318\verb|lua_getn| returns the number of elements in the table
2319at stack position \verb|index|.
2320This number is the value of the table field \verb|n|,
2321if it has a numeric value,
2322or the largest numerical index with a non-\nil\ value in the table.
2323 2374
2324\subsection{Calling Functions} 2375\subsection{Calling Functions}
2325 2376
2326Functions defined in Lua 2377Functions defined in Lua
2327(and C~functions registered in Lua) 2378and C~functions registered in Lua
2328can be called from the host program. 2379can be called from the host program.
2329This is done using the following protocol: 2380This is done using the following protocol:
2330First, the function to be called is pushed onto the stack; 2381First, the function to be called is pushed onto the stack;
@@ -2332,27 +2383,16 @@ then, the arguments to the function are pushed
2332in \emph{direct order}, that is, the first argument is pushed first. 2383in \emph{direct order}, that is, the first argument is pushed first.
2333Finally, the function is called using 2384Finally, the function is called using
2334\begin{verbatim} 2385\begin{verbatim}
2335 int lua_call (lua_State *L, int nargs, int nresults); 2386 void lua_call (lua_State *L, int nargs, int nresults);
2336\end{verbatim} 2387\end{verbatim}
2337\DefAPI{lua_call} 2388\DefAPI{lua_call}
2338This function returns the same error codes as \verb|lua_dostring| and
2339friends \see{luado}.
2340If you want to propagate the error,
2341%% TODO: explain 'propagate'.
2342instead of returning an error code,
2343use
2344\begin{verbatim}
2345 void lua_rawcall (lua_State *L, int nargs, int nresults);
2346\end{verbatim}
2347\DefAPI{lua_rawcall}
2348
2349In both functions,
2350\verb|nargs| is the number of arguments that you pushed onto the stack. 2389\verb|nargs| is the number of arguments that you pushed onto the stack.
2351All arguments and the function value are popped from the stack, 2390All arguments and the function value are popped from the stack,
2352and the function results are pushed. 2391and the function results are pushed.
2353The number of results are adjusted to \verb|nresults|, 2392The number of results are adjusted to \verb|nresults|,
2354unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. 2393unless \verb|nresults| is \IndexAPI{LUA_MULTRET}.
2355In that case, \emph{all} results from the function are pushed. 2394In that case, \emph{all} results from the function are pushed.
2395Lua takes care that the returned values fit into the stack space.
2356The function results are pushed onto the stack in direct order 2396The function results are pushed onto the stack in direct order
2357(the first result is pushed first), 2397(the first result is pushed first),
2358so that after the call the last result is on the top. 2398so that after the call the last result is on the top.
@@ -2386,8 +2426,11 @@ to show all the details.
2386Usually programmers use several macros and auxiliar functions that 2426Usually programmers use several macros and auxiliar functions that
2387provide higher level access to Lua.) 2427provide higher level access to Lua.)
2388 2428
2429%% TODO: pcall
2430
2389\medskip 2431\medskip
2390 2432
2433>>>>
2391%% TODO: mover essas 2 para algum lugar melhor. 2434%% TODO: mover essas 2 para algum lugar melhor.
2392Some special Lua functions have their own C~interfaces. 2435Some special Lua functions have their own C~interfaces.
2393The host program can generate a Lua error calling the function 2436The host program can generate a Lua error calling the function
@@ -2523,6 +2566,9 @@ This table is always located at pseudo-index
2523\IndexAPI{LUA_REGISTRYINDEX}. 2566\IndexAPI{LUA_REGISTRYINDEX}.
2524Any C~library can store data into this table, 2567Any C~library can store data into this table,
2525as long as it chooses a key different from other libraries. 2568as long as it chooses a key different from other libraries.
2569Typically, you can use as key a string containing the library name,
2570or a light userdata with the address of a C object in your code.
2571
2526The integer keys in the registry are used by the reference mechanism, 2572The integer keys in the registry are used by the reference mechanism,
2527implemented by the auxiliar library, 2573implemented by the auxiliar library,
2528and therefore should not be used by other purposes. 2574and therefore should not be used by other purposes.
@@ -2752,26 +2798,42 @@ this execution ocurrs without any calls to hooks.
2752 2798
2753The standard libraries provide useful functions 2799The standard libraries provide useful functions
2754that are implemented directly through the standard C~API. 2800that are implemented directly through the standard C~API.
2755Therefore, they are not essential to the language, 2801Some of these functions provide essential services to the language
2802(e.g. \verb|type| and \verb|getmetatable|);
2803others provide access to ``outside'' servides (e.g. I/O);
2804and others could be implemented in Lua itself,
2805but are quite useful or have critical performance to
2806deserve an implementation in C (e.g. \verb|sort|).
2807
2808All libraries are implemented through the official C API,
2756and are provided as separate C~modules. 2809and are provided as separate C~modules.
2757Currently, Lua has the following standard libraries: 2810Currently, Lua has the following standard libraries:
2758\begin{itemize} 2811\begin{itemize}
2759\item basic library; 2812\item basic library;
2760\item string manipulation; 2813\item string manipulation;
2814\item table manipulation;
2761\item mathematical functions (sin, log, etc.); 2815\item mathematical functions (sin, log, etc.);
2762\item input and output (plus some system facilities). 2816\item input and output;
2817\item operating system facilities;
2818\item debug facilities.
2763\end{itemize} 2819\end{itemize}
2820Except for the basic library,
2821each library provides all its functions as fields of a global table
2822or as methods of its objects.
2823
2764To have access to these libraries, 2824To have access to these libraries,
2765the C~host program must call the functions 2825the C~host program must call the functions
2766\verb|lua_baselibopen|, 2826\verb|lua_baselibopen|,
2767\verb|lua_strlibopen|, \verb|lua_mathlibopen|, 2827\verb|lua_strlibopen|,
2828\verb|lua_tablibopen|,
2829\verb|lua_mathlibopen|,
2768and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|. 2830and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|.
2769\DefAPI{lua_baselibopen} 2831\DefAPI{lua_baselibopen}
2770\DefAPI{lua_strlibopen} 2832\DefAPI{lua_strlibopen}
2833\DefAPI{lua_tablibopen}
2771\DefAPI{lua_mathlibopen} 2834\DefAPI{lua_mathlibopen}
2772\DefAPI{lua_iolibopen} 2835\DefAPI{lua_iolibopen}
2773 2836
2774Lua's web site has links to Lua libraries written by users.
2775 2837
2776\subsection{Basic Functions} \label{predefined} 2838\subsection{Basic Functions} \label{predefined}
2777 2839
@@ -2779,23 +2841,11 @@ The basic library provides some core functions to Lua.
2779If you do not include this library in your application, 2841If you do not include this library in your application,
2780you should check carefully whether you need to provide some alternative 2842you should check carefully whether you need to provide some alternative
2781implementation for some facilities. 2843implementation for some facilities.
2782(For instance,
2783without an \verb|_ERRORMESSAGE| function,
2784Lua is unable to show error messages.)
2785 2844
2786The basic library also defines a global variable \IndexAPI{_VERSION} 2845The basic library also defines a global variable \IndexAPI{_VERSION}
2787with a string containing the current interpreter version. 2846with a string containing the current interpreter version.
2788The current content of this string is {\tt "Lua \Version"}. 2847The current content of this string is {\tt "Lua \Version"}.
2789 2848
2790\subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert}
2791Prints its only string argument to \IndexVerb{stderr}.
2792All error messages in Lua are printed through the function stored
2793in the \verb|_ALERT| global variable
2794\see{error}.
2795Therefore, a program may assign another function to this variable
2796to change the way such messages are shown
2797(for instance, for systems without \verb|stderr|).
2798
2799\subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert} 2849\subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert}
2800Issues an \emph{``assertion failed!''} error 2850Issues an \emph{``assertion failed!''} error
2801when its argument \verb|v| is \nil; 2851when its argument \verb|v| is \nil;
@@ -2804,14 +2854,13 @@ This function is equivalent to the following Lua function:
2804\begin{verbatim} 2854\begin{verbatim}
2805 function assert (v, m) 2855 function assert (v, m)
2806 if not v then 2856 if not v then
2807 m = m or "" 2857 error(m or "assertion failed!")
2808 error("assertion failed! " .. m)
2809 end 2858 end
2810 return v 2859 return v
2811 end 2860 end
2812\end{verbatim} 2861\end{verbatim}
2813 2862
2814\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\DefLIB{call} 2863??\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\DefLIB{call}
2815\label{pdf-call} 2864\label{pdf-call}
2816Calls function \verb|func| with 2865Calls function \verb|func| with
2817the arguments given by the table \verb|arg|. 2866the arguments given by the table \verb|arg|.
@@ -2829,7 +2878,7 @@ If the string \verb|mode| contains \verb|"x"|,
2829then the call is \emph{protected}.\index{protected calls} 2878then the call is \emph{protected}.\index{protected calls}
2830In this mode, function \verb|call| does not propagate an error, 2879In this mode, function \verb|call| does not propagate an error,
2831regardless of what happens during the call. 2880regardless of what happens during the call.
2832Instead, it returns \nil\ to signal the error 2881Instead, it returns \nil{} to signal the error
2833(besides calling the appropriated error handler). 2882(besides calling the appropriated error handler).
2834 2883
2835If \verb|errhandler| is provided, 2884If \verb|errhandler| is provided,
@@ -2852,115 +2901,60 @@ Receives a file name,
2852opens the named file, and executes its contents as a Lua chunk. 2901opens the named file, and executes its contents as a Lua chunk.
2853When called without arguments, 2902When called without arguments,
2854\verb|dofile| executes the contents of the standard input (\verb|stdin|). 2903\verb|dofile| executes the contents of the standard input (\verb|stdin|).
2855If there is any error executing the file, 2904Returns any value returned by the chunk.
2856then \verb|dofile| returns \nil{} plus one of the following strings
2857describing the error:
2858\verb|"file error"|, \verb|"run-time error"|,
2859\verb|"syntax error"|, \verb|"memory error"|, or
2860\verb|"error in error handling"|.
2861Otherwise, it returns the values returned by the chunk,
2862or a non-\nil\ value if the chunk returns no values.
2863It issues an error when called with a non-string argument.
2864
2865\subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring}
2866Executes a given string as a Lua chunk.
2867If there is any error executing the string,
2868then \verb|dostring| returns \nil\ plus a string describing
2869the error (see \verb|dofile|).
2870Otherwise, it returns the values returned by the chunk,
2871or a non-\nil\ value if the chunk returns no values.
2872The optional parameter \verb|chunkname|
2873is the ``name of the chunk'',
2874used in error messages and debug information.
2875 2905
2876\subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error} 2906\subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error}
2877Calls the error handler \see{error} and then terminates 2907Terminates the last protected function called,
2878the last protected function called 2908and returns \verb|message| as the error message.
2879(in~C: \verb|lua_dofile|, \verb|lua_dostring|,
2880\verb|lua_dobuffer|, or \verb|lua_callfunction|;
2881in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
2882If \verb|message| is absent, the error handler is not called.
2883Function \verb|error| never returns. 2909Function \verb|error| never returns.
2884 2910
2885\subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach} 2911\subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals}
2886Executes the given \verb|func| over all elements of \verb|table|. 2912Returns the current table of globals in use by the function.
2887For each element, the function is called with the index and 2913\verb|function| can be a Lua function or a number,
2888respective value as arguments. 2914meaning the function at that stack level:
2889If the function returns a non-\nil\ value, 2915Level 1 is the function calling \verb|getglobals|.
2890then the loop is broken, and this value is returned 2916If the given function is not a Lua function,
2891as the final value of \verb|foreach|. 2917returns the ``global'' table of globals.
2892This function is equivalent to the following Lua function: 2918The default for \verb|function| is 1.
2893\begin{verbatim}
2894 function foreach (t, f)
2895 for i, v in t do
2896 local res = f(i, v)
2897 if res then return res end
2898 end
2899 end
2900\end{verbatim}
2901 2919
2902The behavior of \verb|foreach| is \emph{undefined} if you change 2920\subsubsection*{\ff \T{getmetatable (object)}}
2903the table \verb|t| during the traversal. 2921\DefLIB{getmetatable}\label{pdf-getmetatable}
2904 2922
2923Returns the metatable of the given object.
2924If the object does not have a metatable, returns \nil.
2905 2925
2906\subsubsection*{\ff \T{foreachi (table, func)}}\DefLIB{foreachi} 2926\subsubsection*{\ff \T{getmode (table)}}\DefLIB{getmode}
2907Executes the given \verb|func| over the 2927
2908numerical indices of \verb|table|. 2928Returns the weak mode of a table, as a string.
2909For each index, the function is called with the index and 2929Valid values for this string are \verb|""| for regular (non-weak) tables,
2910respective value as arguments. 2930\verb|"k"| for weak keys, \verb|"v"| for weak values,
2911Indices are visited in sequential order, 2931and \verb|"kv"| for both.
2912from~1 to \verb|n|,
2913where \verb|n| is the result of \verb|getn(table)| (see below).
2914If the function returns a non-\nil\ value,
2915then the loop is broken, and this value is returned
2916as the final value of \verb|foreachi|.
2917This function is equivalent to the following Lua function:
2918\begin{verbatim}
2919 function foreachi (t, f)
2920 for i=1,getn(t) do
2921 local res = f(i, t[i])
2922 if res then return res end
2923 end
2924 end
2925\end{verbatim}
2926 2932
2927\subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo} 2933\subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo}
2928Returns the number of Kbytes of dynamic memory Lua is using, 2934Returns the number of Kbytes of dynamic memory Lua is using,
2929and (as a second result) the 2935and (as a second result) the
2930current garbage collector threshold (also in Kbytes). 2936current garbage collector threshold (also in Kbytes).
2931 2937
2932\subsubsection*{\ff \T{getn (table)}}\DefLIB{getn}\label{getn}
2933Returns the ``size'' of a table, when seen as a list.
2934If the table has an \verb|n| field with a numeric value,
2935this value is the ``size'' of the table.
2936Otherwise, the ``size'' is the largest numerical index with a non-\nil\
2937value in the table.
2938This function is equivalent to the following Lua function:
2939\begin{verbatim}
2940 function getn (t)
2941 if type(t.n) == "number" then return t.n end
2942 local max = 0
2943 for i, _ in t do
2944 if type(i) == "number" and i>max then max=i end
2945 end
2946 return max
2947 end
2948\end{verbatim}
2949
2950\subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals}
2951Returns the current table of globals.
2952If the argument \verb|table| is given,
2953then it also sets this table as the table of globals.
2954
2955\subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile} 2938\subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile}
2956Similar to \verb|dofile|, 2939Loads a file as a Lua chunk.
2957but returns the contents of a Lua chunk as a function, 2940If there is no errors,
2958instead of executing it. 2941returns the compiled chunk as a function;
2942otherwise, returns \nil{} plus an error message.
2959 2943
2960\subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring} 2944\subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring}
2961Similar to \verb|dostring|, 2945Loads a string as a Lua chunk.
2962but returns the contents of a Lua chunk as a function, 2946If there is no errors,
2963instead of executing it. 2947returns the compiled chunk as a function;
2948otherwise, returns \nil{} plus an error message.
2949
2950The optional parameter \verb|chunkname|
2951is the ``name of the chunk'',
2952used in error messages and debug information.
2953
2954To load and run a given string, use the idiom
2955\begin{verbatim}
2956 assert(loadstring(s))()
2957\end{verbatim}
2964 2958
2965\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next} 2959\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next}
2966Allows a program to traverse all fields of a table. 2960Allows a program to traverse all fields of a table.
@@ -2968,22 +2962,22 @@ Its first argument is a table and its second argument
2968is an index in this table. 2962is an index in this table.
2969\verb|next| returns the next index of the table and the 2963\verb|next| returns the next index of the table and the
2970value associated with the index. 2964value associated with the index.
2971When called with \nil\ as its second argument, 2965When called with \nil{} as its second argument,
2972\verb|next| returns the first index 2966\verb|next| returns the first index
2973of the table and its associated value. 2967of the table and its associated value.
2974When called with the last index, 2968When called with the last index,
2975or with \nil\ in an empty table, 2969or with \nil{} in an empty table,
2976\verb|next| returns \nil. 2970\verb|next| returns \nil.
2977If the second argument is absent, then it is interpreted as \nil. 2971If the second argument is absent, then it is interpreted as \nil.
2978 2972
2979Lua has no declaration of fields; 2973Lua has no declaration of fields;
2980semantically, there is no difference between a 2974semantically, there is no difference between a
2981field not present in a table or a field with value \nil. 2975field not present in a table or a field with value \nil.
2982Therefore, \verb|next| only considers fields with non-\nil\ values. 2976Therefore, \verb|next| only considers fields with non-\nil{} values.
2983The order in which the indices are enumerated is not specified, 2977The order in which the indices are enumerated is not specified,
2984\emph{even for numeric indices} 2978\emph{even for numeric indices}
2985(to traverse a table in numeric order, 2979(to traverse a table in numeric order,
2986use a numerical \rwd{for} or the function \verb|foreachi|). 2980use a numerical \rwd{for} or the function \verb|ipairs|).
2987 2981
2988The behavior of \verb|next| is \emph{undefined} if you change 2982The behavior of \verb|next| is \emph{undefined} if you change
2989the table during the traversal. 2983the table during the traversal.
@@ -3049,22 +3043,27 @@ While running a packaged file,
3049\verb|require| defines the global variable \IndexVerb{_REQUIREDNAME} 3043\verb|require| defines the global variable \IndexVerb{_REQUIREDNAME}
3050with the package name. 3044with the package name.
3051 3045
3046\subsubsection*{\ff \T{setglobals (function, table)}}\DefLIB{setglobals}
3047Sets the current table of globals to be used by the given function.
3048\verb|function| can be a Lua function or a number,
3049meaning the function at that stack level:
3050Level 1 is the function calling \verb|setglobals|.
3052 3051
3053\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} 3052\subsubsection*{\ff \T{setmetatable (table, metatable)}}\DefLIB{setmetatable}
3054Sorts table elements in a given order, \emph{in-place},
3055from \verb|table[1]| to \verb|table[n]|,
3056where \verb|n| is the result of \verb|getn(table)| \see{getn}.
3057If \verb|comp| is given,
3058then it must be a function that receives two table elements,
3059and returns true
3060when the first is less than the second
3061(so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
3062If \verb|comp| is not given,
3063then the standard Lua operator \verb|<| is used instead.
3064 3053
3065The sort algorithm is \emph{not} stable 3054Sets the metatable for the given table.
3066(that is, elements considered equal by the given order 3055(You cannot change the metatable of a userdata from Lua.)
3067may have their relative positions changed by the sort). 3056If \verb|metatable| is \nil, removes the metatable of the given table.
3057
3058\subsubsection*{\ff \T{setmode (table, mode)}}\DefLIB{setmode}
3059
3060Set the weak mode of a table.
3061The new mode is described by the \verb|mode| string.
3062Valid values for this string are \verb|""| for regular (non-weak) tables,
3063\verb|"k"| for weak keys, \verb|"v"| for weak values,
3064and \verb|"kv"| for both.
3065
3066This function returns its first argument (\verb|table|).
3068 3067
3069\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} 3068\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
3070Tries to convert its argument to a number. 3069Tries to convert its argument to a number.
@@ -3086,30 +3085,6 @@ converts it to a string in a reasonable format.
3086For complete control of how numbers are converted, 3085For complete control of how numbers are converted,
3087use \verb|format| \see{format}. 3086use \verb|format| \see{format}.
3088 3087
3089
3090\subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert}
3091
3092Inserts element \verb|value| at position \verb|pos| in \verb|table|,
3093shifting other elements up to open space, if necessary.
3094The default value for \verb|pos| is \verb|n+1|,
3095where \verb|n| is the result of \verb|getn(table)| \see{getn},
3096so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end
3097of table \verb|t|.
3098This function also sets or increments the field \verb|n| of the table
3099to \verb|n+1|.
3100
3101\subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove}
3102
3103Removes from \verb|table| the element at position \verb|pos|,
3104shifting other elements down to close the space, if necessary.
3105Returns the value of the removed element.
3106The default value for \verb|pos| is \verb|n|,
3107where \verb|n| is the result of \verb|getn(table)| \see{getn},
3108so that a call \verb|tremove(t)| removes the last element
3109of table \verb|t|.
3110This function also sets or decrements the field \verb|n| of the table
3111to \verb|n-1|.
3112
3113\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} 3088\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
3114Returns the type of its only argument, coded as a string. 3089Returns the type of its only argument, coded as a string.
3115The possible results of this function are 3090The possible results of this function are
@@ -3128,7 +3103,8 @@ This function is equivalent to
3128\end{verbatim} 3103\end{verbatim}
3129except that the above code can be valid only for a fixed \M{n}. 3104except that the above code can be valid only for a fixed \M{n}.
3130The number \M{n} of returned values 3105The number \M{n} of returned values
3131is the result of \verb|getn(list)| \seepage{getn}. 3106is either the value of \verb|list.n|, if it is a number,
3107or one less the index of the first absent (\nil) value.
3132 3108
3133\subsection{String Manipulation} 3109\subsection{String Manipulation}
3134This library provides generic functions for string manipulation, 3110This library provides generic functions for string manipulation,
@@ -3136,10 +3112,13 @@ such as finding and extracting substrings and pattern matching.
3136When indexing a string in Lua, the first character is at position~1 3112When indexing a string in Lua, the first character is at position~1
3137(not at~0, as in C). 3113(not at~0, as in C).
3138Indices are allowed to be negative and are interpreted as indexing backwards, 3114Indices are allowed to be negative and are interpreted as indexing backwards,
3139from the end of the string. Thus, the last character is at position \Math{-1}, 3115from the end of the string.
3140and so on. 3116Thus, the last character is at position \Math{-1}, and so on.
3141 3117
3142\subsubsection*{\ff \T{strbyte (s [, i])}}\DefLIB{strbyte} 3118The string library provides all its functions inside the table
3119\DefLIB{string}.
3120
3121\subsubsection*{\ff \T{string.byte (s [, i])}}\DefLIB{string.byte}
3143Returns the internal numerical code of the \M{i}-th character of \verb|s|. 3122Returns the internal numerical code of the \M{i}-th character of \verb|s|.
3144If \verb|i| is absent, then it is assumed to be~1. 3123If \verb|i| is absent, then it is assumed to be~1.
3145\verb|i| may be negative. 3124\verb|i| may be negative.
@@ -3147,7 +3126,7 @@ If \verb|i| is absent, then it is assumed to be~1.
3147\NOTE 3126\NOTE
3148Numerical codes are not necessarily portable across platforms. 3127Numerical codes are not necessarily portable across platforms.
3149 3128
3150\subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\DefLIB{strchar} 3129\subsubsection*{\ff \T{string.char (i1, i2, \ldots)}}\DefLIB{string.char}
3151Receives 0 or more integers. 3130Receives 0 or more integers.
3152Returns a string with length equal to the number of arguments, 3131Returns a string with length equal to the number of arguments,
3153in which each character has the internal numerical code equal 3132in which each character has the internal numerical code equal
@@ -3156,59 +3135,60 @@ to its correspondent argument.
3156\NOTE 3135\NOTE
3157Numerical codes are not necessarily portable across platforms. 3136Numerical codes are not necessarily portable across platforms.
3158 3137
3159\subsubsection*{\ff \T{strfind (s, pattern [, init [, plain]])}}\DefLIB{strfind} 3138\subsubsection*{\ff \T{string.find (s, pattern [, init [, plain]])}}
3139\DefLIB{string.find}
3160Looks for the first \emph{match} of 3140Looks for the first \emph{match} of
3161\verb|pattern| in the string \verb|s|. 3141\verb|pattern| in the string \verb|s|.
3162If it finds one, then \verb|strfind| returns the indices of \verb|s| 3142If it finds one, then \verb|find| returns the indices of \verb|s|
3163where this occurrence starts and ends; 3143where this occurrence starts and ends;
3164otherwise, it returns \nil. 3144otherwise, it returns \nil.
3165If the pattern specifies captures (see \verb|gsub| below), 3145If the pattern specifies captures (see \verb|string.gsub| below),
3166the captured strings are returned as extra results. 3146the captured strings are returned as extra results.
3167A third, optional numerical argument \verb|init| specifies 3147A third, optional numerical argument \verb|init| specifies
3168where to start the search; 3148where to start the search;
3169its default value is~1, and may be negative. 3149its default value is~1, and may be negative.
3170A value of \True\ as a fourth, optional argument \verb|plain| 3150A value of \True{} as a fourth, optional argument \verb|plain|
3171turns off the pattern matching facilities, 3151turns off the pattern matching facilities,
3172so the function does a plain ``find substring'' operation, 3152so the function does a plain ``find substring'' operation,
3173with no characters in \verb|pattern| being considered ``magic''. 3153with no characters in \verb|pattern| being considered ``magic''.
3174Note that if \verb|plain| is given, then \verb|init| must be given too. 3154Note that if \verb|plain| is given, then \verb|init| must be given too.
3175 3155
3176\subsubsection*{\ff \T{strlen (s)}}\DefLIB{strlen} 3156\subsubsection*{\ff \T{string.len (s)}}\DefLIB{string.len}
3177Receives a string and returns its length. 3157Receives a string and returns its length.
3178The empty string \verb|""| has length 0. 3158The empty string \verb|""| has length 0.
3179Embedded zeros are counted, 3159Embedded zeros are counted,
3180and so \verb|"a\000b\000c"| has length 5. 3160and so \verb|"a\000b\000c"| has length 5.
3181 3161
3182\subsubsection*{\ff \T{strlower (s)}}\DefLIB{strlower} 3162\subsubsection*{\ff \T{string.lower (s)}}\DefLIB{string.lower}
3183Receives a string and returns a copy of that string with all 3163Receives a string and returns a copy of that string with all
3184uppercase letters changed to lowercase. 3164uppercase letters changed to lowercase.
3185All other characters are left unchanged. 3165All other characters are left unchanged.
3186The definition of what an uppercase letter is depends on the current locale. 3166The definition of what is an uppercase letter depends on the current locale.
3187 3167
3188\subsubsection*{\ff \T{strrep (s, n)}}\DefLIB{strrep} 3168\subsubsection*{\ff \T{string.rep (s, n)}}\DefLIB{string.rep}
3189Returns a string that is the concatenation of \verb|n| copies of 3169Returns a string that is the concatenation of \verb|n| copies of
3190the string \verb|s|. 3170the string \verb|s|.
3191 3171
3192\subsubsection*{\ff \T{strsub (s, i [, j])}}\DefLIB{strsub} 3172\subsubsection*{\ff \T{string.sub (s, i [, j])}}\DefLIB{string.sub}
3193Returns another string, which is a substring of \verb|s|, 3173Returns another string, which is a substring of \verb|s|,
3194starting at \verb|i| and running until \verb|j|; 3174starting at \verb|i| and running until \verb|j|;
3195\verb|i| and \verb|j| may be negative. 3175\verb|i| and \verb|j| may be negative.
3196If \verb|j| is absent, then it is assumed to be equal to \Math{-1} 3176If \verb|j| is absent, then it is assumed to be equal to \Math{-1}
3197(which is the same as the string length). 3177(which is the same as the string length).
3198In particular, 3178In particular,
3199the call \verb|strsub(s,1,j)| returns a prefix of \verb|s| 3179the call \verb|string.sub(s,1,j)| returns a prefix of \verb|s|
3200with length \verb|j|, 3180with length \verb|j|,
3201and the call \verb|strsub(s, -i)| returns a suffix of \verb|s| 3181and the call \verb|string.sub(s, -i)| returns a suffix of \verb|s|
3202with length \verb|i|. 3182with length \verb|i|.
3203 3183
3204\subsubsection*{\ff \T{strupper (s)}}\DefLIB{strupper} 3184\subsubsection*{\ff \T{string.upper (s)}}\DefLIB{string.upper}
3205Receives a string and returns a copy of that string with all 3185Receives a string and returns a copy of that string with all
3206lowercase letters changed to uppercase. 3186lowercase letters changed to uppercase.
3207All other characters are left unchanged. 3187All other characters are left unchanged.
3208The definition of what a lowercase letter is depends on the current locale. 3188The definition of what is a lowercase letter depends on the current locale.
3209 3189
3210\subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\DefLIB{format} 3190\subsubsection*{\ff \T{string.format (formatstring, e1, e2, \ldots)}}
3211\label{format} 3191\DefLIB{string.format}\label{format}
3212Returns a formatted version of its variable number of arguments 3192Returns a formatted version of its variable number of arguments
3213following the description given in its first argument (which must be a string). 3193following the description given in its first argument (which must be a string).
3214The format string follows the same rules as the \verb|printf| family of 3194The format string follows the same rules as the \verb|printf| family of
@@ -3224,7 +3204,7 @@ and all double quotes, returns, and backslashes in the string
3224are correctly escaped when written. 3204are correctly escaped when written.
3225For instance, the call 3205For instance, the call
3226\begin{verbatim} 3206\begin{verbatim}
3227 format('%q', 'a string with "quotes" and \n new line') 3207 string.format('%q', 'a string with "quotes" and \n new line')
3228\end{verbatim} 3208\end{verbatim}
3229will produce the string: 3209will produce the string:
3230\begin{verbatim} 3210\begin{verbatim}
@@ -3245,8 +3225,8 @@ For example, \verb|"%*g"| can be simulated with
3245String values to be formatted with 3225String values to be formatted with
3246\verb|%s| cannot contain embedded zeros. 3226\verb|%s| cannot contain embedded zeros.
3247 3227
3248\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} 3228\subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}}
3249\DefLIB{gsub} 3229\DefLIB{string.gsub}
3250Returns a copy of \verb|s| 3230Returns a copy of \verb|s|
3251in which all occurrences of the pattern \verb|pat| have been 3231in which all occurrences of the pattern \verb|pat| have been
3252replaced by a replacement string specified by \verb|repl|. 3232replaced by a replacement string specified by \verb|repl|.
@@ -3292,10 +3272,6 @@ Here are some examples:
3292 local t = {name="Lua", version="4.1"} 3272 local t = {name="Lua", version="4.1"}
3293 x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end) 3273 x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end)
3294 --> x="Lua - 4.1" 3274 --> x="Lua - 4.1"
3295
3296 local t = {}
3297 gsub("first second word", "%w+", function (w) tinsert(t, w) end)
3298 --> t={"first", "second", "word"; n=3}
3299\end{verbatim} 3275\end{verbatim}
3300 3276
3301 3277
@@ -3380,7 +3356,7 @@ a single character class followed by \verb|?|,
3380which matches 0 or 1 occurrence of a character in the class; 3356which matches 0 or 1 occurrence of a character in the class;
3381\item 3357\item
3382\T{\%\M{n}}, for \M{n} between 1 and 9; 3358\T{\%\M{n}}, for \M{n} between 1 and 9;
3383such item matches a sub-string equal to the \M{n}-th captured string 3359such item matches a substring equal to the \M{n}-th captured string
3384(see below); 3360(see below);
3385\item 3361\item
3386\T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; 3362\T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters;
@@ -3405,7 +3381,7 @@ At other positions,
3405\paragraph{Captures:} 3381\paragraph{Captures:}
3406A pattern may contain sub-patterns enclosed in parentheses; 3382A pattern may contain sub-patterns enclosed in parentheses;
3407they describe \Def{captures}. 3383they describe \Def{captures}.
3408When a match succeeds, the sub-strings of the subject string 3384When a match succeeds, the substrings of the subject string
3409that match captures are stored (\emph{captured}) for future use. 3385that match captures are stored (\emph{captured}) for future use.
3410Captures are numbered according to their left parentheses. 3386Captures are numbered according to their left parentheses.
3411For instance, in the pattern \verb|"(a*(.)%w(%s*))"|, 3387For instance, in the pattern \verb|"(a*(.)%w(%s*))"|,
@@ -3418,77 +3394,223 @@ and the part matching \verb|%s*| has number~3.
3418A pattern cannot contain embedded zeros. Use \verb|%z| instead. 3394A pattern cannot contain embedded zeros. Use \verb|%z| instead.
3419 3395
3420 3396
3397\subsection{Table Manipulation}
3398This library provides generic functions for table manipulation,
3399It provides all its functions inside the table \DefLIB{table}.
3400
3401Most functions in the table library library assume that the table
3402represents an array or a list.
3403For those functions, an important concept is the \emph{size} of the array.
3404There are three ways to specify that size:
3405\begin{itemize}
3406\item the field \verb|"n"| ---
3407When the table has a field \verb|"n"| with a numerical value,
3408that value is assumed as its size.
3409\item \verb|setn| ---
3410You can call the \verb|table.setn| function to explicitly set
3411the size of a table.
3412\item implicit size ---
3413%% TODO
3414\end{itemize}
3415For more details, see the descriptions of the \verb|table.getn| and
3416\verb|table.setn| functions.
3417
3418\subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach}
3419Executes the given \verb|func| over all elements of \verb|table|.
3420For each element, \verb|func| is called with the index and
3421respective value as arguments.
3422If \verb|func| returns a non-\nil{} value,
3423then the loop is broken, and this value is returned
3424as the final value of \verb|foreach|.
3425
3426The behavior of \verb|foreach| is \emph{undefined} if you change
3427the table \verb|t| during the traversal.
3428
3429
3430\subsubsection*{\ff \T{table.foreachi (table, func)}}\DefLIB{table.foreachi}
3431Executes the given \verb|func| over the
3432numerical indices of \verb|table|.
3433For each index, \verb|func| is called with the index and
3434respective value as arguments.
3435Indices are visited in sequential order,
3436from~1 to \verb|n|,
3437where \verb|n| is the size of the table \see{getn}.
3438If \verb|func| returns a non-\nil{} value,
3439then the loop is broken, and this value is returned
3440as the final value of \verb|foreachi|.
3441
3442\subsubsection*{\ff \T{table.getn (table)}}\DefLIB{table.getn}\label{getn}
3443Returns the ``size'' of a table, when seen as a list.
3444If the table has an \verb|n| field with a numeric value,
3445this value is the ``size'' of the table.
3446Otherwise, if there was a previous call to
3447\verb|table.getn| or to \verb|table.setn| over this table,
3448the respective value is returned.
3449Otherwise, the ``size'' is one less the first integer index with
3450a \nil{} value.
3451
3452Notice that the last option happens only once for a table.
3453If you call \verb|table.getn| again over the same table,
3454it will return the same previous result,
3455even if the table has been modified.
3456The only way to change the value of \verb|table.getn| is by calling
3457\verb|table.setn| or assigning to field \verb|"n"| in the table.
3458
3459\subsubsection*{\ff \T{table.sort (table [, comp])}}\DefLIB{table.sort}
3460Sorts table elements in a given order, \emph{in-place},
3461from \verb|table[1]| to \verb|table[n]|,
3462where \verb|n| is the size of the table \see{getn}.
3463If \verb|comp| is given,
3464then it must be a function that receives two table elements,
3465and returns true
3466when the first is less than the second
3467(so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
3468If \verb|comp| is not given,
3469then the standard Lua operator \verb|<| is used instead.
3470
3471The sort algorithm is \emph{not} stable
3472(that is, elements considered equal by the given order
3473may have their relative positions changed by the sort).
3474
3475\subsubsection*{\ff \T{table.insert (table, [pos,] value)}}\DefLIB{table.insert}
3476
3477Inserts element \verb|value| at position \verb|pos| in \verb|table|,
3478shifting other elements up to open space, if necessary.
3479The default value for \verb|pos| is \verb|n+1|,
3480where \verb|n| is the size of the table \see{getn},
3481so that a call \verb|table.insert(t,x)| inserts \verb|x| at the end
3482of table \verb|t|.
3483This function also updates the size of the table,
3484calling \verb|table.setn(table, n+1)|.
3485
3486\subsubsection*{\ff \T{table.remove (table [, pos])}}\DefLIB{table.remove}
3487
3488Removes from \verb|table| the element at position \verb|pos|,
3489shifting other elements down to close the space, if necessary.
3490Returns the value of the removed element.
3491The default value for \verb|pos| is \verb|n|,
3492where \verb|n| is the size of the table \see{getn},
3493so that a call \verb|tremove(t)| removes the last element
3494of table \verb|t|.
3495This function also updates the size of the table,
3496calling \verb|table.setn(table, n-1)|.
3497
3498\subsubsection*{\ff \T{table.setn (table, n)}}\DefLIB{table.setn}
3499
3500Updates the ``size'' of a table.
3501If the table has a field \verb|"n"| with a numerical value,
3502that value is changed to the given \verb|n|.
3503Otherwise, it updates an internal state of the \verb|table| library
3504so that subsequent calls to \verb|table.getn(table)| return \verb|n|.
3505
3506
3421\subsection{Mathematical Functions} \label{mathlib} 3507\subsection{Mathematical Functions} \label{mathlib}
3422 3508
3423This library is an interface to most functions of the standard C~math library. 3509This library is an interface to most functions of the standard C~math library.
3424(Some have slightly different names.) 3510(Some have slightly different names.)
3511It provides all its functions inside the table \DefLIB{math}.
3425In addition, 3512In addition,
3426it registers a tag method for the binary exponentiation operator \verb|^| that 3513it registers a ??tag method for the binary exponentiation operator \verb|^|
3427returns \Math{x^y} when applied to numbers \verb|x^y|. 3514that returns \Math{x^y} when applied to numbers \verb|x^y|.
3428 3515
3429The library provides the following functions: 3516The library provides the following functions:
3430\DefLIB{abs}\DefLIB{acos}\DefLIB{asin}\DefLIB{atan} 3517\DefLIB{math.abs}\DefLIB{math.acos}\DefLIB{math.asin}\DefLIB{math.atan}
3431\DefLIB{atan2}\DefLIB{ceil}\DefLIB{cos}\DefLIB{def}\DefLIB{exp} 3518\DefLIB{math.atan2}\DefLIB{math.ceil}\DefLIB{math.cos}
3432\DefLIB{floor}\DefLIB{log}\DefLIB{log10}\DefLIB{max}\DefLIB{min} 3519\DefLIB{math.def}\DefLIB{math.exp}
3433\DefLIB{mod}\DefLIB{rad}\DefLIB{sin}\DefLIB{sqrt}\DefLIB{tan} 3520\DefLIB{math.floor}\DefLIB{math.log}\DefLIB{math.log10}
3434\DefLIB{frexp}\DefLIB{ldexp}\DefLIB{random}\DefLIB{randomseed} 3521\DefLIB{math.max}\DefLIB{math.min}
3522\DefLIB{math.mod}\DefLIB{math.rad}\DefLIB{math.sin}
3523\DefLIB{math.sqrt}\DefLIB{math.tan}
3524\DefLIB{math.frexp}\DefLIB{math.ldexp}\DefLIB{math.random}
3525\DefLIB{math.randomseed}
3435\begin{verbatim} 3526\begin{verbatim}
3436 abs acos asin atan atan2 ceil cos deg exp floor log log10 3527 math.abs math.acos math.asin math.atan math.atan2
3437 max min mod rad sin sqrt tan frexp ldexp random randomseed 3528 math.ceil math.cos math.deg math.exp math.floor
3529 math.log math.log10 math.max math.min math.mod
3530 math.rad math.sin math.sqrt math.tan math.frexp
3531 math.ldexp math.random math.randomseed
3438\end{verbatim} 3532\end{verbatim}
3439plus a global variable \IndexLIB{PI}. 3533plus a variable \IndexLIB{math.pi}.
3440Most of them 3534Most of them
3441are only interfaces to the homonymous functions in the C~library, 3535are only interfaces to the homonymous functions in the C~library,
3442except that, for the trigonometric functions, 3536except that, for the trigonometric functions,
3443all angles are expressed in \emph{degrees}, not radians. 3537all angles are expressed in \emph{degrees}, not radians.
3444The functions \verb|deg| and \verb|rad| can be used to convert 3538The functions \verb|math.deg| and \verb|math.rad| can be used to convert
3445between radians and degrees. 3539between radians and degrees.
3446 3540
3447The function \verb|max| returns the maximum 3541The function \verb|math.max| returns the maximum
3448value of its numeric arguments. 3542value of its numeric arguments.
3449Similarly, \verb|min| computes the minimum. 3543Similarly, \verb|math.min| computes the minimum.
3450Both can be used with 1, 2, or more arguments. 3544Both can be used with 1, 2, or more arguments.
3451 3545
3452The functions \verb|random| and \verb|randomseed| are interfaces to 3546The functions \verb|math.random| and \verb|math.randomseed|
3453the simple random generator functions \verb|rand| and \verb|srand|, 3547are interfaces to the simple random generator functions
3454provided by ANSI~C. 3548\verb|rand| and \verb|srand|, provided by ANSI~C.
3455(No guarantees can be given for their statistical properties.) 3549(No guarantees can be given for their statistical properties.)
3456When called without arguments, 3550When called without arguments,
3457\verb|random| returns a pseudo-random real number in the range \Math{[0,1)}. 3551\verb|math.random| returns a pseudo-random real number
3552in the range \Math{[0,1)}.
3458When called with a number \Math{n}, 3553When called with a number \Math{n},
3459\verb|random| returns a pseudo-random integer in the range \Math{[1,n]}. 3554\verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}.
3460When called with two arguments, \Math{l} and \Math{u}, 3555When called with two arguments, \Math{l} and \Math{u},
3461\verb|random| returns a pseudo-random integer in the range \Math{[l,u]}. 3556\verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}.
3462 3557
3463 3558
3464\subsection{Input and Output Facilities} \label{libio} 3559\subsection{Input and Output Facilities} \label{libio}
3465 3560
3466All input and output operations in Lua are done, by default, 3561The I/O library provides two different styles for file manipulation.
3467over two \Def{file handles}: one for reading and one for writing. 3562The first one uses implicit file descriptors;
3468These handles are stored in two Lua global variables, 3563that is, there are operations to set a default input file and a
3469called \verb|_INPUT| and \verb|_OUTPUT|. 3564default output file,
3470The global variables 3565and all input/output operations are over those default files.
3471\verb|_STDIN|, \verb|_STDOUT|, and \verb|_STDERR| 3566The second style uses explicit file descriptors.
3472are initialized with file descriptors for 3567
3473\verb|stdin|, \verb|stdout|, and \verb|stderr|. 3568When using implicit file descriptors,
3474Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|. 3569all operations are supplied by table \DefLIB{io}.
3475\DefLIB{_INPUT}\DefLIB{_OUTPUT} 3570When using explicit file descriptors,
3476\DefLIB{_STDIN}\DefLIB{_STDOUT}\DefLIB{_STDERR} 3571the operation \DefLIB{io.open} returns a file descriptor,
3572and then all operations are supplied as methods by the file descriptor.
3573
3574Moreover, the table \verb|io| also provides
3575three predefined file descriptors:
3576\DefLIB{io.stdin}, \DefLIB{io.stdout}, and \DefLIB{io.stderr},
3577with their usual meaning from C.
3477 3578
3478A file handle is a userdata containing the file stream (\verb|FILE*|), 3579A file handle is a userdata containing the file stream (\verb|FILE*|),
3479and with a distinctive tag created by the I/O library. 3580with a distinctive metatable created by the I/O library.
3480 3581
3481Unless otherwise stated, 3582Unless otherwise stated,
3482all I/O functions return \nil\ on failure and 3583all I/O functions return \nil{} on failure
3483some value different from \nil\ on success. 3584(plus an error message as a second result)
3585and some value different from \nil{} on success.
3586
3587\subsubsection*{\ff \T{io.close ([handle])}}\DefLIB{io.close}
3588
3589Equivalent to \verb|fh:close| over the default output file.
3590
3591\subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush}
3592
3593Equivalent to \verb|fh:flush| over the default output file.
3484 3594
3485\subsubsection*{\ff \T{openfile (filename, mode)}}\DefLIB{openfile} 3595\subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input}
3596
3597When called with a file name, it opens the named file (in text mode),
3598and sets its handle as the default input file
3599(and returns nothing).
3600When called with a file handle,
3601it simply sets that file handle as the default input file.
3602When called without parameters,
3603it returns the current default input file.
3604
3605In case of errors this function raises the error,
3606instead of returning an error code.
3607
3608\subsubsection*{\ff \T{io.open (filename, mode)}}\DefLIB{io.open}
3486 3609
3487This function opens a file, 3610This function opens a file,
3488in the mode specified in the string \verb|mode|. 3611in the mode specified in the string \verb|mode|.
3489It returns a new file handle, 3612It returns a new file handle,
3490or, in case of errors, \nil\ plus a string describing the error. 3613or, in case of errors, \nil{} plus an error message.
3491This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
3492 3614
3493The \verb|mode| string can be any of the following: 3615The \verb|mode| string can be any of the following:
3494\begin{description}\leftskip=20pt 3616\begin{description}\leftskip=20pt
@@ -3504,141 +3626,41 @@ The \verb|mode| string may also have a \verb|b| at the end,
3504which is needed in some systems to open the file in binary mode. 3626which is needed in some systems to open the file in binary mode.
3505This string is exactly what is used in the standard~C function \verb|fopen|. 3627This string is exactly what is used in the standard~C function \verb|fopen|.
3506 3628
3507\subsubsection*{\ff \T{closefile (handle)}}\DefLIB{closefile} 3629\subsubsection*{\ff \T{io.output ([file])}}\DefLIB{io.output}
3508
3509This function closes the given file.
3510It does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
3511 3630
3512\subsubsection*{\ff \T{readfrom (filename)}}\DefLIB{readfrom} 3631Similar to \verb|io.input|, but operates over the default output file.
3513 3632
3514This function may be called in two ways. 3633\subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read}
3515When called with a file name, it opens the named file (in text mode),
3516sets its handle as the value of \verb|_INPUT|,
3517and returns this value.
3518It does not close the current input file.
3519When called without parameters,
3520it closes the \verb|_INPUT| file,
3521and restores \verb|stdin| as the value of \verb|_INPUT|.
3522If this function fails, it returns \nil,
3523plus a string describing the error.
3524 3634
3525\NOTE 3635Equivalent to \verb|fh:read| over the default input file.
3526If \verb|filename| starts with a \verb-|-,
3527then a \Index{piped input} is opened, via function \IndexVerb{popen}.
3528Not all systems implement pipes.
3529Moreover,
3530the number of files that can be open at the same time is
3531usually limited and depends on the system.
3532
3533\subsubsection*{\ff \T{writeto (filename)}}\DefLIB{writeto}
3534
3535This function may be called in two ways.
3536When called with a file name,
3537it opens the named file (in text mode),
3538sets its handle as the value of \verb|_OUTPUT|,
3539and returns this value.
3540It does not close the current output file.
3541Note that, if the file already exists,
3542then it will be \emph{completely erased} with this operation.
3543When called without parameters,
3544this function closes the \verb|_OUTPUT| file,
3545and restores \verb|stdout| as the value of \verb|_OUTPUT|.
3546\index{closing a file}
3547If this function fails, it returns \nil,
3548plus a string describing the error.
3549 3636
3550\NOTE 3637\subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile}
3551If \verb|filename| starts with a \verb-|-,
3552then a \Index{piped input} is opened, via function \IndexVerb{popen}.
3553Not all systems implement pipes.
3554Moreover,
3555the number of files that can be open at the same time is
3556usually limited and depends on the system.
3557 3638
3558\subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto} 3639Returns a handle for a temporary file.
3640This file is open in read/write mode,
3641and it is automatically removed when the program ends.
3559 3642
3560Opens a file named \verb|filename| (in text mode) 3643\subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write}
3561sets its handle as the value of \verb|_OUTPUT|,
3562and returns this value.
3563Unlike the \verb|writeto| operation,
3564this function does not erase any previous contents of the file;
3565instead, anything written to the file is appended to its end.
3566If this function fails, it returns \nil,
3567plus a string describing the error.
3568 3644
3569\subsubsection*{\ff \T{remove (filename)}}\DefLIB{remove} 3645Equivalent to \verb|fh:write| over the default output file.
3570 3646
3571Deletes the file with the given name.
3572If this function fails, it returns \nil,
3573plus a string describing the error.
3574 3647
3575\subsubsection*{\ff \T{rename (name1, name2)}}\DefLIB{rename}
3576 3648
3577Renames file named \verb|name1| to \verb|name2|. 3649\subsubsection*{\ff \T{fh:close ([handle])}}\DefLIB{fh:close}
3578If this function fails, it returns \nil,
3579plus a string describing the error.
3580 3650
3581\subsubsection*{\ff \T{flush ([filehandle])}}\DefLIB{flush} 3651Closes the file \verb|fh|.
3582 3652
3583Saves any written data to the given file. 3653\subsubsection*{\ff \T{fh:flush ()}}\DefLIB{fh:flush}
3584If \verb|filehandle| is not specified,
3585then \verb|flush| flushes all open files.
3586If this function fails, it returns \nil,
3587plus a string describing the error.
3588 3654
3589\subsubsection*{\ff \T{seek (filehandle [, whence] [, offset])}}\DefLIB{seek} 3655Saves any written data to the file \verb|fh|.
3590 3656
3591Sets and gets the file position, 3657\subsubsection*{\ff \T{fh:read (format1, ...)}}\DefLIB{fh:read}
3592measured in bytes from the beginning of the file,
3593to the position given by \verb|offset| plus a base
3594specified by the string \verb|whence|, as follows:
3595\begin{description}\leftskip=20pt
3596\item[``set''] base is position 0 (beginning of the file);
3597\item[``cur''] base is current position;
3598\item[``end''] base is end of file;
3599\end{description}
3600In case of success, function \verb|seek| returns the final file position,
3601measured in bytes from the beginning of the file.
3602If this function fails, it returns \nil,
3603plus a string describing the error.
3604 3658
3605The default value for \verb|whence| is \verb|"cur"|, 3659Reads the file \verb|fh|,
3606and for \verb|offset| is 0.
3607Therefore, the call \verb|seek(file)| returns the current
3608file position, without changing it;
3609the call \verb|seek(file, "set")| sets the position to the
3610beginning of the file (and returns 0);
3611and the call \verb|seek(file, "end")| sets the position to the
3612end of the file, and returns its size.
3613
3614\subsubsection*{\ff \T{tmpfile ()}}\DefLIB{tmpfile}
3615
3616Returns a handle for a temporary file.
3617This file is open in read/write mode,
3618and it is automatically removed when the program ends.
3619
3620\subsubsection*{\ff \T{tmpname ()}}\DefLIB{tmpname}
3621
3622Returns a string with a file name that can
3623be used for a temporary file.
3624The file must be explicitly opened before its use
3625and removed when no longer needed.
3626
3627This function is equivalent to the \verb|tmpnam| C~function,
3628and many people (and even some compilers!) advise against its use,
3629because between the time you call the function
3630and the time you open the file,
3631it is possible for another process
3632to create a file with the same name.
3633
3634\subsubsection*{\ff \T{read ([filehandle,] format1, ...)}}\DefLIB{read}
3635
3636Reads file \verb|_INPUT|,
3637or \verb|filehandle| if this argument is given,
3638according to the given formats, which specify what to read. 3660according to the given formats, which specify what to read.
3639For each format, 3661For each format,
3640the function returns a string (or a number) with the characters read, 3662the function returns a string (or a number) with the characters read,
3641or \nil\ if it cannot read data with the specified format. 3663or \nil{} if it cannot read data with the specified format.
3642When called without formats, 3664When called without formats,
3643it uses a default format that reads the entire next line 3665it uses a default format that reads the entire next line
3644(see below). 3666(see below).
@@ -3650,34 +3672,61 @@ this is the only format that returns a number instead of a string.
3650\item[``*a''] reads the whole file, starting at the current position. 3672\item[``*a''] reads the whole file, starting at the current position.
3651On end of file, it returns the empty string. 3673On end of file, it returns the empty string.
3652\item[``*l''] reads the next line (skipping the end of line), 3674\item[``*l''] reads the next line (skipping the end of line),
3653returning \nil\ on end of file. 3675returning \nil{} on end of file.
3654This is the default format. 3676This is the default format.
3655\item[\emph{number}] reads a string with up to that number of characters, 3677\item[\emph{number}] reads a string with up to that number of characters,
3656or \nil\ on end of file. 3678or \nil{} on end of file.
3657If number is zero, 3679If number is zero,
3658it reads nothing and returns an empty string, 3680it reads nothing and returns an empty string,
3659or \nil\ on end of file. 3681or \nil{} on end of file.
3682\end{description}
3683
3684\subsubsection*{\ff \T{fh:seek ([whence] [, offset])}}\DefLIB{fh:seek}
3685
3686Sets and gets the file position,
3687measured in bytes from the beginning of the file,
3688to the position given by \verb|offset| plus a base
3689specified by the string \verb|whence|, as follows:
3690\begin{description}\leftskip=20pt
3691\item[``set''] base is position 0 (beginning of the file);
3692\item[``cur''] base is current position;
3693\item[``end''] base is end of file;
3660\end{description} 3694\end{description}
3695In case of success, function \verb|seek| returns the final file position,
3696measured in bytes from the beginning of the file.
3697If this function fails, it returns \nil,
3698plus a string describing the error.
3699
3700The default value for \verb|whence| is \verb|"cur"|,
3701and for \verb|offset| is 0.
3702Therefore, the call \verb|file:seek()| returns the current
3703file position, without changing it;
3704the call \verb|file:seek("set")| sets the position to the
3705beginning of the file (and returns 0);
3706and the call \verb|file:seek("end")| sets the position to the
3707end of the file, and returns its size.
3661 3708
3662\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\DefLIB{write} 3709\subsubsection*{\ff \T{fh:write (value1, ...)}}\DefLIB{fh:write}
3663 3710
3664Writes the value of each of its arguments to 3711Writes the value of each of its arguments to
3665filehandle \verb|_OUTPUT|, 3712the filehandle \verb|fh|.
3666or to \verb|filehandle| if this argument is given.
3667The arguments must be strings or numbers. 3713The arguments must be strings or numbers.
3668To write other values, 3714To write other values,
3669use \verb|tostring| or \verb|format| before \verb|write|. 3715use \verb|tostring| or \verb|format| before \verb|write|.
3670If this function fails, it returns \nil, 3716If this function fails, it returns \nil,
3671plus a string describing the error. 3717plus a string describing the error.
3672 3718
3673\subsection{System Facilities} \label{libiosys}
3674 3719
3675\subsubsection*{\ff \T{clock ()}}\DefLIB{clock} 3720\subsection{Operating System Facilities} \label{libiosys}
3721
3722This library is implemented through table \DefLIB{os}.
3723
3724\subsubsection*{\ff \T{os.clock ()}}\DefLIB{os.clock}
3676 3725
3677Returns an approximation of the amount of CPU time 3726Returns an approximation of the amount of CPU time
3678used by the program, in seconds. 3727used by the program, in seconds.
3679 3728
3680\subsubsection*{\ff \T{date ([format [, time]])}}\DefLIB{date} 3729\subsubsection*{\ff \T{os.date ([format [, time]])}}\DefLIB{os.date}
3681 3730
3682Returns a string or a table containing date and time, 3731Returns a string or a table containing date and time,
3683formatted according to the given string \verb|format|. 3732formatted according to the given string \verb|format|.
@@ -3693,45 +3742,57 @@ then the date is formatted in Coordinated Universal Time.
3693After that optional character, 3742After that optional character,
3694if \verb|format| is \verb|*t|, 3743if \verb|format| is \verb|*t|,
3695then \verb|date| returns a table with the following fields: 3744then \verb|date| returns a table with the following fields:
3696\verb|year|, \verb|month| (1--12), \verb|day| (1--31), 3745\verb|year| (four digits), \verb|month| (1--12), \verb|day| (1--31),
3697\verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--59), 3746\verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--61),
3698\verb|wday| (weekday, Sunday is 1), 3747\verb|wday| (weekday, Sunday is 1),
3699\verb|yday| (day of the year), 3748\verb|yday| (day of the year),
3700and \verb|isdst| (daylight saving flag). 3749and \verb|isdst| (daylight saving flag, a boolean).
3701 3750
3702If format is not \verb|*t|, 3751If format is not \verb|*t|,
3703then \verb|date| returns the date as a string, 3752then \verb|date| returns the date as a string,
3704formatted according with the same rules as the C~function \verb|strftime|. 3753formatted according with the same rules as the C~function \verb|strftime|.
3705When called without arguments, 3754When called without arguments,
3706\verb|date| returns a reasonable date and time representation that depends on 3755\verb|date| returns a reasonable date and time representation that depends on
3707the host system and on the current locale (thus, \verb|date()| is equivalent 3756the host system and on the current locale
3708to \verb|date("%c")|). 3757(that is, \verb|os.date()| is equivalent to \verb|os.date("%c")|).
3709 3758
3710\subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime} 3759\subsubsection*{\ff \T{os.difftime (t1, t2)}}\DefLIB{os.difftime}
3711 3760
3712Returns the number of seconds from time \verb|t1| to time \verb|t2|. 3761Returns the number of seconds from time \verb|t1| to time \verb|t2|.
3713In Posix, Windows, and some other systems, 3762In Posix, Windows, and some other systems,
3714this value is exactly \verb|t1|\Math{-}\verb|t2|. 3763this value is exactly \verb|t1|\Math{-}\verb|t2|.
3715 3764
3716\subsubsection*{\ff \T{execute (command)}}\DefLIB{execute} 3765\subsubsection*{\ff \T{os.execute (command)}}\DefLIB{os.execute}
3717 3766
3718This function is equivalent to the C~function \verb|system|. 3767This function is equivalent to the C~function \verb|system|.
3719It passes \verb|command| to be executed by an operating system shell. 3768It passes \verb|command| to be executed by an operating system shell.
3720It returns a status code, which is system-dependent. 3769It returns a status code, which is system-dependent.
3721 3770
3722\subsubsection*{\ff \T{exit ([code])}}\DefLIB{exit} 3771\subsubsection*{\ff \T{os.exit ([code])}}\DefLIB{os.exit}
3723 3772
3724Calls the C~function \verb|exit|, 3773Calls the C~function \verb|exit|,
3725with an optional \verb|code|, 3774with an optional \verb|code|,
3726to terminate the host program. 3775to terminate the host program.
3727The default value for \verb|code| is the success code. 3776The default value for \verb|code| is the success code.
3728 3777
3729\subsubsection*{\ff \T{getenv (varname)}}\DefLIB{getenv} 3778\subsubsection*{\ff \T{os.getenv (varname)}}\DefLIB{os.getenv}
3730 3779
3731Returns the value of the process environment variable \verb|varname|, 3780Returns the value of the process environment variable \verb|varname|,
3732or \nil\ if the variable is not defined. 3781or \nil{} if the variable is not defined.
3782
3783\subsubsection*{\ff \T{os.remove (filename)}}\DefLIB{os.remove}
3784
3785Deletes the file with the given name.
3786If this function fails, it returns \nil,
3787plus a string describing the error.
3733 3788
3734\subsubsection*{\ff \T{setlocale (locale [, category])}}\DefLIB{setlocale} 3789\subsubsection*{\ff \T{os.rename (name1, name2)}}\DefLIB{os.rename}
3790
3791Renames file named \verb|name1| to \verb|name2|.
3792If this function fails, it returns \nil,
3793plus a string describing the error.
3794
3795\subsubsection*{\ff \T{os.setlocale (locale [, category])}}\DefLIB{os.setlocale}
3735 3796
3736This function is an interface to the C~function \verb|setlocale|. 3797This function is an interface to the C~function \verb|setlocale|.
3737\verb|locale| is a string specifying a locale; 3798\verb|locale| is a string specifying a locale;
@@ -3740,15 +3801,15 @@ This function is an interface to the C~function \verb|setlocale|.
3740\verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|; 3801\verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|;
3741the default category is \verb|"all"|. 3802the default category is \verb|"all"|.
3742The function returns the name of the new locale, 3803The function returns the name of the new locale,
3743or \nil\ if the request cannot be honored. 3804or \nil{} if the request cannot be honored.
3744 3805
3745\subsubsection*{\ff \T{time ([table])}}\DefLIB{time} 3806\subsubsection*{\ff \T{os.time ([table])}}\DefLIB{os.time}
3746 3807
3747Returns the current time when called without arguments, 3808Returns the current time when called without arguments,
3748or a time representing the date and time specified by the given table. 3809or a time representing the date and time specified by the given table.
3749This table must have fields \verb|year|, \verb|month|, and \verb|day|, 3810This table must have fields \verb|year|, \verb|month|, and \verb|day|,
3750and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| 3811and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst|
3751(for a description of these fields, see the \verb|date| function). 3812(for a description of these fields, see the \verb|os.date| function).
3752 3813
3753The returned value is a number, whose meaning depends on your system. 3814The returned value is a number, whose meaning depends on your system.
3754In Posix, Windows, and some other systems, this number counts the number 3815In Posix, Windows, and some other systems, this number counts the number
@@ -3757,6 +3818,21 @@ In other systems, the meaning is not specified,
3757and the number returned bt \verb|time| can be used only as an argument to 3818and the number returned bt \verb|time| can be used only as an argument to
3758\verb|date| and \verb|difftime|. 3819\verb|date| and \verb|difftime|.
3759 3820
3821\subsubsection*{\ff \T{os.tmpname ()}}\DefLIB{os.tmpname}
3822
3823Returns a string with a file name that can
3824be used for a temporary file.
3825The file must be explicitly opened before its use
3826and removed when no longer needed.
3827
3828This function is equivalent to the \verb|tmpnam| C~function,
3829and many people (and even some compilers!) advise against its use,
3830because between the time you call the function
3831and the time you open the file,
3832it is possible for another process
3833to create a file with the same name.
3834
3835
3760\subsection{The Reflexive Debug Interface} 3836\subsection{The Reflexive Debug Interface}
3761 3837
3762The library \verb|ldblib| provides 3838The library \verb|ldblib| provides
@@ -3808,7 +3884,7 @@ This function returns the name and the value of the local variable
3808with index \verb|local| of the function at level \verb|level| of the stack. 3884with index \verb|local| of the function at level \verb|level| of the stack.
3809(The first parameter or local variable has index~1, and so on, 3885(The first parameter or local variable has index~1, and so on,
3810until the last active local variable.) 3886until the last active local variable.)
3811The function returns \nil\ if there is no local 3887The function returns \nil{} if there is no local
3812variable with the given index, 3888variable with the given index,
3813and raises an error when called with a \verb|level| out of range. 3889and raises an error when called with a \verb|level| out of range.
3814(You can call \verb|getinfo| to check whether the level is valid.) 3890(You can call \verb|getinfo| to check whether the level is valid.)
@@ -3817,7 +3893,7 @@ and raises an error when called with a \verb|level| out of range.
3817 3893
3818This function assigns the value \verb|value| to the local variable 3894This function assigns the value \verb|value| to the local variable
3819with index \verb|local| of the function at level \verb|level| of the stack. 3895with index \verb|local| of the function at level \verb|level| of the stack.
3820The function returns \nil\ if there is no local 3896The function returns \nil{} if there is no local
3821variable with the given index, 3897variable with the given index,
3822and raises an error when called with a \verb|level| out of range. 3898and raises an error when called with a \verb|level| out of range.
3823(You can call \verb|getinfo| to check whether the level is valid.) 3899(You can call \verb|getinfo| to check whether the level is valid.)
@@ -3858,84 +3934,83 @@ it is also frequently used as a stand-alone language.
3858An interpreter for Lua as a stand-alone language, 3934An interpreter for Lua as a stand-alone language,
3859called simply \verb|lua|, 3935called simply \verb|lua|,
3860is provided with the standard distribution. 3936is provided with the standard distribution.
3861This program can be called with any sequence of the following arguments: 3937The stand-alone interpreter includes
3938all standard libraries plus the reflexive debug interface.
3939Its usage is:
3940\begin{verbatim}
3941 lua [options] [prog [args]]
3942\end{verbatim}
3943The options are:
3862\begin{description}\leftskip=20pt 3944\begin{description}\leftskip=20pt
3863\item[\T{-sNUM}] sets the stack size to \T{NUM}
3864(if present, this must be the first option);
3865\item[\T{-} ] executes \verb|stdin| as a file; 3945\item[\T{-} ] executes \verb|stdin| as a file;
3866\item[\T{-c}] calls \verb|lua_close| after processing all arguments;
3867\item[\T{-e} \rm\emph{stat}] executes string \emph{stat}; 3946\item[\T{-e} \rm\emph{stat}] executes string \emph{stat};
3868\item[\T{-f} \rm\emph{filename}] executes file \emph{filename} with the 3947\item[\T{-l} \rm\emph{file}] executes file \emph{file};
3869remaining arguments in table \verb|arg|; 3948\item[\T{-i}] enters interactive mode after running \emph{prog};
3870\item[\T{-i}] enters interactive mode with prompt;
3871\item[\T{-q}] enters interactive mode without prompt;
3872\item[\T{-v}] prints version information; 3949\item[\T{-v}] prints version information;
3873\item[\T{var=}\rm\emph{value}] sets global \verb|var| to string \verb|"|\emph{value}\verb|"|; 3950\item[\T{--}] stop handling options.
3874\item[\emph{filename}] executes file \emph{filename}.
3875\end{description} 3951\end{description}
3952After handling its options, \verb|lua| runs the given \emph{prog},
3953passing to it the given \emph{args}.
3876When called without arguments, 3954When called without arguments,
3877\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, 3955\verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
3878and as \verb|lua -| otherwise. 3956and as \verb|lua -| otherwise.
3879 3957
3880All arguments are handled in order, except \verb|-c|. 3958Before running any argument,
3959the intepreter checks for an environment variable \IndexVerb{LUA_INIT}.
3960If its format is \verb|@|\emph{filename},
3961then lua executes the file.
3962Otherwise, lua executes the string itself.
3963
3964All options are handled in order, except \verb|-i|.
3881For instance, an invocation like 3965For instance, an invocation like
3882\begin{verbatim} 3966\begin{verbatim}
3883 $ lua -i a=test prog.lua 3967 $ lua -e'a=1' -e 'print(a)' prog.lua
3884\end{verbatim} 3968\end{verbatim}
3885will first interact with the user until an \verb|EOF| in \verb|stdin|, 3969will first set \verb|a| to 1, then print \verb|a|,
3886then will set \verb|a| to \verb|"test"|, 3970and finally run the file \verb|prog.lua|.
3887and finally will run the file \verb|prog.lua|. 3971(Here, \verb|$| is the shell prompt. Your prompt may be different.)
3888(Here, 3972
3889\verb|$| is the shell prompt. Your prompt may be different.) 3973Before starting to run the program,
3890 3974\verb|lua| collects all arguments in the command line
3891When the option \T{-f filename} is used, 3975in a global table called \verb|arg|.
3892all remaining arguments in the command line 3976The program name is stored in index 0,
3893are passed to the Lua program \verb|filename| in a table called \verb|arg|. 3977the first argument after the program goes to index 1,
3894In this table, 3978and so on.
3895the field \verb|n| gets the index of the last argument, 3979The field \verb|n| gets the number of arguments after the program name.
3896and the field 0 gets \verb|"filename"|. 3980Any argument before the program name
3981(that is, the options plus the interpreter name)
3982goes to negative indices.
3897For instance, in the call 3983For instance, in the call
3898\begin{verbatim} 3984\begin{verbatim}
3899 $ lua a.lua -f b.lua t1 t3 3985 $ lua -la.lua b.lua t1 t2
3900\end{verbatim} 3986\end{verbatim}
3901the interpreter first runs the file \T{a.lua}, 3987the interpreter first runs the file \T{a.lua},
3902then creates a table 3988then creates a table
3903\begin{verbatim} 3989\begin{verbatim}
3904 arg = {"t1", "t3"; n = 2, [0] = "b.lua"} 3990 arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua",
3991 [1] = "t1", [2] = "t2"; n = 2 }
3905\end{verbatim} 3992\end{verbatim}
3906and finally runs the file \T{b.lua}. 3993and finally runs the file \T{b.lua}.
3907 3994
3908The stand-alone interpreter includes
3909all standard libraries plus the reflexive debug interface.
3910It also provides a \verb|getargs| function that
3911can be used to access \emph{all} command line arguments.
3912\DefLIB{getargs}
3913For instance, if you call Lua with the line
3914\begin{verbatim}
3915 $ lua -c a b
3916\end{verbatim}
3917then a call to \verb|getargs| in \verb|a| or \verb|b| will return the table
3918\begin{verbatim}
3919 {[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3}
3920\end{verbatim}
3921
3922In interactive mode, 3995In interactive mode,
3923a multi-line statement can be written ending intermediate 3996if you write an incomplete statement,
3924lines with a backslash (`\verb|\|'). 3997the interpreter waits for its completion.
3998
3925If the global variable \IndexVerb{_PROMPT} is defined as a string, 3999If the global variable \IndexVerb{_PROMPT} is defined as a string,
3926then its value is used as the prompt. 4000then its value is used as the prompt.
3927Therefore, the prompt can be changed directly on the command line: 4001Therefore, the prompt can be changed directly on the command line:
3928\begin{verbatim} 4002\begin{verbatim}
3929 $ lua _PROMPT='myprompt> ' -i 4003 $ lua -e"_PROMPT='myprompt> '" -i
3930\end{verbatim} 4004\end{verbatim}
4005(the first pair of quotes is for the shell,
4006the second is for Lua),
3931or in any Lua programs by assigning to \verb|_PROMPT|. 4007or in any Lua programs by assigning to \verb|_PROMPT|.
3932Note the use of \verb|-i| to enter interactive mode; otherwise, 4008Note the use of \verb|-i| to enter interactive mode; otherwise,
3933the program would end just after the assignment to \verb|_PROMPT|. 4009the program would end just after the assignment to \verb|_PROMPT|.
3934 4010
3935In Unix systems, Lua scripts can be made into executable programs 4011In Unix systems, Lua scripts can be made into executable programs
3936by using \verb|chmod +x| and the~\verb|#!| form, 4012by using \verb|chmod +x| and the~\verb|#!| form,
3937as in \verb|#!/usr/local/bin/lua|, 4013as in \verb|#!/usr/local/bin/lua|.
3938or \verb|#!/usr/local/bin/lua -f| to get other arguments.
3939(Of course, 4014(Of course,
3940the location of the Lua interpreter may be different in your machine. 4015the location of the Lua interpreter may be different in your machine.
3941If \verb|lua| is in your \verb|PATH|, 4016If \verb|lua| is in your \verb|PATH|,
@@ -3945,6 +4020,8 @@ then a more portable solution is \verb|#!/usr/bin/env lua|.)
3945%------------------------------------------------------------------------------ 4020%------------------------------------------------------------------------------
3946\section*{Acknowledgments} 4021\section*{Acknowledgments}
3947 4022
4023%% TODO rever isso?
4024
3948The authors thank CENPES/PETROBRAS which, 4025The authors thank CENPES/PETROBRAS which,
3949jointly with \tecgraf, used early versions of 4026jointly with \tecgraf, used early versions of
3950this system extensively and gave valuable comments. 4027this system extensively and gave valuable comments.
@@ -3977,7 +4054,7 @@ A function call as the last expression in a list constructor
3977(like \verb|{a,b,f()}}|) has all its return values inserted in the list. 4054(like \verb|{a,b,f()}}|) has all its return values inserted in the list.
3978 4055
3979\item 4056\item
3980\rwd{global} and \rwd{in} are reserved words. 4057\rwd{in} is a reserved word.
3981 4058
3982\item 4059\item
3983When a literal string of the form \verb|[[...]]| starts with a newline, 4060When a literal string of the form \verb|[[...]]| starts with a newline,
@@ -3997,11 +4074,6 @@ The \verb|read| option \verb|*w| is obsolete.
3997\item 4074\item
3998The \verb|format| option \verb|%n$| is obsolete. 4075The \verb|format| option \verb|%n$| is obsolete.
3999 4076
4000\item
4001\verb|newtag| is deprecated, being replaced by \verb|newtype|.
4002Tags created in Lua with \verb|newtype| (or \verb|newtag|) can only
4003be used for tables.
4004
4005\end{itemize} 4077\end{itemize}
4006 4078
4007 4079
@@ -4009,22 +4081,30 @@ be used for tables.
4009\begin{itemize} 4081\begin{itemize}
4010 4082
4011\item 4083\item
4012The \verb|lua_pushuserdata| function has been replaced by 4084Userdata!!
4013\verb|lua_newuserdatabox|.
4014 4085
4015\end{itemize} 4086\end{itemize}
4016 4087
4017%{=============================================================== 4088%{===============================================================
4018\newpage 4089\newpage
4019\section*{The Complete Syntax of Lua} \label{BNF} 4090\section*{The Complete Syntax of Lua} \label{BNF}
4020
4021\addcontentsline{toc}{section}{The Complete Syntax of Lua} 4091\addcontentsline{toc}{section}{The Complete Syntax of Lua}
4022 4092
4093The notation used here is the usual extended BNF,
4094in which
4095\rep{\emph{a}}~means 0 or more \emph{a}'s, and
4096\opt{\emph{a}}~means an optional \emph{a}.
4097Non-terminals are shown in \emph{italics},
4098keywords are shown in {\bf bold},
4099and other terminal symbols are shown in {\tt typewriter} font,
4100enclosed in single quotes.
4101
4102
4023\renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} 4103\renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent}
4024 4104
4025\renewcommand{\OrNL}{\\ & \Or & } 4105\renewcommand{\OrNL}{\\ & \Or & }
4026%\newcommand{\Nter}[1]{{\rm{\tt#1}}} 4106%\newcommand{\Nter}[1]{{\rm{\tt#1}}}
4027\newcommand{\Nter}[1]{#1} 4107%\newcommand{\Nter}[1]{\ter{#1}}
4028 4108
4029\index{grammar} 4109\index{grammar}
4030 4110
@@ -4049,7 +4129,8 @@ The \verb|lua_pushuserdata| function has been replaced by
4049 \rwd{do} block \rwd{end} 4129 \rwd{do} block \rwd{end}
4050\OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1 4130\OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
4051 \rwd{do} block \rwd{end} 4131 \rwd{do} block \rwd{end}
4052\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} 4132\OrNL \rwd{function} funcname funcbody
4133\OrNL \rwd{local} \rwd{function} \Nter{Name} funcbody
4053\OrNL \rwd{local} namelist \opt{init} 4134\OrNL \rwd{local} namelist \opt{init}
4054} 4135}
4055 4136
@@ -4072,8 +4153,10 @@ The \verb|lua_pushuserdata| function has been replaced by
4072 4153
4073\produc{exp}{% 4154\produc{exp}{%
4074 \rwd{nil} 4155 \rwd{nil}
4156 \rwd{false}
4157 \rwd{true}
4075\Or \Nter{Number} 4158\Or \Nter{Number}
4076\Or \Nter{Literal} 4159\OrNL \Nter{Literal}
4077\Or function 4160\Or function
4078\Or prefixexp 4161\Or prefixexp
4079\OrNL tableconstructor 4162\OrNL tableconstructor
@@ -4094,7 +4177,9 @@ The \verb|lua_pushuserdata| function has been replaced by
4094\Or \Nter{Literal} 4177\Or \Nter{Literal}
4095} 4178}
4096 4179
4097\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}} 4180\produc{function}{\rwd{function} funcbody}
4181
4182\produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
4098 4183
4099\produc{parlist1}{% 4184\produc{parlist1}{%
4100 \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}} 4185 \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}}