From fdd04e7a7f624dad1a1443e08193241dea935287 Mon Sep 17 00:00:00 2001
From: Roberto Ierusalimschy <roberto@inf.puc-rio.br>
Date: Wed, 9 Aug 2000 16:09:20 -0300
Subject: first version of manual for 4.0 beta

---
 manual.tex | 725 ++++++++++++++++++++++++++++---------------------------------
 1 file changed, 332 insertions(+), 393 deletions(-)

(limited to 'manual.tex')

diff --git a/manual.tex b/manual.tex
index 3d098d32..f808e3c9 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
-% $Id: manual.tex,v 1.38 2000/05/12 19:49:18 roberto Exp roberto $
+% $Id: manual.tex,v 1.39 2000/05/24 13:54:49 roberto Exp roberto $
 
 \documentclass[11pt]{article}
 \usepackage{fullpage,bnf}
@@ -122,7 +122,7 @@ Waldemar Celes
 \tecgraf\ --- Computer Science Department --- PUC-Rio
 }
 
-\date{{\small \tt\$Date: 2000/05/12 19:49:18 $ $}}
+\date{{\small \tt\$Date: 2000/05/24 13:54:49 $ $}}
 
 \maketitle
 
@@ -211,7 +211,7 @@ thus creating customized programming languages sharing a syntactical framework.
 
 Lua is free-distribution software,
 and provided as usual with no guarantees,
-as stated in the copyright notice.
+as stated in its copyright notice.
 The implementation described in this manual is available
 at the following URL's:
 \begin{verbatim}
@@ -242,8 +242,7 @@ Lua: an extensible embedded language.
 \section{Environment and Chunks}
 
 All statements in Lua are executed in a \Def{global environment}.
-This environment, which keeps all global variables,
-is initialized with a call from the embedding program to
+This environment is initialized with a call from the embedding program to
 \verb|lua_newstate| and
 persists until a call to \verb|lua_close|,
 or the end of the embedding program.
@@ -260,11 +259,15 @@ Any variable is assumed to be global unless explicitly declared local
 \see{localvar}.
 Before the first assignment, the value of a global variable is \nil;
 this default can be changed \see{tag-method}.
+A ``table of globals'' (called \emph{tog}) is used to keep all
+global names and values.
 
 The unit of execution of Lua is called a \Def{chunk}.
-A chunk is simply a sequence of statements:
+A chunk is simply a sequence of statements,
+which are executed sequentially.
+Each statement can be optionally followed by a semicolon:
 \begin{Produc}
-\produc{chunk}{\rep{stat} \opt{ret}}
+\produc{chunk}{\rep{stat} \opt{\ter{;}}}
 \end{Produc}%
 Statements are described in \See{stats}.
 (The notation above is the usual extended BNF,
@@ -274,7 +277,6 @@ in which
 \oneormore{\emph{a}} means one or more \emph{a}'s.)
 
 A chunk may be in a file or in a string inside the host program.
-A chunk may optionally end with a \verb|return| statement \see{return}.
 When a chunk is executed, first all its code is pre-compiled,
 and then the statements are executed in sequential order.
 All modifications a chunk effects on the global environment persist
@@ -405,7 +407,8 @@ The following strings denote other \Index{tokens}:
    (   )   {   }   [   ]   ;   ,   .   ..  ...
 \end{verbatim}
 
-\IndexEmph{Literal strings} can be delimited by matching single or double quotes,
+\IndexEmph{Literal strings}
+can be delimited by matching single or double quotes,
 and can contain the C-like escape sequences
 \verb|'\a'| (bell),
 \verb|'\b'| (backspace),
@@ -456,39 +459,6 @@ Examples of valid numerical constants are
    3     3.0     3.1416  314.16e-2   0.31416E1
 \end{verbatim}
 
-\subsection{The \Index{Pre-processor}} \label{pre-processor}
-
-All lines that start with a \verb|$| sign are handled by a pre-processor.
-The following directives are understood by the pre-processor:
-\begin{description}
-\item[\T{\$debug}] --- turn on debugging facilities \see{pragma}.
-\item[\T{\$nodebug}] --- turn off debugging facilities \see{pragma}.
-\item[\T{\$if \M{cond}}] --- start a conditional part.
-If \M{cond} is false, then this part is skipped by the lexical analyzer.
-\item[\T{\$ifnot \M{cond}}] --- start a conditional part.
-If \M{cond} is true, then this part is skipped by the lexical analyzer.
-\item[\T{\$end}] --- end a conditional part.
-\item[\T{\$else}] --- start an ``else'' conditional part,
-flipping the ``skip'' status.
-\item[\T{\$endinput}] --- end the lexical parse of the chunk.
-For all purposes,
-it is as if the chunk physically ended at this point.
-\end{description}
-
-Directives may be freely nested.
-In particular, a \verb|$endinput| may occur inside a \verb|$if|;
-in that case, even the matching \verb|$end| is not parsed.
-
-A \M{cond} part may be
-\begin{description}
-\item[\T{nil}] --- always false.
-\item[\T{1}] --- always true.
-\item[\T{\M{name}}] --- true if the value of the
-global variable \M{name} is different from \nil.
-Note that \M{name} is evaluated \emph{before} the chunk starts its execution.
-Therefore, actions in a chunk do not affect its own conditional directives.
-\end{description}
-
 \subsection{\Index{Coercion}} \label{coercion}
 
 Lua provides some automatic conversions between values at run time.
@@ -501,7 +471,7 @@ a conversion from number to string then back to number
 reproduces the original number \emph{exactly}.
 Thus,
 the conversion does not necessarily produces nice-looking text for some numbers.
-For complete control on how numbers are converted to strings,
+For complete control of how numbers are converted to strings,
 use the \verb|format| function \see{format}.
 
 
@@ -533,18 +503,11 @@ Non-conventional commands include table constructors
 and local variable declarations \see{localvar}.
 
 \subsubsection{Blocks}
-A \Index{block} is a list of statements, which are executed sequentially.
-A statement may be have an optional \Index{label},
-which is syntactically an identifier,
-and can be optionally followed by a semicolon:
+A \Index{block} is a list of statements;
+syntatically, this is equal to a chunk:
 \begin{Produc}
-\produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}}
-\produc{label}{\ter{$\vert$} name \ter{$\vert$}}
+\produc{block}{chunk}
 \end{Produc}%
-\NOTE
-For syntactic reasons, the \rwd{return} and
-\rwd{break} statements can only be written
-as the last statement of a block.
 
 A block may be explicitly delimited:
 \begin{Produc}
@@ -552,7 +515,7 @@ A block may be explicitly delimited:
 \end{Produc}%
 This is useful to control the scope of local variables \see{localvar},
 and to add a \rwd{return} or \rwd{break} statement in the middle
-of another block:
+of another block; for instance,
 \begin{verbatim}
   do return end        -- return is the last statement in this block
 \end{verbatim}
@@ -593,16 +556,17 @@ or a formal parameter:
 \end{Produc}%
 Square brackets are used to index a table:
 \begin{Produc}
-\produc{var}{simpleexp \ter{[} exp1 \ter{]}}
+\produc{var}{varorfunc \ter{[} exp1 \ter{]}}
+\produc{varorfunc}{var \Or functioncall}
 \end{Produc}%
-The \M{simpleexp} should result in a table value,
+The \M{varorfunc} should result in a table value,
 from where the field indexed by the expression \M{exp1}
 value gets the assigned value.
 
 The syntax \verb|var.NAME| is just syntactic sugar for
 \verb|var["NAME"]|:
 \begin{Produc}
-\produc{var}{simpleexp \ter{.} name}
+\produc{var}{varorfunc \ter{.} name}
 \end{Produc}%
 
 The meaning of assignments and evaluations of global variables and
@@ -633,7 +597,8 @@ All values different from \nil\ are considered true;
 only \nil\ is considered false.
 
 \index{return}
-The \rwd{return} statement is used to return values from a function or from a chunk.
+The \rwd{return} statement is used to return values
+from a function or from a chunk.
 \label{return}
 Because functions or chunks may return more than one value,
 the syntax for a \Index{return statement} is
@@ -642,24 +607,24 @@ the syntax for a \Index{return statement} is
 \end{Produc}%
 
 \index{break}
-The \rwd{break} statement can be used to terminate the execution of a block,
-skipping to the next statement after the block:
+The \rwd{break} statement can be used to terminate the execution of a loop,
+skipping to the next statement after the loop:
 \begin{Produc}
-\produc{stat}{\rwd{break} \opt{name}}
+\produc{stat}{\rwd{break}}
 \end{Produc}%
-A \rwd{break} without a label ends the innermost enclosing loop
+A \rwd{break} ends the innermost enclosing loop
 (while, repeat, or for).
-A \rwd{break} with a label breaks the innermost enclosing
-statement with that label.
-Thus,
-labels do not have to be unique.
 
+\NOTE
 For syntactic reasons, \rwd{return} and \rwd{break}
-statements can only be written as the last statement of a block.
+statements can only be written as the last statements of a block.
 
 \subsubsection{For Statement} \label{for}\index{for}
 
-The \rwd{for} statement has the following syntax:
+The \rwd{for} statement has two forms,
+one for numbers and one for tables.
+
+The numerical \rwd{for} loop has the following syntax:
 \begin{Produc}
 \produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
                     \rwd{do} block \rwd{end}}
@@ -692,9 +657,52 @@ before the loop starts.
 you cannot use its value after the \rwd{for} ends.
 \item You can use \rwd{break} to exit a \rwd{for}.
 If you need the value of the index,
-then assign it to another variable before breaking.
+assign it to another variable before breaking.
 \end{itemize}
 
+The table \rwd{for} statement traverses all pairs
+index--value of a given table.
+It has the following syntax:
+\begin{Produc}
+\produc{stat}{\rwd{for} name \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
+\end{verbatim}
+is equivalent to the following code:
+\begin{verbatim}
+  do
+    local _t = exp
+    local index, value = next(t, nil)
+    while index do
+      block
+      index, value = next(t, index)
+    end
+  end
+\end{verbatim}
+Notice the following:
+\begin{itemize}\itemsep=0pt
+\item \verb|_t| is an invisible variable.
+The name is here for explanatory purposes only.
+\item The behavior is undefined if you assign to \verb|index| inside
+the block.
+\item The behavior is undefined if you create
+new indices in table \verb|_t| during the traversal.
+However, it is safe to change the values associated with present indices.
+\item The variables \verb|index| and \verb|value| are local to the statement;
+you cannot use their values after the \rwd{for} ends.
+\item You can use \rwd{break} to exit a \rwd{for}.
+If you need the value of \verb|index| or \verb|value|,
+assign them to other variables before breaking.
+\item The order that table elements are traversed is completely undefined,
+\emph{even for numerical indices}.
+If you want to traverse indices in numerical order,
+use a numerical \rwd{for}.
+\end{itemize}
+
+
 \subsubsection{Function Calls as Statements} \label{funcstat}
 Because of possible side-effects,
 function calls can be executed as statements:
@@ -734,13 +742,10 @@ The basic expressions in Lua are
 \produc{exp}{number}
 \produc{exp}{literal}
 \produc{exp}{function}
-\produc{exp}{simpleexp}
-\end{Produc}%
-\begin{Produc}
-\produc{simpleexp}{var}
-\produc{simpleexp}{upvalue}
-\produc{simpleexp}{functioncall}
-\produc{simpleexp}{tableconstructor}
+\produc{exp}{var}
+\produc{exp}{upvalue}
+\produc{exp}{functioncall}
+\produc{exp}{tableconstructor}
 \end{Produc}%
 
 Numbers (numerical constants) and
@@ -931,7 +936,7 @@ in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
 
 Both forms may have an optional trailing comma,
 and can be used in the same constructor separated by
-a semi-collon.
+a semi-colon.
 For example, all forms below are correct.
 \begin{verbatim}
    x = {;}
@@ -943,27 +948,27 @@ For example, all forms below are correct.
 \subsubsection{Function Calls}  \label{functioncall}
 A \Index{function call} has the following syntax:
 \begin{Produc}
-\produc{functioncall}{simpleexp args}
+\produc{functioncall}{varorfunc args}
 \end{Produc}%
-First, \M{simpleexp} is evaluated.
+First, \M{varorfunc} is evaluated.
 If its value 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{simpleexp},
+having as first parameter the value of \M{varorfunc},
 and then the original call arguments.
 
 The form
 \begin{Produc}
-\produc{functioncall}{simpleexp \ter{:} name args}
+\produc{functioncall}{varorfunc \ter{:} name args}
 \end{Produc}%
 can be used to call ``methods''.
-A call \verb|simpleexp:name(...)|
+A call \verb|varorfunc:name(...)|
 is syntactic sugar for
 \begin{verbatim}
-  simpleexp.name(simpleexp, ...)
+  varorfunc.name(varorfunc, ...)
 \end{verbatim}
-except that \verb|simpleexp| is evaluated only once.
+except that \verb|varorfunc| is evaluated only once.
 
 Arguments have the following syntax:
 \begin{Produc}
@@ -983,7 +988,7 @@ the parameter list is a single literal string.
 
 Because a function can return any number of results
 \see{return},
-the number of results must be adjusted before used.
+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,
 thus discarding all returned values.
@@ -999,7 +1004,7 @@ is the last (or the only) expression in an assignment,
 in an argument list, or in a return statement.
 Here are some examples.
 \begin{verbatim}
-   f();               -- adjusted to 0
+   f();               -- adjusted to 0 results
    g(f(), x);         -- f() is adjusted to 1 result
    g(x, f());         -- g gets x plus all values returned by f()
    a,b,c = f(), x;    -- f() is adjusted to 1 result (and c gets nil)
@@ -1098,7 +1103,7 @@ Then, we have the following mapping from arguments to parameters:
    g(5, r())        a=5, b=1, arg={2, 3; n=2}
 \end{verbatim}
 
-Results are returned using the \verb|return| statement \see{return}.
+Results are returned using the \rwd{return} statement \see{return}.
 If control reaches the end of a function
 without encountering a \rwd{return} statement,
 then the function returns with no results.
@@ -1149,19 +1154,25 @@ The name used in an upvalue may be the name of any variable visible
 at the point where the function is defined,
 that is
 global variables and local variables from the immediately enclosing function.
+Notice that when the upvalue is a table,
+only the reference to that table
+(which is the value of the upvalue) is frozen;
+the table contents can be changed at will.
 
 Here are some examples:
 \begin{verbatim}
       a,b,c = 1,2,3   -- global variables
       local d
       function f (x)
-        local b       -- x and b are local to f; b shadows the global b
+        local b = {}       -- x and b are local to f; b shadows the global b
         local g = function (a)
           local y     -- a and y are local to g
           p = a       -- OK, access local 'a'
           p = c       -- OK, access global 'c'
           p = b       -- ERROR: cannot access a variable in outer scope
           p = %b      -- OK, access frozen value of 'b' (local to 'f')
+          %b = 3      -- ERROR: cannot change an upvalue
+          %b.x = 3    -- OK, change the table contents
           p = %c      -- OK, access frozen value of global 'c'
           p = %y      -- ERROR: 'y' is not visible where 'g' is defined
           p = %d      -- ERROR: 'd' is not visible where 'g' is defined
@@ -1183,6 +1194,14 @@ and then the corresponding function from the library
 \verb|lua_dobuffer|, or \verb|lua_callfunction|)
 is terminated, returning an error condition.
 
+Memory allocation error is an exception to the previous rule.
+When a \verb|malloc| fails, Lua may not be able to execute the
+\verb|_ERRORMESSAGE| function.
+So, for this kind of error, Lua does not call
+the \verb|_ERRORMESSAGE| function;
+instead, the corresponding function from the library
+returns immeditely with a special error code.
+
 The only argument to \verb|_ERRORMESSAGE| is a string
 describing the error.
 The default definition for
@@ -1193,15 +1212,6 @@ and uses the debug facilities \see{debugI}
 to print some extra information,
 such as a call stack traceback.
 
-To provide more information about errors,
-Lua programs should include the compilation pragma \verb|$debug|,
-\index{debug pragma}\label{pragma}
-or be loaded from the host after calling \verb|lua_setdebug(1)|
-\see{debugI}.
-When an error occurs in a chunk compiled with this option,
-the I/O error-message routine is able to print the number of the
-lines where the calls (and the error) were made.
-
 Lua code can explicitly generate an error by calling the built-in
 function \verb|error| \see{pdf-error}.
 Lua code can ``catch'' an error using the built-in function
@@ -1241,13 +1251,13 @@ The code shown here is only \emph{illustrative};
 the real behavior is hard coded in the interpreter,
 and it is much more efficient than this simulation.
 All functions used in these descriptions
-(\verb|rawgetglobal|, \verb|tonumber|, \verb|call|, etc.)
+(\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)
 are described in \See{predefined}.
 
 \begin{description}
 
 \item[``add'':]\index{add event}
-called when a \verb|+| operation is applied to non numerical operands.
+called when a \verb|+| operation is applied to non-numerical operands.
 
 The function \verb|getbinmethod| defines how Lua chooses a tag method
 for a binary operation.
@@ -1282,16 +1292,19 @@ the tag method for the ``add' event is
       end
 \end{verbatim}
 
+All global variables are kept in a table.
+You can get this table calling the \verb|globals| function.
+
 \item[``sub'':]\index{sub event}
-called when a \verb|-| operation is applied to non numerical operands.
+called when a \verb|-| operation is applied to non-numerical operands.
 Behavior similar to the ``add'' event.
 
 \item[``mul'':]\index{mul event}
-called when a \verb|*| operation is applied to non numerical operands.
+called when a \verb|*| operation is applied to non-numerical operands.
 Behavior similar to the ``add'' event.
 
 \item[``div'':]\index{div event}
-called when a \verb|/| operation is applied to non numerical operands.
+called when a \verb|/| operation is applied to non-numerical operands.
 Behavior similar to the ``add'' event.
 
 \item[``pow'':]\index{pow event}
@@ -1310,7 +1323,7 @@ called when a \verb|^| operation (exponentiation) is applied.
 \end{verbatim}
 
 \item[``unm'':]\index{unm event}
-called when a unary \verb|-| operation is applied to a non numerical operand.
+called when a unary \verb|-| operation is applied to a non-numerical operand.
 \begin{verbatim}
       function unm_event (op)
         local o = tonumber(op)
@@ -1361,7 +1374,7 @@ usual equivalences:
 \end{verbatim}
 
 \item[``concat'':]\index{concatenation event}
-called when a concatenation is applied to non string operands.
+called when a concatenation is applied to non-string operands.
 \begin{verbatim}
       function concat_event (op1, op2)
         if (type(op1) == "string" or type(op1) == "number") and
@@ -1391,7 +1404,8 @@ Note that
 the tag is that of the \emph{current value} of the global variable.
 \begin{verbatim}
       function getglobal (varname)
-        local value = rawgetglobal(varname)
+        -- access the table of globals
+        local value = rawget(globals(), varname)
         local tm = gettagmethod(tag(value), "getglobal")
         if not tm then
           return value
@@ -1408,10 +1422,10 @@ This method cannot be set for numbers, strings, and tables and
 userdata with default tags.
 \begin{verbatim}
       function setglobal (varname, newvalue)
-        local oldvalue = rawgetglobal(varname)
+        local oldvalue = rawget(globals(), varname)
         local tm = gettagmethod(tag(oldvalue), "setglobal")
         if not tm then
-          rawsetglobal(varname, newvalue)
+          rawset(globals(), varname, newvalue)
         else
           tm(varname, oldvalue, newvalue)
         end
@@ -1430,7 +1444,7 @@ This method cannot be set for tables with default tag.
         elseif type(table) ~= "table" then
           error("indexed expression not a table");
         else
-          local v = rawgettable(table, index)
+          local v = rawget(table, index)
           tm = gettagmethod(tag(table), "index")
           if v == nil and tm then
             return tm(table, index)
@@ -1452,13 +1466,13 @@ This method cannot be set for tables with default tag.
         elseif type(table) ~= "table" then
           error("indexed expression not a table")
         else
-          rawsettable(table, index, value)
+          rawset(table, index, value)
         end
       end
 \end{verbatim}
 
 \item[``function'':]\index{function event}
-called when Lua tries to call a non function value.
+called when Lua tries to call a non-function value.
 \begin{verbatim}
       function function_event (func, ...)
         if type(func) == "function" then
@@ -1540,36 +1554,32 @@ Before calling any API function,
 you must create a state.
 This is done by calling\Deffunc{lua_newstate}
 \begin{verbatim}
-lua_State *lua_newstate (const char *s, ...);
+lua_State *lua_newstate (int stacksize, int builtin);
 \end{verbatim}
-The arguments to this function form a list of name-value options,
-terminated with \verb|NULL|.
-Currently, the function accepts the following options:
-\begin{itemize}
-\item \verb|"stack"| --- the stack size.
+The arguments to this function are
+the stack size for the interpreter and a boolean that
+indicates whether the predefined functions should be loaded or not.
 Each function call needs one stack position for each local variable
 and temporary variables, plus one position for book-keeping.
 The stack must also have at least ten extra positions available.
 For very small implementations, without recursive functions,
 a stack size of 100 should be enough.
-The default stack size is 1024.
-
-\item \verb|"builtin"| --- the value is a boolean (0 or 1) that
-indicates whether the predefined functions should be loaded or not.
-The default is to load those functions.
-\end{itemize}
+A value 0 for \verb|stacksize| uses a default size of 1024 positions.
 For instance, the call
 \begin{verbatim}
-lua_State *L = lua_newstate(NULL);
+lua_State *L = lua_newstate(0, 1);
 \end{verbatim}
 creates a new state with a stack of 1024 positions
 and with the predefined functions loaded;
 the call
 \begin{verbatim}
-lua_State *L = lua_newstate("builtin", 0, "stack", 100, NULL);
+lua_State *L = lua_newstate(100, 0)
 \end{verbatim}
 creates a new state with a stack of 100 positions,
 without the predefined functions.
+When you create a state without the builtin function,
+you must provide by yourself any function that your interpreter may need
+(such as \verb|_ALERT| and \verb|_ERRORMESSAGE| for error report, etc.).
 
 To release a state, you call
 \begin{verbatim}
@@ -1578,7 +1588,7 @@ void lua_close (lua_State *L);
 This function destroys all objects in the current Lua environment
 (calling the corresponding garbage collection tag methods)
 and frees all dynamic memory used by the state.
-Usually, you do not need to call this function,
+Frequently, you do not need to call this function,
 because all resources are naturally released when the program ends.
 On the other hand,
 long-running programs ---
@@ -1588,6 +1598,8 @@ to avoid growing too big.
 
 With the exception of \verb|lua_newstate|,
 all functions in the API need a state as their first argument.
+
+>>>>>>>>>>>>
 However, most applications use a single state.
 To avoid the burden of passing this only state explicitly to all
 functions, and also to keep compatibility with old versions of Lua,
@@ -1615,11 +1627,11 @@ again as a macro.)
 The only exception is \verb|lua_newstate|;
 in this case, the corresponding macro is
 \begin{verbatim}
-#define lua_open()      ((void)(lua_state?0:(lua_state=lua_newstate(0))))
+#define lua_open()      ((void)(lua_state?0:(lua_state=lua_newstate(0, 1))))
 \end{verbatim}
 This code checks whether the global state has been initialized;
 if not, it creates a new state with default settings and
-assigns it to \verb|lua_newstate|.
+assigns it to \verb|lua_state|.
 
 By default, the single-state macros are all active.
 If you need to use multiple states,
@@ -1630,11 +1642,7 @@ including \verb|lua.h| in your code:
 #define LUA_REENTRANT
 #include "lua.h"
 \end{verbatim}
-
-In the sequel, we will show all functions in the single-state form
-(therefore, they are actually macros).
-When you define \verb|LUA_REENTRANT|,
-all of them get a state as the first parameter.
+<<<<<<<<<
 
 
 \subsection{Exchanging Values between C and Lua} \label{valuesCLua}
@@ -1644,11 +1652,11 @@ all values passed between Lua and C have type
 which works like an abstract type in C that can hold any Lua value.
 Values of type \verb|lua_Object| have no meaning outside Lua;
 for instance,
-you cannot compare two \verb|lua_Object's| directly.
+you cannot compare two \verb|lua_Object|s directly.
 Instead, you should use the following function:
 \Deffunc{lua_equal}
 \begin{verbatim}
-int lua_equal       (lua_Object o1, lua_Object o2);
+int lua_equal       (lua_State *L, lua_Object o1, lua_Object o2);
 \end{verbatim}
 
 To check the type of a \verb|lua_Object|,
@@ -1658,14 +1666,14 @@ the following functions are available:
 \Deffunc{lua_isfunction}
 \Deffunc{lua_type}
 \begin{verbatim}
-int lua_isnil        (lua_Object object);
-int lua_isnumber     (lua_Object object);
-int lua_isstring     (lua_Object object);
-int lua_istable      (lua_Object object);
-int lua_isfunction   (lua_Object object);
-int lua_iscfunction  (lua_Object object);
-int lua_isuserdata   (lua_Object object);
-const char *lua_type (lua_Object object);
+int lua_isnil        (lua_State *L, lua_Object object);
+int lua_isnumber     (lua_State *L, lua_Object object);
+int lua_isstring     (lua_State *L, lua_Object object);
+int lua_istable      (lua_State *L, lua_Object object);
+int lua_isfunction   (lua_State *L, lua_Object object);
+int lua_iscfunction  (lua_State *L, lua_Object object);
+int lua_isuserdata   (lua_State *L, lua_Object object);
+const char *lua_type (lua_State *L, lua_Object object);
 \end{verbatim}
 The \verb|lua_is*| functions return 1 if the object is compatible
 with the given type, and 0 otherwise.
@@ -1685,7 +1693,7 @@ To get the tag of a \verb|lua_Object|,
 use the following function:
 \Deffunc{lua_tag}
 \begin{verbatim}
-int lua_tag (lua_Object object);
+int lua_tag (lua_State *L, lua_Object object);
 \end{verbatim}
 
 To translate a value from type \verb|lua_Object| to a specific C type,
@@ -1693,11 +1701,11 @@ you can use the following conversion functions:
 \Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen}
 \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata}
 \begin{verbatim}
-double         lua_getnumber    (lua_Object object);
-const char    *lua_getstring    (lua_Object object);
-size_t         lua_strlen       (lua_Object object);
-lua_CFunction  lua_getcfunction (lua_Object object);
-void          *lua_getuserdata  (lua_Object object);
+double         lua_getnumber    (lua_State *L, lua_Object object);
+const char    *lua_getstring    (lua_State *L, lua_Object object);
+size_t         lua_strlen       (lua_State *L, lua_Object object);
+lua_CFunction  lua_getcfunction (lua_State *L, lua_Object object);
+void          *lua_getuserdata  (lua_State *L, lua_Object object);
 \end{verbatim}
 
 \verb|lua_getnumber| converts a \verb|lua_Object| to a floating-point number.
@@ -1713,15 +1721,11 @@ but returns a pointer to a string inside the Lua environment.
 Those strings always have a 0 after their last character (like in C),
 but may contain other zeros in their body.
 If you do not know whether a string may contain zeros,
-you can use \verb|lua_strlen| to get the actual length.
+you should use \verb|lua_strlen| to get the actual length.
 Because Lua has garbage collection,
 there is no guarantee that the pointer returned by \verb|lua_getstring|
 will be valid after the block ends
 \see{GC}.
-So,
-if you need the string later on,
-you should duplicate it with something like
-\verb|memcpy(malloc(lua_strlen(o),lua_getstring(o)))|.
 
 \verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function.
 This \verb|lua_Object| must be a C~function;
@@ -1746,7 +1750,7 @@ The structure lua2C is an \emph{abstract array}
 that can be indexed with the function:
 \Deffunc{lua_lua2C}
 \begin{verbatim}
-lua_Object lua_lua2C (int number);
+lua_Object lua_lua2C (lua_State *L, int number);
 \end{verbatim}
 where \verb|number| starts with 1.
 When called with a number larger than the array size,
@@ -1764,13 +1768,13 @@ is done with the following functions:
 \Deffunc{lua_pushnil}\Deffunc{lua_pushobject}
 \Deffunc{lua_pushuserdata}\label{pushing}
 \begin{verbatim}
-void lua_pushnumber    (double n);
-void lua_pushlstring   (const char *s, size_t len);
-void lua_pushstring    (const char *s);
-void lua_pushusertag   (void *u, int tag);
-void lua_pushnil       (void);
-void lua_pushobject    (lua_Object object);
-void lua_pushcfunction (lua_CFunction f);  /* macro */
+void lua_pushnumber    (lua_State *L, double n);
+void lua_pushlstring   (lua_State *L, const char *s, size_t len);
+void lua_pushstring    (lua_State *L, const char *s);
+void lua_pushusertag   (lua_State *L, void *u, int tag);
+void lua_pushnil       (lua_State *L);
+void lua_pushobject    (lua_State *L, lua_Object object);
+void lua_pushcfunction (lua_State *L, lua_CFunction f);  /* macro */
 \end{verbatim}
 All of them receive a C value,
 convert it to a corresponding \verb|lua_Object|,
@@ -1783,27 +1787,23 @@ otherwise you should use the more general \verb|lua_pushlstring|.
 The function
 \Deffunc{lua_pop}
 \begin{verbatim}
-lua_Object lua_pop (void);
+lua_Object lua_pop (lua_State *L);
 \end{verbatim}
 returns a reference to the object at the top of the C2lua stack,
 and pops it.
 
-As a general rule, all API functions pop from the stack
-all elements they use.
-
 When C code calls Lua repeatedly, as in a loop,
-objects returned by these calls can accumulate,
+objects returned by these calls accumulate,
 and may cause a stack overflow.
 To avoid this,
 nested blocks can be defined with the functions
 \begin{verbatim}
-void lua_beginblock (void);
-void lua_endblock   (void);
+void lua_beginblock (lua_State *L);
+void lua_endblock   (lua_State *L);
 \end{verbatim}
 After the end of the block,
-all \verb|lua_Object|'s created inside it are released.
-The use of explicit nested blocks is good programming practice
-and is strongly encouraged.
+all \verb|lua_Object|s created inside it are released.
+The \verb|lua_endblock| function also empties the C2Lua stack.
 
 \subsection{Garbage Collection}\label{GC}
 Because Lua has automatic memory management and garbage collection,
@@ -1818,13 +1818,13 @@ and never to store \verb|lua_Object|s in C global variables.
 A garbage collection cycle can be forced by:
 \Deffunc{lua_collectgarbage}
 \begin{verbatim}
-long lua_collectgarbage (long limit);
+long lua_collectgarbage (lua_State *L, long limit);
 \end{verbatim}
 This function returns the number of objects collected.
 The argument \verb|limit| makes the next cycle occur only
 after that number of new objects have been created.
 If \verb|limit| is 0,
-then Lua uses an adaptive heuristics to set this limit.
+then Lua uses an adaptive heuristic to set this limit.
 
 
 \subsection{Userdata and Tags}\label{C-tags}
@@ -1846,14 +1846,14 @@ whose semantics are only known to the host program.
 Tags are created with the function
 \Deffunc{lua_newtag}
 \begin{verbatim}
-int lua_newtag (void);
+int lua_newtag (lua_State *L);
 \end{verbatim}
 The function \verb|lua_settag| changes the tag of
 the object on the top of C2lua (and pops it);
 the object must be a userdata or a table:
 \Deffunc{lua_settag}
 \begin{verbatim}
-void lua_settag (int tag);
+void lua_settag (lua_State *L, int tag);
 \end{verbatim}
 The given \verb|tag| must be a value created with \verb|lua_newtag|.
 
@@ -1862,19 +1862,30 @@ A host program can execute Lua chunks written in a file or in a string
 using the following functions:%
 \Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer}
 \begin{verbatim}
-int lua_dofile   (const char *filename);
-int lua_dostring (const char *string);
-int lua_dobuffer (const char *buff, size_t size, const char *name);
+int lua_dofile   (lua_State *L, const char *filename);
+int lua_dostring (lua_State *L, const char *string);
+int lua_dobuffer (lua_State *L, const char *buff,
+                  size_t size, const char *name);
 \end{verbatim}
-All these functions return an error code:
-0, in case of success; non zero, in case of errors.
-More specifically, \verb|lua_dofile| returns 2 if for any reason
-it could not open the file.
-(In this case,
+All these functions return
+0, in case of success, or one of the following error codes:
+\begin{itemize}
+\item \verb|LUA_ERRRUN| ---
+error while running the chunk.
+\item \verb|LUA_ERRSYNTAX| ---
+syntax error during pre-compilation.
+\item \verb|LUA_ERRMEM| ---
+memory allocation error;
+for such errors, Lua does not call the \verb|LUA_ERRORMESSAGE| function.
+\item \verb|LUA_ERRFILE| ---
+error opening the file (only for \verb|lua_dofile|).
+In this case,
 you may want to
 check \verb|errno|,
 call \verb|strerror|,
-or call \verb|perror| to tell the user what went wrong.)
+or call \verb|perror| to tell the user what went wrong.
+\end{itemize}
+
 When called with argument \verb|NULL|,
 \verb|lua_dofile| executes the \verb|stdin| stream.
 Functions \verb|lua_dofile| and \verb|lua_dobuffer|
@@ -1900,39 +1911,44 @@ To read the value of any global Lua variable,
 one uses the function
 \Deffunc{lua_getglobal}
 \begin{verbatim}
-lua_Object lua_getglobal (const char *varname);
+lua_Object lua_getglobal (lua_State *L, const char *varname);
 \end{verbatim}
 As in Lua, this function may trigger a tag method
 for the ``getglobal'' event.
-To read the real value of any global variable,
+To read the real value of a global variable,
 without invoking any tag method,
-use the \emph{raw} version:
-\Deffunc{lua_rawgetglobal}
-\begin{verbatim}
-lua_Object lua_rawgetglobal (const char *varname);
-\end{verbatim}
+use the \emph{lua_rawget} function over the table of globals.
 
 To store a value previously pushed onto C2lua in a global variable,
 there is the function
 \Deffunc{lua_setglobal}
 \begin{verbatim}
-void lua_setglobal (const char *varname);
+void lua_setglobal (lua_State *L, const char *varname);
 \end{verbatim}
 As in Lua, this function may trigger a tag method
 for the ``setglobal'' event.
-To set the real value of any global variable,
+To set the real value of a global variable,
 without invoking any tag method,
-use the \emph{raw} version:
-\Deffunc{lua_rawgetglobal}
+use the \emph{lua_rawset} function over the table of globals.
+
+To get the table of globals,
+you should call
+\Deffunc{lua_pushglobaltable}
 \begin{verbatim}
-void lua_rawsetglobal (const char *varname);
+void lua_pushglobaltable (lua_State *L);
+\end{verbatim}
+To set another table as the table of globals,
+you use
+\Deffunc{lua_setglobaltable}
+\begin{verbatim}
+void lua_setglobaltable (lua_State *L, lua_Object newtable);
 \end{verbatim}
 
 Tables can also be manipulated via the API.
 The function
 \Deffunc{lua_gettable}
 \begin{verbatim}
-lua_Object lua_gettable (void);
+lua_Object lua_gettable (lua_State *L);
 \end{verbatim}
 pops a table and an index from the stack C2lua,
 and returns the contents of the table at that index.
@@ -1941,9 +1957,9 @@ for the ``gettable'' event.
 To get the real value of any table index,
 without invoking any tag method,
 use the \emph{raw} version:
-\Deffunc{lua_rawgetglobal}
+\Deffunc{lua_rawget}
 \begin{verbatim}
-lua_Object lua_rawgettable (void);
+lua_Object lua_rawget (lua_State *L);
 \end{verbatim}
 
 To store a value in an index,
@@ -1952,22 +1968,22 @@ the program must push the table, the index, and the value onto C2lua
 and then call the function
 \Deffunc{lua_settable}
 \begin{verbatim}
-void lua_settable (void);
+void lua_settable (lua_State *L);
 \end{verbatim}
 As in Lua, this operation may trigger a tag method
 for the ``settable'' event.
 To set the real value of any table index,
 without invoking any tag method,
 use the \emph{raw} version:
-\Deffunc{lua_rawsettable}
+\Deffunc{lua_rawset}
 \begin{verbatim}
-void lua_rawsettable (void);
+void lua_rawset (lua_State *L);
 \end{verbatim}
 
 Finally, the function
 \Deffunc{lua_createtable}
 \begin{verbatim}
-lua_Object lua_createtable (void);
+lua_Object lua_createtable (lua_State *L);
 \end{verbatim}
 creates and returns a new, empty table.
 
@@ -1981,10 +1997,9 @@ first, the arguments to the function are pushed onto C2lua
 Then, the function is called using
 \Deffunc{lua_callfunction}
 \begin{verbatim}
-int lua_callfunction (lua_Object function);
+int lua_callfunction (lua_State *L, lua_Object function);
 \end{verbatim}
-This function returns an error code:
-0, in case of success; non zero, in case of errors.
+This function returns the same error codes that \verb|lua_dostring|.
 Finally, the results are returned in structure lua2C
 (recall that a Lua function may return many values),
 and can be retrieved with the macro \verb|lua_getresult|,
@@ -1999,23 +2014,23 @@ equivalent to the Lua code:
       a,b = f("how", t.x, 4)
 \end{verbatim}
 \begin{verbatim}
-  lua_pushstring("how");                               /* 1st argument */
-  lua_pushobject(lua_getglobal("t"));      /* push value of global 't' */
-  lua_pushstring("x");                          /* push the string 'x' */
-  lua_pushobject(lua_gettable());      /* push result of t.x (2nd arg) */
-  lua_pushnumber(4);                                   /* 3rd argument */
-  lua_callfunction(lua_getglobal("f"));           /* call Lua function */
-  lua_pushobject(lua_getresult(1));   /* push first result of the call */
-  lua_setglobal("a");                       /* set global variable 'a' */
-  lua_pushobject(lua_getresult(2));  /* push second result of the call */
-  lua_setglobal("b");                       /* set global variable 'b' */
+  lua_pushstring(L, "how");                                 /* 1st argument */
+  lua_pushobject(L, lua_getglobal(L, "t"))      /* push value of global 't' */
+  lua_pushstring(L, "x");                            /* push the string 'x' */
+  lua_pushobject(L, lua_gettable(L));       /* push result of t.x (2nd arg) */
+  lua_pushnumber(L, 4);                                     /* 3rd argument */
+  lua_callfunction(L, lua_getglobal(L, "f"));                   /* call `f' */
+  lua_pushobject(L, lua_getresult(L, 1));  /* push first result of the call */
+  lua_setglobal(L, "a");                         /* set global variable 'a' */
+  lua_pushobject(L, lua_getresult(L, 2)); /* push second result of the call */
+  lua_setglobal(L, "b");                         /* set global variable 'b' */
 \end{verbatim}
 
 Some special Lua functions have exclusive interfaces.
 The host program can generate a Lua error calling the function
 \Deffunc{lua_error}
 \begin{verbatim}
-void lua_error (const char *message);
+void lua_error (lua_State *L, const char *message);
 \end{verbatim}
 This function never returns.
 If \verb|lua_error| is called from a C~function that has been called from Lua,
@@ -2030,7 +2045,7 @@ then \verb|_ERRORMESSAGE| is not called.
 
 Tag methods can be changed with: \Deffunc{lua_settagmethod}
 \begin{verbatim}
-lua_Object lua_settagmethod (int tag, const char *event);
+lua_Object lua_settagmethod (lua_State *L, int tag, const char *event);
 \end{verbatim}
 The first parameter is the tag,
 and the second is the event name \see{tag-method};
@@ -2040,19 +2055,19 @@ which is the old tag method value.
 To get just the current value of a tag method,
 use the function \Deffunc{lua_gettagmethod}
 \begin{verbatim}
-lua_Object lua_gettagmethod (int tag, const char *event);
+lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event);
 \end{verbatim}
 
 It is also possible to copy all tag methods from one tag
 to another: \Deffunc{lua_copytagmethods}
 \begin{verbatim}
-int lua_copytagmethods (int tagto, int tagfrom);
+int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
 \end{verbatim}
 This function returns \verb|tagto|.
 
 You can traverse a table with the function \Deffunc{lua_next}
 \begin{verbatim}
-int lua_next (lua_Object t, int i);
+int lua_next (lua_State *L, lua_Object t, int i);
 \end{verbatim}
 Its first argument is the table to be traversed,
 and the second is a \emph{cursor};
@@ -2068,51 +2083,27 @@ A typical traversal looks like the following code:
   lua_Object t;
   ...   /* gets the table at `t' */
   i = 0;
-  lua_beginblock();
-  while ((i = lua_next(t, i)) != 0) {
-    lua_Object key = lua_getresult(1);
-    lua_Object value = lua_getresult(2);
+  lua_beginblock(L);
+  while ((i = lua_next(L, t, i)) != 0) {
+    lua_Object key = lua_getresult(L, 1);
+    lua_Object value = lua_getresult(L, 2);
     ...  /* uses `key' and `value' */
-    lua_endblock();
-    lua_beginblock();  /* reopens a block */
+    lua_endblock(L);
+    lua_beginblock(L);  /* reopens a block */
   }
-  lua_endblock();
+  lua_endblock(L);
 \end{verbatim}
 The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the
 results of each iteration from the stack.
 Without them, a traversal of a large table may overflow the stack.
 
-To traverse the global variables, use \Deffunc{lua_nextvar}
-\begin{verbatim}
-const char *lua_nextvar (const char *varname);
-\end{verbatim}
-Here, the cursor is a string;
-in the first call you set it to \verb|NULL|;
-for each call the function returns the name of a global variable,
-to be used in the next call,
-or \verb|NULL| to signal the end of the traverse.
-The function also returns, in the Lua2C array,
-the name (again) and the value of the global variable.
-A typical traversal looks like the following code:
-\begin{verbatim}
-  const char *name = NULL;
-  lua_beginblock();
-  while ((name = lua_nextvar(name)) != NULL) {
-    lua_Object value = lua_getresult(2);
-    ...  /* uses `name' and `value' */
-    lua_endblock();
-    lua_beginblock();  /* reopens a block */
-  }
-  lua_endblock();
-\end{verbatim}
-
 
 \subsection{Defining C Functions} \label{LuacallC}
 To register a C~function to Lua,
 there is the following convenience macro:
 \Deffunc{lua_register}
 \begin{verbatim}
-#define lua_register(n,f)       (lua_pushcfunction(f), lua_setglobal(n))
+#define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
 /* const char *n;   */
 /* lua_CFunction f; */
 \end{verbatim}
@@ -2122,9 +2113,10 @@ This pointer must have type \verb|lua_CFunction|,
 which is defined as
 \Deffunc{lua_CFunction}
 \begin{verbatim}
-typedef void (*lua_CFunction) (void);
+typedef void (*lua_CFunction) (lua_State *L);
 \end{verbatim}
-that is, a pointer to a function with no parameters and no results.
+that is, a pointer to a function with no results and a single argument,
+a Lua environment.
 
 In order to communicate properly with Lua,
 a C~function must follow a protocol,
@@ -2148,7 +2140,7 @@ To associate upvalues to a C~function,
 first these values must be pushed on C2lua.
 Then the function \Deffunc{lua_pushcclosure}
 \begin{verbatim}
-void lua_pushcclosure (lua_CFunction fn, int n);
+void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
 \end{verbatim}
 is used to put the C~function on C2lua,
 with the argument \verb|n| telling how many upvalues must be
@@ -2161,8 +2153,6 @@ before the actual arguments provided in the call.
 
 For some examples of C~functions, see files \verb|lstrlib.c|,
 \verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution.
-In particular,
-\verb|liolib.c| defines C~closures with file handles are upvalues.
 
 \subsection{References to Lua Objects}
 
@@ -2174,9 +2164,9 @@ The routines to manipulate references are the following:
 \Deffunc{lua_ref}\Deffunc{lua_getref}
 \Deffunc{lua_unref}
 \begin{verbatim}
-int        lua_ref    (int lock);
-lua_Object lua_getref (int ref);
-void       lua_unref  (int ref);
+int        lua_ref    (lua_State *L, int lock);
+lua_Object lua_getref (lua_State *L, int ref);
+void       lua_unref  (lua_State *L, int ref);
 \end{verbatim}
 The function \verb|lua_ref| creates a reference
 to the object that is on the top of the stack,
@@ -2288,7 +2278,7 @@ Instead, it returns \nil\ to signal the error
 (besides calling the appropriated error handler).
 
 If \verb|errhandler| is provided,
-the error function \verb|_ERRORMESSAGE| is temporarily set \verb|errhandler|,
+the error function \verb|_ERRORMESSAGE| is temporarily set to \verb|errhandler|,
 while \verb|func| runs.
 In particular, if \verb|errhandler| is \nil,
 no error messages will be issued during the execution of the called function.
@@ -2318,8 +2308,8 @@ When called without arguments,
 If there is any error executing the file,
 then \verb|dofile| returns \nil.
 Otherwise, it returns the values returned by the chunk,
-or a non \nil\ value if the chunk returns no values.
-It issues an error when called with a non string argument.
+or a non-\nil\ value if the chunk returns no values.
+It issues an error when called with a non-string argument.
 \verb|dofile| is equivalent to the API function \verb|lua_dofile|.
 
 \subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring}
@@ -2327,7 +2317,7 @@ Executes a given string as a Lua chunk.
 If there is any error executing the string,
 then \verb|dostring| returns \nil.
 Otherwise, it returns the values returned by the chunk,
-or a non \nil\ value if the chunk returns no values.
+or a non-\nil\ value if the chunk returns no values.
 The optional parameter \verb|chunkname|
 is the ``name of the chunk'',
 used in error messages and debug information.
@@ -2354,20 +2344,16 @@ as the final value of \verb|foreach|.
 This function could be defined in Lua:
 \begin{verbatim}
       function foreach (t, f)
-        local i, v = nil
-        while 1 do
-          i, v = next(t, i)
-          if not i then break end
+        for i, v in t do
           local res = f(i, v)
           if res then return res end
         end
       end
 \end{verbatim}
 
-You may change the \emph{values} of existing fields in the table during the traversal,
-but
-if you create new indices,
-then
+You may change the \emph{values} of existing
+fields in the table during the traversal,
+but if you create new indices,
 the semantics of \verb|foreach| is undefined.
 
 
@@ -2393,43 +2379,19 @@ This function could be defined in Lua:
       end
 \end{verbatim}
 
-You may change the \emph{values} of existing fields in the table during the traversal,
-but
-if you create new indices (even non-numeric),
-then
+You may change the \emph{values} of existing fields in the
+table during the traversal,
+but if you create new indices (even non-numeric),
 the semantics of \verb|foreachi| is undefined.
 
 \subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar}
-Executes \verb|function| over all global variables.
-For each variable,
-the function is called with its name and its value as arguments.
-If the function returns any non-nil value,
-then the loop is broken, and this value is returned
-as the final value of \verb|foreachvar|.
-
-This function could be defined in Lua:
-\begin{verbatim}
-      function foreachvar (f)
-        local n, v = nil
-        while 1 do
-          n, v = nextvar(n)
-          if not n then break end
-          local res = f(n, v)
-          if res then return res end
-        end
-      end
-\end{verbatim}
-
-You may change the values of existing global variables during the traversal,
-but
-if you create new global variables,
-then
-the semantics of \verb|foreachvar| is undefined.
+This function is obsolete.
+Use \verb|foreach(globals(), function)| instead.
 
 
 \subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal}
 Gets the value of a global variable,
-or calls a tag method for ``getgloball''.
+or calls a tag method for ``getglobal''.
 Its full semantics is explained in \See{tag-method}.
 The string \verb|name| does not need to be a
 syntactically valid variable name.
@@ -2444,10 +2406,8 @@ This function could be defined in Lua:
 \begin{verbatim}
       function getn (t)
         if type(t.n) == 'number' then return t.n end
-        local max, i = 0, nil
-        while 1 do
-          i = next(t, i)
-          if not i then break end
+        local max = 0
+        for i, _ in t do
           if type(i) == 'number' and i>max then max=i end
         end
         return max
@@ -2459,6 +2419,11 @@ This function could be defined in Lua:
 Returns the current tag method
 for a given pair \M{(tag, event)}.
 
+\subsubsection*{\ff \T{globals ([newtable])}}\Deffunc{globals}
+Returns the current table of globals.
+If the argument \verb|newtable| is given,
+set this table as the new table of globals.
+
 \subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag}
 Returns a new tag.
 \verb|newtag| is equivalent to the API function \verb|lua_newtag|.
@@ -2480,33 +2445,20 @@ If the second argument is absent, then it is interpreted as \nil.
 Lua has no declaration of fields;
 semantically, there is no difference between a
 field not present in a table or a field with value \nil.
-Therefore, \verb|next| only considers fields with non \nil\ values.
+Therefore, \verb|next| only considers fields with non-\nil\ values.
 The order in which the indices are enumerated is not specified,
 \emph{even for numeric indices}
 (to traverse a table in numeric order,
 use a counter or the function \verb|foreachi|).
 
-You may change the \emph{values} of existing fields in the table during the traversal,
-but
-if you create new indices,
-then
+You may change the \emph{values} of existing fields in the
+table during the traversal,
+but if you create new indices,
 the semantics of \verb|next| is undefined.
 
 \subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar}
-This function is similar to the function \verb|next|,
-but iterates instead over the global variables.
-Its single argument is the name of a global variable,
-or \nil\ to get a first name.
-If this argument is absent, then it is interpreted as \nil.
-Like \verb|next|, \verb|nextvar| returns the name of another variable
-and its value,
-or \nil\ if there are no more variables.
-
-You may change the \emph{values} of existing global variables during the traversal,
-but
-if you create new global variables,
-then
-the semantics of \verb|nextvar| is undefined.
+This function is obsolete.
+Use \verb|next(globals(), name)| instead.
 
 \subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print}
 Receives any number of arguments,
@@ -2517,27 +2469,26 @@ for instance for debugging.
 See \See{libio} for functions for formatted output.
 
 \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
-Gets the value of a global variable,
-without invoking any tag method.
-The string \verb|name| does not need to be a
-syntactically valid variable name.
+This function is obsolete.
+Use \verb|rawget(globals(), name)| instead.
 
 \subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable}
+This function was renamed to \verb|rawget|.
+
+\subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget}
 Gets the real value of \verb|table[index]|,
 without invoking any tag method.
 \verb|table| must be a table,
 and \verb|index| is any value different from \nil.
 
 \subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
-Sets the named global variable to the given value,
-without invoking any tag method.
-The string \verb|name| does not need to be a
-syntactically valid variable name.
-Therefore,
-this function can be used to set global variables with strange names like
-\verb|"m v 1"| or \verb|"34"|.
+This function is obsolete.
+Use \verb|rawset(globals(), name, value)| instead.
 
 \subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable}
+This function was renamed to \verb|rawset|.
+
+\subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset}
 Sets the real value of \verb|table[index]| to \verb|value|,
 without invoking any tag method.
 \verb|table| must be a table,
@@ -2546,7 +2497,7 @@ and \verb|value| is any Lua value.
 
 \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal}
 Sets the named global variable to the given value,
-or calls a tag method for ``setgloball''.
+or calls a tag method for ``setglobal''.
 Its full semantics is explained in \See{tag-method}.
 The string \verb|name| does not need to be a
 syntactically valid variable name.
@@ -2577,6 +2528,10 @@ and returns true when the first is less than the second
 If \verb|comp| is not given,
 the standard Lua operator \verb|<| is used instead.
 
+The sort algorithm is 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)}}\Deffunc{tag}\label{pdf-tag}
 Allows Lua programs to test the tag of a value \see{TypesSec}.
 It receives one argument, and returns its tag (a number).
@@ -2601,7 +2556,7 @@ In other bases, only unsigned integers are accepted.
 \subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring}
 Receives an argument of any type and
 converts it to a string in a reasonable format.
-For complete control on how numbers are converted,
+For complete control of how numbers are converted,
 use function \verb|format|.
 
 
@@ -2708,7 +2663,7 @@ to its correspondent argument.
 \Deffunc{strfind}
 Looks for the first \emph{match} of
 \verb|pattern| in \verb|str|.
-If it finds one, then it returns the indices on \verb|str|
+If it finds one, then it returns the indices of \verb|str|
 where this occurrence starts and ends;
 otherwise, it returns \nil.
 If the pattern specifies captures (see \verb|gsub| below),
@@ -2853,9 +2808,9 @@ Here are some examples:
   x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
   --> x="4+5 = 9"
 
-  local t = {name="lua", version="3.2"}
+  local t = {name="lua", version="4.0"}
   x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
-  --> x="lua - 3.2"
+  --> x="lua - 4.0"
 
   t = {n=0}
   gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
@@ -2883,12 +2838,12 @@ The following combinations are allowed in describing a character class:
 \item[\T{\%w}] --- represents all alphanumeric characters.
 \item[\T{\%x}] --- represents all hexadecimal digits.
 \item[\T{\%z}] --- represents the character with representation 0.
-\item[\T{\%\M{x}}] (where \M{x} is any non alphanumeric character)  ---
+\item[\T{\%\M{x}}] (where \M{x} is any non-alphanumeric character)  ---
 represents the character \M{x}.
-This is the standard way to escape the magic characters \verb|()%.[]*-?|.
-It is strongly recommended that any control character (even the non magic)
+This is the standard way to escape the magic characters \verb|()%.[]*+-?|.
+We recommend that any ``punct'' character (even the non magic)
 should be preceded by a \verb|%|
-when used to represent itself in a pattern,
+when used to represent itself in a pattern.
 
 \item[\T{[char-set]}] ---
 represents the class which is the union of all
@@ -3131,7 +3086,8 @@ usually limited and depends on the system.
 Opens a file named \verb|filename| and sets it as the
 value of \verb|_OUTPUT|.
 Unlike the \verb|writeto| operation,
-this function does not erase any previous contents of the file.
+this function does not erase any previous contents of the file;
+instead, anything written to the file is appended to its end.
 If this function fails, it returns \nil,
 plus a string describing the error.
 
@@ -3209,7 +3165,7 @@ This is the default format.
 \item[``*a''] reads the whole file, starting at the current position.
 On end of file, it returns the empty string.
 \item[``*w''] reads the next word
-(maximal sequence of non white-space characters),
+(maximal sequence of non--white-space characters),
 skipping spaces if necessary, or \nil\ on end of file.
 \item[\emph{number}] reads a string with up to that number of characters,
 or \nil\ on end of file.
@@ -3362,8 +3318,6 @@ or \verb|"main"| if this is the main part of a chunk.
 
 \item[currentline]
 the current line where the given function is executing.
-It only works if the function has been compiled with debug
-information.
 When no line information is available,
 \verb|currentline| is set to \Math{-1}.
 
@@ -3400,17 +3354,6 @@ The function being executed, as a \verb|lua_Object|.
 
 \end{description}
 
-The generation of debug information is controlled by an internal flag,
-which can be switched with
-\begin{verbatim}
-int lua_setdebug (lua_State *L, int debug);
-\end{verbatim}
-This function sets the flag and returns its previous value.
-This flag can also be set from Lua~\see{pragma}.
-Setting the flag using \verb|lua_setdebug| affects all chunks that are
-compiled afterwards.
-Individual functions may still control the generation of debug information
-by using \verb|$debug| or \verb|$nodebug|.
 
 \subsection{Manipulating Local Variables}
 
@@ -3430,10 +3373,6 @@ until the last active local variable).
 \Deffunc{lua_getlocal}\Deffunc{lua_setlocal}
 The following functions allow the manipulation of the
 local variables of a given activation record.
-They only work if the function has been compiled with debug
-information \see{pragma}.
-For these functions, a local variable becomes
-visible in the line after its definition.
 \begin{verbatim}
 int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
 int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
@@ -3450,8 +3389,7 @@ For \verb|lua_setlocal|,
 you fill the \verb|index| and the \verb|value| fields of \verb|v|,
 and the function assigns that value to the variable.
 Both functions return 0 on failure, that happens
-if the index is greater than the number of active local variables,
-or if the activation record has no debug information.
+if the index is greater than the number of active local variables.
 
 As an example, the following function lists the names of all
 local variables for a function in a given level of the stack:
@@ -3465,7 +3403,7 @@ int listvars (lua_State *L, int level) {
     lua_Localvar v;
     v.index = i;
     if (lua_getlocal(L, &ar, &v) == 0)
-      return 1;  /* no more locals, or no debug information */
+      return 1;  /* no more locals */
     printf("%s\n", v.name);
   }
 }
@@ -3505,8 +3443,6 @@ the line of code it is executing.
 The \verb|event| field of \verb|ar| has the string \verb|"line"|,
 and the \verb|currentline| field has the line number.
 Again, you can use this \verb|ar| in other calls to the debug API.
-This hook is called only if the active function
-has been compiled with debug information~\see{pragma}.
 
 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,
@@ -3601,8 +3537,6 @@ this hook will be called every time the interpreter changes
 the line of code it is executing.
 The only argument to the hook is the line number the interpreter
 is about to execute.
-This hook is called only if the active function
-has been compiled with debug information~\see{pragma}.
 
 When called without arguments,
 this function turns off line hooks.
@@ -3620,7 +3554,6 @@ This program can be called with any sequence of the following arguments:
 \begin{description}
 \item[\T{-}] executes \verb|stdin| as a file;
 \item[\T{-c}] calls \verb|lua_close| after running all arguments;
-\item[\T{-d}] turns on debug information;
 \item[\T{-e} \rm\emph{stat}] executes string \verb|stat|;
 \item[\T{-f filename}] executes file \verb|filename| with the
 remaining arguments in table \verb|arg|;
@@ -3658,8 +3591,16 @@ then creates a table \T{arg},
   arg = {"t1", "t3";  n = 2, [0] = "b.lua"}
 \end{verbatim}
 and then runs the file \T{b.lua}.
-The stand-alone interpreter also provides a \verb|getarg| function that
+The stand-alone interpreter also provides a \verb|getargs| function that
 can be used to access \emph{all} command line arguments.
+For instance, if you call Lua with the line 
+\begin{verbatim}
+> lua -d a b 
+\end{verbatim}
+and the file \verb|a| (or \verb|b|) calls \verb|getargs|,
+the call will return the table
+\verb|{[0] = "lua", [1] = "-d", [2] = "a", [3] = "b", n = 3}|.
+\Deffunc{getargs}
 
 In interactive mode,
 a multi-line statement can be written finishing intermediate
@@ -3680,11 +3621,11 @@ or \verb|#!/usr/local/bin/lua -f| to get other arguments.
 \section*{Acknowledgments}
 
 The authors would like to thank CENPES/PETROBRAS which,
-jointly with \tecgraf, used extensively early versions of
-this system and gave valuable comments.
+jointly with \tecgraf, used early versions of
+this system extensively and gave valuable comments.
 The authors would also like to thank Carlos Henrique Levy,
 who found the name of the game.
-Lua means \emph{moon} in Portuguese.
+Lua means ``moon'' in Portuguese.
 
 
 \appendix
@@ -3746,11 +3687,9 @@ and is no longer a synonym for \verb|lua_tag|.
 
 \begin{Produc}
 
-\produc{chunk}{\rep{stat} \opt{ret}}
+\produc{chunk}{\rep{stat} \opt{\ter{;}}}
 
-\produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}}
-
-\produc{label}{\ter{$\vert$} name \ter{$\vert$}}
+\produc{block}{chunk}
 
 \produc{stat}{%
 	varlist1 \ter{=} explist1
@@ -3762,7 +3701,7 @@ and is no longer a synonym for \verb|lua_tag|.
 	\rep{\rwd{elseif} exp1 \rwd{then} block}
 	\opt{\rwd{else} block} \rwd{end}
 \OrNL	\rwd{return} \opt{explist1}
-\OrNL	\rwd{break} \opt{name}
+\OrNL	\rwd{break}
 \OrNL	\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
 	\rwd{do} block \rwd{end}
 \OrNL	\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
@@ -3771,10 +3710,12 @@ and is no longer a synonym for \verb|lua_tag|.
 
 \produc{var}{%
 	name
-\OrNL	simpleexp \ter{[} exp1 \ter{]}
-\OrNL	simpleexp \ter{.} name
+\OrNL	varorfunc \ter{[} exp1 \ter{]}
+\OrNL	varorfunc \ter{.} name
 }
 
+\produc{varorfunc}{var \Or functioncall}
+
 \produc{varlist1}{var \rep{\ter{,} var}}
 
 \produc{declist}{name \rep{\ter{,} name}}
@@ -3786,20 +3727,18 @@ and is no longer a synonym for \verb|lua_tag|.
 \Or	number
 \Or	literal
 \Or	function
-\Or	simpleexp
+\Or	upvalue
+\Or	functioncall
+\Or	tableconstructor
 \Or	\ter{(} exp \ter{)}
+\Or	exp binop exp
+\Or	unop exp
 }
 
 \produc{exp1}{exp}
 
 \produc{explist1}{\rep{exp1 \ter{,}} exp}
 
-\produc{simpleexp}{%
-	var
-\Or	upvalue
-\Or	functioncall
-\Or	tableconstructor
-}
 
 \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
 \produc{fieldlist}{%
@@ -3818,8 +3757,8 @@ and is no longer a synonym for \verb|lua_tag|.
 }
 
 \produc{functioncall}{%
-	simpleexp args
-\Or	simpleexp \ter{:} name args
+	varorfunc args
+\Or	varorfunc \ter{:} name args
 }
 
 \produc{args}{%
-- 
cgit v1.2.3-55-g6feb

