aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-06-06 09:49:28 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2002-06-06 09:49:28 -0300
commitdc6e6c48bb7eeac20f79acd9fe4aa4fbb4496303 (patch)
tree87e0ebe5d3e33d2d793d84ff7592d9eb7838391b
parente3cddc950cc84755437e3c2302d12f6c3fcb691b (diff)
downloadlua-dc6e6c48bb7eeac20f79acd9fe4aa4fbb4496303.tar.gz
lua-dc6e6c48bb7eeac20f79acd9fe4aa4fbb4496303.tar.bz2
lua-dc6e6c48bb7eeac20f79acd9fe4aa4fbb4496303.zip
on the way to 5.0
-rw-r--r--manual.tex322
1 files changed, 168 insertions, 154 deletions
diff --git a/manual.tex b/manual.tex
index 9dcd09da..883dd0c8 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.54 2001/10/31 20:31:38 roberto Exp $ 1% $Id: manual.tex,v 1.55 2002/02/14 21:48:32 roberto Exp roberto $
2 2
3\documentclass[11pt,twoside,draft]{article} 3\documentclass[11pt,twoside,draft]{article}
4\usepackage{fullpage} 4\usepackage{fullpage}
@@ -20,7 +20,7 @@
20\newcommand{\False}{{\bf false}} 20\newcommand{\False}{{\bf false}}
21\newcommand{\True}{{\bf true}} 21\newcommand{\True}{{\bf true}}
22%\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} 22%\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}}
23\def\tecgraf{{\sf TeCGraf}} 23\def\tecgraf{{\sf Tecgraf}}
24 24
25\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}} 25\newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}}
26\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}} 26\newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}}
@@ -81,39 +81,31 @@ Last revised on \today
81\null\vfill 81\null\vfill
82 82
83\noindent 83\noindent
84Copyright \copyright\ 1994--2001 TeCGraf, PUC-Rio. All rights reserved. 84Copyright \copyright\ 2002 Tecgraf, PUC-Rio. All rights reserved.
85
86Permission is hereby granted, free of charge,
87to any person obtaining a copy of this software
88and associated documentation files (the "Software"),
89to deal in the Software without restriction,
90including without limitation the rights to use, copy, modify,
91merge, publish, distribute, sublicense,
92and/or sell copies of the Software,
93and to permit persons to whom the Software is furnished to do so,
94subject to the following conditions:
95
96The above copyright notice and this permission notice shall be
97included in all copies or substantial portions of the Software.
98
99THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
100EXPRESS OR IMPLIED,
101INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
102FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
103IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
104FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
105WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
106ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
107OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
85 108
86Permission is hereby granted, without written agreement and without license
87or royalty fees, to use, copy, modify, translate, and distribute
88this software and its documentation (hereby called the ``package'')
89for any purpose, including commercial applications, subject to
90the following conditions:
91\begin{itemize}
92\item The above copyright notice and this permission notice shall appear in all
93 copies or substantial portions of this package.
94
95\item The origin of this package must not be misrepresented; you must not
96 claim that you wrote the original package. If you use this package in a
97 product, an acknowledgment in the product documentation would be greatly
98 appreciated (but it is not required).
99
100\item Altered source versions must be plainly marked as such, and must not be
101 misrepresented as being the original package.
102\end{itemize}
103The authors specifically disclaim any warranties, including, but not limited
104to, the implied warranties of merchantability and fitness for a particular
105purpose. The package provided hereunder is on an ``as~is'' basis, and the
106authors have no obligation to provide maintenance, support, updates,
107enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the
108authors be held liable to any party for direct, indirect, special,
109incidental, or consequential damages arising out of the use of this package
110and its documentation.
111
112The Lua language and this implementation have been entirely designed and
113written by Waldemar Celes, Roberto Ierusalimschy, and Luiz Henrique de
114Figueiredo at TeCGraf, PUC-Rio in Brazil.
115
116This implementation contains no third-party code.
117 109
118Copies of this manual can be obtained at 110Copies of this manual can be obtained at
119Lua's official web site, 111Lua's official web site,
@@ -140,7 +132,7 @@ Waldemar Celes
140\tecgraf\ --- Computer Science Department --- PUC-Rio 132\tecgraf\ --- Computer Science Department --- PUC-Rio
141} 133}
142 134
143%\date{{\small \tt\$Date: 2001/10/31 20:31:38 $ $}} 135%\date{{\small \tt\$Date: 2002/02/14 21:48:32 $ $}}
144 136
145\maketitle 137\maketitle
146 138
@@ -282,12 +274,10 @@ environments, and freely switch between them \see{mangstate}.
282 274
283The global environment can be manipulated by Lua code or 275The global environment can be manipulated by Lua code or
284by the embedding program, 276by the embedding program,
285which can read and write global variables
286using the API functions from the library that implements Lua. 277using the API functions from the library that implements Lua.
287 278
288The unit of execution of Lua is called a \Def{chunk}. 279The unit of execution of Lua is called a \Def{chunk}.
289A chunk is simply a sequence of statements, 280A chunk is simply a sequence of statements.
290which are executed sequentially.
291Statements are described in \See{stats}. 281Statements are described in \See{stats}.
292 282
293A chunk may be stored in a file or in a string inside the host program. 283A chunk may be stored in a file or in a string inside the host program.
@@ -330,7 +320,7 @@ Lua is 8-bit clean,
330and so strings may contain any 8-bit character, 320and so strings may contain any 8-bit character,
331including embedded zeros (\verb|'\0'|) \see{lexical}. 321including embedded zeros (\verb|'\0'|) \see{lexical}.
332 322
333Functions are considered \emph{first-class values} in Lua. 323Functions are \emph{first-class values} in Lua.
334This means that functions can be stored in variables, 324This means that functions can be stored in variables,
335passed as arguments to other functions, and returned as results. 325passed as arguments to other functions, and returned as results.
336Lua can call (and manipulate) functions written in Lua and 326Lua can call (and manipulate) functions written in Lua and
@@ -353,7 +343,7 @@ The type \emph{table} implements \Index{associative arrays},
353that is, \Index{arrays} that can be indexed not only with numbers, 343that is, \Index{arrays} that can be indexed not only with numbers,
354but with any value (except \nil). 344but with any value (except \nil).
355Moreover, 345Moreover,
356tables are \emph{heterogeneous}, 346tables can be \emph{heterogeneous},
357that is, they can contain values of all types. 347that is, they can contain values of all types.
358Tables are the sole data structuring mechanism in Lua; 348Tables are the sole data structuring mechanism in Lua;
359they may be used not only to represent ordinary arrays, 349they may be used not only to represent ordinary arrays,
@@ -368,10 +358,7 @@ Like indices, the value of a table field can be of any type.
368In particular, 358In particular,
369because functions are first class values, 359because functions are first class values,
370table fields may contain functions. 360table fields may contain functions.
371So, tables may also carry \emph{methods}. 361So, tables may also carry \emph{methods} \see{func-def}.
372%The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
373%which calls the method \verb|f| from the table \verb|t| passing
374%the table itself as the first parameter \see{func-def}.
375 362
376Tables, functions, and userdata values are \emph{objects}: 363Tables, functions, and userdata values are \emph{objects}:
377variables do not actually \emph{contain} these values, 364variables do not actually \emph{contain} these values,
@@ -394,7 +381,7 @@ Lua checks for a function in the field \verb|"add"| in its metatable.
394If it finds one, 381If it finds one,
395Lua calls that function to perform the addition. 382Lua calls that function to perform the addition.
396 383
397A metatable works as a kind of an extended ``type'' for the object. 384A metatable works as a kind of an extended ``type'' for the object:
398Objects that share a metatable has identical behavior. 385Objects that share a metatable has identical behavior.
399 386
400A metatable controls how an object behaves in arithmetic operations, 387A metatable controls how an object behaves in arithmetic operations,
@@ -413,7 +400,8 @@ through the \verb|metatable| function \see{pdf-metatable}.
413 400
414\subsection{\Index{Coercion}} \label{coercion} 401\subsection{\Index{Coercion}} \label{coercion}
415 402
416Lua provides automatic conversion between string and number values at run time. 403Lua provides automatic conversion between
404string and number values at run time.
417Any arithmetic operation applied to a string tries to convert 405Any arithmetic operation applied to a string tries to convert
418that string to a number, following the usual rules. 406that string to a number, following the usual rules.
419Conversely, whenever a number is used when a string is expected, 407Conversely, whenever a number is used when a string is expected,
@@ -430,15 +418,16 @@ use the \verb|format| function \see{format}.
430There are two kinds of variables in Lua: 418There are two kinds of variables in Lua:
431global variables 419global variables
432and local variables. 420and local variables.
433\Index{Global variables} do not need to be declared.
434Variables are assumed to be global unless explicitly declared local 421Variables are assumed to be global unless explicitly declared local
435\see{localvar}. 422\see{localvar}.
436Before the first assignment, the value of a variable is \nil\ % 423Before the first assignment, the value of a variable is \nil.
437(this default can be changed for global variables; see \See{tag-method}).
438 424
439An ordinary Lua table is used to keep all global names and values. 425All global variables live as fields in ordinary Lua tables.
440This table can be accessed and changed with the \verb|globals| function 426Usually, globals live in a table called \Index{table of globals}.
441\see{pdf-globals}. 427However, a function can individually change its global table,
428so that all global variables in that function will refer to that table.
429This mechanism allows the creation of \Index{namespaces} and other
430modularization facilities.
442 431
443\Index{Local variables} are lexically scoped. 432\Index{Local variables} are lexically scoped.
444Therefore, local variables can be freely accessed by functions 433Therefore, local variables can be freely accessed by functions
@@ -501,11 +490,11 @@ A weak table can have weak keys, weak values, or both.
501A table with weak keys allows the collection of its keys, 490A table with weak keys allows the collection of its keys,
502but prevents the collection of its values. 491but prevents the collection of its values.
503A table with both weak keys and weak values allows the collection of 492A table with both weak keys and weak values allows the collection of
504both keys and values 493both keys and values.
505In any case, if either the key or the value is collected, 494In any case, if either the key or the value is collected,
506the whole pair is removed from the table. 495the whole pair is removed from the table.
507The weakness of a table is controled by the 496The weakness of a table is controled by the
508\verb|weakmode| field in its metatable \see{weakmode}. 497\verb|__weakmode| field in its metatable \see{weakmode}.
509 498
510 499
511%------------------------------------------------------------------------------ 500%------------------------------------------------------------------------------
@@ -538,13 +527,12 @@ and cannot be used as identifiers:
538 or repeat return then true 527 or repeat return then true
539 until while 528 until while
540\end{verbatim} 529\end{verbatim}
541(The keyword \rwd{global} is reserved for future use.)
542 530
543Lua is a case-sensitive language: 531Lua is a case-sensitive language:
544\T{and} is a reserved word, but \T{And} and \T{\'and} 532\T{and} is a reserved word, but \T{And} and \T{\'and}
545(if the locale permits) are two different, valid identifiers. 533(if the locale permits) are two different, valid identifiers.
546As a convention, identifiers starting with an underscore followed by 534As a convention, identifiers starting with an underscore followed by
547uppercase letters (such as \verb|_INPUT|) 535uppercase letters (such as \verb|_VERSION|)
548are reserved for internal variables. 536are reserved for internal variables.
549 537
550The following strings denote other \Index{tokens}: 538The following strings denote other \Index{tokens}:
@@ -574,7 +562,7 @@ A character in a string may also be specified by its numerical value,
574through the escape sequence `\verb|\|\emph{ddd}', 562through the escape sequence `\verb|\|\emph{ddd}',
575where \emph{ddd} is a sequence of up to three \emph{decimal} digits. 563where \emph{ddd} is a sequence of up to three \emph{decimal} digits.
576Strings in Lua may contain any 8-bit value, including embedded zeros, 564Strings in Lua may contain any 8-bit value, including embedded zeros,
577which can be specified as `\verb|\000|'. 565which can be specified as `\verb|\0|'.
578 566
579Literal strings can also be delimited by matching \verb|[[| $\ldots$ \verb|]]|. 567Literal strings can also be delimited by matching \verb|[[| $\ldots$ \verb|]]|.
580Literals in this bracketed form may run for several lines, 568Literals in this bracketed form may run for several lines,
@@ -589,7 +577,7 @@ other quoted strings.
589As an example, in a system using ASCII 577As an example, in a system using ASCII
590(in which `\verb|a|' is coded as~97, 578(in which `\verb|a|' is coded as~97,
591newline is coded as~10, and `\verb|1|' is coded as~49), 579newline is coded as~10, and `\verb|1|' is coded as~49),
592the following four literals below are equivalent: 580the four literals below denote the same string:
593\begin{verbatim} 581\begin{verbatim}
594 1) "alo\n123\"" 582 1) "alo\n123\""
595 2) '\97lo\10\04923"' 583 2) '\97lo\10\04923"'
@@ -608,8 +596,14 @@ Examples of valid numerical constants are
608\end{verbatim} 596\end{verbatim}
609 597
610\IndexEmph{Comments} start anywhere outside a string with a 598\IndexEmph{Comments} start anywhere outside a string with a
611double hyphen (\verb|--|) and run until the end of the line. 599double hyphen (\verb|--|);
612(There are no block comments in Lua.) 600If the text after \verb|--| is different from \verb|[[|,
601the comment is a short comment,
602that runs until the end of the line.
603Otherwise, it is a long comment,
604that runs until the corresponding \verb|]]|.
605Long comments may run for several lines,
606and may contain nested \verb|[[| $\ldots$ \verb|]]| pairs.
613For convenience, 607For convenience,
614the first line of a chunk is skipped if it starts with \verb|#|. 608the first line of a chunk is skipped if it starts with \verb|#|.
615This facility allows the use of Lua as a script interpreter 609This facility allows the use of Lua as a script interpreter
@@ -647,15 +641,19 @@ The expression denoting the table to be indexed has a restricted syntax;
647The meaning of assignments and evaluations of global and 641The meaning of assignments and evaluations of global and
648indexed variables can be changed via metatables. 642indexed variables can be changed via metatables.
649An assignment to a global variable \verb|x = val| 643An assignment to a global variable \verb|x = val|
650is equivalent to an assignment in the global table: 644is equivalent to the assignment
651\verb|globals().x = val|. 645\verb|_glob.x = val|,
646where \verb|_glob| is the table of globals of the running function
647(\see{global-table} for a discussion about the table of globals).
652An assignment to an indexed variable \verb|t[i] = val| is equivalent to 648An assignment to an indexed variable \verb|t[i] = val| is equivalent to
653\verb|settable_event(t,i,val)|. 649\verb|settable_event(t,i,val)|.
654An access to a global variable \verb|x| 650An access to a global variable \verb|x|
655is equivalent to an access to the global table: \verb|globals().x|. 651is equivalent to \verb|_glob.x|
652(again, \see{global-table} for a discussion about \verb|_glob|).
656An access to an indexed variable \verb|t[i]| is equivalent to 653An access to an indexed variable \verb|t[i]| is equivalent to
657a call \verb|gettable_event(t,i)|. 654a call \verb|gettable_event(t,i)|.
658See \See{metatable} for a complete description of these functions. 655See \See{metatable} for a complete description of the
656\verb|settable_event| and \verb|gettable_event| functions.
659(These functions are not defined in Lua. 657(These functions are not defined in Lua.
660We use them here only for explanatory purposes.) 658We use them here only for explanatory purposes.)
661 659
@@ -667,8 +665,7 @@ similar to those in Pascal or C.
667The conventional commands include 665The conventional commands include
668assignment, control structures, and procedure calls. 666assignment, control structures, and procedure calls.
669Non-conventional commands include table constructors 667Non-conventional commands include table constructors
670\see{tableconstructor} 668and variable declarations.
671and local variable declarations \see{localvar}.
672 669
673\subsubsection{Chunks}\label{chunks} 670\subsubsection{Chunks}\label{chunks}
674The unit of execution of Lua is called a \Def{chunk}. 671The unit of execution of Lua is called a \Def{chunk}.
@@ -687,7 +684,7 @@ Non-terminals are shown in \emph{italics},
687keywords are shown in {\bf bold}, 684keywords are shown in {\bf bold},
688and other terminal symbols are shown in {\tt typewriter} font, 685and other terminal symbols are shown in {\tt typewriter} font,
689enclosed in single quotes. 686enclosed in single quotes.
690The complete syntax of Lua in EBNF is given on page~\pageref{BNF}. 687The complete syntax of Lua in extended BNF is given on page~\pageref{BNF}.
691 688
692\subsubsection{Blocks} 689\subsubsection{Blocks}
693A \Index{block} is a list of statements; 690A \Index{block} is a list of statements;
@@ -702,7 +699,7 @@ A block may be explicitly delimited:
702\end{Produc}% 699\end{Produc}%
703\IndexKW{do} 700\IndexKW{do}
704Explicit blocks are useful 701Explicit blocks are useful
705to control the scope of local variables \see{localvar}. 702to control the scope of variable declarations.
706Explicit blocks are also sometimes used to 703Explicit blocks are also sometimes used to
707add a \rwd{return} or \rwd{break} statement in the middle 704add a \rwd{return} or \rwd{break} statement in the middle
708of another block \see{control}. 705of another block \see{control}.
@@ -723,9 +720,9 @@ Expressions are discussed in \See{expressions}.
723Before the assignment, 720Before the assignment,
724the list of values is \emph{adjusted} to the length of 721the list of values is \emph{adjusted} to the length of
725the list of variables.\index{adjustment} 722the list of variables.\index{adjustment}
726If there are more values than are needed, 723If there are more values than needed,
727the excess values are thrown away. 724the excess values are thrown away.
728If there are less values than are needed, 725If there are less values than needed,
729the list is extended with as many \nil's as needed. 726the list is extended with as many \nil's as needed.
730If the list of expressions ends with a function call, 727If the list of expressions ends with a function call,
731then all values returned by that function call enter in the list of values, 728then all values returned by that function call enter in the list of values,
@@ -739,7 +736,7 @@ So, the code
739 i = 3 736 i = 3
740 i, a[i] = i+1, 20 737 i, a[i] = i+1, 20
741\end{verbatim} 738\end{verbatim}
742sets \verb|a[3]| to 20, but does not affect \verb|a[4]| 739sets \verb|a[3]| to 20, without affecting \verb|a[4]|
743because the \verb|i| in \verb|a[i]| is evaluated 740because the \verb|i| in \verb|a[i]| is evaluated
744before it is assigned 4. 741before it is assigned 4.
745Similarly, the line 742Similarly, the line
@@ -762,11 +759,12 @@ familiar syntax:
762 \rep{\rwd{elseif} exp \rwd{then} block} 759 \rep{\rwd{elseif} exp \rwd{then} block}
763 \opt{\rwd{else} block} \rwd{end}} 760 \opt{\rwd{else} block} \rwd{end}}
764\end{Produc}% 761\end{Produc}%
765There is also a \rwd{for} statement in two flavors \see{for}. 762Lua also has a \rwd{for} statement, in two flavors \see{for}.
766 763
767The \Index{condition expression} \M{exp} of a 764The \Index{condition expression} \M{exp} of a
768control structure may return any value. 765control structure may return any value.
769All values different from \nil\ and \False\ are considered true; 766All values different from \nil\ and \False\ are considered true
767(in particular, the number 0 and the empty string are also true);
770both \False\ and \nil\ are considered false. 768both \False\ and \nil\ are considered false.
771 769
772The \rwd{return} statement is used to return values 770The \rwd{return} statement is used to return values
@@ -858,51 +856,45 @@ it calls this function to produce a new value for each iteration,
858stopping when the new value is \nil. 856stopping when the new value is \nil.
859It has the following syntax: 857It has the following syntax:
860\begin{Produc} 858\begin{Produc}
861\produc{stat}{\rwd{for} name \opt{\ter{,} name} \rwd{in} exp 859\produc{stat}{\rwd{for} name \rep{\ter{,} name} \rwd{in} explist1
862 \rwd{do} block \rwd{end}} 860 \rwd{do} block \rwd{end}}
863\end{Produc}% 861\end{Produc}%
864A \rwd{for} statement like 862A \rwd{for} statement like
865\begin{verbatim} 863\begin{verbatim}
866 for var1, var2 in exp do block end 864 for var_1, ..., var_n in explist do block end
867\end{verbatim} 865\end{verbatim}
868is equivalent to the code: 866is equivalent to the code:
869\begin{verbatim} 867\begin{verbatim}
870 do 868 do
871 local _f = exp 869 local _f, _s, var_1 = explist
872 while 1 do 870 while 1 do
873 local var1, var2 = _f() 871 local var_2, ..., var_n
874 if var1 == nil then break end 872 var_1, ..., var_n = _f(_s, var_1)
873 if var_1 == nil then break end
875 block 874 block
876 end 875 end
877 end 876 end
878\end{verbatim} 877\end{verbatim}
879Note the following: 878Note the following:
880\begin{itemize}\itemsep=0pt 879\begin{itemize}\itemsep=0pt
881\item \verb|exp| is evaluated only once. 880\item \verb|explist| is evaluated only once.
882Its result is the function that will be evaluated for each loop. 881Its results are a ``generator'' function,
883\item \verb|_f| is an invisible variable. 882a ``state'', and an initial value for the ``iterator variable''.
884The name is here for explanatory purposes only. 883\item \verb|_f| and \verb|_s| are invisible variables.
885\item The behavior is \emph{undefined} if you assign to \verb|var1| 884The names are here for explanatory purposes only.
886or \verb|var2| inside the block. 885\item The behavior is \emph{undefined} if you assign to any
886\verb|var_i| inside the block.
887\item You can use \rwd{break} to exit a \rwd{for} loop. 887\item You can use \rwd{break} to exit a \rwd{for} loop.
888\item The loop variables \verb|var1| and \verb|var2| are 888\item The loop variables \verb|var_i| are local to the statement;
889local to the statement;
890you cannot use their values after the \rwd{for} ends. 889you cannot use their values after the \rwd{for} ends.
891If you need these values, 890If you need these values,
892then assign them to other variables before breaking or exiting the loop. 891then assign them to other variables before breaking or exiting the loop.
893\item The absence of the optional variable \verb|var2| does not
894change the meaning of the loop.
895\end{itemize} 892\end{itemize}
896 893
897If the generator is a table \verb|t|, 894If the first result of the expression list is a table \verb|t|
898then the loop works as if it has received the following generator function: 895(instead of a function),
899\begin{verbatim} 896then the loop works as if it has received \verb|next, t| as its
900 local k,v = nil 897expression list.
901 function generator ()
902 k,v = next(t, k)
903 return k,v
904 end
905\end{verbatim}
906That is, the loop iterates over the (key,value) pairs of the table. 898That is, the loop iterates over the (key,value) pairs of the table.
907 899
908 900
@@ -1341,7 +1333,7 @@ is syntactic sugar for
1341\index{visibility} 1333\index{visibility}
1342 1334
1343Lua is a lexically scoped language. 1335Lua is a lexically scoped language.
1344The scope of local variables begins at the first statement \emph{after} 1336The scope of variables begins at the first statement \emph{after}
1345their declaration and lasts until the end of the innermost block that 1337their declaration and lasts until the end of the innermost block that
1346includes the declaration. 1338includes the declaration.
1347For instance: 1339For instance:
@@ -1352,7 +1344,7 @@ For instance:
1352 print(x) --> 10 1344 print(x) --> 10
1353 x = x+1 1345 x = x+1
1354 do -- another block 1346 do -- another block
1355 local x = x+1 -- another x 1347 local x = x+1 -- another `x'
1356 print(x) --> 12 1348 print(x) --> 12
1357 end 1349 end
1358 print(x) --> 11 1350 print(x) --> 11
@@ -1390,8 +1382,6 @@ In that code,
1390each function uses a different \verb|y| variable, 1382each function uses a different \verb|y| variable,
1391while all of them share the same \verb|x|. 1383while all of them share the same \verb|x|.
1392 1384
1393
1394
1395\subsection{Error Handling} \label{error} 1385\subsection{Error Handling} \label{error}
1396 1386
1397Because Lua is an extension language, 1387Because Lua is an extension language,
@@ -1446,7 +1436,11 @@ If so, the value associated with that key (the \IndexEmph{handler})
1446controls how Lua will perform the operation. 1436controls how Lua will perform the operation.
1447 1437
1448Metatables control the operations listed next. 1438Metatables control the operations listed next.
1449Each operation is identified by its corresponding key. 1439Each operation is identified by its corresponding name.
1440The key for each operation is a string with its name prefixed by
1441two underscores;
1442for instance, the key for operation ``add'' is the
1443string \verb|"__add"|.
1450The semantics of these operations is better explained by a Lua function 1444The semantics of these operations is better explained by a Lua function
1451describing how the interpreter executes that operation. 1445describing how the interpreter executes that operation.
1452%Each function shows how a handler is called, 1446%Each function shows how a handler is called,
@@ -1483,7 +1477,7 @@ the behavior of the ``add'' operation is
1483 if o1 and o2 then -- both operands are numeric 1477 if o1 and o2 then -- both operands are numeric
1484 return o1+o2 -- '+' here is the primitive 'add' 1478 return o1+o2 -- '+' here is the primitive 'add'
1485 else -- at least one of the operands is not numeric 1479 else -- at least one of the operands is not numeric
1486 local h = getbinhandler(op1, op2, "add") 1480 local h = getbinhandler(op1, op2, "__add")
1487 if h then 1481 if h then
1488 -- call the handler with both operands 1482 -- call the handler with both operands
1489 return h(op1, op2) 1483 return h(op1, op2)
@@ -1510,7 +1504,7 @@ Behavior similar to the ``add'' operation.
1510the \verb|^| operation (exponentiation) operation. 1504the \verb|^| operation (exponentiation) operation.
1511\begin{verbatim} ?? 1505\begin{verbatim} ??
1512 function pow_op (op1, op2) 1506 function pow_op (op1, op2)
1513 local h = getbinhandler(op1, op2, "pow") 1507 local h = getbinhandler(op1, op2, "__pow")
1514 if h then 1508 if h then
1515 -- call the handler with both operands 1509 -- call the handler with both operands
1516 return h(op1, op2) 1510 return h(op1, op2)
@@ -1529,7 +1523,7 @@ the unary \verb|-| operation.
1529 return -o -- '-' here is the primitive 'unm' 1523 return -o -- '-' here is the primitive 'unm'
1530 else -- the operand is not numeric. 1524 else -- the operand is not numeric.
1531 -- Try to get a handler from the operand; 1525 -- Try to get a handler from the operand;
1532 local h = metatable(op).unm 1526 local h = metatable(op).__unm
1533 if h then 1527 if h then
1534 -- call the handler with the operand and nil 1528 -- call the handler with the operand and nil
1535 return h(op, nil) 1529 return h(op, nil)
@@ -1549,7 +1543,7 @@ the \verb|<| operation.
1549 elseif type(op1) == "string" and type(op2) == "string" then 1543 elseif type(op1) == "string" and type(op2) == "string" then
1550 return op1 < op2 -- lexicographic comparison 1544 return op1 < op2 -- lexicographic comparison
1551 else 1545 else
1552 local h = getbinhandler(op1, op2, "lt") 1546 local h = getbinhandler(op1, op2, "__lt")
1553 if h then 1547 if h then
1554 return h(op1, op2) 1548 return h(op1, op2)
1555 else 1549 else
@@ -1574,7 +1568,7 @@ the \verb|..| (concatenation) operation.
1574 (type(op2) == "string" or type(op2) == "number") then 1568 (type(op2) == "string" or type(op2) == "number") then
1575 return op1..op2 -- primitive string concatenation 1569 return op1..op2 -- primitive string concatenation
1576 else 1570 else
1577 local h = getbinhandler(op1, op2, "concat") 1571 local h = getbinhandler(op1, op2, "__concat")
1578 if h then 1572 if h then
1579 return h(op1, op2) 1573 return h(op1, op2)
1580 else 1574 else
@@ -1593,14 +1587,14 @@ See the ``gettable'' operation for its semantics.
1593called whenever Lua accesses an indexed variable. 1587called whenever Lua accesses an indexed variable.
1594\begin{verbatim} 1588\begin{verbatim}
1595 function gettable_op (table, key) 1589 function gettable_op (table, key)
1596 local h = metatable(table).gettable 1590 local h = metatable(table).__gettable
1597 if h == nil then 1591 if h == nil then
1598 if type(table) ~= "table" then 1592 if type(table) ~= "table" then
1599 error("indexed expression not a table"); 1593 error("indexed expression not a table");
1600 else 1594 else
1601 local v = rawget(table, key) 1595 local v = rawget(table, key)
1602 if v ~= nil then return v end 1596 if v ~= nil then return v end
1603 h = metatable(table).index 1597 h = metatable(table).__index
1604 if h == nil then return nil end 1598 if h == nil then return nil end
1605 end 1599 end
1606 end 1600 end
@@ -1614,7 +1608,7 @@ called whenever Lua accesses an indexed variable.
1614called when Lua assigns to an indexed variable. 1608called when Lua assigns to an indexed variable.
1615\begin{verbatim} 1609\begin{verbatim}
1616 function settable_event (table, key, value) 1610 function settable_event (table, key, value)
1617 local h = metatable(table).settable 1611 local h = metatable(table).__settable
1618 if h == nil then 1612 if h == nil then
1619 if type(table) ~= "table" then 1613 if type(table) ~= "table" then
1620 error("indexed expression not a table") 1614 error("indexed expression not a table")
@@ -1634,7 +1628,7 @@ called when Lua calls a value.
1634 if type(func) == "function" then 1628 if type(func) == "function" then
1635 return func(unpack(arg)) -- regular call 1629 return func(unpack(arg)) -- regular call
1636 else 1630 else
1637 local h = metatable(func).call 1631 local h = metatable(func).__call
1638 if h then 1632 if h then
1639 tinsert(arg, 1, func) 1633 tinsert(arg, 1, func)
1640 return h(unpack(arg)) 1634 return h(unpack(arg))
@@ -1656,7 +1650,7 @@ For each userdata to be collected,
1656Lua does the equivalent of the following function: 1650Lua does the equivalent of the following function:
1657\begin{verbatim} 1651\begin{verbatim}
1658 function gc_op (obj) 1652 function gc_op (obj)
1659 local h = metatable(obj).gc 1653 local h = metatable(obj).__gc
1660 if h then 1654 if h then
1661 h(obj) 1655 h(obj)
1662 end 1656 end
@@ -1673,7 +1667,7 @@ Second, metatables control the weakmode of tables \see{weak-table}.
1673The weakmode of a table \verb|t| is defined by a string: 1667The weakmode of a table \verb|t| is defined by a string:
1674\label{weakmode} 1668\label{weakmode}
1675\begin{verbatim} 1669\begin{verbatim}
1676 s = metatable(t).weakmode 1670 s = metatable(t).__weakmode
1677\end{verbatim} 1671\end{verbatim}
1678Valid values for this string are \verb|"k"| for weak keys, 1672Valid values for this string are \verb|"k"| for weak keys,
1679\verb|"v"| for weak values, 1673\verb|"v"| for weak values,
@@ -1713,17 +1707,9 @@ every function in the library (except \verb|lua_open| below).
1713Before calling any API function, 1707Before calling any API function,
1714you must create a state by calling 1708you must create a state by calling
1715\begin{verbatim} 1709\begin{verbatim}
1716 lua_State *lua_open (int stacksize); 1710 lua_State *lua_open (void);
1717\end{verbatim} 1711\end{verbatim}
1718\DefAPI{lua_open} 1712\DefAPI{lua_open}
1719The sole argument to this function is the stack size for the interpreter.
1720(Each function call needs one stack position for each argument, local variable,
1721and temporary value, plus one position for book-keeping.
1722The stack must also have some 20 extra positions available.
1723For very small implementations, without recursive functions,
1724a stack size of~100 should be enough.)
1725If \verb|stacksize| is zero,
1726then a default size of~1024 is used.
1727 1713
1728To release a state created with \verb|lua_open|, call 1714To release a state created with \verb|lua_open|, call
1729\begin{verbatim} 1715\begin{verbatim}
@@ -1752,7 +1738,7 @@ If you have a C~library that offers multi-threading or co-routines,
1752then Lua can cooperate with it to implement the equivalent facility in Lua. 1738then Lua can cooperate with it to implement the equivalent facility in Lua.
1753The following function creates a new ``thread'' in Lua: 1739The following function creates a new ``thread'' in Lua:
1754\begin{verbatim} 1740\begin{verbatim}
1755 lua_State *lua_newthread (lua_State *L, int stacksize); 1741 lua_State *lua_newthread (lua_State *L);
1756\end{verbatim} 1742\end{verbatim}
1757\DefAPI{lua_newthread} 1743\DefAPI{lua_newthread}
1758The new state returned by this function shares with the original state 1744The new state returned by this function shares with the original state
@@ -1811,19 +1797,22 @@ When you interact with Lua API,
1811\emph{you are responsible for controlling stack overflow}. 1797\emph{you are responsible for controlling stack overflow}.
1812The function 1798The function
1813\begin{verbatim} 1799\begin{verbatim}
1814 int lua_stackspace (lua_State *L); 1800 int lua_checkstack (lua_State *L, int size);
1815\end{verbatim} 1801\end{verbatim}
1816\DefAPI{lua_stackspace} 1802\DefAPI{lua_checkstack}
1817returns the number of stack positions still available. 1803returns true if there is at lease \verb|size|
1804stack positions still available.
1818Whenever Lua calls C, \DefAPI{LUA_MINSTACK} 1805Whenever Lua calls C, \DefAPI{LUA_MINSTACK}
1819it ensures that 1806it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true,
1807that is, that
1820at least \verb|LUA_MINSTACK| positions are still available. 1808at least \verb|LUA_MINSTACK| positions are still available.
1821\verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16, 1809\verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20,
1822so that usually you do not have to worry about stack space 1810so that usually you do not have to worry about stack space
1823unless your code has loops pushing elements onto the stack. 1811unless your code has loops pushing elements onto the stack.
1824 1812
1825Most query functions accept as indices any value inside the 1813Most query functions accept as indices any value inside the
1826available stack space. 1814available stack space, that is, indices up to the maximum stack size
1815you (or Lua) have checked through \verb|lua_checkstack|.
1827Such indices are called \emph{acceptable indices}. 1816Such indices are called \emph{acceptable indices}.
1828More formally, we define an \IndexEmph{acceptable index} 1817More formally, we define an \IndexEmph{acceptable index}
1829as follows: 1818as follows:
@@ -2178,7 +2167,7 @@ but after the call the responsibility is back to you.
2178If you need to push other elements after calling any of these functions, 2167If you need to push other elements after calling any of these functions,
2179and you want to ``play safe'', 2168and you want to ``play safe'',
2180you must either check the stack space 2169you must either check the stack space
2181with \verb|lua_stackspace| 2170with \verb|lua_checkstack|
2182or remove the returned elements 2171or remove the returned elements
2183from the stack (if you do not need them). 2172from the stack (if you do not need them).
2184For instance, the following code 2173For instance, the following code
@@ -2573,7 +2562,7 @@ information about an active function:
2573 const char *event; /* "call", "return" */ 2562 const char *event; /* "call", "return" */
2574 int currentline; /* (l) */ 2563 int currentline; /* (l) */
2575 const char *name; /* (n) */ 2564 const char *name; /* (n) */
2576 const char *namewhat; /* (n) global, tag method, local, field */ 2565 const char *namewhat; /* (n) `global', `local', `field', `method' */
2577 int nups; /* (u) number of upvalues */ 2566 int nups; /* (u) number of upvalues */
2578 int linedefined; /* (S) */ 2567 int linedefined; /* (S) */
2579 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ 2568 const char *what; /* (S) "Lua" function, "C" function, Lua "main" */
@@ -2661,11 +2650,10 @@ then \verb|name| is set to \verb|NULL|.
2661 2650
2662\item[namewhat] 2651\item[namewhat]
2663Explains the previous field. 2652Explains the previous field.
2664If the function is a global variable, 2653It can be \verb|"global"|, \verb|"local"|, \verb|"method"|,
2665\verb|namewhat| is \verb|"global"|; 2654\verb|"field"|, or \verb|""| (the empty string),
2666if the function is a tag method, 2655according to how the function was called.
2667\verb|namewhat| is \verb|"tag-method"|; 2656(Lua uses the empty string when no other option seems to apply.)
2668otherwise, it is \verb|""| (the empty string).
2669 2657
2670\item[nups] 2658\item[nups]
2671Number of upvalues of the function. 2659Number of upvalues of the function.
@@ -2974,11 +2962,6 @@ Similar to \verb|dostring|,
2974but returns the contents of a Lua chunk as a function, 2962but returns the contents of a Lua chunk as a function,
2975instead of executing it. 2963instead of executing it.
2976 2964
2977\subsubsection*{\ff \T{newtype (name)}}\DefLIB{newtype}\label{pdf-newtype}
2978Creates a new type with the given name
2979(which can be used only for table objects).
2980Returns the tag of the new type.
2981
2982\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next} 2965\subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next}
2983Allows a program to traverse all fields of a table. 2966Allows a program to traverse all fields of a table.
2984Its first argument is a table and its second argument 2967Its first argument is a table and its second argument
@@ -3027,9 +3010,45 @@ without invoking any tag method.
3027\verb|index| is any value different from \nil; 3010\verb|index| is any value different from \nil;
3028and \verb|value| is any Lua value. 3011and \verb|value| is any Lua value.
3029 3012
3030\subsubsection*{\ff \T{require (module)}}\DefLIB{require} 3013\subsubsection*{\ff \T{require (packagename)}}\DefLIB{require}
3014
3015Loads the given package.
3016The function starts by looking into the table \IndexVerb{_LOADED}
3017whether \verb|packagename| is already loaded.
3018If it is, then \verb|require| is done.
3019Otherwise, it searches a path looking for a file to load.
3020
3021If the global variable \IndexVerb{LUA_PATH} is a string,
3022this string is the path.
3023Otherwise, \verb|require| tries the environment variable \verb|LUA_PATH|.
3024In the last resort, it uses a predefined path.
3025
3026The path is a sequence of \emph{templates} separated by semicolons.
3027For each template, \verb|require| will change an eventual interrogation
3028mark in the template to \verb|packagename|,
3029and then will try to load the resulting file name.
3030So, for instance, if the path is
3031\begin{verbatim}
3032 "./?.lua;./?.lc;/usr/local/?/init.lua;/lasttry"
3033\end{verbatim}
3034a \verb|require "mod"| will try to load the files
3035\verb|./mod.lua|,
3036\verb|./mod.lc|,
3037\verb|/usr/local/mod/init.lua|,
3038and \verb|/lasttry|, in that order.
3039
3040The function stops the search as soon as it can load a file,
3041and then it runs the file.
3042If there is any error loading or running the file,
3043or if it cannot find any file in the path,
3044then \verb|require| signals an error.
3045Otherwise, it marks in table \verb|_LOADED|
3046that the package is loaded, and returns.
3047
3048While running a packaged file,
3049\verb|require| defines the global variable \IndexVerb{_REQUIREDNAME}
3050with the package name.
3031 3051
3032TO BE WRITTEN.
3033 3052
3034\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} 3053\subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort}
3035Sorts table elements in a given order, \emph{in-place}, 3054Sorts table elements in a given order, \emph{in-place},
@@ -3241,7 +3260,9 @@ stands for the value of the \M{n}-th captured substring.
3241 3260
3242If \verb|repl| is a function, then this function is called every time a 3261If \verb|repl| is a function, then this function is called every time a
3243match occurs, with all captured substrings passed as arguments, 3262match occurs, with all captured substrings passed as arguments,
3244in order (see below). 3263in order (see below);
3264if the pattern specifies no captures,
3265then the whole match is passed as a sole argument.
3245If the value returned by this function is a string, 3266If the value returned by this function is a string,
3246then it is used as the replacement string; 3267then it is used as the replacement string;
3247otherwise, the replacement string is the empty string. 3268otherwise, the replacement string is the empty string.
@@ -3273,7 +3294,7 @@ Here are some examples:
3273 --> x="Lua - 4.1" 3294 --> x="Lua - 4.1"
3274 3295
3275 local t = {} 3296 local t = {}
3276 gsub("first second word", "(%w+)", function (w) tinsert(t, w) end) 3297 gsub("first second word", "%w+", function (w) tinsert(t, w) end)
3277 --> t={"first", "second", "word"; n=3} 3298 --> t={"first", "second", "word"; n=3}
3278\end{verbatim} 3299\end{verbatim}
3279 3300
@@ -3628,14 +3649,7 @@ The available formats are
3628this is the only format that returns a number instead of a string. 3649this is the only format that returns a number instead of a string.
3629\item[``*a''] reads the whole file, starting at the current position. 3650\item[``*a''] reads the whole file, starting at the current position.
3630On end of file, it returns the empty string. 3651On end of file, it returns the empty string.
3631\item[``*u\emph{string}''] reads until the first occurence of 3652\item[``*l''] reads the next line (skipping the end of line),
3632\emph{string} in the file.
3633The string itself is read, but it is not included in the result.
3634If \verb|read| cannot finds the string,
3635it reads (and returns) the file until its end,
3636or \nil\ if the file was already at its end.
3637\item[``*l''] equivalent to \verb|"*u\n"|.
3638Reads the next line (skipping the end of line),
3639returning \nil\ on end of file. 3653returning \nil\ on end of file.
3640This is the default format. 3654This is the default format.
3641\item[\emph{number}] reads a string with up to that number of characters, 3655\item[\emph{number}] reads a string with up to that number of characters,
@@ -4033,7 +4047,7 @@ The \verb|lua_pushuserdata| function has been replaced by
4033\OrNL \rwd{break} 4047\OrNL \rwd{break}
4034\OrNL \rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp} 4048\OrNL \rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp}
4035 \rwd{do} block \rwd{end} 4049 \rwd{do} block \rwd{end}
4036\OrNL \rwd{for} \Nter{Name} \opt{\ter{,} \Nter{Name}} \rwd{in} exp 4050\OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1
4037 \rwd{do} block \rwd{end} 4051 \rwd{do} block \rwd{end}
4038\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} 4052\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
4039\OrNL \rwd{local} namelist \opt{init} 4053\OrNL \rwd{local} namelist \opt{init}