From f4d3bc52f486bb1f0d32c6240faffb0e63bbb8fe Mon Sep 17 00:00:00 2001
From: Roberto Ierusalimschy <roberto@inf.puc-rio.br>
Date: Mon, 18 Nov 2002 12:39:34 -0200
Subject: towards 5.0 beta

---
 manual.tex | 456 +++++++++++++++++++++++++++++++++++++++----------------------
 1 file changed, 293 insertions(+), 163 deletions(-)

(limited to 'manual.tex')

diff --git a/manual.tex b/manual.tex
index bd1f9464..0ae9459b 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
-% $Id: manual.tex,v 1.61 2002/08/13 20:00:51 roberto Exp roberto $
+% $Id: manual.tex,v 1.63 2002/11/18 14:37:57 roberto Exp $
 %{[(
 
 \documentclass[11pt,twoside]{article}
@@ -26,7 +26,7 @@
 \newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}}
 \newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}}
 \newcommand{\IndexEmph}[1]{\emph{#1}\index{#1@{\lowercase{#1}}}}
-\newcommand{\IndexTM}[1]{\index{#1 event@{``#1'' event}}\index{tag method!#1}}
+\newcommand{\IndexTM}[1]{\index{#1 event@{``#1'' event}}\index{metamethod!#1}}
 \newcommand{\Def}[1]{\emph{#1}\index{#1}}
 \newcommand{\IndexAPI}[1]{\T{#1}\DefAPI{#1}}
 \newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}}
@@ -36,7 +36,7 @@
 
 \newcommand{\ff}{$\bullet$\ }
 
-\newcommand{\Version}{5.0 (alpha)}
+\newcommand{\Version}{5.0 (beta)}
 
 % changes to bnf.sty by LHF
 \renewcommand{\Or}{$|$ }
@@ -58,7 +58,7 @@
 \parindent=0pt
 \vglue1.5in
 {\LARGE\bf
-The Programming Language Lua}
+The Lua Programming Language}
 \hfill
 \vskip4pt \hrule height 4pt width \hsize \vskip4pt
 \hfill
@@ -134,7 +134,7 @@ Waldemar Celes
 \tecgraf\ --- Computer Science Department --- PUC-Rio
 }
 
-%\date{{\small \tt\$Date: 2002/08/13 20:00:51 $ $}}
+%\date{{\small \tt\$Date: 2002/11/18 14:37:57 $ $}}
 
 \maketitle
 
@@ -272,8 +272,7 @@ This environment is initialized with a call from the embedding program to
 \verb|lua_open| and
 persists until a call to \verb|lua_close|
 or the end of the embedding program.
-If necessary,
-the host programmer can create multiple independent global
+The host program can create multiple independent global
 environments, and freely switch between them \see{mangstate}.
 
 The unit of execution of Lua is called a \Def{chunk}.
@@ -285,13 +284,12 @@ 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.
-All modifications a chunk effects on the global environment persist
+All modifications a chunk makes to the global environment persist
 after the chunk ends.
 
 Chunks may also be pre-compiled into binary form and stored in files;
 see program \IndexVerb{luac} for details.
-Text files with chunks and their binary pre-compiled forms
-are interchangeable;
+Programs in source and compiled forms are interchangeable;
 Lua automatically detects the file type and acts accordingly.
 \index{pre-compilation}
 
@@ -315,8 +313,8 @@ There are seven \Index{basic types} in Lua:
 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.
+In Lua, both \nil{} and \False{} make a condition false,
+and any other value makes it true.
 \emph{Number} represents real (double-precision floating-point) numbers.
 \emph{String} represents arrays of characters.
 \index{eight-bit clean}
@@ -331,8 +329,8 @@ Lua can call (and manipulate) functions written in Lua and
 functions written in C
 \see{functioncall}.
 
-The type \emph{userdata} is provided to allow the store of
-arbitrary C data in Lua variables.
+The type \emph{userdata} is provided to allow arbitrary C data to
+be stored in Lua variables.
 This type corresponds to a block of raw memory
 and has no pre-defined operations in Lua,
 except assignment and identity test.
@@ -367,7 +365,7 @@ So, tables may also carry \emph{methods} \see{func-def}.
 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
+Assignment, parameter passing, and function returns
 always manipulate references to these values,
 and do not imply any kind of copy.
 
@@ -377,7 +375,7 @@ of a given value \see{pdf-type}.
 
 \subsubsection{Metatables}
 
-Each table or userdata object in Lua may have a \Index{metatable}.
+Each table and 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.
@@ -389,11 +387,11 @@ Lua calls that function to perform the addition.
 We call the keys in a metatable \Index{events},
 and the values \Index{metamethods}.
 In the previous example, \verb|"add"| is the event,
-and the metamethod is the function that performs the addition.
+and the function is the metamethod that performs the addition.
 
 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
+A metatable can also define a function to be called when a userdata
 is garbage collected.
 \See{metatable} gives a detailed description of which events you
 can control with metatables.
@@ -499,7 +497,12 @@ A table with both weak keys and weak values allows the collection of
 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 set with the \verb|setmode| function.
+The weakness of a table is controled by the value of the
+\verb|__mode| field of its metatable.
+If the \verb|__mode| field is a string containing the \verb|k| character,
+the keys in the table are weak.
+If \verb|__mode| contains \verb|v|,
+the values in the table are weak.
 
 
 %------------------------------------------------------------------------------
@@ -527,10 +530,10 @@ and cannot be used as identifiers:
 \index{reserved words}
 \begin{verbatim}
        and       break     do        else      elseif
-       end       false     for       function  global
-       if        in        local     nil       not
-       or        repeat    return    then      true
-       until     while
+       end       false     for       function  if
+       in        local     nil       not       or
+       repeat    return    then      true      until
+       while
 \end{verbatim}
 
 Lua is a case-sensitive language:
@@ -542,8 +545,8 @@ are reserved for internal variables.
 
 The following strings denote other \Index{tokens}:
 \begin{verbatim}
-       +     -     *     /     ^     %
-       ~=    <=    >=    <     >     ==    =
+       +     -     *     /     ^     =
+       ~=    <=    >=    <     >     ==
        (     )     {     }     [     ]
        ;     :     ,     .     ..    ...
 \end{verbatim}
@@ -1048,17 +1051,9 @@ from lower to higher priority:
        not   - (unary)
        ^
 \end{verbatim}
-All binary operators are left associative,
-except for \verb|^| (exponentiation),
-which is right associative.
-\NOTE
-The pre-compiler may rearrange the order of evaluation of
-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)
-metamethods for those operators.
+The \verb|..| (concatenation) and \verb|^| (exponentiation)
+operators are right associative.
+All other binary operators are left associative.
 
 \subsubsection{Table Constructors} \label{tableconstructor}
 Table \Index{constructors} are expressions that create tables;
@@ -1561,12 +1556,7 @@ the \verb|..| (concatenation) operation.
 \end{verbatim}
 
 \item[``index'':]\IndexTM{index}
-This handler is called when Lua tries to retrieve the value of an index
-not present in a table.
-See the ``gettable'' operation for its semantics.
-
-\item[``gettable'':]\IndexTM{gettable}
-called whenever Lua accesses an indexed variable.
+The ``gettable'' operation \verb|table[key]|.
 \begin{verbatim}
        function gettable_event (table, key)
          local h
@@ -1576,7 +1566,7 @@ called whenever Lua accesses an indexed variable.
            h = metatable(table).__index
            if h == nil then return nil end
          else
-           h = metatable(table).__gettable
+           h = metatable(table).__index
            if h == nil then
              error("indexed expression not a table");
            end
@@ -1588,12 +1578,7 @@ called whenever Lua accesses an indexed variable.
 \end{verbatim}
 
 \item[``newindex'':]\IndexTM{index}
-This handler is called when Lua tries to insert the value of an index
-not present in a table.
-See the ``settable'' operation for its semantics.
-
-\item[``settable'':]\IndexTM{settable}
-called when Lua assigns to an indexed variable.
+The ``settable'' operation \verb|table[key] = value|.
 \begin{verbatim}
        function settable_event (table, key, value)
          local h
@@ -1603,7 +1588,7 @@ called when Lua assigns to an indexed variable.
            h = metatable(table).__newindex
            if h == nil then rawset(table, key, value); return end
          else
-           h = metatable(table).__settable
+           h = metatable(table).__newindex
            if h == nil then
              error("indexed expression not a table");
            end
@@ -1658,6 +1643,56 @@ with the last userdata created in the program
 
 
 
+\subsection{Coroutines}
+
+Lua supports coroutines,
+also called \emph{semi-coroutines}, \emph{generators},
+or \emph{colaborative multithreading}.
+A coroutine in Lua represents an independent thread of execution.
+Unlike ``real'' threads, however,
+a coroutine only suspends its execution by explicitly calling
+an yield function.
+
+You create a coroutine with a call to \verb|coroutine.create|.
+Its sole argument is a function,
+which is the main function of the coroutine.
+The \verb|coroutine.create| only creates a new coroutine and
+returns a handle to it (an object of type \emph{thread}).
+It does not start the coroutine execution.
+
+When you first call \verb|coroutine.resume|,
+passing as argument the thread returned by \verb|coroutine.create|,
+the coroutine starts its execution,
+at the first line of its main function.
+Extra arguments passed to \verb|coroutine.resume| are given as
+parameters for the coroutine main function.
+After the coroutine starts running,
+it runs until it terminates or it \emph{yields}.
+
+A coroutine can terminate its execution in two ways:
+Normally, when its main function returns
+(explicitly or implicitly, after the last instruction);
+and abnormally, if there is an unprotected error.
+In the first case, \verb|coroutine.resume| returns \True,
+plus any values returned by the coroutine main function.
+In case of errors, \verb|coroutine.resume| returns \False
+plus an error message.
+
+A coroutine yields calling \verb|coroutine.yield|.
+When a coroutine yields,
+the corresponding \verb|coroutine.resume| returns immediately,
+even if the yield happens inside nested function calls
+(that is, not in the main function,
+but in a function directly or indirectly called by the main function).
+In the case of a yield, \verb|coroutine.resume| also returns \True,
+plus any values passed to \verb|coroutine.yield|.
+The next time you resume the same coroutine,
+it continues its execution from the point where it yielded,
+with the call to \verb|coroutine.yield| returning any extra
+arguments passed to \verb|coroutine.resume|.
+
+
+
 %------------------------------------------------------------------------------
 \section{The Application Program Interface}\label{API}
 \index{C API}
@@ -1682,7 +1717,7 @@ The Lua library is fully reentrant:
 it has no global variables.
 \index{state}
 The whole state of the Lua interpreter
-(global variables, stack, tag methods, etc.)\
+(global variables, stack, etc.)
 is stored in a dynamically allocated structure of type \verb|lua_State|;
 \DefAPI{lua_State}
 this state must be passed as the first argument to
@@ -1703,8 +1738,8 @@ To release a state created with \verb|lua_open|, call
 This function destroys all objects in the given Lua environment
 (calling the corresponding garbage-collection metamethods, if any)
 and frees all dynamic memory used by that state.
-Usually, you do not need to call this function,
-because all resources are naturally released when your program ends.
+On several platforms, you may not need to call this function,
+because all resources are naturally released when the host program ends.
 On the other hand,
 long-running programs ---
 like a daemon or a web server ---
@@ -1727,7 +1762,7 @@ The following function creates a new ``thread'' in Lua:
 \end{verbatim}
 \DefAPI{lua_newthread}
 The new state returned by this function shares with the original state
-all global environment (such as tables, tag methods, etc.),
+all global environment (such as tables),
 but has an independent run-time stack.
 (The use of these multiple stacks must be ``syncronized'' with C.
 How to explain that? TO BE WRITTEN.)
@@ -1754,6 +1789,8 @@ Each C invocation has its own stack.
 Whenever Lua calls C, the called function gets a new stack,
 which is independent of previous stacks or of stacks of still
 active C functions.
+That stack contains initially any arguments to the C function,
+and it is where the C function pushes its results \see{LuacallC}.
 
 For convenience,
 most query operations in the API do not follow a strict stack discipline.
@@ -1872,8 +1909,8 @@ then
        lua_insert(L,  1)      --> 30 10 20 30 40*
        lua_insert(L, -1)      --> 30 10 20 30 40*  (no effect)
        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*
+       lua_settop(L, -3)      --> 30 40*
+       lua_settop(L,  6)      --> 30 40 nil nil nil nil*
 \end{verbatim}
 
 
@@ -1883,22 +1920,22 @@ then
 To check the type of a stack element,
 the following functions are available:
 \begin{verbatim}
-       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);
-       int         lua_isfunction  (lua_State *L, int index);
-       int         lua_iscfunction (lua_State *L, int index);
-       int         lua_isuserdata  (lua_State *L, int index);
-       int         lua_isdataval   (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);
+       int         lua_isfunction      (lua_State *L, int index);
+       int         lua_iscfunction     (lua_State *L, int index);
+       int         lua_isuserdata      (lua_State *L, int index);
+       int         lua_islightuserdata (lua_State *L, int index);
 \end{verbatim}
 \DefAPI{lua_type}
 \DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring}
 \DefAPI{lua_istable}\DefAPI{lua_isboolean}
 \DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}
-\DefAPI{lua_isuserdata}\DefAPI{lua_isdataval}
+\DefAPI{lua_isuserdata}\DefAPI{lua_islightuserdata}
 These functions can be called with any acceptable index.
 
 \verb|lua_type| returns the type of a value in the stack,
@@ -1925,13 +1962,16 @@ 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).
+as any value has a boolean value).
 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},
-and \verb|lua_isfunction| accepts both Lua functions and C~functions.
+\verb|lua_isfunction| accepts both Lua functions and C~functions,
+and \verb|lua_isuserdata| accepts both full and ligth userdata.
 To distinguish between Lua functions and C~functions,
 you should use \verb|lua_iscfunction|.
+To distinguish between full and ligth userdata,
+you can use \verb|lua_islightuserdata|.
 To distinguish between numbers and numerical strings,
 you can use \verb|lua_type|.
 
@@ -2178,6 +2218,22 @@ You can load a Lua chunk with
                                    const char *chunkname);
 \end{verbatim}
 \DefAPI{Chunkreader}\DefAPI{lua_load}
+The return values of \verb|lua_load| are:
+\begin{itemize}
+\item 0 --- no errors;
+\item \IndexAPI{LUA_ERRSYNTAX} ---
+syntax error during pre-compilation.
+\item \IndexAPI{LUA_ERRMEM} ---
+memory allocation error.
+\end{itemize}
+If there are no errors,
+\verb|lua_load| pushes the compiled chunk as a Lua
+function on top of the stack.
+Otherwise, it pushes an error message.
+
+\verb|lua_load| automatically detects whether the chunk is text or binary,
+and loads it accordingly (see program \IndexVerb{luac}).
+
 \verb|lua_load| uses the \emph{reader} to read the chunk.
 Everytime it needs another piece of the chunk,
 it calls the reader,
@@ -2192,21 +2248,6 @@ In the current implementation,
 the reader function cannot call any Lua function;
 to ensure that, it always receives \verb|NULL| as the Lua state.
 
-\verb|lua_load| automatically detects whether the chunk is text or binary,
-and loads it accordingly (see program \IndexVerb{luac}).
-
-The return values of \verb|lua_load| are:
-\begin{itemize}
-\item 0 --- no errors;
-\item \IndexAPI{LUA_ERRSYNTAX} ---
-syntax error during pre-compilation.
-\item \IndexAPI{LUA_ERRMEM} ---
-memory allocation error.
-\end{itemize}
-If there are no errors,
-the compiled chunk is pushed as a Lua function on top of the stack.
-Otherwise, an error message is pushed.
-
 The \emph{chunkname} is used for error messages
 and debug information \see{debugI}.
 
@@ -2446,20 +2487,19 @@ error while running the error handler function.
 Some special Lua functions have their own C~interfaces.
 The host program can generate a Lua error calling the function
 \begin{verbatim}
-       void lua_error (lua_State *L, const char *message);
+       void lua_error (lua_State *L);
 \end{verbatim}
 \DefAPI{lua_error}
+The error message (which actually can be any type of object)
+is popped from the stack.
 This function never returns.
-If \verb|lua_error| is called from a C~function that has been called from Lua,
+If \verb|lua_error| is called from a C~function that
+has been called from Lua,
 then the corresponding Lua execution terminates,
 as if an error had occurred inside Lua code.
 Otherwise, the whole host program terminates with a call to
 \verb|exit(EXIT_FAILURE)|.
-Before terminating execution,
-the \verb|message| is passed to the error handler function,
-\verb|_ERRORMESSAGE| \see{error}.
-If \verb|message| is \verb|NULL|,
-then \verb|_ERRORMESSAGE| is not called.
+%% TODO: at_panic
 
 The function
 \begin{verbatim}
@@ -2476,6 +2516,7 @@ Concatenation is done following the usual semantics of Lua
 
 
 \subsection{Defining C Functions} \label{LuacallC}
+
 Lua can be extended with functions written in~C.
 These functions must be of type \verb|lua_CFunction|,
 which is defined as
@@ -2489,8 +2530,10 @@ the number of values it has returned to Lua.
 In order to communicate properly with Lua,
 a C~function must follow the following protocol,
 which defines the way parameters and results are passed:
-A C~function receives its arguments from Lua in the stack,
+A C~function receives its arguments from Lua in its stack,
 in direct order (the first argument is pushed first).
+So, when the function starts,
+its first argument (if any) is at index 1.
 To return values to Lua, a C~function just pushes them onto the stack,
 in direct order (the first result is pushed first),
 and returns the number of results.
@@ -2617,7 +2660,7 @@ The structure \verb|lua_Debug| is used to carry different pieces of
 information about an active function:
 \begin{verbatim}
       typedef struct lua_Debug {
-        lua_Hookevent event;
+        int event;
         const char *name;      /* (n) */
         const char *namewhat;  /* (n) `global', `local', `field', `method' */
         const char *what;      /* (S) `Lua' function, `C' function, Lua `main' */
@@ -2768,11 +2811,9 @@ a \emph{call} event, when Lua calls a function;
 a \emph{return} event, when Lua returns from a function;
 a \emph{line} event, when Lua starts executing a new line of code;
 and a \emph{count} event, that happens every ``count'' instructions.
-Lua identifies them with the following enumeration:
-\begin{verbatim}
-typedef enum lua_Hookevent {
-  LUA_HOOKCALL, LUA_HOOKRET, LUA_HOOKLINE, LUA_HOOKCOUNT
-} lua_Hookevent;
+Lua identifies them with the following constants:
+\DefAPI{LUA_HOOKCALL}, \DefAPI{LUA_HOOKRET},
+\DefAPI{LUA_HOOKLINE}, and \DefAPI{LUA_HOOKCOUNT}.
 \end{verbatim}
 
 A hook has type \verb|lua_Hook|, defined as follows:
@@ -2792,7 +2833,22 @@ It is formed by a disjunction of the constants
 \verb|LUA_MASKRET|,
 \verb|LUA_MASKLINE|,
 plus the macro \verb|LUA_MASKCOUNT(count)|.
-%TODO explicar melhor...
+For each event, the hook is called as explained below:
+\begin{description}
+\item{call hook} called when the interpreter calls a function.
+The hook is called just after Lua ``enters'' the new function.
+\item{return hook} called when the interpreter returns from a function.
+The hook is called just before Lua ``leaves'' the function.
+\item{line hook} called when the interpreter is about to
+start the execution of a new line of code,
+or when it jumps back (even for the same line).
+(For obvious reasons, this event does not happens while Lua is executing
+a C function.)
+\item{count hook} called after the interpreter executes every
+\verb|count| instructions.
+(For obvious reasons, this event does not happens while Lua is executing
+a C function.)
+\end{description}
 
 A hook is disabled with the mask zero.
 
@@ -2811,7 +2867,7 @@ For the value of any other field, the hook must call \verb|lua_getinfo|.
 
 While Lua is running a hook, it disables other calls to hooks.
 Therefore, if a hook calls Lua to execute a function or a chunk,
-this execution ocurrs without any calls to hooks.
+that execution ocurrs without any calls to hooks.
 
 
 %------------------------------------------------------------------------------
@@ -2844,16 +2900,19 @@ or as methods of its objects.
 
 To have access to these libraries,
 the C~host program must call the functions
-\verb|lua_baselibopen|,
-\verb|lua_strlibopen|,
-\verb|lua_tablibopen|,
-\verb|lua_mathlibopen|,
-and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|.
+\verb|lua_baselibopen| (for the basic library),
+\verb|lua_strlibopen| (for the string library),
+\verb|lua_tablibopen| (for the table library),
+\verb|lua_mathlibopen| (for the mathematical library),
+\verb|lua_iolibopen| (for the I/O and the Operating System libraries),
+and \verb|lua_dblibopen| (for the debug library),
+which are declared in \verb|lualib.h|.
 \DefAPI{lua_baselibopen}
 \DefAPI{lua_strlibopen}
 \DefAPI{lua_tablibopen}
 \DefAPI{lua_mathlibopen}
 \DefAPI{lua_iolibopen}
+\DefAPI{lua_dblibopen}
 
 
 \subsection{Basic Functions} \label{predefined}
@@ -2863,7 +2922,7 @@ If you do not include this library in your application,
 you should check carefully whether you need to provide some alternative
 implementation for some facilities.
 
-The basic library also defines a global variable \IndexAPI{_VERSION}
+The basic library also defines a global variable \IndexLIB{_VERSION}
 with a string containing the current interpreter version.
 The current content of this string is {\tt "Lua \Version"}.
 
@@ -2897,11 +2956,19 @@ When called without arguments,
 \verb|dofile| executes the contents of the standard input (\verb|stdin|).
 Returns any value returned by the chunk.
 
-\subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error}
+\subsubsection*{\ff \T{error (message [, level])}}
+DefLIB{error}\label{pdf-error}
 Terminates the last protected function called,
 and returns \verb|message| as the error message.
 Function \verb|error| never returns.
 
+The \verb|level| argument affects to where the error
+message points the error.
+With level 1 (the default), the error position is where the
+\verb|error| function was called.
+Level 2 points the error to where the function
+that called \verb|error| was called; and so on.
+
 \subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals}
 Returns the current table of globals in use by the function.
 \verb|function| can be a Lua function or a number,
@@ -2917,13 +2984,6 @@ The default for \verb|function| is 1.
 Returns the metatable of the given object.
 If the object does not have a metatable, returns \nil.
 
-\subsubsection*{\ff \T{getmode (table)}}\DefLIB{getmode}
-
-Returns the weak mode of a table, as a string.
-Valid values for this string are \verb|""| for regular (non-weak) tables,
-\verb|"k"| for weak keys, \verb|"v"| for weak values,
-and \verb|"kv"| for both.
-
 \subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo}
 Returns the number of Kbytes of dynamic memory Lua is using,
 and (as a second result) the
@@ -2931,7 +2991,7 @@ current garbage collector threshold (also in Kbytes).
 
 \subsubsection*{\ff \T{ipairs (t)}}\DefLIB{ipairs}
 
-Returns the table \verb|t| and a generator function
+Returns a generator function and the table \verb|t|,
 so that the construction
 \begin{verbatim}
        for i,v in ipairs(t) do ... end
@@ -2988,7 +3048,7 @@ the table during the traversal.
 
 \subsubsection*{\ff \T{pairs (t)}}\DefLIB{pairs}
 
-Returns the table \verb|t| and the function \verb|next|,
+Returns the function \verb|next| and the table \verb|t|,
 so that the construction
 \begin{verbatim}
        for k,v in pairs(t) do ... end
@@ -2999,7 +3059,11 @@ will iterate over all pairs of key--value of table \verb|t|.
 \label{pdf-pcall}
 Calls function \verb|func| with
 the given arguments in protected mode.
-Its first result is a boolean, true if the call succeeds without errors.
+That means that any error inside \verb|func| is not propagated;
+instead, \verb|pcall| catches the error,
+returning a status code.
+Its first result is the status code (a boolean),
+true if the call succeeds without errors.
 In such case, \verb|pcall| also returns all results from the call,
 after this first result.
 In case of any error, \verb|pcall| returns false plus the error message.
@@ -3015,13 +3079,13 @@ For formatted output, see \verb|format| \see{format}.
 
 \subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget}
 Gets the real value of \verb|table[index]|,
-without invoking any tag method.
+without invoking any metamethod.
 \verb|table| must be a table;
 \verb|index| is any value different from \nil.
 
 \subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset}
 Sets the real value of \verb|table[index]| to \verb|value|,
-without invoking any tag method.
+without invoking any metamethod.
 \verb|table| must be a table;
 \verb|index| is any value different from \nil;
 and \verb|value| is any Lua value.
@@ -3077,16 +3141,6 @@ Sets the metatable for the given table.
 (You cannot change the metatable of a userdata from Lua.)
 If \verb|metatable| is \nil, removes the metatable of the given table.
 
-\subsubsection*{\ff \T{setmode (table, mode)}}\DefLIB{setmode}
-
-Set the weak mode of a table.
-The new mode is described by the \verb|mode| string.
-Valid values for this string are \verb|""| for regular (non-weak) tables,
-\verb|"k"| for weak keys, \verb|"v"| for weak values,
-and \verb|"kv"| for both.
-
-This function returns its first argument (\verb|table|).
-
 \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
@@ -3249,7 +3303,31 @@ String values to be formatted with
 
 \subsubsection*{\ff \T{string.gfind (s, pat)}}
 
-% TODO
+Returns a generator function that,
+each time it is called,
+returns the next captures from pattern \verb|pat| over string \verb|s|.
+
+If \verb|pat| specifies no captures,
+then the whole match is produced in each call.
+
+As an example, the following loop
+\begin{verbatim}
+  s = "hello world from Lua"
+  for w in string.gfind(s, "%a+") do
+    print(w)
+  end
+\end{verbatim}
+will iterate over all the words from string \verb|s|,
+printing each one in a line.
+The next example collects all pairs \verb|key=value| from the
+given string into a table:
+\begin{verbatim}
+  t = {}
+  s = "from=world, to=Lua"
+  for k, v in string.gfind(s, "(%w+)=(%w+)") do
+    t[k] = v
+  end
+\end{verbatim}
 
 \subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}}
 \DefLIB{string.gsub}
@@ -3280,24 +3358,28 @@ For instance, when \verb|n| is 1 only the first occurrence of
 
 Here are some examples:
 \begin{verbatim}
-   x = gsub("hello world", "(%w+)", "%1 %1")
+   x = string.gsub("hello world", "(%w+)", "%1 %1")
    --> x="hello hello world world"
 
-   x = gsub("hello world", "(%w+)", "%1 %1", 1)
+   x = string.gsub("hello world", "(%w+)", "%1 %1", 1)
    --> x="hello hello world"
 
-   x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
+   x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
    --> x="world hello Lua from"
 
-   x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv)
+   x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
    --> x="home = /home/roberto, user = roberto"  (for instance)
 
-   x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
+   x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
+         return loadstring(s)()
+       end)
    --> x="4+5 = 9"
 
-   local t = {name="Lua", version="4.1"}
-   x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end)
-   --> x="Lua - 4.1"
+   local t = {name="Lua", version="5.0"}
+   x = string.gsub("$name - $version", "%$(%w+)", function (v)
+         return t[v]
+       end)
+   --> x="Lua - 5.0"
 \end{verbatim}
 
 
@@ -3416,6 +3498,11 @@ stored as the first capture (and therefore has number~1);
 the character matching \verb|.| is captured with number~2,
 and the part matching \verb|%s*| has number~3.
 
+As a special case, the empty capture \verb|()| captures
+the current string position (a number).
+For instance, if we apply the pattern \verb|"()aa()"| on the
+string \verb|"flaaap"|, there will be two captures: 3 and 5.
+
 \NOTE
 A pattern cannot contain embedded zeros.  Use \verb|%z| instead.
 
@@ -3442,6 +3529,14 @@ with a \nil{} value.
 For more details, see the descriptions of the \verb|table.getn| and
 \verb|table.setn| functions.
 
+\subsubsection*{\ff \T{table.concat (table [, sep [, i [, j]]])}}
+\DefLIB{table.concat}
+Returns \verb|table[i]..sep..table[i+1] ... sep..table[j]|.
+The default value for \verb|sep| is the empty string,
+the default for \verb|i| is 1,
+and the default for \verb|j| is the size of the table.
+If \verb|i| is greater than \verb|j|, returns the empty string.
+
 \subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach}
 Executes the given \verb|func| over all elements of \verb|table|.
 For each element, \verb|func| is called with the index and
@@ -3560,6 +3655,7 @@ The library provides the following functions:
 plus a variable \IndexLIB{math.pi}.
 Most of them
 are only interfaces to the homonymous functions in the C~library.
+All trigonometric functions work in radians.
 The functions \verb|math.deg| and \verb|math.rad| convert
 between radians and degrees.
 
@@ -3579,6 +3675,9 @@ When called with a number \Math{n},
 \verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}.
 When called with two arguments, \Math{l} and \Math{u},
 \verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}.
+The \verb|math.randomseed| function sets a ``seed''
+for the pseudo-random generator:
+Equal seeds produce equal sequences of numbers.
 
 
 \subsection{Input and Output Facilities} \label{libio}
@@ -3611,12 +3710,12 @@ and some value different from \nil{} on success.
 
 \subsubsection*{\ff \T{io.close ([handle])}}\DefLIB{io.close}
 
-Equivalent to \verb|handle:close()|.
+Equivalent to \verb|file:close()|.
 Without a \verb|handle|, closes the default output file.
 
 \subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush}
 
-Equivalent to \verb|fh:flush| over the default output file.
+Equivalent to \verb|file:flush| over the default output file.
 
 \subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input}
 
@@ -3631,6 +3730,24 @@ it returns the current default input file.
 In case of errors this function raises the error,
 instead of returning an error code.
 
+\subsubsection*{\ff \T{io.lines ([filename])}}\DefLIB{io.lines}
+
+Opens the given file name in read mode,
+and returns a generator function that,
+each time it is called,
+returns a new line from the file.
+Therefore, the construction
+\begin{verbatim}
+       for lines in io.lines(filename) do ... end
+\end{verbatim}
+will iterate over all lines of the file.
+When the generator function detects the end of file,
+it returns nil (to finish the loop) and automatically closes the file.
+
+The call \verb|io.lines()| (without a file name) is equivalent
+to \verb|io.input():lines()|, that is, it iterates over the
+lines of the default input file.
+
 \subsubsection*{\ff \T{io.open (filename, mode)}}\DefLIB{io.open}
 
 This function opens a file,
@@ -3658,7 +3775,7 @@ Similar to \verb|io.input|, but operates over the default output file.
 
 \subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read}
 
-Equivalent to \verb|fh:read| over the default input file.
+Equivalent to \verb|file:read| over the default input file.
 
 \subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile}
 
@@ -3668,21 +3785,34 @@ and it is automatically removed when the program ends.
 
 \subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write}
 
-Equivalent to \verb|fh:write| over the default output file.
+Equivalent to \verb|file:write| over the default output file.
+
 
 
+\subsubsection*{\ff \T{file:close ()}}\DefLIB{file:close}
 
-\subsubsection*{\ff \T{fh:close ([handle])}}\DefLIB{fh:close}
+Closes the file \verb|file|.
 
-Closes the file \verb|fh|.
+\subsubsection*{\ff \T{file:flush ()}}\DefLIB{file:flush}
 
-\subsubsection*{\ff \T{fh:flush ()}}\DefLIB{fh:flush}
+Saves any written data to the file \verb|file|.
 
-Saves any written data to the file \verb|fh|.
+\subsubsection*{\ff \T{file:lines ()}}\DefLIB{file:lines}
+
+Returns a generator function that,
+each time it is called,
+returns a new line from the file.
+Therefore, the construction
+\begin{verbatim}
+       for lines in file:lines() do ... end
+\end{verbatim}
+will iterate over all lines of the file.
+(Unlike \verb|io.lines|, this function does not close the file
+when the loop ends.)
 
-\subsubsection*{\ff \T{fh:read (format1, ...)}}\DefLIB{fh:read}
+\subsubsection*{\ff \T{file:read (format1, ...)}}\DefLIB{file:read}
 
-Reads the file \verb|fh|,
+Reads the file \verb|file|,
 according to the given formats, which specify what to read.
 For each format,
 the function returns a string (or a number) with the characters read,
@@ -3707,7 +3837,7 @@ it reads nothing and returns an empty string,
 or \nil{} on end of file.
 \end{description}
 
-\subsubsection*{\ff \T{fh:seek ([whence] [, offset])}}\DefLIB{fh:seek}
+\subsubsection*{\ff \T{file:seek ([whence] [, offset])}}\DefLIB{file:seek}
 
 Sets and gets the file position,
 measured in bytes from the beginning of the file,
@@ -3732,10 +3862,10 @@ beginning of the file (and returns 0);
 and the call \verb|file:seek("end")| sets the position to the
 end of the file, and returns its size.
 
-\subsubsection*{\ff \T{fh:write (value1, ...)}}\DefLIB{fh:write}
+\subsubsection*{\ff \T{file:write (value1, ...)}}\DefLIB{file:write}
 
 Writes the value of each of its arguments to
-the filehandle \verb|fh|.
+the filehandle \verb|file|.
 The arguments must be strings or numbers.
 To write other values,
 use \verb|tostring| or \verb|format| before \verb|write|.
@@ -3929,7 +4059,7 @@ and raises an error when called with a \verb|level| out of range.
 Sets the given function as a hook.
 The string \verb|mask| and the number \verb|count| describe
 when the hook will be called.
-The string mask may have the following characteres,
+The string mask may have the following characters,
 with the given meaning:
 \begin{description}
 \item[{\tt "c"}] The hook is called every time Lua calls a function;
@@ -3973,18 +4103,18 @@ The stand-alone interpreter includes
 all standard libraries plus the reflexive debug interface.
 Its usage is:
 \begin{verbatim}
-      lua [options] [prog [args]]
+      lua [options] [script [args]]
 \end{verbatim}
 The options are:
 \begin{description}\leftskip=20pt
 \item[\T{-} ] executes \verb|stdin| as a file;
 \item[\T{-e} \rm\emph{stat}] executes string \emph{stat};
 \item[\T{-l} \rm\emph{file}] executes file \emph{file};
-\item[\T{-i}] enters interactive mode after running \emph{prog};
+\item[\T{-i}] enters interactive mode after running \emph{script};
 \item[\T{-v}] prints version information;
 \item[\T{--}] stop handling options.
 \end{description}
-After handling its options, \verb|lua| runs the given \emph{prog},
+After handling its options, \verb|lua| runs the given \emph{script},
 passing to it the given \emph{args}.
 When called without arguments,
 \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
@@ -3999,20 +4129,20 @@ Otherwise, lua executes the string itself.
 All options are handled in order, except \verb|-i|.
 For instance, an invocation like
 \begin{verbatim}
-       $ lua -e'a=1' -e 'print(a)' prog.lua
+       $ lua -e'a=1' -e 'print(a)' script.lua
 \end{verbatim}
 will first set \verb|a| to 1, then print \verb|a|,
-and finally run the file \verb|prog.lua|.
+and finally run the file \verb|script.lua|.
 (Here, \verb|$| is the shell prompt. Your prompt may be different.)
 
-Before starting to run the program,
+Before starting to run the script,
 \verb|lua| collects all arguments in the command line
 in a global table called \verb|arg|.
-The program name is stored in index 0,
-the first argument after the program goes to index 1,
+The script name is stored in index 0,
+the first argument after the script name goes to index 1,
 and so on.
-The field \verb|n| gets the number of arguments after the program name.
-Any arguments before the program name
+The field \verb|n| gets the number of arguments after the script name.
+Any arguments before the script name
 (that is, the interpreter name plus the options)
 go to negative indices.
 For instance, in the call
@@ -4083,7 +4213,7 @@ Mark Ian Barlow,
 Nick Trout,
 Noemi Rodriguez,
 Norman Ramsey,
-Philippe Lhost,
+Philippe Lhoste,
 Renata Ratton,
 Renato Borges,
 Renato Cerqueira,
-- 
cgit v1.2.3-55-g6feb

