summaryrefslogtreecommitdiff
path: root/manual.tex
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>1998-01-02 16:34:00 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>1998-01-02 16:34:00 -0200
commitc332c4e9271a723a9e60bf5d49f0b3e18447bd91 (patch)
tree04e5efe4a766cd1311292fa89a798bbf66ea28a4 /manual.tex
parent964c503a63af6df00cb3dfca0283be61655b535e (diff)
downloadlua-c332c4e9271a723a9e60bf5d49f0b3e18447bd91.tar.gz
lua-c332c4e9271a723a9e60bf5d49f0b3e18447bd91.tar.bz2
lua-c332c4e9271a723a9e60bf5d49f0b3e18447bd91.zip
reference manual of the Lua language
Diffstat (limited to 'manual.tex')
-rw-r--r--manual.tex591
1 files changed, 360 insertions, 231 deletions
diff --git a/manual.tex b/manual.tex
index ea33c449..94cb3d58 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 2.12 1997/07/30 22:15:18 roberto Exp roberto $ 1% $Id: manual.tex,v 2.13 1997/09/16 19:01:10 roberto Exp $
2 2
3\documentstyle[fullpage,11pt,bnf]{article} 3\documentstyle[fullpage,11pt,bnf]{article}
4 4
@@ -38,7 +38,7 @@ Waldemar Celes
38\tecgraf\ --- Computer Science Department --- PUC-Rio 38\tecgraf\ --- Computer Science Department --- PUC-Rio
39} 39}
40 40
41\date{\small \verb$Date: 1997/07/30 22:15:18 $} 41\date{\small \verb$Date: 1997/09/16 19:01:10 $}
42 42
43\maketitle 43\maketitle
44 44
@@ -150,14 +150,14 @@ at the following URL's:
150\section{Environment and Chunks} 150\section{Environment and Chunks}
151 151
152All statements in Lua are executed in a \Def{global environment}. 152All statements in Lua are executed in a \Def{global environment}.
153This environment, which keeps all global variables and functions, 153This environment, which keeps all global variables,
154is initialized at the beginning of the embedding program and 154is initialized at the beginning of the embedding program and
155persists until its end. 155persists until its end.
156 156
157The global environment can be manipulated by Lua code or 157The global environment can be manipulated by Lua code or
158by the embedding program, 158by the embedding program,
159which can read and write global variables 159which can read and write global variables
160using functions in the library that implements Lua. 160using functions from the API library that implements Lua.
161 161
162\Index{Global variables} do not need declaration. 162\Index{Global variables} do not need declaration.
163Any variable is assumed to be global unless explicitly declared local 163Any variable is assumed to be global unless explicitly declared local
@@ -166,27 +166,22 @@ Before the first assignment, the value of a global variable is \nil;
166this default can be changed \see{tag-method}. 166this default can be changed \see{tag-method}.
167 167
168The unit of execution of Lua is called a \Def{chunk}. 168The unit of execution of Lua is called a \Def{chunk}.
169The syntax for chunks is: 169A chunk is simply a sequence of statements:
170\begin{Produc} 170\begin{Produc}
171\produc{chunk}{\rep{stat \Or function} \opt{ret}} 171\produc{chunk}{\rep{stat} \opt{ret}}
172\end{Produc}% 172\end{Produc}%
173(As usual, \rep{\emph{a}} means 0 or more \emph{a}'s, 173(As usual, \rep{\emph{a}} means 0 or more \emph{a}'s,
174\opt{\emph{a}} means an optional \emph{a} and \oneormore{\emph{a}} means 174\opt{\emph{a}} means an optional \emph{a} and \oneormore{\emph{a}} means
175one or more \emph{a}'s.) 175one or more \emph{a}'s.)
176 176
177A chunk may contain statements and function definitions, 177A chunk may be in a file or in a string inside the host program.
178and may be in a file or in a string inside the host program.
179A chunk may optionally end with a \verb|return| statement \see{return}. 178A chunk may optionally end with a \verb|return| statement \see{return}.
180When a chunk is executed, first all its functions and statements are compiled, 179When a chunk is executed, first all its code is pre-compiled,
181then the statements are executed in sequential order. 180then the statements are executed in sequential order.
182All modifications a chunk effects on the global environment persist 181All modifications a chunk effects on the global environment persist
183after its end. 182after its end.
184Those include modifications to global variables
185and definitions of new functions
186(actually, a function definition is an
187assignment to a global variable \see{TypesSec}).
188 183
189Chunks may be pre-compiled into binary form; 184Chunks may also be pre-compiled into binary form;
190see program \IndexVerb{luac} for details. 185see program \IndexVerb{luac} for details.
191Text files with chunks and their binary pre-compiled forms 186Text files with chunks and their binary pre-compiled forms
192are interchangeable. 187are interchangeable.
@@ -215,8 +210,6 @@ of a given value \see{pdf-type}.
215Functions are considered first-class values in Lua. 210Functions are considered first-class values in Lua.
216This means that functions can be stored in variables, 211This means that functions can be stored in variables,
217passed as arguments to other functions and returned as results. 212passed as arguments to other functions and returned as results.
218When a function is defined in Lua, its body is compiled and stored
219in a given variable.
220Lua can call (and manipulate) functions written in Lua and 213Lua can call (and manipulate) functions written in Lua and
221functions written in C. 214functions written in C.
222They can be distinguished by their tags: 215They can be distinguished by their tags:
@@ -292,6 +285,8 @@ The following words are reserved, and cannot be used as identifiers:
292Lua is a case-sensitive language: 285Lua is a case-sensitive language:
293\T{and} is a reserved word, but \T{And} and \T{\'and} 286\T{and} is a reserved word, but \T{And} and \T{\'and}
294(if the locale permits) are two other different identifiers. 287(if the locale permits) are two other different identifiers.
288As a convention, identifiers starting with underscore followed by
289uppercase letters should not be used in regular programs.
295 290
296The following strings denote other \Index{tokens}: 291The following strings denote other \Index{tokens}:
297\begin{verbatim} 292\begin{verbatim}
@@ -307,7 +302,7 @@ Literals in this bracketed form may run for several lines,
307may contain nested \verb|[[ ... ]]| pairs, 302may contain nested \verb|[[ ... ]]| pairs,
308and do not interpret escape sequences. 303and do not interpret escape sequences.
309This form is specially convenient for 304This form is specially convenient for
310handling strings that contain program pieces or 305writing strings that contain program pieces or
311other quoted strings. 306other quoted strings.
312 307
313\Index{Comments} start anywhere outside a string with a 308\Index{Comments} start anywhere outside a string with a
@@ -405,6 +400,12 @@ For syntactic reasons, a \IndexVerb{return} statement can only be written
405as the last statement of a block. 400as the last statement of a block.
406This restriction also avoids some ``statement not reached'' conditions. 401This restriction also avoids some ``statement not reached'' conditions.
407 402
403A block may be explicitly delimited:
404\begin{Produc}
405\produc{stat}{\rwd{do} block \rwd{end}}
406\end{Produc}%
407This is useful to control the scope of local variables.
408
408\subsubsection{\Index{Assignment}} \label{assignment} 409\subsubsection{\Index{Assignment}} \label{assignment}
409The language allows \Index{multiple assignment}. 410The language allows \Index{multiple assignment}.
410Therefore, the syntax for assignment 411Therefore, the syntax for assignment
@@ -433,7 +434,7 @@ or a formal parameter:
433\end{Produc}% 434\end{Produc}%
434Square brackets are used to index a table: 435Square brackets are used to index a table:
435\begin{Produc} 436\begin{Produc}
436\produc{var}{var \ter{[} exp1 \ter{]}} 437\produc{var}{simpleexp \ter{[} exp1 \ter{]}}
437\end{Produc}% 438\end{Produc}%
438The \verb|var| should result in a table value, 439The \verb|var| should result in a table value,
439where the field indexed by the expression value gets the assigned value. 440where the field indexed by the expression value gets the assigned value.
@@ -452,7 +453,7 @@ Function \T{settable\_event} is used only for explanatory purposes.)
452The syntax \verb|var.NAME| is just syntactic sugar for 453The syntax \verb|var.NAME| is just syntactic sugar for
453\verb|var["NAME"]|: 454\verb|var["NAME"]|:
454\begin{Produc} 455\begin{Produc}
455\produc{var}{var \ter{.} name} 456\produc{var}{simpleexp \ter{.} name}
456\end{Produc}% 457\end{Produc}%
457 458
458\subsubsection{Control Structures} 459\subsubsection{Control Structures}
@@ -504,18 +505,28 @@ Otherwise, all variables are initialized with \nil.
504 505
505\subsection{\Index{Expressions}} 506\subsection{\Index{Expressions}}
506 507
507\subsubsection{\Index{Simple Expressions}} 508\subsubsection{\Index{Basic Expressions}}
508Simple expressions are: 509Basic expressions are:
509\begin{Produc} 510\begin{Produc}
510\produc{exp}{\ter{(} exp \ter{)}} 511\produc{exp}{\ter{(} exp \ter{)}}
511\produc{exp}{\rwd{nil}} 512\produc{exp}{\rwd{nil}}
512\produc{exp}{\ter{number}} 513\produc{exp}{\ter{number}}
513\produc{exp}{\ter{literal}} 514\produc{exp}{\ter{literal}}
514\produc{exp}{var} 515\produc{exp}{function}
516\produc{exp}{simpleexp}
515\end{Produc}% 517\end{Produc}%
518\begin{Produc}
519\produc{simpleexp}{var}
520\produc{simpleexp}{upvalue}
521\produc{simpleexp}{functioncall}
522\end{Produc}%
523
516Numbers (numerical constants) and 524Numbers (numerical constants) and
517string literals are explained in Section~\ref{lexical}. 525string literals are explained in Section~\ref{lexical};
518Variables are explained in Section~\ref{assignment}. 526variables are explained in Section~\ref{assignment};
527upvalues are explained in Section~\ref{upvalue};
528function definitions (\M{function}) are explained in Section~\ref{func-def};
529function call are explained in Section~\ref{functioncall}.
519 530
520An access to a global variable \verb|x| is equivalent to a 531An access to a global variable \verb|x| is equivalent to a
521call \verb|getglobal('x')|; 532call \verb|getglobal('x')|;
@@ -619,7 +630,8 @@ or to create a table and initialize some fields.
619The general syntax for constructors is: 630The general syntax for constructors is:
620\begin{Produc} 631\begin{Produc}
621\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} 632\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
622\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist} 633\produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist
634\Or ffieldlist \ter{;} lfieldlist}
623\produc{lfieldlist}{\opt{lfieldlist1}} 635\produc{lfieldlist}{\opt{lfieldlist1}}
624\produc{ffieldlist}{\opt{ffieldlist1}} 636\produc{ffieldlist}{\opt{ffieldlist1}}
625\end{Produc} 637\end{Produc}
@@ -664,39 +676,53 @@ is essentially equivalent to:
664An expression like \verb|{x = 1, y = 4}| is 676An expression like \verb|{x = 1, y = 4}| is
665in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. 677in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
666 678
679Both forms may have an optional ending comma,
680and can be used in the same constructor separated by
681a semi-collon.
682For example, all forms below are correct:
683\begin{verbatim}
684 x = {;}; x = {'a', 'b',}; x = {type='list'; 'a', 'b'}
685 x = {f(0), f(1), f(2),; n=3}
686\end{verbatim}
687
667\subsubsection{Function Calls} \label{functioncall} 688\subsubsection{Function Calls} \label{functioncall}
668A \Index{function call} has the following syntax: 689A \Index{function call} has the following syntax:
669\begin{Produc} 690\begin{Produc}
670\produc{functioncall}{var realParams} 691\produc{functioncall}{simpleexp realParams}
671\end{Produc}% 692\end{Produc}%
672Here, \M{var} can be any variable (global, local, indexed, etc). 693First, \M{simpleexp} is evaluated.
673If its value has type \emph{function}, 694If its value has type \emph{function},
674then this function is called. 695then this function is called.
675Otherwise, the ``function'' tag method is called, 696Otherwise, the ``function'' tag method is called,
676having as first parameter the value of \M{var}, 697having as first parameter the value of \M{simpleexp},
677and then the original call parameters. 698and then the original call parameters.
678 699
679The form: 700The form:
680\begin{Produc} 701\begin{Produc}
681\produc{functioncall}{var \ter{:} name realParams} 702\produc{functioncall}{simpleexp \ter{:} name realParams}
682\end{Produc}% 703\end{Produc}%
683can be used to call ``methods''. 704can be used to call ``methods''.
684A call \verb|var:name(...)| 705A call \verb|simpleexp:name(...)|
685is syntactic sugar for 706is syntactic sugar for
686\begin{verbatim} 707\begin{verbatim}
687 var.name(var, ...) 708 simpleexp.name(simpleexp, ...)
688\end{verbatim} 709\end{verbatim}
689except that \verb|var| is evaluated only once. 710except that \verb|simpleexp| is evaluated only once.
690 711
691\begin{Produc} 712\begin{Produc}
692\produc{realParams}{\ter{(} \opt{explist1} \ter{)}} 713\produc{realParams}{\ter{(} \opt{explist1} \ter{)}}
693\produc{realParams}{tableconstructor} 714\produc{realParams}{tableconstructor}
715\produc{realParams}{\ter{literal}}
694\produc{explist1}{exp1 \rep{\ter{,} exp1}} 716\produc{explist1}{exp1 \rep{\ter{,} exp1}}
695\end{Produc}% 717\end{Produc}%
696All argument expressions are evaluated before the call. 718All argument expressions are evaluated before the call.
697A call of the form \verb|f{...}| is syntactic sugar for 719A call of the form \verb|f{...}| is syntactic sugar for
698\verb|f({...})|, that is, 720\verb|f({...})|, that is,
699the parameter list is a single new table. 721the parameter list is a single new table.
722A call of the form \verb|f'...'|
723(or \verb|f"..."| or \verb|f[[...]]|) is syntactic sugar for
724\verb|f('...')|, that is,
725the parameter list is a single literal string.
700 726
701Because a function can return any number of results 727Because a function can return any number of results
702\see{return}, 728\see{return},
@@ -712,23 +738,40 @@ If the function is called in a place that can hold many values
712(syntactically denoted by the non-terminal \M{exp}), 738(syntactically denoted by the non-terminal \M{exp}),
713then no adjustment is made. 739then no adjustment is made.
714 740
741\subsubsection{\Index{Function Definitions}} \label{func-def}
715 742
716\subsection{\Index{Function Definitions}} \label{func-def}
717
718Functions in Lua can be defined anywhere in the global level of a chunk.
719The syntax for function definition is: 743The syntax for function definition is:
720\begin{Produc} 744\begin{Produc}
721\produc{function}{\rwd{function} var \ter{(} \opt{parlist1} \ter{)} 745\produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)}
746 block \rwd{end}}
747\produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)}
722 block \rwd{end}} 748 block \rwd{end}}
749\produc{funcname}{name \Or name \ter{.} name}
723\end{Produc} 750\end{Produc}
751The statement:
752\begin{verbatim}
753 function f (...)
754 ...
755 end
756\end{verbatim}
757is just syntactic sugar for:
758\begin{verbatim}
759 f = function (...)
760 ...
761 end
762\end{verbatim}
724 763
764A function definition is an executable expresion,
765whose value has type \emph{function}.
725When Lua pre-compiles a chunk, 766When Lua pre-compiles a chunk,
726all its function bodies are pre-compiled, too. 767all its function bodies are pre-compiled, too.
727Then, when Lua ``executes'' the function definition, 768Then, whenever Lua executes the function definition,
728its body is stored, with type \emph{function}, 769its upvalues are fixed \see{upvalue},
729into the variable \verb|var|. 770and the function is \emph{instantiated} (or ``closed'').
730It is in this sense that 771This function instance (or ``closure'')
731a function definition is an assignment to a global variable. 772is the final value of the expression.
773Different instances of a same function
774may have different upvalues.
732 775
733Parameters act as local variables, 776Parameters act as local variables,
734initialized with the argument values. 777initialized with the argument values.
@@ -774,7 +817,7 @@ then the function returns with no results.
774There is a special syntax for defining \Index{methods}, 817There is a special syntax for defining \Index{methods},
775that is, functions that have an extra parameter \Def{self}. 818that is, functions that have an extra parameter \Def{self}.
776\begin{Produc} 819\begin{Produc}
777\produc{function}{\rwd{function} var \ter{:} name \ter{(} \opt{parlist1} 820\produc{function}{\rwd{function} name \ter{:} name \ter{(} \opt{parlist1}
778 \ter{)} block \rwd{end}} 821 \ter{)} block \rwd{end}}
779\end{Produc}% 822\end{Produc}%
780Thus, a declaration like 823Thus, a declaration like
@@ -785,16 +828,54 @@ end
785\end{verbatim} 828\end{verbatim}
786is equivalent to 829is equivalent to
787\begin{verbatim} 830\begin{verbatim}
788function v.f (self, ...) 831v.f = function (self, ...)
789 ... 832 ...
790end 833end
791\end{verbatim} 834\end{verbatim}
792that is, the function gets an extra formal parameter called \verb|self|. 835that is, the function gets an extra formal parameter called \verb|self|.
793Notice that 836Notice that the variable \verb|v| must have been
794the variable \verb|v| must have been
795previously initialized with a table value. 837previously initialized with a table value.
796 838
797 839
840\subsection{\Index{Visibility} and \Index{Upvalues}} \label{upvalue}
841
842A function body may refer to its own local variables
843(which includes its parameters) and to global variables,
844as long as they are not shadowed by local
845variables from enclosing functions.
846A function \emph{cannot} access a local
847variable from an enclosing function,
848since such variables may no longer exist when the function is called.
849However, a function may access the \emph{value} of a local variable
850from an enclosing function, using \emph{upvalues}.
851
852\begin{Produc}
853\produc{upvalue}{\ter{\%} name}
854\end{Produc}
855An upvalue is somewhat similar to a variable expression,
856but whose value is frozen when the function wherein it
857appears is instantiated.
858The name used in an upvalue may be the name of any variable visible
859at the point where the function is defined.
860
861See some examples below:
862\begin{verbatim}
863a,b,c = 1 -- global variables
864function f ()
865 local x,b; -- x and b are locals to f
866 function g ()
867 local a,y -- a and y are locals go g
868 p = a -- OK, access local 'a'
869 p = c -- OK, access global 'c'
870 p = b -- ERROR: cannot access a variable in outer scope
871 p = %b -- OK, access frozen value of 'b'
872 p = %c -- OK, access frozen value of global 'c'
873 p = %y -- ERROR: 'y' is not visible where 'g' is defined
874 end
875end
876\end{verbatim}
877
878
798\subsection{Tag Methods} \label{tag-method} 879\subsection{Tag Methods} \label{tag-method}
799 880
800Lua provides a powerful mechanism to extend its semantics, 881Lua provides a powerful mechanism to extend its semantics,
@@ -1123,6 +1204,9 @@ lines where the calls (and the error) were made.
1123 1204
1124Lua code can explicitly generate an error by calling the built-in 1205Lua code can explicitly generate an error by calling the built-in
1125function \verb|error| \see{pdf-error}. 1206function \verb|error| \see{pdf-error}.
1207Lua code can ``catch'' an error using the built-in function
1208\verb|call| \see{pdf-call}.
1209
1126 1210
1127 1211
1128\section{The Application Program Interface} 1212\section{The Application Program Interface}
@@ -1142,6 +1226,29 @@ The API functions can be classified in the following categories:
1142All API functions and related types and constants 1226All API functions and related types and constants
1143are declared in the header file \verb|lua.h|. 1227are declared in the header file \verb|lua.h|.
1144 1228
1229Before calling any API function,
1230the library must be initalizated.
1231This is done by calling:\Deffunc{lua_open}
1232\begin{verbatim}
1233void lua_open (void);
1234\end{verbatim}
1235This function allocates and initializes some internal structures,
1236and defines all pre-defined functions of Lua.
1237If the library is already opened,
1238this function has no effect.
1239
1240If necessary, the library may be closed:\Deffunc{lua_close}
1241\begin{verbatim}
1242void lua_close (void);
1243\end{verbatim}
1244This function destroys all objects in the Lua environment
1245(calling the correspondent garbage collector tag methods),
1246and then frees all dynamic memory used by the library.
1247Usually, there is no need to call this function,
1248since these resources are naturally released when the program ends.
1249If the library is already closed,
1250this function has no effect.
1251
1145\subsection{Exchanging Values between C and Lua} \label{valuesCLua} 1252\subsection{Exchanging Values between C and Lua} \label{valuesCLua}
1146Because Lua has no static type system, 1253Because Lua has no static type system,
1147all values passed between Lua and C have type 1254all values passed between Lua and C have type
@@ -1214,7 +1321,7 @@ otherwise, the function returns 0 (the \verb|NULL| pointer).
1214 1321
1215Because Lua has automatic memory management and garbage collection, 1322Because Lua has automatic memory management and garbage collection,
1216a \verb|lua_Object| has a limited scope, 1323a \verb|lua_Object| has a limited scope,
1217and is only valid inside the \emph{block} where it was created. 1324and is only valid inside the \emph{block} where it has been created.
1218A C function called from Lua is a block, 1325A C function called from Lua is a block,
1219and its parameters are valid only until its end. 1326and its parameters are valid only until its end.
1220It is good programming practice to convert Lua objects to C values 1327It is good programming practice to convert Lua objects to C values
@@ -1235,9 +1342,10 @@ If \verb|limit|=0, then Lua uses an adaptable heuristics to set this limit.
1235All communication between Lua and C is done through two 1342All communication between Lua and C is done through two
1236abstract data types, called \Def{lua2C} and \Def{C2lua}. 1343abstract data types, called \Def{lua2C} and \Def{C2lua}.
1237The first one, as the name implies, is used to pass values 1344The first one, as the name implies, is used to pass values
1238from Lua to C: parameters when Lua calls C and results when C calls Lua. 1345from Lua to C:
1346Parameters when Lua calls C and results when C calls Lua.
1239The structure C2lua is used in the reverse direction: 1347The structure C2lua is used in the reverse direction:
1240parameters when C calls Lua and results when Lua calls C. 1348Parameters when C calls Lua and results when Lua calls C.
1241 1349
1242The structure lua2C is an abstract array, 1350The structure lua2C is an abstract array,
1243which can be indexed with the function: 1351which can be indexed with the function:
@@ -1255,7 +1363,7 @@ Notice that the structure lua2C cannot be directly modified by C code.
1255 1363
1256The second structure, C2lua, is a stack. 1364The second structure, C2lua, is a stack.
1257Pushing elements into this stack 1365Pushing elements into this stack
1258is done with the following functions: 1366is done with the following functions and macros:
1259\Deffunc{lua_pushnumber}\Deffunc{lua_pushstring} 1367\Deffunc{lua_pushnumber}\Deffunc{lua_pushstring}
1260\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag} 1368\Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag}
1261\Deffunc{lua_pushnil}\Deffunc{lua_pushobject} 1369\Deffunc{lua_pushnil}\Deffunc{lua_pushobject}
@@ -1263,10 +1371,10 @@ is done with the following functions:
1263\begin{verbatim} 1371\begin{verbatim}
1264void lua_pushnumber (double n); 1372void lua_pushnumber (double n);
1265void lua_pushstring (char *s); 1373void lua_pushstring (char *s);
1266void lua_pushcfunction (lua_CFunction f);
1267void lua_pushusertag (void *u, int tag); 1374void lua_pushusertag (void *u, int tag);
1268void lua_pushnil (void); 1375void lua_pushnil (void);
1269void lua_pushobject (lua_Object object); 1376void lua_pushobject (lua_Object object);
1377void lua_pushcfunction (lua_CFunction f); /* macro */
1270\end{verbatim} 1378\end{verbatim}
1271All of them receive a C value, 1379All of them receive a C value,
1272convert it to a corresponding \verb|lua_Object|, 1380convert it to a corresponding \verb|lua_Object|,
@@ -1280,7 +1388,7 @@ returns a reference to the object at the top of the C2lua stack,
1280and pops it. 1388and pops it.
1281 1389
1282As a general rule, all API functions pop from the stack 1390As a general rule, all API functions pop from the stack
1283all elements that they use. 1391all elements they use.
1284 1392
1285Because userdata are objects, 1393Because userdata are objects,
1286the function \verb|lua_pushusertag| may create a new userdata. 1394the function \verb|lua_pushusertag| may create a new userdata.
@@ -1468,6 +1576,9 @@ If the C function has been called from Lua,
1468then the corresponding Lua execution terminates, 1576then the corresponding Lua execution terminates,
1469as if an error had occurred inside Lua code. 1577as if an error had occurred inside Lua code.
1470Otherwise, the whole program terminates with a call to \verb|exit(1)|. 1578Otherwise, the whole program terminates with a call to \verb|exit(1)|.
1579The \verb|message| is passed to the error handler method.
1580If \verb|message| is \verb|NULL|,
1581the error handler method is not called.
1471 1582
1472The error handler method \see{error} can be changed with: 1583The error handler method \see{error} can be changed with:
1473\Deffunc{lua_seterrormethod} 1584\Deffunc{lua_seterrormethod}
@@ -1495,6 +1606,13 @@ there is the function
1495lua_Object lua_gettagmethod (int tag, char *event); 1606lua_Object lua_gettagmethod (int tag, char *event);
1496\end{verbatim} 1607\end{verbatim}
1497 1608
1609It is also possible to copy all tag methods from one tag to another:
1610\Deffunc{lua_copytagmethods}
1611\begin{verbatim}
1612int lua_copytagmethods (int tagto, int tagfrom);
1613\end{verbatim}
1614This function returns \verb|tagto|.
1615
1498 1616
1499\subsection{C Functions} \label{LuacallC} 1617\subsection{C Functions} \label{LuacallC}
1500To register a C function to Lua, 1618To register a C function to Lua,
@@ -1527,8 +1645,30 @@ in direct order \see{valuesCLua}.
1527Like a Lua function, a C function called by Lua can also return 1645Like a Lua function, a C function called by Lua can also return
1528many results. 1646many results.
1529 1647
1530For some examples, see files \verb|strlib.c|, 1648When a C function is created,
1531\verb|iolib.c| and \verb|mathlib.c| in Lua distribution. 1649it is possible to associate some \emph{upvalues} to it;
1650then these values can be accessed by the function whenever it is called.
1651To associate upvalues to a function,
1652first these values must be pushed on C2lua.
1653Then the function:
1654\Deffunc{lua_pushCclosure}
1655\begin{verbatim}
1656void lua_pushCclosure (lua_CFunction fn, int n);
1657\end{verbatim}
1658is used to put the C function on C2lua,
1659with the argument \verb|n| telling how many upvalues must be
1660associated with the function
1661(notice that the macro \verb|lua_pushcfunction| is defined as
1662\verb|lua_pushCclosure| with \verb|n| set to 0).
1663Any time the function \verb|fn| is called,
1664it can access those upvalues using:
1665\Deffunc{lua_upvalue}
1666\begin{verbatim}
1667lua_Object lua_upvalue (int n);
1668\end{verbatim}
1669
1670For some examples, see files \verb|lstrlib.c|,
1671\verb|liolib.c| and \verb|lmathlib.c| in Lua distribution.
1532 1672
1533\subsection{References to Lua Objects} 1673\subsection{References to Lua Objects}
1534 1674
@@ -1581,14 +1721,15 @@ Currently there are three standard libraries:
1581\item input and output (plus some system facilities). 1721\item input and output (plus some system facilities).
1582\end{itemize} 1722\end{itemize}
1583In order to have access to these libraries, 1723In order to have access to these libraries,
1584the host program must call the functions 1724the C host program must call the functions
1585\verb|strlib_open|, \verb|mathlib_open|, and \verb|iolib_open|, 1725\verb|lua_strlibopen|, \verb|lua_mathlibopen|, and \verb|lua_iolibopen|,
1586declared in \verb|lualib.h|. 1726declared in \verb|lualib.h|.
1587 1727
1588 1728
1589\subsection{Predefined Functions} \label{predefined} 1729\subsection{Predefined Functions} \label{predefined}
1590 1730
1591\subsubsection*{\ff \T{call (func, arg, [retmode])}}\Deffunc{call} 1731\subsubsection*{\ff \T{call (func, arg [, mode [, errmethod]])}}\Deffunc{call}
1732\label{pdf-call}
1592This function calls function \verb|func| with 1733This function calls function \verb|func| with
1593the arguments given by the table \verb|arg|. 1734the arguments given by the table \verb|arg|.
1594The call is equivalent to 1735The call is equivalent to
@@ -1598,9 +1739,9 @@ The call is equivalent to
1598If \verb|arg.n| is not defined, 1739If \verb|arg.n| is not defined,
1599then Lua stops getting arguments at the first nil value. 1740then Lua stops getting arguments at the first nil value.
1600 1741
1601If \verb|retmode| is absent, 1742By default,
1602all results from \verb|func| are just returned by the call. 1743all results from \verb|func| are just returned by the call.
1603If \verb|retmode| is equal to \verb|"pack"|, 1744If the string \verb|mode| contains \verb|p|,
1604the results are \emph{packed} in a single table.\index{packed results} 1745the results are \emph{packed} in a single table.\index{packed results}
1605That is, \verb|call| returns just one table; 1746That is, \verb|call| returns just one table;
1606at index \verb|n|, the table has the total number of results 1747at index \verb|n|, the table has the total number of results
@@ -1611,9 +1752,24 @@ For instance, the following calls produce the following results:
1611a = call(sin, {5}) --> a = 0.0871557 = sin(5) 1752a = call(sin, {5}) --> a = 0.0871557 = sin(5)
1612a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) 1753a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments)
1613t = {x=1} 1754t = {x=1}
1614a = call(next, {t,nil;n=2}, "pack") --> a={"x", 1; n=2} 1755a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2}
1615\end{verbatim} 1756\end{verbatim}
1616 1757
1758By default,
1759if an error occurs during the function call,
1760the error is propagated.
1761If the string \verb|mode| contains \verb|x|,
1762then the call is \emph{protected}.\index{protected calls}
1763In this mode, function \verb|call| does not generate an error,
1764whatever happens during the call.
1765Instead, it returns \nil\ to signal the error
1766(besides calling the appropriated error method).
1767
1768If provided, \verb|errmethod| is temporarily set as the error method,
1769while \verb|func| runs.
1770As a particular case, if \verb|errmethod| is \nil,
1771no error messages will be issued during the execution of the called function.
1772
1617\subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage} 1773\subsubsection*{\ff \T{collectgarbage ([limit])}}\Deffunc{collectgarbage}
1618Forces a garbage collection cycle. 1774Forces a garbage collection cycle.
1619Returns the number of objects collected. 1775Returns the number of objects collected.
@@ -1638,15 +1794,12 @@ or a non \nil\ value if the chunk returns no values.
1638It issues an error when called with a non string argument. 1794It issues an error when called with a non string argument.
1639\verb|dofile| is equivalent to the API function \verb|lua_dofile|. 1795\verb|dofile| is equivalent to the API function \verb|lua_dofile|.
1640 1796
1641\subsubsection*{\ff \T{dostring (string [, errmethod])}}\Deffunc{dostring} 1797\subsubsection*{\ff \T{dostring (string)}}\Deffunc{dostring}
1642This function executes a given string as a Lua chunk. 1798This function executes a given string as a Lua chunk.
1643If there is any error executing the string, it returns \nil. 1799If there is any error executing the string, it returns \nil.
1644Otherwise, it returns the values returned by the chunk, 1800Otherwise, it returns the values returned by the chunk,
1645or a non \nil\ value if the chunk returns no values. 1801or a non \nil\ value if the chunk returns no values.
1646If provided, \verb|errmethod| is temporarily set as the error method, 1802\verb|dostring| is equivalent to the API function \verb|lua_dostring|.
1647while \verb|string| runs.
1648As a particular case, if \verb|errmethod| is \nil,
1649no error messages will be issued during the execution of the string.
1650 1803
1651\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} 1804\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag}
1652Returns a new tag. 1805Returns a new tag.
@@ -1661,17 +1814,17 @@ value associated with the index.
1661When called with \nil\ as its second argument, 1814When called with \nil\ as its second argument,
1662the function returns the first index 1815the function returns the first index
1663of the table (and its associated value). 1816of the table (and its associated value).
1664When called with the last index, or with \nil\ in an empty table, 1817When called with the last index,
1818or with \nil\ in an empty table,
1665it returns \nil. 1819it returns \nil.
1666 1820
1667In Lua there is no declaration of fields; 1821Lua has no declaration of fields;
1668semantically, there is no difference between a 1822semantically, there is no difference between a
1669field not present in a table or a field with value \nil. 1823field not present in a table or a field with value \nil.
1670Therefore, the function only considers fields with non \nil\ values. 1824Therefore, the function only considers fields with non \nil\ values.
1671The order in which the indices are enumerated is not specified, 1825The order in which the indices are enumerated is not specified,
1672\emph{not even for numeric indices} 1826\emph{even for numeric indices}
1673(to traverse a table in numeric order, 1827(to traverse a table in numeric order, use a counter).
1674use a counter).
1675If the table is modified in any way during a traversal, 1828If the table is modified in any way during a traversal,
1676the semantics of \verb|next| is undefined. 1829the semantics of \verb|next| is undefined.
1677 1830
@@ -1690,6 +1843,46 @@ otherwise the semantics of \verb|nextvar| is undefined.
1690 1843
1691This function cannot be written with the standard API. 1844This function cannot be written with the standard API.
1692 1845
1846\subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach}
1847Executes \verb|function| over all elements of \verb|table|.
1848For each element, the function is called with the index and
1849respective value as arguments.
1850If the function returns any non-nil value,
1851the loop is broken, and the value is returned
1852as the final value of |verb|foreach|.
1853
1854This function could be defined in Lua:
1855\begin{verbatim}
1856function foreach (t, f)
1857 local i, v = next(t, nil)
1858 while i do
1859 local res = f(i, v)
1860 if res then return res end
1861 i, v = next(t, i)
1862 end
1863end
1864\end{verbatim}
1865
1866\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar}
1867Executes \verb|function| over all global variables.
1868For each variable,
1869the function is called with its name and its value as arguments.
1870If the function returns any non-nil value,
1871the loop is broken, and the value is returned
1872as the final value of |verb|foreachvar|.
1873
1874This function could be defined in Lua:
1875\begin{verbatim}
1876function foreachvar (f)
1877 local n, v = nextvar(nil)
1878 while n do
1879 local res = f(n, v)
1880 if res then return res end
1881 n, v = nextvar(n)
1882 end
1883end
1884\end{verbatim}
1885
1693\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring} 1886\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring}
1694This function receives an argument of any type and 1887This function receives an argument of any type and
1695converts it to a string in a reasonable format. 1888converts it to a string in a reasonable format.
@@ -1697,19 +1890,27 @@ converts it to a string in a reasonable format.
1697\subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print} 1890\subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print}
1698This function receives any number of arguments, 1891This function receives any number of arguments,
1699and prints their values in a reasonable format. 1892and prints their values in a reasonable format.
1700Each value is printed in a new line.
1701This function is not intended for formatted output, 1893This function is not intended for formatted output,
1702but as a quick way to show a value, 1894but as a quick way to show a value,
1703for instance for error messages or debugging. 1895for instance for error messages or debugging.
1704See Section~\ref{libio} for functions for formatted output. 1896See Section~\ref{libio} for functions for formatted output.
1705 1897
1706\subsubsection*{\ff \T{tonumber (e)}}\Deffunc{tonumber} 1898\subsubsection*{\ff \T{tonumber (e [, base])}}\Deffunc{tonumber}
1707This function receives one argument, 1899This function receives one argument,
1708and tries to convert it to a number. 1900and tries to convert it to a number.
1709If the argument is already a number or a string convertible 1901If the argument is already a number or a string convertible
1710to a number \see{coercion}, then it returns that number; 1902to a number, then it returns that number;
1711otherwise, it returns \nil. 1903otherwise, it returns \nil.
1712 1904
1905An optional argument specifies the base to interpret the numeral.
1906The base may be any integer between 2 and 36 inclusive.
1907In bases above 10, the letter `A' (either upper or lower case)
1908represents 10, `B' represents 11, and so forth, with `Z' representing 35.
1909
1910In base 10 (the default), the number may have a decimal part,
1911as well as an optional exponent part \see{coercion}.
1912In other bases only integer numbers are accepted.
1913
1713\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} 1914\subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type}
1714This function allows Lua to test the type of a value. 1915This function allows Lua to test the type of a value.
1715It receives one argument, and returns its type, coded as a string. 1916It receives one argument, and returns its type, coded as a string.
@@ -1720,7 +1921,6 @@ The possible results of this function are
1720\verb|"table"|, 1921\verb|"table"|,
1721\verb|"function"|, 1922\verb|"function"|,
1722and \verb|"userdata"|. 1923and \verb|"userdata"|.
1723\verb|type| is equivalent to the API function \verb|lua_type|.
1724 1924
1725\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag} 1925\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}
1726This function allows Lua to test the tag of a value \see{TypesSec}. 1926This function allows Lua to test the tag of a value \see{TypesSec}.
@@ -1734,14 +1934,26 @@ This function sets the tag of a given table \see{TypesSec}.
1734For security reasons, 1934For security reasons,
1735it is impossible to change the tag of a userdata from Lua. 1935it is impossible to change the tag of a userdata from Lua.
1736 1936
1737\subsubsection*{\ff \T{assert (v)}}\Deffunc{assert} 1937\subsubsection*{\ff \T{assert (v [, message])}}\Deffunc{assert}
1738This function issues an \emph{``assertion failed!''} error 1938This function issues an \emph{``assertion failed!''} error
1739when its argument is \nil. 1939when its argument is \nil.
1740 1940
1941This function could be defined in Lua:
1942\begin{verbatim}
1943function assert (v, m)
1944 if not v then
1945 m = m or ""
1946 error("assertion failed! " .. m)
1947 end
1948end
1949\end{verbatim}
1950
1741\subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error} 1951\subsubsection*{\ff \T{error (message)}}\Deffunc{error}\label{pdf-error}
1742This function issues an error message and terminates 1952This function calls the error handler and then terminates
1743the last called function from the library 1953the last protected function called
1744(\verb|lua_dofile|, \verb|lua_dostring|, or \verb|lua_callfunction|). 1954(in C: \verb|lua_dofile|, \verb|lua_dostring|, or \verb|lua_callfunction|;
1955in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
1956If \verb|message| is \nil, the error handler is not called.
1745It never returns. 1957It never returns.
1746\verb|error| is equivalent to the API function \verb|lua_error|. 1958\verb|error| is equivalent to the API function \verb|lua_error|.
1747 1959
@@ -1760,8 +1972,10 @@ and \verb|value| is any Lua value.
1760 1972
1761\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} 1973\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
1762This function assigns the given value to a global variable. 1974This function assigns the given value to a global variable.
1763The string \verb|name| does not need to be a syntactically valid variable name. 1975The string \verb|name| does not need to be a
1764Therefore, this function can set global variables with strange names like 1976syntactically valid variable name.
1977Therefore,
1978this function can set global variables with strange names like
1765\verb|"m v 1"| or \verb|34|. 1979\verb|"m v 1"| or \verb|34|.
1766It returns the value of its second argument. 1980It returns the value of its second argument.
1767 1981
@@ -1799,12 +2013,17 @@ it restores the default behavior for the given event.
1799This function returns the current tag method 2013This function returns the current tag method
1800for a given pair \M{<tag, event>}. 2014for a given pair \M{<tag, event>}.
1801 2015
2016\subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}}
2017\Deffunc{copytagmethods}
2018This function copies all tag methods from one tag to another;
2019it returns \verb|tagto|.
2020
1802 2021
1803\subsection{String Manipulation} 2022\subsection{String Manipulation}
1804This library provides generic functions for string manipulation, 2023This library provides generic functions for string manipulation,
1805such as finding and extracting substrings and pattern matching. 2024such as finding and extracting substrings and pattern matching.
1806When indexing a string, the first character is at position~1, 2025When indexing a string, the first character is at position~1
1807not~0, as in C. 2026(not~0, as in C).
1808 2027
1809\subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} 2028\subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}}
1810\Deffunc{strfind} 2029\Deffunc{strfind}
@@ -1904,7 +2123,7 @@ the appropriate format string.
1904For example, \verb|"%*g"| can be simulated with 2123For example, \verb|"%*g"| can be simulated with
1905\verb|"%"..width.."g"|. 2124\verb|"%"..width.."g"|.
1906 2125
1907\subsubsection*{\ff \T{gsub (s, pat, repl [, table] [, n])}} 2126\subsubsection*{\ff \T{gsub (s, pat, repl [, n])}}
1908\Deffunc{gsub} 2127\Deffunc{gsub}
1909Returns a copy of \verb|s|, 2128Returns a copy of \verb|s|,
1910where all occurrences of the pattern \verb|pat| have been 2129where all occurrences of the pattern \verb|pat| have been
@@ -1918,11 +2137,7 @@ with \verb|n| between 1 and 9
1918stands for the value of the n-th captured substring. 2137stands for the value of the n-th captured substring.
1919 2138
1920If \verb|repl| is a function, then this function is called every time a 2139If \verb|repl| is a function, then this function is called every time a
1921match occurs, with the following arguments: 2140match occurs, with all captured substrings passed as arguments,
1922If \verb|table| is present, then the first argument is this table
1923and the second one is a match counter (1 for the first call).
1924Independently of these two optional arguments,
1925all captured substrings are passed as arguments,
1926in order (see below); 2141in order (see below);
1927If the value returned by this function is a string, 2142If the value returned by this function is a string,
1928then it is used as the replacement string; 2143then it is used as the replacement string;
@@ -1935,6 +2150,9 @@ For instance, when \verb|n| is 1 only the first occurrence of
1935 2150
1936See some examples below: 2151See some examples below:
1937\begin{verbatim} 2152\begin{verbatim}
2153 x = gsub("hello world", "(%w%w*)", "%1 %1")
2154 --> x="hello hello world world"
2155
1938 x = gsub("hello world", "(%w%w*)", "%1 %1", 1) 2156 x = gsub("hello world", "(%w%w*)", "%1 %1", 1)
1939 --> x="hello hello world" 2157 --> x="hello hello world"
1940 2158
@@ -1944,17 +2162,13 @@ See some examples below:
1944 x = gsub("4+5 = $return 4+5$", "$(.-)%$", dostring) 2162 x = gsub("4+5 = $return 4+5$", "$(.-)%$", dostring)
1945 --> x="4+5 = 9" 2163 --> x="4+5 = 9"
1946 2164
1947 function f(t, i, v) return t[v] end 2165 local t = {name="lua", version="3.0"}
1948 t = {name="lua", version="3.0"} 2166 x = gsub("$name - $version", "$(%w%w*)", function (v) return %t[v] end)
1949 x = gsub("$name - $version", "$(%w%w*)", f, t)
1950 --> x="lua - 3.0" 2167 --> x="lua - 3.0"
1951 2168
1952 t = {"apple", "orange", "lime"} 2169 t = {n=0}
1953 x = gsub("x and x and x", "x", rawgettable, t) 2170 gsub("first second word", "(%w%w*)",
1954 --> x="apple and orange and lime" 2171 function (w) %t.n = %t.n+1; %t[%t.n] = w end)
1955
1956 t = {}
1957 dummy, t.n = gsub("first second word", "(%w%w*)", rawsettable, t)
1958 --> t={"first", "second", "word"; n=3} 2172 --> t={"first", "second", "word"; n=3}
1959\end{verbatim} 2173\end{verbatim}
1960 2174
@@ -2073,10 +2287,13 @@ The library provides the following functions:
2073abs acos asin atan atan2 ceil cos floor log log10 2287abs acos asin atan atan2 ceil cos floor log log10
2074max min mod sin sqrt tan random randomseed 2288max min mod sin sqrt tan random randomseed
2075\end{verbatim} 2289\end{verbatim}
2290plus a global variable \IndexVerb{PI}.
2076Most of them 2291Most of them
2077are only interfaces to the homonymous functions in the C library, 2292are only interfaces to the homonymous functions in the C library,
2078except that, for the trigonometric functions, 2293except that, for the trigonometric functions,
2079all angles are expressed in \emph{degrees}, not radians. 2294all angles are expressed in \emph{degrees}, not radians.
2295Functions \IndexVerb{deg} and \IndexVerb{rad} can be used to convert
2296between radians and degrees.
2080 2297
2081The function \verb|max| returns the maximum 2298The function \verb|max| returns the maximum
2082value of its numeric arguments. 2299value of its numeric arguments.
@@ -2195,11 +2412,12 @@ This function returns a string with a file name that can safely
2195be used for a temporary file. 2412be used for a temporary file.
2196The file must be explicitly removed when no longer needed. 2413The file must be explicitly removed when no longer needed.
2197 2414
2198\subsubsection*{\ff \T{read ([readpattern])}}\Deffunc{read} 2415\subsubsection*{\ff \T{read ([filehandle] [readpattern])}}\Deffunc{read}
2199 2416
2200This function reads the file \verb|_INPUT| 2417This function reads the file \verb|_INPUT|,
2418or from \verb|filehandle| if this argument is given,
2201according to a read pattern, that specifies how much to read; 2419according to a read pattern, that specifies how much to read;
2202characters are read from the current input file until 2420characters are read from the input file until
2203the read pattern fails or ends. 2421the read pattern fails or ends.
2204The function \verb|read| returns a string with the characters read, 2422The function \verb|read| returns a string with the characters read,
2205even if the pattern succeeds only partially, 2423even if the pattern succeeds only partially,
@@ -2220,7 +2438,7 @@ it never fails.
2220A character class followed by \verb|*| reads until a character that 2438A character class followed by \verb|*| reads until a character that
2221does not belong to the class, or end of file; 2439does not belong to the class, or end of file;
2222since it can match a sequence of zero characters, it never fails. 2440since it can match a sequence of zero characters, it never fails.
2223Notice that the behavior of read patterns is different from 2441Notice that the behavior of read patterns is slightly different from
2224the regular pattern matching behavior, 2442the regular pattern matching behavior,
2225where a \verb|*| expands to the maximum length \emph{such that} 2443where a \verb|*| expands to the maximum length \emph{such that}
2226the rest of the pattern does not fail. 2444the rest of the pattern does not fail.
@@ -2247,10 +2465,11 @@ or \nil\ on end of file.
2247or \nil\ if the next characters do not conform to an integer format. 2465or \nil\ if the next characters do not conform to an integer format.
2248\end{itemize} 2466\end{itemize}
2249 2467
2250\subsubsection*{\ff \T{write (value1, ...)}}\Deffunc{write} 2468\subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\Deffunc{write}
2251 2469
2252This function writes the value of each of its arguments to the 2470This function writes the value of each of its arguments to the
2253file \verb|_OUTPUT|. 2471file \verb|_OUTPUT|,
2472or to \verb|filehandle| if this argument is given,
2254The arguments must be strings or numbers. 2473The arguments must be strings or numbers.
2255To write other values, 2474To write other values,
2256use \verb|tostring| or \verb|format| before \verb|write|. 2475use \verb|tostring| or \verb|format| before \verb|write|.
@@ -2436,35 +2655,36 @@ is provided with the standard distribution.
2436This program can be called with any sequence of the following arguments: 2655This program can be called with any sequence of the following arguments:
2437\begin{description} 2656\begin{description}
2438\item[\T{-v}] prints version information. 2657\item[\T{-v}] prints version information.
2439\item[\T{-}] runs interactively, accepting commands from standard input 2658\item[\T{-d}] turns on debug information.
2440until an \verb|EOF|.
2441\item[\T{-e stat}] executes \verb|stat| as a Lua chunk. 2659\item[\T{-e stat}] executes \verb|stat| as a Lua chunk.
2442\item[\T{var=exp}] executes \verb|var=exp| as a Lua chunk. 2660\item[\T{-i}] runs interactively,
2661accepting commands from standard input until an \verb|EOF|.
2662Each line entered is immediatly executed.
2663\item[\T{-q}] same as \T{-i}, but without a prompt (quiet mode).
2664\item[\T{-}] executes \verb|stdin| as a file.
2665\item[\T{var=value}] sets global \verb|var| with string \verb|value|.
2443\item[\T{filename}] executes file \verb|filename| as a Lua chunk. 2666\item[\T{filename}] executes file \verb|filename| as a Lua chunk.
2444\end{description} 2667\end{description}
2668When called without arguments,
2669Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal,
2670and \verb|lua -| otherwise.
2671
2445All arguments are handled in order. 2672All arguments are handled in order.
2446For instance, an invocation like 2673For instance, an invocation like
2447\begin{verbatim} 2674\begin{verbatim}
2448$ lua - a=1 prog.lua 2675$ lua -i a=test prog.lua
2449\end{verbatim} 2676\end{verbatim}
2450will first interact with the user until an \verb|EOF|, 2677will first interact with the user until an \verb|EOF|,
2451then will set \verb|a| to 1, 2678then will set \verb|a| to \verb|"test"|,
2452and finally will run file \verb|prog.lua|. 2679and finally will run file \verb|prog.lua|.
2453 2680
2454Please notice that the interaction with the shell may lead to 2681When in interactive mode,
2455unintended results. 2682a multi-line statement can be written finishing intermediate
2456For instance, a call like 2683lines with a backslash (\verb|\|).
2684The prompt presented is the value of the global variable \verb|_PROMPT|.
2685For instance, the prompt can be changed like below:
2457\begin{verbatim} 2686\begin{verbatim}
2458$ lua a="name" prog.lua 2687$ lua _PROMPT='myprompt> ' -i
2459\end{verbatim}
2460will \emph{not} set \verb|a| to the string \verb|"name"|.
2461Instead, the quotes will be handled by the shell,
2462lua will get only \verb|a=name| to run,
2463and \verb|a| will finish with \nil,
2464because the global variable \verb|name| has not been initialized.
2465Instead, one should write
2466\begin{verbatim}
2467$ lua 'a="name"' prog.lua
2468\end{verbatim} 2688\end{verbatim}
2469 2689
2470\section*{Acknowledgments} 2690\section*{Acknowledgments}
@@ -2487,122 +2707,31 @@ the previous public versions of Lua,
2487some differences had to be introduced. 2707some differences had to be introduced.
2488Here is a list of all these incompatibilities. 2708Here is a list of all these incompatibilities.
2489 2709
2490\subsection*{Incompatibilities with \Index{version 2.5}} 2710\subsection*{Incompatibilities with \Index{version 3.0}}
2491\begin{itemize} 2711\begin{itemize}
2492\item
2493The whole fallback mechanism has been replaced by tag methods.
2494Nevertheless, the function \verb|setfallback| has been rewritten in
2495a way that uses tag methods to fully emulate the old behavior
2496of fallbacks.
2497\item
2498Tags now must be created with the function \verb|newtag|.
2499Nevertheless, old user defined tags are still accepted
2500(user defined tags must be positive;
2501\verb|newtag| uses negative numbers).
2502Tag methods cannot be set for such user defined tags,
2503and fallbacks do not affect tags created by \verb|newtag|.
2504\item
2505Lua 2.5 accepts mixed comparisons of strings and numbers,
2506like \verb|2<"12"|, giving weird results.
2507Now this is an error.
2508\item
2509Character \verb|"-"| (hyphen) now is ``magic'' in pattern matching.
2510\item
2511Some API functions have been rewritten as macros.
2512\end{itemize}
2513 2712
2514\subsection*{Incompatibilities with \Index{version 2.4}} 2713\item The whole library must be explicitly openen before used.
2515The whole I/O facilities have been rewritten. 2714However, all standard libraries check whether Lua is already opened,
2516We strongly encourage programmers to adapt their code 2715so any program that opens at least one standard library before using
2517to this new version. 2716Lua API does not need to be corrected.
2518The incompatibilities between the new and the old libraries are:
2519\begin{itemize}
2520\item The format facility of function \verb|write| has been supersed by
2521function \verb|format|;
2522therefore this facility has been dropped.
2523\item Function \verb|read| now uses \emph{read patterns} to specify
2524what to read;
2525this is incompatible with the old format options.
2526\item Function \verb|strfind| now accepts patterns,
2527so it may have a different behavior when the pattern includes
2528special characters.
2529\end{itemize}
2530 2717
2531\subsection*{Incompatibilities with \Index{version 2.2}} 2718\item Function \verb|dostring| does not accept an optional second argument,
2532\begin{itemize} 2719with a temporary error method.
2533\item 2720Now Function \verb|call| offers this facility.
2534Functions \verb|date| and \verb|time| (from \verb|iolib|)
2535have been superseded by the new, more powerful version of function \verb|date|.
2536\item
2537Function \verb|append| (from \verb|iolib|) now returns 1 whenever it succeeds,
2538whether the file is new or not.
2539\item
2540Function \verb|int2str| (from \verb|strlib|) has been superseded by new
2541function \verb|format|, with parameter \verb|"%c"|.
2542\item
2543The API lock mechanism has been superseded by the reference mechanism.
2544However, \verb|lua.h| provides compatibility macros,
2545so there is no need to change programs.
2546\item
2547The API function \verb|lua_pushliteral| now is just a macro to
2548\verb|lua_pushstring|.
2549\end{itemize}
2550 2721
2551\subsection*{Incompatibilities with \Index{version 2.1}} 2722\item Function \verb|gsub| does not accept an optional fourth argument
2552\begin{itemize} 2723(a callback data, a table).
2553\item 2724Closures make this feature irrelevant.
2554The function \verb|type| now returns the string \verb|"function"| 2725
2555both for C and Lua functions. 2726\item The syntax for function declaration is now more restricted;
2556Because Lua functions and C functions are compatible, 2727for instance, the old syntax \verb|function f[exp] (x) ... end| is not
2557this behavior is usually more useful. 2728accepted in 3.1.
2558When needed, the second result of function \T{type} may be used 2729Progams should use an explicit assignment instead.
2559to distinguish between Lua and C functions. 2730
2560\item 2731\item Old pre-compiled code is obsolete, and must be re-compiled.
2561A function definition only assigns the function value to the 2732
2562given variable at execution time. 2733\item The option \verb|a=b| in Lua stand-alone does not need extra quotes.
2563\end{itemize}
2564 2734
2565\subsection*{Incompatibilities with \Index{version 1.1}}
2566\begin{itemize}
2567\item
2568The equality test operator now is denoted by \verb|==|,
2569instead of \verb|=|.
2570\item
2571The syntax for table construction has been greatly simplified.
2572The old \verb|@(size)| has been substituted by \verb|{}|.
2573The list constructor (formerly \verb|@[...]|) and the record
2574constructor (formerly \verb|@{...}|) now are both coded like
2575\verb|{...}|.
2576When the construction involves a function call,
2577like in \verb|@func{...}|,
2578the new syntax does not use the \verb|@|.
2579More important, \emph{a construction function must now
2580explicitly return the constructed table}.
2581\item
2582The function \verb|lua_call| no longer has the parameter \verb|nparam|.
2583\item
2584The function \verb|lua_pop| is no longer available,
2585since it could lead to strange behavior.
2586In particular,
2587to access results returned from a Lua function,
2588the new macro \verb|lua_getresult| should be used.
2589\item
2590The old functions \verb|lua_storefield| and \verb|lua_storeindexed|
2591have been replaced by
2592\begin{verbatim}
2593int lua_storesubscript (void);
2594\end{verbatim}
2595with the parameters explicitly pushed on the stack.
2596\item
2597The functionality of the function \verb|lua_errorfunction| has been
2598replaced by the \emph{fallback} mechanism \see{error}.
2599\item
2600When calling a function from the Lua library,
2601parameters passed through the stack
2602must be pushed just before the corresponding call,
2603with no intermediate calls to Lua.
2604Special care should be taken with macros like
2605\verb|lua_getindexed| and \verb|lua_getfield|.
2606\end{itemize} 2735\end{itemize}
2607 2736
2608\newcommand{\indexentry}[2]{\item {#1} #2} 2737\newcommand{\indexentry}[2]{\item {#1} #2}