aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2001-07-19 10:36:18 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2001-07-19 10:36:18 -0300
commita94cba4b88a940cba7a35244b8a1b393f33a905c (patch)
tree6828eb0e630b492a9d62022bb82819172a06afa9
parentf9f355221fc41b5db5e6bc7b3e369c4d074003d5 (diff)
downloadlua-a94cba4b88a940cba7a35244b8a1b393f33a905c.tar.gz
lua-a94cba4b88a940cba7a35244b8a1b393f33a905c.tar.bz2
lua-a94cba4b88a940cba7a35244b8a1b393f33a905c.zip
ready for 4.1 alpha?
-rw-r--r--manual.tex790
1 files changed, 487 insertions, 303 deletions
diff --git a/manual.tex b/manual.tex
index 6e1d490f..8284b989 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.48 2001/01/29 19:33:55 roberto Exp roberto $ 1% $Id: manual.tex,v 1.49 2001/01/31 19:53:01 roberto Exp roberto $
2 2
3\documentclass[11pt]{article} 3\documentclass[11pt]{article}
4\usepackage{fullpage} 4\usepackage{fullpage}
@@ -29,7 +29,7 @@
29 29
30\newcommand{\ff}{$\bullet$\ } 30\newcommand{\ff}{$\bullet$\ }
31 31
32\newcommand{\Version}{4.0} 32\newcommand{\Version}{4.1 (alpha)}
33 33
34% LHF 34% LHF
35\renewcommand{\ter}[1]{{\rm`{\tt#1}'}} 35\renewcommand{\ter}[1]{{\rm`{\tt#1}'}}
@@ -71,7 +71,7 @@ Last revised on \today
71\null\vfill 71\null\vfill
72 72
73\noindent 73\noindent
74Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved. 74Copyright \copyright\ 1994--2001 TeCGraf, PUC-Rio. All rights reserved.
75 75
76\noindent 76\noindent
77Permission is hereby granted, without written agreement and without license 77Permission is hereby granted, without written agreement and without license
@@ -110,7 +110,7 @@ This implementation contains no third-party code.
110 110
111\noindent 111\noindent
112Copies of this manual can be obtained at 112Copies of this manual can be obtained at
113\verb|http://www.tecgraf.puc-rio.br/lua/|. 113\verb|http://www.lua.org|.
114 114
115\bigskip 115\bigskip
116\noindent 116\noindent
@@ -134,7 +134,7 @@ Waldemar Celes
134\tecgraf\ --- Computer Science Department --- PUC-Rio 134\tecgraf\ --- Computer Science Department --- PUC-Rio
135} 135}
136 136
137\date{{\small \tt\$Date: 2001/01/29 19:33:55 $ $}} 137\date{{\small \tt\$Date: 2001/01/31 19:53:01 $ $}}
138 138
139\maketitle 139\maketitle
140 140
@@ -228,8 +228,8 @@ as stated in its copyright notice.
228The implementation described in this manual is available 228The implementation described in this manual is available
229at the following URL's: 229at the following URL's:
230\begin{verbatim} 230\begin{verbatim}
231 http://www.tecgraf.puc-rio.br/lua/ 231 http://www.lua.org
232 ftp://ftp.tecgraf.puc-rio.br/pub/lua/ 232 ftp://ftp.lua.org
233\end{verbatim} 233\end{verbatim}
234 234
235Like any other reference manual, 235Like any other reference manual,
@@ -305,6 +305,7 @@ are interchangeable.
305Lua automatically detects the file type and acts accordingly. 305Lua automatically detects the file type and acts accordingly.
306\index{pre-compilation} 306\index{pre-compilation}
307 307
308
308\section{\Index{Types and Tags}} \label{TypesSec} 309\section{\Index{Types and Tags}} \label{TypesSec}
309 310
310Lua is a \emph{dynamically typed language}. 311Lua is a \emph{dynamically typed language}.
@@ -365,23 +366,92 @@ to tables, and do not imply any kind of copy.
365Moreover, tables must be explicitly created before used 366Moreover, tables must be explicitly created before used
366\see{tableconstructor}. 367\see{tableconstructor}.
367 368
368Each of the types \M{nil}, \M{number}, and \M{string} has a different tag. 369
369All values of each of these types have the same pre-defined tag. 370\subsection{Tags}
370As explained above, 371
371values of type \M{function} can have two different tags, 372Each type has a \emph{name},
372depending on whether they are Lua functions or C~functions. 373and a numerical identifier,
373Finally, 374called a \Index{tag}.
374values of type \M{userdata} and \M{table} can have variable tags, 375Tags are mainly used by C code,
375assigned by the programmer \see{tag-method}. 376to avoid the manipulation of strings.
376The \verb|tag| function returns the tag of a given value. 377Most operations over types, in the C API,
377User tags are created with the function \verb|newtag|. 378require a tag to identify the type.
378The \verb|settag| function 379In Lua, all operations over types work
379is used to change the tag of a table \see{pdf-newtag}. 380both with type names or tags.
380The tag of userdata values can only be set from~C \see{C-tags}. 381
381Tags are mainly used to select \emph{tag methods} when 382
382some events occur. 383\subsection{User-defined Types}
383Tag methods are the main mechanism for extending the 384
384semantics of Lua \see{tag-method}. 385Lua programs can create new types,
386called \Index{User-defined Types}.
387A user-defined type is always based on a base type,
388either a table or a userdata.
389Objects of an extended type have an internal structure
390identical to the corresponding base type,
391but may have diferent semantics for each operation.
392
393The \verb|newtype| function creates a new type \see{pdf-newtype}.
394Types created by Lua programs are always based upon tables;
395types created by C can be based upon tables or upon userdata.
396The \verb|settagmethod| function defines new semantics for
397the operations of this new type \see{tag-method}.
398The \verb|settype| function changes the type of a given object
399\see{pdf-settype}.
400
401
402\section{Garbage Collection}\label{GC}
403
404Lua does automatic memory management.
405To do that,
406Lua runs a \Index{garbage collector} from time to time.
407All objects in Lua are subjected to automatic management:
408tables, userdata, functions, and strings.
409
410Lua uses two numbers to control its garbage-collection cycles.
411One number counts how many bytes of dynamic memory Lua is using,
412and the other is a threshold.
413When the number of bytes crosses the threshold,
414Lua runs the garbage collector,
415which reclaims the memory of all ``dead'' objects
416(that is, objects no longer accessible from Lua).
417The byte counter is corrected,
418and then the threshold is reset to twice the value of the byte counter.
419
420Through the C API, you can consult those numbers,
421and change the threshold \see{GC-API}.
422Setting the threshold to zero actually forces an immediate
423garbage-collection cycle,
424while setting it to a huge number stops the garbage collector.
425Using Lua code you have a more limited control of memory management,
426through functions \verb|gcinfo| and \verb|collectgarbage|.
427
428
429You can set garbage-collector tag methods for user-defined
430types based on userdata \see{tag-method}.
431Lua calls those functions when it is about to free a userdata
432of the corresponding type.
433Using this facility, you can coordinate Lua's garbage collection
434with external resourse management
435(such as closing files or freeing your own memory).
436
437
438\subsection{Weak Tables}\label{weak-table}
439
440A \IndexEmph{weak table} is a table whose elements are
441\IndexEmph{weak references}.
442A weak reference is ignored by the garbage collector,
443so that if the only references to an object are weak references,
444the garbage collector will collect that object.
445
446A weak table can have weak keys, weak values, or both.
447A table with weak keys allows the collection of its keys,
448but avoids the collection of its values.
449A table with both weak keys and weak values allow the collection of both.
450In any case, if either the key or the value is collected,
451the whole pair is removed from the table.
452The weakness of a table is controled by the
453function \verb|weakmode| \see{weakmode}.
454
385 455
386\section{The Language} 456\section{The Language}
387 457
@@ -398,14 +468,16 @@ except that
398the definition of letter depends on the current locale: 468the definition of letter depends on the current locale:
399Any character considered alphabetic by the current locale 469Any character considered alphabetic by the current locale
400can be used in an identifier. 470can be used in an identifier.
401The following words are \emph{reserved}, and cannot be used as identifiers: 471The following words are \emph{reserved},
472and cannot be used as identifiers:
402\index{reserved words} 473\index{reserved words}
403\begin{verbatim} 474\begin{verbatim}
404 and break do else elseif 475 and break do else elseif
405 end for function if in 476 end for function global if
406 local nil not or repeat 477 in local nil not or
407 return then until while 478 repeat return then until while
408\end{verbatim} 479\end{verbatim}
480(\rwd{global} is reserved for future use.)
409 481
410Lua is a case-sensitive language: 482Lua is a case-sensitive language:
411\T{and} is a reserved word, but \T{And} and \T{\'and} 483\T{and} is a reserved word, but \T{And} and \T{\'and}
@@ -447,6 +519,8 @@ Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|.
447Literals in this bracketed form may run for several lines, 519Literals in this bracketed form may run for several lines,
448may contain nested \verb|[[| \dots\ \verb|]]| pairs, 520may contain nested \verb|[[| \dots\ \verb|]]| pairs,
449and do not interpret escape sequences. 521and do not interpret escape sequences.
522When the \verb|[[| is immediatly followed by a newline,
523this newline is not included in the string.
450This form is specially convenient for 524This form is specially convenient for
451writing strings that contain program pieces or 525writing strings that contain program pieces or
452other quoted strings. 526other quoted strings.
@@ -457,6 +531,9 @@ the following three literals are equivalent:
457 2) '\97lo\10\04923"' 531 2) '\97lo\10\04923"'
458 3) [[alo 532 3) [[alo
459 123"]] 533 123"]]
534 4) [[
535 alo
536 123"]]
460\end{verbatim} 537\end{verbatim}
461 538
462\IndexEmph{Comments} start anywhere outside a string with a 539\IndexEmph{Comments} start anywhere outside a string with a
@@ -489,22 +566,6 @@ For complete control of how numbers are converted to strings,
489use the \verb|format| function \see{format}. 566use the \verb|format| function \see{format}.
490 567
491 568
492\subsection{\Index{Adjustment}} \label{adjust}
493
494Functions in Lua can return many values.
495Because there are no type declarations,
496when a function is called
497the system does not know how many values the function will return,
498or how many parameters it needs.
499Therefore, sometimes, a list of values must be \emph{adjusted}, at run time,
500to a given length.
501If there are more values than are needed,
502then the excess values are thrown away.
503If there are less values than are needed,
504then the list is extended with as many \nil's as needed.
505This adjustment occurs in multiple assignments \see{assignment}
506and in function calls \see{functioncall}.
507
508 569
509\subsection{Statements}\label{stats} 570\subsection{Statements}\label{stats}
510 571
@@ -560,9 +621,15 @@ Multiple assignment can be used to exchange two values, as in
560 x, y = y, x 621 x, y = y, x
561\end{verbatim} 622\end{verbatim}
562 623
563The two lists in a multiple assignment may have different lengths.
564Before the assignment, the list of values is adjusted to 624Before the assignment, the list of values is adjusted to
565the length of the list of variables \see{adjust}. 625the length of the list of variables.
626If there are more values than are needed,
627the excess values are thrown away.
628If there are less values than are needed,
629the list is extended with as many \nil's as needed.
630If the list of expressions (\M{explist1}) ends with a function call,
631all values returned by the function call enter in the list of values,
632before the adjust.
566 633
567A single name can denote a global variable, a local variable, 634A single name can denote a global variable, a local variable,
568or a formal parameter: 635or a formal parameter:
@@ -572,17 +639,16 @@ or a formal parameter:
572 639
573Square brackets are used to index a table: 640Square brackets are used to index a table:
574\begin{Produc} 641\begin{Produc}
575\produc{var}{varorfunc \ter{[} exp1 \ter{]}} 642\produc{var}{exp \ter{[} exp \ter{]}}
576\produc{varorfunc}{var \Or functioncall}
577\end{Produc}% 643\end{Produc}%
578The \M{varorfunc} should result in a table value, 644The first expression (\M{exp}) should result in a table value,
579from where the field indexed by the expression \M{exp1} 645from where the field indexed by the expression \M{exp}
580value gets the assigned value. 646value gets the assigned value.
581 647
582The syntax \verb|var.NAME| is just syntactic sugar for 648The syntax \verb|var.NAME| is just syntactic sugar for
583\verb|var["NAME"]|: 649\verb|var["NAME"]|:
584\begin{Produc} 650\begin{Produc}
585\produc{var}{varorfunc \ter{.} name} 651\produc{var}{exp \ter{.} name}
586\end{Produc}% 652\end{Produc}%
587 653
588The meaning of assignments and evaluations of global variables and 654The meaning of assignments and evaluations of global variables and
@@ -605,13 +671,14 @@ familiar syntax
605\index{repeat-until statement} 671\index{repeat-until statement}
606\index{if-then-else statement} 672\index{if-then-else statement}
607\begin{Produc} 673\begin{Produc}
608\produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end}} 674\produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}}
609\produc{stat}{\rwd{repeat} block \rwd{until} exp1} 675\produc{stat}{\rwd{repeat} block \rwd{until} exp}
610\produc{stat}{\rwd{if} exp1 \rwd{then} block 676\produc{stat}{\rwd{if} exp \rwd{then} block
611 \rep{\rwd{elseif} exp1 \rwd{then} block} 677 \rep{\rwd{elseif} exp \rwd{then} block}
612 \opt{\rwd{else} block} \rwd{end}} 678 \opt{\rwd{else} block} \rwd{end}}
613\end{Produc}% 679\end{Produc}%
614The \Index{condition expression} \M{exp1} of a control structure may return any value. 680The \Index{condition expression} \M{exp} of a
681control structure may return any value.
615All values different from \nil\ are considered true; 682All values different from \nil\ are considered true;
616only \nil\ is considered false. 683only \nil\ is considered false.
617 684
@@ -650,7 +717,7 @@ one for numbers and one for tables.
650\newpage 717\newpage
651The numerical \rwd{for} loop has the following syntax: 718The numerical \rwd{for} loop has the following syntax:
652\begin{Produc} 719\begin{Produc}
653\produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} 720\produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
654 \rwd{do} block \rwd{end}} 721 \rwd{do} block \rwd{end}}
655\end{Produc}% 722\end{Produc}%
656A \rwd{for} statement like 723A \rwd{for} statement like
@@ -688,7 +755,7 @@ The table \rwd{for} statement traverses all pairs
688(index,value) of a given table. 755(index,value) of a given table.
689It has the following syntax: 756It has the following syntax:
690\begin{Produc} 757\begin{Produc}
691\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp1 758\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp
692 \rwd{do} block \rwd{end}} 759 \rwd{do} block \rwd{end}}
693\end{Produc}% 760\end{Produc}%
694A \rwd{for} statement like 761A \rwd{for} statement like
@@ -699,10 +766,10 @@ is equivalent to the code:
699\begin{verbatim} 766\begin{verbatim}
700 do 767 do
701 local _t = exp 768 local _t = exp
702 local index, value = next(t, nil) 769 local index, value = next(_t, nil)
703 while index do 770 while index do
704 block 771 block
705 index, value = next(t, index) 772 index, value = next(_t, index)
706 end 773 end
707 end 774 end
708\end{verbatim} 775\end{verbatim}
@@ -774,6 +841,9 @@ The basic expressions in Lua are
774\produc{exp}{tableconstructor} 841\produc{exp}{tableconstructor}
775\end{Produc}% 842\end{Produc}%
776 843
844An expression enclosed in parentheses always results
845in only one value.
846
777Numbers (numerical constants) and 847Numbers (numerical constants) and
778literal strings are explained in \See{lexical}; 848literal strings are explained in \See{lexical};
779variables are explained in \See{assignment}; 849variables are explained in \See{assignment};
@@ -790,11 +860,6 @@ See \See{tag-method} for a description of these functions
790(\verb|getglobal| is in the basic library; 860(\verb|getglobal| is in the basic library;
791\T{gettable\_event} is used for explanatory purposes only). 861\T{gettable\_event} is used for explanatory purposes only).
792 862
793The non-terminal \M{exp1} is used to indicate that the values
794returned by an expression must be adjusted to one single value:
795\begin{Produc}
796\produc{exp1}{exp}
797\end{Produc}%
798 863
799\subsubsection{Arithmetic Operators} 864\subsubsection{Arithmetic Operators}
800Lua supports the usual \Index{arithmetic operators}: 865Lua supports the usual \Index{arithmetic operators}:
@@ -823,7 +888,10 @@ If they are different, then the result is \nil.
823Otherwise, their values are compared. 888Otherwise, their values are compared.
824Numbers and strings are compared in the usual way. 889Numbers and strings are compared in the usual way.
825Tables, userdata, and functions are compared by reference, 890Tables, userdata, and functions are compared by reference,
826that is, two tables are considered equal only if they are the \emph{same} table. 891that is,
892two tables are considered equal only if they are the \emph{same} table.
893Every time you create a new table (or userdata, or function) this
894new value is different from any previously existing value.
827The operator \verb|~=| is exactly the negation of equality (\verb|==|). 895The operator \verb|~=| is exactly the negation of equality (\verb|==|).
828 896
829\NOTE 897\NOTE
@@ -904,10 +972,10 @@ except for \verb|^| (exponentiation),
904which is right associative. 972which is right associative.
905\NOTE 973\NOTE
906The pre-compiler may rearrange the order of evaluation of 974The pre-compiler may rearrange the order of evaluation of
907associative operators (such as~\verb|..| or~\verb|+|), 975associative or commutative operators,
908as long as these optimizations do not change normal results. 976as long as these optimizations do not change normal results.
909However, these optimizations may change some results 977However, these optimizations may change some results
910if you define non-associative 978if you define non-associative (or non-commutative)
911tag methods for these operators. 979tag methods for these operators.
912 980
913\subsubsection{Table Constructors} \label{tableconstructor} 981\subsubsection{Table Constructors} \label{tableconstructor}
@@ -920,14 +988,11 @@ The general syntax for constructors is
920\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} 988\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
921\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist 989\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist
922 \Or ffieldlist \ter{;} lfieldlist} 990 \Or ffieldlist \ter{;} lfieldlist}
923\produc{lfieldlist}{\opt{lfieldlist1}} 991\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}}
924\produc{ffieldlist}{\opt{ffieldlist1}} 992\produc{ffieldlist}{\opt{ffieldlist1}}
925\end{Produc}% 993\end{Produc}%
926 994
927The form \emph{lfieldlist1} is used to initialize lists: 995The form \emph{explist1} is used to initialize lists.
928\begin{Produc}
929\produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}}
930\end{Produc}%
931The expressions in the list are assigned to consecutive numerical indices, 996The expressions in the list are assigned to consecutive numerical indices,
932starting with~1. 997starting with~1.
933For example, 998For example,
@@ -944,6 +1009,8 @@ is equivalent to
944 a = temp 1009 a = temp
945 end 1010 end
946\end{verbatim} 1011\end{verbatim}
1012If the last expression in the list is a function call,
1013all values returned by the call enter the list \see{functioncall}.
947 1014
948The form \emph{ffieldlist1} initializes other fields in a table: 1015The form \emph{ffieldlist1} initializes other fields in a table:
949\begin{Produc} 1016\begin{Produc}
@@ -982,20 +1049,20 @@ For example, all forms below are correct.
982\subsubsection{Function Calls} \label{functioncall} 1049\subsubsection{Function Calls} \label{functioncall}
983A \Index{function call} in Lua has the following syntax: 1050A \Index{function call} in Lua has the following syntax:
984\begin{Produc} 1051\begin{Produc}
985\produc{functioncall}{varorfunc args} 1052\produc{functioncall}{exp args}
986\end{Produc}% 1053\end{Produc}%
987First, \M{varorfunc} is evaluated. 1054First, \M{exp} and \M{args} are evaluated.
988If its value has type \emph{function}, 1055If the value of \M{exp} has type \emph{function},
989then this function is called, 1056then this function is called,
990with the given arguments. 1057with the given arguments.
991Otherwise, the ``function'' tag method is called, 1058Otherwise, the ``function'' tag method is called,
992having as first parameter the value of \M{varorfunc}, 1059having as first parameter the value of \M{exp},
993and then the original call arguments 1060followed by the original call arguments
994\see{tag-method}. 1061\see{tag-method}.
995 1062
996The form 1063The form
997\begin{Produc} 1064\begin{Produc}
998\produc{functioncall}{varorfunc \ter{:} name args} 1065\produc{functioncall}{exp \ter{:} name args}
999\end{Produc}% 1066\end{Produc}%
1000can be used to call ``methods''. 1067can be used to call ``methods''.
1001A call \verb|v:name(...)| 1068A call \verb|v:name(...)|
@@ -1005,9 +1072,9 @@ except that \verb|v| is evaluated only once.
1005Arguments have the following syntax: 1072Arguments have the following syntax:
1006\begin{Produc} 1073\begin{Produc}
1007\produc{args}{\ter{(} \opt{explist1} \ter{)}} 1074\produc{args}{\ter{(} \opt{explist1} \ter{)}}
1075\produc{explist1}{\rep{exp \ter{,}} exp}
1008\produc{args}{tableconstructor} 1076\produc{args}{tableconstructor}
1009\produc{args}{literal} 1077\produc{args}{literal}
1010\produc{explist1}{\rep{exp1 \ter{,}} exp}
1011\end{Produc}% 1078\end{Produc}%
1012All argument expressions are evaluated before the call. 1079All argument expressions are evaluated before the call.
1013A call of the form \verb|f{...}| is syntactic sugar for 1080A call of the form \verb|f{...}| is syntactic sugar for
@@ -1020,20 +1087,16 @@ the argument list is a single literal string.
1020 1087
1021Because a function can return any number of results 1088Because a function can return any number of results
1022\see{return}, 1089\see{return},
1023the number of results must be adjusted before they are used \see{adjust}. 1090the number of results must be adjusted before they are used.
1024If the function is called as a statement \see{funcstat}, 1091If the function is called as a statement \see{funcstat},
1025then its return list is adjusted to~0, 1092then its return list is adjusted to~0,
1026thus discarding all returned values. 1093thus discarding all returned values.
1027If the function is called in a place that needs a single value 1094If the function is called inside another expression,
1028(syntactically denoted by the non-terminal \M{exp1}), 1095or in the middle of a list of expressions,
1029then its return list is adjusted to~1, 1096then its return list is adjusted to~1,
1030thus discarding all returned values but the first one. 1097thus discarding all returned values but the first one.
1031If the function is called in a place that can hold many values 1098If the function is called as the last element of a list of expressions,
1032(syntactically denoted by the non-terminal \M{exp}),
1033then no adjustment is made. 1099then no adjustment is made.
1034The only places that can hold many values
1035is the last (or the only) expression in an assignment,
1036in an argument list, or in the \rwd{return} statement.
1037Here are some examples: 1100Here are some examples:
1038\begin{verbatim} 1101\begin{verbatim}
1039 f() -- adjusted to 0 results 1102 f() -- adjusted to 0 results
@@ -1043,7 +1106,16 @@ Here are some examples:
1043 a,b,c = x, f() -- f() is adjusted to 2 1106 a,b,c = x, f() -- f() is adjusted to 2
1044 a,b,c = f() -- f() is adjusted to 3 1107 a,b,c = f() -- f() is adjusted to 3
1045 return f() -- returns all values returned by f() 1108 return f() -- returns all values returned by f()
1046 return x,y,f() -- returns a, b, and all values returned by f() 1109 return x,y,f() -- returns x, y, and all values returned by f()
1110 {f()} -- creates a list with all values returned by f()
1111 {f(), nil} -- f() is adjusted to 1 result
1112\end{verbatim}
1113
1114If you embrace a function call in parentheses,
1115then it is adjusted to return exactly one value:
1116\begin{verbatim}
1117 return x, y, (f()) -- returns x, y, and one value from f()
1118 {(f())} -- create a table with exactly one element
1047\end{verbatim} 1119\end{verbatim}
1048 1120
1049\subsubsection{\Index{Function Definitions}} \label{func-def} 1121\subsubsection{\Index{Function Definitions}} \label{func-def}
@@ -1054,7 +1126,7 @@ The syntax for function definition is
1054 block \rwd{end}} 1126 block \rwd{end}}
1055\produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} 1127\produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)}
1056 block \rwd{end}} 1128 block \rwd{end}}
1057\produc{funcname}{name \Or name \ter{.} name \Or name \ter{:} name} 1129\produc{funcname}{name \rep{\ter{.} name} \opt{\ter{:} name}}
1058\end{Produc}% 1130\end{Produc}%
1059The statement 1131The statement
1060\begin{verbatim} 1132\begin{verbatim}
@@ -1066,11 +1138,11 @@ is just syntactic sugar for
1066\end{verbatim} 1138\end{verbatim}
1067and the statement 1139and the statement
1068\begin{verbatim} 1140\begin{verbatim}
1069 function v.f () ... end 1141 function v.c.f () ... end
1070\end{verbatim} 1142\end{verbatim}
1071is syntactic sugar for 1143is syntactic sugar for
1072\begin{verbatim} 1144\begin{verbatim}
1073 v.f = function () ... end 1145 v.c.f = function () ... end
1074\end{verbatim} 1146\end{verbatim}
1075 1147
1076A function definition is an executable expression, 1148A function definition is an executable expression,
@@ -1094,7 +1166,7 @@ initialized with the argument values:
1094\label{vararg}% 1166\label{vararg}%
1095When a function is called, 1167When a function is called,
1096the list of \Index{arguments} is adjusted to 1168the list of \Index{arguments} is adjusted to
1097the length of the list of parameters \see{adjust}, 1169the length of the list of parameters,
1098unless the function is a \Def{vararg function}, 1170unless the function is a \Def{vararg function},
1099which is 1171which is
1100indicated by three dots (`\verb|...|') at the end of its parameter list. 1172indicated by three dots (`\verb|...|') at the end of its parameter list.
@@ -1132,20 +1204,17 @@ If control reaches the end of a function
1132without encountering a \rwd{return} statement, 1204without encountering a \rwd{return} statement,
1133then the function returns with no results. 1205then the function returns with no results.
1134 1206
1135The syntax 1207The \emph{colon} syntax
1136\begin{Produc}
1137\produc{funcname}{name \ter{:} name}
1138\end{Produc}%
1139is used for defining \IndexEmph{methods}, 1208is used for defining \IndexEmph{methods},
1140that is, functions that have an implicit extra parameter \IndexVerb{self}. 1209that is, functions that have an implicit extra parameter \IndexVerb{self}.
1141 1210
1142The statement 1211The statement
1143\begin{verbatim} 1212\begin{verbatim}
1144 function v:f (...) ... end 1213 function v.c:f (...) ... end
1145\end{verbatim} 1214\end{verbatim}
1146is just syntactic sugar for 1215is just syntactic sugar for
1147\begin{verbatim} 1216\begin{verbatim}
1148 v.f = function (self, ...) ... end 1217 v.c.f = function (self, ...) ... end
1149\end{verbatim} 1218\end{verbatim}
1150Note that the function gets an extra formal parameter called \verb|self|. 1219Note that the function gets an extra formal parameter called \verb|self|.
1151 1220
@@ -1192,7 +1261,7 @@ Here are some examples:
1192 local y -- a and y are local to g 1261 local y -- a and y are local to g
1193 p = a -- OK, access local `a' 1262 p = a -- OK, access local `a'
1194 p = c -- OK, access global `c' 1263 p = c -- OK, access global `c'
1195 p = b -- ERROR: cannot access a variable in outer scope 1264 p = b -- ERROR: cannot access a variable in outer function
1196 p = %b -- OK, access frozen value of `b' (local to `f') 1265 p = %b -- OK, access frozen value of `b' (local to `f')
1197 %b = 3 -- ERROR: cannot change an upvalue 1266 %b = 3 -- ERROR: cannot change an upvalue
1198 %b.x = 3 -- OK, change the table contents 1267 %b.x = 3 -- OK, change the table contents
@@ -1245,34 +1314,33 @@ Lua code can ``catch'' an error using the function
1245 1314
1246\subsection{Tag Methods} \label{tag-method}\index{tag method} 1315\subsection{Tag Methods} \label{tag-method}\index{tag method}
1247 1316
1248Lua provides a powerful mechanism to extend its semantics,
1249called \emph{tag methods}.
1250A tag method is a programmer-defined function 1317A tag method is a programmer-defined function
1251that is called at specific key points during the execution of a Lua program, 1318that defines how Lua operations act over user-defined types
1252allowing the programmer to change the standard Lua behavior at these points. 1319(and, sometimes, over basic types as well).
1253Each of these points is called an \Def{event}. 1320An \Def{event} is any operation that may invoke a tag method.
1254 1321
1255The tag method called for any specific event is selected 1322Lua selects the tag method called for any specific event
1256according to the tag of the values involved 1323according to the types of the values involved
1257in the event \see{TypesSec}. 1324in the event \see{TypesSec}.
1258The function \IndexLIB{settagmethod} changes the tag method 1325The function \IndexLIB{settagmethod} changes the tag method
1259associated with a given pair \M{(tag, event)}. 1326associated with a given pair \M{(type, event)}.
1260Its first parameter is the tag, the second parameter is the event name 1327Its first parameter is the type (its name or its tag),
1261(a string; see below), 1328the second parameter is the event name (a string; see below),
1262and the third parameter is the new method (a function), 1329and the third parameter is the new method (a function),
1263or \nil\ to restore the default behavior for the pair. 1330or \nil\ to restore the default behavior for the pair.
1264The \verb|settagmethod| function returns the previous tag method for that pair.
1265A companion function \IndexLIB{gettagmethod} 1331A companion function \IndexLIB{gettagmethod}
1266receives a tag and an event name and returns the 1332receives a type and an event name and returns the
1267current method associated with the pair. 1333current method associated with the pair.
1268 1334
1269Tag methods are called in the following events, 1335Tag methods are called in the following events,
1270identified by the given names. 1336identified by the given names.
1271The semantics of tag methods is better explained by a Lua function 1337The semantics of tag methods is better explained by a Lua function
1272describing the behavior of the interpreter at each event. 1338describing the behavior of the interpreter at each event.
1273This function not only shows when a tag method is called, 1339Each event-handler function shows how a tag method is called,
1274but also its arguments, its results, and the default behavior. 1340its arguments (that is, its signature),
1275The code shown here is only \emph{illustrative}; 1341its results,
1342and the default behavior in the absence of a tag method.
1343The code shown here in Lua is only illustrative;
1276the real behavior is hard coded in the interpreter, 1344the real behavior is hard coded in the interpreter,
1277and it is much more efficient than this simulation. 1345and it is much more efficient than this simulation.
1278All functions used in these descriptions 1346All functions used in these descriptions
@@ -1287,7 +1355,7 @@ called when a \verb|+| operation is applied to non-numerical operands.
1287The function \verb|getbinmethod| below defines how Lua chooses a tag method 1355The function \verb|getbinmethod| below defines how Lua chooses a tag method
1288for a binary operation. 1356for a binary operation.
1289First, Lua tries the first operand. 1357First, Lua tries the first operand.
1290If its tag does not define a tag method for the operation, 1358If its type does not define a tag method for the operation,
1291then Lua tries the second operand. 1359then Lua tries the second operand.
1292If it also fails, then it gets a tag method from tag~0. 1360If it also fails, then it gets a tag method from tag~0.
1293\begin{verbatim} 1361\begin{verbatim}
@@ -1307,9 +1375,8 @@ the tag method for the ``add'' event is
1307 else -- at least one of the operands is not numeric 1375 else -- at least one of the operands is not numeric
1308 local tm = getbinmethod(op1, op2, "add") 1376 local tm = getbinmethod(op1, op2, "add")
1309 if tm then 1377 if tm then
1310 -- call the method with both operands and an extra 1378 -- call the method with both operands
1311 -- argument with the event name 1379 return tm(op1, op2)
1312 return tm(op1, op2, "add")
1313 else -- no tag method available: default behavior 1380 else -- no tag method available: default behavior
1314 error("unexpected type at arithmetic operation") 1381 error("unexpected type at arithmetic operation")
1315 end 1382 end
@@ -1336,9 +1403,8 @@ even for numerical operands.
1336 function pow_event (op1, op2) 1403 function pow_event (op1, op2)
1337 local tm = getbinmethod(op1, op2, "pow") 1404 local tm = getbinmethod(op1, op2, "pow")
1338 if tm then 1405 if tm then
1339 -- call the method with both operands and an extra 1406 -- call the method with both operands
1340 -- argument with the event name 1407 return tm(op1, op2)
1341 return tm(op1, op2, "pow")
1342 else -- no tag method available: default behavior 1408 else -- no tag method available: default behavior
1343 error("unexpected type at arithmetic operation") 1409 error("unexpected type at arithmetic operation")
1344 end 1410 end
@@ -1358,9 +1424,8 @@ called when a unary \verb|-| operation is applied to a non-numerical operand.
1358 local tm = gettagmethod(tag(op), "unm") or 1424 local tm = gettagmethod(tag(op), "unm") or
1359 gettagmethod(0, "unm") 1425 gettagmethod(0, "unm")
1360 if tm then 1426 if tm then
1361 -- call the method with the operand, nil, and an extra 1427 -- call the method with the operand and nil
1362 -- argument with the event name 1428 return tm(op, nil)
1363 return tm(op, nil, "unm")
1364 else -- no tag method available: default behavior 1429 else -- no tag method available: default behavior
1365 error("unexpected type at arithmetic operation") 1430 error("unexpected type at arithmetic operation")
1366 end 1431 end
@@ -1381,15 +1446,15 @@ It corresponds to the \verb|<| operator.
1381 else 1446 else
1382 local tm = getbinmethod(op1, op2, "lt") 1447 local tm = getbinmethod(op1, op2, "lt")
1383 if tm then 1448 if tm then
1384 return tm(op1, op2, "lt") 1449 return tm(op1, op2)
1385 else 1450 else
1386 error("unexpected type at comparison"); 1451 error("unexpected type at comparison");
1387 end 1452 end
1388 end 1453 end
1389 end 1454 end
1390\end{verbatim} 1455\end{verbatim}
1391The other order operators use this tag method according to the 1456The other order operators use the \verb|"lt"| tag method
1392usual equivalences: 1457according to the usual equivalences:
1393\begin{verbatim} 1458\begin{verbatim}
1394 a>b <=> b<a 1459 a>b <=> b<a
1395 a<=b <=> not (b<a) 1460 a<=b <=> not (b<a)
@@ -1406,7 +1471,7 @@ called when a concatenation is applied to non-string operands.
1406 else 1471 else
1407 local tm = getbinmethod(op1, op2, "concat") 1472 local tm = getbinmethod(op1, op2, "concat")
1408 if tm then 1473 if tm then
1409 return tm(op1, op2, "concat") 1474 return tm(op1, op2)
1410 else 1475 else
1411 error("unexpected type for concatenation") 1476 error("unexpected type for concatenation")
1412 end 1477 end
@@ -1421,8 +1486,7 @@ See the ``gettable'' event for its semantics.
1421 1486
1422\item[``getglobal'':]\IndexTM{getglobal} 1487\item[``getglobal'':]\IndexTM{getglobal}
1423called whenever Lua needs the value of a global variable. 1488called whenever Lua needs the value of a global variable.
1424This method can only be set for \nil\ and for tags 1489This method can only be set for \nil\ and for user-defined types.
1425created by \verb|newtag|.
1426Note that 1490Note that
1427the tag is that of the \emph{current value} of the global variable. 1491the tag is that of the \emph{current value} of the global variable.
1428\begin{verbatim} 1492\begin{verbatim}
@@ -1438,6 +1502,12 @@ the tag is that of the \emph{current value} of the global variable.
1438 end 1502 end
1439\end{verbatim} 1503\end{verbatim}
1440The function \verb|getglobal| is defined in the basic library~\see{predefined}. 1504The function \verb|getglobal| is defined in the basic library~\see{predefined}.
1505\NOTE
1506\verb|getglobal| is ``overloaded'' here.
1507It is the name both of the event and
1508of the function that handles the event
1509to call an eventual tag method
1510(called \verb|tm| in the above code).
1441 1511
1442\item[``setglobal'':]\IndexTM{setglobal} 1512\item[``setglobal'':]\IndexTM{setglobal}
1443called whenever Lua assigns to a global variable. 1513called whenever Lua assigns to a global variable.
@@ -1455,6 +1525,8 @@ userdata with the default tag.
1455 end 1525 end
1456\end{verbatim} 1526\end{verbatim}
1457The function \verb|setglobal| is defined in the basic library~\see{predefined}. 1527The function \verb|setglobal| is defined in the basic library~\see{predefined}.
1528\NOTE
1529See previous note.
1458 1530
1459\item[``gettable'':]\IndexTM{gettable} 1531\item[``gettable'':]\IndexTM{gettable}
1460called whenever Lua accesses an indexed variable. 1532called whenever Lua accesses an indexed variable.
@@ -1531,9 +1603,10 @@ Lua does the equivalent of the following function:
1531 end 1603 end
1532\end{verbatim} 1604\end{verbatim}
1533In a garbage-collection cycle, 1605In a garbage-collection cycle,
1534the tag methods for userdata are called in \emph{reverse} order of tag creation, 1606the tag methods for userdata are called in \emph{reverse}
1607order of type creation,
1535that is, the first tag methods to be called are those associated 1608that is, the first tag methods to be called are those associated
1536with the last tag created in the program. 1609with the last type created in the program.
1537Moreover, at the end of the cycle, 1610Moreover, at the end of the cycle,
1538Lua does the equivalent of the call \verb|gc_event(nil)|. 1611Lua does the equivalent of the call \verb|gc_event(nil)|.
1539 1612
@@ -1553,7 +1626,8 @@ are declared in the header file \verb|lua.h|.
1553\NOTE 1626\NOTE
1554Even when we use the term ``function'', 1627Even when we use the term ``function'',
1555any facility in the API may be provided as a \emph{macro} instead. 1628any facility in the API may be provided as a \emph{macro} instead.
1556All such macros use each of its arguments exactly once, 1629All such macros use each of its arguments exactly once
1630(except for the first argument, which is always a state),
1557and so do not generate hidden side-effects. 1631and so do not generate hidden side-effects.
1558 1632
1559 1633
@@ -1604,6 +1678,31 @@ With the exception of \verb|lua_open|,
1604all functions in the Lua API need a state as their first argument. 1678all functions in the Lua API need a state as their first argument.
1605 1679
1606 1680
1681\subsection{Threads}
1682
1683Lua offers a partial support for multiple threads.
1684If you have a C library that offers multi-threading or co-routines,
1685Lua can cooperate with it to implement the equivalent facility in Lua.
1686The following function creates a new ``thread'' in Lua:
1687\begin{verbatim}
1688 lua_State *lua_newthread (lua_State *L, int stacksize);
1689\end{verbatim}
1690\DefAPI{lua_newthread}
1691The new state returned by this function shares with the original state
1692all global environment (such as tables, tag methods, etc.),
1693but has an independent stack.
1694(The use of these multiple stacks must be ``syncronized'' with C.
1695How to explain that? TO BE WRITTEN.)
1696
1697Each thread has an independent table for global variables.
1698When you create a thread this table is the same as of the given state,
1699but you can change each one independently.
1700
1701You destroy threads with \verb|lua_close|.
1702When you destroy the last thread of a global state,
1703the state itself is also destroyed.
1704
1705
1607\subsection{The Stack and Indices} 1706\subsection{The Stack and Indices}
1608 1707
1609Lua uses a \emph{stack} to pass values to and from C. 1708Lua uses a \emph{stack} to pass values to and from C.
@@ -1650,7 +1749,7 @@ Whenever Lua calls C, \DefAPI{LUA_MINSTACK}
1650it ensures that 1749it ensures that
1651at least \verb|LUA_MINSTACK| positions are still available. 1750at least \verb|LUA_MINSTACK| positions are still available.
1652\verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16, 1751\verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16,
1653and so you have to worry about stack space only 1752so that usually you have to worry about stack space only
1654when your code has loops pushing elements onto the stack. 1753when your code has loops pushing elements onto the stack.
1655 1754
1656Most query functions accept as indices any value inside the 1755Most query functions accept as indices any value inside the
@@ -1714,8 +1813,9 @@ then
1714To check the type of a stack element, 1813To check the type of a stack element,
1715the following functions are available: 1814the following functions are available:
1716\begin{verbatim} 1815\begin{verbatim}
1717 int lua_type (lua_State *L, int index);
1718 int lua_tag (lua_State *L, int index); 1816 int lua_tag (lua_State *L, int index);
1817 int lua_rawtag (lua_State *L, int index);
1818 const char *lua_type (lua_State *L, int index);
1719 int lua_isnil (lua_State *L, int index); 1819 int lua_isnil (lua_State *L, int index);
1720 int lua_isnumber (lua_State *L, int index); 1820 int lua_isnumber (lua_State *L, int index);
1721 int lua_isstring (lua_State *L, int index); 1821 int lua_isstring (lua_State *L, int index);
@@ -1729,34 +1829,21 @@ the following functions are available:
1729\DefAPI{lua_istable} 1829\DefAPI{lua_istable}
1730\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata} 1830\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata}
1731These functions can be called with any acceptable index. 1831These functions can be called with any acceptable index.
1732The \verb|lua_isnumber| function may have a side effect of changing the
1733actual value in the stack from a string to a number.
1734 1832
1735\verb|lua_type| returns one of the following constants, 1833\verb|lua_tag| returns the tag of a value in the stack,
1736according to the type of the given object: 1834or \verb|LUA_TNONE| for a non-valid index
1835(that is, if that stack position is ``empty'').
1836The tags for the basic types are the following constants:
1737\verb|LUA_TNIL|, 1837\verb|LUA_TNIL|,
1738\verb|LUA_TNUMBER|, 1838\verb|LUA_TNUMBER|,
1739\verb|LUA_TSTRING|, 1839\verb|LUA_TSTRING|,
1740\verb|LUA_TTABLE|, 1840\verb|LUA_TTABLE|,
1741\verb|LUA_TFUNCTION|, 1841\verb|LUA_TFUNCTION|,
1742\verb|LUA_TUSERDATA|. 1842\verb|LUA_TUSERDATA|.
1743If the index is non-valid 1843\verb|lua_rawtag| is similar to \verb|lua_tag|,
1744(that is, if that stack position is ``empty''), 1844but it returns the tag of the basic (raw) type of a value.
1745then \verb|lua_type| returns \verb|LUA_TNONE|. 1845\verb|lua_type| is similar to \verb|lua_tag|,
1746These constants can be converted to strings with 1846but it returns the type name of the given value.
1747\begin{verbatim}
1748 const char *lua_typename (lua_State *L, int t);
1749\end{verbatim}
1750\DefAPI{lua_typename}
1751where \verb|t| is a type returned by \verb|lua_type|.
1752The strings returned by \verb|lua_typename| are
1753\verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|,
1754\verb|"function"|, \verb|"userdata"|, and \verb|"no value"|,
1755
1756\verb|lua_tag| returns the tag of a value,
1757or \verb|LUA_NOTAG| for a non-valid index.
1758The default tag value for all types is equal to the value
1759returned by \verb|lua_type|.
1760 1847
1761The \verb|lua_is*| functions return~1 if the object is compatible 1848The \verb|lua_is*| functions return~1 if the object is compatible
1762with the given type, and 0 otherwise. 1849with the given type, and 0 otherwise.
@@ -1767,7 +1854,7 @@ and \verb|lua_isfunction| accepts both Lua functions and C~functions.
1767To distinguish between Lua functions and C~functions, 1854To distinguish between Lua functions and C~functions,
1768you should use \verb|lua_iscfunction|. 1855you should use \verb|lua_iscfunction|.
1769To distinguish between numbers and numerical strings, 1856To distinguish between numbers and numerical strings,
1770you can use \verb|lua_type|. 1857you can use \verb|lua_rawtag| (or \verb|lua_tag|).
1771 1858
1772The API also has functions to compare two values in the stack: 1859The API also has functions to compare two values in the stack:
1773\begin{verbatim} 1860\begin{verbatim}
@@ -1799,9 +1886,6 @@ they act as if the given value had an incorrect type.
1799to a floating-point number. 1886to a floating-point number.
1800This value must be a number or a string convertible to number 1887This value must be a number or a string convertible to number
1801\see{coercion}; otherwise, \verb|lua_tonumber| returns~0. 1888\see{coercion}; otherwise, \verb|lua_tonumber| returns~0.
1802If the value is a string,
1803\verb|lua_tonumber| also changes the
1804actual value in the stack to a number.
1805 1889
1806\verb|lua_tostring| converts a Lua value to a string 1890\verb|lua_tostring| converts a Lua value to a string
1807(\verb|const char*|). 1891(\verb|const char*|).
@@ -1811,11 +1895,12 @@ If the value is a number,
1811\verb|lua_tostring| also changes the 1895\verb|lua_tostring| also changes the
1812actual value in the stack to a string. 1896actual value in the stack to a string.
1813This function returns a pointer to a string inside the Lua environment. 1897This function returns a pointer to a string inside the Lua environment.
1814Those strings always have a zero (\verb|'\0'|) 1898This pointer is always fully aligned.
1899The strings always have a zero (\verb|'\0'|)
1815after their last character (as in C), 1900after their last character (as in C),
1816but may contain other zeros in their body. 1901but may contain other zeros in their body.
1817If you do not know whether a string may contain zeros, 1902If you do not know whether a string may contain zeros,
1818you should use \verb|lua_strlen| to get its actual length. 1903you can use \verb|lua_strlen| to get its actual length.
1819Because Lua has garbage collection, 1904Because Lua has garbage collection,
1820there is no guarantee that the pointer returned by \verb|lua_tostring| 1905there is no guarantee that the pointer returned by \verb|lua_tostring|
1821will be valid after the respective value is removed from the stack. 1906will be valid after the respective value is removed from the stack.
@@ -1839,13 +1924,12 @@ push C~values onto the stack:
1839 void lua_pushnumber (lua_State *L, double n); 1924 void lua_pushnumber (lua_State *L, double n);
1840 void lua_pushlstring (lua_State *L, const char *s, size_t len); 1925 void lua_pushlstring (lua_State *L, const char *s, size_t len);
1841 void lua_pushstring (lua_State *L, const char *s); 1926 void lua_pushstring (lua_State *L, const char *s);
1842 void lua_pushusertag (lua_State *L, void *u, int tag);
1843 void lua_pushnil (lua_State *L); 1927 void lua_pushnil (lua_State *L);
1844 void lua_pushcfunction (lua_State *L, lua_CFunction f); 1928 void lua_pushcfunction (lua_State *L, lua_CFunction f);
1845\end{verbatim} 1929\end{verbatim}
1846\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring} 1930\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring}
1847\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag} 1931\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag}
1848\DefAPI{lua_pushnil}\DefAPI{lua_pushuserdata}\label{pushing} 1932\DefAPI{lua_pushnil}\label{pushing}
1849These functions receive a C~value, 1933These functions receive a C~value,
1850convert it to a corresponding Lua value, 1934convert it to a corresponding Lua value,
1851and push the result onto the stack. 1935and push the result onto the stack.
@@ -1857,18 +1941,9 @@ otherwise you should use the more general \verb|lua_pushlstring|,
1857which accepts an explicit size. 1941which accepts an explicit size.
1858 1942
1859 1943
1860\subsection{Garbage Collection}\label{GC} 1944\subsection{Garbage Collection API}\label{GC-API}
1861
1862Lua uses two numbers to control its garbage collection.
1863One number counts how many bytes of dynamic memory Lua is using,
1864and the other is a threshold.
1865When the number of bytes crosses the threshold,
1866Lua runs a garbage-collection cycle,
1867which reclaims the memory of all ``dead'' objects
1868(that is, objects no longer accessible from Lua).
1869The byte counter is corrected,
1870and then the threshold is reset to twice the value of the byte counter.
1871 1945
1946Lua uses two numbers to control its garbage collection \see{GC}.
1872You can access the current values of these two numbers through the 1947You can access the current values of these two numbers through the
1873following functions: 1948following functions:
1874\begin{verbatim} 1949\begin{verbatim}
@@ -1896,35 +1971,62 @@ to set your own threshold
1896(the tag method is called after Lua resets the threshold). 1971(the tag method is called after Lua resets the threshold).
1897 1972
1898 1973
1899\subsection{Userdata and Tags}\label{C-tags} 1974\subsection{Userdata}
1975
1976You can create new userdata with the following functions:
1977\begin{verbatim}
1978 void *lua_newuserdata (lua_State *L, size_t size);
1979 void lua_newuserdatabox (lua_State *L, void *u);
1980\end{verbatim}
1981\DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox}
1982The first function, \verb|lua_newuserdata|,
1983allocates a new block of memory with the given size,
1984pushes on the stack a new userdata with the block address,
1985and returns this address.
1986The second function, \verb|lua_newuserdatabox|,
1987gets a pointer and pushes on the stack a new userdata
1988with that pointer.
1989In this case, Lua does not care about the pointer's value.
1990By default, all userdata are created with a standard tag,
1991\verb|LUA_TUSERDATA|.
1992
1993When Lua collects a userdata created by \verb|lua_newuserdata|,
1994it automatically frees its corresponding memory.
1995On the other hand, Lua never uses pointers in
1996userdata created with \verb|lua_newuserdatabox|;
1997it is up to you to free any associated memory,
1998setting a garbage-collection tag method, for instance.
1999
1900 2000
1901Because userdata are objects, 2001\subsection{Types and Tags}
1902the function \verb|lua_pushusertag| may create a new userdata.
1903If Lua has a userdata with the given value (\verb|void*|) and tag,
1904then that userdata is pushed.
1905Otherwise, a new userdata is created, with the given value and tag.
1906If this function is called with
1907\verb|tag| equal to \verb|LUA_ANYTAG|\DefAPI{LUA_ANYTAG},
1908then Lua will try to find any userdata with the given value,
1909regardless of its tag.
1910If there is no userdata with that value, then a new one is created,
1911with tag equal to 0.
1912 2002
1913Userdata can have different tags, 2003User-defined types are created with the function
1914whose semantics are only known to the host program.
1915Tags are created with the function
1916\begin{verbatim} 2004\begin{verbatim}
1917 int lua_newtag (lua_State *L); 2005 int lua_newtype (lua_State *L, const char *name, int basictype);
1918\end{verbatim} 2006\end{verbatim}
1919\DefAPI{lua_newtag} 2007\DefAPI{lua_newtype}
1920The function \verb|lua_settag| changes the tag of 2008\verb|name| is the name of the new type,
2009and \verb|basictype| is the basic type for objects with this new type,
2010which can be \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|.
2011
2012The function \verb|lua_settag| changes the tag (i.e., the type) of
1921the object on top of the stack (without popping it): 2013the object on top of the stack (without popping it):
1922\begin{verbatim} 2014\begin{verbatim}
1923 void lua_settag (lua_State *L, int tag); 2015 void lua_settag (lua_State *L, int tag);
1924\end{verbatim} 2016\end{verbatim}
1925\DefAPI{lua_settag} 2017\DefAPI{lua_settag}
1926The object must be a userdata or a table; 2018The given \verb|tag| must be a user-defined tag,
1927the given \verb|tag| must be a value created with \verb|lua_newtag|. 2019and the basic type of the object must be the basic type for that
2020tag (userdata or table).
2021
2022The following functions allow you to translate a tag to a type name
2023and a type name to a tag:
2024\begin{verbatim}
2025 int lua_name2tag (lua_State *L, const char *name);
2026 const char *lua_tag2name (lua_State *L, int tag);
2027\end{verbatim}
2028\DefAPI{lua_name2tag}\DefAPI{lua_tag2name}
2029
1928 2030
1929\subsection{Executing Lua Code}\label{luado} 2031\subsection{Executing Lua Code}\label{luado}
1930A host program can execute Lua chunks written in a file or in a string 2032A host program can execute Lua chunks written in a file or in a string
@@ -2144,7 +2246,7 @@ In both functions,
2144\verb|nargs| is the number of arguments that you pushed onto the stack. 2246\verb|nargs| is the number of arguments that you pushed onto the stack.
2145All arguments and the function value are popped from the stack, 2247All arguments and the function value are popped from the stack,
2146and the function results are pushed. 2248and the function results are pushed.
2147The number of results are adjusted \see{adjust} to \verb|nresults|, 2249The number of results are adjusted to \verb|nresults|,
2148unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. 2250unless \verb|nresults| is \IndexAPI{LUA_MULTRET}.
2149In that case, \emph{all} results from the function are pushed. 2251In that case, \emph{all} results from the function are pushed.
2150The function results are pushed in direct order 2252The function results are pushed in direct order
@@ -2392,6 +2494,27 @@ Any C~library can store data into this table,
2392as long as it chooses a key different from other libraries. 2494as long as it chooses a key different from other libraries.
2393 2495
2394 2496
2497
2498\subsection{Weak Tables}
2499
2500The following constants and functions control the weak mode of a table:
2501\begin{verbatim}
2502 #define LUA_WEAK_KEY ...
2503 #define LUA_WEAK_VALUE ...
2504\end{verbatim}
2505\begin{verbatim}
2506 void lua_setweakmode (lua_State *L, int mode);
2507 int lua_getweakmode (lua_State *L, int index);
2508\end{verbatim}
2509\DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode}
2510Both functions operate over the table at the top of the stack.
2511Modes are described as bit sets, so that
2512\verb|LUA_WEAK_KEY| means weak keys,
2513\verb|LUA_WEAK_VALUE| means weak values,
2514\verb|LUA_WEAK_KEY | LUA_WEAK_VALUE| means both,
2515and zero means none.
2516
2517
2395\section{Standard Libraries} 2518\section{Standard Libraries}
2396 2519
2397The standard libraries provide useful functions 2520The standard libraries provide useful functions
@@ -2499,22 +2622,25 @@ or as pre-compiled chunks.
2499When called without arguments, 2622When called without arguments,
2500\verb|dofile| executes the contents of the standard input (\verb|stdin|). 2623\verb|dofile| executes the contents of the standard input (\verb|stdin|).
2501If there is any error executing the file, 2624If there is any error executing the file,
2502then \verb|dofile| returns \nil. 2625then \verb|dofile| returns \nil{} plus one of the following strings
2626describing the error:
2627\verb|"file error"|, \verb|"run-time error"|,
2628\verb|"syntax error"|, \verb|"memory error"|, or
2629\verb|"error in error handling"|.
2503Otherwise, it returns the values returned by the chunk, 2630Otherwise, it returns the values returned by the chunk,
2504or a non-\nil\ value if the chunk returns no values. 2631or a non-\nil\ value if the chunk returns no values.
2505It issues an error when called with a non-string argument. 2632It issues an error when called with a non-string argument.
2506%\verb|dofile| is equivalent to the API function \verb|lua_dofile|.
2507 2633
2508\subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring} 2634\subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring}
2509Executes a given string as a Lua chunk. 2635Executes a given string as a Lua chunk.
2510If there is any error executing the string, 2636If there is any error executing the string,
2511then \verb|dostring| returns \nil. 2637then \verb|dostring| returns \nil plus a string describing
2638the error (see \verb|dofile|).
2512Otherwise, it returns the values returned by the chunk, 2639Otherwise, it returns the values returned by the chunk,
2513or a non-\nil\ value if the chunk returns no values. 2640or a non-\nil\ value if the chunk returns no values.
2514The optional parameter \verb|chunkname| 2641The optional parameter \verb|chunkname|
2515is the ``name of the chunk'', 2642is the ``name of the chunk'',
2516used in error messages and debug information. 2643used in error messages and debug information.
2517%\verb|dostring| is equivalent to the API function \verb|lua_dostring|.
2518 2644
2519\subsubsection*{\ff \T{error (message)}}\DefLIB{error}\label{pdf-error} 2645\subsubsection*{\ff \T{error (message)}}\DefLIB{error}\label{pdf-error}
2520Calls the error handler \see{error} and then terminates 2646Calls the error handler \see{error} and then terminates
@@ -2554,7 +2680,7 @@ For each index, the function is called with the index and
2554respective value as arguments. 2680respective value as arguments.
2555Indices are visited in sequential order, 2681Indices are visited in sequential order,
2556from~1 to \verb|n|, 2682from~1 to \verb|n|,
2557where \verb|n| is the result of \verb|getn(table)| \see{getn}. 2683where \verb|n| is the result of \verb|getn(table)| (see below).
2558If the function returns any non-\nil\ value, 2684If the function returns any non-\nil\ value,
2559then the loop is broken, and this value is returned 2685then the loop is broken, and this value is returned
2560as the final value of \verb|foreachi|. 2686as the final value of \verb|foreachi|.
@@ -2568,6 +2694,10 @@ This function could be defined in Lua:
2568 end 2694 end
2569\end{verbatim} 2695\end{verbatim}
2570 2696
2697\subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo}
2698Returns the number of Kbytes of dynamic memory Lua is using,
2699and (as a second result) the
2700current garbage collector threshold (also in Kbytes).
2571 2701
2572\subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal} 2702\subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal}
2573Gets the value of a global variable, 2703Gets the value of a global variable,
@@ -2606,9 +2736,10 @@ Returns the current table of globals.
2606If the argument \verb|table| is given, 2736If the argument \verb|table| is given,
2607then it also sets this table as the table of globals. 2737then it also sets this table as the table of globals.
2608 2738
2609\subsubsection*{\ff \T{newtag ()}}\DefLIB{newtag}\label{pdf-newtag} 2739\subsubsection*{\ff \T{newtype (name)}}\DefLIB{newtype}\label{pdf-newtype}
2610Returns a new tag. 2740Creates a new type with the given name
2611%\verb|newtag| is equivalent to the API function \verb|lua_newtag|. 2741(which can be used only for table objects).
2742Returns the tag of the new type.
2612 2743
2613\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next} 2744\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next}
2614Allows a program to traverse all fields of a table. 2745Allows a program to traverse all fields of a table.
@@ -2658,6 +2789,20 @@ without invoking any tag method.
2658\verb|index| is any value different from \nil, 2789\verb|index| is any value different from \nil,
2659and \verb|value| is any Lua value. 2790and \verb|value| is any Lua value.
2660 2791
2792\subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype}
2793Returns the basic (raw) type of its only argument, coded as a string.
2794The possible results of this function are
2795\verb|"nil"| (a string, not the value \nil),
2796\verb|"number"|,
2797\verb|"string"|,
2798\verb|"table"|,
2799\verb|"function"|,
2800and \verb|"userdata"|.
2801
2802\subsubsection*{\ff \T{require (module)}}\DefLIB{require}
2803
2804TO BE WRITTEN.
2805
2661\subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal} 2806\subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal}
2662Sets the named global variable to the given value, 2807Sets the named global variable to the given value,
2663or calls a tag method for ``setglobal''. 2808or calls a tag method for ``setglobal''.
@@ -2665,10 +2810,9 @@ Its full semantics is explained in \See{tag-method}.
2665The string \verb|name| does not need to be a 2810The string \verb|name| does not need to be a
2666syntactically valid variable name. 2811syntactically valid variable name.
2667 2812
2668\subsubsection*{\ff \T{settag (t, tag)}}\DefLIB{settag} 2813\subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype}
2669Sets the tag of a given table \see{TypesSec}. 2814Sets the type of a given table \see{TypesSec}.
2670\verb|tag| must be a value created with \verb|newtag| 2815\verb|type| must be the name or the tag of a user-defined type.
2671\see{pdf-newtag}.
2672\verb|settag| returns the value of its first argument (the table). 2816\verb|settag| returns the value of its first argument (the table).
2673For the safety of host programs, 2817For the safety of host programs,
2674it is impossible to change the tag of a userdata from Lua. 2818it is impossible to change the tag of a userdata from Lua.
@@ -2724,7 +2868,6 @@ For complete control of how numbers are converted,
2724use function \verb|format|. 2868use function \verb|format|.
2725 2869
2726 2870
2727
2728\subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert} 2871\subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert}
2729 2872
2730Inserts element \verb|value| at table position \verb|pos|, 2873Inserts element \verb|value| at table position \verb|pos|,
@@ -2786,15 +2929,28 @@ except that the table accesses are all \emph{raw}
2786\end{verbatim} 2929\end{verbatim}
2787 2930
2788\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} 2931\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
2789Allows Lua programs to test the type of a value. 2932Returns the type name of its only argument.
2790It receives one argument, and returns its type, coded as a string. 2933
2791The possible results of this function are 2934\subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack}
2792\verb|"nil"| (a string, not the value \nil), 2935Returns all elements from the given list.
2793\verb|"number"|, 2936This function is equivalent to
2794\verb|"string"|, 2937\begin{verbatim}
2795\verb|"table"|, 2938 return list[1], list[2], ..., list[n]
2796\verb|"function"|, 2939\end{verbatim}
2797and \verb|"userdata"|. 2940except that the above code can be valid only for a fixed \M{n}.
2941The number of returned values, \M{n},
2942is the result of \verb|getn(list)| \see{getn},
2943
2944\subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode}
2945
2946Controls the weakness of a table.
2947When \verb|mode| is \verb|"?"|,
2948returns the current mode of the table, as a string;
2949otherwise, sets the weakmode of the table to the given mode (also a string).
2950Valid mode strings are \verb|"k"| for weak keys,
2951\verb|"v"| for weak values,
2952\verb|"kv"| for both,
2953and \verb|""| for none (that is, for ``normal'' tables).
2798 2954
2799 2955
2800\subsection{String Manipulation} 2956\subsection{String Manipulation}
@@ -2913,9 +3069,8 @@ For example, \verb|"%*g"| can be simulated with
2913\verb|"%"..width.."g"|. 3069\verb|"%"..width.."g"|.
2914 3070
2915\NOTE 3071\NOTE
2916Neither the format string nor the string values to be formatted with 3072String values to be formatted with
2917\verb|%s| can contain embedded zeros. 3073\verb|%s| cannot contain embedded zeros.
2918\verb|%q| handles string values with embedded zeros.
2919 3074
2920\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} 3075\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}}
2921\DefLIB{gsub} 3076\DefLIB{gsub}
@@ -2975,7 +3130,7 @@ Here are some examples:
2975a \Def{character class} is used to represent a set of characters. 3130a \Def{character class} is used to represent a set of characters.
2976The following combinations are allowed in describing a character class: 3131The following combinations are allowed in describing a character class:
2977\begin{description} 3132\begin{description}
2978\item[\emph{x}] (where \emph{x} is any magic characters 3133\item[\emph{x}] (where \emph{x} is not one of the magic characters
2979\verb|^$()%.[]*+-?|) 3134\verb|^$()%.[]*+-?|)
2980--- represents the character \emph{x} itself. 3135--- represents the character \emph{x} itself.
2981\item[\T{.}] --- (a dot) represents all characters. 3136\item[\T{.}] --- (a dot) represents all characters.
@@ -3170,7 +3325,7 @@ The \verb|mode| string can be any of the following:
3170\end{description} 3325\end{description}
3171The \verb|mode| string may also have a \verb|b| at the end, 3326The \verb|mode| string may also have a \verb|b| at the end,
3172which is needed in some systems to open the file in binary mode. 3327which is needed in some systems to open the file in binary mode.
3173This string is exactlty what is used in the standard~C function \verb|fopen|. 3328This string is exactly what is used in the standard~C function \verb|fopen|.
3174 3329
3175\subsubsection*{\ff \T{closefile (handle)}}\DefLIB{closefile} 3330\subsubsection*{\ff \T{closefile (handle)}}\DefLIB{closefile}
3176 3331
@@ -3180,7 +3335,7 @@ It does not modify either \verb|_INPUT| or \verb|_OUTPUT|.
3180\subsubsection*{\ff \T{readfrom (filename)}}\DefLIB{readfrom} 3335\subsubsection*{\ff \T{readfrom (filename)}}\DefLIB{readfrom}
3181 3336
3182This function may be called in two ways. 3337This function may be called in two ways.
3183When called with a file name, it opens the named file, 3338When called with a file name, it opens the named file (in text mode),
3184sets its handle as the value of \verb|_INPUT|, 3339sets its handle as the value of \verb|_INPUT|,
3185and returns this value. 3340and returns this value.
3186It does not close the current input file. 3341It does not close the current input file.
@@ -3202,7 +3357,7 @@ usually limited and depends on the system.
3202 3357
3203This function may be called in two ways. 3358This function may be called in two ways.
3204When called with a file name, 3359When called with a file name,
3205it opens the named file, 3360it opens the named file (in text mode),
3206sets its handle as the value of \verb|_OUTPUT|, 3361sets its handle as the value of \verb|_OUTPUT|,
3207and returns this value. 3362and returns this value.
3208It does not close the current output file. 3363It does not close the current output file.
@@ -3225,8 +3380,8 @@ usually limited and depends on the system.
3225 3380
3226\subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto} 3381\subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto}
3227 3382
3228Opens a file named \verb|filename| and sets its handle as the 3383Opens a file named \verb|filename| (in text mode)
3229value of \verb|_OUTPUT|. 3384and sets its handle as the value of \verb|_OUTPUT|.
3230Unlike the \verb|writeto| operation, 3385Unlike the \verb|writeto| operation,
3231this function does not erase any previous contents of the file; 3386this function does not erase any previous contents of the file;
3232instead, anything written to the file is appended to its end. 3387instead, anything written to the file is appended to its end.
@@ -3278,13 +3433,26 @@ beginning of the file (and returns 0);
3278and the call \verb|seek(file, "end")| sets the position to the 3433and the call \verb|seek(file, "end")| sets the position to the
3279end of the file, and returns its size. 3434end of the file, and returns its size.
3280 3435
3436\subsubsection*{\ff \T{tmpfile ()}}\DefLIB{tmpfile}
3437
3438Returns a handle for a temporary file.
3439This file is open in read/write mode,
3440and it is automatically removed when the program ends.
3441
3281\subsubsection*{\ff \T{tmpname ()}}\DefLIB{tmpname} 3442\subsubsection*{\ff \T{tmpname ()}}\DefLIB{tmpname}
3282 3443
3283Returns a string with a file name that can safely 3444Returns a string with a file name that can
3284be used for a temporary file. 3445be used for a temporary file.
3285The file must be explicitly opened before its use 3446The file must be explicitly opened before its use
3286and removed when no longer needed. 3447and removed when no longer needed.
3287 3448
3449This function is equivalent to the \verb|tmpnam| C function,
3450and many people advise against its use,
3451because between the time you call the function
3452and the time you open the file,
3453it is possible for another process
3454to create a file with the same name.
3455
3288\subsubsection*{\ff \T{read ([filehandle,] format1, ...)}}\DefLIB{read} 3456\subsubsection*{\ff \T{read ([filehandle,] format1, ...)}}\DefLIB{read}
3289 3457
3290Reads file \verb|_INPUT|, 3458Reads file \verb|_INPUT|,
@@ -3301,16 +3469,23 @@ The available formats are
3301\begin{description} 3469\begin{description}
3302\item[``*n''] reads a number; 3470\item[``*n''] reads a number;
3303this is the only format that returns a number instead of a string. 3471this is the only format that returns a number instead of a string.
3304\item[``*l''] reads the next line
3305(skipping the end of line), or \nil\ on end of file.
3306This is the default format.
3307\item[``*a''] reads the whole file, starting at the current position. 3472\item[``*a''] reads the whole file, starting at the current position.
3308On end of file, it returns the empty string. 3473On end of file, it returns the empty string.
3309\item[``*w''] reads the next word 3474\item[``*u\emph{string}''] reads until the first occurence of
3310(maximal sequence of non--white-space characters), 3475\emph{string} in the file.
3311skipping spaces if necessary, or \nil\ on end of file. 3476The string itself is read, but it is not included in the result.
3477If it cannot finds the string,
3478reads (and returns) the file until its end,
3479or \nil\ if the file was already on its end.
3480\item[``*l''] equivalent to \verb|"*u\n"|.
3481Reads the next line (skipping the end of line),
3482returning \nil\ on end of file.
3483This is the default format.
3312\item[\emph{number}] reads a string with up to that number of characters, 3484\item[\emph{number}] reads a string with up to that number of characters,
3313or \nil\ on end of file. 3485or \nil\ on end of file.
3486Particularly, if number is zero,
3487reads nothing and returns an empty string,
3488or \nil\ on end of file.
3314\end{description} 3489\end{description}
3315 3490
3316\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\DefLIB{write} 3491\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\DefLIB{write}
@@ -3331,15 +3506,41 @@ plus a string describing the error.
3331Returns an approximation of the amount of CPU time 3506Returns an approximation of the amount of CPU time
3332used by the program, in seconds. 3507used by the program, in seconds.
3333 3508
3334\subsubsection*{\ff \T{date ([format])}}\DefLIB{date} 3509\subsubsection*{\ff \T{date ([format [, time]])}}\DefLIB{date}
3510
3511Returns a string or a table containing date and time,
3512formatted according to the given string \verb|format|.
3513
3514If the \verb|time| argument is present,
3515this is the time to be formatted
3516(see the \verb|time| function for a description of this value).
3517Otherwise, \verb|date| formats the current time.
3518
3519If \verb|format| starts with \verb|!|,
3520the date is formatted in Coordinated Universal Time.
3335 3521
3336Returns a string containing date and time 3522After that optional character,
3337formatted according to the given string \verb|format|, 3523if \verb|format| is \verb|*t|,
3338following the same rules of the ANSI~C function \verb|strftime|. 3524the function returns a table with the following fields:
3525\verb|year|, \verb|month| (1-12), \verb|day| (1-31),
3526\verb|hour| (0-23), \verb|min| (0-59), \verb|sec| (0-59),
3527\verb|wday| (weekday, Sunday is 1),
3528\verb|yday| (day of the year),
3529and \verb|isdst| (daylight saving flag).
3530
3531If format is not \verb|*t|, the function returns the date
3532as a string, formatted according with the
3533same rules of the ANSI~C function \verb|strftime|.
3339When called without arguments, 3534When called without arguments,
3340it returns a reasonable date and time representation that depends on 3535it returns a reasonable date and time representation that depends on
3341the host system and on the current locale. 3536the host system and on the current locale.
3342 3537
3538\subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime}
3539
3540Returns the number of seconds from time \verb|t1| to time \verb|t2|.
3541In Posix, Windows, and some other systems,
3542this value is exactly \Math{t1-t2}.
3543
3343\subsubsection*{\ff \T{execute (command)}}\DefLIB{execute} 3544\subsubsection*{\ff \T{execute (command)}}\DefLIB{execute}
3344 3545
3345This function is equivalent to the C~function \verb|system|. 3546This function is equivalent to the C~function \verb|system|.
@@ -3369,6 +3570,21 @@ the default category is \verb|"all"|.
3369The function returns the name of the new locale, 3570The function returns the name of the new locale,
3370or \nil\ if the request cannot be honored. 3571or \nil\ if the request cannot be honored.
3371 3572
3573\subsubsection*{\ff \T{time ([table])}}\DefLIB{time}
3574
3575Returns the current time (when called without arguments),
3576or a time representing the date/time specified by the given table.
3577This table must have fields \verb|year|, \verb|month|, and \verb|day|,
3578and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst|
3579(for a description of these fields, see the \verb|date| function).
3580
3581The returned value is a number, whose meaning depends on your system.
3582In Posix, Windows, and some other systems, this number counts the number
3583of seconds since some given start time (the ``epoch'').
3584In other systems, the meaning is not specified,
3585and such number can be used only as an argument to
3586functions \verb|date| and \verb|difftime|.
3587
3372 3588
3373\section{The Debug Interface} \label{debugI} 3589\section{The Debug Interface} \label{debugI}
3374 3590
@@ -3597,11 +3813,11 @@ You should exert great care when using this library.
3597The functions provided here should be used exclusively for debugging 3813The functions provided here should be used exclusively for debugging
3598and similar tasks (e.g., profiling). 3814and similar tasks (e.g., profiling).
3599Please resist the temptation to use them as a 3815Please resist the temptation to use them as a
3600usual programming tool. 3816usual programming tool:
3601They are slow and violate some (otherwise) secure aspects of the 3817They can be \emph{very} slow.
3602language (e.g., privacy of local variables). 3818Moreover, \verb|setlocal| and \verb|getlocal|
3603As a general rule, if your program does not need this library, 3819violate the privacy of local variables,
3604do not open it. 3820and therefore can compromise some (otherwise) secure code.
3605 3821
3606 3822
3607\subsubsection*{\ff \T{getinfo (function, [what])}}\DefLIB{getinfo} 3823\subsubsection*{\ff \T{getinfo (function, [what])}}\DefLIB{getinfo}
@@ -3619,6 +3835,8 @@ then \verb|getinfo| returns \nil.
3619The returned table contains all the fields returned by \verb|lua_getinfo|, 3835The returned table contains all the fields returned by \verb|lua_getinfo|,
3620with the string \verb|what| describing what to get. 3836with the string \verb|what| describing what to get.
3621The default for \verb|what| is to get all information available. 3837The default for \verb|what| is to get all information available.
3838The option \verb|f|, if present,
3839adds a field named \verb|func| with the function itself.
3622 3840
3623For instance, the expression \verb|getinfo(1,"n").name| returns 3841For instance, the expression \verb|getinfo(1,"n").name| returns
3624the name of the current function, if a reasonable name can be found, 3842the name of the current function, if a reasonable name can be found,
@@ -3770,41 +3988,30 @@ Lua means ``moon'' in Portuguese.
3770\section*{Incompatibilities with Previous Versions} 3988\section*{Incompatibilities with Previous Versions}
3771\addcontentsline{toc}{section}{Incompatibilities with Previous Versions} 3989\addcontentsline{toc}{section}{Incompatibilities with Previous Versions}
3772 3990
3773Lua 4.0 is a major revision of the language.
3774We took a great care to avoid incompatibilities with 3991We took a great care to avoid incompatibilities with
3775the previous public versions of Lua, 3992the previous public versions of Lua,
3776but some differences had to be introduced. 3993but some differences had to be introduced.
3777Here is a list of all these incompatibilities. 3994Here is a list of all these incompatibilities.
3778 3995
3779 3996
3780\subsection*{Incompatibilities with \Index{version 3.2}} 3997\subsection*{Incompatibilities with \Index{version 4.0}}
3781 3998
3782\subsubsection*{Changes in the Language} 3999\subsubsection*{Changes in the Language}
3783\begin{itemize} 4000\begin{itemize}
3784 4001
3785\item 4002\item
3786All pragmas (\verb|$debug|, \verb|$if|, \ldots) have been removed. 4003Function calls written between parentheses result in exactly one value.
3787 4004
3788\item 4005\item
3789\rwd{for}, \rwd{break}, and \rwd{in} are now reserved words. 4006A function call as the last expression in a list constructor
4007(like \verb|{a,b,f()}}|) has all its return values inserted in the list.
3790 4008
3791\item 4009\item
3792Garbage-collection tag methods for tables is now obsolete. 4010\rwd{global} and \rwd{in} are reserved words.
3793 4011
3794\item 4012\item
3795There is now only one tag method for order operators. 4013When a literal string of the form \verb|[[...]]| starts with a newline,
3796 4014this newline is ignored.
3797\item
3798In nested function calls like \verb|f(g(x))|,
3799\emph{all} return values from \verb|g| are passed as arguments to \verb|f|.
3800This only happens when \verb|g| is the last
3801or the only argument to \verb|f|.
3802
3803\item
3804The pre-compiler may assume that some operators are associative,
3805for optimizations.
3806This may cause problems if these operators
3807have non-associative tag methods.
3808 4015
3809\item Old pre-compiled code is obsolete, and must be re-compiled. 4016\item Old pre-compiled code is obsolete, and must be re-compiled.
3810 4017
@@ -3815,29 +4022,15 @@ have non-associative tag methods.
3815\begin{itemize} 4022\begin{itemize}
3816 4023
3817\item 4024\item
3818When traversing a table with \verb|next| or \verb|foreach|, 4025The \verb|read| option \verb|*w| is obsolete.
3819the table cannot be modified in any way.
3820
3821\item
3822General read patterns are now obsolete.
3823 4026
3824\item 4027\item
3825The functions \verb|rawgettable| and \verb|rawsettable| 4028The \verb|format| option \verb|%n$| is obsolete.
3826have been renamed to \verb|rawget| and \verb|rawset|.
3827 4029
3828\item 4030\item
3829The functions \verb|foreachvar|, \verb|nextvar|, 4031\verb|newtag| is deprecated, being replaced by \verb|newtype|.
3830\verb|rawsetglobal|, and \verb|rawgetglobal| are obsolete. 4032Tags created in Lua with \verb|newtype| (or \verb|newtag|) can only
3831You can get their functionality using table operations 4033be used for tables.
3832over the table of globals,
3833which is returned by \verb|globals|.
3834
3835\item
3836\verb|setglobal| and \verb|sort| no longer return a value;
3837\verb|type| no longer returns a second value.
3838
3839\item
3840The \verb|p| option in function \verb|call| is now obsolete.
3841 4034
3842\end{itemize} 4035\end{itemize}
3843 4036
@@ -3846,11 +4039,8 @@ The \verb|p| option in function \verb|call| is now obsolete.
3846\begin{itemize} 4039\begin{itemize}
3847 4040
3848\item 4041\item
3849The API has been completely rewritten: 4042The \verb|lua_pushuserdata| function has been replaced by
3850It is now fully reentrant and much clearer. 4043\verb|lua_newuserdatabox|.
3851
3852\item
3853The debug API has been completely rewritten.
3854 4044
3855\end{itemize} 4045\end{itemize}
3856 4046
@@ -3879,32 +4069,29 @@ The debug API has been completely rewritten.
3879 varlist1 \ter{=} explist1 4069 varlist1 \ter{=} explist1
3880\OrNL functioncall 4070\OrNL functioncall
3881\OrNL \rwd{do} block \rwd{end} 4071\OrNL \rwd{do} block \rwd{end}
3882\OrNL \rwd{while} exp1 \rwd{do} block \rwd{end} 4072\OrNL \rwd{while} exp \rwd{do} block \rwd{end}
3883\OrNL \rwd{repeat} block \rwd{until} exp1 4073\OrNL \rwd{repeat} block \rwd{until} exp
3884\OrNL \rwd{if} exp1 \rwd{then} block 4074\OrNL \rwd{if} exp \rwd{then} block
3885 \rep{\rwd{elseif} exp1 \rwd{then} block} 4075 \rep{\rwd{elseif} exp \rwd{then} block}
3886 \opt{\rwd{else} block} \rwd{end} 4076 \opt{\rwd{else} block} \rwd{end}
3887\OrNL \rwd{return} \opt{explist1} 4077\OrNL \rwd{return} \opt{explist1}
3888\OrNL \rwd{break} 4078\OrNL \rwd{break}
3889\OrNL \rwd{for} \Nter{name} \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} 4079\OrNL \rwd{for} \Nter{name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
3890 \rwd{do} block \rwd{end} 4080 \rwd{do} block \rwd{end}
3891\OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp1 4081\OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp
3892 \rwd{do} block \rwd{end} 4082 \rwd{do} block \rwd{end}
3893\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} 4083\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
3894\OrNL \rwd{local} declist \opt{init} 4084\OrNL \rwd{local} declist \opt{init}
3895} 4085}
3896 4086
3897\produc{funcname}{% 4087\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}}
3898 \Nter{name} 4088 \opt{\ter{:} \Nter{name}}}
3899\Or \Nter{name} \ter{.} \Nter{name}
3900\Or \Nter{name} \ter{:} \Nter{name}
3901}
3902 4089
3903\produc{varlist1}{var \rep{\ter{,} var}} 4090\produc{varlist1}{var \rep{\ter{,} var}}
3904 4091
3905\produc{var}{% 4092\produc{var}{%
3906 \Nter{name} 4093 \Nter{name}
3907\Or varorfunc \ter{[} exp1 \ter{]} 4094\Or varorfunc \ter{[} exp \ter{]}
3908\Or varorfunc \ter{.} \Nter{name} 4095\Or varorfunc \ter{.} \Nter{name}
3909} 4096}
3910 4097
@@ -3914,9 +4101,7 @@ The debug API has been completely rewritten.
3914 4101
3915\produc{init}{\ter{=} explist1} 4102\produc{init}{\ter{=} explist1}
3916 4103
3917\produc{explist1}{\rep{exp1 \ter{,}} exp} 4104\produc{explist1}{\rep{exp \ter{,}} exp}
3918
3919\produc{exp1}{exp}
3920 4105
3921\produc{exp}{% 4106\produc{exp}{%
3922 \rwd{nil} 4107 \rwd{nil}
@@ -3960,9 +4145,8 @@ The debug API has been completely rewritten.
3960\Or lfieldlist \ter{;} ffieldlist 4145\Or lfieldlist \ter{;} ffieldlist
3961\Or ffieldlist \ter{;} lfieldlist 4146\Or ffieldlist \ter{;} lfieldlist
3962} 4147}
3963\produc{lfieldlist}{\opt{lfieldlist1}} 4148\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}}
3964\produc{ffieldlist}{\opt{ffieldlist1}} 4149\produc{ffieldlist}{\opt{ffieldlist1}}
3965\produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}}
3966\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} 4150\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
3967\produc{ffield}{% 4151\produc{ffield}{%
3968 \ter{[} exp \ter{]} \ter{=} exp 4152 \ter{[} exp \ter{]} \ter{=} exp