aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-02-14 19:48:32 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-02-14 19:48:32 -0200
commite966dd93be46f34bb335f09f38b4ab1777ace5f5 (patch)
tree656dbdd6c1cb1a88251a46dbe033e061c850b0df
parent2f8e3c5543bf9bf1fb50eaf3742fec1c6f940f44 (diff)
downloadlua-e966dd93be46f34bb335f09f38b4ab1777ace5f5.tar.gz
lua-e966dd93be46f34bb335f09f38b4ab1777ace5f5.tar.bz2
lua-e966dd93be46f34bb335f09f38b4ab1777ace5f5.zip
towards next version...
-rw-r--r--manual.tex1149
1 files changed, 475 insertions, 674 deletions
diff --git a/manual.tex b/manual.tex
index 7992baf5..9dcd09da 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.53 2001/10/31 18:06:05 roberto Exp roberto $ 1% $Id: manual.tex,v 1.54 2001/10/31 20:31:38 roberto Exp $
2 2
3\documentclass[11pt,twoside,draft]{article} 3\documentclass[11pt,twoside,draft]{article}
4\usepackage{fullpage} 4\usepackage{fullpage}
@@ -17,6 +17,8 @@
17\newcommand{\T}[1]{{\tt #1}} 17\newcommand{\T}[1]{{\tt #1}}
18\newcommand{\Math}[1]{$#1$} 18\newcommand{\Math}[1]{$#1$}
19\newcommand{\nil}{{\bf nil}} 19\newcommand{\nil}{{\bf nil}}
20\newcommand{\False}{{\bf false}}
21\newcommand{\True}{{\bf true}}
20%\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} 22%\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
21\def\tecgraf{{\sf TeCGraf}} 23\def\tecgraf{{\sf TeCGraf}}
22 24
@@ -33,7 +35,7 @@
33 35
34\newcommand{\ff}{$\bullet$\ } 36\newcommand{\ff}{$\bullet$\ }
35 37
36\newcommand{\Version}{4.1 (alpha)} 38\newcommand{\Version}{4.1 (beta)}
37 39
38% changes to bnf.sty by LHF 40% changes to bnf.sty by LHF
39\renewcommand{\Or}{$|$ } 41\renewcommand{\Or}{$|$ }
@@ -138,7 +140,7 @@ Waldemar Celes
138\tecgraf\ --- Computer Science Department --- PUC-Rio 140\tecgraf\ --- Computer Science Department --- PUC-Rio
139} 141}
140 142
141%\date{{\small \tt\$Date: 2001/10/31 18:06:05 $ $}} 143%\date{{\small \tt\$Date: 2001/10/31 20:31:38 $ $}}
142 144
143\maketitle 145\maketitle
144 146
@@ -157,7 +159,7 @@ powerful data description constructs
157based on associative arrays and extensible semantics. 159based on associative arrays and extensible semantics.
158Lua is 160Lua is
159dynamically typed, 161dynamically typed,
160interpreted from bytecodes, 162interpreted from opcodes,
161and has automatic memory management with garbage collection, 163and has automatic memory management with garbage collection,
162making it ideal for 164making it ideal for
163configuration, 165configuration,
@@ -184,7 +186,7 @@ poderosas constru\c{c}\~oes para descri\c{c}\~ao de dados,
184baseadas em tabelas associativas e sem\^antica extens\'\i vel. 186baseadas em tabelas associativas e sem\^antica extens\'\i vel.
185Lua \'e 187Lua \'e
186tipada dinamicamente, 188tipada dinamicamente,
187interpretada a partir de \emph{bytecodes}, 189interpretada a partir de \emph{opcodes},
188e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo. 190e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo.
189Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para 191Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para
190configura\c{c}\~ao, 192configura\c{c}\~ao,
@@ -289,7 +291,7 @@ which are executed sequentially.
289Statements are described in \See{stats}. 291Statements are described in \See{stats}.
290 292
291A chunk may be stored in a file or in a string inside the host program. 293A chunk may be stored in a file or in a string inside the host program.
292When a chunk is executed, first it is pre-compiled into bytecodes for 294When a chunk is executed, first it is pre-compiled into opcodes for
293a virtual machine, 295a virtual machine,
294and then the compiled statements are executed 296and then the compiled statements are executed
295by an interpreter for the virtual machine. 297by an interpreter for the virtual machine.
@@ -312,10 +314,15 @@ variables do not have types; only values do.
312Therefore, there are no type definitions in the language. 314Therefore, there are no type definitions in the language.
313All values carry their own type. 315All values carry their own type.
314 316
315There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, 317There are seven \Index{basic types} in Lua:
318\Def{nil}, \Def{boolean}, \Def{number},
316\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. 319\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}.
317\emph{Nil} is the type of the value \nil, 320\emph{Nil} is the type of the value \nil,
318whose main property is to be different from any other value. 321whose main property is to be different from any other value;
322usually it represents the absence of a useful value.
323\emph{Boolean} is the type of the values \False and \True.
324In Lua, both \nil{} and \False make a condition fails,
325and any other value makes it succeeds.
319\emph{Number} represents real (double-precision floating-point) numbers. 326\emph{Number} represents real (double-precision floating-point) numbers.
320\emph{String} represents arrays of characters. 327\emph{String} represents arrays of characters.
321\index{eight-bit clean} 328\index{eight-bit clean}
@@ -335,9 +342,9 @@ arbitrary \Index{C~pointers} to be stored in Lua variables.
335This type corresponds to a \verb|void*| 342This type corresponds to a \verb|void*|
336and has no pre-defined operations in Lua, 343and has no pre-defined operations in Lua,
337except assignment and equality test. 344except assignment and equality test.
338However, by using \emph{tag methods}, 345However, by using \emph{metatables},
339the programmer can define operations for userdata values 346the programmer can define operations for userdata values
340\see{tag-method}. 347\see{metatables}.
341Userdata values cannot be created or modified in Lua, 348Userdata values cannot be created or modified in Lua,
342only through the C~API. 349only through the C~API.
343This guarantees the integrity of data owned by the host program. 350This guarantees the integrity of data owned by the host program.
@@ -348,7 +355,7 @@ but with any value (except \nil).
348Moreover, 355Moreover,
349tables are \emph{heterogeneous}, 356tables are \emph{heterogeneous},
350that is, they can contain values of all types. 357that is, they can contain values of all types.
351Tables are the main data structuring mechanism in Lua; 358Tables are the sole data structuring mechanism in Lua;
352they may be used not only to represent ordinary arrays, 359they may be used not only to represent ordinary arrays,
353but also symbol tables, sets, records, graphs, trees, etc. 360but also symbol tables, sets, records, graphs, trees, etc.
354To represent \Index{records}, Lua uses the field name as an index. 361To represent \Index{records}, Lua uses the field name as an index.
@@ -366,49 +373,42 @@ So, tables may also carry \emph{methods}.
366%which calls the method \verb|f| from the table \verb|t| passing 373%which calls the method \verb|f| from the table \verb|t| passing
367%the table itself as the first parameter \see{func-def}. 374%the table itself as the first parameter \see{func-def}.
368 375
369Strings, tables, functions, and userdata values are \emph{objects}: 376Tables, functions, and userdata values are \emph{objects}:
370variables do not actually \emph{contain} these values, 377variables do not actually \emph{contain} these values,
371only \emph{references} to them. 378only \emph{references} to them.
372Assignment, parameter passing, and returns from functions 379Assignment, parameter passing, and returns from functions
373always manipulate references to these values, and do not imply any kind of copy. 380always manipulate references to these values,
381and do not imply any kind of copy.
374 382
375The library function \verb|type| returns a string describing the type 383The library function \verb|type| returns a string describing the type
376of a given value \see{pdf-type}. 384of a given value \see{pdf-type}.
377 385
378\subsubsection{Tags}\label{tags} 386\subsubsection{Metatables}
379 387
380Each type is denoted both by a \emph{name}, 388Each table or userdata object in Lua may have a \Index{metatable}.
381which is a string, 389
382and a \IndexEmph{tag}, 390You can change several aspects of the behavior
383which is an integer. 391of an object by setting specific fields in its metatable.
384Tags are mainly used by C~code, 392For instance, when an object is the operand of an addition,
385to avoid the manipulation of strings. 393Lua checks for a function in the field \verb|"add"| in its metatable.
386In the C~API, 394If it finds one,
387most operations over types require a tag to identify the type. 395Lua calls that function to perform the addition.
388In Lua, all operations over types work transparently 396
389with both type names and tags. 397A metatable works as a kind of an extended ``type'' for the object.
390The \verb|tag| function returns the tag of a given value \see{pdf-tag}. 398Objects that share a metatable has identical behavior.
391 399
392 400A metatable controls how an object behaves in arithmetic operations,
393\subsubsection{User-defined Types} 401order comparisons, concatenation, and indexing.
394 402A metatable can also defines a function to be called when a userdata
395Lua programs can create new types, 403is garbage collected,
396called \IndexEmph{user-defined types}. 404and how the garbage collector treats entries in a table
397A user-defined type is always based on a base type, 405\see{weak-table}.
398which can be either table or userdata. 406\See{metatable} gives a detailed description of which events you
399Objects of a user-defined type have an internal structure 407can control with metatables.
400identical to the corresponding base type, 408
401but the programmer may define different semantics for each operation on them 409You can query and change the metatable of an object
402\see{tag-method}. 410through the \verb|metatable| function \see{pdf-metatable}.
403 411
404The \verb|newtype| function creates a new type \see{pdf-newtype}
405with a name selected by the programmer.
406Types created by Lua programs are always based on tables;
407types created in~C can be based on tables or on userdata.
408The \verb|settagmethod| function defines new semantics for
409the operations of this new type \see{tag-method}.
410The \verb|settype| function changes the type of a given object
411\see{pdf-settype}.
412 412
413 413
414\subsection{\Index{Coercion}} \label{coercion} 414\subsection{\Index{Coercion}} \label{coercion}
@@ -421,7 +421,6 @@ the number is converted to a string, in a reasonable format.
421The format is chosen so that 421The format is chosen so that
422a conversion from number to string then back to number 422a conversion from number to string then back to number
423reproduces the original number \emph{exactly}. 423reproduces the original number \emph{exactly}.
424The conversion does not necessarily produces nice-looking text for some numbers.
425For complete control of how numbers are converted to strings, 424For complete control of how numbers are converted to strings,
426use the \verb|format| function \see{format}. 425use the \verb|format| function \see{format}.
427 426
@@ -445,6 +444,7 @@ This table can be accessed and changed with the \verb|globals| function
445Therefore, local variables can be freely accessed by functions 444Therefore, local variables can be freely accessed by functions
446defined inside their scope \see{visibility}. 445defined inside their scope \see{visibility}.
447 446
447
448\subsection{Garbage Collection}\label{GC} 448\subsection{Garbage Collection}\label{GC}
449 449
450Lua does automatic memory management. 450Lua does automatic memory management.
@@ -464,7 +464,7 @@ you can set garbage-collector tag methods for user-defined
464types based on userdata \see{tag-method}. 464types based on userdata \see{tag-method}.
465Lua calls those functions when it is about to free a userdata 465Lua calls those functions when it is about to free a userdata
466of the corresponding type. 466of the corresponding type.
467Using this facility, you can coordinate Lua's garbage collection 467Using this facility, you can coordinate Lua's garbage collection
468with external resource management 468with external resource management
469(such as closing files, network or database connections, 469(such as closing files, network or database connections,
470or freeing your own memory). 470or freeing your own memory).
@@ -488,7 +488,7 @@ through the functions \verb|gcinfo| and \verb|collectgarbage|
488\see{predefined}. 488\see{predefined}.
489 489
490 490
491\subsection{Weak Tables}\label{weak-table} 491\subsubsection{Weak Tables}\label{weak-table}
492 492
493A \IndexEmph{weak table} is a table whose elements are 493A \IndexEmph{weak table} is a table whose elements are
494\IndexEmph{weak references}. 494\IndexEmph{weak references}.
@@ -505,7 +505,7 @@ both keys and values
505In any case, if either the key or the value is collected, 505In any case, if either the key or the value is collected,
506the whole pair is removed from the table. 506the whole pair is removed from the table.
507The weakness of a table is controled by the 507The weakness of a table is controled by the
508\verb|weakmode| function \see{weakmode}. 508\verb|weakmode| field in its metatable \see{weakmode}.
509 509
510 510
511%------------------------------------------------------------------------------ 511%------------------------------------------------------------------------------
@@ -533,15 +533,12 @@ and cannot be used as identifiers:
533\index{reserved words} 533\index{reserved words}
534\begin{verbatim} 534\begin{verbatim}
535 and break do else elseif 535 and break do else elseif
536 end for function global if 536 end false for function global
537 in local nil not or 537 if in local nil not
538 repeat return then until while 538 or repeat return then true
539 until while
539\end{verbatim} 540\end{verbatim}
540(The keyword \rwd{global} is reserved for future use.) 541(The keyword \rwd{global} is reserved for future use.)
541%\IndexKW{and}\IndexKW{break}\IndexKW{do}\IndexKW{else}\IndexKW{elseif}
542%\IndexKW{end}\IndexKW{for}\IndexKW{function}\IndexKW{global}\IndexKW{if}
543%\IndexKW{in}\IndexKW{local}\IndexKW{nil}\IndexKW{not}\IndexKW{or}
544%\IndexKW{repeat}\IndexKW{return}\IndexKW{then}\IndexKW{until}\IndexKW{while}
545 542
546Lua is a case-sensitive language: 543Lua is a case-sensitive language:
547\T{and} is a reserved word, but \T{And} and \T{\'and} 544\T{and} is a reserved word, but \T{And} and \T{\'and}
@@ -552,7 +549,7 @@ are reserved for internal variables.
552 549
553The following strings denote other \Index{tokens}: 550The following strings denote other \Index{tokens}:
554\begin{verbatim} 551\begin{verbatim}
555 + - * / ^ % 552 + - * / ^ %
556 ~= <= >= < > == = 553 ~= <= >= < > == =
557 ( ) { } [ ] 554 ( ) { } [ ]
558 ; : , . .. ... 555 ; : , . .. ...
@@ -590,8 +587,8 @@ This form is specially convenient for
590writing strings that contain program pieces or 587writing strings that contain program pieces or
591other quoted strings. 588other quoted strings.
592As an example, in a system using ASCII 589As an example, in a system using ASCII
593(in which 590(in which `\verb|a|' is coded as~97,
594`\verb|a|' is coded as~97, newline is coded as~10, and `\verb|1|' is coded as~49), 591newline is coded as~10, and `\verb|1|' is coded as~49),
595the following four literals below are equivalent: 592the following four literals below are equivalent:
596\begin{verbatim} 593\begin{verbatim}
597 1) "alo\n123\"" 594 1) "alo\n123\""
@@ -633,32 +630,34 @@ or a formal parameter in a function
633 630
634Square brackets are used to index a table: 631Square brackets are used to index a table:
635\begin{Produc} 632\begin{Produc}
636\produc{var}{exp \ter{[} exp \ter{]}} 633\produc{var}{prefixexp \ter{[} exp \ter{]}}
637\end{Produc}% 634\end{Produc}%
638The first expression should result in a table value, 635The first expression should result in a table value,
639and the second expression identifies the specific place inside that table. 636and the second expression identifies a specific entry inside that table.
640 637
641The syntax \verb|var.NAME| is just syntactic sugar for 638The syntax \verb|var.NAME| is just syntactic sugar for
642\verb|var["NAME"]|: 639\verb|var["NAME"]|:
643\begin{Produc} 640\begin{Produc}
644\produc{var}{exp \ter{.} name} 641\produc{var}{prefixexp \ter{.} name}
645\end{Produc}% 642\end{Produc}%
646Expressions are discussed in \See{expressions}.
647 643
648The meaning of assignments and evaluations of global variables and 644The expression denoting the table to be indexed has a restricted syntax;
649indexed variables can be changed by tag methods \see{tag-method}. 645\See{expressions} for details.
646
647The meaning of assignments and evaluations of global and
648indexed variables can be changed via metatables.
650An assignment to a global variable \verb|x = val| 649An assignment to a global variable \verb|x = val|
651is equivalent to a call \verb|setglobal("x", val)| and 650is equivalent to an assignment in the global table:
652an assignment to an indexed variable \verb|t[i] = val| is equivalent to 651\verb|globals().x = val|.
652An assignment to an indexed variable \verb|t[i] = val| is equivalent to
653\verb|settable_event(t,i,val)|. 653\verb|settable_event(t,i,val)|.
654An access to a global variable \verb|x| 654An access to a global variable \verb|x|
655is equivalent to a call \verb|getglobal("x")| and 655is equivalent to an access to the global table: \verb|globals().x|.
656an access to an indexed variable \verb|t[i]| is equivalent to 656An access to an indexed variable \verb|t[i]| is equivalent to
657a call \verb|gettable_event(t,i)|. 657a call \verb|gettable_event(t,i)|.
658See \See{tag-method} for a complete description of these functions 658See \See{metatable} for a complete description of these functions.
659(\verb|setglobal| and \verb|getglobal| are in the basic library; 659(These functions are not defined in Lua.
660\T{settable\_event} and \T{gettable\_event} 660We use them here only for explanatory purposes.)
661are used for explanatory purposes only).
662 661
663 662
664\subsection{Statements}\label{stats} 663\subsection{Statements}\label{stats}
@@ -701,6 +700,7 @@ A block may be explicitly delimited:
701\begin{Produc} 700\begin{Produc}
702\produc{stat}{\rwd{do} block \rwd{end}} 701\produc{stat}{\rwd{do} block \rwd{end}}
703\end{Produc}% 702\end{Produc}%
703\IndexKW{do}
704Explicit blocks are useful 704Explicit blocks are useful
705to control the scope of local variables \see{localvar}. 705to control the scope of local variables \see{localvar}.
706Explicit blocks are also sometimes used to 706Explicit blocks are also sometimes used to
@@ -732,9 +732,8 @@ then all values returned by that function call enter in the list of values,
732before the adjust 732before the adjust
733(except when the call is enclosed in parentheses; see \See{expressions}). 733(except when the call is enclosed in parentheses; see \See{expressions}).
734 734
735This statement first evaluates all values on the right side 735The assignment statement first evaluates all its expressions,
736and eventual indices on the left side, 736and only then makes the assignments.
737and then makes the assignments.
738So, the code 737So, the code
739\begin{verbatim} 738\begin{verbatim}
740 i = 3 739 i = 3
@@ -743,19 +742,19 @@ So, the code
743sets \verb|a[3]| to 20, but does not affect \verb|a[4]| 742sets \verb|a[3]| to 20, but does not affect \verb|a[4]|
744because the \verb|i| in \verb|a[i]| is evaluated 743because the \verb|i| in \verb|a[i]| is evaluated
745before it is assigned 4. 744before it is assigned 4.
746 745Similarly, the line
747Multiple assignment can be used to exchange two values, as in
748\begin{verbatim} 746\begin{verbatim}
749 x, y = y, x 747 x, y = y, x
750\end{verbatim} 748\end{verbatim}
749exchanges the values of \verb|x| and \verb|y|.
751 750
752\subsubsection{Control Structures}\label{control} 751\subsubsection{Control Structures}\label{control}
753The control structures 752The control structures
754\rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and 753\rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and
755familiar syntax: 754familiar syntax:
756\index{while-do statement} 755\index{while-do statement}\IndexKW{while}
757\index{repeat-until statement} 756\index{repeat-until statement}\IndexKW{repeat}\IndexKW{until}
758\index{if-then-else statement} 757\index{if-then-else statement}\IndexKW{if}\IndexKW{else}\IndexKW{elseif}
759\begin{Produc} 758\begin{Produc}
760\produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}} 759\produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}}
761\produc{stat}{\rwd{repeat} block \rwd{until} exp} 760\produc{stat}{\rwd{repeat} block \rwd{until} exp}
@@ -767,11 +766,11 @@ There is also a \rwd{for} statement in two flavors \see{for}.
767 766
768The \Index{condition expression} \M{exp} of a 767The \Index{condition expression} \M{exp} of a
769control structure may return any value. 768control structure may return any value.
770All values different from \nil\ are considered true; 769All values different from \nil\ and \False\ are considered true;
771only \nil\ is considered false. 770both \False\ and \nil\ are considered false.
772 771
773The \rwd{return} statement is used to return values 772The \rwd{return} statement is used to return values
774from a function or from a chunk. 773from a function or from a chunk.\IndexKW{return}
775\label{return}% 774\label{return}%
776\index{return statement}% 775\index{return statement}%
777Functions and chunks may return more than one value, 776Functions and chunks may return more than one value,
@@ -782,7 +781,7 @@ and so the syntax for the \rwd{return} statement is
782 781
783The \rwd{break} statement can be used to terminate the execution of a 782The \rwd{break} statement can be used to terminate the execution of a
784\rwd{while}, \rwd{repeat}, or \rwd{for} loop, 783\rwd{while}, \rwd{repeat}, or \rwd{for} loop,
785skipping to the next statement after the loop: 784skipping to the next statement after the loop:\IndexKW{break}
786\index{break statement} 785\index{break statement}
787\begin{Produc} 786\begin{Produc}
788\produc{stat}{\rwd{break}} 787\produc{stat}{\rwd{break}}
@@ -791,26 +790,29 @@ A \rwd{break} ends the innermost enclosing loop.
791 790
792\NOTE 791\NOTE
793For syntactic reasons, \rwd{return} and \rwd{break} 792For syntactic reasons, \rwd{return} and \rwd{break}
794statements can only be written as the \emph{last} statements of a block. 793statements can only be written as the \emph{last} statement of a block.
795If it is really necessary to \rwd{return} or \rwd{break} in the 794If it is really necessary to \rwd{return} or \rwd{break} in the
796middle of a block, 795middle of a block,
797then an explicit inner block can used, 796then an explicit inner block can used,
798as in the idioms 797as in the idioms
799`\verb|do return end|' and 798`\verb|do return end|' and
800`\verb|do break end|', 799`\verb|do break end|',
801because now \rwd{return} and \rwd{break} are last statements in the inner block. 800because now \rwd{return} and \rwd{break} are the last statements in
801their (inner) blocks.
802In practice, 802In practice,
803these idioms are only used during debugging. 803these idioms are only used during debugging.
804(The idiom `\verb|do return end|' can be added at the beginning of a chunk 804(For instance, a line `\verb|do return end|' can be added at the
805for syntax checking only.) 805beginning of a chunk for syntax checking only.)
806 806
807\subsubsection{For Statement} \label{for}\index{for statement} 807\subsubsection{For Statement} \label{for}\index{for statement}
808 808
809The \rwd{for} statement has two forms, 809The \rwd{for} statement has two forms,
810one for numbers and one for tables. 810one for numbers and one generic.
811\IndexKW{for}\IndexKW{in}
811 812
812The numerical \rwd{for} loop 813The numerical \rwd{for} loop repeats a block of code while a
813repeats a block of code while a control variables runs through an arithmetic progression. It has the following syntax: 814control variables runs through an arithmetic progression.
815It has the following syntax:
814\begin{Produc} 816\begin{Produc}
815\produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp} 817\produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
816 \rwd{do} block \rwd{end}} 818 \rwd{do} block \rwd{end}}
@@ -835,13 +837,13 @@ is equivalent to the code:
835\end{verbatim} 837\end{verbatim}
836Note the following: 838Note the following:
837\begin{itemize}\itemsep=0pt 839\begin{itemize}\itemsep=0pt
840\item Both the limit and the step are evaluated only once,
841before the loop starts.
838\item \verb|_limit| and \verb|_step| are invisible variables. 842\item \verb|_limit| and \verb|_step| are invisible variables.
839The names are here for explanatory purposes only. 843The names are here for explanatory purposes only.
840\item The behavior is \emph{undefined} if you assign to \verb|var| inside 844\item The behavior is \emph{undefined} if you assign to \verb|var| inside
841the block. 845the block.
842\item If the third expression (the step) is absent, then a step of~1 is used. 846\item If the third expression (the step) is absent, then a step of~1 is used.
843\item Both the limit and the step are evaluated only once,
844before the loop starts.
845\item You can use \rwd{break} to exit a \rwd{for} loop. 847\item You can use \rwd{break} to exit a \rwd{for} loop.
846\item The loop variable \verb|var| is local to the statement; 848\item The loop variable \verb|var| is local to the statement;
847you cannot use its value after the \rwd{for} ends or is broken. 849you cannot use its value after the \rwd{for} ends or is broken.
@@ -849,47 +851,60 @@ If you need the value of the loop variable \verb|var|,
849then assign it to another variable before breaking or exiting the loop. 851then assign it to another variable before breaking or exiting the loop.
850\end{itemize} 852\end{itemize}
851 853
852The table \rwd{for} statement traverses all pairs 854The generic \rwd{for} statement works both over tables
853(index,value) of a given table. 855and over functions.
856When used with a \IndexEmph{generator function},
857it calls this function to produce a new value for each iteration,
858stopping when the new value is \nil.
854It has the following syntax: 859It has the following syntax:
855\begin{Produc} 860\begin{Produc}
856\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp 861\produc{stat}{\rwd{for} name \opt{\ter{,} name} \rwd{in} exp
857 \rwd{do} block \rwd{end}} 862 \rwd{do} block \rwd{end}}
858\end{Produc}% 863\end{Produc}%
859A \rwd{for} statement like 864A \rwd{for} statement like
860\begin{verbatim} 865\begin{verbatim}
861 for index, value in exp do block end 866 for var1, var2 in exp do block end
862\end{verbatim} 867\end{verbatim}
863is equivalent to the code: 868is equivalent to the code:
864\begin{verbatim} 869\begin{verbatim}
865 do 870 do
866 local _t = exp 871 local _f = exp
867 local index, value = next(_t, nil) 872 while 1 do
868 while index do 873 local var1, var2 = _f()
874 if var1 == nil then break end
869 block 875 block
870 index, value = next(_t, index)
871 end 876 end
872 end 877 end
873\end{verbatim} 878\end{verbatim}
874Note the following: 879Note the following:
875\begin{itemize}\itemsep=0pt 880\begin{itemize}\itemsep=0pt
876\item \verb|_t| is an invisible variable. 881\item \verb|exp| is evaluated only once.
882Its result is the function that will be evaluated for each loop.
883\item \verb|_f| is an invisible variable.
877The name is here for explanatory purposes only. 884The name is here for explanatory purposes only.
878\item The behavior is \emph{undefined} if you assign to \verb|index| inside 885\item The behavior is \emph{undefined} if you assign to \verb|var1|
879the block. 886or \verb|var2| inside the block.
880\item The behavior is \emph{undefined} if you change
881the table \verb|_t| during the traversal.
882\item You can use \rwd{break} to exit a \rwd{for} loop. 887\item You can use \rwd{break} to exit a \rwd{for} loop.
883\item The loop variables \verb|index| and \verb|value| are local to the statement; 888\item The loop variables \verb|var1| and \verb|var2| are
889local to the statement;
884you cannot use their values after the \rwd{for} ends. 890you cannot use their values after the \rwd{for} ends.
885If you need the value of \verb|index| or \verb|value|, 891If you need these values,
886then assign them to other variables before breaking or exiting the loop. 892then assign them to other variables before breaking or exiting the loop.
887\item The order that table elements are traversed is undefined, 893\item The absence of the optional variable \verb|var2| does not
888\emph{even for numerical indices}. 894change the meaning of the loop.
889If you want to traverse indices in numerical order,
890use a numerical \rwd{for}.
891\end{itemize} 895\end{itemize}
892 896
897If the generator is a table \verb|t|,
898then the loop works as if it has received the following generator function:
899\begin{verbatim}
900 local k,v = nil
901 function generator ()
902 k,v = next(t, k)
903 return k,v
904 end
905\end{verbatim}
906That is, the loop iterates over the (key,value) pairs of the table.
907
893 908
894\subsubsection{Function Calls as Statements} \label{funcstat} 909\subsubsection{Function Calls as Statements} \label{funcstat}
895Because of possible side-effects, 910Because of possible side-effects,
@@ -902,7 +917,7 @@ Function calls are explained in \See{functioncall}.
902 917
903\subsubsection{Local Declarations} \label{localvar} 918\subsubsection{Local Declarations} \label{localvar}
904\Index{Local variables} may be declared anywhere inside a block. 919\Index{Local variables} may be declared anywhere inside a block.
905The declaration may include an initial assignment: 920The declaration may include an initial assignment:\IndexKW{local}
906\begin{Produc} 921\begin{Produc}
907\produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}} 922\produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}}
908\produc{namelist}{name \rep{\ter{,} name}} 923\produc{namelist}{name \rep{\ter{,} name}}
@@ -923,15 +938,15 @@ Visibility rules for local variables are explained in \See{visibility}.
923%\subsubsection{\Index{Basic Expressions}} 938%\subsubsection{\Index{Basic Expressions}}
924The basic expressions in Lua are the following: 939The basic expressions in Lua are the following:
925\begin{Produc} 940\begin{Produc}
926\produc{exp}{\ter{(} exp \ter{)}} 941\produc{exp}{prefixexp}
927\produc{exp}{\rwd{nil}} 942\produc{exp}{\rwd{nil} \Or \rwd{false} \Or \rwd{true}}
928\produc{exp}{number} 943\produc{exp}{Number}
929\produc{exp}{literal} 944\produc{exp}{Literal}
930\produc{exp}{var}
931\produc{exp}{function} 945\produc{exp}{function}
932\produc{exp}{functioncall}
933\produc{exp}{tableconstructor} 946\produc{exp}{tableconstructor}
947\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
934\end{Produc}% 948\end{Produc}%
949\IndexKW{nil}
935 950
936An expression enclosed in parentheses always results in only one value. 951An expression enclosed in parentheses always results in only one value.
937Thus, 952Thus,
@@ -957,10 +972,10 @@ the binary \verb|+| (addition),
957and unary \verb|-| (negation). 972and unary \verb|-| (negation).
958If the operands are numbers, or strings that can be converted to 973If the operands are numbers, or strings that can be converted to
959numbers \see{coercion}, 974numbers \see{coercion},
960then all operations except exponentiation have the usual meaning; 975then all operations except exponentiation have the usual meaning,
976while exponentiation calls a global function \verb|pow|;
961otherwise, an appropriate tag method is called \see{tag-method}. 977otherwise, an appropriate tag method is called \see{tag-method}.
962An exponentiation always calls a tag method. 978The standard mathematical library defines function \verb|pow|,
963The standard mathematical library defines this method for numbers,
964giving the expected meaning to \Index{exponentiation} 979giving the expected meaning to \Index{exponentiation}
965\see{mathlib}. 980\see{mathlib}.
966 981
@@ -969,10 +984,10 @@ The \Index{relational operators} in Lua are
969\begin{verbatim} 984\begin{verbatim}
970 == ~= < > <= >= 985 == ~= < > <= >=
971\end{verbatim} 986\end{verbatim}
972These operators return \nil\ as false and a value different from \nil\ as true. 987These operators always result in \False\ or \True.
973 988
974Equality (\verb|==|) first compares the type of its operands. 989Equality (\verb|==|) first compares the type of its operands.
975If the types are different, then the result is \nil. 990If the types are different, then the result is \False.
976Otherwise, the values of the operands are compared. 991Otherwise, the values of the operands are compared.
977Numbers and strings are compared in the usual way. 992Numbers and strings are compared in the usual way.
978Tables, userdata, and functions are compared \emph{by reference}, 993Tables, userdata, and functions are compared \emph{by reference},
@@ -1006,38 +1021,54 @@ The \Index{logical operators} in Lua are
1006 and or not 1021 and or not
1007\end{verbatim} 1022\end{verbatim}
1008Like the control structures \see{control}, 1023Like the control structures \see{control},
1009all logical operators consider \nil\ as false and anything else as true. 1024all logical operators consider both \False\ and \nil\ as false
1025and anything else as true.
1026\IndexKW{and}\IndexKW{or}\IndexKW{not}
1010 1027
1011The conjunction operator \rwd{and} returns \nil\ if its first argument is \nil; 1028The operator \rwd{not} always return \False\ or \True.
1029
1030The conjunction operator \rwd{and} returns its first argument
1031if its value is \False\ or \nil;
1012otherwise, \rwd{and} returns its second argument. 1032otherwise, \rwd{and} returns its second argument.
1013The disjunction operator \rwd{or} returns its first argument 1033The disjunction operator \rwd{or} returns its first argument
1014if it is different from \nil; 1034if it is different from \nil and \False;
1015otherwise, \rwd{or} returns its second argument. 1035otherwise, \rwd{or} returns its second argument.
1016Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation}, 1036Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation},
1017that is, 1037that is,
1018the second operand is evaluated only if necessary. 1038the second operand is evaluated only if necessary.
1019 1039For example,
1020There are two useful Lua idioms that use logical operators.
1021The first idiom is
1022\begin{verbatim}
1023 x = x or v
1024\end{verbatim}
1025which is equivalent to
1026\begin{verbatim} 1040\begin{verbatim}
1027 if x == nil then x = v end 1041 10 or error() -> 10
1042 nil or "a" -> "a"
1043 nil and 10 -> nil
1044 false and error() -> false
1045 false and nil -> false
1046 false or nil -> nil
1047 10 and 20 -> 20
1028\end{verbatim} 1048\end{verbatim}
1029This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set.
1030 1049
1031The second idiom is 1050%There are two useful Lua idioms that use logical operators.
1032\begin{verbatim} 1051%The first idiom is
1033 x = a and b or c 1052%\begin{verbatim}
1034\end{verbatim} 1053% x = x or v
1035which should be read as \verb|x = (a and b) or c|. 1054%\end{verbatim}
1036This idiom is equivalent to 1055%which is equivalent to
1037\begin{verbatim} 1056%\begin{verbatim}
1038 if a then x = b else x = c end 1057% if not x then x = v end
1039\end{verbatim} 1058%\end{verbatim}
1040provided that \verb|b| is not \nil. 1059%This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set
1060%(provided that \verb|x| is not a boolean value).
1061
1062%The second idiom is
1063%\begin{verbatim}
1064% x = a and b or c
1065%\end{verbatim}
1066%which should be read as \verb|x = (a and b) or c|.
1067%This idiom is equivalent to
1068%\begin{verbatim}
1069% if a then x = b else x = c end
1070%\end{verbatim}
1071%provided that \verb|b| is not \nil.
1041 1072
1042\subsubsection{Concatenation} \label{concat} 1073\subsubsection{Concatenation} \label{concat}
1043The string \Index{concatenation} operator in Lua is 1074The string \Index{concatenation} operator in Lua is
@@ -1063,13 +1094,12 @@ except for \verb|^| (exponentiation),
1063which is right associative. 1094which is right associative.
1064\NOTE 1095\NOTE
1065The pre-compiler may rearrange the order of evaluation of 1096The pre-compiler may rearrange the order of evaluation of
1066associative or commutative operators, 1097associative operators,
1098and may exchange the operands of commutative operators,
1067as long as these optimizations do not change normal results. 1099as long as these optimizations do not change normal results.
1068However, these optimizations may change some results 1100However, these optimizations may change some results
1069if you define non-associative (or non-commutative) 1101if you define non-associative (or non-commutative)
1070tag methods for these operators. 1102tag methods for these operators.
1071In general,
1072you should not write code that depends on the order of evaluation.
1073 1103
1074\subsubsection{Table Constructors} \label{tableconstructor} 1104\subsubsection{Table Constructors} \label{tableconstructor}
1075Table \Index{constructors} are expressions that create tables; 1105Table \Index{constructors} are expressions that create tables;
@@ -1078,28 +1108,35 @@ Constructors can be used to create empty tables,
1078or to create a table and initialize some of its fields. 1108or to create a table and initialize some of its fields.
1079The general syntax for constructors is 1109The general syntax for constructors is
1080\begin{Produc} 1110\begin{Produc}
1081\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} 1111\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
1082\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist 1112\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
1083 \Or ffieldlist \ter{;} lfieldlist} 1113\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp}
1084\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}} 1114\produc{fieldsep}{\ter{,} \Or \ter{;}}
1085\produc{ffieldlist}{\opt{ffieldlist1 \opt{\ter{,}}}}
1086\end{Produc}% 1115\end{Produc}%
1087 1116
1088The form \emph{explist1} is used to initialize \IndexEmph{lists}. 1117Each field of the form \verb|[exp1] = exp2| adds to the new table an entry
1089The expressions in a list are assigned to consecutive numerical indices 1118with key \verb|exp1| and value \verb|exp2|.
1090in the table, 1119A field of the form \verb|name = exp| is equivalent to
1091starting with~1. 1120\verb|["name"] = exp|.
1121Finally, fields of the form \verb|exp| add to the new table entries
1122with the given expression indexed by consecutive numerical integers,
1123starting with 1.
1124Fields in the other formats do not affect this counting.
1092For example, 1125For example,
1093\begin{verbatim} 1126\begin{verbatim}
1094 a = {"v1", "v2", 34} 1127 a = {[f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45}
1095\end{verbatim} 1128\end{verbatim}
1096is equivalent to 1129is equivalent to
1097\begin{verbatim} 1130\begin{verbatim}
1098 do 1131 do
1099 local temp = {} 1132 local temp = {}
1100 temp[1] = "v1" 1133 temp[f(1)] = g
1101 temp[2] = "v2" 1134 temp[1] = "x" -- 1st exp
1102 temp[3] = 34 1135 temp[2] = "y" -- 2nd exp
1136 temp.x = 1 -- temp["x"] = 1
1137 temp[3] = f(x) -- 3rd exp
1138 temp[30] = 23
1139 temp[4] = 45 -- 4th exp
1103 a = temp 1140 a = temp
1104 end 1141 end
1105\end{verbatim} 1142\end{verbatim}
@@ -1110,59 +1147,28 @@ then all values returned by the call enter the list consecutively
1110If you want to avoid this, 1147If you want to avoid this,
1111enclose the function call in parentheses. 1148enclose the function call in parentheses.
1112 1149
1113The form \emph{ffieldlist1} initializes other fields in a table: 1150The field list may have an optional trailing separator,
1114\begin{Produc} 1151as a convenience for machine-generated code.
1115\produc{ffieldlist1}{ffield \rep{\ter{,} ffield}} 1152
1116\produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp}
1117\end{Produc}%
1118For example,
1119\begin{verbatim}
1120 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
1121\end{verbatim}
1122is equivalent to
1123\begin{verbatim}
1124 do
1125 local temp = {}
1126 temp[f(k)] = g(y)
1127 temp["x"] = 1 -- or temp.x = 1
1128 temp["y"] = 3 -- or temp.y = 3
1129 temp[0] = b+c
1130 a = temp
1131 end
1132\end{verbatim}
1133An expression like \verb|{x = 1, y = 4}| is
1134in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
1135
1136Both forms may have an optional trailing comma
1137(for convenience of machine-generated code),
1138and can be used in the same constructor separated by
1139a semi-colon.
1140For example, all forms below are correct.
1141\begin{verbatim}
1142 x = {;}
1143 x = {"a", "b",}
1144 x = {type="list"; "a", "b"}
1145 x = {f(0), f(1), f(2),; n=3,}
1146\end{verbatim}
1147 1153
1148\subsubsection{Function Calls} \label{functioncall} 1154\subsubsection{Function Calls} \label{functioncall}
1149A \Index{function call} in Lua has the following syntax: 1155A \Index{function call} in Lua has the following syntax:
1150\begin{Produc} 1156\begin{Produc}
1151\produc{functioncall}{exp args} 1157\produc{functioncall}{prefixexp args}
1152\end{Produc}% 1158\end{Produc}%
1153In a function call, 1159In a function call,
1154first \M{exp} and \M{args} are evaluated. 1160first \M{prefixexp} and \M{args} are evaluated.
1155If the value of \M{exp} has type \emph{function}, 1161If the value of \M{prefixexp} has type \emph{function},
1156then this function is called, 1162then this function is called,
1157with the given arguments. 1163with the given arguments.
1158Otherwise, the ``function'' tag method is called, 1164Otherwise, the ``function'' tag method is called,
1159having as first parameter the value of \M{exp}, 1165having as first parameter the value of \M{prefixexp},
1160followed by the original call arguments 1166followed by the original call arguments
1161\see{tag-method}. 1167\see{tag-method}.
1162 1168
1163The form 1169The form
1164\begin{Produc} 1170\begin{Produc}
1165\produc{functioncall}{exp \ter{:} name args} 1171\produc{functioncall}{prefixexp \ter{:} name args}
1166\end{Produc}% 1172\end{Produc}%
1167can be used to call ``methods''. 1173can be used to call ``methods''.
1168A call \verb|v:name(...)| 1174A call \verb|v:name(...)|
@@ -1173,7 +1179,7 @@ Arguments have the following syntax:
1173\begin{Produc} 1179\begin{Produc}
1174\produc{args}{\ter{(} \opt{explist1} \ter{)}} 1180\produc{args}{\ter{(} \opt{explist1} \ter{)}}
1175\produc{args}{tableconstructor} 1181\produc{args}{tableconstructor}
1176\produc{args}{literal} 1182\produc{args}{Literal}
1177\end{Produc}% 1183\end{Produc}%
1178All argument expressions are evaluated before the call. 1184All argument expressions are evaluated before the call.
1179A call of the form \verb|f{...}| is syntactic sugar for 1185A call of the form \verb|f{...}| is syntactic sugar for
@@ -1188,11 +1194,11 @@ Because a function can return any number of results
1188\see{return}, 1194\see{return},
1189the number of results must be adjusted before they are used. 1195the number of results must be adjusted before they are used.
1190If the function is called as a statement \see{funcstat}, 1196If the function is called as a statement \see{funcstat},
1191then its return list is adjusted to~0, 1197then its return list is adjusted to~0 elements,
1192thus discarding all returned values. 1198thus discarding all returned values.
1193If the function is called inside another expression, 1199If the function is called inside another expression,
1194or in the middle of a list of expressions, 1200or in the middle of a list of expressions,
1195then its return list is adjusted to~1, 1201then its return list is adjusted to~1 element,
1196thus discarding all returned values but the first one. 1202thus discarding all returned values but the first one.
1197If the function is called as the last element of a list of expressions, 1203If the function is called as the last element of a list of expressions,
1198then no adjustment is made 1204then no adjustment is made
@@ -1219,9 +1225,23 @@ then it is adjusted to return exactly one value:
1219 {(f())} -- creates a table with exactly one element 1225 {(f())} -- creates a table with exactly one element
1220\end{verbatim} 1226\end{verbatim}
1221 1227
1228As an exception to the format-free syntax of Lua,
1229you cannot put a line break before the \verb|(| in a function call.
1230That restriction avoids some ambiguities in the language.
1231If you write
1232\begin{verbatim}
1233 a = f
1234 (g).x(a)
1235\end{verbatim}
1236Lua would read that as \verb|a = f(g).x(a)|.
1237So, if you want two statements, you must add a semi-colon between them.
1238If you actually want to call \verb|f|,
1239you must remove the line break before \verb|(g)|.
1240
1241
1222\subsubsection{\Index{Function Definitions}} \label{func-def} 1242\subsubsection{\Index{Function Definitions}} \label{func-def}
1223 1243
1224The syntax for function definition is 1244The syntax for function definition is\IndexKW{function}
1225\begin{Produc} 1245\begin{Produc}
1226\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} 1246\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)}
1227 block \rwd{end}} 1247 block \rwd{end}}
@@ -1260,8 +1280,8 @@ may refer to different non-local variables \see{visibility}.
1260Parameters act as local variables, 1280Parameters act as local variables,
1261initialized with the argument values: 1281initialized with the argument values:
1262\begin{Produc} 1282\begin{Produc}
1263\produc{parlist1}{\ter{\ldots}}
1264\produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}} 1283\produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}}
1284\produc{parlist1}{\ter{\ldots}}
1265\end{Produc}% 1285\end{Produc}%
1266\label{vararg}% 1286\label{vararg}%
1267When a function is called, 1287When a function is called,
@@ -1349,7 +1369,7 @@ defined inside their scope.
1349For instance: 1369For instance:
1350\begin{verbatim} 1370\begin{verbatim}
1351 local counter = 0 1371 local counter = 0
1352 function inc (x) 1372 function inc (x)
1353 counter = counter + x 1373 counter = counter + x
1354 return counter 1374 return counter
1355 end 1375 end
@@ -1411,35 +1431,28 @@ Lua code can ``catch'' an error using the function
1411\verb|call| \see{pdf-call}. 1431\verb|call| \see{pdf-call}.
1412 1432
1413 1433
1414\subsection{Tag Methods} \label{tag-method} 1434\subsection{Metatables} \label{metatable}
1415 1435
1416A \IndexEmph{tag method} is a programmer-defined function 1436Every table and userdata value in Lua may have a \emph{metatable}.
1417that defines how Lua operations act over user-defined types 1437This \IndexEmph{metatable} is a table that defines the behavior of
1418(and, sometimes, over basic types as well). 1438the original table and userdata under some operations.
1419An \Def{event} is any operation that may invoke a tag method. 1439You can query and change the metatable of an object with
1420 1440function \verb|metatable| \see{pdf-metatable}.
1421Lua selects the tag method called for any specific event 1441
1422according to the types of the values involved 1442For each of these operations Lua associates a specific key.
1423in the event \see{TypesSec}. 1443When Lua performs one of these operations over a table or a userdata,
1424The function \IndexLIB{settagmethod} changes the tag method 1444if checks whether that object has a metatable with the corresponding key.
1425associated with a given (\M{type}, \M{event}) pair. 1445If so, the value associated with that key (the \IndexEmph{handler})
1426The first parameter to \verb|settagmethod| is the type 1446controls how Lua will perform the operation.
1427(represented by its name or tag), 1447
1428the second parameter is the event name (a string; see below), 1448Metatables control the operations listed next.
1429and the third parameter is the new method (a function), 1449Each operation is identified by its corresponding key.
1430or \nil\ to restore the default behavior for the pair. 1450The semantics of these operations is better explained by a Lua function
1431A companion function \IndexLIB{gettagmethod} 1451describing how the interpreter executes that operation.
1432receives a type and an event name and returns the 1452%Each function shows how a handler is called,
1433current method associated to them. 1453%its arguments (that is, its signature),
1434 1454%its results,
1435Tag methods are called in the following events, 1455%and the default behavior in the absence of a handler.
1436identified by the given names.
1437The semantics of tag methods is better explained by a Lua function
1438describing the behavior of the interpreter at each event.
1439Each event-handler function shows how a tag method is called,
1440its arguments (that is, its signature),
1441its results,
1442and the default behavior in the absence of a tag method.
1443The code shown here in Lua is only illustrative; 1456The code shown here in Lua is only illustrative;
1444the real behavior is hard coded in the interpreter, 1457the real behavior is hard coded in the interpreter,
1445and it is much more efficient than this simulation. 1458and it is much more efficient than this simulation.
@@ -1450,34 +1463,31 @@ are described in \See{predefined}.
1450\begin{description} 1463\begin{description}
1451 1464
1452\item[``add'':]\IndexTM{add} 1465\item[``add'':]\IndexTM{add}
1453called when a \verb|+| operation is applied to non-numerical operands. 1466the \verb|+| operation.
1454 1467
1455The function \verb|getbinmethod| below defines how Lua chooses a tag method 1468The function \verb|getbinhandler| below defines how Lua chooses a handler
1456for a binary operation. 1469for a binary operation.
1457First, Lua tries the first operand. 1470First, Lua tries the first operand.
1458If its type does not define a tag method for the operation, 1471If its type does not define a handler for the operation,
1459then Lua tries the second operand. 1472then Lua tries the second operand.
1460If it also fails, then it gets a tag method from tag~0.
1461\begin{verbatim} 1473\begin{verbatim}
1462 function getbinmethod (op1, op2, event) 1474 function getbinhandler (op1, op2, event)
1463 return gettagmethod(tag(op1), event) or 1475 return metatable(op1)[event] or metatable(op2)[event]
1464 gettagmethod(tag(op2), event) or
1465 gettagmethod(0, event)
1466 end 1476 end
1467\end{verbatim} 1477\end{verbatim}
1468Using this function, 1478Using this function,
1469the tag method for the ``add'' event is 1479the behavior of the ``add'' operation is
1470\begin{verbatim} 1480\begin{verbatim}
1471 function add_event (op1, op2) 1481 function add_op (op1, op2)
1472 local o1, o2 = tonumber(op1), tonumber(op2) 1482 local o1, o2 = tonumber(op1), tonumber(op2)
1473 if o1 and o2 then -- both operands are numeric 1483 if o1 and o2 then -- both operands are numeric
1474 return o1+o2 -- '+' here is the primitive 'add' 1484 return o1+o2 -- '+' here is the primitive 'add'
1475 else -- at least one of the operands is not numeric 1485 else -- at least one of the operands is not numeric
1476 local tm = getbinmethod(op1, op2, "add") 1486 local h = getbinhandler(op1, op2, "add")
1477 if tm then 1487 if h then
1478 -- call the method with both operands 1488 -- call the handler with both operands
1479 return tm(op1, op2) 1489 return h(op1, op2)
1480 else -- no tag method available: default behavior 1490 else -- no handler available: default behavior
1481 error("unexpected type at arithmetic operation") 1491 error("unexpected type at arithmetic operation")
1482 end 1492 end
1483 end 1493 end
@@ -1485,48 +1495,45 @@ the tag method for the ``add'' event is
1485\end{verbatim} 1495\end{verbatim}
1486 1496
1487\item[``sub'':]\IndexTM{sub} 1497\item[``sub'':]\IndexTM{sub}
1488called when a \verb|-| operation is applied to non-numerical operands. 1498the \verb|-| operation.
1489Behavior similar to the ``add'' event. 1499Behavior similar to the ``add'' operation.
1490 1500
1491\item[``mul'':]\IndexTM{mul} 1501\item[``mul'':]\IndexTM{mul}
1492called when a \verb|*| operation is applied to non-numerical operands. 1502the \verb|*| operation.
1493Behavior similar to the ``add'' event. 1503Behavior similar to the ``add'' operation.
1494 1504
1495\item[``div'':]\IndexTM{div} 1505\item[``div'':]\IndexTM{div}
1496called when a \verb|/| operation is applied to non-numerical operands. 1506the \verb|/| operation.
1497Behavior similar to the ``add'' event. 1507Behavior similar to the ``add'' operation.
1498 1508
1499\item[``pow'':]\IndexTM{pow} 1509\item[``pow'':]\IndexTM{pow}
1500called when a \verb|^| operation (exponentiation) is applied, 1510the \verb|^| operation (exponentiation) operation.
1501even for numerical operands. 1511\begin{verbatim} ??
1502\begin{verbatim} 1512 function pow_op (op1, op2)
1503 function pow_event (op1, op2) 1513 local h = getbinhandler(op1, op2, "pow")
1504 local tm = getbinmethod(op1, op2, "pow") 1514 if h then
1505 if tm then 1515 -- call the handler with both operands
1506 -- call the method with both operands 1516 return h(op1, op2)
1507 return tm(op1, op2) 1517 else -- no handler available: default behavior
1508 else -- no tag method available: default behavior
1509 error("unexpected type at arithmetic operation") 1518 error("unexpected type at arithmetic operation")
1510 end 1519 end
1511 end 1520 end
1512\end{verbatim} 1521\end{verbatim}
1513 1522
1514\item[``unm'':]\IndexTM{unm} 1523\item[``unm'':]\IndexTM{unm}
1515called when a unary \verb|-| operation is applied to a non-numerical operand. 1524the unary \verb|-| operation.
1516\begin{verbatim} 1525\begin{verbatim}
1517 function unm_event (op) 1526 function unm_op (op)
1518 local o = tonumber(op) 1527 local o = tonumber(op)
1519 if o then -- operand is numeric 1528 if o then -- operand is numeric
1520 return -o -- '-' here is the primitive 'unm' 1529 return -o -- '-' here is the primitive 'unm'
1521 else -- the operand is not numeric. 1530 else -- the operand is not numeric.
1522 -- Try to get a tag method from the operand; 1531 -- Try to get a handler from the operand;
1523 -- if it does not have one, try a "global" one (tag 0) 1532 local h = metatable(op).unm
1524 local tm = gettagmethod(tag(op), "unm") or 1533 if h then
1525 gettagmethod(0, "unm") 1534 -- call the handler with the operand and nil
1526 if tm then 1535 return h(op, nil)
1527 -- call the method with the operand and nil 1536 else -- no handler available: default behavior
1528 return tm(op, nil)
1529 else -- no tag method available: default behavior
1530 error("unexpected type at arithmetic operation") 1537 error("unexpected type at arithmetic operation")
1531 end 1538 end
1532 end 1539 end
@@ -1534,26 +1541,24 @@ called when a unary \verb|-| operation is applied to a non-numerical operand.
1534\end{verbatim} 1541\end{verbatim}
1535 1542
1536\item[``lt'':]\IndexTM{lt} 1543\item[``lt'':]\IndexTM{lt}
1537called when an order operation is applied to non-numerical 1544the \verb|<| operation.
1538or non-string operands.
1539It corresponds to the \verb|<| operator.
1540\begin{verbatim} 1545\begin{verbatim}
1541 function lt_event (op1, op2) 1546 function lt_op (op1, op2)
1542 if type(op1) == "number" and type(op2) == "number" then 1547 if type(op1) == "number" and type(op2) == "number" then
1543 return op1 < op2 -- numeric comparison 1548 return op1 < op2 -- numeric comparison
1544 elseif type(op1) == "string" and type(op2) == "string" then 1549 elseif type(op1) == "string" and type(op2) == "string" then
1545 return op1 < op2 -- lexicographic comparison 1550 return op1 < op2 -- lexicographic comparison
1546 else 1551 else
1547 local tm = getbinmethod(op1, op2, "lt") 1552 local h = getbinhandler(op1, op2, "lt")
1548 if tm then 1553 if h then
1549 return tm(op1, op2) 1554 return h(op1, op2)
1550 else 1555 else
1551 error("unexpected type at comparison"); 1556 error("unexpected type at comparison");
1552 end 1557 end
1553 end 1558 end
1554 end 1559 end
1555\end{verbatim} 1560\end{verbatim}
1556The other order operators use the \verb|"lt"| tag method 1561The other order operators also use the \verb|lt_op| function,
1557according to the usual equivalences: 1562according to the usual equivalences:
1558\begin{verbatim} 1563\begin{verbatim}
1559 a>b <=> b<a 1564 a>b <=> b<a
@@ -1562,16 +1567,16 @@ according to the usual equivalences:
1562\end{verbatim} 1567\end{verbatim}
1563 1568
1564\item[``concat'':]\IndexTM{concatenation} 1569\item[``concat'':]\IndexTM{concatenation}
1565called when a concatenation is applied to non-string operands. 1570the \verb|..| (concatenation) operation.
1566\begin{verbatim} 1571\begin{verbatim}
1567 function concat_event (op1, op2) 1572 function concat_op (op1, op2)
1568 if (type(op1) == "string" or type(op1) == "number") and 1573 if (type(op1) == "string" or type(op1) == "number") and
1569 (type(op2) == "string" or type(op2) == "number") then 1574 (type(op2) == "string" or type(op2) == "number") then
1570 return op1..op2 -- primitive string concatenation 1575 return op1..op2 -- primitive string concatenation
1571 else 1576 else
1572 local tm = getbinmethod(op1, op2, "concat") 1577 local h = getbinhandler(op1, op2, "concat")
1573 if tm then 1578 if h then
1574 return tm(op1, op2) 1579 return h(op1, op2)
1575 else 1580 else
1576 error("unexpected type for concatenation") 1581 error("unexpected type for concatenation")
1577 end 1582 end
@@ -1580,107 +1585,59 @@ called when a concatenation is applied to non-string operands.
1580\end{verbatim} 1585\end{verbatim}
1581 1586
1582\item[``index'':]\IndexTM{index} 1587\item[``index'':]\IndexTM{index}
1583called when Lua tries to retrieve the value of an index 1588This handler is called when Lua tries to retrieve the value of an index
1584not present in a table. 1589not present in a table.
1585See the ``gettable'' event for its semantics. 1590See the ``gettable'' operation for its semantics.
1586
1587\item[``getglobal'':]\IndexTM{getglobal}
1588called whenever Lua needs the value of a global variable.
1589This method can only be set for \nil\ and for user-defined types.
1590Note that
1591the tag is that of the \emph{current value} of the global variable.
1592\begin{verbatim}
1593 function getglobal (varname)
1594 -- access the table of globals
1595 local value = rawget(globals(), varname)
1596 local tm = gettagmethod(tag(value), "getglobal")
1597 if not tm then
1598 return value
1599 else
1600 return tm(varname, value)
1601 end
1602 end
1603\end{verbatim}
1604The function \verb|getglobal| is defined in the basic library~\see{predefined}.
1605\NOTE
1606\verb|getglobal| is ``overloaded'' here.
1607It is the name both of the event and
1608of the function that handles the event
1609to call an eventual tag method
1610(called \verb|tm| in the above code).
1611
1612\item[``setglobal'':]\IndexTM{setglobal}
1613called whenever Lua assigns to a global variable.
1614This method cannot be set for numbers, strings, and tables and
1615userdata with the default tag.
1616\begin{verbatim}
1617 function setglobal (varname, newvalue)
1618 local oldvalue = rawget(globals(), varname)
1619 local tm = gettagmethod(tag(oldvalue), "setglobal")
1620 if not tm then
1621 rawset(globals(), varname, newvalue)
1622 else
1623 tm(varname, oldvalue, newvalue)
1624 end
1625 end
1626\end{verbatim}
1627The function \verb|setglobal| is defined in the basic library~\see{predefined}.
1628\NOTE
1629See previous note.
1630 1591
1631\item[``gettable'':]\IndexTM{gettable} 1592\item[``gettable'':]\IndexTM{gettable}
1632called whenever Lua accesses an indexed variable. 1593called whenever Lua accesses an indexed variable.
1633This method cannot be set for tables with the default tag.
1634\begin{verbatim} 1594\begin{verbatim}
1635 function gettable_event (table, index) 1595 function gettable_op (table, key)
1636 local tm = gettagmethod(tag(table), "gettable") 1596 local h = metatable(table).gettable
1637 if tm then 1597 if h == nil then
1638 return tm(table, index) 1598 if type(table) ~= "table" then
1639 elseif type(table) ~= "table" then 1599 error("indexed expression not a table");
1640 error("indexed expression not a table");
1641 else
1642 local v = rawget(table, index)
1643 tm = gettagmethod(tag(table), "index")
1644 if v == nil and tm then
1645 return tm(table, index)
1646 else 1600 else
1647 return v 1601 local v = rawget(table, key)
1602 if v ~= nil then return v end
1603 h = metatable(table).index
1604 if h == nil then return nil end
1648 end 1605 end
1649 end 1606 end
1607 if type(h) == 'function' then
1608 return h(table, key) -- call the handler
1609 else return h[key] -- or repeat operation with it
1650 end 1610 end
1651\end{verbatim} 1611\end{verbatim}
1652 1612
1653\item[``settable'':]\IndexTM{settable} 1613\item[``settable'':]\IndexTM{settable}
1654called when Lua assigns to an indexed variable. 1614called when Lua assigns to an indexed variable.
1655This method cannot be set for tables with the default tag.
1656\begin{verbatim} 1615\begin{verbatim}
1657 function settable_event (table, index, value) 1616 function settable_event (table, key, value)
1658 local tm = gettagmethod(tag(table), "settable") 1617 local h = metatable(table).settable
1659 if tm then 1618 if h == nil then
1660 tm(table, index, value) 1619 if type(table) ~= "table" then
1661 elseif type(table) ~= "table" then 1620 error("indexed expression not a table")
1662 error("indexed expression not a table") 1621 rawset(table, key, value)
1663 else 1622 else
1664 rawset(table, index, value) 1623 if type(h) == 'function' then
1624 h(table, key, value) -- call the handler
1625 else h[key] = value -- or repeat operation with it
1665 end 1626 end
1666 end 1627 end
1667\end{verbatim} 1628\end{verbatim}
1668 1629
1669\item[``function'':]\IndexTM{function} 1630\item[``call'':]\IndexTM{call}
1670called when Lua tries to call a non-function value. 1631called when Lua calls a value.
1671\begin{verbatim} 1632\begin{verbatim}
1672 function function_event (func, ...) 1633 function function_op (func, ...)
1673 if type(func) == "function" then 1634 if type(func) == "function" then
1674 return call(func, arg) 1635 return func(unpack(arg)) -- regular call
1675 else 1636 else
1676 local tm = gettagmethod(tag(func), "function") 1637 local h = metatable(func).call
1677 if tm then 1638 if h then
1678 for i=arg.n,1,-1 do 1639 tinsert(arg, 1, func)
1679 arg[i+1] = arg[i] 1640 return h(unpack(arg))
1680 end
1681 arg.n = arg.n+1
1682 arg[1] = func
1683 return call(tm, arg)
1684 else 1641 else
1685 error("call expression not a function") 1642 error("call expression not a function")
1686 end 1643 end
@@ -1688,30 +1645,39 @@ called when Lua tries to call a non-function value.
1688 end 1645 end
1689\end{verbatim} 1646\end{verbatim}
1690 1647
1691\item[``gc'':]\IndexTM{gc} 1648\end{description}
1692called when Lua is ``garbage collecting'' a userdata. 1649
1693This tag method can be set only from~C, 1650\subsubsection{Metatables and Garbage collection}
1694and cannot be set for a userdata with the default tag. 1651
1652Metatables also control some aspects of the garbage collector.
1653First, they are used to define \IndexEmph{finalizer} methods
1654for userdata values.
1695For each userdata to be collected, 1655For each userdata to be collected,
1696Lua does the equivalent of the following function: 1656Lua does the equivalent of the following function:
1697\begin{verbatim} 1657\begin{verbatim}
1698 function gc_event (obj) 1658 function gc_op (obj)
1699 local tm = gettagmethod(tag(obj), "gc") 1659 local h = metatable(obj).gc
1700 if tm then 1660 if h then
1701 tm(obj) 1661 h(obj)
1702 end 1662 end
1703 end 1663 end
1704\end{verbatim} 1664\end{verbatim}
1705In a garbage-collection cycle, 1665In a garbage-collection cycle,
1706the tag methods for userdata are called in \emph{reverse} 1666the finalizers for userdata are called in \emph{reverse}
1707order of type creation, 1667order of their creation,
1708that is, the first tag methods to be called are those associated 1668that is, the first finalizer to be called is the one associated
1709with the last type created in the program. 1669with the last userdata created in the program
1710Moreover, at the end of the cycle, 1670(among those to be collected in this cycle).
1711Lua does the equivalent of the call \verb|gc_event(nil)|. 1671
1712 1672Second, metatables control the weakmode of tables \see{weak-table}.
1713\end{description} 1673The weakmode of a table \verb|t| is defined by a string:
1714 1674\label{weakmode}
1675\begin{verbatim}
1676 s = metatable(t).weakmode
1677\end{verbatim}
1678Valid values for this string are \verb|"k"| for weak keys,
1679\verb|"v"| for weak values,
1680and \verb|"kv"| for both.
1715 1681
1716 1682
1717 1683
@@ -1799,9 +1765,12 @@ Each thread has an independent table for global variables.
1799When you create a thread, this table is the same as that of the given state, 1765When you create a thread, this table is the same as that of the given state,
1800but you can change each one independently. 1766but you can change each one independently.
1801 1767
1802You destroy threads with \verb|lua_close|. 1768You destroy threads with \DefAPI{lua_closethread}
1803When you destroy the last thread sharing a given state, 1769\begin{verbatim}
1804the state itself is also destroyed. 1770 void lua_closethread (lua_State *L, lua_State *thread);
1771\end{verbatim}
1772You cannot close the sole (or last) thread of a state.
1773Instead, you must close the state itself.
1805 1774
1806 1775
1807\subsection{The Stack and Indices} 1776\subsection{The Stack and Indices}
@@ -1879,9 +1848,10 @@ The API offers the following functions for basic stack manipulation:
1879 void lua_pushvalue (lua_State *L, int index); 1848 void lua_pushvalue (lua_State *L, int index);
1880 void lua_remove (lua_State *L, int index); 1849 void lua_remove (lua_State *L, int index);
1881 void lua_insert (lua_State *L, int index); 1850 void lua_insert (lua_State *L, int index);
1851 void lua_replace (lua_State *L, int index);
1882\end{verbatim} 1852\end{verbatim}
1883\DefAPI{lua_settop}\DefAPI{lua_pushvalue} 1853\DefAPI{lua_settop}\DefAPI{lua_pushvalue}
1884\DefAPI{lua_remove}\DefAPI{lua_insert} 1854\DefAPI{lua_remove}\DefAPI{lua_insert}\DefAPI{lua_replace}
1885 1855
1886\verb|lua_settop| accepts any acceptable index, 1856\verb|lua_settop| accepts any acceptable index,
1887or 0, 1857or 0,
@@ -1902,6 +1872,9 @@ at the given index.
1902shifting down the elements above that position to fill the gap. 1872shifting down the elements above that position to fill the gap.
1903\verb|lua_insert| moves the top element into the given position, 1873\verb|lua_insert| moves the top element into the given position,
1904shifting up the elements above that position to open space. 1874shifting up the elements above that position to open space.
1875\verb|lua_replace| moves the top element into the given position,
1876without shifting any element (therefore it replaces the value at
1877the given position).
1905These functions accept only valid indices. 1878These functions accept only valid indices.
1906(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
1907pseudo-indices, as they do not represent a stack position.) 1880pseudo-indices, as they do not represent a stack position.)
@@ -1916,8 +1889,9 @@ then
1916 lua_remove(L, 6) --> 10 20 30 40 30* 1889 lua_remove(L, 6) --> 10 20 30 40 30*
1917 lua_insert(L, 1) --> 30 10 20 30 40* 1890 lua_insert(L, 1) --> 30 10 20 30 40*
1918 lua_insert(L, -1) --> 30 10 20 30 40* (no effect) 1891 lua_insert(L, -1) --> 30 10 20 30 40* (no effect)
1919 lua_settop(L, -3) --> 30 10 20* 1892 lua_replace(L, 2) --> 30 40 20 30*
1920 lua_settop(L, 6) --> 30 10 20 nil nil nil* 1893 lua_settop(L, -3) --> 30 40 20*
1894 lua_settop(L, 6) --> 30 40 20 nil nil nil*
1921\end{verbatim} 1895\end{verbatim}
1922 1896
1923 1897
@@ -1927,10 +1901,9 @@ then
1927To check the type of a stack element, 1901To check the type of a stack element,
1928the following functions are available: 1902the following functions are available:
1929\begin{verbatim} 1903\begin{verbatim}
1930 int lua_tag (lua_State *L, int index); 1904 int lua_type (lua_State *L, int index);
1931 int lua_rawtag (lua_State *L, int index);
1932 const char *lua_type (lua_State *L, int index);
1933 int lua_isnil (lua_State *L, int index); 1905 int lua_isnil (lua_State *L, int index);
1906 int lua_isboolean (lua_State *L, int index);
1934 int lua_isnumber (lua_State *L, int index); 1907 int lua_isnumber (lua_State *L, int index);
1935 int lua_isstring (lua_State *L, int index); 1908 int lua_isstring (lua_State *L, int index);
1936 int lua_istable (lua_State *L, int index); 1909 int lua_istable (lua_State *L, int index);
@@ -1938,30 +1911,36 @@ the following functions are available:
1938 int lua_iscfunction (lua_State *L, int index); 1911 int lua_iscfunction (lua_State *L, int index);
1939 int lua_isuserdata (lua_State *L, int index); 1912 int lua_isuserdata (lua_State *L, int index);
1940\end{verbatim} 1913\end{verbatim}
1941\DefAPI{lua_type}\DefAPI{lua_tag} 1914\DefAPI{lua_type}
1942\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring} 1915\DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
1943\DefAPI{lua_istable} 1916\DefAPI{lua_istable}\DefAPI{lua_isboolean}
1944\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata} 1917\DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata}
1945These functions can be called with any acceptable index. 1918These functions can be called with any acceptable index.
1946 1919
1947\verb|lua_tag| returns the tag of a value in the stack, 1920\verb|lua_type| returns the type of a value in the stack,
1948or \verb|LUA_TNONE| for a non-valid index 1921or \verb|LUA_TNONE| for a non-valid index
1949(that is, if that stack position is ``empty''). 1922(that is, if that stack position is ``empty'').
1950The tags for the basic types are the following constants 1923The types are coded by the following constants
1951defined in \verb|lua.h|: 1924defined in \verb|lua.h|:
1952\verb|LUA_TNIL|, 1925\verb|LUA_TNIL|,
1953\verb|LUA_TNUMBER|, 1926\verb|LUA_TNUMBER|,
1927\verb|LUA_TBOOLEAN|,
1954\verb|LUA_TSTRING|, 1928\verb|LUA_TSTRING|,
1955\verb|LUA_TTABLE|, 1929\verb|LUA_TTABLE|,
1956\verb|LUA_TFUNCTION|, 1930\verb|LUA_TFUNCTION|,
1957\verb|LUA_TUSERDATA|. 1931\verb|LUA_TUSERDATA|.
1958\verb|lua_rawtag| is similar to \verb|lua_tag|, 1932The following function translates a tag to a type name:
1959but returns the tag of the basic (raw) type of a value. 1933\begin{verbatim}
1960\verb|lua_type| is similar to \verb|lua_tag|, 1934 const char *lua_type (lua_State *L, int index);
1961but returns the type name of the given value. 1935\end{verbatim}
1936\DefAPI{lua_typename}
1962 1937
1963The \verb|lua_is*| functions return~1 if the object is compatible 1938The \verb|lua_is*| functions return~1 if the object is compatible
1964with the given type, and 0 otherwise. 1939with the given type, and 0 otherwise.
1940(\verb|lua_isboolean| is an exception to this rule,
1941and it succeeds only for boolean values;
1942otherwise it would be useless,
1943as any value is compatible with a boolean.)
1965They always return 0 for a non-valid index. 1944They always return 0 for a non-valid index.
1966\verb|lua_isnumber| accepts numbers and numerical strings, 1945\verb|lua_isnumber| accepts numbers and numerical strings,
1967\verb|lua_isstring| accepts strings and numbers \see{coercion}, 1946\verb|lua_isstring| accepts strings and numbers \see{coercion},
@@ -1987,6 +1966,7 @@ Both functions return 0 if any of the indices are non-valid.
1987To translate a value in the stack to a specific C~type, 1966To translate a value in the stack to a specific C~type,
1988you can use the following conversion functions: 1967you can use the following conversion functions:
1989\begin{verbatim} 1968\begin{verbatim}
1969 int lua_toboolean (lua_State *L, int index);
1990 lua_Number lua_tonumber (lua_State *L, int index); 1970 lua_Number lua_tonumber (lua_State *L, int index);
1991 const char *lua_tostring (lua_State *L, int index); 1971 const char *lua_tostring (lua_State *L, int index);
1992 size_t lua_strlen (lua_State *L, int index); 1972 size_t lua_strlen (lua_State *L, int index);
@@ -1994,11 +1974,20 @@ you can use the following conversion functions:
1994 void *lua_touserdata (lua_State *L, int index); 1974 void *lua_touserdata (lua_State *L, int index);
1995\end{verbatim} 1975\end{verbatim}
1996\DefAPI{lua_tonumber}\DefAPI{lua_tostring}\DefAPI{lua_strlen} 1976\DefAPI{lua_tonumber}\DefAPI{lua_tostring}\DefAPI{lua_strlen}
1997\DefAPI{lua_tocfunction}\DefAPI{lua_touserdata} 1977\DefAPI{lua_tocfunction}\DefAPI{lua_touserdata}\DefAPI{lua_toboolean}
1998These functions can be called with any acceptable index. 1978These functions can be called with any acceptable index.
1999When called with a non-valid index, 1979When called with a non-valid index,
2000they act as if the given value had an incorrect type. 1980they act as if the given value had an incorrect type.
2001 1981
1982\verb|lua_toboolean| converts the Lua value at the given index
1983to a C ``boolean'' value (that is, (int)0 or (int)1).
1984Like all tests in Lua, it returns 1 for any Lua value different from
1985\False\ and \nil;
1986otherwise it returns 0.
1987It also returns 0 when called with a non-valid index.
1988(If you want to accept only real boolean values,
1989use \verb|lua_isboolean| to test the type of the value.)
1990
2002\verb|lua_tonumber| converts the Lua value at the given index 1991\verb|lua_tonumber| converts the Lua value at the given index
2003to a number (by default, \verb|lua_Number| is \verb|double|). 1992to a number (by default, \verb|lua_Number| is \verb|double|).
2004\DefAPI{lua_Number} 1993\DefAPI{lua_Number}
@@ -2043,6 +2032,7 @@ otherwise, \verb|lua_touserdata| returns \verb|NULL|.
2043The API has the following functions to 2032The API has the following functions to
2044push C~values onto the stack: 2033push C~values onto the stack:
2045\begin{verbatim} 2034\begin{verbatim}
2035 void lua_pushboolean (lua_State *L, int b);
2046 void lua_pushnumber (lua_State *L, lua_Number n); 2036 void lua_pushnumber (lua_State *L, lua_Number n);
2047 void lua_pushlstring (lua_State *L, const char *s, size_t len); 2037 void lua_pushlstring (lua_State *L, const char *s, size_t len);
2048 void lua_pushstring (lua_State *L, const char *s); 2038 void lua_pushstring (lua_State *L, const char *s);
@@ -2050,7 +2040,7 @@ push C~values onto the stack:
2050 void lua_pushcfunction (lua_State *L, lua_CFunction f); 2040 void lua_pushcfunction (lua_State *L, lua_CFunction f);
2051\end{verbatim} 2041\end{verbatim}
2052\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring} 2042\DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring}
2053\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag} 2043\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag}\DefAPI{lua_pushboolean}
2054\DefAPI{lua_pushnil}\label{pushing} 2044\DefAPI{lua_pushnil}\label{pushing}
2055These functions receive a C~value, 2045These functions receive a C~value,
2056convert it to a corresponding Lua value, 2046convert it to a corresponding Lua value,
@@ -2088,7 +2078,7 @@ If the new threshold is smaller than the byte counter,
2088then Lua immediately runs the garbage collector. 2078then Lua immediately runs the garbage collector.
2089In particular 2079In particular
2090\verb|lua_setgcthreshold(L,0)| forces a garbage collectiion. 2080\verb|lua_setgcthreshold(L,0)| forces a garbage collectiion.
2091After the collection, 2081After the collection,
2092a new threshold is set according to the previous rule. 2082a new threshold is set according to the previous rule.
2093%% TODO: What `previous rule'? 2083%% TODO: What `previous rule'?
2094 2084
@@ -2125,36 +2115,9 @@ it is up to you to free any associated memory,
2125setting a garbage-collection tag method, for instance. 2115setting a garbage-collection tag method, for instance.
2126 2116
2127 2117
2128\subsection{Types and Tags} 2118\subsection{Metatables}
2129 2119
2130User-defined types are created with the function 2120%% TODO
2131\begin{verbatim}
2132 int lua_newtype (lua_State *L, const char *name, int basictype);
2133\end{verbatim}
2134\DefAPI{lua_newtype}
2135where
2136\verb|name| is the name of the new type,
2137and \verb|basictype| is the basic type for objects with this new type,
2138which can be either \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|.
2139
2140The function \verb|lua_settag| changes the tag (i.e., the type) of
2141the object on top of the stack (without popping it):
2142\begin{verbatim}
2143 void lua_settag (lua_State *L, int tag);
2144\end{verbatim}
2145\DefAPI{lua_settag}
2146The given \verb|tag| must be a user-defined tag,
2147%% TODO: nao pode voltar ao tag original, ie basico?
2148and the basic type of the object must be the basic type for that
2149tag (userdata or table).
2150
2151The following functions allow you to translate a tag to a type name
2152and a type name to a tag:
2153\begin{verbatim}
2154 int lua_name2tag (lua_State *L, const char *name);
2155 const char *lua_tag2name (lua_State *L, int tag);
2156\end{verbatim}
2157\DefAPI{lua_name2tag}\DefAPI{lua_tag2name}
2158 2121
2159 2122
2160\subsection{Executing Lua Chunks}\label{luado} 2123\subsection{Executing Lua Chunks}\label{luado}
@@ -2240,50 +2203,6 @@ The compiled chunk is left as a function on top of the stack.
2240The return values are the same as those of 2203The return values are the same as those of
2241\verb|lua_dofile| and \verb|lua_dobuffer|. 2204\verb|lua_dofile| and \verb|lua_dobuffer|.
2242 2205
2243\subsection{Manipulating Global Variables} \label{globals}
2244
2245To read the value of a global Lua variable,
2246you call
2247\begin{verbatim}
2248 void lua_getglobal (lua_State *L, const char *varname);
2249\end{verbatim}
2250\DefAPI{lua_getglobal}
2251which pushes onto the stack the value of the given variable.
2252(The string \verb|varname| does not need to be a
2253syntactically valid variable name.)
2254As in Lua, this function may trigger a tag method
2255for the ``getglobal'' event \see{tag-method}.
2256To read the real value of a global variable,
2257without invoking any tag method,
2258use \verb|lua_rawget| over the table of globals
2259(see below).
2260
2261To store a value in a global variable,
2262you call
2263\begin{verbatim}
2264 void lua_setglobal (lua_State *L, const char *varname);
2265\end{verbatim}
2266\DefAPI{lua_setglobal}
2267which pops from the stack the value to be stored in the given variable.
2268(The string \verb|varname| does not need to be a
2269syntactically valid variable name.)
2270As in Lua, this function may trigger a tag method
2271for the ``setglobal'' event \see{tag-method}.
2272To set the real value of a global variable,
2273without invoking any tag method,
2274use \verb|lua_rawset| over the table of globals
2275(see below).
2276
2277All global variables are kept in an ordinary Lua table.
2278This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}.
2279To set another table as the table of globals,
2280you call
2281\begin{verbatim}
2282 void lua_setglobals (lua_State *L);
2283\end{verbatim}
2284\DefAPI{lua_setglobals}
2285The table to be used is popped from the stack.
2286
2287\subsection{Manipulating Tables} 2206\subsection{Manipulating Tables}
2288 2207
2289Tables are created by calling 2208Tables are created by calling
@@ -2371,18 +2290,20 @@ unless you know the key is actually a string.
2371Recall that \verb|lua_tostring| \emph{changes} the value at the given index; 2290Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
2372this confuses \verb|lua_next|. 2291this confuses \verb|lua_next|.
2373 2292
2374The following functions control the weak mode of a table: 2293\subsection{Manipulating Global Variables} \label{globals}
2294
2295All global variables are kept in an ordinary Lua table.
2296This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}.
2297
2298To access and change the value of global variables,
2299you can use regular table operations over the global table.
2300For instance, to access the value of a global variable, do
2375\begin{verbatim} 2301\begin{verbatim}
2376 void lua_setweakmode (lua_State *L, int mode); 2302 lua_pushstring(L, varname);
2377 int lua_getweakmode (lua_State *L, int index); 2303 lua_gettable(L, LUA_GLOBALSINDEX);
2378\end{verbatim} 2304\end{verbatim}
2379\DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode} 2305
2380Both functions operate over the table at the top of the stack. 2306You can change the global table of a Lua thread using \verb|lua_replace|.
2381Modes are described as bit sets, so that
2382\verb|LUA_WEAK_KEY| means weak keys,
2383\verb|LUA_WEAK_VALUE| means weak values, the combination
2384\verb"LUA_WEAK_KEY | LUA_WEAK_VALUE" means both,
2385and zero means none.
2386 2307
2387 2308
2388\subsection{Using Tables as Arrays} 2309\subsection{Using Tables as Arrays}
@@ -2450,25 +2371,32 @@ so that after the call the last result is on the top.
2450The following example shows how the host program may do the 2371The following example shows how the host program may do the
2451equivalent to the Lua code: 2372equivalent to the Lua code:
2452\begin{verbatim} 2373\begin{verbatim}
2453 a,b = f("how", t.x, 14) 2374 a = f("how", t.x, 14)
2454\end{verbatim} 2375\end{verbatim}
2455Here it is in~C: 2376Here it is in~C:
2456\begin{verbatim} 2377\begin{verbatim}
2457 lua_getglobal(L, "t"); /* global `t' (for later use) */ 2378 lua_pushstring(L, "t");
2458 lua_getglobal(L, "f"); /* function to be called */ 2379 lua_gettable(L, LUA_GLOBALSINDEX); /* global `t' (for later use) */
2380 lua_pushstring(L, "a"); /* var name */
2381 lua_pushstring(L, "f"); /* function name */
2382 lua_gettable(L, LUA_GLOBALSINDEX); /* function to be called */
2459 lua_pushstring(L, "how"); /* 1st argument */ 2383 lua_pushstring(L, "how"); /* 1st argument */
2460 lua_pushstring(L, "x"); /* push the string "x" */ 2384 lua_pushstring(L, "x"); /* push the string "x" */
2461 lua_gettable(L, -4); /* push result of t.x (2nd arg) */ 2385 lua_gettable(L, -5); /* push result of t.x (2nd arg) */
2462 lua_pushnumber(L, 14); /* 3rd argument */ 2386 lua_pushnumber(L, 14); /* 3rd argument */
2463 lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */ 2387 lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
2464 lua_setglobal(L, "b"); /* set global variable `b' */ 2388 lua_settable(L, LUA_GLOBALSINDEX); /* set global variable `a' */
2465 lua_setglobal(L, "a"); /* set global variable `a' */
2466 lua_pop(L, 1); /* remove `t' from the stack */ 2389 lua_pop(L, 1); /* remove `t' from the stack */
2467\end{verbatim} 2390\end{verbatim}
2468Notice that the code above is ``balanced'': 2391Notice that the code above is ``balanced'':
2469at its end, the stack is back to its original configuration. 2392at its end, the stack is back to its original configuration.
2470This is considered good programming practice. 2393This is considered good programming practice.
2471 2394
2395(We did this example using only the raw functions provided by Lua's API,
2396to show all the details.
2397Usually programmers use several macros and auxiliar functions that
2398provide higher level access to Lua.)
2399
2472\medskip 2400\medskip
2473 2401
2474%% TODO: mover essas 2 para algum lugar melhor. 2402%% TODO: mover essas 2 para algum lugar melhor.
@@ -2496,35 +2424,13 @@ The function
2496\end{verbatim} 2424\end{verbatim}
2497\DefAPI{lua_concat} 2425\DefAPI{lua_concat}
2498concatenates the \verb|n| values at the top of the stack, 2426concatenates the \verb|n| values at the top of the stack,
2499pops them, and leaves the result at the top; 2427pops them, and leaves the result at the top.
2500\verb|n|~must be at least 2. 2428If \verb|n| is 1, the result is that single string
2429(that is, the function does nothing);
2430if \verb|n| is 0, the result is the empty string.
2501Concatenation is done following the usual semantics of Lua 2431Concatenation is done following the usual semantics of Lua
2502\see{concat}. 2432\see{concat}.
2503 2433
2504\subsection{Manipulating Tag Methods}
2505Tag methods can be changed with
2506\begin{verbatim}
2507 void lua_settagmethod (lua_State *L, int tag, const char *event);
2508\end{verbatim}
2509\DefAPI{lua_settagmethod}
2510The second parameter is the tag,
2511and the third is the event name \see{tag-method};
2512the new method is popped from the stack.
2513To get the current value of a tag method,
2514use the function
2515\begin{verbatim}
2516 void lua_gettagmethod (lua_State *L, int tag, const char *event);
2517\end{verbatim}
2518\DefAPI{lua_gettagmethod}
2519
2520It is also possible to copy all tag methods from one tag
2521to another:
2522\begin{verbatim}
2523 int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
2524\end{verbatim}
2525\DefAPI{lua_copytagmethods}
2526This function returns \verb|tagto|.
2527
2528 2434
2529\subsection{Defining C Functions} \label{LuacallC} 2435\subsection{Defining C Functions} \label{LuacallC}
2530Lua can be extended with functions written in~C. 2436Lua can be extended with functions written in~C.
@@ -2569,7 +2475,10 @@ of numerical arguments and returns their average and sum:
2569To register a C~function to Lua, 2475To register a C~function to Lua,
2570there is the following convenience macro: 2476there is the following convenience macro:
2571\begin{verbatim} 2477\begin{verbatim}
2572 #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) 2478 #define lua_register(L,n,f) \
2479 (lua_pushstring(L, n), \
2480 lua_pushcfunction(L, f), \
2481 lua_settable(L, LUA_GLOBALSINDEX))
2573 /* const char *n; */ 2482 /* const char *n; */
2574 /* lua_CFunction f; */ 2483 /* lua_CFunction f; */
2575\end{verbatim} 2484\end{verbatim}
@@ -2704,7 +2613,8 @@ For instance, to know in which line a function \verb|f| was defined,
2704you can write 2613you can write
2705\begin{verbatim} 2614\begin{verbatim}
2706 lua_Debug ar; 2615 lua_Debug ar;
2707 lua_getglobal(L, "f"); 2616 lua_pushstring(L, "f");
2617 lua_gettable(L, LUA_GLOBALSINDEX); /* get global `f' */
2708 lua_getinfo(L, ">S", &ar); 2618 lua_getinfo(L, ">S", &ar);
2709 printf("%d\n", ar.linedefined); 2619 printf("%d\n", ar.linedefined);
2710\end{verbatim} 2620\end{verbatim}
@@ -2885,6 +2795,10 @@ implementation for some facilities.
2885without an \verb|_ERRORMESSAGE| function, 2795without an \verb|_ERRORMESSAGE| function,
2886Lua is unable to show error messages.) 2796Lua is unable to show error messages.)
2887 2797
2798The basic library also defines a global variable \IndexAPI{_VERSION}
2799with a string containing the current interpreter version.
2800The current content of this string is {\tt "Lua \Version"}.
2801
2888\subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert} 2802\subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert}
2889Prints its only string argument to \IndexVerb{stderr}. 2803Prints its only string argument to \IndexVerb{stderr}.
2890All error messages in Lua are printed through the function stored 2804All error messages in Lua are printed through the function stored
@@ -3027,13 +2941,6 @@ Returns the number of Kbytes of dynamic memory Lua is using,
3027and (as a second result) the 2941and (as a second result) the
3028current garbage collector threshold (also in Kbytes). 2942current garbage collector threshold (also in Kbytes).
3029 2943
3030\subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal}
3031Gets the value of a global variable,
3032possibly via a ``getglobal'' tag method.
3033Its full semantics is explained in \See{tag-method}.
3034The string \verb|name| does not need to be a
3035syntactically valid variable name.
3036
3037\subsubsection*{\ff \T{getn (table)}}\DefLIB{getn}\label{getn} 2944\subsubsection*{\ff \T{getn (table)}}\DefLIB{getn}\label{getn}
3038Returns the ``size'' of a table, when seen as a list. 2945Returns the ``size'' of a table, when seen as a list.
3039If the table has an \verb|n| field with a numeric value, 2946If the table has an \verb|n| field with a numeric value,
@@ -3052,13 +2959,6 @@ This function is equivalent to the following Lua function:
3052 end 2959 end
3053\end{verbatim} 2960\end{verbatim}
3054 2961
3055\subsubsection*{\ff \T{gettagmethod (tag, event)}}
3056\DefLIB{gettagmethod}
3057Returns the current tag method
3058for a given pair \M{(tag, event)}.
3059This function cannot be used to get a tag method for the ``gc'' event.
3060(``gc'' tag methods can only be manipulated by C~code.)
3061
3062\subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals} 2962\subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals}
3063Returns the current table of globals. 2963Returns the current table of globals.
3064If the argument \verb|table| is given, 2964If the argument \verb|table| is given,
@@ -3127,50 +3027,17 @@ without invoking any tag method.
3127\verb|index| is any value different from \nil; 3027\verb|index| is any value different from \nil;
3128and \verb|value| is any Lua value. 3028and \verb|value| is any Lua value.
3129 3029
3130\subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype}
3131Returns the basic (raw) type of its only argument, coded as a string.
3132The possible results of this function are
3133\verb|"nil"| (a string, not the value \nil),
3134\verb|"number"|,
3135\verb|"string"|,
3136\verb|"table"|,
3137\verb|"function"|,
3138and \verb|"userdata"|.
3139
3140\subsubsection*{\ff \T{require (module)}}\DefLIB{require} 3030\subsubsection*{\ff \T{require (module)}}\DefLIB{require}
3141 3031
3142TO BE WRITTEN. 3032TO BE WRITTEN.
3143 3033
3144\subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal}
3145Sets the named global variable to the given value,
3146possibly via a ``setglobal'' tag method.
3147Its full semantics is explained in \See{tag-method}.
3148The string \verb|name| does not need to be a
3149syntactically valid variable name.
3150
3151\subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype}
3152Sets the type of a given table \see{TypesSec}.
3153\verb|type| must be the name or the tag of a user-defined type.
3154\verb|settype| returns the value of its first argument (the table).
3155For the safety of host programs,
3156you can only change the type of userdata from~C, not from Lua.
3157
3158\subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}}
3159\DefLIB{settagmethod}
3160Sets a new tag method to the given pair \M{(tag, event)} and
3161returns the old method.
3162If \verb|newmethod| is \nil,
3163then \verb|settagmethod| restores the default behavior for the given event.
3164This function cannot be used to set a tag method for the ``gc'' event.
3165(``gc'' tag methods can only be manipulated by C~code.)
3166
3167\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} 3034\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort}
3168Sorts table elements in a given order, \emph{in-place}, 3035Sorts table elements in a given order, \emph{in-place},
3169from \verb|table[1]| to \verb|table[n]|, 3036from \verb|table[1]| to \verb|table[n]|,
3170where \verb|n| is the result of \verb|getn(table)| \see{getn}. 3037where \verb|n| is the result of \verb|getn(table)| \see{getn}.
3171If \verb|comp| is given, 3038If \verb|comp| is given,
3172then it must be a function that receives two table elements, 3039then it must be a function that receives two table elements,
3173and returns true (that is, a value different from \nil) 3040and returns true
3174when the first is less than the second 3041when the first is less than the second
3175(so that \verb|not comp(a[i+1],a[i])| will be true after the sort). 3042(so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
3176If \verb|comp| is not given, 3043If \verb|comp| is not given,
@@ -3180,10 +3047,6 @@ The sort algorithm is \emph{not} stable
3180(that is, elements considered equal by the given order 3047(that is, elements considered equal by the given order
3181may have their relative positions changed by the sort). 3048may have their relative positions changed by the sort).
3182 3049
3183\subsubsection*{\ff \T{tag (v)}}\DefLIB{tag}\label{pdf-tag}
3184Returns the tag of a value \see{TypesSec}.
3185Tags are integers.
3186
3187\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} 3050\subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
3188Tries to convert its argument to a number. 3051Tries to convert its argument to a number.
3189If the argument is already a number or a string convertible 3052If the argument is already a number or a string convertible
@@ -3215,25 +3078,6 @@ so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end
3215of table \verb|t|. 3078of table \verb|t|.
3216This function also sets or increments the field \verb|n| of the table 3079This function also sets or increments the field \verb|n| of the table
3217to \verb|n+1|. 3080to \verb|n+1|.
3218This function is equivalent to the following Lua function,
3219except that the table accesses in \verb|tinsert| are all \emph{raw}
3220(that is, without tag methods):
3221\begin{verbatim}
3222 function tinsert (t, ...)
3223 local pos, value
3224 local n = getn(t)
3225 if arg.n == 1 then
3226 pos, value = n+1, arg[1]
3227 else
3228 pos, value = arg[1], arg[2]
3229 end
3230 t.n = n+1;
3231 for i=n,pos,-1 do
3232 t[i+1] = t[i]
3233 end
3234 t[pos] = value
3235 end
3236\end{verbatim}
3237 3081
3238\subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove} 3082\subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove}
3239 3083
@@ -3246,28 +3090,16 @@ so that a call \verb|tremove(t)| removes the last element
3246of table \verb|t|. 3090of table \verb|t|.
3247This function also sets or decrements the field \verb|n| of the table 3091This function also sets or decrements the field \verb|n| of the table
3248to \verb|n-1|. 3092to \verb|n-1|.
3249This function is equivalent to the following Lua function,
3250except that the table accesses in \verb|tremove| are all \emph{raw}
3251(that is, without tag methods):
3252\begin{verbatim}
3253 function tremove (t, pos)
3254 local n = getn(t)
3255 if n<=0 then return end
3256 pos = pos or n
3257 local value = t[pos]
3258 for i=pos,n-1 do
3259 t[i] = t[i+1]
3260 end
3261 t[n] = nil
3262 t.n = n-1
3263 return value
3264 end
3265\end{verbatim}
3266 3093
3267\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} 3094\subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
3268Returns the type name of a value. 3095Returns the type of its only argument, coded as a string.
3269Type names are strings and are set with \verb|settype| for user-defined types. 3096The possible results of this function are
3270For other types, \verb|type| is equivalent to \verb|rawtype|. 3097\verb|"nil"| (a string, not the value \nil),
3098\verb|"number"|,
3099\verb|"string"|,
3100\verb|"table"|,
3101\verb|"function"|,
3102and \verb|"userdata"|.
3271 3103
3272\subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack} 3104\subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack}
3273Returns all elements from the given list. 3105Returns all elements from the given list.
@@ -3279,18 +3111,6 @@ except that the above code can be valid only for a fixed \M{n}.
3279The number \M{n} of returned values 3111The number \M{n} of returned values
3280is the result of \verb|getn(list)| \seepage{getn}. 3112is the result of \verb|getn(list)| \seepage{getn}.
3281 3113
3282\subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode}
3283
3284Controls the weakness of a table.
3285When \verb|mode| is \verb|"?"|,
3286\verb|weakmode| returns the current mode of the table, as a string;
3287otherwise, it sets the weakmode of the table to the given mode (also a string).
3288Valid mode strings are \verb|"k"| for weak keys,
3289\verb|"v"| for weak values,
3290\verb|"kv"| for both,
3291and \verb|""| for none (that is, for ``normal'' tables).
3292
3293
3294\subsection{String Manipulation} 3114\subsection{String Manipulation}
3295This library provides generic functions for string manipulation, 3115This library provides generic functions for string manipulation,
3296such as finding and extracting substrings and pattern matching. 3116such as finding and extracting substrings and pattern matching.
@@ -3328,7 +3148,7 @@ the captured strings are returned as extra results.
3328A third, optional numerical argument \verb|init| specifies 3148A third, optional numerical argument \verb|init| specifies
3329where to start the search; 3149where to start the search;
3330its default value is~1, and may be negative. 3150its default value is~1, and may be negative.
3331A value of~1 as a fourth, optional argument \verb|plain| 3151A value of \True\ as a fourth, optional argument \verb|plain|
3332turns off the pattern matching facilities, 3152turns off the pattern matching facilities,
3333so the function does a plain ``find substring'' operation, 3153so the function does a plain ``find substring'' operation,
3334with no characters in \verb|pattern| being considered ``magic''. 3154with no characters in \verb|pattern| being considered ``magic''.
@@ -3867,7 +3687,7 @@ and \verb|isdst| (daylight saving flag).
3867 3687
3868If format is not \verb|*t|, 3688If format is not \verb|*t|,
3869then \verb|date| returns the date as a string, 3689then \verb|date| returns the date as a string,
3870formatted according with the same rules of the C~function \verb|strftime|. 3690formatted according with the same rules as the C~function \verb|strftime|.
3871When called without arguments, 3691When called without arguments,
3872\verb|date| returns a reasonable date and time representation that depends on 3692\verb|date| returns a reasonable date and time representation that depends on
3873the host system and on the current locale (thus, \verb|date()| is equivalent 3693the host system and on the current locale (thus, \verb|date()| is equivalent
@@ -3960,7 +3780,7 @@ with the string \verb|what| describing what to get.
3960The default for \verb|what| is to get all information available. 3780The default for \verb|what| is to get all information available.
3961If present, 3781If present,
3962the option \verb|f| 3782the option \verb|f|
3963adds a field named \verb|func| with the function itself. 3783adds a field named \verb|func| with the function itself.
3964 3784
3965For instance, the expression \verb|getinfo(1,"n").name| returns 3785For instance, the expression \verb|getinfo(1,"n").name| returns
3966the name of the current function, if a reasonable name can be found, 3786the name of the current function, if a reasonable name can be found,
@@ -4139,7 +3959,7 @@ Here is a list of all these incompatibilities.
4139Function calls written between parentheses result in exactly one value. 3959Function calls written between parentheses result in exactly one value.
4140 3960
4141\item 3961\item
4142A function call as the last expression in a list constructor 3962A function call as the last expression in a list constructor
4143(like \verb|{a,b,f()}}|) has all its return values inserted in the list. 3963(like \verb|{a,b,f()}}|) has all its return values inserted in the list.
4144 3964
4145\item 3965\item
@@ -4211,28 +4031,26 @@ The \verb|lua_pushuserdata| function has been replaced by
4211 \opt{\rwd{else} block} \rwd{end} 4031 \opt{\rwd{else} block} \rwd{end}
4212\OrNL \rwd{return} \opt{explist1} 4032\OrNL \rwd{return} \opt{explist1}
4213\OrNL \rwd{break} 4033\OrNL \rwd{break}
4214\OrNL \rwd{for} \Nter{name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp} 4034\OrNL \rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
4215 \rwd{do} block \rwd{end} 4035 \rwd{do} block \rwd{end}
4216\OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp 4036\OrNL \rwd{for} \Nter{Name} \opt{\ter{,} \Nter{Name}} \rwd{in} exp
4217 \rwd{do} block \rwd{end} 4037 \rwd{do} block \rwd{end}
4218\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} 4038\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
4219\OrNL \rwd{local} namelist \opt{init} 4039\OrNL \rwd{local} namelist \opt{init}
4220} 4040}
4221 4041
4222\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} 4042\produc{funcname}{\Nter{Name} \rep{\ter{.} \Nter{Name}}
4223 \opt{\ter{:} \Nter{name}}} 4043 \opt{\ter{:} \Nter{Name}}}
4224 4044
4225\produc{varlist1}{var \rep{\ter{,} var}} 4045\produc{varlist1}{var \rep{\ter{,} var}}
4226 4046
4227\produc{var}{% 4047\produc{var}{%
4228 \Nter{name} 4048 \Nter{Name}
4229\Or varorfunc \ter{[} exp \ter{]} 4049\Or prefixexp \ter{[} exp \ter{]}
4230\Or varorfunc \ter{.} \Nter{name} 4050\Or prefixexp \ter{.} \Nter{Name}
4231} 4051}
4232 4052
4233\produc{varorfunc}{var \Or functioncall} 4053\produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
4234
4235\produc{namelist}{\Nter{name} \rep{\ter{,} \Nter{name}}}
4236 4054
4237\produc{init}{\ter{=} explist1} 4055\produc{init}{\ter{=} explist1}
4238 4056
@@ -4240,65 +4058,48 @@ The \verb|lua_pushuserdata| function has been replaced by
4240 4058
4241\produc{exp}{% 4059\produc{exp}{%
4242 \rwd{nil} 4060 \rwd{nil}
4243\Or \Nter{number} 4061\Or \Nter{Number}
4244\Or \Nter{literal} 4062\Or \Nter{Literal}
4245\Or var
4246\Or function 4063\Or function
4247\Or upvalue 4064\Or prefixexp
4248\OrNL functioncall 4065\OrNL tableconstructor
4249\Or tableconstructor
4250\Or \ter{(} exp \ter{)}
4251\Or exp binop exp 4066\Or exp binop exp
4252\Or unop exp 4067\Or unop exp
4253} 4068}
4254 4069
4070\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
4255 4071
4256\produc{functioncall}{% 4072\produc{functioncall}{%
4257 varorfunc args 4073 prefixexp args
4258\Or varorfunc \ter{:} \Nter{name} args 4074\Or prefixexp \ter{:} \Nter{Name} args
4259} 4075}
4260 4076
4261\produc{args}{% 4077\produc{args}{%
4262 \ter{(} \opt{explist1} \ter{)} 4078 \ter{(} \opt{explist1} \ter{)}
4263\Or tableconstructor 4079\Or tableconstructor
4264\Or \Nter{literal} 4080\Or \Nter{Literal}
4265} 4081}
4266 4082
4267\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}} 4083\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
4268 4084
4269\produc{parlist1}{% 4085\produc{parlist1}{%
4270 \ter{\ldots} 4086 \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}}
4271\Or \Nter{name} \rep{\ter{,} \Nter{name}} \opt{\ter{,} \ter{\ldots}} 4087\Or \ter{\ldots}
4272} 4088}
4273 4089
4274\produc{upvalue}{\ter{\%} \Nter{name}} 4090\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
4275 4091\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
4276\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} 4092\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp}
4277\produc{fieldlist}{% 4093\produc{fieldsep}{\ter{,} \Or \ter{;}}
4278 lfieldlist
4279\Or ffieldlist
4280\Or lfieldlist \ter{;} ffieldlist
4281\Or ffieldlist \ter{;} lfieldlist
4282}
4283\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}}
4284\produc{ffieldlist}{\opt{ffieldlist1}}
4285\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
4286\produc{ffield}{%
4287 \ter{[} exp \ter{]} \ter{=} exp
4288\Or \Nter{name} \ter{=} exp
4289}
4290 4094
4291\produc{binop}{\ter{+} \Or \ter{-} \Or \ter{*} \Or \ter{/} \Or \ter{\^{ }} \Or 4095\produc{binop}{\ter{+} \Or \ter{-} \Or \ter{*} \Or \ter{/} \Or \ter{\^{ }} \Or
4292 \ter{..} \OrNL \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=} 4096 \ter{..} \Or \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=}
4293 \Or \ter{==} \Or \ter{\~{ }=} \OrNL \rwd{and} \Or \rwd{or}} 4097 \Or \ter{==} \Or \ter{\~{ }=} \OrNL \rwd{and} \Or \rwd{or}}
4294 4098
4295\produc{unop}{\ter{-} \Or \rwd{not}} 4099\produc{unop}{\ter{-} \Or \rwd{not}}
4296 4100
4297\end{Produc} 4101\end{Produc}
4298 4102
4299
4300\NOTE
4301This grammar is not (yet) consistent with the productions in the text.
4302%}=============================================================== 4103%}===============================================================
4303 4104
4304% Index 4105% Index