aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2001-10-31 16:06:05 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2001-10-31 16:06:05 -0200
commit36eb6658599f7ec158b819f259eca338ee9a0d1a (patch)
tree1c506015ce33d1f5316ed2bd2d5a830d52f54a87
parent070204300ce44e7e415b299394d51d2d105a39d1 (diff)
downloadlua-36eb6658599f7ec158b819f259eca338ee9a0d1a.tar.gz
lua-36eb6658599f7ec158b819f259eca338ee9a0d1a.tar.bz2
lua-36eb6658599f7ec158b819f259eca338ee9a0d1a.zip
no more refs, upvalues; lexical scoping;pseudo-indices
-rw-r--r--manual.tex410
1 files changed, 171 insertions, 239 deletions
diff --git a/manual.tex b/manual.tex
index 3bc18b07..ebd7d3ae 100644
--- a/manual.tex
+++ b/manual.tex
@@ -291,8 +291,8 @@ Statements are described in \See{stats}.
291A chunk may be stored in a file or in a string inside the host program. 291A chunk may be stored in a file or in a string inside the host program.
292When a chunk is executed, first it is pre-compiled into bytecodes for 292When a chunk is executed, first it is pre-compiled into bytecodes for
293a virtual machine, 293a virtual machine,
294and then the compiled statements are executed in sequential order, 294and then the compiled statements are executed
295by simulating the virtual machine. 295by an interpreter for the virtual machine.
296All modifications a chunk effects on the global environment persist 296All modifications a chunk effects on the global environment persist
297after the chunk ends. 297after the chunk ends.
298 298
@@ -311,15 +311,12 @@ This means that
311variables do not have types; only values do. 311variables do not have types; only values do.
312Therefore, there are no type definitions in the language. 312Therefore, there are no type definitions in the language.
313All values carry their own type. 313All values carry their own type.
314Besides a type, all values also have a tag \see{tags}.
315 314
316There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, 315There are six \Index{basic types} in Lua: \Def{nil}, \Def{number},
317\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. 316\Def{string}, \Def{function}, \Def{userdata}, and \Def{table}.
318\emph{Nil} is the type of the value \nil, 317\emph{Nil} is the type of the value \nil,
319whose main property is to be different from any other value. 318whose main property is to be different from any other value.
320\emph{Number} represents real 319\emph{Number} represents real (double-precision floating-point) numbers.
321%(double-precision floating-point)
322numbers.
323\emph{String} represents arrays of characters. 320\emph{String} represents arrays of characters.
324\index{eight-bit clean} 321\index{eight-bit clean}
325Lua is 8-bit clean, 322Lua is 8-bit clean,
@@ -365,9 +362,9 @@ In particular,
365because functions are first class values, 362because functions are first class values,
366table fields may contain functions. 363table fields may contain functions.
367So, tables may also carry \emph{methods}. 364So, tables may also carry \emph{methods}.
368The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, 365%The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|,
369which calls the method \verb|f| from the table \verb|t| passing 366%which calls the method \verb|f| from the table \verb|t| passing
370the table itself as the first parameter \see{func-def}. 367%the table itself as the first parameter \see{func-def}.
371 368
372Strings, tables, functions, and userdata values are \emph{objects}: 369Strings, tables, functions, and userdata values are \emph{objects}:
373variables do not actually \emph{contain} these values, 370variables do not actually \emph{contain} these values,
@@ -378,41 +375,9 @@ always manipulate references to these values, and do not imply any kind of copy.
378The library function \verb|type| returns a string describing the type 375The library function \verb|type| returns a string describing the type
379of a given value \see{pdf-type}. 376of a given value \see{pdf-type}.
380 377
378\subsubsection{Tags}\label{tags}
381 379
382\subsection{\Index{Coercion}} \label{coercion} 380Each type is denoted both by a \emph{name},
383
384Lua provides automatic conversion between string and number values at run time.
385Any arithmetic operation applied to a string tries to convert
386that string to a number, following the usual rules.
387Conversely, whenever a number is used when a string is expected,
388the number is converted to a string, in a reasonable format.
389The format is chosen so that
390a conversion from number to string then back to number
391reproduces the original number \emph{exactly}.
392The conversion does not necessarily produces nice-looking text for some numbers.
393For complete control of how numbers are converted to strings,
394use the \verb|format| function \see{format}.
395
396
397\subsection{Variables}
398
399There are two kinds of variables in Lua:
400global variables
401and local variables.
402\Index{Global variables} do not need to be declared.
403Variables are assumed to be global unless explicitly declared local
404\see{localvar}.
405Before the first assignment, the value of a variable is \nil\ %
406(this default can be changed for global variables; see \See{tag-method}).
407
408An ordinary Lua table is used to keep all global names and values.
409This table can be accessed and changed with the \verb|globals| function
410\see{pdf-globals}.
411
412
413\subsection{Tags}\label{tags}
414
415Each type has a \emph{name},
416which is a string, 381which is a string,
417and a \IndexEmph{tag}, 382and a \IndexEmph{tag},
418which is an integer. 383which is an integer.
@@ -425,7 +390,7 @@ with both type names and tags.
425The \verb|tag| function returns the tag of a given value \see{pdf-tag}. 390The \verb|tag| function returns the tag of a given value \see{pdf-tag}.
426 391
427 392
428\subsection{User-defined Types} 393\subsubsection{User-defined Types}
429 394
430Lua programs can create new types, 395Lua programs can create new types,
431called \IndexEmph{user-defined types}. 396called \IndexEmph{user-defined types}.
@@ -446,6 +411,40 @@ The \verb|settype| function changes the type of a given object
446\see{pdf-settype}. 411\see{pdf-settype}.
447 412
448 413
414\subsection{\Index{Coercion}} \label{coercion}
415
416Lua provides automatic conversion between string and number values at run time.
417Any arithmetic operation applied to a string tries to convert
418that string to a number, following the usual rules.
419Conversely, whenever a number is used when a string is expected,
420the number is converted to a string, in a reasonable format.
421The format is chosen so that
422a conversion from number to string then back to number
423reproduces the original number \emph{exactly}.
424The conversion does not necessarily produces nice-looking text for some numbers.
425For complete control of how numbers are converted to strings,
426use the \verb|format| function \see{format}.
427
428
429\subsection{Variables}
430
431There are two kinds of variables in Lua:
432global variables
433and local variables.
434\Index{Global variables} do not need to be declared.
435Variables are assumed to be global unless explicitly declared local
436\see{localvar}.
437Before the first assignment, the value of a variable is \nil\ %
438(this default can be changed for global variables; see \See{tag-method}).
439
440An ordinary Lua table is used to keep all global names and values.
441This table can be accessed and changed with the \verb|globals| function
442\see{pdf-globals}.
443
444\Index{Local variables} are lexically scoped.
445Therefore, local variables can be freely accessed by functions
446defined inside their scope \see{visibility}.
447
449\subsection{Garbage Collection}\label{GC} 448\subsection{Garbage Collection}\label{GC}
450 449
451Lua does automatic memory management. 450Lua does automatic memory management.
@@ -455,9 +454,8 @@ and freeing it when the objects are no longer needed.
455Lua manages memory automatically by running 454Lua manages memory automatically by running
456a \Index{garbage collector} from time to time 455a \Index{garbage collector} from time to time
457and 456and
458collecting all ``dead'' objects 457collecting all dead objects
459(essentially, all objects that are no longer accessible from Lua 458(all objects that are no longer accessible from Lua).
460as the value of a global variable or table field).
461All objects in Lua are subject to automatic management: 459All objects in Lua are subject to automatic management:
462tables, userdata, functions, and strings. 460tables, userdata, functions, and strings.
463 461
@@ -476,7 +474,7 @@ One number counts how many bytes of dynamic memory Lua is using,
476and the other is a threshold. 474and the other is a threshold.
477When the number of bytes crosses the threshold, 475When the number of bytes crosses the threshold,
478Lua runs the garbage collector, 476Lua runs the garbage collector,
479which reclaims the memory of all ``dead'' objects. 477which reclaims the memory of all dead objects.
480The byte counter is corrected, 478The byte counter is corrected,
481and then the threshold is reset to twice the value of the byte counter. 479and then the threshold is reset to twice the value of the byte counter.
482 480
@@ -624,7 +622,7 @@ in Unix systems \see{lua-sa}.
624\subsection{Variables}\label{variables} 622\subsection{Variables}\label{variables}
625 623
626Variables are places that store values. 624Variables are places that store values.
627In Lua, variables are given by simple identifiers or by table fields. 625%In Lua, variables are given by simple identifiers or by table fields.
628 626
629A single name can denote a global variable, a local variable, 627A single name can denote a global variable, a local variable,
630or a formal parameter in a function 628or a formal parameter in a function
@@ -638,7 +636,7 @@ Square brackets are used to index a table:
638\produc{var}{exp \ter{[} exp \ter{]}} 636\produc{var}{exp \ter{[} exp \ter{]}}
639\end{Produc}% 637\end{Produc}%
640The first expression should result in a table value, 638The first expression should result in a table value,
641from where the field given by the second expression gets the assigned value. 639and the second expression identifies the specific place inside that table.
642 640
643The syntax \verb|var.NAME| is just syntactic sugar for 641The syntax \verb|var.NAME| is just syntactic sugar for
644\verb|var["NAME"]|: 642\verb|var["NAME"]|:
@@ -657,8 +655,6 @@ An access to a global variable \verb|x|
657is equivalent to a call \verb|getglobal("x")| and 655is equivalent to a call \verb|getglobal("x")| and
658an access to an indexed variable \verb|t[i]| is equivalent to 656an access to an indexed variable \verb|t[i]| is equivalent to
659a call \verb|gettable_event(t,i)|. 657a call \verb|gettable_event(t,i)|.
660Of course,
661\verb|i| and \verb|val| can be complicated expressions.
662See \See{tag-method} for a complete description of these functions 658See \See{tag-method} for a complete description of these functions
663(\verb|setglobal| and \verb|getglobal| are in the basic library; 659(\verb|setglobal| and \verb|getglobal| are in the basic library;
664\T{settable\_event} and \T{gettable\_event} 660\T{settable\_event} and \T{gettable\_event}
@@ -915,17 +911,12 @@ If present, an initial assignment has the same semantics
915of a multiple assignment \see{assignment}. 911of a multiple assignment \see{assignment}.
916Otherwise, all variables are initialized with \nil. 912Otherwise, all variables are initialized with \nil.
917 913
918The scope of local variables begins \emph{after}
919the declaration and lasts until the end of the block.
920Thus, the code
921\verb|local print=print|
922creates a local variable named \verb|print| whose
923initial value is that of the \emph{global} variable of the same name.
924
925A chunk is also a block \see{chunks}, 914A chunk is also a block \see{chunks},
926and so local variables can be declared outside any explicit block. 915and so local variables can be declared outside any explicit block.
927Such local variables die when the chunk ends. 916Such local variables die when the chunk ends.
928 917
918Visibility rules for local variables are explained in \See{visibility}.
919
929 920
930\subsection{\Index{Expressions}}\label{expressions} 921\subsection{\Index{Expressions}}\label{expressions}
931 922
@@ -937,14 +928,12 @@ The basic expressions in Lua are the following:
937\produc{exp}{number} 928\produc{exp}{number}
938\produc{exp}{literal} 929\produc{exp}{literal}
939\produc{exp}{var} 930\produc{exp}{var}
940\produc{exp}{upvalue}
941\produc{exp}{function} 931\produc{exp}{function}
942\produc{exp}{functioncall} 932\produc{exp}{functioncall}
943\produc{exp}{tableconstructor} 933\produc{exp}{tableconstructor}
944\end{Produc}% 934\end{Produc}%
945 935
946An expression enclosed in parentheses always results in only one value 936An expression enclosed in parentheses always results in only one value.
947(the only expressions that can result in multiple values are function calls).
948Thus, 937Thus,
949\verb|(f(x,y,z))| is always a single value, 938\verb|(f(x,y,z))| is always a single value,
950even if \verb|f| returns several values. 939even if \verb|f| returns several values.
@@ -953,7 +942,6 @@ or \nil\ if \verb|f| does not return any values.)
953 942
954\emph{Numbers} and \emph{literal strings} are explained in \See{lexical}; 943\emph{Numbers} and \emph{literal strings} are explained in \See{lexical};
955variables are explained in \See{variables}; 944variables are explained in \See{variables};
956upvalues are explained in \See{upvalue};
957function definitions are explained in \See{func-def}; 945function definitions are explained in \See{func-def};
958function calls are explained in \See{functioncall}; 946function calls are explained in \See{functioncall};
959table constructors are explained in \See{tableconstructor}. 947table constructors are explained in \See{tableconstructor}.
@@ -972,7 +960,7 @@ numbers \see{coercion},
972then all operations except exponentiation have the usual meaning; 960then all operations except exponentiation have the usual meaning;
973otherwise, an appropriate tag method is called \see{tag-method}. 961otherwise, an appropriate tag method is called \see{tag-method}.
974An exponentiation always calls a tag method. 962An exponentiation always calls a tag method.
975The standard mathematical library redefines this method for numbers, 963The standard mathematical library defines this method for numbers,
976giving the expected meaning to \Index{exponentiation} 964giving the expected meaning to \Index{exponentiation}
977\see{mathlib}. 965\see{mathlib}.
978 966
@@ -986,26 +974,13 @@ These operators return \nil\ as false and a value different from \nil\ as true.
986Equality (\verb|==|) first compares the type of its operands. 974Equality (\verb|==|) first compares the type of its operands.
987If the types are different, then the result is \nil. 975If the types are different, then the result is \nil.
988Otherwise, the values of the operands are compared. 976Otherwise, the values of the operands are compared.
989Numbers are compared in the usual way. 977Numbers and strings are compared in the usual way.
990Strings, tables, userdata, and functions are compared \emph{by reference}, 978Tables, userdata, and functions are compared \emph{by reference},
991that is, 979that is,
992two tables are considered equal only if they are the \emph{same} table. 980two tables are considered equal only if they are the \emph{same} table.
993In particular,
994equality is a constant-time operation and does not depend on the size of the
995strings or tables.
996 981
997Every time you create a new table (or string, userdata, or function), 982Every time you create a new table (or userdata, or function),
998this new value is different from any previously existing value. 983this new value is different from any previously existing value.
999In particular,
1000this is true for strings,
1001even if a string is built in different ways.
1002For example, all strings below are equal,
1003that is, they are the \emph{same} string:
1004\begin{verbatim}
1005 "Lua" .. " 4.1"
1006 "Lua " .. "4.1"
1007 "Lua 4.1"
1008\end{verbatim}
1009 984
1010\NOTE 985\NOTE
1011The conversion rules of \See{coercion} 986The conversion rules of \See{coercion}
@@ -1020,18 +995,9 @@ The operator \verb|~=| is exactly the negation of equality (\verb|==|).
1020The order operators work as follows. 995The order operators work as follows.
1021If both arguments are numbers, then they are compared as such. 996If both arguments are numbers, then they are compared as such.
1022Otherwise, if both arguments are strings, 997Otherwise, if both arguments are strings,
1023then their values are compared according to the current locale (see below). 998then their values are compared according to the current locale.
1024Otherwise, the ``lt'' tag method is called \see{tag-method}. 999Otherwise, the ``lt'' tag method is called \see{tag-method}.
1025 1000
1026String comparison according to the current locale
1027means that
1028if you sort strings using \verb|<=|,
1029then
1030\emph{\'agua} will appear before \emph{book}
1031and close to all other strings beginning with \emph{ag},
1032even though \emph{\'a}~appears after \emph{b} in the usual ISO Latin encoding.
1033\index{string comparison}
1034
1035 1001
1036\subsubsection{Logical Operators} 1002\subsubsection{Logical Operators}
1037The \Index{logical operators} in Lua are 1003The \Index{logical operators} in Lua are
@@ -1141,7 +1107,7 @@ is equivalent to
1141If the last expression in the list is a function call, 1107If the last expression in the list is a function call,
1142then all values returned by the call enter the list consecutively 1108then all values returned by the call enter the list consecutively
1143\see{functioncall}. 1109\see{functioncall}.
1144To avoid this, 1110If you want to avoid this,
1145enclose the function call in parentheses. 1111enclose the function call in parentheses.
1146 1112
1147The form \emph{ffieldlist1} initializes other fields in a table: 1113The form \emph{ffieldlist1} initializes other fields in a table:
@@ -1168,7 +1134,7 @@ An expression like \verb|{x = 1, y = 4}| is
1168in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. 1134in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|.
1169 1135
1170Both forms may have an optional trailing comma 1136Both forms may have an optional trailing comma
1171(for convinence of machine-generated code), 1137(for convenience of machine-generated code),
1172and can be used in the same constructor separated by 1138and can be used in the same constructor separated by
1173a semi-colon. 1139a semi-colon.
1174For example, all forms below are correct. 1140For example, all forms below are correct.
@@ -1285,12 +1251,11 @@ whose value has type \emph{function}.
1285When Lua pre-compiles a chunk, 1251When Lua pre-compiles a chunk,
1286all its function bodies are pre-compiled too. 1252all its function bodies are pre-compiled too.
1287Then, whenever Lua executes the function definition, 1253Then, whenever Lua executes the function definition,
1288its upvalues (if any) are fixed \see{upvalue}, 1254the function is \emph{instantiated} (or \emph{closed}).
1289and the function is \emph{instantiated} (or \emph{closed}).
1290This function instance (or \emph{closure}) 1255This function instance (or \emph{closure})
1291is the final value of the expression. 1256is the final value of the expression.
1292Different instances of the same function 1257Different instances of the same function
1293may have different upvalues. 1258may refer to different non-local variables \see{visibility}.
1294 1259
1295Parameters act as local variables, 1260Parameters act as local variables,
1296initialized with the argument values: 1261initialized with the argument values:
@@ -1350,62 +1315,61 @@ is syntactic sugar for
1350\begin{verbatim} 1315\begin{verbatim}
1351 t.a.b.c.f = function (self, ...) ... end 1316 t.a.b.c.f = function (self, ...) ... end
1352\end{verbatim} 1317\end{verbatim}
1353Note that the function gets an extra formal parameter called \verb|self|.
1354
1355
1356\subsection{Visibility and Upvalues} \label{upvalue}
1357\index{visibility}\index{upvalues}
1358
1359A function body may refer to its own local variables
1360(which include its parameters) and to global variables,
1361as long as they are not \emph{shadowed} by local
1362variables with the same name from enclosing functions.
1363A function \emph{cannot} access a local
1364variable from an enclosing function,
1365since such variables may no longer exist when the function is called.
1366However, a function may access the \emph{value} of a local variable
1367from an enclosing function, using \emph{upvalues},
1368whose syntax is
1369\begin{Produc}
1370\produc{upvalue}{\ter{\%} name}
1371\end{Produc}%
1372 1318
1373An upvalue is somewhat similar to a variable expression,
1374but whose value is \emph{frozen} when the function in which it
1375appears is instantiated.
1376The name used in an upvalue may be the name of any variable visible
1377at the point where the function is defined,
1378that is,
1379global variables and local variables
1380from the \emph{immediately enclosing} function.
1381 1319
1382Note that when the upvalue is a table, 1320\subsection{Visibility Rules} \label{visibility}
1383only the \emph{reference} to that table 1321\index{visibility}
1384(which is the value of the upvalue) is frozen;
1385the table contents can be changed at will.
1386Using table values as upvalues is a technique for having
1387writable but private state attached to functions.
1388 1322
1389Here are some examples: 1323Lua is a lexically scoped language.
1324The scope of local variables begins at the first statement \emph{after}
1325their declaration and lasts until the end of the innermost block that
1326includes the declaration.
1327For instance:
1390\begin{verbatim} 1328\begin{verbatim}
1391 a,b,c = 1,2,3 -- global variables 1329 x = 10 -- global variable
1392 local d 1330 do -- new block
1393 function f (x) 1331 local x = x -- new `x', with value 10
1394 local b = {} -- x and b are local to f; b shadows the global b 1332 print(x) --> 10
1395 local g = function (a) 1333 x = x+1
1396 local y -- a and y are local to g 1334 do -- another block
1397 p = a -- OK, access local `a' 1335 local x = x+1 -- another x
1398 p = c -- OK, access global `c' 1336 print(x) --> 12
1399 p = b -- ERROR: cannot access a variable in outer function 1337 end
1400 p = %b -- OK, access frozen value of `b' (local to `f') 1338 print(x) --> 11
1401 %b = 3 -- ERROR: cannot change an upvalue 1339 end
1402 %b.x = 3 -- OK, change the table contents 1340 print(x) --> 10 (the global one)
1403 p = %c -- OK, access frozen value of global `c'
1404 p = %y -- ERROR: `y' is not visible where `g' is defined
1405 p = %d -- ERROR: `d' is not visible where `g' is defined
1406 end -- g
1407 end -- f
1408\end{verbatim} 1341\end{verbatim}
1342Notice that, in a declaration like \verb|local x = x|,
1343the new \verb|x| being declared is not in scope yet,
1344so the second \verb|x| refers to the ``outside'' variable.
1345
1346Because of this \Index{lexical scoping} rules,
1347local variables can be freely accessed by functions
1348defined inside their scope.
1349For instance:
1350\begin{verbatim}
1351 local counter = 0
1352 function inc (x)
1353 counter = counter + x
1354 return counter
1355 end
1356\end{verbatim}
1357
1358Notice that each execution of a \rwd{local} statement
1359``creates'' new local variables.
1360Consider the following example:
1361\begin{verbatim}
1362 a = {}
1363 local x = 20
1364 for i=1,10 do
1365 local y = 0
1366 a[i] = function () y=y+1; return x+y end
1367 end
1368\end{verbatim}
1369In that code,
1370each function uses a different \verb|y| variable,
1371while all of them share the same \verb|x|.
1372
1409 1373
1410 1374
1411\subsection{Error Handling} \label{error} 1375\subsection{Error Handling} \label{error}
@@ -1437,9 +1401,9 @@ The default definition for
1437this function calls \verb|_ALERT|, \DefLIB{_ALERT} 1401this function calls \verb|_ALERT|, \DefLIB{_ALERT}
1438which prints the message to \verb|stderr| \see{alert}. 1402which prints the message to \verb|stderr| \see{alert}.
1439The standard I/O library redefines \verb|_ERRORMESSAGE| 1403The standard I/O library redefines \verb|_ERRORMESSAGE|
1440and uses the debug facilities \see{debugI} 1404and uses the debug interface \see{debugI}
1441to print some extra information, 1405to print some extra information,
1442such as a call stack traceback. 1406such as a call-stack traceback.
1443 1407
1444Lua code can explicitly generate an error by calling the 1408Lua code can explicitly generate an error by calling the
1445function \verb|error| \see{pdf-error}. 1409function \verb|error| \see{pdf-error}.
@@ -1458,7 +1422,7 @@ Lua selects the tag method called for any specific event
1458according to the types of the values involved 1422according to the types of the values involved
1459in the event \see{TypesSec}. 1423in the event \see{TypesSec}.
1460The function \IndexLIB{settagmethod} changes the tag method 1424The function \IndexLIB{settagmethod} changes the tag method
1461associated with a given pair (\M{type}, \M{event}). 1425associated with a given (\M{type}, \M{event}) pair.
1462The first parameter to \verb|settagmethod| is the type 1426The first parameter to \verb|settagmethod| is the type
1463(represented by its name or tag), 1427(represented by its name or tag),
1464the second parameter is the event name (a string; see below), 1428the second parameter is the event name (a string; see below),
@@ -1466,7 +1430,7 @@ and the third parameter is the new method (a function),
1466or \nil\ to restore the default behavior for the pair. 1430or \nil\ to restore the default behavior for the pair.
1467A companion function \IndexLIB{gettagmethod} 1431A companion function \IndexLIB{gettagmethod}
1468receives a type and an event name and returns the 1432receives a type and an event name and returns the
1469current method associated with the pair. 1433current method associated to them.
1470 1434
1471Tag methods are called in the following events, 1435Tag methods are called in the following events,
1472identified by the given names. 1436identified by the given names.
@@ -1850,11 +1814,11 @@ For convenience,
1850most query operations in the API do not follow a strict stack discipline. 1814most query operations in the API do not follow a strict stack discipline.
1851Instead, they can refer to any element in the stack by using an \emph{index}: 1815Instead, they can refer to any element in the stack by using an \emph{index}:
1852A positive index represents an \emph{absolute} stack position 1816A positive index represents an \emph{absolute} stack position
1853(starting at~1, not 0 as in C); 1817(starting at~1);
1854a negative index represents an \emph{offset} from the top of the stack. 1818a negative index represents an \emph{offset} from the top of the stack.
1855More specifically, if the stack has \M{n} elements, 1819More specifically, if the stack has \M{n} elements,
1856then index~1 represents the first element 1820then index~1 represents the first element
1857(that is, the first element pushed onto the stack), 1821(that is, the element that was pushed onto the stack first),
1858and 1822and
1859index~\M{n} represents the last element; 1823index~\M{n} represents the last element;
1860index~\Math{-1} also represents the last element 1824index~\Math{-1} also represents the last element
@@ -1886,8 +1850,8 @@ Whenever Lua calls C, \DefAPI{LUA_MINSTACK}
1886it ensures that 1850it ensures that
1887at least \verb|LUA_MINSTACK| positions are still available. 1851at least \verb|LUA_MINSTACK| positions are still available.
1888\verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16, 1852\verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16,
1889so that usually you have to worry about stack space only 1853so that usually you do not have to worry about stack space
1890when your code has loops pushing elements onto the stack. 1854unless your code has loops pushing elements onto the stack.
1891 1855
1892Most query functions accept as indices any value inside the 1856Most query functions accept as indices any value inside the
1893available stack space. 1857available stack space.
@@ -1899,6 +1863,15 @@ as follows:
1899\end{verbatim} 1863\end{verbatim}
1900Note that 0 is not an acceptable index. 1864Note that 0 is not an acceptable index.
1901 1865
1866Unless otherwise noticed,
1867any function that accepts valid indices can also be called with
1868\Index{pseudo-indices},
1869which represent some Lua values that are accessible to the C~code
1870but are not in the stack.
1871
1872Pseudo-indices are used to access the registry
1873and the upvalues of a C function \see{c-closure}.
1874
1902\subsection{Stack Manipulation} 1875\subsection{Stack Manipulation}
1903The API offers the following functions for basic stack manipulation: 1876The API offers the following functions for basic stack manipulation:
1904\begin{verbatim} 1877\begin{verbatim}
@@ -1930,6 +1903,8 @@ shifting down the elements above that position to fill the gap.
1930\verb|lua_insert| moves the top element into the given position, 1903\verb|lua_insert| moves the top element into the given position,
1931shifting up the elements above that position to open space. 1904shifting up the elements above that position to open space.
1932These functions accept only valid indices. 1905These functions accept only valid indices.
1906(Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with
1907pseudo-indices, as they do not represent a stack position.)
1933 1908
1934As an example, if the stack starts as \verb|10 20 30 40 50*| 1909As an example, if the stack starts as \verb|10 20 30 40 50*|
1935(from bottom to top; the \verb|*| marks the top), 1910(from bottom to top; the \verb|*| marks the top),
@@ -1946,6 +1921,7 @@ then
1946\end{verbatim} 1921\end{verbatim}
1947 1922
1948 1923
1924
1949\subsection{Querying the Stack} 1925\subsection{Querying the Stack}
1950 1926
1951To check the type of a stack element, 1927To check the type of a stack element,
@@ -2036,8 +2012,10 @@ otherwise, the function returns \verb|NULL|.
2036If the value is a number, 2012If the value is a number,
2037then \verb|lua_tostring| also 2013then \verb|lua_tostring| also
2038\emph{changes the actual value in the stack to a string}. 2014\emph{changes the actual value in the stack to a string}.
2039This change confuses \verb|lua_next| when \verb|lua_tostring| is applied to keys. 2015(This change confuses \verb|lua_next|
2040\verb|lua_tostring| returns a fully aligned pointer to a string inside the Lua environment. 2016when \verb|lua_tostring| is applied to keys.)
2017\verb|lua_tostring| returns a fully aligned pointer
2018to a string inside the Lua environment.
2041This string always has a zero (\verb|'\0'|) 2019This string always has a zero (\verb|'\0'|)
2042after its last character (as in~C), 2020after its last character (as in~C),
2043but may contain other zeros in its body. 2021but may contain other zeros in its body.
@@ -2047,7 +2025,7 @@ Because Lua has garbage collection,
2047there is no guarantee that the pointer returned by \verb|lua_tostring| 2025there is no guarantee that the pointer returned by \verb|lua_tostring|
2048will be valid after the corresponding value is removed from the stack. 2026will be valid after the corresponding value is removed from the stack.
2049So, if you need the string after the current function returns, 2027So, if you need the string after the current function returns,
2050then you should duplicate it (or lock it; see \See{lock}). 2028then you should duplicate it (or put it into the registry \see{registry}).
2051 2029
2052\verb|lua_tocfunction| converts a value in the stack to a C~function. 2030\verb|lua_tocfunction| converts a value in the stack to a C~function.
2053This value must be a C~function; 2031This value must be a C~function;
@@ -2078,7 +2056,7 @@ These functions receive a C~value,
2078convert it to a corresponding Lua value, 2056convert it to a corresponding Lua value,
2079and push the result onto the stack. 2057and push the result onto the stack.
2080In particular, \verb|lua_pushlstring| and \verb|lua_pushstring| 2058In particular, \verb|lua_pushlstring| and \verb|lua_pushstring|
2081make an \emph{internal copy} of the given string. 2059make an internal copy of the given string.
2082\verb|lua_pushstring| can only be used to push proper C~strings 2060\verb|lua_pushstring| can only be used to push proper C~strings
2083(that is, strings that end with a zero and do not contain embedded zeros); 2061(that is, strings that end with a zero and do not contain embedded zeros);
2084otherwise, you should use the more general \verb|lua_pushlstring|, 2062otherwise, you should use the more general \verb|lua_pushlstring|,
@@ -2141,7 +2119,7 @@ By default, all userdata are created with a standard tag,
2141 2119
2142When Lua collects a userdata created by \verb|lua_newuserdata|, 2120When Lua collects a userdata created by \verb|lua_newuserdata|,
2143it automatically frees its corresponding memory. 2121it automatically frees its corresponding memory.
2144On the other hand, Lua never uses pointers in 2122On the other hand, Lua never accesses pointers in
2145userdata created with \verb|lua_newuserdatabox|; 2123userdata created with \verb|lua_newuserdatabox|;
2146it is up to you to free any associated memory, 2124it is up to you to free any associated memory,
2147setting a garbage-collection tag method, for instance. 2125setting a garbage-collection tag method, for instance.
@@ -2392,7 +2370,8 @@ A typical traversal looks like this:
2392\end{verbatim} 2370\end{verbatim}
2393 2371
2394NOTE: 2372NOTE:
2395Do not call \verb|lua_tostring| on a key, 2373While traversing a table,
2374do not call \verb|lua_tostring| on a key,
2396unless you know the key is actually a string. 2375unless you know the key is actually a string.
2397Recall that \verb|lua_tostring| \emph{changes} the value at the given index; 2376Recall that \verb|lua_tostring| \emph{changes} the value at the given index;
2398this confuses \verb|lua_next|. 2377this confuses \verb|lua_next|.
@@ -2406,7 +2385,7 @@ The following functions control the weak mode of a table:
2406Both functions operate over the table at the top of the stack. 2385Both functions operate over the table at the top of the stack.
2407Modes are described as bit sets, so that 2386Modes are described as bit sets, so that
2408\verb|LUA_WEAK_KEY| means weak keys, 2387\verb|LUA_WEAK_KEY| means weak keys,
2409\verb|LUA_WEAK_VALUE| means weak values, 2388\verb|LUA_WEAK_VALUE| means weak values, the combination
2410\verb"LUA_WEAK_KEY | LUA_WEAK_VALUE" means both, 2389\verb"LUA_WEAK_KEY | LUA_WEAK_VALUE" means both,
2411and zero means none. 2390and zero means none.
2412 2391
@@ -2609,93 +2588,51 @@ by calling
2609 lua_register(L, "average", foo); 2588 lua_register(L, "average", foo);
2610\end{verbatim} 2589\end{verbatim}
2611 2590
2612\subsection{Defining C Closures} 2591\subsection{Defining C Closures} \label{c-closure}
2613 2592
2614When a C~function is created, 2593When a C~function is created,
2615it is possible to associate some \emph{upvalues} to it 2594it is possible to associate some values to it,
2616\see{upvalue},
2617thus creating a \IndexEmph{C~closure}; 2595thus creating a \IndexEmph{C~closure};
2618these values are passed to the function whenever it is called, 2596these values are then accessible to the function whenever it is called.
2619as ordinary arguments. 2597To associate values to a C~function,
2620To associate upvalues to a C~function,
2621first these values should be pushed onto the stack 2598first these values should be pushed onto the stack
2622(when there are multiple upvalues, 2599(when there are multiple values, the first value is pushed first).
2623the first upvalue is pushed first).
2624Then the function 2600Then the function
2625\begin{verbatim} 2601\begin{verbatim}
2626 void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); 2602 void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
2627\end{verbatim} 2603\end{verbatim}
2628\DefAPI{lua_pushcclosure} 2604\DefAPI{lua_pushcclosure}
2629is used to push the C~function onto the stack, 2605is used to push the C~function onto the stack,
2630with the argument \verb|n| telling how many upvalues should be 2606with the argument \verb|n| telling how many values should be
2631associated with the function 2607associated with the function
2632(these upvalues are popped from the stack); 2608(\verb|lua_pushcclosure| also pops these values from the stack);
2633in fact, the macro \verb|lua_pushcfunction| is defined as 2609in fact, the macro \verb|lua_pushcfunction| is defined as
2634\verb|lua_pushcclosure| with \verb|n| set to 0. 2610\verb|lua_pushcclosure| with \verb|n| set to 0.
2611
2635Then, whenever the C~function is called, 2612Then, whenever the C~function is called,
2636these upvalues are inserted as the \emph{last} arguments to the function, 2613those values are located at specific pseudo-indices.
2637after the actual arguments provided in the call. 2614Those pseudo-indices are produced by a macro \IndexAPI{lua_upvalueindex}.
2638This makes it easy to get the upvalues without knowing how many arguments 2615The first value associated with a function is at position
2639the function received (recall that functions in Lua can receive any number of 2616\verb|lua_upvalueindex(1)|, and so on.
2640arguments): The \M{i}-th upvalue is in the stack at index \Math{i-(n+1)},
2641where \M{n} is the number of upvalues.
2642(A C~function that uses upvalues must know beforehand how many it expects.)
2643 2617
2644For examples of C~functions and closures, see files 2618For examples of C~functions and closures, see files
2645\verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c| 2619\verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c|
2646in the official Lua distribution. 2620in the official Lua distribution.
2647 2621
2648\subsection{References to Lua Values} \label{lock}
2649 2622
2650If the C~code needs to keep a Lua value 2623\subsubsection*{Registry} \label{registry}
2651outside the life span of a C~function, 2624
2652then it must create a \Def{reference} to the value. 2625Lua provides a pre-defined table that can be used by any C~code to
2653The functions to manipulate references are the following: 2626store whatever Lua value it needs to store,
2654\begin{verbatim} 2627especially if the C~code needs to keep that Lua value
2655 int lua_ref (lua_State *L, int lock); 2628outside the life span of a C~function.
2656 int lua_getref (lua_State *L, int ref); 2629This table is always located at pseudo-index
2657 void lua_unref (lua_State *L, int ref); 2630\IndexAPI{LUA_REGISTRYINDEX}.
2658\end{verbatim}
2659\DefAPI{lua_ref}\DefAPI{lua_getref}\DefAPI{lua_unref}
2660
2661\verb|lua_ref| pops a value from
2662the stack, creates a reference to it,
2663and returns this reference.
2664For a \nil\ value,
2665the reference is always \verb|LUA_REFNIL|.\DefAPI{LUA_REFNIL}
2666%% TODO: why LUA_REFNIL? pode-se chamar lua_getref(L,LUA_REFNIL)?
2667(\verb|lua.h| also defines a constant \verb|LUA_NOREF| \DefAPI{LUA_NOREF}
2668that
2669is different from any valid reference.)
2670%% TODO: give example of use of LUA_NOREF
2671If \verb|lock| is not zero, then the object is \emph{locked}:
2672this means the object will not be garbage collected.
2673\emph{Unlocked references may be garbage collected}.
2674
2675Whenever the referenced object is needed in~C,
2676a call to \verb|lua_getref|
2677pushes that object onto the stack;
2678if the object has been collected,
2679\verb|lua_getref| returns 0 (and does not push anything).
2680
2681When a reference is no longer needed,
2682it should be released with a call to \verb|lua_unref|.
2683
2684
2685\subsubsection*{Registry}
2686%% TODO: nao precisa de secao propria? explicar melhor o uso.
2687
2688When Lua starts, it registers a table at position
2689\IndexAPI{LUA_REFREGISTRY}.
2690It can be accessed through the macro
2691\begin{verbatim}
2692 #define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY)
2693\end{verbatim}
2694\DefAPI{lua_getregistry}
2695This table can be used by C~libraries as a general registry mechanism.
2696Any C~library can store data into this table, 2631Any C~library can store data into this table,
2697as long as it chooses a key different from other libraries. 2632as long as it chooses a key different from other libraries.
2698 2633The integer keys in the registry are used by the reference mechanism,
2634implemented by the auxiliar library,
2635and therefore should not be used by other purposes.
2699 2636
2700 2637
2701%------------------------------------------------------------------------------ 2638%------------------------------------------------------------------------------
@@ -2823,7 +2760,7 @@ If the function is a global variable,
2823\verb|namewhat| is \verb|"global"|; 2760\verb|namewhat| is \verb|"global"|;
2824if the function is a tag method, 2761if the function is a tag method,
2825\verb|namewhat| is \verb|"tag-method"|; 2762\verb|namewhat| is \verb|"tag-method"|;
2826otherwise, \verb|namewhat| is \verb|""| (the empty string). 2763otherwise, it is \verb|""| (the empty string).
2827 2764
2828\item[nups] 2765\item[nups]
2829Number of upvalues of the function. 2766Number of upvalues of the function.
@@ -2899,7 +2836,7 @@ set their corresponding hooks and return their previous values.
2899 2836
2900The call hook is called whenever the 2837The call hook is called whenever the
2901interpreter enters or leaves a function. 2838interpreter enters or leaves a function.
2902The \verb|event| field of \verb|ar| has the strings \verb|"call"| 2839The \verb|event| field of \verb|ar| has the string \verb|"call"|
2903or \verb|"return"|. 2840or \verb|"return"|.
2904This \verb|ar| can then be used in calls to \verb|lua_getinfo|, 2841This \verb|ar| can then be used in calls to \verb|lua_getinfo|,
2905\verb|lua_getlocal|, and \verb|lua_setlocal| 2842\verb|lua_getlocal|, and \verb|lua_setlocal|
@@ -2909,7 +2846,7 @@ local variables.
2909The line hook is called every time the interpreter changes 2846The line hook is called every time the interpreter changes
2910the line of code it is executing. 2847the line of code it is executing.
2911The \verb|event| field of \verb|ar| has the string \verb|"line"|, 2848The \verb|event| field of \verb|ar| has the string \verb|"line"|,
2912and the \verb|currentline| field has the line number. 2849and the \verb|currentline| field has the new line number.
2913Again, you can use this \verb|ar| in other calls to the debug API. 2850Again, you can use this \verb|ar| in other calls to the debug API.
2914 2851
2915While Lua is running a hook, it disables other calls to hooks. 2852While Lua is running a hook, it disables other calls to hooks.
@@ -3013,11 +2950,6 @@ then Lua immediately runs the garbage collector \see{GC}.
3013If \verb|limit| is absent, it defaults to zero 2950If \verb|limit| is absent, it defaults to zero
3014(thus forcing a garbage-collection cycle). 2951(thus forcing a garbage-collection cycle).
3015 2952
3016\subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}}
3017\DefLIB{copytagmethods}
3018Copies all tag methods from one tag to another;
3019returns \verb|tagto|.
3020
3021\subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile} 2953\subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile}
3022Receives a file name, 2954Receives a file name,
3023opens the named file, and executes its contents as a Lua chunk. 2955opens the named file, and executes its contents as a Lua chunk.
@@ -3044,13 +2976,13 @@ The optional parameter \verb|chunkname|
3044is the ``name of the chunk'', 2976is the ``name of the chunk'',
3045used in error messages and debug information. 2977used in error messages and debug information.
3046 2978
3047\subsubsection*{\ff \T{error (message)}}\DefLIB{error}\label{pdf-error} 2979\subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error}
3048Calls the error handler \see{error} and then terminates 2980Calls the error handler \see{error} and then terminates
3049the last protected function called 2981the last protected function called
3050(in~C: \verb|lua_dofile|, \verb|lua_dostring|, 2982(in~C: \verb|lua_dofile|, \verb|lua_dostring|,
3051\verb|lua_dobuffer|, or \verb|lua_callfunction|; 2983\verb|lua_dobuffer|, or \verb|lua_callfunction|;
3052in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). 2984in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode).
3053If \verb|message| is \nil, then the error handler is not called. 2985If \verb|message| is absent, the error handler is not called.
3054Function \verb|error| never returns. 2986Function \verb|error| never returns.
3055 2987
3056\subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach} 2988\subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach}
@@ -3522,11 +3454,11 @@ Here are some examples:
3522 --> x="4+5 = 9" 3454 --> x="4+5 = 9"
3523 3455
3524 local t = {name="Lua", version="4.1"} 3456 local t = {name="Lua", version="4.1"}
3525 x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) 3457 x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end)
3526 --> x="Lua - 4.1" 3458 --> x="Lua - 4.1"
3527 3459
3528 local t = {n=0} 3460 local t = {}
3529 gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) 3461 gsub("first second word", "(%w+)", function (w) tinsert(t, w) end)
3530 --> t={"first", "second", "word"; n=3} 3462 --> t={"first", "second", "word"; n=3}
3531\end{verbatim} 3463\end{verbatim}
3532 3464