From e966dd93be46f34bb335f09f38b4ab1777ace5f5 Mon Sep 17 00:00:00 2001
From: Roberto Ierusalimschy <roberto@inf.puc-rio.br>
Date: Thu, 14 Feb 2002 19:48:32 -0200
Subject: towards next version...

---
 manual.tex | 1149 +++++++++++++++++++++++++-----------------------------------
 1 file changed, 475 insertions(+), 674 deletions(-)

(limited to 'manual.tex')

diff --git a/manual.tex b/manual.tex
index 7992baf5..9dcd09da 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
-% $Id: manual.tex,v 1.53 2001/10/31 18:06:05 roberto Exp roberto $
+% $Id: manual.tex,v 1.54 2001/10/31 20:31:38 roberto Exp $
 
 \documentclass[11pt,twoside,draft]{article}
 \usepackage{fullpage}
@@ -17,6 +17,8 @@
 \newcommand{\T}[1]{{\tt #1}}
 \newcommand{\Math}[1]{$#1$}
 \newcommand{\nil}{{\bf nil}}
+\newcommand{\False}{{\bf false}}
+\newcommand{\True}{{\bf true}}
 %\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
 \def\tecgraf{{\sf TeCGraf}}
 
@@ -33,7 +35,7 @@
 
 \newcommand{\ff}{$\bullet$\ }
 
-\newcommand{\Version}{4.1 (alpha)}
+\newcommand{\Version}{4.1 (beta)}
 
 % changes to bnf.sty by LHF
 \renewcommand{\Or}{$|$ }
@@ -138,7 +140,7 @@ Waldemar Celes
 \tecgraf\ --- Computer Science Department --- PUC-Rio
 }
 
-%\date{{\small \tt\$Date: 2001/10/31 18:06:05 $ $}}
+%\date{{\small \tt\$Date: 2001/10/31 20:31:38 $ $}}
 
 \maketitle
 
@@ -157,7 +159,7 @@ powerful data description constructs
 based on associative arrays and extensible semantics.
 Lua is
 dynamically typed,
-interpreted from bytecodes,
+interpreted from opcodes,
 and has automatic memory management with garbage collection,
 making it ideal for
 configuration,
@@ -184,7 +186,7 @@ poderosas constru\c{c}\~oes para descri\c{c}\~ao de dados,
 baseadas em tabelas associativas e sem\^antica extens\'\i vel.
 Lua \'e
 tipada dinamicamente,
-interpretada a partir de \emph{bytecodes},
+interpretada a partir de \emph{opcodes},
 e tem gerenciamento autom\'atico de mem\'oria com coleta de lixo.
 Essas caracter\'{\i}sticas fazem de Lua uma linguagem ideal para
 configura\c{c}\~ao,
@@ -289,7 +291,7 @@ which are executed sequentially.
 Statements are described in \See{stats}.
 
 A chunk may be stored in a file or in a string inside the host program.
-When a chunk is executed, first it is pre-compiled into bytecodes for
+When a chunk is executed, first it is pre-compiled into opcodes for
 a virtual machine,
 and then the compiled statements are executed
 by an interpreter for the virtual machine.
@@ -312,10 +314,15 @@ variables do not have types; only values do.
 Therefore, there are no type definitions in the language.
 All values carry their own type.
 
-There are six \Index{basic types} in Lua: \Def{nil}, \Def{number},
+There are seven \Index{basic types} in Lua:
+\Def{nil}, \Def{boolean}, \Def{number},
 \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}.
 \emph{Nil} is the type of the value \nil,
-whose main property is to be different from any other value.
+whose main property is to be different from any other value;
+usually it represents the absence of a useful value.
+\emph{Boolean} is the type of the values \False and \True.
+In Lua, both \nil{} and \False make a condition fails,
+and any other value makes it succeeds.
 \emph{Number} represents real (double-precision floating-point) numbers.
 \emph{String} represents arrays of characters.
 \index{eight-bit clean}
@@ -335,9 +342,9 @@ arbitrary \Index{C~pointers} to be stored in Lua variables.
 This type corresponds to a \verb|void*|
 and has no pre-defined operations in Lua,
 except assignment and equality test.
-However, by using \emph{tag methods},
+However, by using \emph{metatables},
 the programmer can define operations for userdata values
-\see{tag-method}.
+\see{metatables}.
 Userdata values cannot be created or modified in Lua,
 only through the C~API.
 This guarantees the integrity of data owned by the host program.
@@ -348,7 +355,7 @@ but with any value (except \nil).
 Moreover,
 tables are \emph{heterogeneous},
 that is, they can contain values of all types.
-Tables are the main data structuring mechanism in Lua;
+Tables are the sole data structuring mechanism in Lua;
 they may be used not only to represent ordinary arrays,
 but also symbol tables, sets, records, graphs, trees, etc.
 To represent \Index{records}, Lua uses the field name as an index.
@@ -366,49 +373,42 @@ So, tables may also carry \emph{methods}.
 %which calls the method \verb|f| from the table \verb|t| passing
 %the table itself as the first parameter \see{func-def}.
 
-Strings, tables, functions, and userdata values are \emph{objects}:
+Tables, functions, and userdata values are \emph{objects}:
 variables do not actually \emph{contain} these values,
 only \emph{references} to them.
 Assignment, parameter passing, and returns from functions
-always manipulate references to these values, and do not imply any kind of copy.
+always manipulate references to these values,
+and do not imply any kind of copy.
 
 The library function \verb|type| returns a string describing the type
 of a given value \see{pdf-type}.
 
-\subsubsection{Tags}\label{tags}
-
-Each type is denoted both by a \emph{name},
-which is a string,
-and a \IndexEmph{tag},
-which is an integer.
-Tags are mainly used by C~code,
-to avoid the manipulation of strings.
-In the C~API,
-most operations over types require a tag to identify the type.
-In Lua, all operations over types work transparently
-with both type names and tags.
-The \verb|tag| function returns the tag of a given value \see{pdf-tag}.
-
-
-\subsubsection{User-defined Types}
-
-Lua programs can create new types,
-called \IndexEmph{user-defined types}.
-A user-defined type is always based on a base type,
-which can be either table or userdata.
-Objects of a user-defined type have an internal structure
-identical to the corresponding base type,
-but the programmer may define different semantics for each operation on them
-\see{tag-method}.
+\subsubsection{Metatables}
+
+Each table or userdata object in Lua may have a \Index{metatable}.
+
+You can change several aspects of the behavior
+of an object by setting specific fields in its metatable.
+For instance, when an object is the operand of an addition,
+Lua checks for a function in the field \verb|"add"| in its metatable.
+If it finds one,
+Lua calls that function to perform the addition.
+
+A metatable works as a kind of an extended ``type'' for the object.
+Objects that share a metatable has identical behavior.
+
+A metatable controls how an object behaves in arithmetic operations,
+order comparisons, concatenation, and indexing.
+A metatable can also defines a function to be called when a userdata
+is garbage collected,
+and how the garbage collector treats entries in a table
+\see{weak-table}.
+\See{metatable} gives a detailed description of which events you
+can control with metatables.
+
+You can query and change the metatable of an object
+through the \verb|metatable| function \see{pdf-metatable}.
 
-The \verb|newtype| function creates a new type \see{pdf-newtype}
-with a name selected by the programmer.
-Types created by Lua programs are always based on tables;
-types created in~C can be based on tables or on userdata.
-The \verb|settagmethod| function defines new semantics for
-the operations of this new type \see{tag-method}.
-The \verb|settype| function changes the type of a given object
-\see{pdf-settype}.
 
 
 \subsection{\Index{Coercion}} \label{coercion}
@@ -421,7 +421,6 @@ the number is converted to a string, in a reasonable format.
 The format is chosen so that
 a conversion from number to string then back to number
 reproduces the original number \emph{exactly}.
-The conversion does not necessarily produces nice-looking text for some numbers.
 For complete control of how numbers are converted to strings,
 use the \verb|format| function \see{format}.
 
@@ -445,6 +444,7 @@ This table can be accessed and changed with the \verb|globals| function
 Therefore, local variables can be freely accessed by functions
 defined inside their scope \see{visibility}.
 
+
 \subsection{Garbage Collection}\label{GC}
 
 Lua does automatic memory management.
@@ -464,7 +464,7 @@ you can set garbage-collector tag methods for user-defined
 types based on userdata \see{tag-method}.
 Lua calls those functions when it is about to free a userdata
 of the corresponding type.
-Using this facility, you can coordinate Lua's garbage collection 
+Using this facility, you can coordinate Lua's garbage collection
 with external resource management
 (such as closing files, network or database connections,
 or freeing your own memory).
@@ -488,7 +488,7 @@ through the functions \verb|gcinfo| and \verb|collectgarbage|
 \see{predefined}.
 
 
-\subsection{Weak Tables}\label{weak-table}
+\subsubsection{Weak Tables}\label{weak-table}
 
 A \IndexEmph{weak table} is a table whose elements are
 \IndexEmph{weak references}.
@@ -505,7 +505,7 @@ both keys and values
 In any case, if either the key or the value is collected,
 the whole pair is removed from the table.
 The weakness of a table is controled by the
-\verb|weakmode| function \see{weakmode}.
+\verb|weakmode| field in its metatable \see{weakmode}.
 
 
 %------------------------------------------------------------------------------
@@ -533,15 +533,12 @@ and cannot be used as identifiers:
 \index{reserved words}
 \begin{verbatim}
        and       break     do        else      elseif
-       end       for       function  global    if
-       in        local     nil       not       or
-       repeat    return    then      until     while
+       end       false     for       function  global
+       if        in        local     nil       not
+       or        repeat    return    then      true
+       until     while
 \end{verbatim}
 (The keyword \rwd{global} is reserved for future use.)
-%\IndexKW{and}\IndexKW{break}\IndexKW{do}\IndexKW{else}\IndexKW{elseif}
-%\IndexKW{end}\IndexKW{for}\IndexKW{function}\IndexKW{global}\IndexKW{if}
-%\IndexKW{in}\IndexKW{local}\IndexKW{nil}\IndexKW{not}\IndexKW{or}
-%\IndexKW{repeat}\IndexKW{return}\IndexKW{then}\IndexKW{until}\IndexKW{while}
 
 Lua is a case-sensitive language:
 \T{and} is a reserved word, but \T{And} and \T{\'and}
@@ -552,7 +549,7 @@ are reserved for internal variables.
 
 The following strings denote other \Index{tokens}:
 \begin{verbatim}
-       +     -     *     /     ^     %    
+       +     -     *     /     ^     %
        ~=    <=    >=    <     >     ==    =
        (     )     {     }     [     ]
        ;     :     ,     .     ..    ...
@@ -590,8 +587,8 @@ This form is specially convenient for
 writing strings that contain program pieces or
 other quoted strings.
 As an example, in a system using ASCII
-(in which
-`\verb|a|' is coded as~97, newline is coded as~10, and `\verb|1|' is coded as~49),
+(in which `\verb|a|' is coded as~97,
+newline is coded as~10, and `\verb|1|' is coded as~49),
 the following four literals below are equivalent:
 \begin{verbatim}
        1)   "alo\n123\""
@@ -633,32 +630,34 @@ or a formal parameter in a function
 
 Square brackets are used to index a table:
 \begin{Produc}
-\produc{var}{exp \ter{[} exp \ter{]}}
+\produc{var}{prefixexp \ter{[} exp \ter{]}}
 \end{Produc}%
 The first expression should result in a table value,
-and the second expression identifies the specific place inside that table.
+and the second expression identifies a specific entry inside that table.
 
 The syntax \verb|var.NAME| is just syntactic sugar for
 \verb|var["NAME"]|:
 \begin{Produc}
-\produc{var}{exp \ter{.} name}
+\produc{var}{prefixexp \ter{.} name}
 \end{Produc}%
-Expressions are discussed in \See{expressions}.
 
-The meaning of assignments and evaluations of global variables and
-indexed variables can be changed by tag methods \see{tag-method}.
+The expression denoting the table to be indexed has a restricted syntax;
+\See{expressions} for details.
+
+The meaning of assignments and evaluations of global and
+indexed variables can be changed via metatables.
 An assignment to a global variable \verb|x = val|
-is equivalent to a call \verb|setglobal("x", val)| and
-an assignment to an indexed variable \verb|t[i] = val| is equivalent to
+is equivalent to an assignment in the global table:
+\verb|globals().x = val|.
+An assignment to an indexed variable \verb|t[i] = val| is equivalent to
 \verb|settable_event(t,i,val)|.
 An access to a global variable \verb|x|
-is equivalent to a call \verb|getglobal("x")| and
-an access to an indexed variable \verb|t[i]| is equivalent to
+is equivalent to an access to the global table: \verb|globals().x|.
+An access to an indexed variable \verb|t[i]| is equivalent to
 a call \verb|gettable_event(t,i)|.
-See \See{tag-method} for a complete description of these functions
-(\verb|setglobal| and \verb|getglobal| are in the basic library;
-\T{settable\_event} and \T{gettable\_event}
-are used for explanatory purposes only).
+See \See{metatable} for a complete description of these functions.
+(These functions are not defined in Lua.
+We use them here only for explanatory purposes.)
 
 
 \subsection{Statements}\label{stats}
@@ -701,6 +700,7 @@ A block may be explicitly delimited:
 \begin{Produc}
 \produc{stat}{\rwd{do} block \rwd{end}}
 \end{Produc}%
+\IndexKW{do}
 Explicit blocks are useful
 to control the scope of local variables \see{localvar}.
 Explicit blocks are also sometimes used to
@@ -732,9 +732,8 @@ then all values returned by that function call enter in the list of values,
 before the adjust
 (except when the call is enclosed in parentheses; see \See{expressions}).
 
-This statement first evaluates all values on the right side
-and eventual indices on the left side,
-and then makes the assignments.
+The assignment statement first evaluates all its expressions,
+and only then makes the assignments.
 So, the code
 \begin{verbatim}
        i = 3
@@ -743,19 +742,19 @@ So, the code
 sets \verb|a[3]| to 20, but does not affect \verb|a[4]|
 because the \verb|i| in \verb|a[i]| is evaluated
 before it is assigned 4.
-
-Multiple assignment can be used to exchange two values, as in
+Similarly, the line
 \begin{verbatim}
        x, y = y, x
 \end{verbatim}
+exchanges the values of \verb|x| and \verb|y|.
 
 \subsubsection{Control Structures}\label{control}
 The control structures
 \rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and
 familiar syntax:
-\index{while-do statement}
-\index{repeat-until statement}
-\index{if-then-else statement}
+\index{while-do statement}\IndexKW{while}
+\index{repeat-until statement}\IndexKW{repeat}\IndexKW{until}
+\index{if-then-else statement}\IndexKW{if}\IndexKW{else}\IndexKW{elseif}
 \begin{Produc}
 \produc{stat}{\rwd{while} exp \rwd{do} block \rwd{end}}
 \produc{stat}{\rwd{repeat} block \rwd{until} exp}
@@ -767,11 +766,11 @@ There is also a \rwd{for} statement in two flavors \see{for}.
 
 The \Index{condition expression} \M{exp} of a
 control structure may return any value.
-All values different from \nil\ are considered true;
-only \nil\ is considered false.
+All values different from \nil\ and \False\ are considered true;
+both \False\ and \nil\ are considered false.
 
 The \rwd{return} statement is used to return values
-from a function or from a chunk.
+from a function or from a chunk.\IndexKW{return}
 \label{return}%
 \index{return statement}%
 Functions and chunks may return more than one value,
@@ -782,7 +781,7 @@ and so the syntax for the \rwd{return} statement is
 
 The \rwd{break} statement can be used to terminate the execution of a
 \rwd{while}, \rwd{repeat}, or \rwd{for} loop,
-skipping to the next statement after the loop:
+skipping to the next statement after the loop:\IndexKW{break}
 \index{break statement}
 \begin{Produc}
 \produc{stat}{\rwd{break}}
@@ -791,26 +790,29 @@ A \rwd{break} ends the innermost enclosing loop.
 
 \NOTE
 For syntactic reasons, \rwd{return} and \rwd{break}
-statements can only be written as the \emph{last} statements of a block.
+statements can only be written as the \emph{last} statement of a block.
 If it is really necessary to \rwd{return} or \rwd{break} in the
 middle of a block,
 then an explicit inner block can used,
 as in the idioms
 `\verb|do return end|' and
 `\verb|do break end|',
-because now \rwd{return} and \rwd{break} are last statements in the inner block.
+because now \rwd{return} and \rwd{break} are the last statements in
+their (inner) blocks.
 In practice,
 these idioms are only used during debugging.
-(The idiom `\verb|do return end|' can be added at the beginning of a chunk
-for syntax checking only.)
+(For instance, a line `\verb|do return end|' can be added at the
+beginning of a chunk for syntax checking only.)
 
 \subsubsection{For Statement} \label{for}\index{for statement}
 
 The \rwd{for} statement has two forms,
-one for numbers and one for tables.
+one for numbers and one generic.
+\IndexKW{for}\IndexKW{in}
 
-The numerical \rwd{for} loop
-repeats a block of code while a control variables runs through an arithmetic progression. It has the following syntax:
+The numerical \rwd{for} loop repeats a block of code while a
+control variables runs through an arithmetic progression.
+It has the following syntax:
 \begin{Produc}
 \produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
                     \rwd{do} block \rwd{end}}
@@ -835,13 +837,13 @@ is equivalent to the code:
 \end{verbatim}
 Note the following:
 \begin{itemize}\itemsep=0pt
+\item Both the limit and the step are evaluated only once,
+before the loop starts.
 \item \verb|_limit| and \verb|_step| are invisible variables.
 The names are here for explanatory purposes only.
 \item The behavior is \emph{undefined} if you assign to \verb|var| inside
 the block.
 \item If the third expression (the step) is absent, then a step of~1 is used.
-\item Both the limit and the step are evaluated only once,
-before the loop starts.
 \item You can use \rwd{break} to exit a \rwd{for} loop.
 \item The loop variable \verb|var| is local to the statement;
 you 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|,
 then assign it to another variable before breaking or exiting the loop.
 \end{itemize}
 
-The table \rwd{for} statement traverses all pairs
-(index,value) of a given table.
+The generic \rwd{for} statement works both over tables
+and over functions.
+When used with a \IndexEmph{generator function},
+it calls this function to produce a new value for each iteration,
+stopping when the new value is \nil.
 It has the following syntax:
 \begin{Produc}
-\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp
+\produc{stat}{\rwd{for} name \opt{\ter{,} name} \rwd{in} exp
                     \rwd{do} block \rwd{end}}
 \end{Produc}%
 A \rwd{for} statement like
 \begin{verbatim}
-       for index, value in exp do block end
+       for var1, var2 in exp do block end
 \end{verbatim}
 is equivalent to the code:
 \begin{verbatim}
        do
-         local _t = exp
-         local index, value = next(_t, nil)
-         while index do
+         local _f = exp
+         while 1 do
+           local var1, var2 = _f()
+           if var1 == nil then break end
            block
-           index, value = next(_t, index)
          end
        end
 \end{verbatim}
 Note the following:
 \begin{itemize}\itemsep=0pt
-\item \verb|_t| is an invisible variable.
+\item \verb|exp| is evaluated only once.
+Its result is the function that will be evaluated for each loop.
+\item \verb|_f| is an invisible variable.
 The name is here for explanatory purposes only.
-\item The behavior is \emph{undefined} if you assign to \verb|index| inside
-the block.
-\item The behavior is \emph{undefined} if you change
-the table \verb|_t| during the traversal.
+\item The behavior is \emph{undefined} if you assign to \verb|var1|
+or \verb|var2| inside the block.
 \item You can use \rwd{break} to exit a \rwd{for} loop.
-\item The loop variables \verb|index| and \verb|value| are local to the statement;
+\item The loop variables \verb|var1| and \verb|var2| are
+local to the statement;
 you cannot use their values after the \rwd{for} ends.
-If you need the value of \verb|index| or \verb|value|,
+If you need these values,
 then assign them to other variables before breaking or exiting the loop.
-\item The order that table elements are traversed is undefined,
-\emph{even for numerical indices}.
-If you want to traverse indices in numerical order,
-use a numerical \rwd{for}.
+\item The absence of the optional variable \verb|var2| does not
+change the meaning of the loop.
 \end{itemize}
 
+If the generator is a table \verb|t|,
+then the loop works as if it has received the following generator function:
+\begin{verbatim}
+       local k,v = nil
+       function generator ()
+         k,v = next(t, k)
+         return k,v
+       end
+\end{verbatim}
+That is, the loop iterates over the (key,value) pairs of the table.
+
 
 \subsubsection{Function Calls as Statements} \label{funcstat}
 Because of possible side-effects,
@@ -902,7 +917,7 @@ Function calls are explained in \See{functioncall}.
 
 \subsubsection{Local Declarations} \label{localvar}
 \Index{Local variables} may be declared anywhere inside a block.
-The declaration may include an initial assignment:
+The declaration may include an initial assignment:\IndexKW{local}
 \begin{Produc}
 \produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}}
 \produc{namelist}{name \rep{\ter{,} name}}
@@ -923,15 +938,15 @@ Visibility rules for local variables are explained in \See{visibility}.
 %\subsubsection{\Index{Basic Expressions}}
 The basic expressions in Lua are the following:
 \begin{Produc}
-\produc{exp}{\ter{(} exp \ter{)}}
-\produc{exp}{\rwd{nil}}
-\produc{exp}{number}
-\produc{exp}{literal}
-\produc{exp}{var}
+\produc{exp}{prefixexp}
+\produc{exp}{\rwd{nil} \Or \rwd{false} \Or \rwd{true}}
+\produc{exp}{Number}
+\produc{exp}{Literal}
 \produc{exp}{function}
-\produc{exp}{functioncall}
 \produc{exp}{tableconstructor}
+\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
 \end{Produc}%
+\IndexKW{nil}
 
 An expression enclosed in parentheses always results in only one value.
 Thus,
@@ -957,10 +972,10 @@ the binary \verb|+| (addition),
 and unary \verb|-| (negation).
 If the operands are numbers, or strings that can be converted to
 numbers \see{coercion},
-then all operations except exponentiation have the usual meaning;
+then all operations except exponentiation have the usual meaning,
+while exponentiation calls a global function \verb|pow|;
 otherwise, an appropriate tag method is called \see{tag-method}.
-An exponentiation always calls a tag method.
-The standard mathematical library defines this method for numbers,
+The standard mathematical library defines function \verb|pow|,
 giving the expected meaning to \Index{exponentiation}
 \see{mathlib}.
 
@@ -969,10 +984,10 @@ The \Index{relational operators} in Lua are
 \begin{verbatim}
        ==    ~=    <     >     <=    >=
 \end{verbatim}
-These operators return \nil\ as false and a value different from \nil\ as true.
+These operators always result in \False\ or \True.
 
 Equality (\verb|==|) first compares the type of its operands.
-If the types are different, then the result is \nil.
+If the types are different, then the result is \False.
 Otherwise, the values of the operands are compared.
 Numbers and strings are compared in the usual way.
 Tables, userdata, and functions are compared \emph{by reference},
@@ -1006,38 +1021,54 @@ The \Index{logical operators} in Lua are
        and   or    not
 \end{verbatim}
 Like the control structures \see{control},
-all logical operators consider \nil\ as false and anything else as true.
+all logical operators consider both \False\ and \nil\ as false
+and anything else as true.
+\IndexKW{and}\IndexKW{or}\IndexKW{not}
 
-The conjunction operator \rwd{and} returns \nil\ if its first argument is \nil;
+The operator \rwd{not} always return \False\ or \True.
+
+The conjunction operator \rwd{and} returns its first argument
+if its value is \False\ or \nil;
 otherwise, \rwd{and} returns its second argument.
 The disjunction operator \rwd{or} returns its first argument
-if it is different from \nil;
+if it is different from \nil and \False;
 otherwise, \rwd{or} returns its second argument.
 Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation},
 that is,
 the second operand is evaluated only if necessary.
-
-There are two useful Lua idioms that use logical operators.
-The first idiom is
-\begin{verbatim}
-       x = x or v
-\end{verbatim}
-which is equivalent to
+For example,
 \begin{verbatim}
-       if x == nil then x = v end
+       10 or error()       -> 10
+       nil or "a"          -> "a"
+       nil and 10          -> nil
+       false and error()   -> false
+       false and nil       -> false
+       false or nil        -> nil
+       10 and 20           -> 20
 \end{verbatim}
-This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set.
 
-The second idiom is
-\begin{verbatim}
-       x = a and b or c
-\end{verbatim}
-which should be read as \verb|x = (a and b) or c|.
-This idiom is equivalent to
-\begin{verbatim}
-       if a then x = b else x = c end
-\end{verbatim}
-provided that \verb|b| is not \nil.
+%There are two useful Lua idioms that use logical operators.
+%The first idiom is
+%\begin{verbatim}
+%       x = x or v
+%\end{verbatim}
+%which is equivalent to
+%\begin{verbatim}
+%       if not x then x = v end
+%\end{verbatim}
+%This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set
+%(provided that \verb|x| is not a boolean value).
+
+%The second idiom is
+%\begin{verbatim}
+%       x = a and b or c
+%\end{verbatim}
+%which should be read as \verb|x = (a and b) or c|.
+%This idiom is equivalent to
+%\begin{verbatim}
+%       if a then x = b else x = c end
+%\end{verbatim}
+%provided that \verb|b| is not \nil.
 
 \subsubsection{Concatenation} \label{concat}
 The string \Index{concatenation} operator in Lua is
@@ -1063,13 +1094,12 @@ except for \verb|^| (exponentiation),
 which is right associative.
 \NOTE
 The pre-compiler may rearrange the order of evaluation of
-associative or commutative operators,
+associative operators,
+and may exchange the operands of commutative operators,
 as long as these optimizations do not change normal results.
 However, these optimizations may change some results
 if you define non-associative (or non-commutative)
 tag methods for these operators.
-In general,
-you should not write code that depends on the order of evaluation.
 
 \subsubsection{Table Constructors} \label{tableconstructor}
 Table \Index{constructors} are expressions that create tables;
@@ -1078,28 +1108,35 @@ Constructors can be used to create empty tables,
 or to create a table and initialize some of its fields.
 The general syntax for constructors is
 \begin{Produc}
-\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
-\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist
-	\Or ffieldlist \ter{;} lfieldlist}
-\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}}
-\produc{ffieldlist}{\opt{ffieldlist1 \opt{\ter{,}}}}
+\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
+\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
+\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp}
+\produc{fieldsep}{\ter{,} \Or \ter{;}}
 \end{Produc}%
 
-The form \emph{explist1} is used to initialize \IndexEmph{lists}.
-The expressions in a list are assigned to consecutive numerical indices
-in the table,
-starting with~1.
+Each field of the form \verb|[exp1] = exp2| adds to the new table an entry
+with key \verb|exp1| and value \verb|exp2|.
+A field of the form \verb|name = exp| is equivalent to
+\verb|["name"] = exp|.
+Finally, fields of the form \verb|exp| add to the new table entries
+with the given expression indexed by consecutive numerical integers,
+starting with 1.
+Fields in the other formats do not affect this counting.
 For example,
 \begin{verbatim}
-       a = {"v1", "v2", 34}
+       a = {[f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45}
 \end{verbatim}
 is equivalent to
 \begin{verbatim}
        do
          local temp = {}
-         temp[1] = "v1"
-         temp[2] = "v2"
-         temp[3] = 34
+         temp[f(1)] = g
+         temp[1] = "x"         -- 1st exp
+         temp[2] = "y"         -- 2nd exp
+         temp.x = 1            -- temp["x"] = 1
+         temp[3] = f(x)        -- 3rd exp
+         temp[30] = 23
+         temp[4] = 45          -- 4th exp
          a = temp
        end
 \end{verbatim}
@@ -1110,59 +1147,28 @@ then all values returned by the call enter the list consecutively
 If you want to avoid this,
 enclose the function call in parentheses.
 
-The form \emph{ffieldlist1} initializes other fields in a table:
-\begin{Produc}
-\produc{ffieldlist1}{ffield \rep{\ter{,} ffield}}
-\produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp}
-\end{Produc}%
-For example,
-\begin{verbatim}
-       a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
-\end{verbatim}
-is equivalent to
-\begin{verbatim}
-       do
-         local temp = {}
-         temp[f(k)] = g(y)
-         temp["x"] = 1    -- or temp.x = 1
-         temp["y"] = 3    -- or temp.y = 3
-         temp[0] = b+c
-         a = temp
-       end
-\end{verbatim}
-An expression like \verb|{x = 1, y = 4}| is
-in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
-
-Both forms may have an optional trailing comma
-(for convenience of machine-generated code),
-and can be used in the same constructor separated by
-a semi-colon.
-For example, all forms below are correct.
-\begin{verbatim}
-       x = {;}
-       x = {"a", "b",}
-       x = {type="list"; "a", "b"}
-       x = {f(0), f(1), f(2),; n=3,}
-\end{verbatim}
+The field list may have an optional trailing separator,
+as a convenience for machine-generated code.
+
 
 \subsubsection{Function Calls}  \label{functioncall}
 A \Index{function call} in Lua has the following syntax:
 \begin{Produc}
-\produc{functioncall}{exp args}
+\produc{functioncall}{prefixexp args}
 \end{Produc}%
 In a function call,
-first \M{exp} and \M{args} are evaluated.
-If the value of \M{exp} has type \emph{function},
+first \M{prefixexp} and \M{args} are evaluated.
+If the value of \M{prefixexp} has type \emph{function},
 then this function is called,
 with the given arguments.
 Otherwise, the ``function'' tag method is called,
-having as first parameter the value of \M{exp},
+having as first parameter the value of \M{prefixexp},
 followed by the original call arguments
 \see{tag-method}.
 
 The form
 \begin{Produc}
-\produc{functioncall}{exp \ter{:} name args}
+\produc{functioncall}{prefixexp \ter{:} name args}
 \end{Produc}%
 can be used to call ``methods''.
 A call \verb|v:name(...)|
@@ -1173,7 +1179,7 @@ Arguments have the following syntax:
 \begin{Produc}
 \produc{args}{\ter{(} \opt{explist1} \ter{)}}
 \produc{args}{tableconstructor}
-\produc{args}{literal}
+\produc{args}{Literal}
 \end{Produc}%
 All argument expressions are evaluated before the call.
 A call of the form \verb|f{...}| is syntactic sugar for
@@ -1188,11 +1194,11 @@ Because a function can return any number of results
 \see{return},
 the number of results must be adjusted before they are used.
 If the function is called as a statement \see{funcstat},
-then its return list is adjusted to~0,
+then its return list is adjusted to~0 elements,
 thus discarding all returned values.
 If the function is called inside another expression,
 or in the middle of a list of expressions,
-then its return list is adjusted to~1,
+then its return list is adjusted to~1 element,
 thus discarding all returned values but the first one.
 If the function is called as the last element of a list of expressions,
 then no adjustment is made
@@ -1219,9 +1225,23 @@ then it is adjusted to return exactly one value:
        {(f())}            -- creates a table with exactly one element
 \end{verbatim}
 
+As an exception to the format-free syntax of Lua,
+you cannot put a line break before the \verb|(| in a function call.
+That restriction avoids some ambiguities in the language.
+If you write
+\begin{verbatim}
+       a = f
+       (g).x(a)
+\end{verbatim}
+Lua would read that as \verb|a = f(g).x(a)|.
+So, if you want two statements, you must add a semi-colon between them.
+If you actually want to call \verb|f|,
+you must remove the line break before \verb|(g)|.
+
+
 \subsubsection{\Index{Function Definitions}} \label{func-def}
 
-The syntax for function definition is
+The syntax for function definition is\IndexKW{function}
 \begin{Produc}
 \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)}
   block \rwd{end}}
@@ -1260,8 +1280,8 @@ may refer to different non-local variables \see{visibility}.
 Parameters act as local variables,
 initialized with the argument values:
 \begin{Produc}
-\produc{parlist1}{\ter{\ldots}}
 \produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}}
+\produc{parlist1}{\ter{\ldots}}
 \end{Produc}%
 \label{vararg}%
 When a function is called,
@@ -1349,7 +1369,7 @@ defined inside their scope.
 For instance:
 \begin{verbatim}
   local counter = 0
-  function inc (x) 
+  function inc (x)
     counter = counter + x
     return counter
   end
@@ -1411,35 +1431,28 @@ Lua code can ``catch'' an error using the function
 \verb|call| \see{pdf-call}.
 
 
-\subsection{Tag Methods} \label{tag-method}
-
-A \IndexEmph{tag method} is a programmer-defined function
-that defines how Lua operations act over user-defined types
-(and, sometimes, over basic types as well).
-An \Def{event} is any operation that may invoke a tag method.
-
-Lua selects the tag method called for any specific event
-according to the types of the values involved
-in the event \see{TypesSec}.
-The function \IndexLIB{settagmethod} changes the tag method
-associated with a given (\M{type}, \M{event}) pair.
-The first parameter to \verb|settagmethod| is the type
-(represented by its name or tag),
-the second parameter is the event name (a string; see below),
-and the third parameter is the new method (a function),
-or \nil\ to restore the default behavior for the pair.
-A companion function \IndexLIB{gettagmethod}
-receives a type and an event name and returns the
-current method associated to them.
-
-Tag methods are called in the following events,
-identified by the given names.
-The semantics of tag methods is better explained by a Lua function
-describing the behavior of the interpreter at each event.
-Each event-handler function shows how a tag method is called,
-its arguments (that is, its signature),
-its results,
-and the default behavior in the absence of a tag method.
+\subsection{Metatables} \label{metatable}
+
+Every table and userdata value in Lua may have a \emph{metatable}.
+This \IndexEmph{metatable} is a table that defines the behavior of
+the original table and userdata under some operations.
+You can query and change the metatable of an object with
+function \verb|metatable| \see{pdf-metatable}.
+
+For each of these operations Lua associates a specific key.
+When Lua performs one of these operations over a table or a userdata,
+if checks whether that object has a metatable with the corresponding key.
+If so, the value associated with that key (the \IndexEmph{handler})
+controls how Lua will perform the operation.
+
+Metatables control the operations listed next.
+Each operation is identified by its corresponding key.
+The semantics of these operations is better explained by a Lua function
+describing how the interpreter executes that operation.
+%Each function shows how a handler is called,
+%its arguments (that is, its signature),
+%its results,
+%and the default behavior in the absence of a handler.
 The code shown here in Lua is only illustrative;
 the real behavior is hard coded in the interpreter,
 and it is much more efficient than this simulation.
@@ -1450,34 +1463,31 @@ are described in \See{predefined}.
 \begin{description}
 
 \item[``add'':]\IndexTM{add}
-called when a \verb|+| operation is applied to non-numerical operands.
+the \verb|+| operation.
 
-The function \verb|getbinmethod| below defines how Lua chooses a tag method
+The function \verb|getbinhandler| below defines how Lua chooses a handler
 for a binary operation.
 First, Lua tries the first operand.
-If its type does not define a tag method for the operation,
+If its type does not define a handler for the operation,
 then Lua tries the second operand.
-If it also fails, then it gets a tag method from tag~0.
 \begin{verbatim}
-       function getbinmethod (op1, op2, event)
-         return gettagmethod(tag(op1), event) or
-                gettagmethod(tag(op2), event) or
-                gettagmethod(0, event)
+       function getbinhandler (op1, op2, event)
+         return metatable(op1)[event] or metatable(op2)[event]
        end
 \end{verbatim}
 Using this function,
-the tag method for the ``add'' event is
+the behavior of the ``add'' operation is
 \begin{verbatim}
-       function add_event (op1, op2)
+       function add_op (op1, op2)
          local o1, o2 = tonumber(op1), tonumber(op2)
          if o1 and o2 then  -- both operands are numeric
            return o1+o2  -- '+' here is the primitive 'add'
          else  -- at least one of the operands is not numeric
-           local tm = getbinmethod(op1, op2, "add")
-           if tm then
-             -- call the method with both operands
-             return tm(op1, op2)
-           else  -- no tag method available: default behavior
+           local h = getbinhandler(op1, op2, "add")
+           if h then
+             -- call the handler with both operands
+             return h(op1, op2)
+           else  -- no handler available: default behavior
              error("unexpected type at arithmetic operation")
            end
          end
@@ -1485,48 +1495,45 @@ the tag method for the ``add'' event is
 \end{verbatim}
 
 \item[``sub'':]\IndexTM{sub}
-called when a \verb|-| operation is applied to non-numerical operands.
-Behavior similar to the ``add'' event.
+the \verb|-| operation.
+Behavior similar to the ``add'' operation.
 
 \item[``mul'':]\IndexTM{mul}
-called when a \verb|*| operation is applied to non-numerical operands.
-Behavior similar to the ``add'' event.
+the \verb|*| operation.
+Behavior similar to the ``add'' operation.
 
 \item[``div'':]\IndexTM{div}
-called when a \verb|/| operation is applied to non-numerical operands.
-Behavior similar to the ``add'' event.
+the \verb|/| operation.
+Behavior similar to the ``add'' operation.
 
 \item[``pow'':]\IndexTM{pow}
-called when a \verb|^| operation (exponentiation) is applied,
-even for numerical operands.
-\begin{verbatim}
-       function pow_event (op1, op2)
-         local tm = getbinmethod(op1, op2, "pow")
-         if tm then
-           -- call the method with both operands
-           return tm(op1, op2)
-         else  -- no tag method available: default behavior
+the \verb|^| operation (exponentiation) operation.
+\begin{verbatim} ??
+       function pow_op (op1, op2)
+         local h = getbinhandler(op1, op2, "pow")
+         if h then
+           -- call the handler with both operands
+           return h(op1, op2)
+         else  -- no handler available: default behavior
            error("unexpected type at arithmetic operation")
          end
        end
 \end{verbatim}
 
 \item[``unm'':]\IndexTM{unm}
-called when a unary \verb|-| operation is applied to a non-numerical operand.
+the unary \verb|-| operation.
 \begin{verbatim}
-       function unm_event (op)
+       function unm_op (op)
          local o = tonumber(op)
          if o then  -- operand is numeric
            return -o  -- '-' here is the primitive 'unm'
          else  -- the operand is not numeric.
-           -- Try to get a tag method from the operand;
-           --  if it does not have one, try a "global" one (tag 0)
-           local tm = gettagmethod(tag(op), "unm") or
-                      gettagmethod(0, "unm")
-           if tm then
-             -- call the method with the operand and nil
-             return tm(op, nil)
-           else  -- no tag method available: default behavior
+           -- Try to get a handler from the operand;
+           local h = metatable(op).unm
+           if h then
+             -- call the handler with the operand and nil
+             return h(op, nil)
+           else  -- no handler available: default behavior
              error("unexpected type at arithmetic operation")
            end
          end
@@ -1534,26 +1541,24 @@ called when a unary \verb|-| operation is applied to a non-numerical operand.
 \end{verbatim}
 
 \item[``lt'':]\IndexTM{lt}
-called when an order operation is applied to non-numerical
-or non-string operands.
-It corresponds to the \verb|<| operator.
+the \verb|<| operation.
 \begin{verbatim}
-       function lt_event (op1, op2)
+       function lt_op (op1, op2)
          if type(op1) == "number" and type(op2) == "number" then
            return op1 < op2   -- numeric comparison
          elseif type(op1) == "string" and type(op2) == "string" then
            return op1 < op2   -- lexicographic comparison
          else
-           local tm = getbinmethod(op1, op2, "lt")
-           if tm then
-             return tm(op1, op2)
+           local h = getbinhandler(op1, op2, "lt")
+           if h then
+             return h(op1, op2)
            else
              error("unexpected type at comparison");
            end
          end
        end
 \end{verbatim}
-The other order operators use the \verb|"lt"| tag method
+The other order operators also use the \verb|lt_op| function,
 according to the usual equivalences:
 \begin{verbatim}
        a>b    <=>  b<a
@@ -1562,16 +1567,16 @@ according to the usual equivalences:
 \end{verbatim}
 
 \item[``concat'':]\IndexTM{concatenation}
-called when a concatenation is applied to non-string operands.
+the \verb|..| (concatenation) operation.
 \begin{verbatim}
-       function concat_event (op1, op2)
+       function concat_op (op1, op2)
          if (type(op1) == "string" or type(op1) == "number") and
             (type(op2) == "string" or type(op2) == "number") then
            return op1..op2  -- primitive string concatenation
          else
-           local tm = getbinmethod(op1, op2, "concat")
-           if tm then
-             return tm(op1, op2)
+           local h = getbinhandler(op1, op2, "concat")
+           if h then
+             return h(op1, op2)
            else
              error("unexpected type for concatenation")
            end
@@ -1580,107 +1585,59 @@ called when a concatenation is applied to non-string operands.
 \end{verbatim}
 
 \item[``index'':]\IndexTM{index}
-called when Lua tries to retrieve the value of an index
+This handler is called when Lua tries to retrieve the value of an index
 not present in a table.
-See the ``gettable'' event for its semantics.
-
-\item[``getglobal'':]\IndexTM{getglobal}
-called whenever Lua needs the value of a global variable.
-This method can only be set for \nil\ and for user-defined types.
-Note that
-the tag is that of the \emph{current value} of the global variable.
-\begin{verbatim}
-       function getglobal (varname)
-         -- access the table of globals
-         local value = rawget(globals(), varname)
-         local tm = gettagmethod(tag(value), "getglobal")
-         if not tm then
-           return value
-         else
-           return tm(varname, value)
-         end
-       end
-\end{verbatim}
-The function \verb|getglobal| is defined in the basic library~\see{predefined}.
-\NOTE
-\verb|getglobal| is ``overloaded'' here.
-It is the name both of the event and
-of the function that handles the event
-to call an eventual tag method
-(called \verb|tm| in the above code).
-
-\item[``setglobal'':]\IndexTM{setglobal}
-called whenever Lua assigns to a global variable.
-This method cannot be set for numbers, strings, and tables and
-userdata with the default tag.
-\begin{verbatim}
-       function setglobal (varname, newvalue)
-         local oldvalue = rawget(globals(), varname)
-         local tm = gettagmethod(tag(oldvalue), "setglobal")
-         if not tm then
-           rawset(globals(), varname, newvalue)
-         else
-           tm(varname, oldvalue, newvalue)
-         end
-       end
-\end{verbatim}
-The function \verb|setglobal| is defined in the basic library~\see{predefined}.
-\NOTE
-See previous note.
+See the ``gettable'' operation for its semantics.
 
 \item[``gettable'':]\IndexTM{gettable}
 called whenever Lua accesses an indexed variable.
-This method cannot be set for tables with the default tag.
 \begin{verbatim}
-       function gettable_event (table, index)
-         local tm = gettagmethod(tag(table), "gettable")
-         if tm then
-           return tm(table, index)
-         elseif type(table) ~= "table" then
-           error("indexed expression not a table");
-         else
-           local v = rawget(table, index)
-           tm = gettagmethod(tag(table), "index")
-           if v == nil and tm then
-             return tm(table, index)
+       function gettable_op (table, key)
+         local h = metatable(table).gettable
+         if h == nil then
+           if type(table) ~= "table" then
+             error("indexed expression not a table");
            else
-             return v
+             local v = rawget(table, key)
+             if v ~= nil then return v end
+             h = metatable(table).index
+             if h == nil then return nil end
            end
          end
+         if type(h) == 'function' then
+           return h(table, key)      -- call the handler
+         else return h[key]          -- or repeat operation with it
        end
 \end{verbatim}
 
 \item[``settable'':]\IndexTM{settable}
 called when Lua assigns to an indexed variable.
-This method cannot be set for tables with the default tag.
 \begin{verbatim}
-       function settable_event (table, index, value)
-         local tm = gettagmethod(tag(table), "settable")
-         if tm then
-           tm(table, index, value)
-         elseif type(table) ~= "table" then
-           error("indexed expression not a table")
+       function settable_event (table, key, value)
+         local h = metatable(table).settable
+         if h == nil then
+           if type(table) ~= "table" then
+             error("indexed expression not a table")
+           rawset(table, key, value)
          else
-           rawset(table, index, value)
+           if type(h) == 'function' then
+             h(table, key, value)    -- call the handler
+           else h[key] = value       -- or repeat operation with it
          end
        end
 \end{verbatim}
 
-\item[``function'':]\IndexTM{function}
-called when Lua tries to call a non-function value.
+\item[``call'':]\IndexTM{call}
+called when Lua calls a value.
 \begin{verbatim}
-       function function_event (func, ...)
+       function function_op (func, ...)
          if type(func) == "function" then
-           return call(func, arg)
+           return func(unpack(arg))   -- regular call
          else
-           local tm = gettagmethod(tag(func), "function")
-           if tm then
-             for i=arg.n,1,-1 do
-               arg[i+1] = arg[i]
-             end
-             arg.n = arg.n+1
-             arg[1] = func
-             return call(tm, arg)
+           local h = metatable(func).call
+           if h then
+             tinsert(arg, 1, func)
+             return h(unpack(arg))
            else
              error("call expression not a function")
            end
@@ -1688,30 +1645,39 @@ called when Lua tries to call a non-function value.
        end
 \end{verbatim}
 
-\item[``gc'':]\IndexTM{gc}
-called when Lua is ``garbage collecting'' a userdata.
-This tag method can be set only from~C,
-and cannot be set for a userdata with the default tag.
+\end{description}
+
+\subsubsection{Metatables and Garbage collection}
+
+Metatables also control some aspects of the garbage collector.
+First, they are used to define \IndexEmph{finalizer} methods
+for userdata values.
 For each userdata to be collected,
 Lua does the equivalent of the following function:
 \begin{verbatim}
-       function gc_event (obj)
-         local tm = gettagmethod(tag(obj), "gc")
-         if tm then
-           tm(obj)
+       function gc_op (obj)
+         local h = metatable(obj).gc
+         if h then
+           h(obj)
          end
        end
 \end{verbatim}
 In a garbage-collection cycle,
-the tag methods for userdata are called in \emph{reverse}
-order of type creation,
-that is, the first tag methods to be called are those associated
-with the last type created in the program.
-Moreover, at the end of the cycle,
-Lua does the equivalent of the call \verb|gc_event(nil)|.
-
-\end{description}
-
+the finalizers for userdata are called in \emph{reverse}
+order of their creation,
+that is, the first finalizer to be called is the one associated
+with the last userdata created in the program
+(among those to be collected in this cycle).
+
+Second, metatables control the weakmode of tables \see{weak-table}.
+The weakmode of a table \verb|t| is defined by a string:
+\label{weakmode}
+\begin{verbatim}
+  s = metatable(t).weakmode
+\end{verbatim}
+Valid values for this string are \verb|"k"| for weak keys,
+\verb|"v"| for weak values,
+and \verb|"kv"| for both.
 
 
 
@@ -1799,9 +1765,12 @@ Each thread has an independent table for global variables.
 When you create a thread, this table is the same as that of the given state,
 but you can change each one independently.
 
-You destroy threads with \verb|lua_close|.
-When you destroy the last thread sharing a given state,
-the state itself is also destroyed.
+You destroy threads with \DefAPI{lua_closethread}
+\begin{verbatim}
+       void lua_closethread (lua_State *L, lua_State *thread);
+\end{verbatim}
+You cannot close the sole (or last) thread of a state.
+Instead, you must close the state itself.
 
 
 \subsection{The Stack and Indices}
@@ -1879,9 +1848,10 @@ The API offers the following functions for basic stack manipulation:
        void lua_pushvalue (lua_State *L, int index);
        void lua_remove    (lua_State *L, int index);
        void lua_insert    (lua_State *L, int index);
+       void lua_replace   (lua_State *L, int index);
 \end{verbatim}
 \DefAPI{lua_settop}\DefAPI{lua_pushvalue}
-\DefAPI{lua_remove}\DefAPI{lua_insert}
+\DefAPI{lua_remove}\DefAPI{lua_insert}\DefAPI{lua_replace}
 
 \verb|lua_settop| accepts any acceptable index,
 or 0,
@@ -1902,6 +1872,9 @@ at the given index.
 shifting down the elements above that position to fill the gap.
 \verb|lua_insert| moves the top element into the given position,
 shifting up the elements above that position to open space.
+\verb|lua_replace| moves the top element into the given position,
+without shifting any element (therefore it replaces the value at
+the given position).
 These functions accept only valid indices.
 (Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with
 pseudo-indices, as they do not represent a stack position.)
@@ -1916,8 +1889,9 @@ then
        lua_remove(L,  6)      --> 10 20 30 40 30*
        lua_insert(L,  1)      --> 30 10 20 30 40*
        lua_insert(L, -1)      --> 30 10 20 30 40*  (no effect)
-       lua_settop(L, -3)      --> 30 10 20*
-       lua_settop(L,  6)      --> 30 10 20 nil nil nil*
+       lua_replace(L, 2)      --> 30 40 20 30*
+       lua_settop(L, -3)      --> 30 40 20*
+       lua_settop(L,  6)      --> 30 40 20 nil nil nil*
 \end{verbatim}
 
 
@@ -1927,10 +1901,9 @@ then
 To check the type of a stack element,
 the following functions are available:
 \begin{verbatim}
-       int         lua_tag         (lua_State *L, int index);
-       int         lua_rawtag      (lua_State *L, int index);
-       const char *lua_type        (lua_State *L, int index);
+       int         lua_type        (lua_State *L, int index);
        int         lua_isnil       (lua_State *L, int index);
+       int         lua_isboolean   (lua_State *L, int index);
        int         lua_isnumber    (lua_State *L, int index);
        int         lua_isstring    (lua_State *L, int index);
        int         lua_istable     (lua_State *L, int index);
@@ -1938,30 +1911,36 @@ the following functions are available:
        int         lua_iscfunction (lua_State *L, int index);
        int         lua_isuserdata  (lua_State *L, int index);
 \end{verbatim}
-\DefAPI{lua_type}\DefAPI{lua_tag}
+\DefAPI{lua_type}
 \DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
-\DefAPI{lua_istable}
+\DefAPI{lua_istable}\DefAPI{lua_isboolean}
 \DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata}
 These functions can be called with any acceptable index.
 
-\verb|lua_tag| returns the tag of a value in the stack,
+\verb|lua_type| returns the type of a value in the stack,
 or \verb|LUA_TNONE| for a non-valid index
 (that is, if that stack position is ``empty'').
-The tags for the basic types are the following constants
+The types are coded by the following constants
 defined in \verb|lua.h|:
 \verb|LUA_TNIL|,
 \verb|LUA_TNUMBER|,
+\verb|LUA_TBOOLEAN|,
 \verb|LUA_TSTRING|,
 \verb|LUA_TTABLE|,
 \verb|LUA_TFUNCTION|,
 \verb|LUA_TUSERDATA|.
-\verb|lua_rawtag| is similar to \verb|lua_tag|,
-but returns the tag of the basic (raw) type of a value.
-\verb|lua_type| is similar to \verb|lua_tag|,
-but returns the type name of the given value.
+The following function translates a tag to a type name:
+\begin{verbatim}
+       const char *lua_type        (lua_State *L, int index);
+\end{verbatim}
+\DefAPI{lua_typename}
 
 The \verb|lua_is*| functions return~1 if the object is compatible
 with the given type, and 0 otherwise.
+(\verb|lua_isboolean| is an exception to this rule,
+and it succeeds only for boolean values;
+otherwise it would be useless,
+as any value is compatible with a boolean.)
 They always return 0 for a non-valid index.
 \verb|lua_isnumber| accepts numbers and numerical strings,
 \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.
 To translate a value in the stack to a specific C~type,
 you can use the following conversion functions:
 \begin{verbatim}
+       int            lua_toboolean   (lua_State *L, int index);
        lua_Number     lua_tonumber    (lua_State *L, int index);
        const char    *lua_tostring    (lua_State *L, int index);
        size_t         lua_strlen      (lua_State *L, int index);
@@ -1994,11 +1974,20 @@ you can use the following conversion functions:
        void          *lua_touserdata  (lua_State *L, int index);
 \end{verbatim}
 \DefAPI{lua_tonumber}\DefAPI{lua_tostring}\DefAPI{lua_strlen}
-\DefAPI{lua_tocfunction}\DefAPI{lua_touserdata}
+\DefAPI{lua_tocfunction}\DefAPI{lua_touserdata}\DefAPI{lua_toboolean}
 These functions can be called with any acceptable index.
 When called with a non-valid index,
 they act as if the given value had an incorrect type.
 
+\verb|lua_toboolean| converts the Lua value at the given index
+to a C ``boolean'' value (that is, (int)0 or (int)1).
+Like all tests in Lua, it returns 1 for any Lua value different from
+\False\ and \nil;
+otherwise it returns 0.
+It also returns 0 when called with a non-valid index.
+(If you want to accept only real boolean values,
+use \verb|lua_isboolean| to test the type of the value.)
+
 \verb|lua_tonumber| converts the Lua value at the given index
 to a number (by default, \verb|lua_Number| is \verb|double|).
 \DefAPI{lua_Number}
@@ -2043,6 +2032,7 @@ otherwise, \verb|lua_touserdata| returns \verb|NULL|.
 The API has the following functions to
 push C~values onto the stack:
 \begin{verbatim}
+       void lua_pushboolean   (lua_State *L, int b);
        void lua_pushnumber    (lua_State *L, lua_Number n);
        void lua_pushlstring   (lua_State *L, const char *s, size_t len);
        void lua_pushstring    (lua_State *L, const char *s);
@@ -2050,7 +2040,7 @@ push C~values onto the stack:
        void lua_pushcfunction (lua_State *L, lua_CFunction f);
 \end{verbatim}
 \DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring}
-\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag}
+\DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag}\DefAPI{lua_pushboolean}
 \DefAPI{lua_pushnil}\label{pushing}
 These functions receive a C~value,
 convert it to a corresponding Lua value,
@@ -2088,7 +2078,7 @@ If the new threshold is smaller than the byte counter,
 then Lua immediately runs the garbage collector.
 In particular
 \verb|lua_setgcthreshold(L,0)| forces a garbage collectiion.
-After the collection, 
+After the collection,
 a new threshold is set according to the previous rule.
 %% TODO: What `previous rule'?
 
@@ -2125,36 +2115,9 @@ it is up to you to free any associated memory,
 setting a garbage-collection tag method, for instance.
 
 
-\subsection{Types and Tags}
+\subsection{Metatables}
 
-User-defined types are created with the function
-\begin{verbatim}
-       int lua_newtype (lua_State *L, const char *name, int basictype);
-\end{verbatim}
-\DefAPI{lua_newtype}
-where
-\verb|name| is the name of the new type,
-and \verb|basictype| is the basic type for objects with this new type,
-which can be either \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|.
-
-The function \verb|lua_settag| changes the tag (i.e., the type) of
-the object on top of the stack (without popping it):
-\begin{verbatim}
-       void lua_settag (lua_State *L, int tag);
-\end{verbatim}
-\DefAPI{lua_settag}
-The given \verb|tag| must be a user-defined tag,
-%% TODO: nao pode voltar ao tag original, ie basico?
-and the basic type of the object must be the basic type for that
-tag (userdata or table).
-
-The following functions allow you to translate a tag to a type name
-and a type name to a tag:
-\begin{verbatim}
-       int         lua_name2tag (lua_State *L, const char *name);
-       const char *lua_tag2name (lua_State *L, int tag);
-\end{verbatim}
-\DefAPI{lua_name2tag}\DefAPI{lua_tag2name}
+%% TODO
 
 
 \subsection{Executing Lua Chunks}\label{luado}
@@ -2240,50 +2203,6 @@ The compiled chunk is left as a function on top of the stack.
 The return values are the same as those of
 \verb|lua_dofile| and \verb|lua_dobuffer|.
 
-\subsection{Manipulating Global Variables} \label{globals}
-
-To read the value of a global Lua variable,
-you call
-\begin{verbatim}
-       void lua_getglobal (lua_State *L, const char *varname);
-\end{verbatim}
-\DefAPI{lua_getglobal}
-which pushes onto the stack the value of the given variable.
-(The string \verb|varname| does not need to be a
-syntactically valid variable name.)
-As in Lua, this function may trigger a tag method
-for the ``getglobal'' event \see{tag-method}.
-To read the real value of a global variable,
-without invoking any tag method,
-use \verb|lua_rawget| over the table of globals
-(see below).
-
-To store a value in a global variable,
-you call
-\begin{verbatim}
-       void lua_setglobal (lua_State *L, const char *varname);
-\end{verbatim}
-\DefAPI{lua_setglobal}
-which pops from the stack the value to be stored in the given variable.
-(The string \verb|varname| does not need to be a
-syntactically valid variable name.)
-As in Lua, this function may trigger a tag method
-for the ``setglobal'' event \see{tag-method}.
-To set the real value of a global variable,
-without invoking any tag method,
-use \verb|lua_rawset| over the table of globals
-(see below).
-
-All global variables are kept in an ordinary Lua table.
-This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}.
-To set another table as the table of globals,
-you call
-\begin{verbatim}
-       void lua_setglobals (lua_State *L);
-\end{verbatim}
-\DefAPI{lua_setglobals}
-The table to be used is popped from the stack.
-
 \subsection{Manipulating Tables}
 
 Tables are created by calling
@@ -2371,18 +2290,20 @@ unless you know the key is actually a string.
 Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
 this confuses \verb|lua_next|.
 
-The following functions control the weak mode of a table:
+\subsection{Manipulating Global Variables} \label{globals}
+
+All global variables are kept in an ordinary Lua table.
+This table is always at pseudo-index \IndexAPI{LUA_GLOBALSINDEX}.
+
+To access and change the value of global variables,
+you can use regular table operations over the global table.
+For instance, to access the value of a global variable, do
 \begin{verbatim}
-       void lua_setweakmode (lua_State *L, int mode);
-       int  lua_getweakmode (lua_State *L, int index);
+       lua_pushstring(L, varname);
+       lua_gettable(L, LUA_GLOBALSINDEX);
 \end{verbatim}
-\DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode}
-Both functions operate over the table at the top of the stack.
-Modes are described as bit sets, so that
-\verb|LUA_WEAK_KEY| means weak keys,
-\verb|LUA_WEAK_VALUE| means weak values, the combination
-\verb"LUA_WEAK_KEY | LUA_WEAK_VALUE" means both,
-and zero means none.
+
+You can change the global table of a Lua thread using \verb|lua_replace|.
 
 
 \subsection{Using Tables as Arrays}
@@ -2450,25 +2371,32 @@ so that after the call the last result is on the top.
 The following example shows how the host program may do the
 equivalent to the Lua code:
 \begin{verbatim}
-       a,b = f("how", t.x, 14)
+       a = f("how", t.x, 14)
 \end{verbatim}
 Here it is in~C:
 \begin{verbatim}
-    lua_getglobal(L, "t");                      /* global `t' (for later use) */
-    lua_getglobal(L, "f");                           /* function to be called */
+    lua_pushstring(L, "t");
+    lua_gettable(L, LUA_GLOBALSINDEX);          /* global `t' (for later use) */
+    lua_pushstring(L, "a");                                       /* var name */
+    lua_pushstring(L, "f");                                  /* function name */
+    lua_gettable(L, LUA_GLOBALSINDEX);               /* function to be called */
     lua_pushstring(L, "how");                                 /* 1st argument */
     lua_pushstring(L, "x");                            /* push the string "x" */
-    lua_gettable(L, -4);                      /* push result of t.x (2nd arg) */
+    lua_gettable(L, -5);                      /* push result of t.x (2nd arg) */
     lua_pushnumber(L, 14);                                    /* 3rd argument */
-    lua_call(L, 3, 2);        /* call function with 3 arguments and 2 results */
-    lua_setglobal(L, "b");                         /* set global variable `b' */
-    lua_setglobal(L, "a");                         /* set global variable `a' */
+    lua_call(L, 3, 1);         /* call function with 3 arguments and 1 result */
+    lua_settable(L, LUA_GLOBALSINDEX);             /* set global variable `a' */
     lua_pop(L, 1);                               /* remove `t' from the stack */
 \end{verbatim}
 Notice that the code above is ``balanced'':
 at its end, the stack is back to its original configuration.
 This is considered good programming practice.
 
+(We did this example using only the raw functions provided by Lua's API,
+to show all the details.
+Usually programmers use several macros and auxiliar functions that
+provide higher level access to Lua.)
+
 \medskip
 
 %% TODO: mover essas 2 para algum lugar melhor.
@@ -2496,35 +2424,13 @@ The function
 \end{verbatim}
 \DefAPI{lua_concat}
 concatenates the \verb|n| values at the top of the stack,
-pops them, and leaves the result at the top;
-\verb|n|~must be at least 2.
+pops them, and leaves the result at the top.
+If \verb|n| is 1, the result is that single string
+(that is, the function does nothing);
+if \verb|n| is 0, the result is the empty string.
 Concatenation is done following the usual semantics of Lua
 \see{concat}.
 
-\subsection{Manipulating Tag Methods}
-Tag methods can be changed with
-\begin{verbatim}
-       void lua_settagmethod (lua_State *L, int tag, const char *event);
-\end{verbatim}
-\DefAPI{lua_settagmethod}
-The second parameter is the tag,
-and the third is the event name \see{tag-method};
-the new method is popped from the stack.
-To get the current value of a tag method,
-use the function
-\begin{verbatim}
-       void lua_gettagmethod (lua_State *L, int tag, const char *event);
-\end{verbatim}
-\DefAPI{lua_gettagmethod}
-
-It is also possible to copy all tag methods from one tag
-to another:
-\begin{verbatim}
-       int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
-\end{verbatim}
-\DefAPI{lua_copytagmethods}
-This function returns \verb|tagto|.
-
 
 \subsection{Defining C Functions} \label{LuacallC}
 Lua can be extended with functions written in~C.
@@ -2569,7 +2475,10 @@ of numerical arguments and returns their average and sum:
 To register a C~function to Lua,
 there is the following convenience macro:
 \begin{verbatim}
-     #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
+       #define lua_register(L,n,f) \
+               (lua_pushstring(L, n), \
+                lua_pushcfunction(L, f), \
+                lua_settable(L, LUA_GLOBALSINDEX))
      /* const char *n;   */
      /* lua_CFunction f; */
 \end{verbatim}
@@ -2704,7 +2613,8 @@ For instance, to know in which line a function \verb|f| was defined,
 you can write
 \begin{verbatim}
        lua_Debug ar;
-       lua_getglobal(L, "f");
+       lua_pushstring(L, "f");
+       lua_gettable(L, LUA_GLOBALSINDEX);  /* get global `f' */
        lua_getinfo(L, ">S", &ar);
        printf("%d\n", ar.linedefined);
 \end{verbatim}
@@ -2885,6 +2795,10 @@ implementation for some facilities.
 without an \verb|_ERRORMESSAGE| function,
 Lua is unable to show error messages.)
 
+The basic library also defines a global variable \IndexAPI{_VERSION}
+with a string containing the current interpreter version.
+The current content of this string is {\tt "Lua \Version"}.
+
 \subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert}
 Prints its only string argument to \IndexVerb{stderr}.
 All 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,
 and (as a second result) the
 current garbage collector threshold (also in Kbytes).
 
-\subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal}
-Gets the value of a global variable,
-possibly via a ``getglobal'' tag method.
-Its full semantics is explained in \See{tag-method}.
-The string \verb|name| does not need to be a
-syntactically valid variable name.
-
 \subsubsection*{\ff \T{getn (table)}}\DefLIB{getn}\label{getn}
 Returns the ``size'' of a table, when seen as a list.
 If the table has an \verb|n| field with a numeric value,
@@ -3052,13 +2959,6 @@ This function is equivalent to the following Lua function:
        end
 \end{verbatim}
 
-\subsubsection*{\ff \T{gettagmethod (tag, event)}}
-\DefLIB{gettagmethod}
-Returns the current tag method
-for a given pair \M{(tag, event)}.
-This function cannot be used to get a tag method for the ``gc'' event.
-(``gc'' tag methods can only be manipulated by C~code.)
-
 \subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals}
 Returns the current table of globals.
 If the argument \verb|table| is given,
@@ -3127,50 +3027,17 @@ without invoking any tag method.
 \verb|index| is any value different from \nil;
 and \verb|value| is any Lua value.
 
-\subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype}
-Returns the basic (raw) type of its only argument, coded as a string.
-The possible results of this function are
-\verb|"nil"| (a string, not the value \nil),
-\verb|"number"|,
-\verb|"string"|,
-\verb|"table"|,
-\verb|"function"|,
-and \verb|"userdata"|.
-
 \subsubsection*{\ff \T{require (module)}}\DefLIB{require}
 
 TO BE WRITTEN.
 
-\subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal}
-Sets the named global variable to the given value,
-possibly via a ``setglobal'' tag method.
-Its full semantics is explained in \See{tag-method}.
-The string \verb|name| does not need to be a
-syntactically valid variable name.
-
-\subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype}
-Sets the type of a given table \see{TypesSec}.
-\verb|type| must be the name or the tag of a user-defined type.
-\verb|settype| returns the value of its first argument (the table).
-For the safety of host programs,
-you can only change the type of userdata from~C, not from Lua.
-
-\subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}}
-\DefLIB{settagmethod}
-Sets a new tag method to the given pair \M{(tag, event)} and
-returns the old method.
-If \verb|newmethod| is \nil,
-then \verb|settagmethod| restores the default behavior for the given event.
-This function cannot be used to set a tag method for the ``gc'' event.
-(``gc'' tag methods can only be manipulated by C~code.)
-
 \subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort}
 Sorts table elements in a given order, \emph{in-place},
 from \verb|table[1]| to \verb|table[n]|,
 where \verb|n| is the result of \verb|getn(table)| \see{getn}.
 If \verb|comp| is given,
 then it must be a function that receives two table elements,
-and returns true (that is, a value different from \nil)
+and returns true
 when the first is less than the second
 (so that \verb|not comp(a[i+1],a[i])| will be true after the sort).
 If \verb|comp| is not given,
@@ -3180,10 +3047,6 @@ The sort algorithm is \emph{not} stable
 (that is, elements considered equal by the given order
 may have their relative positions changed by the sort).
 
-\subsubsection*{\ff \T{tag (v)}}\DefLIB{tag}\label{pdf-tag}
-Returns the tag of a value \see{TypesSec}.
-Tags are integers.
-
 \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber}
 Tries to convert its argument to a number.
 If 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
 of table \verb|t|.
 This function also sets or increments the field \verb|n| of the table
 to \verb|n+1|.
-This function is equivalent to the following Lua function,
-except that the table accesses in \verb|tinsert| are all \emph{raw}
-(that is, without tag methods):
-\begin{verbatim}
-       function tinsert (t, ...)
-         local pos, value
-         local n = getn(t)
-         if arg.n == 1 then
-           pos, value = n+1, arg[1]
-         else
-           pos, value = arg[1], arg[2]
-         end
-         t.n = n+1;
-         for i=n,pos,-1 do
-           t[i+1] = t[i]
-         end
-         t[pos] = value
-       end
-\end{verbatim}
 
 \subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove}
 
@@ -3246,28 +3090,16 @@ so that a call \verb|tremove(t)| removes the last element
 of table \verb|t|.
 This function also sets or decrements the field \verb|n| of the table
 to \verb|n-1|.
-This function is equivalent to the following Lua function,
-except that the table accesses in \verb|tremove| are all \emph{raw}
-(that is, without tag methods):
-\begin{verbatim}
-       function tremove (t, pos)
-         local n = getn(t)
-         if n<=0 then return end
-         pos = pos or n
-         local value = t[pos]
-         for i=pos,n-1 do
-           t[i] = t[i+1]
-         end
-         t[n] = nil
-         t.n = n-1
-         return value
-       end
-\end{verbatim}
 
 \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type}
-Returns the type name of a value.
-Type names are strings and are set with \verb|settype| for user-defined types.
-For other types, \verb|type| is equivalent to \verb|rawtype|.
+Returns the type of its only argument, coded as a string.
+The possible results of this function are
+\verb|"nil"| (a string, not the value \nil),
+\verb|"number"|,
+\verb|"string"|,
+\verb|"table"|,
+\verb|"function"|,
+and \verb|"userdata"|.
 
 \subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack}
 Returns all elements from the given list.
@@ -3279,18 +3111,6 @@ except that the above code can be valid only for a fixed \M{n}.
 The number \M{n} of returned values
 is the result of \verb|getn(list)| \seepage{getn}.
 
-\subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode}
-
-Controls the weakness of a table.
-When \verb|mode| is \verb|"?"|,
-\verb|weakmode| returns the current mode of the table, as a string;
-otherwise, it sets the weakmode of the table to the given mode (also a string).
-Valid mode strings are \verb|"k"| for weak keys,
-\verb|"v"| for weak values,
-\verb|"kv"| for both,
-and \verb|""| for none (that is, for ``normal'' tables).
-
-
 \subsection{String Manipulation}
 This library provides generic functions for string manipulation,
 such as finding and extracting substrings and pattern matching.
@@ -3328,7 +3148,7 @@ the captured strings are returned as extra results.
 A third, optional numerical argument \verb|init| specifies
 where to start the search;
 its default value is~1, and may be negative.
-A value of~1 as a fourth, optional argument \verb|plain|
+A value of \True\ as a fourth, optional argument \verb|plain|
 turns off the pattern matching facilities,
 so the function does a plain ``find substring'' operation,
 with no characters in \verb|pattern| being considered ``magic''.
@@ -3867,7 +3687,7 @@ and \verb|isdst| (daylight saving flag).
 
 If format is not \verb|*t|,
 then \verb|date| returns the date as a string,
-formatted according with the same rules of the C~function \verb|strftime|.
+formatted according with the same rules as the C~function \verb|strftime|.
 When called without arguments,
 \verb|date| returns a reasonable date and time representation that depends on
 the 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.
 The default for \verb|what| is to get all information available.
 If present,
 the option \verb|f|
-adds a field named \verb|func| with the function itself. 
+adds a field named \verb|func| with the function itself.
 
 For instance, the expression \verb|getinfo(1,"n").name| returns
 the name of the current function, if a reasonable name can be found,
@@ -4139,7 +3959,7 @@ Here is a list of all these incompatibilities.
 Function calls written between parentheses result in exactly one value.
 
 \item
-A function call as the last expression in a list constructor 
+A function call as the last expression in a list constructor
 (like \verb|{a,b,f()}}|) has all its return values inserted in the list.
 
 \item
@@ -4211,28 +4031,26 @@ The \verb|lua_pushuserdata| function has been replaced by
 	\opt{\rwd{else} block} \rwd{end}
 \OrNL	\rwd{return} \opt{explist1}
 \OrNL	\rwd{break}
-\OrNL	\rwd{for} \Nter{name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
+\OrNL	\rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
 	\rwd{do} block \rwd{end}
-\OrNL   \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp
+\OrNL   \rwd{for} \Nter{Name} \opt{\ter{,} \Nter{Name}} \rwd{in} exp
                     \rwd{do} block \rwd{end}
 \OrNL	\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
 \OrNL	\rwd{local} namelist \opt{init}
 }
 
-\produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}}
-                              \opt{\ter{:} \Nter{name}}}
+\produc{funcname}{\Nter{Name} \rep{\ter{.} \Nter{Name}}
+                              \opt{\ter{:} \Nter{Name}}}
 
 \produc{varlist1}{var \rep{\ter{,} var}}
 
 \produc{var}{%
-	\Nter{name}
-\Or	varorfunc \ter{[} exp \ter{]}
-\Or	varorfunc \ter{.} \Nter{name}
+	\Nter{Name}
+\Or	prefixexp \ter{[} exp \ter{]}
+\Or	prefixexp \ter{.} \Nter{Name}
 }
 
-\produc{varorfunc}{var \Or functioncall}
-
-\produc{namelist}{\Nter{name} \rep{\ter{,} \Nter{name}}}
+\produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}}
 
 \produc{init}{\ter{=} explist1}
 
@@ -4240,65 +4058,48 @@ The \verb|lua_pushuserdata| function has been replaced by
 
 \produc{exp}{%
 	\rwd{nil}
-\Or	\Nter{number}
-\Or	\Nter{literal}
-\Or	var
+\Or	\Nter{Number}
+\Or	\Nter{Literal}
 \Or	function
-\Or	upvalue
-\OrNL	functioncall
-\Or	tableconstructor
-\Or	\ter{(} exp \ter{)}
+\Or	prefixexp
+\OrNL	tableconstructor
 \Or	exp binop exp
 \Or	unop exp
 }
 
+\produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}}
 
 \produc{functioncall}{%
-	varorfunc args
-\Or	varorfunc \ter{:} \Nter{name} args
+	prefixexp args
+\Or	prefixexp \ter{:} \Nter{Name} args
 }
 
 \produc{args}{%
 	\ter{(} \opt{explist1} \ter{)}
 \Or	tableconstructor
-\Or	\Nter{literal}
+\Or	\Nter{Literal}
 }
 
 \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}}
 
 \produc{parlist1}{%
-	\ter{\ldots}
-\Or	\Nter{name} \rep{\ter{,} \Nter{name}} \opt{\ter{,} \ter{\ldots}}
+	\Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}}
+\Or	\ter{\ldots}
 }
 
-\produc{upvalue}{\ter{\%} \Nter{name}}
-
-\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
-\produc{fieldlist}{%
-	lfieldlist
-\Or	ffieldlist
-\Or	lfieldlist \ter{;} ffieldlist
-\Or	ffieldlist \ter{;} lfieldlist
-}
-\produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}}
-\produc{ffieldlist}{\opt{ffieldlist1}}
-\produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}}
-\produc{ffield}{%
-	\ter{[} exp \ter{]} \ter{=} exp
-\Or	\Nter{name} \ter{=} exp
-}
+\produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}}
+\produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}}
+\produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp}
+\produc{fieldsep}{\ter{,} \Or \ter{;}}
 
 \produc{binop}{\ter{+} \Or \ter{-} \Or \ter{*} \Or \ter{/} \Or \ter{\^{ }} \Or
-  \ter{..} \OrNL \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=}
+  \ter{..} \Or \ter{<} \Or \ter{<=} \Or \ter{>} \Or \ter{>=}
   \Or \ter{==} \Or \ter{\~{ }=} \OrNL \rwd{and} \Or \rwd{or}}
 
 \produc{unop}{\ter{-} \Or \rwd{not}}
 
 \end{Produc}
 
-
-\NOTE
-This grammar is not (yet) consistent with the productions in the text.
 %}===============================================================
 
 % Index
-- 
cgit v1.2.3-55-g6feb

