aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-08-09 16:09:20 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2000-08-09 16:09:20 -0300
commitfdd04e7a7f624dad1a1443e08193241dea935287 (patch)
treeeb06128623d4756fce45297c14ad6a4bc6ffe6b2
parentfb55c967062b1b13bac298a8f3bcb7ea0663a19c (diff)
downloadlua-fdd04e7a7f624dad1a1443e08193241dea935287.tar.gz
lua-fdd04e7a7f624dad1a1443e08193241dea935287.tar.bz2
lua-fdd04e7a7f624dad1a1443e08193241dea935287.zip
first version of manual for 4.0 beta
-rw-r--r--manual.tex725
1 files changed, 332 insertions, 393 deletions
diff --git a/manual.tex b/manual.tex
index 3d098d32..f808e3c9 100644
--- a/manual.tex
+++ b/manual.tex
@@ -1,4 +1,4 @@
1% $Id: manual.tex,v 1.38 2000/05/12 19:49:18 roberto Exp roberto $ 1% $Id: manual.tex,v 1.39 2000/05/24 13:54:49 roberto Exp roberto $
2 2
3\documentclass[11pt]{article} 3\documentclass[11pt]{article}
4\usepackage{fullpage,bnf} 4\usepackage{fullpage,bnf}
@@ -122,7 +122,7 @@ Waldemar Celes
122\tecgraf\ --- Computer Science Department --- PUC-Rio 122\tecgraf\ --- Computer Science Department --- PUC-Rio
123} 123}
124 124
125\date{{\small \tt\$Date: 2000/05/12 19:49:18 $ $}} 125\date{{\small \tt\$Date: 2000/05/24 13:54:49 $ $}}
126 126
127\maketitle 127\maketitle
128 128
@@ -211,7 +211,7 @@ thus creating customized programming languages sharing a syntactical framework.
211 211
212Lua is free-distribution software, 212Lua is free-distribution software,
213and provided as usual with no guarantees, 213and provided as usual with no guarantees,
214as stated in the copyright notice. 214as stated in its copyright notice.
215The implementation described in this manual is available 215The implementation described in this manual is available
216at the following URL's: 216at the following URL's:
217\begin{verbatim} 217\begin{verbatim}
@@ -242,8 +242,7 @@ Lua: an extensible embedded language.
242\section{Environment and Chunks} 242\section{Environment and Chunks}
243 243
244All statements in Lua are executed in a \Def{global environment}. 244All statements in Lua are executed in a \Def{global environment}.
245This environment, which keeps all global variables, 245This environment is initialized with a call from the embedding program to
246is initialized with a call from the embedding program to
247\verb|lua_newstate| and 246\verb|lua_newstate| and
248persists until a call to \verb|lua_close|, 247persists until a call to \verb|lua_close|,
249or the end of the embedding program. 248or the end of the embedding program.
@@ -260,11 +259,15 @@ Any variable is assumed to be global unless explicitly declared local
260\see{localvar}. 259\see{localvar}.
261Before the first assignment, the value of a global variable is \nil; 260Before the first assignment, the value of a global variable is \nil;
262this default can be changed \see{tag-method}. 261this default can be changed \see{tag-method}.
262A ``table of globals'' (called \emph{tog}) is used to keep all
263global names and values.
263 264
264The unit of execution of Lua is called a \Def{chunk}. 265The unit of execution of Lua is called a \Def{chunk}.
265A chunk is simply a sequence of statements: 266A chunk is simply a sequence of statements,
267which are executed sequentially.
268Each statement can be optionally followed by a semicolon:
266\begin{Produc} 269\begin{Produc}
267\produc{chunk}{\rep{stat} \opt{ret}} 270\produc{chunk}{\rep{stat} \opt{\ter{;}}}
268\end{Produc}% 271\end{Produc}%
269Statements are described in \See{stats}. 272Statements are described in \See{stats}.
270(The notation above is the usual extended BNF, 273(The notation above is the usual extended BNF,
@@ -274,7 +277,6 @@ in which
274\oneormore{\emph{a}} means one or more \emph{a}'s.) 277\oneormore{\emph{a}} means one or more \emph{a}'s.)
275 278
276A chunk may be in a file or in a string inside the host program. 279A chunk may be in a file or in a string inside the host program.
277A chunk may optionally end with a \verb|return| statement \see{return}.
278When a chunk is executed, first all its code is pre-compiled, 280When a chunk is executed, first all its code is pre-compiled,
279and then the statements are executed in sequential order. 281and then the statements are executed in sequential order.
280All modifications a chunk effects on the global environment persist 282All modifications a chunk effects on the global environment persist
@@ -405,7 +407,8 @@ The following strings denote other \Index{tokens}:
405 ( ) { } [ ] ; , . .. ... 407 ( ) { } [ ] ; , . .. ...
406\end{verbatim} 408\end{verbatim}
407 409
408\IndexEmph{Literal strings} can be delimited by matching single or double quotes, 410\IndexEmph{Literal strings}
411can be delimited by matching single or double quotes,
409and can contain the C-like escape sequences 412and can contain the C-like escape sequences
410\verb|'\a'| (bell), 413\verb|'\a'| (bell),
411\verb|'\b'| (backspace), 414\verb|'\b'| (backspace),
@@ -456,39 +459,6 @@ Examples of valid numerical constants are
456 3 3.0 3.1416 314.16e-2 0.31416E1 459 3 3.0 3.1416 314.16e-2 0.31416E1
457\end{verbatim} 460\end{verbatim}
458 461
459\subsection{The \Index{Pre-processor}} \label{pre-processor}
460
461All lines that start with a \verb|$| sign are handled by a pre-processor.
462The following directives are understood by the pre-processor:
463\begin{description}
464\item[\T{\$debug}] --- turn on debugging facilities \see{pragma}.
465\item[\T{\$nodebug}] --- turn off debugging facilities \see{pragma}.
466\item[\T{\$if \M{cond}}] --- start a conditional part.
467If \M{cond} is false, then this part is skipped by the lexical analyzer.
468\item[\T{\$ifnot \M{cond}}] --- start a conditional part.
469If \M{cond} is true, then this part is skipped by the lexical analyzer.
470\item[\T{\$end}] --- end a conditional part.
471\item[\T{\$else}] --- start an ``else'' conditional part,
472flipping the ``skip'' status.
473\item[\T{\$endinput}] --- end the lexical parse of the chunk.
474For all purposes,
475it is as if the chunk physically ended at this point.
476\end{description}
477
478Directives may be freely nested.
479In particular, a \verb|$endinput| may occur inside a \verb|$if|;
480in that case, even the matching \verb|$end| is not parsed.
481
482A \M{cond} part may be
483\begin{description}
484\item[\T{nil}] --- always false.
485\item[\T{1}] --- always true.
486\item[\T{\M{name}}] --- true if the value of the
487global variable \M{name} is different from \nil.
488Note that \M{name} is evaluated \emph{before} the chunk starts its execution.
489Therefore, actions in a chunk do not affect its own conditional directives.
490\end{description}
491
492\subsection{\Index{Coercion}} \label{coercion} 462\subsection{\Index{Coercion}} \label{coercion}
493 463
494Lua provides some automatic conversions between values at run time. 464Lua provides some automatic conversions between values at run time.
@@ -501,7 +471,7 @@ a conversion from number to string then back to number
501reproduces the original number \emph{exactly}. 471reproduces the original number \emph{exactly}.
502Thus, 472Thus,
503the conversion does not necessarily produces nice-looking text for some numbers. 473the conversion does not necessarily produces nice-looking text for some numbers.
504For complete control on how numbers are converted to strings, 474For complete control of how numbers are converted to strings,
505use the \verb|format| function \see{format}. 475use the \verb|format| function \see{format}.
506 476
507 477
@@ -533,18 +503,11 @@ Non-conventional commands include table constructors
533and local variable declarations \see{localvar}. 503and local variable declarations \see{localvar}.
534 504
535\subsubsection{Blocks} 505\subsubsection{Blocks}
536A \Index{block} is a list of statements, which are executed sequentially. 506A \Index{block} is a list of statements;
537A statement may be have an optional \Index{label}, 507syntatically, this is equal to a chunk:
538which is syntactically an identifier,
539and can be optionally followed by a semicolon:
540\begin{Produc} 508\begin{Produc}
541\produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}} 509\produc{block}{chunk}
542\produc{label}{\ter{$\vert$} name \ter{$\vert$}}
543\end{Produc}% 510\end{Produc}%
544\NOTE
545For syntactic reasons, the \rwd{return} and
546\rwd{break} statements can only be written
547as the last statement of a block.
548 511
549A block may be explicitly delimited: 512A block may be explicitly delimited:
550\begin{Produc} 513\begin{Produc}
@@ -552,7 +515,7 @@ A block may be explicitly delimited:
552\end{Produc}% 515\end{Produc}%
553This is useful to control the scope of local variables \see{localvar}, 516This is useful to control the scope of local variables \see{localvar},
554and to add a \rwd{return} or \rwd{break} statement in the middle 517and to add a \rwd{return} or \rwd{break} statement in the middle
555of another block: 518of another block; for instance,
556\begin{verbatim} 519\begin{verbatim}
557 do return end -- return is the last statement in this block 520 do return end -- return is the last statement in this block
558\end{verbatim} 521\end{verbatim}
@@ -593,16 +556,17 @@ or a formal parameter:
593\end{Produc}% 556\end{Produc}%
594Square brackets are used to index a table: 557Square brackets are used to index a table:
595\begin{Produc} 558\begin{Produc}
596\produc{var}{simpleexp \ter{[} exp1 \ter{]}} 559\produc{var}{varorfunc \ter{[} exp1 \ter{]}}
560\produc{varorfunc}{var \Or functioncall}
597\end{Produc}% 561\end{Produc}%
598The \M{simpleexp} should result in a table value, 562The \M{varorfunc} should result in a table value,
599from where the field indexed by the expression \M{exp1} 563from where the field indexed by the expression \M{exp1}
600value gets the assigned value. 564value gets the assigned value.
601 565
602The syntax \verb|var.NAME| is just syntactic sugar for 566The syntax \verb|var.NAME| is just syntactic sugar for
603\verb|var["NAME"]|: 567\verb|var["NAME"]|:
604\begin{Produc} 568\begin{Produc}
605\produc{var}{simpleexp \ter{.} name} 569\produc{var}{varorfunc \ter{.} name}
606\end{Produc}% 570\end{Produc}%
607 571
608The meaning of assignments and evaluations of global variables and 572The meaning of assignments and evaluations of global variables and
@@ -633,7 +597,8 @@ All values different from \nil\ are considered true;
633only \nil\ is considered false. 597only \nil\ is considered false.
634 598
635\index{return} 599\index{return}
636The \rwd{return} statement is used to return values from a function or from a chunk. 600The \rwd{return} statement is used to return values
601from a function or from a chunk.
637\label{return} 602\label{return}
638Because functions or chunks may return more than one value, 603Because functions or chunks may return more than one value,
639the syntax for a \Index{return statement} is 604the syntax for a \Index{return statement} is
@@ -642,24 +607,24 @@ the syntax for a \Index{return statement} is
642\end{Produc}% 607\end{Produc}%
643 608
644\index{break} 609\index{break}
645The \rwd{break} statement can be used to terminate the execution of a block, 610The \rwd{break} statement can be used to terminate the execution of a loop,
646skipping to the next statement after the block: 611skipping to the next statement after the loop:
647\begin{Produc} 612\begin{Produc}
648\produc{stat}{\rwd{break} \opt{name}} 613\produc{stat}{\rwd{break}}
649\end{Produc}% 614\end{Produc}%
650A \rwd{break} without a label ends the innermost enclosing loop 615A \rwd{break} ends the innermost enclosing loop
651(while, repeat, or for). 616(while, repeat, or for).
652A \rwd{break} with a label breaks the innermost enclosing
653statement with that label.
654Thus,
655labels do not have to be unique.
656 617
618\NOTE
657For syntactic reasons, \rwd{return} and \rwd{break} 619For syntactic reasons, \rwd{return} and \rwd{break}
658statements can only be written as the last statement of a block. 620statements can only be written as the last statements of a block.
659 621
660\subsubsection{For Statement} \label{for}\index{for} 622\subsubsection{For Statement} \label{for}\index{for}
661 623
662The \rwd{for} statement has the following syntax: 624The \rwd{for} statement has two forms,
625one for numbers and one for tables.
626
627The numerical \rwd{for} loop has the following syntax:
663\begin{Produc} 628\begin{Produc}
664\produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} 629\produc{stat}{\rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
665 \rwd{do} block \rwd{end}} 630 \rwd{do} block \rwd{end}}
@@ -692,9 +657,52 @@ before the loop starts.
692you cannot use its value after the \rwd{for} ends. 657you cannot use its value after the \rwd{for} ends.
693\item You can use \rwd{break} to exit a \rwd{for}. 658\item You can use \rwd{break} to exit a \rwd{for}.
694If you need the value of the index, 659If you need the value of the index,
695then assign it to another variable before breaking. 660assign it to another variable before breaking.
696\end{itemize} 661\end{itemize}
697 662
663The table \rwd{for} statement traverses all pairs
664index--value of a given table.
665It has the following syntax:
666\begin{Produc}
667\produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp
668 \rwd{do} block \rwd{end}}
669\end{Produc}%
670A \rwd{for} statement like
671\begin{verbatim}
672 for index, value in exp do block end
673\end{verbatim}
674is equivalent to the following code:
675\begin{verbatim}
676 do
677 local _t = exp
678 local index, value = next(t, nil)
679 while index do
680 block
681 index, value = next(t, index)
682 end
683 end
684\end{verbatim}
685Notice the following:
686\begin{itemize}\itemsep=0pt
687\item \verb|_t| is an invisible variable.
688The name is here for explanatory purposes only.
689\item The behavior is undefined if you assign to \verb|index| inside
690the block.
691\item The behavior is undefined if you create
692new indices in table \verb|_t| during the traversal.
693However, it is safe to change the values associated with present indices.
694\item The variables \verb|index| and \verb|value| are local to the statement;
695you cannot use their values after the \rwd{for} ends.
696\item You can use \rwd{break} to exit a \rwd{for}.
697If you need the value of \verb|index| or \verb|value|,
698assign them to other variables before breaking.
699\item The order that table elements are traversed is completely undefined,
700\emph{even for numerical indices}.
701If you want to traverse indices in numerical order,
702use a numerical \rwd{for}.
703\end{itemize}
704
705
698\subsubsection{Function Calls as Statements} \label{funcstat} 706\subsubsection{Function Calls as Statements} \label{funcstat}
699Because of possible side-effects, 707Because of possible side-effects,
700function calls can be executed as statements: 708function calls can be executed as statements:
@@ -734,13 +742,10 @@ The basic expressions in Lua are
734\produc{exp}{number} 742\produc{exp}{number}
735\produc{exp}{literal} 743\produc{exp}{literal}
736\produc{exp}{function} 744\produc{exp}{function}
737\produc{exp}{simpleexp} 745\produc{exp}{var}
738\end{Produc}% 746\produc{exp}{upvalue}
739\begin{Produc} 747\produc{exp}{functioncall}
740\produc{simpleexp}{var} 748\produc{exp}{tableconstructor}
741\produc{simpleexp}{upvalue}
742\produc{simpleexp}{functioncall}
743\produc{simpleexp}{tableconstructor}
744\end{Produc}% 749\end{Produc}%
745 750
746Numbers (numerical constants) and 751Numbers (numerical constants) and
@@ -931,7 +936,7 @@ in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
931 936
932Both forms may have an optional trailing comma, 937Both forms may have an optional trailing comma,
933and can be used in the same constructor separated by 938and can be used in the same constructor separated by
934a semi-collon. 939a semi-colon.
935For example, all forms below are correct. 940For example, all forms below are correct.
936\begin{verbatim} 941\begin{verbatim}
937 x = {;} 942 x = {;}
@@ -943,27 +948,27 @@ For example, all forms below are correct.
943\subsubsection{Function Calls} \label{functioncall} 948\subsubsection{Function Calls} \label{functioncall}
944A \Index{function call} has the following syntax: 949A \Index{function call} has the following syntax:
945\begin{Produc} 950\begin{Produc}
946\produc{functioncall}{simpleexp args} 951\produc{functioncall}{varorfunc args}
947\end{Produc}% 952\end{Produc}%
948First, \M{simpleexp} is evaluated. 953First, \M{varorfunc} is evaluated.
949If its value has type \emph{function}, 954If its value has type \emph{function},
950then this function is called, 955then this function is called,
951with the given arguments. 956with the given arguments.
952Otherwise, the ``function'' tag method is called, 957Otherwise, the ``function'' tag method is called,
953having as first parameter the value of \M{simpleexp}, 958having as first parameter the value of \M{varorfunc},
954and then the original call arguments. 959and then the original call arguments.
955 960
956The form 961The form
957\begin{Produc} 962\begin{Produc}
958\produc{functioncall}{simpleexp \ter{:} name args} 963\produc{functioncall}{varorfunc \ter{:} name args}
959\end{Produc}% 964\end{Produc}%
960can be used to call ``methods''. 965can be used to call ``methods''.
961A call \verb|simpleexp:name(...)| 966A call \verb|varorfunc:name(...)|
962is syntactic sugar for 967is syntactic sugar for
963\begin{verbatim} 968\begin{verbatim}
964 simpleexp.name(simpleexp, ...) 969 varorfunc.name(varorfunc, ...)
965\end{verbatim} 970\end{verbatim}
966except that \verb|simpleexp| is evaluated only once. 971except that \verb|varorfunc| is evaluated only once.
967 972
968Arguments have the following syntax: 973Arguments have the following syntax:
969\begin{Produc} 974\begin{Produc}
@@ -983,7 +988,7 @@ the parameter list is a single literal string.
983 988
984Because a function can return any number of results 989Because a function can return any number of results
985\see{return}, 990\see{return},
986the number of results must be adjusted before used. 991the number of results must be adjusted before they are used.
987If the function is called as a statement \see{funcstat}, 992If the function is called as a statement \see{funcstat},
988then its return list is adjusted to~0, 993then its return list is adjusted to~0,
989thus discarding all returned values. 994thus discarding all returned values.
@@ -999,7 +1004,7 @@ is the last (or the only) expression in an assignment,
999in an argument list, or in a return statement. 1004in an argument list, or in a return statement.
1000Here are some examples. 1005Here are some examples.
1001\begin{verbatim} 1006\begin{verbatim}
1002 f(); -- adjusted to 0 1007 f(); -- adjusted to 0 results
1003 g(f(), x); -- f() is adjusted to 1 result 1008 g(f(), x); -- f() is adjusted to 1 result
1004 g(x, f()); -- g gets x plus all values returned by f() 1009 g(x, f()); -- g gets x plus all values returned by f()
1005 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) 1010 a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil)
@@ -1098,7 +1103,7 @@ Then, we have the following mapping from arguments to parameters:
1098 g(5, r()) a=5, b=1, arg={2, 3; n=2} 1103 g(5, r()) a=5, b=1, arg={2, 3; n=2}
1099\end{verbatim} 1104\end{verbatim}
1100 1105
1101Results are returned using the \verb|return| statement \see{return}. 1106Results are returned using the \rwd{return} statement \see{return}.
1102If control reaches the end of a function 1107If control reaches the end of a function
1103without encountering a \rwd{return} statement, 1108without encountering a \rwd{return} statement,
1104then the function returns with no results. 1109then the function returns with no results.
@@ -1149,19 +1154,25 @@ The name used in an upvalue may be the name of any variable visible
1149at the point where the function is defined, 1154at the point where the function is defined,
1150that is 1155that is
1151global variables and local variables from the immediately enclosing function. 1156global variables and local variables from the immediately enclosing function.
1157Notice that when the upvalue is a table,
1158only the reference to that table
1159(which is the value of the upvalue) is frozen;
1160the table contents can be changed at will.
1152 1161
1153Here are some examples: 1162Here are some examples:
1154\begin{verbatim} 1163\begin{verbatim}
1155 a,b,c = 1,2,3 -- global variables 1164 a,b,c = 1,2,3 -- global variables
1156 local d 1165 local d
1157 function f (x) 1166 function f (x)
1158 local b -- x and b are local to f; b shadows the global b 1167 local b = {} -- x and b are local to f; b shadows the global b
1159 local g = function (a) 1168 local g = function (a)
1160 local y -- a and y are local to g 1169 local y -- a and y are local to g
1161 p = a -- OK, access local 'a' 1170 p = a -- OK, access local 'a'
1162 p = c -- OK, access global 'c' 1171 p = c -- OK, access global 'c'
1163 p = b -- ERROR: cannot access a variable in outer scope 1172 p = b -- ERROR: cannot access a variable in outer scope
1164 p = %b -- OK, access frozen value of 'b' (local to 'f') 1173 p = %b -- OK, access frozen value of 'b' (local to 'f')
1174 %b = 3 -- ERROR: cannot change an upvalue
1175 %b.x = 3 -- OK, change the table contents
1165 p = %c -- OK, access frozen value of global 'c' 1176 p = %c -- OK, access frozen value of global 'c'
1166 p = %y -- ERROR: 'y' is not visible where 'g' is defined 1177 p = %y -- ERROR: 'y' is not visible where 'g' is defined
1167 p = %d -- ERROR: 'd' is not visible where 'g' is defined 1178 p = %d -- ERROR: 'd' is not visible where 'g' is defined
@@ -1183,6 +1194,14 @@ and then the corresponding function from the library
1183\verb|lua_dobuffer|, or \verb|lua_callfunction|) 1194\verb|lua_dobuffer|, or \verb|lua_callfunction|)
1184is terminated, returning an error condition. 1195is terminated, returning an error condition.
1185 1196
1197Memory allocation error is an exception to the previous rule.
1198When a \verb|malloc| fails, Lua may not be able to execute the
1199\verb|_ERRORMESSAGE| function.
1200So, for this kind of error, Lua does not call
1201the \verb|_ERRORMESSAGE| function;
1202instead, the corresponding function from the library
1203returns immeditely with a special error code.
1204
1186The only argument to \verb|_ERRORMESSAGE| is a string 1205The only argument to \verb|_ERRORMESSAGE| is a string
1187describing the error. 1206describing the error.
1188The default definition for 1207The default definition for
@@ -1193,15 +1212,6 @@ and uses the debug facilities \see{debugI}
1193to print some extra information, 1212to print some extra information,
1194such as a call stack traceback. 1213such as a call stack traceback.
1195 1214
1196To provide more information about errors,
1197Lua programs should include the compilation pragma \verb|$debug|,
1198\index{debug pragma}\label{pragma}
1199or be loaded from the host after calling \verb|lua_setdebug(1)|
1200\see{debugI}.
1201When an error occurs in a chunk compiled with this option,
1202the I/O error-message routine is able to print the number of the
1203lines where the calls (and the error) were made.
1204
1205Lua code can explicitly generate an error by calling the built-in 1215Lua code can explicitly generate an error by calling the built-in
1206function \verb|error| \see{pdf-error}. 1216function \verb|error| \see{pdf-error}.
1207Lua code can ``catch'' an error using the built-in function 1217Lua code can ``catch'' an error using the built-in function
@@ -1241,13 +1251,13 @@ The code shown here is only \emph{illustrative};
1241the real behavior is hard coded in the interpreter, 1251the real behavior is hard coded in the interpreter,
1242and it is much more efficient than this simulation. 1252and it is much more efficient than this simulation.
1243All functions used in these descriptions 1253All functions used in these descriptions
1244(\verb|rawgetglobal|, \verb|tonumber|, \verb|call|, etc.) 1254(\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)
1245are described in \See{predefined}. 1255are described in \See{predefined}.
1246 1256
1247\begin{description} 1257\begin{description}
1248 1258
1249\item[``add'':]\index{add event} 1259\item[``add'':]\index{add event}
1250called when a \verb|+| operation is applied to non numerical operands. 1260called when a \verb|+| operation is applied to non-numerical operands.
1251 1261
1252The function \verb|getbinmethod| defines how Lua chooses a tag method 1262The function \verb|getbinmethod| defines how Lua chooses a tag method
1253for a binary operation. 1263for a binary operation.
@@ -1282,16 +1292,19 @@ the tag method for the ``add' event is
1282 end 1292 end
1283\end{verbatim} 1293\end{verbatim}
1284 1294
1295All global variables are kept in a table.
1296You can get this table calling the \verb|globals| function.
1297
1285\item[``sub'':]\index{sub event} 1298\item[``sub'':]\index{sub event}
1286called when a \verb|-| operation is applied to non numerical operands. 1299called when a \verb|-| operation is applied to non-numerical operands.
1287Behavior similar to the ``add'' event. 1300Behavior similar to the ``add'' event.
1288 1301
1289\item[``mul'':]\index{mul event} 1302\item[``mul'':]\index{mul event}
1290called when a \verb|*| operation is applied to non numerical operands. 1303called when a \verb|*| operation is applied to non-numerical operands.
1291Behavior similar to the ``add'' event. 1304Behavior similar to the ``add'' event.
1292 1305
1293\item[``div'':]\index{div event} 1306\item[``div'':]\index{div event}
1294called when a \verb|/| operation is applied to non numerical operands. 1307called when a \verb|/| operation is applied to non-numerical operands.
1295Behavior similar to the ``add'' event. 1308Behavior similar to the ``add'' event.
1296 1309
1297\item[``pow'':]\index{pow event} 1310\item[``pow'':]\index{pow event}
@@ -1310,7 +1323,7 @@ called when a \verb|^| operation (exponentiation) is applied.
1310\end{verbatim} 1323\end{verbatim}
1311 1324
1312\item[``unm'':]\index{unm event} 1325\item[``unm'':]\index{unm event}
1313called when a unary \verb|-| operation is applied to a non numerical operand. 1326called when a unary \verb|-| operation is applied to a non-numerical operand.
1314\begin{verbatim} 1327\begin{verbatim}
1315 function unm_event (op) 1328 function unm_event (op)
1316 local o = tonumber(op) 1329 local o = tonumber(op)
@@ -1361,7 +1374,7 @@ usual equivalences:
1361\end{verbatim} 1374\end{verbatim}
1362 1375
1363\item[``concat'':]\index{concatenation event} 1376\item[``concat'':]\index{concatenation event}
1364called when a concatenation is applied to non string operands. 1377called when a concatenation is applied to non-string operands.
1365\begin{verbatim} 1378\begin{verbatim}
1366 function concat_event (op1, op2) 1379 function concat_event (op1, op2)
1367 if (type(op1) == "string" or type(op1) == "number") and 1380 if (type(op1) == "string" or type(op1) == "number") and
@@ -1391,7 +1404,8 @@ Note that
1391the tag is that of the \emph{current value} of the global variable. 1404the tag is that of the \emph{current value} of the global variable.
1392\begin{verbatim} 1405\begin{verbatim}
1393 function getglobal (varname) 1406 function getglobal (varname)
1394 local value = rawgetglobal(varname) 1407 -- access the table of globals
1408 local value = rawget(globals(), varname)
1395 local tm = gettagmethod(tag(value), "getglobal") 1409 local tm = gettagmethod(tag(value), "getglobal")
1396 if not tm then 1410 if not tm then
1397 return value 1411 return value
@@ -1408,10 +1422,10 @@ This method cannot be set for numbers, strings, and tables and
1408userdata with default tags. 1422userdata with default tags.
1409\begin{verbatim} 1423\begin{verbatim}
1410 function setglobal (varname, newvalue) 1424 function setglobal (varname, newvalue)
1411 local oldvalue = rawgetglobal(varname) 1425 local oldvalue = rawget(globals(), varname)
1412 local tm = gettagmethod(tag(oldvalue), "setglobal") 1426 local tm = gettagmethod(tag(oldvalue), "setglobal")
1413 if not tm then 1427 if not tm then
1414 rawsetglobal(varname, newvalue) 1428 rawset(globals(), varname, newvalue)
1415 else 1429 else
1416 tm(varname, oldvalue, newvalue) 1430 tm(varname, oldvalue, newvalue)
1417 end 1431 end
@@ -1430,7 +1444,7 @@ This method cannot be set for tables with default tag.
1430 elseif type(table) ~= "table" then 1444 elseif type(table) ~= "table" then
1431 error("indexed expression not a table"); 1445 error("indexed expression not a table");
1432 else 1446 else
1433 local v = rawgettable(table, index) 1447 local v = rawget(table, index)
1434 tm = gettagmethod(tag(table), "index") 1448 tm = gettagmethod(tag(table), "index")
1435 if v == nil and tm then 1449 if v == nil and tm then
1436 return tm(table, index) 1450 return tm(table, index)
@@ -1452,13 +1466,13 @@ This method cannot be set for tables with default tag.
1452 elseif type(table) ~= "table" then 1466 elseif type(table) ~= "table" then
1453 error("indexed expression not a table") 1467 error("indexed expression not a table")
1454 else 1468 else
1455 rawsettable(table, index, value) 1469 rawset(table, index, value)
1456 end 1470 end
1457 end 1471 end
1458\end{verbatim} 1472\end{verbatim}
1459 1473
1460\item[``function'':]\index{function event} 1474\item[``function'':]\index{function event}
1461called when Lua tries to call a non function value. 1475called when Lua tries to call a non-function value.
1462\begin{verbatim} 1476\begin{verbatim}
1463 function function_event (func, ...) 1477 function function_event (func, ...)
1464 if type(func) == "function" then 1478 if type(func) == "function" then
@@ -1540,36 +1554,32 @@ Before calling any API function,
1540you must create a state. 1554you must create a state.
1541This is done by calling\Deffunc{lua_newstate} 1555This is done by calling\Deffunc{lua_newstate}
1542\begin{verbatim} 1556\begin{verbatim}
1543lua_State *lua_newstate (const char *s, ...); 1557lua_State *lua_newstate (int stacksize, int builtin);
1544\end{verbatim} 1558\end{verbatim}
1545The arguments to this function form a list of name-value options, 1559The arguments to this function are
1546terminated with \verb|NULL|. 1560the stack size for the interpreter and a boolean that
1547Currently, the function accepts the following options: 1561indicates whether the predefined functions should be loaded or not.
1548\begin{itemize}
1549\item \verb|"stack"| --- the stack size.
1550Each function call needs one stack position for each local variable 1562Each function call needs one stack position for each local variable
1551and temporary variables, plus one position for book-keeping. 1563and temporary variables, plus one position for book-keeping.
1552The stack must also have at least ten extra positions available. 1564The stack must also have at least ten extra positions available.
1553For very small implementations, without recursive functions, 1565For very small implementations, without recursive functions,
1554a stack size of 100 should be enough. 1566a stack size of 100 should be enough.
1555The default stack size is 1024. 1567A value 0 for \verb|stacksize| uses a default size of 1024 positions.
1556
1557\item \verb|"builtin"| --- the value is a boolean (0 or 1) that
1558indicates whether the predefined functions should be loaded or not.
1559The default is to load those functions.
1560\end{itemize}
1561For instance, the call 1568For instance, the call
1562\begin{verbatim} 1569\begin{verbatim}
1563lua_State *L = lua_newstate(NULL); 1570lua_State *L = lua_newstate(0, 1);
1564\end{verbatim} 1571\end{verbatim}
1565creates a new state with a stack of 1024 positions 1572creates a new state with a stack of 1024 positions
1566and with the predefined functions loaded; 1573and with the predefined functions loaded;
1567the call 1574the call
1568\begin{verbatim} 1575\begin{verbatim}
1569lua_State *L = lua_newstate("builtin", 0, "stack", 100, NULL); 1576lua_State *L = lua_newstate(100, 0)
1570\end{verbatim} 1577\end{verbatim}
1571creates a new state with a stack of 100 positions, 1578creates a new state with a stack of 100 positions,
1572without the predefined functions. 1579without the predefined functions.
1580When you create a state without the builtin function,
1581you must provide by yourself any function that your interpreter may need
1582(such as \verb|_ALERT| and \verb|_ERRORMESSAGE| for error report, etc.).
1573 1583
1574To release a state, you call 1584To release a state, you call
1575\begin{verbatim} 1585\begin{verbatim}
@@ -1578,7 +1588,7 @@ void lua_close (lua_State *L);
1578This function destroys all objects in the current Lua environment 1588This function destroys all objects in the current Lua environment
1579(calling the corresponding garbage collection tag methods) 1589(calling the corresponding garbage collection tag methods)
1580and frees all dynamic memory used by the state. 1590and frees all dynamic memory used by the state.
1581Usually, you do not need to call this function, 1591Frequently, you do not need to call this function,
1582because all resources are naturally released when the program ends. 1592because all resources are naturally released when the program ends.
1583On the other hand, 1593On the other hand,
1584long-running programs --- 1594long-running programs ---
@@ -1588,6 +1598,8 @@ to avoid growing too big.
1588 1598
1589With the exception of \verb|lua_newstate|, 1599With the exception of \verb|lua_newstate|,
1590all functions in the API need a state as their first argument. 1600all functions in the API need a state as their first argument.
1601
1602>>>>>>>>>>>>
1591However, most applications use a single state. 1603However, most applications use a single state.
1592To avoid the burden of passing this only state explicitly to all 1604To avoid the burden of passing this only state explicitly to all
1593functions, and also to keep compatibility with old versions of Lua, 1605functions, and also to keep compatibility with old versions of Lua,
@@ -1615,11 +1627,11 @@ again as a macro.)
1615The only exception is \verb|lua_newstate|; 1627The only exception is \verb|lua_newstate|;
1616in this case, the corresponding macro is 1628in this case, the corresponding macro is
1617\begin{verbatim} 1629\begin{verbatim}
1618#define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0)))) 1630#define lua_open() ((void)(lua_state?0:(lua_state=lua_newstate(0, 1))))
1619\end{verbatim} 1631\end{verbatim}
1620This code checks whether the global state has been initialized; 1632This code checks whether the global state has been initialized;
1621if not, it creates a new state with default settings and 1633if not, it creates a new state with default settings and
1622assigns it to \verb|lua_newstate|. 1634assigns it to \verb|lua_state|.
1623 1635
1624By default, the single-state macros are all active. 1636By default, the single-state macros are all active.
1625If you need to use multiple states, 1637If you need to use multiple states,
@@ -1630,11 +1642,7 @@ including \verb|lua.h| in your code:
1630#define LUA_REENTRANT 1642#define LUA_REENTRANT
1631#include "lua.h" 1643#include "lua.h"
1632\end{verbatim} 1644\end{verbatim}
1633 1645<<<<<<<<<
1634In the sequel, we will show all functions in the single-state form
1635(therefore, they are actually macros).
1636When you define \verb|LUA_REENTRANT|,
1637all of them get a state as the first parameter.
1638 1646
1639 1647
1640\subsection{Exchanging Values between C and Lua} \label{valuesCLua} 1648\subsection{Exchanging Values between C and Lua} \label{valuesCLua}
@@ -1644,11 +1652,11 @@ all values passed between Lua and C have type
1644which works like an abstract type in C that can hold any Lua value. 1652which works like an abstract type in C that can hold any Lua value.
1645Values of type \verb|lua_Object| have no meaning outside Lua; 1653Values of type \verb|lua_Object| have no meaning outside Lua;
1646for instance, 1654for instance,
1647you cannot compare two \verb|lua_Object's| directly. 1655you cannot compare two \verb|lua_Object|s directly.
1648Instead, you should use the following function: 1656Instead, you should use the following function:
1649\Deffunc{lua_equal} 1657\Deffunc{lua_equal}
1650\begin{verbatim} 1658\begin{verbatim}
1651int lua_equal (lua_Object o1, lua_Object o2); 1659int lua_equal (lua_State *L, lua_Object o1, lua_Object o2);
1652\end{verbatim} 1660\end{verbatim}
1653 1661
1654To check the type of a \verb|lua_Object|, 1662To check the type of a \verb|lua_Object|,
@@ -1658,14 +1666,14 @@ the following functions are available:
1658\Deffunc{lua_isfunction} 1666\Deffunc{lua_isfunction}
1659\Deffunc{lua_type} 1667\Deffunc{lua_type}
1660\begin{verbatim} 1668\begin{verbatim}
1661int lua_isnil (lua_Object object); 1669int lua_isnil (lua_State *L, lua_Object object);
1662int lua_isnumber (lua_Object object); 1670int lua_isnumber (lua_State *L, lua_Object object);
1663int lua_isstring (lua_Object object); 1671int lua_isstring (lua_State *L, lua_Object object);
1664int lua_istable (lua_Object object); 1672int lua_istable (lua_State *L, lua_Object object);
1665int lua_isfunction (lua_Object object); 1673int lua_isfunction (lua_State *L, lua_Object object);
1666int lua_iscfunction (lua_Object object); 1674int lua_iscfunction (lua_State *L, lua_Object object);
1667int lua_isuserdata (lua_Object object); 1675int lua_isuserdata (lua_State *L, lua_Object object);
1668const char *lua_type (lua_Object object); 1676const char *lua_type (lua_State *L, lua_Object object);
1669\end{verbatim} 1677\end{verbatim}
1670The \verb|lua_is*| functions return 1 if the object is compatible 1678The \verb|lua_is*| functions return 1 if the object is compatible
1671with the given type, and 0 otherwise. 1679with the given type, and 0 otherwise.
@@ -1685,7 +1693,7 @@ To get the tag of a \verb|lua_Object|,
1685use the following function: 1693use the following function:
1686\Deffunc{lua_tag} 1694\Deffunc{lua_tag}
1687\begin{verbatim} 1695\begin{verbatim}
1688int lua_tag (lua_Object object); 1696int lua_tag (lua_State *L, lua_Object object);
1689\end{verbatim} 1697\end{verbatim}
1690 1698
1691To translate a value from type \verb|lua_Object| to a specific C type, 1699To translate a value from type \verb|lua_Object| to a specific C type,
@@ -1693,11 +1701,11 @@ you can use the following conversion functions:
1693\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} 1701\Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen}
1694\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} 1702\Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata}
1695\begin{verbatim} 1703\begin{verbatim}
1696double lua_getnumber (lua_Object object); 1704double lua_getnumber (lua_State *L, lua_Object object);
1697const char *lua_getstring (lua_Object object); 1705const char *lua_getstring (lua_State *L, lua_Object object);
1698size_t lua_strlen (lua_Object object); 1706size_t lua_strlen (lua_State *L, lua_Object object);
1699lua_CFunction lua_getcfunction (lua_Object object); 1707lua_CFunction lua_getcfunction (lua_State *L, lua_Object object);
1700void *lua_getuserdata (lua_Object object); 1708void *lua_getuserdata (lua_State *L, lua_Object object);
1701\end{verbatim} 1709\end{verbatim}
1702 1710
1703\verb|lua_getnumber| converts a \verb|lua_Object| to a floating-point number. 1711\verb|lua_getnumber| converts a \verb|lua_Object| to a floating-point number.
@@ -1713,15 +1721,11 @@ but returns a pointer to a string inside the Lua environment.
1713Those strings always have a 0 after their last character (like in C), 1721Those strings always have a 0 after their last character (like in C),
1714but may contain other zeros in their body. 1722but may contain other zeros in their body.
1715If you do not know whether a string may contain zeros, 1723If you do not know whether a string may contain zeros,
1716you can use \verb|lua_strlen| to get the actual length. 1724you should use \verb|lua_strlen| to get the actual length.
1717Because Lua has garbage collection, 1725Because Lua has garbage collection,
1718there is no guarantee that the pointer returned by \verb|lua_getstring| 1726there is no guarantee that the pointer returned by \verb|lua_getstring|
1719will be valid after the block ends 1727will be valid after the block ends
1720\see{GC}. 1728\see{GC}.
1721So,
1722if you need the string later on,
1723you should duplicate it with something like
1724\verb|memcpy(malloc(lua_strlen(o),lua_getstring(o)))|.
1725 1729
1726\verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function. 1730\verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function.
1727This \verb|lua_Object| must be a C~function; 1731This \verb|lua_Object| must be a C~function;
@@ -1746,7 +1750,7 @@ The structure lua2C is an \emph{abstract array}
1746that can be indexed with the function: 1750that can be indexed with the function:
1747\Deffunc{lua_lua2C} 1751\Deffunc{lua_lua2C}
1748\begin{verbatim} 1752\begin{verbatim}
1749lua_Object lua_lua2C (int number); 1753lua_Object lua_lua2C (lua_State *L, int number);
1750\end{verbatim} 1754\end{verbatim}
1751where \verb|number| starts with 1. 1755where \verb|number| starts with 1.
1752When called with a number larger than the array size, 1756When called with a number larger than the array size,
@@ -1764,13 +1768,13 @@ is done with the following functions:
1764\Deffunc{lua_pushnil}\Deffunc{lua_pushobject} 1768\Deffunc{lua_pushnil}\Deffunc{lua_pushobject}
1765\Deffunc{lua_pushuserdata}\label{pushing} 1769\Deffunc{lua_pushuserdata}\label{pushing}
1766\begin{verbatim} 1770\begin{verbatim}
1767void lua_pushnumber (double n); 1771void lua_pushnumber (lua_State *L, double n);
1768void lua_pushlstring (const char *s, size_t len); 1772void lua_pushlstring (lua_State *L, const char *s, size_t len);
1769void lua_pushstring (const char *s); 1773void lua_pushstring (lua_State *L, const char *s);
1770void lua_pushusertag (void *u, int tag); 1774void lua_pushusertag (lua_State *L, void *u, int tag);
1771void lua_pushnil (void); 1775void lua_pushnil (lua_State *L);
1772void lua_pushobject (lua_Object object); 1776void lua_pushobject (lua_State *L, lua_Object object);
1773void lua_pushcfunction (lua_CFunction f); /* macro */ 1777void lua_pushcfunction (lua_State *L, lua_CFunction f); /* macro */
1774\end{verbatim} 1778\end{verbatim}
1775All of them receive a C value, 1779All of them receive a C value,
1776convert it to a corresponding \verb|lua_Object|, 1780convert it to a corresponding \verb|lua_Object|,
@@ -1783,27 +1787,23 @@ otherwise you should use the more general \verb|lua_pushlstring|.
1783The function 1787The function
1784\Deffunc{lua_pop} 1788\Deffunc{lua_pop}
1785\begin{verbatim} 1789\begin{verbatim}
1786lua_Object lua_pop (void); 1790lua_Object lua_pop (lua_State *L);
1787\end{verbatim} 1791\end{verbatim}
1788returns a reference to the object at the top of the C2lua stack, 1792returns a reference to the object at the top of the C2lua stack,
1789and pops it. 1793and pops it.
1790 1794
1791As a general rule, all API functions pop from the stack
1792all elements they use.
1793
1794When C code calls Lua repeatedly, as in a loop, 1795When C code calls Lua repeatedly, as in a loop,
1795objects returned by these calls can accumulate, 1796objects returned by these calls accumulate,
1796and may cause a stack overflow. 1797and may cause a stack overflow.
1797To avoid this, 1798To avoid this,
1798nested blocks can be defined with the functions 1799nested blocks can be defined with the functions
1799\begin{verbatim} 1800\begin{verbatim}
1800void lua_beginblock (void); 1801void lua_beginblock (lua_State *L);
1801void lua_endblock (void); 1802void lua_endblock (lua_State *L);
1802\end{verbatim} 1803\end{verbatim}
1803After the end of the block, 1804After the end of the block,
1804all \verb|lua_Object|'s created inside it are released. 1805all \verb|lua_Object|s created inside it are released.
1805The use of explicit nested blocks is good programming practice 1806The \verb|lua_endblock| function also empties the C2Lua stack.
1806and is strongly encouraged.
1807 1807
1808\subsection{Garbage Collection}\label{GC} 1808\subsection{Garbage Collection}\label{GC}
1809Because Lua has automatic memory management and garbage collection, 1809Because Lua has automatic memory management and garbage collection,
@@ -1818,13 +1818,13 @@ and never to store \verb|lua_Object|s in C global variables.
1818A garbage collection cycle can be forced by: 1818A garbage collection cycle can be forced by:
1819\Deffunc{lua_collectgarbage} 1819\Deffunc{lua_collectgarbage}
1820\begin{verbatim} 1820\begin{verbatim}
1821long lua_collectgarbage (long limit); 1821long lua_collectgarbage (lua_State *L, long limit);
1822\end{verbatim} 1822\end{verbatim}
1823This function returns the number of objects collected. 1823This function returns the number of objects collected.
1824The argument \verb|limit| makes the next cycle occur only 1824The argument \verb|limit| makes the next cycle occur only
1825after that number of new objects have been created. 1825after that number of new objects have been created.
1826If \verb|limit| is 0, 1826If \verb|limit| is 0,
1827then Lua uses an adaptive heuristics to set this limit. 1827then Lua uses an adaptive heuristic to set this limit.
1828 1828
1829 1829
1830\subsection{Userdata and Tags}\label{C-tags} 1830\subsection{Userdata and Tags}\label{C-tags}
@@ -1846,14 +1846,14 @@ whose semantics are only known to the host program.
1846Tags are created with the function 1846Tags are created with the function
1847\Deffunc{lua_newtag} 1847\Deffunc{lua_newtag}
1848\begin{verbatim} 1848\begin{verbatim}
1849int lua_newtag (void); 1849int lua_newtag (lua_State *L);
1850\end{verbatim} 1850\end{verbatim}
1851The function \verb|lua_settag| changes the tag of 1851The function \verb|lua_settag| changes the tag of
1852the object on the top of C2lua (and pops it); 1852the object on the top of C2lua (and pops it);
1853the object must be a userdata or a table: 1853the object must be a userdata or a table:
1854\Deffunc{lua_settag} 1854\Deffunc{lua_settag}
1855\begin{verbatim} 1855\begin{verbatim}
1856void lua_settag (int tag); 1856void lua_settag (lua_State *L, int tag);
1857\end{verbatim} 1857\end{verbatim}
1858The given \verb|tag| must be a value created with \verb|lua_newtag|. 1858The given \verb|tag| must be a value created with \verb|lua_newtag|.
1859 1859
@@ -1862,19 +1862,30 @@ A host program can execute Lua chunks written in a file or in a string
1862using the following functions:% 1862using the following functions:%
1863\Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer} 1863\Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer}
1864\begin{verbatim} 1864\begin{verbatim}
1865int lua_dofile (const char *filename); 1865int lua_dofile (lua_State *L, const char *filename);
1866int lua_dostring (const char *string); 1866int lua_dostring (lua_State *L, const char *string);
1867int lua_dobuffer (const char *buff, size_t size, const char *name); 1867int lua_dobuffer (lua_State *L, const char *buff,
1868 size_t size, const char *name);
1868\end{verbatim} 1869\end{verbatim}
1869All these functions return an error code: 1870All these functions return
18700, in case of success; non zero, in case of errors. 18710, in case of success, or one of the following error codes:
1871More specifically, \verb|lua_dofile| returns 2 if for any reason 1872\begin{itemize}
1872it could not open the file. 1873\item \verb|LUA_ERRRUN| ---
1873(In this case, 1874error while running the chunk.
1875\item \verb|LUA_ERRSYNTAX| ---
1876syntax error during pre-compilation.
1877\item \verb|LUA_ERRMEM| ---
1878memory allocation error;
1879for such errors, Lua does not call the \verb|LUA_ERRORMESSAGE| function.
1880\item \verb|LUA_ERRFILE| ---
1881error opening the file (only for \verb|lua_dofile|).
1882In this case,
1874you may want to 1883you may want to
1875check \verb|errno|, 1884check \verb|errno|,
1876call \verb|strerror|, 1885call \verb|strerror|,
1877or call \verb|perror| to tell the user what went wrong.) 1886or call \verb|perror| to tell the user what went wrong.
1887\end{itemize}
1888
1878When called with argument \verb|NULL|, 1889When called with argument \verb|NULL|,
1879\verb|lua_dofile| executes the \verb|stdin| stream. 1890\verb|lua_dofile| executes the \verb|stdin| stream.
1880Functions \verb|lua_dofile| and \verb|lua_dobuffer| 1891Functions \verb|lua_dofile| and \verb|lua_dobuffer|
@@ -1900,39 +1911,44 @@ To read the value of any global Lua variable,
1900one uses the function 1911one uses the function
1901\Deffunc{lua_getglobal} 1912\Deffunc{lua_getglobal}
1902\begin{verbatim} 1913\begin{verbatim}
1903lua_Object lua_getglobal (const char *varname); 1914lua_Object lua_getglobal (lua_State *L, const char *varname);
1904\end{verbatim} 1915\end{verbatim}
1905As in Lua, this function may trigger a tag method 1916As in Lua, this function may trigger a tag method
1906for the ``getglobal'' event. 1917for the ``getglobal'' event.
1907To read the real value of any global variable, 1918To read the real value of a global variable,
1908without invoking any tag method, 1919without invoking any tag method,
1909use the \emph{raw} version: 1920use the \emph{lua_rawget} function over the table of globals.
1910\Deffunc{lua_rawgetglobal}
1911\begin{verbatim}
1912lua_Object lua_rawgetglobal (const char *varname);
1913\end{verbatim}
1914 1921
1915To store a value previously pushed onto C2lua in a global variable, 1922To store a value previously pushed onto C2lua in a global variable,
1916there is the function 1923there is the function
1917\Deffunc{lua_setglobal} 1924\Deffunc{lua_setglobal}
1918\begin{verbatim} 1925\begin{verbatim}
1919void lua_setglobal (const char *varname); 1926void lua_setglobal (lua_State *L, const char *varname);
1920\end{verbatim} 1927\end{verbatim}
1921As in Lua, this function may trigger a tag method 1928As in Lua, this function may trigger a tag method
1922for the ``setglobal'' event. 1929for the ``setglobal'' event.
1923To set the real value of any global variable, 1930To set the real value of a global variable,
1924without invoking any tag method, 1931without invoking any tag method,
1925use the \emph{raw} version: 1932use the \emph{lua_rawset} function over the table of globals.
1926\Deffunc{lua_rawgetglobal} 1933
1934To get the table of globals,
1935you should call
1936\Deffunc{lua_pushglobaltable}
1927\begin{verbatim} 1937\begin{verbatim}
1928void lua_rawsetglobal (const char *varname); 1938void lua_pushglobaltable (lua_State *L);
1939\end{verbatim}
1940To set another table as the table of globals,
1941you use
1942\Deffunc{lua_setglobaltable}
1943\begin{verbatim}
1944void lua_setglobaltable (lua_State *L, lua_Object newtable);
1929\end{verbatim} 1945\end{verbatim}
1930 1946
1931Tables can also be manipulated via the API. 1947Tables can also be manipulated via the API.
1932The function 1948The function
1933\Deffunc{lua_gettable} 1949\Deffunc{lua_gettable}
1934\begin{verbatim} 1950\begin{verbatim}
1935lua_Object lua_gettable (void); 1951lua_Object lua_gettable (lua_State *L);
1936\end{verbatim} 1952\end{verbatim}
1937pops a table and an index from the stack C2lua, 1953pops a table and an index from the stack C2lua,
1938and returns the contents of the table at that index. 1954and returns the contents of the table at that index.
@@ -1941,9 +1957,9 @@ for the ``gettable'' event.
1941To get the real value of any table index, 1957To get the real value of any table index,
1942without invoking any tag method, 1958without invoking any tag method,
1943use the \emph{raw} version: 1959use the \emph{raw} version:
1944\Deffunc{lua_rawgetglobal} 1960\Deffunc{lua_rawget}
1945\begin{verbatim} 1961\begin{verbatim}
1946lua_Object lua_rawgettable (void); 1962lua_Object lua_rawget (lua_State *L);
1947\end{verbatim} 1963\end{verbatim}
1948 1964
1949To store a value in an index, 1965To store a value in an index,
@@ -1952,22 +1968,22 @@ the program must push the table, the index, and the value onto C2lua
1952and then call the function 1968and then call the function
1953\Deffunc{lua_settable} 1969\Deffunc{lua_settable}
1954\begin{verbatim} 1970\begin{verbatim}
1955void lua_settable (void); 1971void lua_settable (lua_State *L);
1956\end{verbatim} 1972\end{verbatim}
1957As in Lua, this operation may trigger a tag method 1973As in Lua, this operation may trigger a tag method
1958for the ``settable'' event. 1974for the ``settable'' event.
1959To set the real value of any table index, 1975To set the real value of any table index,
1960without invoking any tag method, 1976without invoking any tag method,
1961use the \emph{raw} version: 1977use the \emph{raw} version:
1962\Deffunc{lua_rawsettable} 1978\Deffunc{lua_rawset}
1963\begin{verbatim} 1979\begin{verbatim}
1964void lua_rawsettable (void); 1980void lua_rawset (lua_State *L);
1965\end{verbatim} 1981\end{verbatim}
1966 1982
1967Finally, the function 1983Finally, the function
1968\Deffunc{lua_createtable} 1984\Deffunc{lua_createtable}
1969\begin{verbatim} 1985\begin{verbatim}
1970lua_Object lua_createtable (void); 1986lua_Object lua_createtable (lua_State *L);
1971\end{verbatim} 1987\end{verbatim}
1972creates and returns a new, empty table. 1988creates and returns a new, empty table.
1973 1989
@@ -1981,10 +1997,9 @@ first, the arguments to the function are pushed onto C2lua
1981Then, the function is called using 1997Then, the function is called using
1982\Deffunc{lua_callfunction} 1998\Deffunc{lua_callfunction}
1983\begin{verbatim} 1999\begin{verbatim}
1984int lua_callfunction (lua_Object function); 2000int lua_callfunction (lua_State *L, lua_Object function);
1985\end{verbatim} 2001\end{verbatim}
1986This function returns an error code: 2002This function returns the same error codes that \verb|lua_dostring|.
19870, in case of success; non zero, in case of errors.
1988Finally, the results are returned in structure lua2C 2003Finally, the results are returned in structure lua2C
1989(recall that a Lua function may return many values), 2004(recall that a Lua function may return many values),
1990and can be retrieved with the macro \verb|lua_getresult|, 2005and can be retrieved with the macro \verb|lua_getresult|,
@@ -1999,23 +2014,23 @@ equivalent to the Lua code:
1999 a,b = f("how", t.x, 4) 2014 a,b = f("how", t.x, 4)
2000\end{verbatim} 2015\end{verbatim}
2001\begin{verbatim} 2016\begin{verbatim}
2002 lua_pushstring("how"); /* 1st argument */ 2017 lua_pushstring(L, "how"); /* 1st argument */
2003 lua_pushobject(lua_getglobal("t")); /* push value of global 't' */ 2018 lua_pushobject(L, lua_getglobal(L, "t")) /* push value of global 't' */
2004 lua_pushstring("x"); /* push the string 'x' */ 2019 lua_pushstring(L, "x"); /* push the string 'x' */
2005 lua_pushobject(lua_gettable()); /* push result of t.x (2nd arg) */ 2020 lua_pushobject(L, lua_gettable(L)); /* push result of t.x (2nd arg) */
2006 lua_pushnumber(4); /* 3rd argument */ 2021 lua_pushnumber(L, 4); /* 3rd argument */
2007 lua_callfunction(lua_getglobal("f")); /* call Lua function */ 2022 lua_callfunction(L, lua_getglobal(L, "f")); /* call `f' */
2008 lua_pushobject(lua_getresult(1)); /* push first result of the call */ 2023 lua_pushobject(L, lua_getresult(L, 1)); /* push first result of the call */
2009 lua_setglobal("a"); /* set global variable 'a' */ 2024 lua_setglobal(L, "a"); /* set global variable 'a' */
2010 lua_pushobject(lua_getresult(2)); /* push second result of the call */ 2025 lua_pushobject(L, lua_getresult(L, 2)); /* push second result of the call */
2011 lua_setglobal("b"); /* set global variable 'b' */ 2026 lua_setglobal(L, "b"); /* set global variable 'b' */
2012\end{verbatim} 2027\end{verbatim}
2013 2028
2014Some special Lua functions have exclusive interfaces. 2029Some special Lua functions have exclusive interfaces.
2015The host program can generate a Lua error calling the function 2030The host program can generate a Lua error calling the function
2016\Deffunc{lua_error} 2031\Deffunc{lua_error}
2017\begin{verbatim} 2032\begin{verbatim}
2018void lua_error (const char *message); 2033void lua_error (lua_State *L, const char *message);
2019\end{verbatim} 2034\end{verbatim}
2020This function never returns. 2035This function never returns.
2021If \verb|lua_error| is called from a C~function that has been called from Lua, 2036If \verb|lua_error| is called from a C~function that has been called from Lua,
@@ -2030,7 +2045,7 @@ then \verb|_ERRORMESSAGE| is not called.
2030 2045
2031Tag methods can be changed with: \Deffunc{lua_settagmethod} 2046Tag methods can be changed with: \Deffunc{lua_settagmethod}
2032\begin{verbatim} 2047\begin{verbatim}
2033lua_Object lua_settagmethod (int tag, const char *event); 2048lua_Object lua_settagmethod (lua_State *L, int tag, const char *event);
2034\end{verbatim} 2049\end{verbatim}
2035The first parameter is the tag, 2050The first parameter is the tag,
2036and the second is the event name \see{tag-method}; 2051and the second is the event name \see{tag-method};
@@ -2040,19 +2055,19 @@ which is the old tag method value.
2040To get just the current value of a tag method, 2055To get just the current value of a tag method,
2041use the function \Deffunc{lua_gettagmethod} 2056use the function \Deffunc{lua_gettagmethod}
2042\begin{verbatim} 2057\begin{verbatim}
2043lua_Object lua_gettagmethod (int tag, const char *event); 2058lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event);
2044\end{verbatim} 2059\end{verbatim}
2045 2060
2046It is also possible to copy all tag methods from one tag 2061It is also possible to copy all tag methods from one tag
2047to another: \Deffunc{lua_copytagmethods} 2062to another: \Deffunc{lua_copytagmethods}
2048\begin{verbatim} 2063\begin{verbatim}
2049int lua_copytagmethods (int tagto, int tagfrom); 2064int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);
2050\end{verbatim} 2065\end{verbatim}
2051This function returns \verb|tagto|. 2066This function returns \verb|tagto|.
2052 2067
2053You can traverse a table with the function \Deffunc{lua_next} 2068You can traverse a table with the function \Deffunc{lua_next}
2054\begin{verbatim} 2069\begin{verbatim}
2055int lua_next (lua_Object t, int i); 2070int lua_next (lua_State *L, lua_Object t, int i);
2056\end{verbatim} 2071\end{verbatim}
2057Its first argument is the table to be traversed, 2072Its first argument is the table to be traversed,
2058and the second is a \emph{cursor}; 2073and the second is a \emph{cursor};
@@ -2068,51 +2083,27 @@ A typical traversal looks like the following code:
2068 lua_Object t; 2083 lua_Object t;
2069 ... /* gets the table at `t' */ 2084 ... /* gets the table at `t' */
2070 i = 0; 2085 i = 0;
2071 lua_beginblock(); 2086 lua_beginblock(L);
2072 while ((i = lua_next(t, i)) != 0) { 2087 while ((i = lua_next(L, t, i)) != 0) {
2073 lua_Object key = lua_getresult(1); 2088 lua_Object key = lua_getresult(L, 1);
2074 lua_Object value = lua_getresult(2); 2089 lua_Object value = lua_getresult(L, 2);
2075 ... /* uses `key' and `value' */ 2090 ... /* uses `key' and `value' */
2076 lua_endblock(); 2091 lua_endblock(L);
2077 lua_beginblock(); /* reopens a block */ 2092 lua_beginblock(L); /* reopens a block */
2078 } 2093 }
2079 lua_endblock(); 2094 lua_endblock(L);
2080\end{verbatim} 2095\end{verbatim}
2081The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the 2096The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the
2082results of each iteration from the stack. 2097results of each iteration from the stack.
2083Without them, a traversal of a large table may overflow the stack. 2098Without them, a traversal of a large table may overflow the stack.
2084 2099
2085To traverse the global variables, use \Deffunc{lua_nextvar}
2086\begin{verbatim}
2087const char *lua_nextvar (const char *varname);
2088\end{verbatim}
2089Here, the cursor is a string;
2090in the first call you set it to \verb|NULL|;
2091for each call the function returns the name of a global variable,
2092to be used in the next call,
2093or \verb|NULL| to signal the end of the traverse.
2094The function also returns, in the Lua2C array,
2095the name (again) and the value of the global variable.
2096A typical traversal looks like the following code:
2097\begin{verbatim}
2098 const char *name = NULL;
2099 lua_beginblock();
2100 while ((name = lua_nextvar(name)) != NULL) {
2101 lua_Object value = lua_getresult(2);
2102 ... /* uses `name' and `value' */
2103 lua_endblock();
2104 lua_beginblock(); /* reopens a block */
2105 }
2106 lua_endblock();
2107\end{verbatim}
2108
2109 2100
2110\subsection{Defining C Functions} \label{LuacallC} 2101\subsection{Defining C Functions} \label{LuacallC}
2111To register a C~function to Lua, 2102To register a C~function to Lua,
2112there is the following convenience macro: 2103there is the following convenience macro:
2113\Deffunc{lua_register} 2104\Deffunc{lua_register}
2114\begin{verbatim} 2105\begin{verbatim}
2115#define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n)) 2106#define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n))
2116/* const char *n; */ 2107/* const char *n; */
2117/* lua_CFunction f; */ 2108/* lua_CFunction f; */
2118\end{verbatim} 2109\end{verbatim}
@@ -2122,9 +2113,10 @@ This pointer must have type \verb|lua_CFunction|,
2122which is defined as 2113which is defined as
2123\Deffunc{lua_CFunction} 2114\Deffunc{lua_CFunction}
2124\begin{verbatim} 2115\begin{verbatim}
2125typedef void (*lua_CFunction) (void); 2116typedef void (*lua_CFunction) (lua_State *L);
2126\end{verbatim} 2117\end{verbatim}
2127that is, a pointer to a function with no parameters and no results. 2118that is, a pointer to a function with no results and a single argument,
2119a Lua environment.
2128 2120
2129In order to communicate properly with Lua, 2121In order to communicate properly with Lua,
2130a C~function must follow a protocol, 2122a C~function must follow a protocol,
@@ -2148,7 +2140,7 @@ To associate upvalues to a C~function,
2148first these values must be pushed on C2lua. 2140first these values must be pushed on C2lua.
2149Then the function \Deffunc{lua_pushcclosure} 2141Then the function \Deffunc{lua_pushcclosure}
2150\begin{verbatim} 2142\begin{verbatim}
2151void lua_pushcclosure (lua_CFunction fn, int n); 2143void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
2152\end{verbatim} 2144\end{verbatim}
2153is used to put the C~function on C2lua, 2145is used to put the C~function on C2lua,
2154with the argument \verb|n| telling how many upvalues must be 2146with the argument \verb|n| telling how many upvalues must be
@@ -2161,8 +2153,6 @@ before the actual arguments provided in the call.
2161 2153
2162For some examples of C~functions, see files \verb|lstrlib.c|, 2154For some examples of C~functions, see files \verb|lstrlib.c|,
2163\verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. 2155\verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution.
2164In particular,
2165\verb|liolib.c| defines C~closures with file handles are upvalues.
2166 2156
2167\subsection{References to Lua Objects} 2157\subsection{References to Lua Objects}
2168 2158
@@ -2174,9 +2164,9 @@ The routines to manipulate references are the following:
2174\Deffunc{lua_ref}\Deffunc{lua_getref} 2164\Deffunc{lua_ref}\Deffunc{lua_getref}
2175\Deffunc{lua_unref} 2165\Deffunc{lua_unref}
2176\begin{verbatim} 2166\begin{verbatim}
2177int lua_ref (int lock); 2167int lua_ref (lua_State *L, int lock);
2178lua_Object lua_getref (int ref); 2168lua_Object lua_getref (lua_State *L, int ref);
2179void lua_unref (int ref); 2169void lua_unref (lua_State *L, int ref);
2180\end{verbatim} 2170\end{verbatim}
2181The function \verb|lua_ref| creates a reference 2171The function \verb|lua_ref| creates a reference
2182to the object that is on the top of the stack, 2172to the object that is on the top of the stack,
@@ -2288,7 +2278,7 @@ Instead, it returns \nil\ to signal the error
2288(besides calling the appropriated error handler). 2278(besides calling the appropriated error handler).
2289 2279
2290If \verb|errhandler| is provided, 2280If \verb|errhandler| is provided,
2291the error function \verb|_ERRORMESSAGE| is temporarily set \verb|errhandler|, 2281the error function \verb|_ERRORMESSAGE| is temporarily set to \verb|errhandler|,
2292while \verb|func| runs. 2282while \verb|func| runs.
2293In particular, if \verb|errhandler| is \nil, 2283In particular, if \verb|errhandler| is \nil,
2294no error messages will be issued during the execution of the called function. 2284no error messages will be issued during the execution of the called function.
@@ -2318,8 +2308,8 @@ When called without arguments,
2318If there is any error executing the file, 2308If there is any error executing the file,
2319then \verb|dofile| returns \nil. 2309then \verb|dofile| returns \nil.
2320Otherwise, it returns the values returned by the chunk, 2310Otherwise, it returns the values returned by the chunk,
2321or a non \nil\ value if the chunk returns no values. 2311or a non-\nil\ value if the chunk returns no values.
2322It issues an error when called with a non string argument. 2312It issues an error when called with a non-string argument.
2323\verb|dofile| is equivalent to the API function \verb|lua_dofile|. 2313\verb|dofile| is equivalent to the API function \verb|lua_dofile|.
2324 2314
2325\subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring} 2315\subsubsection*{\ff \T{dostring (string [, chunkname])}}\Deffunc{dostring}
@@ -2327,7 +2317,7 @@ Executes a given string as a Lua chunk.
2327If there is any error executing the string, 2317If there is any error executing the string,
2328then \verb|dostring| returns \nil. 2318then \verb|dostring| returns \nil.
2329Otherwise, it returns the values returned by the chunk, 2319Otherwise, it returns the values returned by the chunk,
2330or a non \nil\ value if the chunk returns no values. 2320or a non-\nil\ value if the chunk returns no values.
2331The optional parameter \verb|chunkname| 2321The optional parameter \verb|chunkname|
2332is the ``name of the chunk'', 2322is the ``name of the chunk'',
2333used in error messages and debug information. 2323used in error messages and debug information.
@@ -2354,20 +2344,16 @@ as the final value of \verb|foreach|.
2354This function could be defined in Lua: 2344This function could be defined in Lua:
2355\begin{verbatim} 2345\begin{verbatim}
2356 function foreach (t, f) 2346 function foreach (t, f)
2357 local i, v = nil 2347 for i, v in t do
2358 while 1 do
2359 i, v = next(t, i)
2360 if not i then break end
2361 local res = f(i, v) 2348 local res = f(i, v)
2362 if res then return res end 2349 if res then return res end
2363 end 2350 end
2364 end 2351 end
2365\end{verbatim} 2352\end{verbatim}
2366 2353
2367You may change the \emph{values} of existing fields in the table during the traversal, 2354You may change the \emph{values} of existing
2368but 2355fields in the table during the traversal,
2369if you create new indices, 2356but if you create new indices,
2370then
2371the semantics of \verb|foreach| is undefined. 2357the semantics of \verb|foreach| is undefined.
2372 2358
2373 2359
@@ -2393,43 +2379,19 @@ This function could be defined in Lua:
2393 end 2379 end
2394\end{verbatim} 2380\end{verbatim}
2395 2381
2396You may change the \emph{values} of existing fields in the table during the traversal, 2382You may change the \emph{values} of existing fields in the
2397but 2383table during the traversal,
2398if you create new indices (even non-numeric), 2384but if you create new indices (even non-numeric),
2399then
2400the semantics of \verb|foreachi| is undefined. 2385the semantics of \verb|foreachi| is undefined.
2401 2386
2402\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} 2387\subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar}
2403Executes \verb|function| over all global variables. 2388This function is obsolete.
2404For each variable, 2389Use \verb|foreach(globals(), function)| instead.
2405the function is called with its name and its value as arguments.
2406If the function returns any non-nil value,
2407then the loop is broken, and this value is returned
2408as the final value of \verb|foreachvar|.
2409
2410This function could be defined in Lua:
2411\begin{verbatim}
2412 function foreachvar (f)
2413 local n, v = nil
2414 while 1 do
2415 n, v = nextvar(n)
2416 if not n then break end
2417 local res = f(n, v)
2418 if res then return res end
2419 end
2420 end
2421\end{verbatim}
2422
2423You may change the values of existing global variables during the traversal,
2424but
2425if you create new global variables,
2426then
2427the semantics of \verb|foreachvar| is undefined.
2428 2390
2429 2391
2430\subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal} 2392\subsubsection*{\ff \T{getglobal (name)}}\Deffunc{getglobal}
2431Gets the value of a global variable, 2393Gets the value of a global variable,
2432or calls a tag method for ``getgloball''. 2394or calls a tag method for ``getglobal''.
2433Its full semantics is explained in \See{tag-method}. 2395Its full semantics is explained in \See{tag-method}.
2434The string \verb|name| does not need to be a 2396The string \verb|name| does not need to be a
2435syntactically valid variable name. 2397syntactically valid variable name.
@@ -2444,10 +2406,8 @@ This function could be defined in Lua:
2444\begin{verbatim} 2406\begin{verbatim}
2445 function getn (t) 2407 function getn (t)
2446 if type(t.n) == 'number' then return t.n end 2408 if type(t.n) == 'number' then return t.n end
2447 local max, i = 0, nil 2409 local max = 0
2448 while 1 do 2410 for i, _ in t do
2449 i = next(t, i)
2450 if not i then break end
2451 if type(i) == 'number' and i>max then max=i end 2411 if type(i) == 'number' and i>max then max=i end
2452 end 2412 end
2453 return max 2413 return max
@@ -2459,6 +2419,11 @@ This function could be defined in Lua:
2459Returns the current tag method 2419Returns the current tag method
2460for a given pair \M{(tag, event)}. 2420for a given pair \M{(tag, event)}.
2461 2421
2422\subsubsection*{\ff \T{globals ([newtable])}}\Deffunc{globals}
2423Returns the current table of globals.
2424If the argument \verb|newtable| is given,
2425set this table as the new table of globals.
2426
2462\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} 2427\subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag}
2463Returns a new tag. 2428Returns a new tag.
2464\verb|newtag| is equivalent to the API function \verb|lua_newtag|. 2429\verb|newtag| is equivalent to the API function \verb|lua_newtag|.
@@ -2480,33 +2445,20 @@ If the second argument is absent, then it is interpreted as \nil.
2480Lua has no declaration of fields; 2445Lua has no declaration of fields;
2481semantically, there is no difference between a 2446semantically, there is no difference between a
2482field not present in a table or a field with value \nil. 2447field not present in a table or a field with value \nil.
2483Therefore, \verb|next| only considers fields with non \nil\ values. 2448Therefore, \verb|next| only considers fields with non-\nil\ values.
2484The order in which the indices are enumerated is not specified, 2449The order in which the indices are enumerated is not specified,
2485\emph{even for numeric indices} 2450\emph{even for numeric indices}
2486(to traverse a table in numeric order, 2451(to traverse a table in numeric order,
2487use a counter or the function \verb|foreachi|). 2452use a counter or the function \verb|foreachi|).
2488 2453
2489You may change the \emph{values} of existing fields in the table during the traversal, 2454You may change the \emph{values} of existing fields in the
2490but 2455table during the traversal,
2491if you create new indices, 2456but if you create new indices,
2492then
2493the semantics of \verb|next| is undefined. 2457the semantics of \verb|next| is undefined.
2494 2458
2495\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} 2459\subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar}
2496This function is similar to the function \verb|next|, 2460This function is obsolete.
2497but iterates instead over the global variables. 2461Use \verb|next(globals(), name)| instead.
2498Its single argument is the name of a global variable,
2499or \nil\ to get a first name.
2500If this argument is absent, then it is interpreted as \nil.
2501Like \verb|next|, \verb|nextvar| returns the name of another variable
2502and its value,
2503or \nil\ if there are no more variables.
2504
2505You may change the \emph{values} of existing global variables during the traversal,
2506but
2507if you create new global variables,
2508then
2509the semantics of \verb|nextvar| is undefined.
2510 2462
2511\subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print} 2463\subsubsection*{\ff \T{print (e1, e2, ...)}}\Deffunc{print}
2512Receives any number of arguments, 2464Receives any number of arguments,
@@ -2517,27 +2469,26 @@ for instance for debugging.
2517See \See{libio} for functions for formatted output. 2469See \See{libio} for functions for formatted output.
2518 2470
2519\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} 2471\subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal}
2520Gets the value of a global variable, 2472This function is obsolete.
2521without invoking any tag method. 2473Use \verb|rawget(globals(), name)| instead.
2522The string \verb|name| does not need to be a
2523syntactically valid variable name.
2524 2474
2525\subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable} 2475\subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable}
2476This function was renamed to \verb|rawget|.
2477
2478\subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget}
2526Gets the real value of \verb|table[index]|, 2479Gets the real value of \verb|table[index]|,
2527without invoking any tag method. 2480without invoking any tag method.
2528\verb|table| must be a table, 2481\verb|table| must be a table,
2529and \verb|index| is any value different from \nil. 2482and \verb|index| is any value different from \nil.
2530 2483
2531\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} 2484\subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal}
2532Sets the named global variable to the given value, 2485This function is obsolete.
2533without invoking any tag method. 2486Use \verb|rawset(globals(), name, value)| instead.
2534The string \verb|name| does not need to be a
2535syntactically valid variable name.
2536Therefore,
2537this function can be used to set global variables with strange names like
2538\verb|"m v 1"| or \verb|"34"|.
2539 2487
2540\subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} 2488\subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable}
2489This function was renamed to \verb|rawset|.
2490
2491\subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset}
2541Sets the real value of \verb|table[index]| to \verb|value|, 2492Sets the real value of \verb|table[index]| to \verb|value|,
2542without invoking any tag method. 2493without invoking any tag method.
2543\verb|table| must be a table, 2494\verb|table| must be a table,
@@ -2546,7 +2497,7 @@ and \verb|value| is any Lua value.
2546 2497
2547\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} 2498\subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal}
2548Sets the named global variable to the given value, 2499Sets the named global variable to the given value,
2549or calls a tag method for ``setgloball''. 2500or calls a tag method for ``setglobal''.
2550Its full semantics is explained in \See{tag-method}. 2501Its full semantics is explained in \See{tag-method}.
2551The string \verb|name| does not need to be a 2502The string \verb|name| does not need to be a
2552syntactically valid variable name. 2503syntactically valid variable name.
@@ -2577,6 +2528,10 @@ and returns true when the first is less than the second
2577If \verb|comp| is not given, 2528If \verb|comp| is not given,
2578the standard Lua operator \verb|<| is used instead. 2529the standard Lua operator \verb|<| is used instead.
2579 2530
2531The sort algorithm is not stable
2532(that is, elements considered equal by the given order
2533may have their relative positions changed by the sort).
2534
2580\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag} 2535\subsubsection*{\ff \T{tag (v)}}\Deffunc{tag}\label{pdf-tag}
2581Allows Lua programs to test the tag of a value \see{TypesSec}. 2536Allows Lua programs to test the tag of a value \see{TypesSec}.
2582It receives one argument, and returns its tag (a number). 2537It receives one argument, and returns its tag (a number).
@@ -2601,7 +2556,7 @@ In other bases, only unsigned integers are accepted.
2601\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring} 2556\subsubsection*{\ff \T{tostring (e)}}\Deffunc{tostring}
2602Receives an argument of any type and 2557Receives an argument of any type and
2603converts it to a string in a reasonable format. 2558converts it to a string in a reasonable format.
2604For complete control on how numbers are converted, 2559For complete control of how numbers are converted,
2605use function \verb|format|. 2560use function \verb|format|.
2606 2561
2607 2562
@@ -2708,7 +2663,7 @@ to its correspondent argument.
2708\Deffunc{strfind} 2663\Deffunc{strfind}
2709Looks for the first \emph{match} of 2664Looks for the first \emph{match} of
2710\verb|pattern| in \verb|str|. 2665\verb|pattern| in \verb|str|.
2711If it finds one, then it returns the indices on \verb|str| 2666If it finds one, then it returns the indices of \verb|str|
2712where this occurrence starts and ends; 2667where this occurrence starts and ends;
2713otherwise, it returns \nil. 2668otherwise, it returns \nil.
2714If the pattern specifies captures (see \verb|gsub| below), 2669If the pattern specifies captures (see \verb|gsub| below),
@@ -2853,9 +2808,9 @@ Here are some examples:
2853 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) 2808 x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring)
2854 --> x="4+5 = 9" 2809 --> x="4+5 = 9"
2855 2810
2856 local t = {name="lua", version="3.2"} 2811 local t = {name="lua", version="4.0"}
2857 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) 2812 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end)
2858 --> x="lua - 3.2" 2813 --> x="lua - 4.0"
2859 2814
2860 t = {n=0} 2815 t = {n=0}
2861 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) 2816 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end)
@@ -2883,12 +2838,12 @@ The following combinations are allowed in describing a character class:
2883\item[\T{\%w}] --- represents all alphanumeric characters. 2838\item[\T{\%w}] --- represents all alphanumeric characters.
2884\item[\T{\%x}] --- represents all hexadecimal digits. 2839\item[\T{\%x}] --- represents all hexadecimal digits.
2885\item[\T{\%z}] --- represents the character with representation 0. 2840\item[\T{\%z}] --- represents the character with representation 0.
2886\item[\T{\%\M{x}}] (where \M{x} is any non alphanumeric character) --- 2841\item[\T{\%\M{x}}] (where \M{x} is any non-alphanumeric character) ---
2887represents the character \M{x}. 2842represents the character \M{x}.
2888This is the standard way to escape the magic characters \verb|()%.[]*-?|. 2843This is the standard way to escape the magic characters \verb|()%.[]*+-?|.
2889It is strongly recommended that any control character (even the non magic) 2844We recommend that any ``punct'' character (even the non magic)
2890should be preceded by a \verb|%| 2845should be preceded by a \verb|%|
2891when used to represent itself in a pattern, 2846when used to represent itself in a pattern.
2892 2847
2893\item[\T{[char-set]}] --- 2848\item[\T{[char-set]}] ---
2894represents the class which is the union of all 2849represents the class which is the union of all
@@ -3131,7 +3086,8 @@ usually limited and depends on the system.
3131Opens a file named \verb|filename| and sets it as the 3086Opens a file named \verb|filename| and sets it as the
3132value of \verb|_OUTPUT|. 3087value of \verb|_OUTPUT|.
3133Unlike the \verb|writeto| operation, 3088Unlike the \verb|writeto| operation,
3134this function does not erase any previous contents of the file. 3089this function does not erase any previous contents of the file;
3090instead, anything written to the file is appended to its end.
3135If this function fails, it returns \nil, 3091If this function fails, it returns \nil,
3136plus a string describing the error. 3092plus a string describing the error.
3137 3093
@@ -3209,7 +3165,7 @@ This is the default format.
3209\item[``*a''] reads the whole file, starting at the current position. 3165\item[``*a''] reads the whole file, starting at the current position.
3210On end of file, it returns the empty string. 3166On end of file, it returns the empty string.
3211\item[``*w''] reads the next word 3167\item[``*w''] reads the next word
3212(maximal sequence of non white-space characters), 3168(maximal sequence of non--white-space characters),
3213skipping spaces if necessary, or \nil\ on end of file. 3169skipping spaces if necessary, or \nil\ on end of file.
3214\item[\emph{number}] reads a string with up to that number of characters, 3170\item[\emph{number}] reads a string with up to that number of characters,
3215or \nil\ on end of file. 3171or \nil\ on end of file.
@@ -3362,8 +3318,6 @@ or \verb|"main"| if this is the main part of a chunk.
3362 3318
3363\item[currentline] 3319\item[currentline]
3364the current line where the given function is executing. 3320the current line where the given function is executing.
3365It only works if the function has been compiled with debug
3366information.
3367When no line information is available, 3321When no line information is available,
3368\verb|currentline| is set to \Math{-1}. 3322\verb|currentline| is set to \Math{-1}.
3369 3323
@@ -3400,17 +3354,6 @@ The function being executed, as a \verb|lua_Object|.
3400 3354
3401\end{description} 3355\end{description}
3402 3356
3403The generation of debug information is controlled by an internal flag,
3404which can be switched with
3405\begin{verbatim}
3406int lua_setdebug (lua_State *L, int debug);
3407\end{verbatim}
3408This function sets the flag and returns its previous value.
3409This flag can also be set from Lua~\see{pragma}.
3410Setting the flag using \verb|lua_setdebug| affects all chunks that are
3411compiled afterwards.
3412Individual functions may still control the generation of debug information
3413by using \verb|$debug| or \verb|$nodebug|.
3414 3357
3415\subsection{Manipulating Local Variables} 3358\subsection{Manipulating Local Variables}
3416 3359
@@ -3430,10 +3373,6 @@ until the last active local variable).
3430\Deffunc{lua_getlocal}\Deffunc{lua_setlocal} 3373\Deffunc{lua_getlocal}\Deffunc{lua_setlocal}
3431The following functions allow the manipulation of the 3374The following functions allow the manipulation of the
3432local variables of a given activation record. 3375local variables of a given activation record.
3433They only work if the function has been compiled with debug
3434information \see{pragma}.
3435For these functions, a local variable becomes
3436visible in the line after its definition.
3437\begin{verbatim} 3376\begin{verbatim}
3438int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); 3377int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
3439int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); 3378int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v);
@@ -3450,8 +3389,7 @@ For \verb|lua_setlocal|,
3450you fill the \verb|index| and the \verb|value| fields of \verb|v|, 3389you fill the \verb|index| and the \verb|value| fields of \verb|v|,
3451and the function assigns that value to the variable. 3390and the function assigns that value to the variable.
3452Both functions return 0 on failure, that happens 3391Both functions return 0 on failure, that happens
3453if the index is greater than the number of active local variables, 3392if the index is greater than the number of active local variables.
3454or if the activation record has no debug information.
3455 3393
3456As an example, the following function lists the names of all 3394As an example, the following function lists the names of all
3457local variables for a function in a given level of the stack: 3395local variables for a function in a given level of the stack:
@@ -3465,7 +3403,7 @@ int listvars (lua_State *L, int level) {
3465 lua_Localvar v; 3403 lua_Localvar v;
3466 v.index = i; 3404 v.index = i;
3467 if (lua_getlocal(L, &ar, &v) == 0) 3405 if (lua_getlocal(L, &ar, &v) == 0)
3468 return 1; /* no more locals, or no debug information */ 3406 return 1; /* no more locals */
3469 printf("%s\n", v.name); 3407 printf("%s\n", v.name);
3470 } 3408 }
3471} 3409}
@@ -3505,8 +3443,6 @@ the line of code it is executing.
3505The \verb|event| field of \verb|ar| has the string \verb|"line"|, 3443The \verb|event| field of \verb|ar| has the string \verb|"line"|,
3506and the \verb|currentline| field has the line number. 3444and the \verb|currentline| field has the line number.
3507Again, you can use this \verb|ar| in other calls to the debug API. 3445Again, you can use this \verb|ar| in other calls to the debug API.
3508This hook is called only if the active function
3509has been compiled with debug information~\see{pragma}.
3510 3446
3511While Lua is running a hook, it disables other calls to hooks. 3447While Lua is running a hook, it disables other calls to hooks.
3512Therefore, if a hook calls Lua to execute a function or a chunk, 3448Therefore, if a hook calls Lua to execute a function or a chunk,
@@ -3601,8 +3537,6 @@ this hook will be called every time the interpreter changes
3601the line of code it is executing. 3537the line of code it is executing.
3602The only argument to the hook is the line number the interpreter 3538The only argument to the hook is the line number the interpreter
3603is about to execute. 3539is about to execute.
3604This hook is called only if the active function
3605has been compiled with debug information~\see{pragma}.
3606 3540
3607When called without arguments, 3541When called without arguments,
3608this function turns off line hooks. 3542this function turns off line hooks.
@@ -3620,7 +3554,6 @@ This program can be called with any sequence of the following arguments:
3620\begin{description} 3554\begin{description}
3621\item[\T{-}] executes \verb|stdin| as a file; 3555\item[\T{-}] executes \verb|stdin| as a file;
3622\item[\T{-c}] calls \verb|lua_close| after running all arguments; 3556\item[\T{-c}] calls \verb|lua_close| after running all arguments;
3623\item[\T{-d}] turns on debug information;
3624\item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; 3557\item[\T{-e} \rm\emph{stat}] executes string \verb|stat|;
3625\item[\T{-f filename}] executes file \verb|filename| with the 3558\item[\T{-f filename}] executes file \verb|filename| with the
3626remaining arguments in table \verb|arg|; 3559remaining arguments in table \verb|arg|;
@@ -3658,8 +3591,16 @@ then creates a table \T{arg},
3658 arg = {"t1", "t3"; n = 2, [0] = "b.lua"} 3591 arg = {"t1", "t3"; n = 2, [0] = "b.lua"}
3659\end{verbatim} 3592\end{verbatim}
3660and then runs the file \T{b.lua}. 3593and then runs the file \T{b.lua}.
3661The stand-alone interpreter also provides a \verb|getarg| function that 3594The stand-alone interpreter also provides a \verb|getargs| function that
3662can be used to access \emph{all} command line arguments. 3595can be used to access \emph{all} command line arguments.
3596For instance, if you call Lua with the line
3597\begin{verbatim}
3598> lua -d a b
3599\end{verbatim}
3600and the file \verb|a| (or \verb|b|) calls \verb|getargs|,
3601the call will return the table
3602\verb|{[0] = "lua", [1] = "-d", [2] = "a", [3] = "b", n = 3}|.
3603\Deffunc{getargs}
3663 3604
3664In interactive mode, 3605In interactive mode,
3665a multi-line statement can be written finishing intermediate 3606a multi-line statement can be written finishing intermediate
@@ -3680,11 +3621,11 @@ or \verb|#!/usr/local/bin/lua -f| to get other arguments.
3680\section*{Acknowledgments} 3621\section*{Acknowledgments}
3681 3622
3682The authors would like to thank CENPES/PETROBRAS which, 3623The authors would like to thank CENPES/PETROBRAS which,
3683jointly with \tecgraf, used extensively early versions of 3624jointly with \tecgraf, used early versions of
3684this system and gave valuable comments. 3625this system extensively and gave valuable comments.
3685The authors would also like to thank Carlos Henrique Levy, 3626The authors would also like to thank Carlos Henrique Levy,
3686who found the name of the game. 3627who found the name of the game.
3687Lua means \emph{moon} in Portuguese. 3628Lua means ``moon'' in Portuguese.
3688 3629
3689 3630
3690\appendix 3631\appendix
@@ -3746,11 +3687,9 @@ and is no longer a synonym for \verb|lua_tag|.
3746 3687
3747\begin{Produc} 3688\begin{Produc}
3748 3689
3749\produc{chunk}{\rep{stat} \opt{ret}} 3690\produc{chunk}{\rep{stat} \opt{\ter{;}}}
3750 3691
3751\produc{block}{\opt{label} \rep{stat \opt{\ter{;}}}} 3692\produc{block}{chunk}
3752
3753\produc{label}{\ter{$\vert$} name \ter{$\vert$}}
3754 3693
3755\produc{stat}{% 3694\produc{stat}{%
3756 varlist1 \ter{=} explist1 3695 varlist1 \ter{=} explist1
@@ -3762,7 +3701,7 @@ and is no longer a synonym for \verb|lua_tag|.
3762 \rep{\rwd{elseif} exp1 \rwd{then} block} 3701 \rep{\rwd{elseif} exp1 \rwd{then} block}
3763 \opt{\rwd{else} block} \rwd{end} 3702 \opt{\rwd{else} block} \rwd{end}
3764\OrNL \rwd{return} \opt{explist1} 3703\OrNL \rwd{return} \opt{explist1}
3765\OrNL \rwd{break} \opt{name} 3704\OrNL \rwd{break}
3766\OrNL \rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1} 3705\OrNL \rwd{for} name \ter{=} exp1 \ter{,} exp1 \opt{\ter{,} exp1}
3767 \rwd{do} block \rwd{end} 3706 \rwd{do} block \rwd{end}
3768\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} 3707\OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end}
@@ -3771,10 +3710,12 @@ and is no longer a synonym for \verb|lua_tag|.
3771 3710
3772\produc{var}{% 3711\produc{var}{%
3773 name 3712 name
3774\OrNL simpleexp \ter{[} exp1 \ter{]} 3713\OrNL varorfunc \ter{[} exp1 \ter{]}
3775\OrNL simpleexp \ter{.} name 3714\OrNL varorfunc \ter{.} name
3776} 3715}
3777 3716
3717\produc{varorfunc}{var \Or functioncall}
3718
3778\produc{varlist1}{var \rep{\ter{,} var}} 3719\produc{varlist1}{var \rep{\ter{,} var}}
3779 3720
3780\produc{declist}{name \rep{\ter{,} name}} 3721\produc{declist}{name \rep{\ter{,} name}}
@@ -3786,20 +3727,18 @@ and is no longer a synonym for \verb|lua_tag|.
3786\Or number 3727\Or number
3787\Or literal 3728\Or literal
3788\Or function 3729\Or function
3789\Or simpleexp 3730\Or upvalue
3731\Or functioncall
3732\Or tableconstructor
3790\Or \ter{(} exp \ter{)} 3733\Or \ter{(} exp \ter{)}
3734\Or exp binop exp
3735\Or unop exp
3791} 3736}
3792 3737
3793\produc{exp1}{exp} 3738\produc{exp1}{exp}
3794 3739
3795\produc{explist1}{\rep{exp1 \ter{,}} exp} 3740\produc{explist1}{\rep{exp1 \ter{,}} exp}
3796 3741
3797\produc{simpleexp}{%
3798 var
3799\Or upvalue
3800\Or functioncall
3801\Or tableconstructor
3802}
3803 3742
3804\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} 3743\produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}}
3805\produc{fieldlist}{% 3744\produc{fieldlist}{%
@@ -3818,8 +3757,8 @@ and is no longer a synonym for \verb|lua_tag|.
3818} 3757}
3819 3758
3820\produc{functioncall}{% 3759\produc{functioncall}{%
3821 simpleexp args 3760 varorfunc args
3822\Or simpleexp \ter{:} name args 3761\Or varorfunc \ter{:} name args
3823} 3762}
3824 3763
3825\produc{args}{% 3764\produc{args}{%