diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2002-08-06 16:10:44 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2002-08-06 16:10:44 -0300 |
commit | a56e01a9a04be72d05987fb7610b60b9bd047234 (patch) | |
tree | 7806070e048b4752a859ea18c2a2f14803a485c9 | |
parent | 4664f2e9270a956f6175481abe590ba4931b7477 (diff) | |
download | lua-a56e01a9a04be72d05987fb7610b60b9bd047234.tar.gz lua-a56e01a9a04be72d05987fb7610b60b9bd047234.tar.bz2 lua-a56e01a9a04be72d05987fb7610b60b9bd047234.zip |
towards 5.0 alpha...
-rw-r--r-- | manual.tex | 1537 |
1 files changed, 811 insertions, 726 deletions
@@ -1,4 +1,4 @@ | |||
1 | % $Id: manual.tex,v 1.55 2002/02/14 21:48:32 roberto Exp roberto $ | 1 | % $Id: manual.tex,v 1.56 2002/06/06 12:49:28 roberto Exp roberto $ |
2 | 2 | ||
3 | \documentclass[11pt,twoside,draft]{article} | 3 | \documentclass[11pt,twoside,draft]{article} |
4 | \usepackage{fullpage} | 4 | \usepackage{fullpage} |
@@ -35,13 +35,14 @@ | |||
35 | 35 | ||
36 | \newcommand{\ff}{$\bullet$\ } | 36 | \newcommand{\ff}{$\bullet$\ } |
37 | 37 | ||
38 | \newcommand{\Version}{4.1 (beta)} | 38 | \newcommand{\Version}{5.0 (alpha)} |
39 | 39 | ||
40 | % changes to bnf.sty by LHF | 40 | % changes to bnf.sty by LHF |
41 | \renewcommand{\Or}{$|$ } | 41 | \renewcommand{\Or}{$|$ } |
42 | \renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}} | 42 | \renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}} |
43 | \renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}} | 43 | \renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}} |
44 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} | 44 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} |
45 | \newcommand{\Nter}[1]{{\tt#1}} | ||
45 | \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } | 46 | \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } |
46 | 47 | ||
47 | \makeindex | 48 | \makeindex |
@@ -132,7 +133,7 @@ Waldemar Celes | |||
132 | \tecgraf\ --- Computer Science Department --- PUC-Rio | 133 | \tecgraf\ --- Computer Science Department --- PUC-Rio |
133 | } | 134 | } |
134 | 135 | ||
135 | %\date{{\small \tt\$Date: 2002/02/14 21:48:32 $ $}} | 136 | %\date{{\small \tt\$Date: 2002/06/06 12:49:28 $ $}} |
136 | 137 | ||
137 | \maketitle | 138 | \maketitle |
138 | 139 | ||
@@ -272,10 +273,6 @@ If necessary, | |||
272 | the host programmer can create multiple independent global | 273 | the host programmer can create multiple independent global |
273 | environments, and freely switch between them \see{mangstate}. | 274 | environments, and freely switch between them \see{mangstate}. |
274 | 275 | ||
275 | The global environment can be manipulated by Lua code or | ||
276 | by the embedding program, | ||
277 | using the API functions from the library that implements Lua. | ||
278 | |||
279 | The unit of execution of Lua is called a \Def{chunk}. | 276 | The unit of execution of Lua is called a \Def{chunk}. |
280 | A chunk is simply a sequence of statements. | 277 | A chunk is simply a sequence of statements. |
281 | Statements are described in \See{stats}. | 278 | Statements are described in \See{stats}. |
@@ -299,9 +296,9 @@ Lua automatically detects the file type and acts accordingly. | |||
299 | \subsection{\Index{Values and Types}} \label{TypesSec} | 296 | \subsection{\Index{Values and Types}} \label{TypesSec} |
300 | 297 | ||
301 | Lua is a \emph{dynamically typed language}. | 298 | Lua is a \emph{dynamically typed language}. |
302 | This means that | 299 | That means that |
303 | variables do not have types; only values do. | 300 | variables do not have types; only values do. |
304 | Therefore, there are no type definitions in the language. | 301 | There are no type definitions in the language. |
305 | All values carry their own type. | 302 | All values carry their own type. |
306 | 303 | ||
307 | There are seven \Index{basic types} in Lua: | 304 | There are seven \Index{basic types} in Lua: |
@@ -310,8 +307,8 @@ There are seven \Index{basic types} in Lua: | |||
310 | \emph{Nil} is the type of the value \nil, | 307 | \emph{Nil} is the type of the value \nil, |
311 | whose main property is to be different from any other value; | 308 | whose main property is to be different from any other value; |
312 | usually it represents the absence of a useful value. | 309 | usually it represents the absence of a useful value. |
313 | \emph{Boolean} is the type of the values \False and \True. | 310 | \emph{Boolean} is the type of the values \False{} and \True. |
314 | In Lua, both \nil{} and \False make a condition fails, | 311 | In Lua, both \nil{} and \False{} make a condition fails, |
315 | and any other value makes it succeeds. | 312 | and any other value makes it succeeds. |
316 | \emph{Number} represents real (double-precision floating-point) numbers. | 313 | \emph{Number} represents real (double-precision floating-point) numbers. |
317 | \emph{String} represents arrays of characters. | 314 | \emph{String} represents arrays of characters. |
@@ -321,17 +318,17 @@ and so strings may contain any 8-bit character, | |||
321 | including embedded zeros (\verb|'\0'|) \see{lexical}. | 318 | including embedded zeros (\verb|'\0'|) \see{lexical}. |
322 | 319 | ||
323 | Functions are \emph{first-class values} in Lua. | 320 | Functions are \emph{first-class values} in Lua. |
324 | This means that functions can be stored in variables, | 321 | That means that functions can be stored in variables, |
325 | passed as arguments to other functions, and returned as results. | 322 | passed as arguments to other functions, and returned as results. |
326 | Lua can call (and manipulate) functions written in Lua and | 323 | Lua can call (and manipulate) functions written in Lua and |
327 | functions written in C | 324 | functions written in C |
328 | \see{functioncall}. | 325 | \see{functioncall}. |
329 | 326 | ||
330 | The type \emph{userdata} is provided to allow | 327 | The type \emph{userdata} is provided to allow the store of |
331 | arbitrary \Index{C~pointers} to be stored in Lua variables. | 328 | arbitrary C data in Lua variables. |
332 | This type corresponds to a \verb|void*| | 329 | This type corresponds to a block of raw memory |
333 | and has no pre-defined operations in Lua, | 330 | and has no pre-defined operations in Lua, |
334 | except assignment and equality test. | 331 | except assignment and identity test. |
335 | However, by using \emph{metatables}, | 332 | However, by using \emph{metatables}, |
336 | the programmer can define operations for userdata values | 333 | the programmer can define operations for userdata values |
337 | \see{metatables}. | 334 | \see{metatables}. |
@@ -370,6 +367,7 @@ and do not imply any kind of copy. | |||
370 | The library function \verb|type| returns a string describing the type | 367 | The library function \verb|type| returns a string describing the type |
371 | of a given value \see{pdf-type}. | 368 | of a given value \see{pdf-type}. |
372 | 369 | ||
370 | |||
373 | \subsubsection{Metatables} | 371 | \subsubsection{Metatables} |
374 | 372 | ||
375 | Each table or userdata object in Lua may have a \Index{metatable}. | 373 | Each table or userdata object in Lua may have a \Index{metatable}. |
@@ -377,28 +375,29 @@ Each table or userdata object in Lua may have a \Index{metatable}. | |||
377 | You can change several aspects of the behavior | 375 | You can change several aspects of the behavior |
378 | of an object by setting specific fields in its metatable. | 376 | of an object by setting specific fields in its metatable. |
379 | For instance, when an object is the operand of an addition, | 377 | For instance, when an object is the operand of an addition, |
380 | Lua checks for a function in the field \verb|"add"| in its metatable. | 378 | Lua checks for a function in the field \verb|"__add"| in its metatable. |
381 | If it finds one, | 379 | If it finds one, |
382 | Lua calls that function to perform the addition. | 380 | Lua calls that function to perform the addition. |
383 | 381 | ||
384 | A metatable works as a kind of an extended ``type'' for the object: | 382 | We call the keys in a metatable \Index{events}, |
385 | Objects that share a metatable has identical behavior. | 383 | and the values \Index{metamethods}. |
384 | In the previous example, \verb|"add"| is the event, | ||
385 | and the metamethod is the function that performs the addition. | ||
386 | 386 | ||
387 | A metatable controls how an object behaves in arithmetic operations, | 387 | A metatable controls how an object behaves in arithmetic operations, |
388 | order comparisons, concatenation, and indexing. | 388 | order comparisons, concatenation, and indexing. |
389 | A metatable can also defines a function to be called when a userdata | 389 | A metatable can also defines a function to be called when a userdata |
390 | is garbage collected, | 390 | is garbage collected. |
391 | and how the garbage collector treats entries in a table | ||
392 | \see{weak-table}. | ||
393 | \See{metatable} gives a detailed description of which events you | 391 | \See{metatable} gives a detailed description of which events you |
394 | can control with metatables. | 392 | can control with metatables. |
395 | 393 | ||
396 | You can query and change the metatable of an object | 394 | You can query and change the metatable of an object |
397 | through the \verb|metatable| function \see{pdf-metatable}. | 395 | through the \verb|setmetatable| and \verb|getmetatable| |
396 | functions \see{pdf-getmetatable}. | ||
398 | 397 | ||
399 | 398 | ||
400 | 399 | ||
401 | \subsection{\Index{Coercion}} \label{coercion} | 400 | \subsection{Coercion} \label{coercion} |
402 | 401 | ||
403 | Lua provides automatic conversion between | 402 | Lua provides automatic conversion between |
404 | string and number values at run time. | 403 | string and number values at run time. |
@@ -437,7 +436,7 @@ defined inside their scope \see{visibility}. | |||
437 | \subsection{Garbage Collection}\label{GC} | 436 | \subsection{Garbage Collection}\label{GC} |
438 | 437 | ||
439 | Lua does automatic memory management. | 438 | Lua does automatic memory management. |
440 | This means that | 439 | That means that |
441 | you do not have to worry about allocating memory for new objects | 440 | you do not have to worry about allocating memory for new objects |
442 | and freeing it when the objects are no longer needed. | 441 | and freeing it when the objects are no longer needed. |
443 | Lua manages memory automatically by running | 442 | Lua manages memory automatically by running |
@@ -449,11 +448,11 @@ All objects in Lua are subject to automatic management: | |||
449 | tables, userdata, functions, and strings. | 448 | tables, userdata, functions, and strings. |
450 | 449 | ||
451 | Using the C~API, | 450 | Using the C~API, |
452 | you can set garbage-collector tag methods for user-defined | 451 | you can set garbage-collector metamethods for userdata \see{metatable}. |
453 | types based on userdata \see{tag-method}. | 452 | When it is about to free a userdata, |
454 | Lua calls those functions when it is about to free a userdata | 453 | Lua calls the metamethod associated with event \verb|gc| in the |
455 | of the corresponding type. | 454 | userdata's metatable. |
456 | Using this facility, you can coordinate Lua's garbage collection | 455 | Using such facility, you can coordinate Lua's garbage collection |
457 | with external resource management | 456 | with external resource management |
458 | (such as closing files, network or database connections, | 457 | (such as closing files, network or database connections, |
459 | or freeing your own memory). | 458 | or freeing your own memory). |
@@ -493,8 +492,7 @@ A table with both weak keys and weak values allows the collection of | |||
493 | both keys and values. | 492 | both keys and values. |
494 | In any case, if either the key or the value is collected, | 493 | In any case, if either the key or the value is collected, |
495 | the whole pair is removed from the table. | 494 | the whole pair is removed from the table. |
496 | The weakness of a table is controled by the | 495 | The weakness of a table is set with the \verb|setmode| function. |
497 | \verb|__weakmode| field in its metatable \see{weakmode}. | ||
498 | 496 | ||
499 | 497 | ||
500 | %------------------------------------------------------------------------------ | 498 | %------------------------------------------------------------------------------ |
@@ -570,8 +568,8 @@ may contain nested \verb|[[| $\ldots$ \verb|]]| pairs, | |||
570 | and do not interpret escape sequences. | 568 | and do not interpret escape sequences. |
571 | For convenience, | 569 | For convenience, |
572 | when the opening \verb|[[| is immediately followed by a newline, | 570 | when the opening \verb|[[| is immediately followed by a newline, |
573 | this newline is not included in the string. | 571 | the newline is not included in the string. |
574 | This form is specially convenient for | 572 | That form is specially convenient for |
575 | writing strings that contain program pieces or | 573 | writing strings that contain program pieces or |
576 | other quoted strings. | 574 | other quoted strings. |
577 | As an example, in a system using ASCII | 575 | As an example, in a system using ASCII |
@@ -619,9 +617,8 @@ A single name can denote a global variable, a local variable, | |||
619 | or a formal parameter in a function | 617 | or a formal parameter in a function |
620 | (formal parameters are just local variables): | 618 | (formal parameters are just local variables): |
621 | \begin{Produc} | 619 | \begin{Produc} |
622 | \produc{var}{name} | 620 | \produc{var}{\Nter{Name}} |
623 | \end{Produc}% | 621 | \end{Produc}% |
624 | |||
625 | Square brackets are used to index a table: | 622 | Square brackets are used to index a table: |
626 | \begin{Produc} | 623 | \begin{Produc} |
627 | \produc{var}{prefixexp \ter{[} exp \ter{]}} | 624 | \produc{var}{prefixexp \ter{[} exp \ter{]}} |
@@ -632,7 +629,7 @@ and the second expression identifies a specific entry inside that table. | |||
632 | The syntax \verb|var.NAME| is just syntactic sugar for | 629 | The syntax \verb|var.NAME| is just syntactic sugar for |
633 | \verb|var["NAME"]|: | 630 | \verb|var["NAME"]|: |
634 | \begin{Produc} | 631 | \begin{Produc} |
635 | \produc{var}{prefixexp \ter{.} name} | 632 | \produc{var}{prefixexp \ter{.} \Nter{Name}} |
636 | \end{Produc}% | 633 | \end{Produc}% |
637 | 634 | ||
638 | The expression denoting the table to be indexed has a restricted syntax; | 635 | The expression denoting the table to be indexed has a restricted syntax; |
@@ -676,16 +673,6 @@ Each statement can be optionally followed by a semicolon: | |||
676 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} | 673 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} |
677 | \end{Produc}% | 674 | \end{Produc}% |
678 | 675 | ||
679 | The notation used above is the usual extended BNF, | ||
680 | in which | ||
681 | \rep{\emph{a}}~means 0 or more \emph{a}'s, and | ||
682 | \opt{\emph{a}}~means an optional \emph{a}. | ||
683 | Non-terminals are shown in \emph{italics}, | ||
684 | keywords are shown in {\bf bold}, | ||
685 | and other terminal symbols are shown in {\tt typewriter} font, | ||
686 | enclosed in single quotes. | ||
687 | The complete syntax of Lua in extended BNF is given on page~\pageref{BNF}. | ||
688 | |||
689 | \subsubsection{Blocks} | 676 | \subsubsection{Blocks} |
690 | A \Index{block} is a list of statements; | 677 | A \Index{block} is a list of statements; |
691 | syntactically, a block is equal to a chunk: | 678 | syntactically, a block is equal to a chunk: |
@@ -693,7 +680,7 @@ syntactically, a block is equal to a chunk: | |||
693 | \produc{block}{chunk} | 680 | \produc{block}{chunk} |
694 | \end{Produc}% | 681 | \end{Produc}% |
695 | 682 | ||
696 | A block may be explicitly delimited: | 683 | A block may be explicitly delimited to produce a single statement: |
697 | \begin{Produc} | 684 | \begin{Produc} |
698 | \produc{stat}{\rwd{do} block \rwd{end}} | 685 | \produc{stat}{\rwd{do} block \rwd{end}} |
699 | \end{Produc}% | 686 | \end{Produc}% |
@@ -763,9 +750,9 @@ Lua also has a \rwd{for} statement, in two flavors \see{for}. | |||
763 | 750 | ||
764 | The \Index{condition expression} \M{exp} of a | 751 | The \Index{condition expression} \M{exp} of a |
765 | control structure may return any value. | 752 | control structure may return any value. |
766 | All values different from \nil\ and \False\ are considered true | 753 | All values different from \nil{} and \False{} are considered true |
767 | (in particular, the number 0 and the empty string are also true); | 754 | (in particular, the number 0 and the empty string are also true); |
768 | both \False\ and \nil\ are considered false. | 755 | both \False{} and \nil{} are considered false. |
769 | 756 | ||
770 | The \rwd{return} statement is used to return values | 757 | The \rwd{return} statement is used to return values |
771 | from a function or from a chunk.\IndexKW{return} | 758 | from a function or from a chunk.\IndexKW{return} |
@@ -798,7 +785,7 @@ as in the idioms | |||
798 | because now \rwd{return} and \rwd{break} are the last statements in | 785 | because now \rwd{return} and \rwd{break} are the last statements in |
799 | their (inner) blocks. | 786 | their (inner) blocks. |
800 | In practice, | 787 | In practice, |
801 | these idioms are only used during debugging. | 788 | those idioms are only used during debugging. |
802 | (For instance, a line `\verb|do return end|' can be added at the | 789 | (For instance, a line `\verb|do return end|' can be added at the |
803 | beginning of a chunk for syntax checking only.) | 790 | beginning of a chunk for syntax checking only.) |
804 | 791 | ||
@@ -809,10 +796,10 @@ one for numbers and one generic. | |||
809 | \IndexKW{for}\IndexKW{in} | 796 | \IndexKW{for}\IndexKW{in} |
810 | 797 | ||
811 | The numerical \rwd{for} loop repeats a block of code while a | 798 | The numerical \rwd{for} loop repeats a block of code while a |
812 | control variables runs through an arithmetic progression. | 799 | control variable runs through an arithmetic progression. |
813 | It has the following syntax: | 800 | It has the following syntax: |
814 | \begin{Produc} | 801 | \begin{Produc} |
815 | \produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp} | 802 | \produc{stat}{\rwd{for} \Nter{Name} \ter{=} exp \ter{,} exp \opt{\ter{,} exp} |
816 | \rwd{do} block \rwd{end}} | 803 | \rwd{do} block \rwd{end}} |
817 | \end{Produc}% | 804 | \end{Produc}% |
818 | The \emph{block} is repeated for \emph{name} starting at the value of | 805 | The \emph{block} is repeated for \emph{name} starting at the value of |
@@ -849,14 +836,13 @@ If you need the value of the loop variable \verb|var|, | |||
849 | then assign it to another variable before breaking or exiting the loop. | 836 | then assign it to another variable before breaking or exiting the loop. |
850 | \end{itemize} | 837 | \end{itemize} |
851 | 838 | ||
852 | The generic \rwd{for} statement works both over tables | 839 | The generic \rwd{for} statement works over functions, |
853 | and over functions. | 840 | called \Index{generators}. |
854 | When used with a \IndexEmph{generator function}, | 841 | It calls its generator to produce a new value for each iteration, |
855 | it calls this function to produce a new value for each iteration, | ||
856 | stopping when the new value is \nil. | 842 | stopping when the new value is \nil. |
857 | It has the following syntax: | 843 | It has the following syntax: |
858 | \begin{Produc} | 844 | \begin{Produc} |
859 | \produc{stat}{\rwd{for} name \rep{\ter{,} name} \rwd{in} explist1 | 845 | \produc{stat}{\rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1 |
860 | \rwd{do} block \rwd{end}} | 846 | \rwd{do} block \rwd{end}} |
861 | \end{Produc}% | 847 | \end{Produc}% |
862 | A \rwd{for} statement like | 848 | A \rwd{for} statement like |
@@ -891,12 +877,6 @@ If you need these values, | |||
891 | then assign them to other variables before breaking or exiting the loop. | 877 | then assign them to other variables before breaking or exiting the loop. |
892 | \end{itemize} | 878 | \end{itemize} |
893 | 879 | ||
894 | If the first result of the expression list is a table \verb|t| | ||
895 | (instead of a function), | ||
896 | then the loop works as if it has received \verb|next, t| as its | ||
897 | expression list. | ||
898 | That is, the loop iterates over the (key,value) pairs of the table. | ||
899 | |||
900 | 880 | ||
901 | \subsubsection{Function Calls as Statements} \label{funcstat} | 881 | \subsubsection{Function Calls as Statements} \label{funcstat} |
902 | Because of possible side-effects, | 882 | Because of possible side-effects, |
@@ -912,7 +892,7 @@ Function calls are explained in \See{functioncall}. | |||
912 | The declaration may include an initial assignment:\IndexKW{local} | 892 | The declaration may include an initial assignment:\IndexKW{local} |
913 | \begin{Produc} | 893 | \begin{Produc} |
914 | \produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}} | 894 | \produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}} |
915 | \produc{namelist}{name \rep{\ter{,} name}} | 895 | \produc{namelist}{\Nter{Name} \rep{\ter{,} \Nter{Name}}} |
916 | \end{Produc}% | 896 | \end{Produc}% |
917 | If present, an initial assignment has the same semantics | 897 | If present, an initial assignment has the same semantics |
918 | of a multiple assignment \see{assignment}. | 898 | of a multiple assignment \see{assignment}. |
@@ -938,14 +918,14 @@ The basic expressions in Lua are the following: | |||
938 | \produc{exp}{tableconstructor} | 918 | \produc{exp}{tableconstructor} |
939 | \produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}} | 919 | \produc{prefixexp}{var \Or functioncall \Or \ter{(} exp \ter{)}} |
940 | \end{Produc}% | 920 | \end{Produc}% |
941 | \IndexKW{nil} | 921 | \IndexKW{nil}\IndexKW{false}\IndexKW{true} |
942 | 922 | ||
943 | An expression enclosed in parentheses always results in only one value. | 923 | An expression enclosed in parentheses always results in only one value. |
944 | Thus, | 924 | Thus, |
945 | \verb|(f(x,y,z))| is always a single value, | 925 | \verb|(f(x,y,z))| is always a single value, |
946 | even if \verb|f| returns several values. | 926 | even if \verb|f| returns several values. |
947 | (The value of \verb|(f(x,y,z))| is the first value returned by \verb|f| | 927 | (The value of \verb|(f(x,y,z))| is the first value returned by \verb|f| |
948 | or \nil\ if \verb|f| does not return any values.) | 928 | or \nil{} if \verb|f| does not return any values.) |
949 | 929 | ||
950 | \emph{Numbers} and \emph{literal strings} are explained in \See{lexical}; | 930 | \emph{Numbers} and \emph{literal strings} are explained in \See{lexical}; |
951 | variables are explained in \See{variables}; | 931 | variables are explained in \See{variables}; |
@@ -965,8 +945,8 @@ and unary \verb|-| (negation). | |||
965 | If the operands are numbers, or strings that can be converted to | 945 | If the operands are numbers, or strings that can be converted to |
966 | numbers \see{coercion}, | 946 | numbers \see{coercion}, |
967 | then all operations except exponentiation have the usual meaning, | 947 | then all operations except exponentiation have the usual meaning, |
968 | while exponentiation calls a global function \verb|pow|; | 948 | while exponentiation calls a global function \verb|pow|; ?? |
969 | otherwise, an appropriate tag method is called \see{tag-method}. | 949 | otherwise, an appropriate metamethod is called \see{metatable}. |
970 | The standard mathematical library defines function \verb|pow|, | 950 | The standard mathematical library defines function \verb|pow|, |
971 | giving the expected meaning to \Index{exponentiation} | 951 | giving the expected meaning to \Index{exponentiation} |
972 | \see{mathlib}. | 952 | \see{mathlib}. |
@@ -976,7 +956,7 @@ The \Index{relational operators} in Lua are | |||
976 | \begin{verbatim} | 956 | \begin{verbatim} |
977 | == ~= < > <= >= | 957 | == ~= < > <= >= |
978 | \end{verbatim} | 958 | \end{verbatim} |
979 | These operators always result in \False\ or \True. | 959 | These operators always result in \False{} or \True. |
980 | 960 | ||
981 | Equality (\verb|==|) first compares the type of its operands. | 961 | Equality (\verb|==|) first compares the type of its operands. |
982 | If the types are different, then the result is \False. | 962 | If the types are different, then the result is \False. |
@@ -986,6 +966,8 @@ Tables, userdata, and functions are compared \emph{by reference}, | |||
986 | that is, | 966 | that is, |
987 | two tables are considered equal only if they are the \emph{same} table. | 967 | two tables are considered equal only if they are the \emph{same} table. |
988 | 968 | ||
969 | ??eq metamethod?? | ||
970 | |||
989 | Every time you create a new table (or userdata, or function), | 971 | Every time you create a new table (or userdata, or function), |
990 | this new value is different from any previously existing value. | 972 | this new value is different from any previously existing value. |
991 | 973 | ||
@@ -1003,7 +985,7 @@ The order operators work as follows. | |||
1003 | If both arguments are numbers, then they are compared as such. | 985 | If both arguments are numbers, then they are compared as such. |
1004 | Otherwise, if both arguments are strings, | 986 | Otherwise, if both arguments are strings, |
1005 | then their values are compared according to the current locale. | 987 | then their values are compared according to the current locale. |
1006 | Otherwise, the ``lt'' tag method is called \see{tag-method}. | 988 | Otherwise, the ``lt'' or the ``le'' metamethod is called \see{metatable}. |
1007 | 989 | ||
1008 | 990 | ||
1009 | \subsubsection{Logical Operators} | 991 | \subsubsection{Logical Operators} |
@@ -1013,14 +995,14 @@ The \Index{logical operators} in Lua are | |||
1013 | and or not | 995 | and or not |
1014 | \end{verbatim} | 996 | \end{verbatim} |
1015 | Like the control structures \see{control}, | 997 | Like the control structures \see{control}, |
1016 | all logical operators consider both \False\ and \nil\ as false | 998 | all logical operators consider both \False{} and \nil{} as false |
1017 | and anything else as true. | 999 | and anything else as true. |
1018 | \IndexKW{and}\IndexKW{or}\IndexKW{not} | 1000 | \IndexKW{and}\IndexKW{or}\IndexKW{not} |
1019 | 1001 | ||
1020 | The operator \rwd{not} always return \False\ or \True. | 1002 | The operator \rwd{not} always return \False{} or \True. |
1021 | 1003 | ||
1022 | The conjunction operator \rwd{and} returns its first argument | 1004 | The conjunction operator \rwd{and} returns its first argument |
1023 | if its value is \False\ or \nil; | 1005 | if its value is \False{} or \nil; |
1024 | otherwise, \rwd{and} returns its second argument. | 1006 | otherwise, \rwd{and} returns its second argument. |
1025 | The disjunction operator \rwd{or} returns its first argument | 1007 | The disjunction operator \rwd{or} returns its first argument |
1026 | if it is different from \nil and \False; | 1008 | if it is different from \nil and \False; |
@@ -1039,41 +1021,19 @@ For example, | |||
1039 | 10 and 20 -> 20 | 1021 | 10 and 20 -> 20 |
1040 | \end{verbatim} | 1022 | \end{verbatim} |
1041 | 1023 | ||
1042 | %There are two useful Lua idioms that use logical operators. | ||
1043 | %The first idiom is | ||
1044 | %\begin{verbatim} | ||
1045 | % x = x or v | ||
1046 | %\end{verbatim} | ||
1047 | %which is equivalent to | ||
1048 | %\begin{verbatim} | ||
1049 | % if not x then x = v end | ||
1050 | %\end{verbatim} | ||
1051 | %This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set | ||
1052 | %(provided that \verb|x| is not a boolean value). | ||
1053 | |||
1054 | %The second idiom is | ||
1055 | %\begin{verbatim} | ||
1056 | % x = a and b or c | ||
1057 | %\end{verbatim} | ||
1058 | %which should be read as \verb|x = (a and b) or c|. | ||
1059 | %This idiom is equivalent to | ||
1060 | %\begin{verbatim} | ||
1061 | % if a then x = b else x = c end | ||
1062 | %\end{verbatim} | ||
1063 | %provided that \verb|b| is not \nil. | ||
1064 | |||
1065 | \subsubsection{Concatenation} \label{concat} | 1024 | \subsubsection{Concatenation} \label{concat} |
1066 | The string \Index{concatenation} operator in Lua is | 1025 | The string \Index{concatenation} operator in Lua is |
1067 | denoted by two dots (`\verb|..|'). | 1026 | denoted by two dots (`\verb|..|'). |
1068 | If both operands are strings or numbers, then they are converted to | 1027 | If both operands are strings or numbers, then they are converted to |
1069 | strings according to the rules mentioned in \See{coercion}. | 1028 | strings according to the rules mentioned in \See{coercion}. |
1070 | Otherwise, the ``concat'' tag method is called \see{tag-method}. | 1029 | Otherwise, the ``concat'' metamethod is called \see{metatable}. |
1071 | 1030 | ||
1072 | \subsubsection{Precedence} | 1031 | \subsubsection{Precedence} |
1073 | \Index{Operator precedence} in Lua follows the table below, | 1032 | \Index{Operator precedence} in Lua follows the table below, |
1074 | from lower to higher priority: | 1033 | from lower to higher priority: |
1075 | \begin{verbatim} | 1034 | \begin{verbatim} |
1076 | and or | 1035 | or |
1036 | and | ||
1077 | < > <= >= ~= == | 1037 | < > <= >= ~= == |
1078 | .. | 1038 | .. |
1079 | + - | 1039 | + - |
@@ -1091,7 +1051,7 @@ and may exchange the operands of commutative operators, | |||
1091 | as long as these optimizations do not change normal results. | 1051 | as long as these optimizations do not change normal results. |
1092 | However, these optimizations may change some results | 1052 | However, these optimizations may change some results |
1093 | if you define non-associative (or non-commutative) | 1053 | if you define non-associative (or non-commutative) |
1094 | tag methods for these operators. | 1054 | metamethods for those operators. |
1095 | 1055 | ||
1096 | \subsubsection{Table Constructors} \label{tableconstructor} | 1056 | \subsubsection{Table Constructors} \label{tableconstructor} |
1097 | Table \Index{constructors} are expressions that create tables; | 1057 | Table \Index{constructors} are expressions that create tables; |
@@ -1102,7 +1062,8 @@ The general syntax for constructors is | |||
1102 | \begin{Produc} | 1062 | \begin{Produc} |
1103 | \produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}} | 1063 | \produc{tableconstructor}{\ter{\{} \opt{fieldlist} \ter{\}}} |
1104 | \produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}} | 1064 | \produc{fieldlist}{field \rep{fieldsep field} \opt{fieldsep}} |
1105 | \produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp \Or exp} | 1065 | \produc{field}{\ter{[} exp \ter{]} \ter{=} exp \Or |
1066 | \Nter{Name} \ter{=} exp \Or exp} | ||
1106 | \produc{fieldsep}{\ter{,} \Or \ter{;}} | 1067 | \produc{fieldsep}{\ter{,} \Or \ter{;}} |
1107 | \end{Produc}% | 1068 | \end{Produc}% |
1108 | 1069 | ||
@@ -1110,8 +1071,8 @@ Each field of the form \verb|[exp1] = exp2| adds to the new table an entry | |||
1110 | with key \verb|exp1| and value \verb|exp2|. | 1071 | with key \verb|exp1| and value \verb|exp2|. |
1111 | A field of the form \verb|name = exp| is equivalent to | 1072 | A field of the form \verb|name = exp| is equivalent to |
1112 | \verb|["name"] = exp|. | 1073 | \verb|["name"] = exp|. |
1113 | Finally, fields of the form \verb|exp| add to the new table entries | 1074 | Finally, fields of the form \verb|exp| are equivalent to |
1114 | with the given expression indexed by consecutive numerical integers, | 1075 | \verb|[i] = exp|, where \verb|i| are consecutive numerical integers, |
1115 | starting with 1. | 1076 | starting with 1. |
1116 | Fields in the other formats do not affect this counting. | 1077 | Fields in the other formats do not affect this counting. |
1117 | For example, | 1078 | For example, |
@@ -1151,16 +1112,16 @@ A \Index{function call} in Lua has the following syntax: | |||
1151 | In a function call, | 1112 | In a function call, |
1152 | first \M{prefixexp} and \M{args} are evaluated. | 1113 | first \M{prefixexp} and \M{args} are evaluated. |
1153 | If the value of \M{prefixexp} has type \emph{function}, | 1114 | If the value of \M{prefixexp} has type \emph{function}, |
1154 | then this function is called, | 1115 | then that function is called, |
1155 | with the given arguments. | 1116 | with the given arguments. |
1156 | Otherwise, the ``function'' tag method is called, | 1117 | Otherwise, its ``call'' metamethod is called, |
1157 | having as first parameter the value of \M{prefixexp}, | 1118 | having as first parameter the value of \M{prefixexp}, |
1158 | followed by the original call arguments | 1119 | followed by the original call arguments |
1159 | \see{tag-method}. | 1120 | \see{metatable}. |
1160 | 1121 | ||
1161 | The form | 1122 | The form |
1162 | \begin{Produc} | 1123 | \begin{Produc} |
1163 | \produc{functioncall}{prefixexp \ter{:} name args} | 1124 | \produc{functioncall}{prefixexp \ter{:} \Nter{name} args} |
1164 | \end{Produc}% | 1125 | \end{Produc}% |
1165 | can be used to call ``methods''. | 1126 | can be used to call ``methods''. |
1166 | A call \verb|v:name(...)| | 1127 | A call \verb|v:name(...)| |
@@ -1235,28 +1196,40 @@ you must remove the line break before \verb|(g)|. | |||
1235 | 1196 | ||
1236 | The syntax for function definition is\IndexKW{function} | 1197 | The syntax for function definition is\IndexKW{function} |
1237 | \begin{Produc} | 1198 | \begin{Produc} |
1238 | \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} | 1199 | \produc{function}{\rwd{function} funcbody} |
1239 | block \rwd{end}} | 1200 | \produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}} |
1240 | \produc{stat}{\rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} | 1201 | \end{Produc}% |
1241 | block \rwd{end}} | 1202 | |
1242 | \produc{funcname}{name \rep{\ter{.} name} \opt{\ter{:} name}} | 1203 | The following syntactic sugar simplifies function definitions: |
1204 | \begin{Produc} | ||
1205 | \produc{stat}{\rwd{function} funcname funcbody} | ||
1206 | \produc{stat}{\rwd{local} \rwd{function} \Nter{name} funcbody} | ||
1207 | \produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} \opt{\ter{:} \Nter{name}}} | ||
1243 | \end{Produc}% | 1208 | \end{Produc}% |
1244 | The statement | 1209 | The statement |
1245 | \begin{verbatim} | 1210 | \begin{verbatim} |
1246 | function f () ... end | 1211 | function f () ... end |
1247 | \end{verbatim} | 1212 | \end{verbatim} |
1248 | is syntactic sugar for | 1213 | translates to |
1249 | \begin{verbatim} | 1214 | \begin{verbatim} |
1250 | f = function () ... end | 1215 | f = function () ... end |
1251 | \end{verbatim} | 1216 | \end{verbatim} |
1252 | and the statement | 1217 | The statement |
1253 | \begin{verbatim} | 1218 | \begin{verbatim} |
1254 | function t.a.b.c.f () ... end | 1219 | function t.a.b.c.f () ... end |
1255 | \end{verbatim} | 1220 | \end{verbatim} |
1256 | is syntactic sugar for | 1221 | translates to |
1257 | \begin{verbatim} | 1222 | \begin{verbatim} |
1258 | t.a.b.c.f = function () ... end | 1223 | t.a.b.c.f = function () ... end |
1259 | \end{verbatim} | 1224 | \end{verbatim} |
1225 | The statement | ||
1226 | \begin{verbatim} | ||
1227 | local function f () ... end | ||
1228 | \end{verbatim} | ||
1229 | translates to | ||
1230 | \begin{verbatim} | ||
1231 | local f; f = function () ... end | ||
1232 | \end{verbatim} | ||
1260 | 1233 | ||
1261 | A function definition is an executable expression, | 1234 | A function definition is an executable expression, |
1262 | whose value has type \emph{function}. | 1235 | whose value has type \emph{function}. |
@@ -1267,7 +1240,8 @@ the function is \emph{instantiated} (or \emph{closed}). | |||
1267 | This function instance (or \emph{closure}) | 1240 | This function instance (or \emph{closure}) |
1268 | is the final value of the expression. | 1241 | is the final value of the expression. |
1269 | Different instances of the same function | 1242 | Different instances of the same function |
1270 | may refer to different non-local variables \see{visibility}. | 1243 | may refer to different non-local variables \see{visibility} |
1244 | and may have different tables of globals \see{global-table}. | ||
1271 | 1245 | ||
1272 | Parameters act as local variables, | 1246 | Parameters act as local variables, |
1273 | initialized with the argument values: | 1247 | initialized with the argument values: |
@@ -1355,7 +1329,7 @@ Notice that, in a declaration like \verb|local x = x|, | |||
1355 | the new \verb|x| being declared is not in scope yet, | 1329 | the new \verb|x| being declared is not in scope yet, |
1356 | so the second \verb|x| refers to the ``outside'' variable. | 1330 | so the second \verb|x| refers to the ``outside'' variable. |
1357 | 1331 | ||
1358 | Because of this \Index{lexical scoping} rules, | 1332 | Because of those \Index{lexical scoping} rules, |
1359 | local variables can be freely accessed by functions | 1333 | local variables can be freely accessed by functions |
1360 | defined inside their scope. | 1334 | defined inside their scope. |
1361 | For instance: | 1335 | For instance: |
@@ -1384,6 +1358,8 @@ while all of them share the same \verb|x|. | |||
1384 | 1358 | ||
1385 | \subsection{Error Handling} \label{error} | 1359 | \subsection{Error Handling} \label{error} |
1386 | 1360 | ||
1361 | %% TODO Must be rewritten!!! | ||
1362 | |||
1387 | Because Lua is an extension language, | 1363 | Because Lua is an extension language, |
1388 | all Lua actions start from C~code in the host program | 1364 | all Lua actions start from C~code in the host program |
1389 | calling a function from the Lua library. | 1365 | calling a function from the Lua library. |
@@ -1427,12 +1403,13 @@ Every table and userdata value in Lua may have a \emph{metatable}. | |||
1427 | This \IndexEmph{metatable} is a table that defines the behavior of | 1403 | This \IndexEmph{metatable} is a table that defines the behavior of |
1428 | the original table and userdata under some operations. | 1404 | the original table and userdata under some operations. |
1429 | You can query and change the metatable of an object with | 1405 | You can query and change the metatable of an object with |
1430 | function \verb|metatable| \see{pdf-metatable}. | 1406 | functions \verb|setmetatable| and \verb|getmetatable| \see{pdf-getmetatable}. |
1431 | 1407 | ||
1432 | For each of these operations Lua associates a specific key. | 1408 | For each of those operations Lua associates a specific key, |
1433 | When Lua performs one of these operations over a table or a userdata, | 1409 | called an \emph{event}. |
1434 | if checks whether that object has a metatable with the corresponding key. | 1410 | When Lua performs one of those operations over a table or a userdata, |
1435 | If so, the value associated with that key (the \IndexEmph{handler}) | 1411 | if checks whether that object has a metatable with the corresponding event. |
1412 | If so, the value associated with that key (the \IndexEmph{metamethod}) | ||
1436 | controls how Lua will perform the operation. | 1413 | controls how Lua will perform the operation. |
1437 | 1414 | ||
1438 | Metatables control the operations listed next. | 1415 | Metatables control the operations listed next. |
@@ -1451,7 +1428,7 @@ The code shown here in Lua is only illustrative; | |||
1451 | the real behavior is hard coded in the interpreter, | 1428 | the real behavior is hard coded in the interpreter, |
1452 | and it is much more efficient than this simulation. | 1429 | and it is much more efficient than this simulation. |
1453 | All functions used in these descriptions | 1430 | All functions used in these descriptions |
1454 | (\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)\ | 1431 | (\verb|rawget|, \verb|tonumber|, etc.) |
1455 | are described in \See{predefined}. | 1432 | are described in \See{predefined}. |
1456 | 1433 | ||
1457 | \begin{description} | 1434 | \begin{description} |
@@ -1469,10 +1446,10 @@ then Lua tries the second operand. | |||
1469 | return metatable(op1)[event] or metatable(op2)[event] | 1446 | return metatable(op1)[event] or metatable(op2)[event] |
1470 | end | 1447 | end |
1471 | \end{verbatim} | 1448 | \end{verbatim} |
1472 | Using this function, | 1449 | Using that function, |
1473 | the behavior of the ``add'' operation is | 1450 | the behavior of the ``add'' operation is |
1474 | \begin{verbatim} | 1451 | \begin{verbatim} |
1475 | function add_op (op1, op2) | 1452 | function add_event (op1, op2) |
1476 | local o1, o2 = tonumber(op1), tonumber(op2) | 1453 | local o1, o2 = tonumber(op1), tonumber(op2) |
1477 | if o1 and o2 then -- both operands are numeric | 1454 | if o1 and o2 then -- both operands are numeric |
1478 | return o1+o2 -- '+' here is the primitive 'add' | 1455 | return o1+o2 -- '+' here is the primitive 'add' |
@@ -1503,8 +1480,8 @@ Behavior similar to the ``add'' operation. | |||
1503 | \item[``pow'':]\IndexTM{pow} | 1480 | \item[``pow'':]\IndexTM{pow} |
1504 | the \verb|^| operation (exponentiation) operation. | 1481 | the \verb|^| operation (exponentiation) operation. |
1505 | \begin{verbatim} ?? | 1482 | \begin{verbatim} ?? |
1506 | function pow_op (op1, op2) | 1483 | function pow_event (op1, op2) |
1507 | local h = getbinhandler(op1, op2, "__pow") | 1484 | local h = getbinhandler(op1, op2, "__pow") ??? |
1508 | if h then | 1485 | if h then |
1509 | -- call the handler with both operands | 1486 | -- call the handler with both operands |
1510 | return h(op1, op2) | 1487 | return h(op1, op2) |
@@ -1517,7 +1494,7 @@ the \verb|^| operation (exponentiation) operation. | |||
1517 | \item[``unm'':]\IndexTM{unm} | 1494 | \item[``unm'':]\IndexTM{unm} |
1518 | the unary \verb|-| operation. | 1495 | the unary \verb|-| operation. |
1519 | \begin{verbatim} | 1496 | \begin{verbatim} |
1520 | function unm_op (op) | 1497 | function unm_event (op) |
1521 | local o = tonumber(op) | 1498 | local o = tonumber(op) |
1522 | if o then -- operand is numeric | 1499 | if o then -- operand is numeric |
1523 | return -o -- '-' here is the primitive 'unm' | 1500 | return -o -- '-' here is the primitive 'unm' |
@@ -1537,7 +1514,7 @@ the unary \verb|-| operation. | |||
1537 | \item[``lt'':]\IndexTM{lt} | 1514 | \item[``lt'':]\IndexTM{lt} |
1538 | the \verb|<| operation. | 1515 | the \verb|<| operation. |
1539 | \begin{verbatim} | 1516 | \begin{verbatim} |
1540 | function lt_op (op1, op2) | 1517 | function lt_event (op1, op2) |
1541 | if type(op1) == "number" and type(op2) == "number" then | 1518 | if type(op1) == "number" and type(op2) == "number" then |
1542 | return op1 < op2 -- numeric comparison | 1519 | return op1 < op2 -- numeric comparison |
1543 | elseif type(op1) == "string" and type(op2) == "string" then | 1520 | elseif type(op1) == "string" and type(op2) == "string" then |
@@ -1552,18 +1529,41 @@ the \verb|<| operation. | |||
1552 | end | 1529 | end |
1553 | end | 1530 | end |
1554 | \end{verbatim} | 1531 | \end{verbatim} |
1555 | The other order operators also use the \verb|lt_op| function, | 1532 | \verb|a>b| is equivalent to \verb|b<a|. |
1556 | according to the usual equivalences: | 1533 | |
1534 | \item[``le'':]\IndexTM{lt} | ||
1535 | the \verb|<=| operation. | ||
1557 | \begin{verbatim} | 1536 | \begin{verbatim} |
1558 | a>b <=> b<a | 1537 | function lt_event (op1, op2) |
1559 | a<=b <=> not (b<a) | 1538 | if type(op1) == "number" and type(op2) == "number" then |
1560 | a>=b <=> not (a<b) | 1539 | return op1 < op2 -- numeric comparison |
1540 | elseif type(op1) == "string" and type(op2) == "string" then | ||
1541 | return op1 < op2 -- lexicographic comparison | ||
1542 | else | ||
1543 | local h = getbinhandler(op1, op2, "__le") | ||
1544 | if h then | ||
1545 | return h(op1, op2) | ||
1546 | else | ||
1547 | h = getbinhandler(op1, op2, "__lt") | ||
1548 | if h then | ||
1549 | return not h(op2, op1) | ||
1550 | else | ||
1551 | error("unexpected type at comparison"); | ||
1552 | end | ||
1553 | end | ||
1554 | end | ||
1555 | end | ||
1561 | \end{verbatim} | 1556 | \end{verbatim} |
1557 | \verb|a>=b| is equivalent to \verb|b<=a|. | ||
1558 | Notice that, in the absence of a ``le'' metamethod, | ||
1559 | Lua tries the ``lt'', assuming that \verb|a<=b| is | ||
1560 | equivalent to \verb|not (b<a)|. | ||
1561 | |||
1562 | 1562 | ||
1563 | \item[``concat'':]\IndexTM{concatenation} | 1563 | \item[``concat'':]\IndexTM{concatenation} |
1564 | the \verb|..| (concatenation) operation. | 1564 | the \verb|..| (concatenation) operation. |
1565 | \begin{verbatim} | 1565 | \begin{verbatim} |
1566 | function concat_op (op1, op2) | 1566 | function concat_event (op1, op2) |
1567 | if (type(op1) == "string" or type(op1) == "number") and | 1567 | if (type(op1) == "string" or type(op1) == "number") and |
1568 | (type(op2) == "string" or type(op2) == "number") then | 1568 | (type(op2) == "string" or type(op2) == "number") then |
1569 | return op1..op2 -- primitive string concatenation | 1569 | return op1..op2 -- primitive string concatenation |
@@ -1586,45 +1586,57 @@ See the ``gettable'' operation for its semantics. | |||
1586 | \item[``gettable'':]\IndexTM{gettable} | 1586 | \item[``gettable'':]\IndexTM{gettable} |
1587 | called whenever Lua accesses an indexed variable. | 1587 | called whenever Lua accesses an indexed variable. |
1588 | \begin{verbatim} | 1588 | \begin{verbatim} |
1589 | function gettable_op (table, key) | 1589 | function gettable_event (table, key) |
1590 | local h = metatable(table).__gettable | 1590 | local h |
1591 | if h == nil then | 1591 | if type(table) == "table" then |
1592 | if type(table) ~= "table" then | 1592 | local v = rawget(table, key) |
1593 | if v ~= nil then return v end | ||
1594 | h = metatable(table).__index | ||
1595 | if h == nil then return nil end | ||
1596 | else | ||
1597 | h = metatable(table).__gettable | ||
1598 | if h == nil then | ||
1593 | error("indexed expression not a table"); | 1599 | error("indexed expression not a table"); |
1594 | else | ||
1595 | local v = rawget(table, key) | ||
1596 | if v ~= nil then return v end | ||
1597 | h = metatable(table).__index | ||
1598 | if h == nil then return nil end | ||
1599 | end | 1600 | end |
1600 | end | 1601 | end |
1601 | if type(h) == 'function' then | 1602 | if type(h) == "function" then |
1602 | return h(table, key) -- call the handler | 1603 | return h(table, key) -- call the handler |
1603 | else return h[key] -- or repeat operation with it | 1604 | else return h[key] -- or repeat operation with it |
1604 | end | 1605 | end |
1605 | \end{verbatim} | 1606 | \end{verbatim} |
1606 | 1607 | ||
1608 | \item[``newindex'':]\IndexTM{index} | ||
1609 | This handler is called when Lua tries to insert the value of an index | ||
1610 | not present in a table. | ||
1611 | See the ``settable'' operation for its semantics. | ||
1612 | |||
1607 | \item[``settable'':]\IndexTM{settable} | 1613 | \item[``settable'':]\IndexTM{settable} |
1608 | called when Lua assigns to an indexed variable. | 1614 | called when Lua assigns to an indexed variable. |
1609 | \begin{verbatim} | 1615 | \begin{verbatim} |
1610 | function settable_event (table, key, value) | 1616 | function settable_event (table, key, value) |
1611 | local h = metatable(table).__settable | 1617 | local h |
1612 | if h == nil then | 1618 | if type(table) == "table" then |
1613 | if type(table) ~= "table" then | 1619 | local v = rawget(table, key) |
1614 | error("indexed expression not a table") | 1620 | if v ~= nil then rawset(table, key, value); return end |
1615 | rawset(table, key, value) | 1621 | h = metatable(table).__newindex |
1622 | if h == nil then rawset(table, key, value); return end | ||
1616 | else | 1623 | else |
1617 | if type(h) == 'function' then | 1624 | h = metatable(table).__settable |
1618 | h(table, key, value) -- call the handler | 1625 | if h == nil then |
1619 | else h[key] = value -- or repeat operation with it | 1626 | error("indexed expression not a table"); |
1627 | end | ||
1620 | end | 1628 | end |
1629 | if type(h) == "function" then | ||
1630 | return h(table, key,value) -- call the handler | ||
1631 | else h[key] = value -- or repeat operation with it | ||
1621 | end | 1632 | end |
1622 | \end{verbatim} | 1633 | \end{verbatim} |
1623 | 1634 | ||
1635 | |||
1624 | \item[``call'':]\IndexTM{call} | 1636 | \item[``call'':]\IndexTM{call} |
1625 | called when Lua calls a value. | 1637 | called when Lua calls a value. |
1626 | \begin{verbatim} | 1638 | \begin{verbatim} |
1627 | function function_op (func, ...) | 1639 | function function_event (func, ...) |
1628 | if type(func) == "function" then | 1640 | if type(func) == "function" then |
1629 | return func(unpack(arg)) -- regular call | 1641 | return func(unpack(arg)) -- regular call |
1630 | else | 1642 | else |
@@ -1643,13 +1655,12 @@ called when Lua calls a value. | |||
1643 | 1655 | ||
1644 | \subsubsection{Metatables and Garbage collection} | 1656 | \subsubsection{Metatables and Garbage collection} |
1645 | 1657 | ||
1646 | Metatables also control some aspects of the garbage collector. | 1658 | Metatables may also define \IndexEmph{finalizer} methods |
1647 | First, they are used to define \IndexEmph{finalizer} methods | ||
1648 | for userdata values. | 1659 | for userdata values. |
1649 | For each userdata to be collected, | 1660 | For each userdata to be collected, |
1650 | Lua does the equivalent of the following function: | 1661 | Lua does the equivalent of the following function: |
1651 | \begin{verbatim} | 1662 | \begin{verbatim} |
1652 | function gc_op (obj) | 1663 | function gc_event (obj) |
1653 | local h = metatable(obj).__gc | 1664 | local h = metatable(obj).__gc |
1654 | if h then | 1665 | if h then |
1655 | h(obj) | 1666 | h(obj) |
@@ -1661,23 +1672,14 @@ the finalizers for userdata are called in \emph{reverse} | |||
1661 | order of their creation, | 1672 | order of their creation, |
1662 | that is, the first finalizer to be called is the one associated | 1673 | that is, the first finalizer to be called is the one associated |
1663 | with the last userdata created in the program | 1674 | with the last userdata created in the program |
1664 | (among those to be collected in this cycle). | 1675 | (among those to be collected in the same cycle). |
1665 | |||
1666 | Second, metatables control the weakmode of tables \see{weak-table}. | ||
1667 | The weakmode of a table \verb|t| is defined by a string: | ||
1668 | \label{weakmode} | ||
1669 | \begin{verbatim} | ||
1670 | s = metatable(t).__weakmode | ||
1671 | \end{verbatim} | ||
1672 | Valid values for this string are \verb|"k"| for weak keys, | ||
1673 | \verb|"v"| for weak values, | ||
1674 | and \verb|"kv"| for both. | ||
1675 | 1676 | ||
1676 | 1677 | ||
1677 | 1678 | ||
1678 | %------------------------------------------------------------------------------ | 1679 | %------------------------------------------------------------------------------ |
1679 | \section{The Application Program Interface}\label{API} | 1680 | \section{The Application Program Interface}\label{API} |
1680 | \index{C API} | 1681 | \index{C API} |
1682 | |||
1681 | This section describes the API for Lua, that is, | 1683 | This section describes the API for Lua, that is, |
1682 | the set of C~functions available to the host program to communicate | 1684 | the set of C~functions available to the host program to communicate |
1683 | with Lua. | 1685 | with Lua. |
@@ -1717,7 +1719,7 @@ To release a state created with \verb|lua_open|, call | |||
1717 | \end{verbatim} | 1719 | \end{verbatim} |
1718 | \DefAPI{lua_close} | 1720 | \DefAPI{lua_close} |
1719 | This function destroys all objects in the given Lua environment | 1721 | This function destroys all objects in the given Lua environment |
1720 | (calling the corresponding garbage-collection tag methods, if any) | 1722 | (calling the corresponding garbage-collection metamethods, if any) |
1721 | and frees all dynamic memory used by that state. | 1723 | and frees all dynamic memory used by that state. |
1722 | Usually, you do not need to call this function, | 1724 | Usually, you do not need to call this function, |
1723 | because all resources are naturally released when your program ends. | 1725 | because all resources are naturally released when your program ends. |
@@ -1734,8 +1736,9 @@ all functions in the Lua API need a state as their first argument. | |||
1734 | \subsection{Threads} | 1736 | \subsection{Threads} |
1735 | 1737 | ||
1736 | Lua offers a partial support for multiple threads of execution. | 1738 | Lua offers a partial support for multiple threads of execution. |
1737 | If you have a C~library that offers multi-threading or co-routines, | 1739 | If you have a C~library that offers multi-threading, |
1738 | then Lua can cooperate with it to implement the equivalent facility in Lua. | 1740 | then Lua can cooperate with it to implement the equivalent facility in Lua. |
1741 | Also, Lua implements its own coroutine system on top of threads. | ||
1739 | The following function creates a new ``thread'' in Lua: | 1742 | The following function creates a new ``thread'' in Lua: |
1740 | \begin{verbatim} | 1743 | \begin{verbatim} |
1741 | lua_State *lua_newthread (lua_State *L); | 1744 | lua_State *lua_newthread (lua_State *L); |
@@ -1761,10 +1764,15 @@ Instead, you must close the state itself. | |||
1761 | 1764 | ||
1762 | \subsection{The Stack and Indices} | 1765 | \subsection{The Stack and Indices} |
1763 | 1766 | ||
1764 | Lua uses a \emph{stack} to pass values to and from C. | 1767 | Lua uses a virtual \emph{stack} to pass values to and from C. |
1765 | Each element in this stack represents a Lua value | 1768 | Each element in this stack represents a Lua value |
1766 | (\nil, number, string, etc.). | 1769 | (\nil, number, string, etc.). |
1767 | 1770 | ||
1771 | Each C invocation has its own stack. | ||
1772 | Whenever Lua calls C, the called function gets a new stack, | ||
1773 | which is independent of previous stacks or of stacks of still | ||
1774 | active C functions. | ||
1775 | |||
1768 | For convenience, | 1776 | For convenience, |
1769 | most query operations in the API do not follow a strict stack discipline. | 1777 | most query operations in the API do not follow a strict stack discipline. |
1770 | Instead, they can refer to any element in the stack by using an \emph{index}: | 1778 | Instead, they can refer to any element in the stack by using an \emph{index}: |
@@ -1797,14 +1805,18 @@ When you interact with Lua API, | |||
1797 | \emph{you are responsible for controlling stack overflow}. | 1805 | \emph{you are responsible for controlling stack overflow}. |
1798 | The function | 1806 | The function |
1799 | \begin{verbatim} | 1807 | \begin{verbatim} |
1800 | int lua_checkstack (lua_State *L, int size); | 1808 | int lua_checkstack (lua_State *L, int extra); |
1801 | \end{verbatim} | 1809 | \end{verbatim} |
1802 | \DefAPI{lua_checkstack} | 1810 | \DefAPI{lua_checkstack} |
1803 | returns true if there is at lease \verb|size| | 1811 | grows the stack size to \verb|top + extra| elements; |
1804 | stack positions still available. | 1812 | it returns false if it cannot grow the stack to that size. |
1813 | This function never shrinks the stack; | ||
1814 | if the stack is already bigger than the new size, | ||
1815 | it is left unchanged. | ||
1816 | |||
1805 | Whenever Lua calls C, \DefAPI{LUA_MINSTACK} | 1817 | Whenever Lua calls C, \DefAPI{LUA_MINSTACK} |
1806 | it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true, | 1818 | it ensures that \verb|lua_checkstack(L, LUA_MINSTACK)| is true, |
1807 | that is, that | 1819 | that is, |
1808 | at least \verb|LUA_MINSTACK| positions are still available. | 1820 | at least \verb|LUA_MINSTACK| positions are still available. |
1809 | \verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20, | 1821 | \verb|LUA_MINSTACK| is defined in \verb|lua.h| as 20, |
1810 | so that usually you do not have to worry about stack space | 1822 | so that usually you do not have to worry about stack space |
@@ -1812,21 +1824,20 @@ unless your code has loops pushing elements onto the stack. | |||
1812 | 1824 | ||
1813 | Most query functions accept as indices any value inside the | 1825 | Most query functions accept as indices any value inside the |
1814 | available stack space, that is, indices up to the maximum stack size | 1826 | available stack space, that is, indices up to the maximum stack size |
1815 | you (or Lua) have checked through \verb|lua_checkstack|. | 1827 | you (or Lua) have set through \verb|lua_checkstack|. |
1816 | Such indices are called \emph{acceptable indices}. | 1828 | Such indices are called \emph{acceptable indices}. |
1817 | More formally, we define an \IndexEmph{acceptable index} | 1829 | More formally, we define an \IndexEmph{acceptable index} |
1818 | as follows: | 1830 | as follows: |
1819 | \begin{verbatim} | 1831 | \begin{verbatim} |
1820 | (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) | 1832 | (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) |
1821 | \end{verbatim} | 1833 | \end{verbatim} |
1822 | Note that 0 is not an acceptable index. | 1834 | Note that 0 is never an acceptable index. |
1823 | 1835 | ||
1824 | Unless otherwise noticed, | 1836 | Unless otherwise noticed, |
1825 | any function that accepts valid indices can also be called with | 1837 | any function that accepts valid indices can also be called with |
1826 | \Index{pseudo-indices}, | 1838 | \Index{pseudo-indices}, |
1827 | which represent some Lua values that are accessible to the C~code | 1839 | which represent some Lua values that are accessible to the C~code |
1828 | but are not in the stack. | 1840 | but are not in the stack. |
1829 | |||
1830 | Pseudo-indices are used to access the table of globals \see{globals}, | 1841 | Pseudo-indices are used to access the table of globals \see{globals}, |
1831 | the registry, and the upvalues of a C function \see{c-closure}. | 1842 | the registry, and the upvalues of a C function \see{c-closure}. |
1832 | 1843 | ||
@@ -1855,14 +1866,14 @@ A useful macro defined in the \verb|lua.h| is | |||
1855 | \DefAPI{lua_pop} | 1866 | \DefAPI{lua_pop} |
1856 | which pops \verb|n| elements from the stack. | 1867 | which pops \verb|n| elements from the stack. |
1857 | 1868 | ||
1858 | \verb|lua_pushvalue| pushes onto the stack a \emph{copy} of the element | 1869 | \verb|lua_pushvalue| pushes onto the stack a copy of the element |
1859 | at the given index. | 1870 | at the given index. |
1860 | \verb|lua_remove| removes the element at the given position, | 1871 | \verb|lua_remove| removes the element at the given position, |
1861 | shifting down the elements above that position to fill the gap. | 1872 | shifting down the elements above that position to fill the gap. |
1862 | \verb|lua_insert| moves the top element into the given position, | 1873 | \verb|lua_insert| moves the top element into the given position, |
1863 | shifting up the elements above that position to open space. | 1874 | shifting up the elements above that position to open space. |
1864 | \verb|lua_replace| moves the top element into the given position, | 1875 | \verb|lua_replace| moves the top element into the given position, |
1865 | without shifting any element (therefore it replaces the value at | 1876 | without shifting any element (therefore replacing the value at |
1866 | the given position). | 1877 | the given position). |
1867 | These functions accept only valid indices. | 1878 | These functions accept only valid indices. |
1868 | (Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with | 1879 | (Obviously, you cannot call \verb|lua_remove| or \verb|lua_insert| with |
@@ -1899,11 +1910,13 @@ the following functions are available: | |||
1899 | int lua_isfunction (lua_State *L, int index); | 1910 | int lua_isfunction (lua_State *L, int index); |
1900 | int lua_iscfunction (lua_State *L, int index); | 1911 | int lua_iscfunction (lua_State *L, int index); |
1901 | int lua_isuserdata (lua_State *L, int index); | 1912 | int lua_isuserdata (lua_State *L, int index); |
1913 | int lua_isdataval (lua_State *L, int index); | ||
1902 | \end{verbatim} | 1914 | \end{verbatim} |
1903 | \DefAPI{lua_type} | 1915 | \DefAPI{lua_type} |
1904 | \DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring} | 1916 | \DefAPI{lua_isnil}\DefAPI{lua_isnumber}\DefAPI{lua_isstring} |
1905 | \DefAPI{lua_istable}\DefAPI{lua_isboolean} | 1917 | \DefAPI{lua_istable}\DefAPI{lua_isboolean} |
1906 | \DefAPI{lua_isfunction}\DefAPI{lua_iscfunction}\DefAPI{lua_isuserdata} | 1918 | \DefAPI{lua_isfunction}\DefAPI{lua_iscfunction} |
1919 | \DefAPI{lua_isuserdata}\DefAPI{lua_isdataval} | ||
1907 | These functions can be called with any acceptable index. | 1920 | These functions can be called with any acceptable index. |
1908 | 1921 | ||
1909 | \verb|lua_type| returns the type of a value in the stack, | 1922 | \verb|lua_type| returns the type of a value in the stack, |
@@ -1917,19 +1930,20 @@ defined in \verb|lua.h|: | |||
1917 | \verb|LUA_TSTRING|, | 1930 | \verb|LUA_TSTRING|, |
1918 | \verb|LUA_TTABLE|, | 1931 | \verb|LUA_TTABLE|, |
1919 | \verb|LUA_TFUNCTION|, | 1932 | \verb|LUA_TFUNCTION|, |
1920 | \verb|LUA_TUSERDATA|. | 1933 | \verb|LUA_TUSERDATA|, |
1921 | The following function translates a tag to a type name: | 1934 | \verb|LUA_TLIGHTUSERDATA|. |
1935 | The following function translates such constants to a type name: | ||
1922 | \begin{verbatim} | 1936 | \begin{verbatim} |
1923 | const char *lua_type (lua_State *L, int index); | 1937 | const char *lua_typename (lua_State *L, int type); |
1924 | \end{verbatim} | 1938 | \end{verbatim} |
1925 | \DefAPI{lua_typename} | 1939 | \DefAPI{lua_typename} |
1926 | 1940 | ||
1927 | The \verb|lua_is*| functions return~1 if the object is compatible | 1941 | The \verb|lua_is*| functions return~1 if the object is compatible |
1928 | with the given type, and 0 otherwise. | 1942 | with the given type, and 0 otherwise. |
1929 | (\verb|lua_isboolean| is an exception to this rule, | 1943 | \verb|lua_isboolean| is an exception to this rule, |
1930 | and it succeeds only for boolean values; | 1944 | and it succeeds only for boolean values |
1931 | otherwise it would be useless, | 1945 | (otherwise it would be useless, |
1932 | as any value is compatible with a boolean.) | 1946 | as any value is compatible with a boolean). |
1933 | They always return 0 for a non-valid index. | 1947 | They always return 0 for a non-valid index. |
1934 | \verb|lua_isnumber| accepts numbers and numerical strings, | 1948 | \verb|lua_isnumber| accepts numbers and numerical strings, |
1935 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, | 1949 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, |
@@ -1937,7 +1951,7 @@ and \verb|lua_isfunction| accepts both Lua functions and C~functions. | |||
1937 | To distinguish between Lua functions and C~functions, | 1951 | To distinguish between Lua functions and C~functions, |
1938 | you should use \verb|lua_iscfunction|. | 1952 | you should use \verb|lua_iscfunction|. |
1939 | To distinguish between numbers and numerical strings, | 1953 | To distinguish between numbers and numerical strings, |
1940 | you can use \verb|lua_rawtag| (or \verb|lua_tag|). | 1954 | you can use \verb|lua_type|. |
1941 | 1955 | ||
1942 | The API also has functions to compare two values in the stack: | 1956 | The API also has functions to compare two values in the stack: |
1943 | \begin{verbatim} | 1957 | \begin{verbatim} |
@@ -1946,11 +1960,9 @@ The API also has functions to compare two values in the stack: | |||
1946 | \end{verbatim} | 1960 | \end{verbatim} |
1947 | \DefAPI{lua_equal} \DefAPI{lua_lessthan} | 1961 | \DefAPI{lua_equal} \DefAPI{lua_lessthan} |
1948 | These functions are equivalent to their counterparts in Lua \see{rel-ops}. | 1962 | These functions are equivalent to their counterparts in Lua \see{rel-ops}. |
1949 | Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event| | ||
1950 | described in \See{tag-method}. | ||
1951 | Both functions return 0 if any of the indices are non-valid. | 1963 | Both functions return 0 if any of the indices are non-valid. |
1952 | 1964 | ||
1953 | \subsection{Getting Values from the Stack} | 1965 | \subsection{Getting Values from the Stack}\label{lua-to} |
1954 | 1966 | ||
1955 | To translate a value in the stack to a specific C~type, | 1967 | To translate a value in the stack to a specific C~type, |
1956 | you can use the following conversion functions: | 1968 | you can use the following conversion functions: |
@@ -1969,9 +1981,9 @@ When called with a non-valid index, | |||
1969 | they act as if the given value had an incorrect type. | 1981 | they act as if the given value had an incorrect type. |
1970 | 1982 | ||
1971 | \verb|lua_toboolean| converts the Lua value at the given index | 1983 | \verb|lua_toboolean| converts the Lua value at the given index |
1972 | to a C ``boolean'' value (that is, (int)0 or (int)1). | 1984 | to a C ``boolean'' value (that is, 0 or 1). |
1973 | Like all tests in Lua, it returns 1 for any Lua value different from | 1985 | Like all tests in Lua, it returns 1 for any Lua value different from |
1974 | \False\ and \nil; | 1986 | \False{} and \nil; |
1975 | otherwise it returns 0. | 1987 | otherwise it returns 0. |
1976 | It also returns 0 when called with a non-valid index. | 1988 | It also returns 0 when called with a non-valid index. |
1977 | (If you want to accept only real boolean values, | 1989 | (If you want to accept only real boolean values, |
@@ -2010,10 +2022,7 @@ This value must be a C~function; | |||
2010 | otherwise, \verb|lua_tocfunction| returns \verb|NULL|. | 2022 | otherwise, \verb|lua_tocfunction| returns \verb|NULL|. |
2011 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. | 2023 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. |
2012 | 2024 | ||
2013 | \verb|lua_touserdata| converts a value to \verb|void*|. | 2025 | \verb|lua_touserdata| is explained in \See{userdata}. |
2014 | This value must have type \emph{userdata}; | ||
2015 | otherwise, \verb|lua_touserdata| returns \verb|NULL|. | ||
2016 | |||
2017 | 2026 | ||
2018 | 2027 | ||
2019 | \subsection{Pushing Values onto the Stack} | 2028 | \subsection{Pushing Values onto the Stack} |
@@ -2027,9 +2036,11 @@ push C~values onto the stack: | |||
2027 | void lua_pushstring (lua_State *L, const char *s); | 2036 | void lua_pushstring (lua_State *L, const char *s); |
2028 | void lua_pushnil (lua_State *L); | 2037 | void lua_pushnil (lua_State *L); |
2029 | void lua_pushcfunction (lua_State *L, lua_CFunction f); | 2038 | void lua_pushcfunction (lua_State *L, lua_CFunction f); |
2039 | void lua_pushlightuserdata (lua_State *L, void *p); | ||
2030 | \end{verbatim} | 2040 | \end{verbatim} |
2041 | |||
2031 | \DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring} | 2042 | \DefAPI{lua_pushnumber}\DefAPI{lua_pushlstring}\DefAPI{lua_pushstring} |
2032 | \DefAPI{lua_pushcfunction}\DefAPI{lua_pushusertag}\DefAPI{lua_pushboolean} | 2043 | \DefAPI{lua_pushcfunction}\DefAPI{lua_pushlightuserdata}\DefAPI{lua_pushboolean} |
2033 | \DefAPI{lua_pushnil}\label{pushing} | 2044 | \DefAPI{lua_pushnil}\label{pushing} |
2034 | These functions receive a C~value, | 2045 | These functions receive a C~value, |
2035 | convert it to a corresponding Lua value, | 2046 | convert it to a corresponding Lua value, |
@@ -2041,12 +2052,42 @@ make an internal copy of the given string. | |||
2041 | otherwise, you should use the more general \verb|lua_pushlstring|, | 2052 | otherwise, you should use the more general \verb|lua_pushlstring|, |
2042 | which accepts an explicit size. | 2053 | which accepts an explicit size. |
2043 | 2054 | ||
2055 | You can also push ``formatted'' strings: | ||
2056 | \begin{verbatim} | ||
2057 | const char *lua_pushfstring (lua_State *L, const char *fmt, ...); | ||
2058 | const char *lua_pushvfstring (lua_State *L, const char *fmt, | ||
2059 | va_list argp); | ||
2060 | \end{verbatim} | ||
2061 | \DefAPI{lua_pushfstring}\DefAPI{lua_pushvfstring} | ||
2062 | Both functions push onto the stack a formatted string, | ||
2063 | and return a pointer to that string. | ||
2064 | These functions are similar to \verb|sprintf| and \verb|vsprintf|, | ||
2065 | but with some important differences: | ||
2066 | \begin{itemize} | ||
2067 | \item You do not have to allocate the space for the result; | ||
2068 | the result is a Lua string, and Lua takes care of memory allocation | ||
2069 | (and deallocation, later). | ||
2070 | \item The conversion specifiers are quite restricted. | ||
2071 | There are no flags, widths, or precisions. | ||
2072 | The conversion specifiers can be simply | ||
2073 | \verb|%%| (inserts a \verb|%| in the string), | ||
2074 | \verb|%s| (inserts a zero-terminated string, with no size restrictions), | ||
2075 | \verb|%f| (inserts a \verb|lua_Number|), | ||
2076 | \verb|%d| (inserts an \verb|int|), | ||
2077 | \verb|%c| (inserts an \verb|int| as a character). | ||
2078 | \end{itemize} | ||
2079 | |||
2044 | 2080 | ||
2045 | \subsection{Controlling Garbage Collection}\label{GC-API} | 2081 | \subsection{Controlling Garbage Collection}\label{GC-API} |
2046 | 2082 | ||
2047 | Lua uses two numbers to control its garbage collection: | 2083 | Lua uses two numbers to control its garbage collection: |
2048 | the \emph{count} and the \emph{threshold} | 2084 | the \emph{count} and the \emph{threshold} \see{GC}. |
2049 | \see{GC}. | 2085 | The first counts the ammount of memory in use by Lua; |
2086 | when the count reaches the threshold, | ||
2087 | Lua runs its garbage collector. | ||
2088 | After the collection, the count is updated, | ||
2089 | and the threshold is set to twice the count value. | ||
2090 | |||
2050 | You can access the current values of these two numbers through the | 2091 | You can access the current values of these two numbers through the |
2051 | following functions: | 2092 | following functions: |
2052 | \begin{verbatim} | 2093 | \begin{verbatim} |
@@ -2069,47 +2110,113 @@ In particular | |||
2069 | \verb|lua_setgcthreshold(L,0)| forces a garbage collectiion. | 2110 | \verb|lua_setgcthreshold(L,0)| forces a garbage collectiion. |
2070 | After the collection, | 2111 | After the collection, |
2071 | a new threshold is set according to the previous rule. | 2112 | a new threshold is set according to the previous rule. |
2072 | %% TODO: What `previous rule'? | ||
2073 | 2113 | ||
2074 | If you want to change the adaptive behavior of the garbage collector, | 2114 | %% TODO do we need a new way to do that?? |
2075 | you can use the garbage-collection tag method for \nil\ % | 2115 | % If you want to change the adaptive behavior of the garbage collector, |
2076 | to set your own threshold | 2116 | % you can use the garbage-collection tag method for \nil{} % |
2077 | (the tag method is called after Lua resets the threshold). | 2117 | % to set your own threshold |
2118 | % (the tag method is called after Lua resets the threshold). | ||
2119 | |||
2120 | |||
2121 | \subsection{Userdata}\label{userdata} | ||
2078 | 2122 | ||
2123 | Userdata represents C values in Lua. | ||
2124 | Lua supports two types of userdata: | ||
2125 | \Def{full userdata} and \Def{light userdata}. | ||
2079 | 2126 | ||
2080 | \subsection{Userdata} | 2127 | A full userdata represents a block of memory. |
2128 | It is an object (like a table): | ||
2129 | You must create it, it can have its own metatable, | ||
2130 | you can detect when it is being collected. | ||
2131 | A full userdata is only equal to itself. | ||
2081 | 2132 | ||
2082 | You can create new userdata with the following functions: | 2133 | A light userdata represents a pointer. |
2134 | It is a value (like a number): | ||
2135 | You do not create it, it has no metatables, | ||
2136 | it is not collected (as it was never created). | ||
2137 | A light userdata is equal to ``any'' | ||
2138 | light userdata with the same address. | ||
2139 | |||
2140 | In Lua code, there is no way to test whether a userdata is full or light; | ||
2141 | both have type \verb|userdata|. | ||
2142 | In C code, \verb|lua_type| returns \verb|LUA_TUSERDATA| for full userdata, | ||
2143 | and \verb|LUA_LIGHTUSERDATA| for light userdata. | ||
2144 | |||
2145 | You can create new full userdata with the following function: | ||
2083 | \begin{verbatim} | 2146 | \begin{verbatim} |
2084 | void *lua_newuserdata (lua_State *L, size_t size); | 2147 | void *lua_newuserdata (lua_State *L, size_t size); |
2085 | void lua_newuserdatabox (lua_State *L, void *u); | ||
2086 | \end{verbatim} | 2148 | \end{verbatim} |
2087 | \DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox} | 2149 | \DefAPI{lua_newuserdata} |
2088 | The first function, \verb|lua_newuserdata|, | 2150 | It allocates a new block of memory with the given size, |
2089 | allocates a new block of memory with the given size, | ||
2090 | pushes on the stack a new userdata with the block address, | 2151 | pushes on the stack a new userdata with the block address, |
2091 | and returns this address. | 2152 | and returns this address. |
2092 | The second function, \verb|lua_newuserdatabox|, | ||
2093 | gets a pointer and pushes on the stack a new userdata | ||
2094 | with that pointer. | ||
2095 | In this case, Lua does not care about the pointer's value. | ||
2096 | By default, all userdata are created with a standard tag, | ||
2097 | \verb|LUA_TUSERDATA|, which is defined in \verb|lua.h|. | ||
2098 | 2153 | ||
2099 | When Lua collects a userdata created by \verb|lua_newuserdata|, | 2154 | To push a light userdata into the stack you use |
2100 | it automatically frees its corresponding memory. | 2155 | \verb|lua_pushlightuserdata| \see{pushing}. |
2101 | On the other hand, Lua never accesses pointers in | 2156 | |
2102 | userdata created with \verb|lua_newuserdatabox|; | 2157 | \verb|lua_touserdata| \see{lua-to} retrieves the value of a userdata. |
2103 | it is up to you to free any associated memory, | 2158 | When applied on a full userdata, it returns the address of its block; |
2104 | setting a garbage-collection tag method, for instance. | 2159 | when applied on a light userdata, it returns its pointer; |
2160 | when applied on a non-userdata value, it returns \verb|NULL|. | ||
2161 | |||
2162 | When Lua collects a full userdata, | ||
2163 | it calls its \verb|gc| metamethod, if any, | ||
2164 | and then it automatically frees its corresponding memory. | ||
2105 | 2165 | ||
2106 | 2166 | ||
2107 | \subsection{Metatables} | 2167 | \subsection{Metatables} |
2108 | 2168 | ||
2109 | %% TODO | 2169 | %% TODO |
2110 | 2170 | ||
2171 | \subsection{Loading Lua Chunks} | ||
2172 | You can load a Lua chunk with | ||
2173 | \begin{verbatim} | ||
2174 | typedef const char * (*lua_Chunkreader) | ||
2175 | (lua_State *L, void *data, size_t *size); | ||
2176 | |||
2177 | int lua_load (lua_State *L, lua_Chunkreader reader, void *data, | ||
2178 | const char *chunkname); | ||
2179 | \end{verbatim} | ||
2180 | \DefAPI{Chunkreader}\DefAPI{lua_load} | ||
2181 | \verb|lua_load| uses the \emph{reader} to read the chunk. | ||
2182 | Everytime it needs another piece of the chunk, | ||
2183 | it calls the reader, | ||
2184 | passing along its \verb|data| parameter. | ||
2185 | The reader must return a pointer to a block of memory | ||
2186 | with the part of the chunk, | ||
2187 | and set \verb|size| to the block size. | ||
2188 | To signal the end of the chunk, the reader must return \verb|NULL|. | ||
2189 | |||
2190 | In the current implementation, | ||
2191 | the reader function cannot call any Lua function; | ||
2192 | to ensure that, it always receives \verb|NULL| as the Lua state. | ||
2193 | |||
2194 | \verb|lua_load| automatically detects whether the chunk is text or binary, | ||
2195 | and loads it accordingly (see program \IndexVerb{luac}). | ||
2196 | |||
2197 | The return values of \verb|lua_load| are: | ||
2198 | \begin{itemize} | ||
2199 | \item 0 --- no errors; | ||
2200 | \item \IndexAPI{LUA_ERRSYNTAX} --- | ||
2201 | syntax error during pre-compilation. | ||
2202 | \item \IndexAPI{LUA_ERRMEM} --- | ||
2203 | memory allocation error. | ||
2204 | \end{itemize} | ||
2205 | If there are no errors, | ||
2206 | the compiled chunk is pushed as a Lua function on top of the stack. | ||
2207 | Otherwise, an error message is pushed. | ||
2208 | |||
2209 | The \emph{chunkname} is used for error messages | ||
2210 | and debug information \see{debugI}. | ||
2211 | |||
2212 | See the auxiliar library (\verb|lauxlib|) | ||
2213 | for examples of how to use \verb|lua_load|, | ||
2214 | and for some ready-to-use functions to load chunks | ||
2215 | from files and from strings. | ||
2216 | |||
2111 | 2217 | ||
2112 | \subsection{Executing Lua Chunks}\label{luado} | 2218 | \subsection{Executing Lua Chunks}\label{luado} |
2219 | >>>> | ||
2113 | A host program can execute Lua chunks written in a file or in a string | 2220 | A host program can execute Lua chunks written in a file or in a string |
2114 | by using the following functions: | 2221 | by using the following functions: |
2115 | \begin{verbatim} | 2222 | \begin{verbatim} |
@@ -2143,59 +2250,11 @@ call \verb|strerror|, | |||
2143 | or call \verb|perror| to tell the user what went wrong. | 2250 | or call \verb|perror| to tell the user what went wrong. |
2144 | \end{itemize} | 2251 | \end{itemize} |
2145 | 2252 | ||
2146 | When called with argument \verb|NULL|, | ||
2147 | \verb|lua_dofile| executes the \verb|stdin| stream. | ||
2148 | \verb|lua_dofile| and \verb|lua_dobuffer| | ||
2149 | are both able to execute pre-compiled chunks. | ||
2150 | They automatically detect whether the chunk is text or binary, | ||
2151 | and load it accordingly (see program \IndexVerb{luac}). | ||
2152 | \verb|lua_dostring| executes only source code, | ||
2153 | given in textual form. | ||
2154 | |||
2155 | The fourth parameter to \verb|lua_dobuffer| | ||
2156 | is the ``name of the chunk'', | ||
2157 | which is used in error messages and debug information. | ||
2158 | If \verb|name| is \verb|NULL|, | ||
2159 | then Lua gives a default name to the chunk. | ||
2160 | |||
2161 | These functions push onto the stack | ||
2162 | any values eventually returned by the chunk. | ||
2163 | A chunk may return any number of values; | ||
2164 | Lua takes care that these values fit into the stack space, | ||
2165 | %% TODO: how? o que acontece se nao da'? | ||
2166 | but after the call the responsibility is back to you. | ||
2167 | If you need to push other elements after calling any of these functions, | ||
2168 | and you want to ``play safe'', | ||
2169 | you must either check the stack space | ||
2170 | with \verb|lua_checkstack| | ||
2171 | or remove the returned elements | ||
2172 | from the stack (if you do not need them). | ||
2173 | For instance, the following code | ||
2174 | executes a chunk from a file and discards all results returned by this chunk, | ||
2175 | leaving the stack as it was before the call: | ||
2176 | \begin{verbatim} | ||
2177 | { | ||
2178 | int oldtop = lua_gettop(L); | ||
2179 | lua_dofile(L, filename); | ||
2180 | lua_settop(L, oldtop); | ||
2181 | } | ||
2182 | \end{verbatim} | ||
2183 | |||
2184 | \subsection{Loading Lua Chunks} | ||
2185 | You can load Lua chunks without executing them with | ||
2186 | \begin{verbatim} | ||
2187 | int lua_loadfile (lua_State *L, const char *filename); | ||
2188 | int lua_loadbuffer (lua_State *L, const char *buff, | ||
2189 | size_t size, const char *name); | ||
2190 | \end{verbatim} | ||
2191 | The compiled chunk is left as a function on top of the stack. | ||
2192 | The return values are the same as those of | ||
2193 | \verb|lua_dofile| and \verb|lua_dobuffer|. | ||
2194 | 2253 | ||
2195 | \subsection{Manipulating Tables} | 2254 | \subsection{Manipulating Tables} |
2196 | 2255 | ||
2197 | Tables are created by calling | 2256 | Tables are created by calling |
2198 | The function | 2257 | the function |
2199 | \begin{verbatim} | 2258 | \begin{verbatim} |
2200 | void lua_newtable (lua_State *L); | 2259 | void lua_newtable (lua_State *L); |
2201 | \end{verbatim} | 2260 | \end{verbatim} |
@@ -2208,16 +2267,16 @@ call | |||
2208 | void lua_gettable (lua_State *L, int index); | 2267 | void lua_gettable (lua_State *L, int index); |
2209 | \end{verbatim} | 2268 | \end{verbatim} |
2210 | \DefAPI{lua_gettable} | 2269 | \DefAPI{lua_gettable} |
2211 | where \verb|index| refers to the table. | 2270 | where \verb|index| points to the table. |
2212 | \verb|lua_gettable| pops a key from the stack | 2271 | \verb|lua_gettable| pops a key from the stack |
2213 | and returns (on the stack) the contents of the table at that key. | 2272 | and returns (on the stack) the contents of the table at that key. |
2214 | The table is left where it was in the stack; | 2273 | The table is left where it was in the stack; |
2215 | this is convenient for getting multiple values from a table. | 2274 | this is convenient for getting multiple values from a table. |
2216 | 2275 | ||
2217 | As in Lua, this function may trigger a tag method | 2276 | As in Lua, this function may trigger a metamethod |
2218 | for the ``gettable'' event \see{tag-method}. | 2277 | for the ``gettable'' or ``index'' events \see{metatable}. |
2219 | To get the real value of any table key, | 2278 | To get the real value of any table key, |
2220 | without invoking any tag method, | 2279 | without invoking any metamethod, |
2221 | use the \emph{raw} version: | 2280 | use the \emph{raw} version: |
2222 | \begin{verbatim} | 2281 | \begin{verbatim} |
2223 | void lua_rawget (lua_State *L, int index); | 2282 | void lua_rawget (lua_State *L, int index); |
@@ -2232,15 +2291,15 @@ and then call | |||
2232 | void lua_settable (lua_State *L, int index); | 2291 | void lua_settable (lua_State *L, int index); |
2233 | \end{verbatim} | 2292 | \end{verbatim} |
2234 | \DefAPI{lua_settable} | 2293 | \DefAPI{lua_settable} |
2235 | where \verb|index| refers to the table. | 2294 | where \verb|index| points to the table. |
2236 | \verb|lua_settable| pops from the stack both the key and the value. | 2295 | \verb|lua_settable| pops from the stack both the key and the value. |
2237 | The table is left where it was in the stack; | 2296 | The table is left where it was in the stack; |
2238 | this is convenient for setting multiple values in a table. | 2297 | this is convenient for setting multiple values in a table. |
2239 | 2298 | ||
2240 | As in Lua, this operation may trigger a tag method | 2299 | As in Lua, this operation may trigger a metamethod |
2241 | for the ``settable'' event. | 2300 | for the ``settable'' or ``newindex'' events. |
2242 | To set the real value of any table index, | 2301 | To set the real value of any table index, |
2243 | without invoking any tag method, | 2302 | without invoking any metamethod, |
2244 | use the \emph{raw} version: | 2303 | use the \emph{raw} version: |
2245 | \begin{verbatim} | 2304 | \begin{verbatim} |
2246 | void lua_rawset (lua_State *L, int index); | 2305 | void lua_rawset (lua_State *L, int index); |
@@ -2252,13 +2311,13 @@ You can traverse a table with the function | |||
2252 | int lua_next (lua_State *L, int index); | 2311 | int lua_next (lua_State *L, int index); |
2253 | \end{verbatim} | 2312 | \end{verbatim} |
2254 | \DefAPI{lua_next} | 2313 | \DefAPI{lua_next} |
2255 | where \verb|index| refers to the table to be traversed. | 2314 | where \verb|index| points to the table to be traversed. |
2256 | The function pops a key from the stack, | 2315 | The function pops a key from the stack, |
2257 | and pushes a key-value pair from the table | 2316 | and pushes a key-value pair from the table |
2258 | (the ``next'' pair after the given key). | 2317 | (the ``next'' pair after the given key). |
2259 | If there are no more elements, then \verb|lua_next| returns 0 | 2318 | If there are no more elements, then \verb|lua_next| returns 0 |
2260 | (and pushes nothing). | 2319 | (and pushes nothing). |
2261 | Use a \nil\ key to signal the start of a traversal. | 2320 | Use a \nil{} key to signal the start of a traversal. |
2262 | 2321 | ||
2263 | A typical traversal looks like this: | 2322 | A typical traversal looks like this: |
2264 | \begin{verbatim} | 2323 | \begin{verbatim} |
@@ -2277,7 +2336,7 @@ While traversing a table, | |||
2277 | do not call \verb|lua_tostring| on a key, | 2336 | do not call \verb|lua_tostring| on a key, |
2278 | unless you know the key is actually a string. | 2337 | unless you know the key is actually a string. |
2279 | Recall that \verb|lua_tostring| \emph{changes} the value at the given index; | 2338 | Recall that \verb|lua_tostring| \emph{changes} the value at the given index; |
2280 | this confuses \verb|lua_next|. | 2339 | this confuses the next call to \verb|lua_next|. |
2281 | 2340 | ||
2282 | \subsection{Manipulating Global Variables} \label{globals} | 2341 | \subsection{Manipulating Global Variables} \label{globals} |
2283 | 2342 | ||
@@ -2302,29 +2361,21 @@ tables indexed by numbers only: | |||
2302 | \begin{verbatim} | 2361 | \begin{verbatim} |
2303 | void lua_rawgeti (lua_State *L, int index, int n); | 2362 | void lua_rawgeti (lua_State *L, int index, int n); |
2304 | void lua_rawseti (lua_State *L, int index, int n); | 2363 | void lua_rawseti (lua_State *L, int index, int n); |
2305 | int lua_getn (lua_State *L, int index); | ||
2306 | \end{verbatim} | 2364 | \end{verbatim} |
2307 | \DefAPI{lua_rawgeti} | 2365 | \DefAPI{lua_rawgeti} |
2308 | \DefAPI{lua_rawseti} | 2366 | \DefAPI{lua_rawseti} |
2309 | \DefAPI{lua_getn} | ||
2310 | 2367 | ||
2311 | \verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table | 2368 | \verb|lua_rawgeti| pushes the value of the \M{n}-th element of the table |
2312 | at stack position \verb|index|. | 2369 | at stack position \verb|index|. |
2313 | |||
2314 | \verb|lua_rawseti| sets the value of the \M{n}-th element of the table | 2370 | \verb|lua_rawseti| sets the value of the \M{n}-th element of the table |
2315 | at stack position \verb|index| to the value at the top of the stack, | 2371 | at stack position \verb|index| to the value at the top of the stack, |
2316 | removing this value from the stack. | 2372 | removing this value from the stack. |
2317 | 2373 | ||
2318 | \verb|lua_getn| returns the number of elements in the table | ||
2319 | at stack position \verb|index|. | ||
2320 | This number is the value of the table field \verb|n|, | ||
2321 | if it has a numeric value, | ||
2322 | or the largest numerical index with a non-\nil\ value in the table. | ||
2323 | 2374 | ||
2324 | \subsection{Calling Functions} | 2375 | \subsection{Calling Functions} |
2325 | 2376 | ||
2326 | Functions defined in Lua | 2377 | Functions defined in Lua |
2327 | (and C~functions registered in Lua) | 2378 | and C~functions registered in Lua |
2328 | can be called from the host program. | 2379 | can be called from the host program. |
2329 | This is done using the following protocol: | 2380 | This is done using the following protocol: |
2330 | First, the function to be called is pushed onto the stack; | 2381 | First, the function to be called is pushed onto the stack; |
@@ -2332,27 +2383,16 @@ then, the arguments to the function are pushed | |||
2332 | in \emph{direct order}, that is, the first argument is pushed first. | 2383 | in \emph{direct order}, that is, the first argument is pushed first. |
2333 | Finally, the function is called using | 2384 | Finally, the function is called using |
2334 | \begin{verbatim} | 2385 | \begin{verbatim} |
2335 | int lua_call (lua_State *L, int nargs, int nresults); | 2386 | void lua_call (lua_State *L, int nargs, int nresults); |
2336 | \end{verbatim} | 2387 | \end{verbatim} |
2337 | \DefAPI{lua_call} | 2388 | \DefAPI{lua_call} |
2338 | This function returns the same error codes as \verb|lua_dostring| and | ||
2339 | friends \see{luado}. | ||
2340 | If you want to propagate the error, | ||
2341 | %% TODO: explain 'propagate'. | ||
2342 | instead of returning an error code, | ||
2343 | use | ||
2344 | \begin{verbatim} | ||
2345 | void lua_rawcall (lua_State *L, int nargs, int nresults); | ||
2346 | \end{verbatim} | ||
2347 | \DefAPI{lua_rawcall} | ||
2348 | |||
2349 | In both functions, | ||
2350 | \verb|nargs| is the number of arguments that you pushed onto the stack. | 2389 | \verb|nargs| is the number of arguments that you pushed onto the stack. |
2351 | All arguments and the function value are popped from the stack, | 2390 | All arguments and the function value are popped from the stack, |
2352 | and the function results are pushed. | 2391 | and the function results are pushed. |
2353 | The number of results are adjusted to \verb|nresults|, | 2392 | The number of results are adjusted to \verb|nresults|, |
2354 | unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. | 2393 | unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. |
2355 | In that case, \emph{all} results from the function are pushed. | 2394 | In that case, \emph{all} results from the function are pushed. |
2395 | Lua takes care that the returned values fit into the stack space. | ||
2356 | The function results are pushed onto the stack in direct order | 2396 | The function results are pushed onto the stack in direct order |
2357 | (the first result is pushed first), | 2397 | (the first result is pushed first), |
2358 | so that after the call the last result is on the top. | 2398 | so that after the call the last result is on the top. |
@@ -2386,8 +2426,11 @@ to show all the details. | |||
2386 | Usually programmers use several macros and auxiliar functions that | 2426 | Usually programmers use several macros and auxiliar functions that |
2387 | provide higher level access to Lua.) | 2427 | provide higher level access to Lua.) |
2388 | 2428 | ||
2429 | %% TODO: pcall | ||
2430 | |||
2389 | \medskip | 2431 | \medskip |
2390 | 2432 | ||
2433 | >>>> | ||
2391 | %% TODO: mover essas 2 para algum lugar melhor. | 2434 | %% TODO: mover essas 2 para algum lugar melhor. |
2392 | Some special Lua functions have their own C~interfaces. | 2435 | Some special Lua functions have their own C~interfaces. |
2393 | The host program can generate a Lua error calling the function | 2436 | The host program can generate a Lua error calling the function |
@@ -2523,6 +2566,9 @@ This table is always located at pseudo-index | |||
2523 | \IndexAPI{LUA_REGISTRYINDEX}. | 2566 | \IndexAPI{LUA_REGISTRYINDEX}. |
2524 | Any C~library can store data into this table, | 2567 | Any C~library can store data into this table, |
2525 | as long as it chooses a key different from other libraries. | 2568 | as long as it chooses a key different from other libraries. |
2569 | Typically, you can use as key a string containing the library name, | ||
2570 | or a light userdata with the address of a C object in your code. | ||
2571 | |||
2526 | The integer keys in the registry are used by the reference mechanism, | 2572 | The integer keys in the registry are used by the reference mechanism, |
2527 | implemented by the auxiliar library, | 2573 | implemented by the auxiliar library, |
2528 | and therefore should not be used by other purposes. | 2574 | and therefore should not be used by other purposes. |
@@ -2752,26 +2798,42 @@ this execution ocurrs without any calls to hooks. | |||
2752 | 2798 | ||
2753 | The standard libraries provide useful functions | 2799 | The standard libraries provide useful functions |
2754 | that are implemented directly through the standard C~API. | 2800 | that are implemented directly through the standard C~API. |
2755 | Therefore, they are not essential to the language, | 2801 | Some of these functions provide essential services to the language |
2802 | (e.g. \verb|type| and \verb|getmetatable|); | ||
2803 | others provide access to ``outside'' servides (e.g. I/O); | ||
2804 | and others could be implemented in Lua itself, | ||
2805 | but are quite useful or have critical performance to | ||
2806 | deserve an implementation in C (e.g. \verb|sort|). | ||
2807 | |||
2808 | All libraries are implemented through the official C API, | ||
2756 | and are provided as separate C~modules. | 2809 | and are provided as separate C~modules. |
2757 | Currently, Lua has the following standard libraries: | 2810 | Currently, Lua has the following standard libraries: |
2758 | \begin{itemize} | 2811 | \begin{itemize} |
2759 | \item basic library; | 2812 | \item basic library; |
2760 | \item string manipulation; | 2813 | \item string manipulation; |
2814 | \item table manipulation; | ||
2761 | \item mathematical functions (sin, log, etc.); | 2815 | \item mathematical functions (sin, log, etc.); |
2762 | \item input and output (plus some system facilities). | 2816 | \item input and output; |
2817 | \item operating system facilities; | ||
2818 | \item debug facilities. | ||
2763 | \end{itemize} | 2819 | \end{itemize} |
2820 | Except for the basic library, | ||
2821 | each library provides all its functions as fields of a global table | ||
2822 | or as methods of its objects. | ||
2823 | |||
2764 | To have access to these libraries, | 2824 | To have access to these libraries, |
2765 | the C~host program must call the functions | 2825 | the C~host program must call the functions |
2766 | \verb|lua_baselibopen|, | 2826 | \verb|lua_baselibopen|, |
2767 | \verb|lua_strlibopen|, \verb|lua_mathlibopen|, | 2827 | \verb|lua_strlibopen|, |
2828 | \verb|lua_tablibopen|, | ||
2829 | \verb|lua_mathlibopen|, | ||
2768 | and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|. | 2830 | and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|. |
2769 | \DefAPI{lua_baselibopen} | 2831 | \DefAPI{lua_baselibopen} |
2770 | \DefAPI{lua_strlibopen} | 2832 | \DefAPI{lua_strlibopen} |
2833 | \DefAPI{lua_tablibopen} | ||
2771 | \DefAPI{lua_mathlibopen} | 2834 | \DefAPI{lua_mathlibopen} |
2772 | \DefAPI{lua_iolibopen} | 2835 | \DefAPI{lua_iolibopen} |
2773 | 2836 | ||
2774 | Lua's web site has links to Lua libraries written by users. | ||
2775 | 2837 | ||
2776 | \subsection{Basic Functions} \label{predefined} | 2838 | \subsection{Basic Functions} \label{predefined} |
2777 | 2839 | ||
@@ -2779,23 +2841,11 @@ The basic library provides some core functions to Lua. | |||
2779 | If you do not include this library in your application, | 2841 | If you do not include this library in your application, |
2780 | you should check carefully whether you need to provide some alternative | 2842 | you should check carefully whether you need to provide some alternative |
2781 | implementation for some facilities. | 2843 | implementation for some facilities. |
2782 | (For instance, | ||
2783 | without an \verb|_ERRORMESSAGE| function, | ||
2784 | Lua is unable to show error messages.) | ||
2785 | 2844 | ||
2786 | The basic library also defines a global variable \IndexAPI{_VERSION} | 2845 | The basic library also defines a global variable \IndexAPI{_VERSION} |
2787 | with a string containing the current interpreter version. | 2846 | with a string containing the current interpreter version. |
2788 | The current content of this string is {\tt "Lua \Version"}. | 2847 | The current content of this string is {\tt "Lua \Version"}. |
2789 | 2848 | ||
2790 | \subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert} | ||
2791 | Prints its only string argument to \IndexVerb{stderr}. | ||
2792 | All error messages in Lua are printed through the function stored | ||
2793 | in the \verb|_ALERT| global variable | ||
2794 | \see{error}. | ||
2795 | Therefore, a program may assign another function to this variable | ||
2796 | to change the way such messages are shown | ||
2797 | (for instance, for systems without \verb|stderr|). | ||
2798 | |||
2799 | \subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert} | 2849 | \subsubsection*{\ff \T{assert (v [, message])}}\DefLIB{assert} |
2800 | Issues an \emph{``assertion failed!''} error | 2850 | Issues an \emph{``assertion failed!''} error |
2801 | when its argument \verb|v| is \nil; | 2851 | when its argument \verb|v| is \nil; |
@@ -2804,14 +2854,13 @@ This function is equivalent to the following Lua function: | |||
2804 | \begin{verbatim} | 2854 | \begin{verbatim} |
2805 | function assert (v, m) | 2855 | function assert (v, m) |
2806 | if not v then | 2856 | if not v then |
2807 | m = m or "" | 2857 | error(m or "assertion failed!") |
2808 | error("assertion failed! " .. m) | ||
2809 | end | 2858 | end |
2810 | return v | 2859 | return v |
2811 | end | 2860 | end |
2812 | \end{verbatim} | 2861 | \end{verbatim} |
2813 | 2862 | ||
2814 | \subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\DefLIB{call} | 2863 | ??\subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\DefLIB{call} |
2815 | \label{pdf-call} | 2864 | \label{pdf-call} |
2816 | Calls function \verb|func| with | 2865 | Calls function \verb|func| with |
2817 | the arguments given by the table \verb|arg|. | 2866 | the arguments given by the table \verb|arg|. |
@@ -2829,7 +2878,7 @@ If the string \verb|mode| contains \verb|"x"|, | |||
2829 | then the call is \emph{protected}.\index{protected calls} | 2878 | then the call is \emph{protected}.\index{protected calls} |
2830 | In this mode, function \verb|call| does not propagate an error, | 2879 | In this mode, function \verb|call| does not propagate an error, |
2831 | regardless of what happens during the call. | 2880 | regardless of what happens during the call. |
2832 | Instead, it returns \nil\ to signal the error | 2881 | Instead, it returns \nil{} to signal the error |
2833 | (besides calling the appropriated error handler). | 2882 | (besides calling the appropriated error handler). |
2834 | 2883 | ||
2835 | If \verb|errhandler| is provided, | 2884 | If \verb|errhandler| is provided, |
@@ -2852,115 +2901,60 @@ Receives a file name, | |||
2852 | opens the named file, and executes its contents as a Lua chunk. | 2901 | opens the named file, and executes its contents as a Lua chunk. |
2853 | When called without arguments, | 2902 | When called without arguments, |
2854 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). | 2903 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). |
2855 | If there is any error executing the file, | 2904 | Returns any value returned by the chunk. |
2856 | then \verb|dofile| returns \nil{} plus one of the following strings | ||
2857 | describing the error: | ||
2858 | \verb|"file error"|, \verb|"run-time error"|, | ||
2859 | \verb|"syntax error"|, \verb|"memory error"|, or | ||
2860 | \verb|"error in error handling"|. | ||
2861 | Otherwise, it returns the values returned by the chunk, | ||
2862 | or a non-\nil\ value if the chunk returns no values. | ||
2863 | It issues an error when called with a non-string argument. | ||
2864 | |||
2865 | \subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring} | ||
2866 | Executes a given string as a Lua chunk. | ||
2867 | If there is any error executing the string, | ||
2868 | then \verb|dostring| returns \nil\ plus a string describing | ||
2869 | the error (see \verb|dofile|). | ||
2870 | Otherwise, it returns the values returned by the chunk, | ||
2871 | or a non-\nil\ value if the chunk returns no values. | ||
2872 | The optional parameter \verb|chunkname| | ||
2873 | is the ``name of the chunk'', | ||
2874 | used in error messages and debug information. | ||
2875 | 2905 | ||
2876 | \subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error} | 2906 | \subsubsection*{\ff \T{error ([message])}}\DefLIB{error}\label{pdf-error} |
2877 | Calls the error handler \see{error} and then terminates | 2907 | Terminates the last protected function called, |
2878 | the last protected function called | 2908 | and returns \verb|message| as the error message. |
2879 | (in~C: \verb|lua_dofile|, \verb|lua_dostring|, | ||
2880 | \verb|lua_dobuffer|, or \verb|lua_callfunction|; | ||
2881 | in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). | ||
2882 | If \verb|message| is absent, the error handler is not called. | ||
2883 | Function \verb|error| never returns. | 2909 | Function \verb|error| never returns. |
2884 | 2910 | ||
2885 | \subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach} | 2911 | \subsubsection*{\ff \T{getglobals (function)}}\DefLIB{getglobals} |
2886 | Executes the given \verb|func| over all elements of \verb|table|. | 2912 | Returns the current table of globals in use by the function. |
2887 | For each element, the function is called with the index and | 2913 | \verb|function| can be a Lua function or a number, |
2888 | respective value as arguments. | 2914 | meaning the function at that stack level: |
2889 | If the function returns a non-\nil\ value, | 2915 | Level 1 is the function calling \verb|getglobals|. |
2890 | then the loop is broken, and this value is returned | 2916 | If the given function is not a Lua function, |
2891 | as the final value of \verb|foreach|. | 2917 | returns the ``global'' table of globals. |
2892 | This function is equivalent to the following Lua function: | 2918 | The default for \verb|function| is 1. |
2893 | \begin{verbatim} | ||
2894 | function foreach (t, f) | ||
2895 | for i, v in t do | ||
2896 | local res = f(i, v) | ||
2897 | if res then return res end | ||
2898 | end | ||
2899 | end | ||
2900 | \end{verbatim} | ||
2901 | 2919 | ||
2902 | The behavior of \verb|foreach| is \emph{undefined} if you change | 2920 | \subsubsection*{\ff \T{getmetatable (object)}} |
2903 | the table \verb|t| during the traversal. | 2921 | \DefLIB{getmetatable}\label{pdf-getmetatable} |
2904 | 2922 | ||
2923 | Returns the metatable of the given object. | ||
2924 | If the object does not have a metatable, returns \nil. | ||
2905 | 2925 | ||
2906 | \subsubsection*{\ff \T{foreachi (table, func)}}\DefLIB{foreachi} | 2926 | \subsubsection*{\ff \T{getmode (table)}}\DefLIB{getmode} |
2907 | Executes the given \verb|func| over the | 2927 | |
2908 | numerical indices of \verb|table|. | 2928 | Returns the weak mode of a table, as a string. |
2909 | For each index, the function is called with the index and | 2929 | Valid values for this string are \verb|""| for regular (non-weak) tables, |
2910 | respective value as arguments. | 2930 | \verb|"k"| for weak keys, \verb|"v"| for weak values, |
2911 | Indices are visited in sequential order, | 2931 | and \verb|"kv"| for both. |
2912 | from~1 to \verb|n|, | ||
2913 | where \verb|n| is the result of \verb|getn(table)| (see below). | ||
2914 | If the function returns a non-\nil\ value, | ||
2915 | then the loop is broken, and this value is returned | ||
2916 | as the final value of \verb|foreachi|. | ||
2917 | This function is equivalent to the following Lua function: | ||
2918 | \begin{verbatim} | ||
2919 | function foreachi (t, f) | ||
2920 | for i=1,getn(t) do | ||
2921 | local res = f(i, t[i]) | ||
2922 | if res then return res end | ||
2923 | end | ||
2924 | end | ||
2925 | \end{verbatim} | ||
2926 | 2932 | ||
2927 | \subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo} | 2933 | \subsubsection*{\ff \T{gcinfo ()}}\DefLIB{gcinfo} |
2928 | Returns the number of Kbytes of dynamic memory Lua is using, | 2934 | Returns the number of Kbytes of dynamic memory Lua is using, |
2929 | and (as a second result) the | 2935 | and (as a second result) the |
2930 | current garbage collector threshold (also in Kbytes). | 2936 | current garbage collector threshold (also in Kbytes). |
2931 | 2937 | ||
2932 | \subsubsection*{\ff \T{getn (table)}}\DefLIB{getn}\label{getn} | ||
2933 | Returns the ``size'' of a table, when seen as a list. | ||
2934 | If the table has an \verb|n| field with a numeric value, | ||
2935 | this value is the ``size'' of the table. | ||
2936 | Otherwise, the ``size'' is the largest numerical index with a non-\nil\ | ||
2937 | value in the table. | ||
2938 | This function is equivalent to the following Lua function: | ||
2939 | \begin{verbatim} | ||
2940 | function getn (t) | ||
2941 | if type(t.n) == "number" then return t.n end | ||
2942 | local max = 0 | ||
2943 | for i, _ in t do | ||
2944 | if type(i) == "number" and i>max then max=i end | ||
2945 | end | ||
2946 | return max | ||
2947 | end | ||
2948 | \end{verbatim} | ||
2949 | |||
2950 | \subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals} | ||
2951 | Returns the current table of globals. | ||
2952 | If the argument \verb|table| is given, | ||
2953 | then it also sets this table as the table of globals. | ||
2954 | |||
2955 | \subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile} | 2938 | \subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile} |
2956 | Similar to \verb|dofile|, | 2939 | Loads a file as a Lua chunk. |
2957 | but returns the contents of a Lua chunk as a function, | 2940 | If there is no errors, |
2958 | instead of executing it. | 2941 | returns the compiled chunk as a function; |
2942 | otherwise, returns \nil{} plus an error message. | ||
2959 | 2943 | ||
2960 | \subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring} | 2944 | \subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring} |
2961 | Similar to \verb|dostring|, | 2945 | Loads a string as a Lua chunk. |
2962 | but returns the contents of a Lua chunk as a function, | 2946 | If there is no errors, |
2963 | instead of executing it. | 2947 | returns the compiled chunk as a function; |
2948 | otherwise, returns \nil{} plus an error message. | ||
2949 | |||
2950 | The optional parameter \verb|chunkname| | ||
2951 | is the ``name of the chunk'', | ||
2952 | used in error messages and debug information. | ||
2953 | |||
2954 | To load and run a given string, use the idiom | ||
2955 | \begin{verbatim} | ||
2956 | assert(loadstring(s))() | ||
2957 | \end{verbatim} | ||
2964 | 2958 | ||
2965 | \subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next} | 2959 | \subsubsection*{\ff \T{next (table, [index])}}\DefLIB{next} |
2966 | Allows a program to traverse all fields of a table. | 2960 | Allows a program to traverse all fields of a table. |
@@ -2968,22 +2962,22 @@ Its first argument is a table and its second argument | |||
2968 | is an index in this table. | 2962 | is an index in this table. |
2969 | \verb|next| returns the next index of the table and the | 2963 | \verb|next| returns the next index of the table and the |
2970 | value associated with the index. | 2964 | value associated with the index. |
2971 | When called with \nil\ as its second argument, | 2965 | When called with \nil{} as its second argument, |
2972 | \verb|next| returns the first index | 2966 | \verb|next| returns the first index |
2973 | of the table and its associated value. | 2967 | of the table and its associated value. |
2974 | When called with the last index, | 2968 | When called with the last index, |
2975 | or with \nil\ in an empty table, | 2969 | or with \nil{} in an empty table, |
2976 | \verb|next| returns \nil. | 2970 | \verb|next| returns \nil. |
2977 | If the second argument is absent, then it is interpreted as \nil. | 2971 | If the second argument is absent, then it is interpreted as \nil. |
2978 | 2972 | ||
2979 | Lua has no declaration of fields; | 2973 | Lua has no declaration of fields; |
2980 | semantically, there is no difference between a | 2974 | semantically, there is no difference between a |
2981 | field not present in a table or a field with value \nil. | 2975 | field not present in a table or a field with value \nil. |
2982 | Therefore, \verb|next| only considers fields with non-\nil\ values. | 2976 | Therefore, \verb|next| only considers fields with non-\nil{} values. |
2983 | The order in which the indices are enumerated is not specified, | 2977 | The order in which the indices are enumerated is not specified, |
2984 | \emph{even for numeric indices} | 2978 | \emph{even for numeric indices} |
2985 | (to traverse a table in numeric order, | 2979 | (to traverse a table in numeric order, |
2986 | use a numerical \rwd{for} or the function \verb|foreachi|). | 2980 | use a numerical \rwd{for} or the function \verb|ipairs|). |
2987 | 2981 | ||
2988 | The behavior of \verb|next| is \emph{undefined} if you change | 2982 | The behavior of \verb|next| is \emph{undefined} if you change |
2989 | the table during the traversal. | 2983 | the table during the traversal. |
@@ -3049,22 +3043,27 @@ While running a packaged file, | |||
3049 | \verb|require| defines the global variable \IndexVerb{_REQUIREDNAME} | 3043 | \verb|require| defines the global variable \IndexVerb{_REQUIREDNAME} |
3050 | with the package name. | 3044 | with the package name. |
3051 | 3045 | ||
3046 | \subsubsection*{\ff \T{setglobals (function, table)}}\DefLIB{setglobals} | ||
3047 | Sets the current table of globals to be used by the given function. | ||
3048 | \verb|function| can be a Lua function or a number, | ||
3049 | meaning the function at that stack level: | ||
3050 | Level 1 is the function calling \verb|setglobals|. | ||
3052 | 3051 | ||
3053 | \subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} | 3052 | \subsubsection*{\ff \T{setmetatable (table, metatable)}}\DefLIB{setmetatable} |
3054 | Sorts table elements in a given order, \emph{in-place}, | ||
3055 | from \verb|table[1]| to \verb|table[n]|, | ||
3056 | where \verb|n| is the result of \verb|getn(table)| \see{getn}. | ||
3057 | If \verb|comp| is given, | ||
3058 | then it must be a function that receives two table elements, | ||
3059 | and returns true | ||
3060 | when the first is less than the second | ||
3061 | (so that \verb|not comp(a[i+1],a[i])| will be true after the sort). | ||
3062 | If \verb|comp| is not given, | ||
3063 | then the standard Lua operator \verb|<| is used instead. | ||
3064 | 3053 | ||
3065 | The sort algorithm is \emph{not} stable | 3054 | Sets the metatable for the given table. |
3066 | (that is, elements considered equal by the given order | 3055 | (You cannot change the metatable of a userdata from Lua.) |
3067 | may have their relative positions changed by the sort). | 3056 | If \verb|metatable| is \nil, removes the metatable of the given table. |
3057 | |||
3058 | \subsubsection*{\ff \T{setmode (table, mode)}}\DefLIB{setmode} | ||
3059 | |||
3060 | Set the weak mode of a table. | ||
3061 | The new mode is described by the \verb|mode| string. | ||
3062 | Valid values for this string are \verb|""| for regular (non-weak) tables, | ||
3063 | \verb|"k"| for weak keys, \verb|"v"| for weak values, | ||
3064 | and \verb|"kv"| for both. | ||
3065 | |||
3066 | This function returns its first argument (\verb|table|). | ||
3068 | 3067 | ||
3069 | \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} | 3068 | \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} |
3070 | Tries to convert its argument to a number. | 3069 | Tries to convert its argument to a number. |
@@ -3086,30 +3085,6 @@ converts it to a string in a reasonable format. | |||
3086 | For complete control of how numbers are converted, | 3085 | For complete control of how numbers are converted, |
3087 | use \verb|format| \see{format}. | 3086 | use \verb|format| \see{format}. |
3088 | 3087 | ||
3089 | |||
3090 | \subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert} | ||
3091 | |||
3092 | Inserts element \verb|value| at position \verb|pos| in \verb|table|, | ||
3093 | shifting other elements up to open space, if necessary. | ||
3094 | The default value for \verb|pos| is \verb|n+1|, | ||
3095 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, | ||
3096 | so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end | ||
3097 | of table \verb|t|. | ||
3098 | This function also sets or increments the field \verb|n| of the table | ||
3099 | to \verb|n+1|. | ||
3100 | |||
3101 | \subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove} | ||
3102 | |||
3103 | Removes from \verb|table| the element at position \verb|pos|, | ||
3104 | shifting other elements down to close the space, if necessary. | ||
3105 | Returns the value of the removed element. | ||
3106 | The default value for \verb|pos| is \verb|n|, | ||
3107 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, | ||
3108 | so that a call \verb|tremove(t)| removes the last element | ||
3109 | of table \verb|t|. | ||
3110 | This function also sets or decrements the field \verb|n| of the table | ||
3111 | to \verb|n-1|. | ||
3112 | |||
3113 | \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} | 3088 | \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} |
3114 | Returns the type of its only argument, coded as a string. | 3089 | Returns the type of its only argument, coded as a string. |
3115 | The possible results of this function are | 3090 | The possible results of this function are |
@@ -3128,7 +3103,8 @@ This function is equivalent to | |||
3128 | \end{verbatim} | 3103 | \end{verbatim} |
3129 | except that the above code can be valid only for a fixed \M{n}. | 3104 | except that the above code can be valid only for a fixed \M{n}. |
3130 | The number \M{n} of returned values | 3105 | The number \M{n} of returned values |
3131 | is the result of \verb|getn(list)| \seepage{getn}. | 3106 | is either the value of \verb|list.n|, if it is a number, |
3107 | or one less the index of the first absent (\nil) value. | ||
3132 | 3108 | ||
3133 | \subsection{String Manipulation} | 3109 | \subsection{String Manipulation} |
3134 | This library provides generic functions for string manipulation, | 3110 | This library provides generic functions for string manipulation, |
@@ -3136,10 +3112,13 @@ such as finding and extracting substrings and pattern matching. | |||
3136 | When indexing a string in Lua, the first character is at position~1 | 3112 | When indexing a string in Lua, the first character is at position~1 |
3137 | (not at~0, as in C). | 3113 | (not at~0, as in C). |
3138 | Indices are allowed to be negative and are interpreted as indexing backwards, | 3114 | Indices are allowed to be negative and are interpreted as indexing backwards, |
3139 | from the end of the string. Thus, the last character is at position \Math{-1}, | 3115 | from the end of the string. |
3140 | and so on. | 3116 | Thus, the last character is at position \Math{-1}, and so on. |
3141 | 3117 | ||
3142 | \subsubsection*{\ff \T{strbyte (s [, i])}}\DefLIB{strbyte} | 3118 | The string library provides all its functions inside the table |
3119 | \DefLIB{string}. | ||
3120 | |||
3121 | \subsubsection*{\ff \T{string.byte (s [, i])}}\DefLIB{string.byte} | ||
3143 | Returns the internal numerical code of the \M{i}-th character of \verb|s|. | 3122 | Returns the internal numerical code of the \M{i}-th character of \verb|s|. |
3144 | If \verb|i| is absent, then it is assumed to be~1. | 3123 | If \verb|i| is absent, then it is assumed to be~1. |
3145 | \verb|i| may be negative. | 3124 | \verb|i| may be negative. |
@@ -3147,7 +3126,7 @@ If \verb|i| is absent, then it is assumed to be~1. | |||
3147 | \NOTE | 3126 | \NOTE |
3148 | Numerical codes are not necessarily portable across platforms. | 3127 | Numerical codes are not necessarily portable across platforms. |
3149 | 3128 | ||
3150 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\DefLIB{strchar} | 3129 | \subsubsection*{\ff \T{string.char (i1, i2, \ldots)}}\DefLIB{string.char} |
3151 | Receives 0 or more integers. | 3130 | Receives 0 or more integers. |
3152 | Returns a string with length equal to the number of arguments, | 3131 | Returns a string with length equal to the number of arguments, |
3153 | in which each character has the internal numerical code equal | 3132 | in which each character has the internal numerical code equal |
@@ -3156,59 +3135,60 @@ to its correspondent argument. | |||
3156 | \NOTE | 3135 | \NOTE |
3157 | Numerical codes are not necessarily portable across platforms. | 3136 | Numerical codes are not necessarily portable across platforms. |
3158 | 3137 | ||
3159 | \subsubsection*{\ff \T{strfind (s, pattern [, init [, plain]])}}\DefLIB{strfind} | 3138 | \subsubsection*{\ff \T{string.find (s, pattern [, init [, plain]])}} |
3139 | \DefLIB{string.find} | ||
3160 | Looks for the first \emph{match} of | 3140 | Looks for the first \emph{match} of |
3161 | \verb|pattern| in the string \verb|s|. | 3141 | \verb|pattern| in the string \verb|s|. |
3162 | If it finds one, then \verb|strfind| returns the indices of \verb|s| | 3142 | If it finds one, then \verb|find| returns the indices of \verb|s| |
3163 | where this occurrence starts and ends; | 3143 | where this occurrence starts and ends; |
3164 | otherwise, it returns \nil. | 3144 | otherwise, it returns \nil. |
3165 | If the pattern specifies captures (see \verb|gsub| below), | 3145 | If the pattern specifies captures (see \verb|string.gsub| below), |
3166 | the captured strings are returned as extra results. | 3146 | the captured strings are returned as extra results. |
3167 | A third, optional numerical argument \verb|init| specifies | 3147 | A third, optional numerical argument \verb|init| specifies |
3168 | where to start the search; | 3148 | where to start the search; |
3169 | its default value is~1, and may be negative. | 3149 | its default value is~1, and may be negative. |
3170 | A value of \True\ as a fourth, optional argument \verb|plain| | 3150 | A value of \True{} as a fourth, optional argument \verb|plain| |
3171 | turns off the pattern matching facilities, | 3151 | turns off the pattern matching facilities, |
3172 | so the function does a plain ``find substring'' operation, | 3152 | so the function does a plain ``find substring'' operation, |
3173 | with no characters in \verb|pattern| being considered ``magic''. | 3153 | with no characters in \verb|pattern| being considered ``magic''. |
3174 | Note that if \verb|plain| is given, then \verb|init| must be given too. | 3154 | Note that if \verb|plain| is given, then \verb|init| must be given too. |
3175 | 3155 | ||
3176 | \subsubsection*{\ff \T{strlen (s)}}\DefLIB{strlen} | 3156 | \subsubsection*{\ff \T{string.len (s)}}\DefLIB{string.len} |
3177 | Receives a string and returns its length. | 3157 | Receives a string and returns its length. |
3178 | The empty string \verb|""| has length 0. | 3158 | The empty string \verb|""| has length 0. |
3179 | Embedded zeros are counted, | 3159 | Embedded zeros are counted, |
3180 | and so \verb|"a\000b\000c"| has length 5. | 3160 | and so \verb|"a\000b\000c"| has length 5. |
3181 | 3161 | ||
3182 | \subsubsection*{\ff \T{strlower (s)}}\DefLIB{strlower} | 3162 | \subsubsection*{\ff \T{string.lower (s)}}\DefLIB{string.lower} |
3183 | Receives a string and returns a copy of that string with all | 3163 | Receives a string and returns a copy of that string with all |
3184 | uppercase letters changed to lowercase. | 3164 | uppercase letters changed to lowercase. |
3185 | All other characters are left unchanged. | 3165 | All other characters are left unchanged. |
3186 | The definition of what an uppercase letter is depends on the current locale. | 3166 | The definition of what is an uppercase letter depends on the current locale. |
3187 | 3167 | ||
3188 | \subsubsection*{\ff \T{strrep (s, n)}}\DefLIB{strrep} | 3168 | \subsubsection*{\ff \T{string.rep (s, n)}}\DefLIB{string.rep} |
3189 | Returns a string that is the concatenation of \verb|n| copies of | 3169 | Returns a string that is the concatenation of \verb|n| copies of |
3190 | the string \verb|s|. | 3170 | the string \verb|s|. |
3191 | 3171 | ||
3192 | \subsubsection*{\ff \T{strsub (s, i [, j])}}\DefLIB{strsub} | 3172 | \subsubsection*{\ff \T{string.sub (s, i [, j])}}\DefLIB{string.sub} |
3193 | Returns another string, which is a substring of \verb|s|, | 3173 | Returns another string, which is a substring of \verb|s|, |
3194 | starting at \verb|i| and running until \verb|j|; | 3174 | starting at \verb|i| and running until \verb|j|; |
3195 | \verb|i| and \verb|j| may be negative. | 3175 | \verb|i| and \verb|j| may be negative. |
3196 | If \verb|j| is absent, then it is assumed to be equal to \Math{-1} | 3176 | If \verb|j| is absent, then it is assumed to be equal to \Math{-1} |
3197 | (which is the same as the string length). | 3177 | (which is the same as the string length). |
3198 | In particular, | 3178 | In particular, |
3199 | the call \verb|strsub(s,1,j)| returns a prefix of \verb|s| | 3179 | the call \verb|string.sub(s,1,j)| returns a prefix of \verb|s| |
3200 | with length \verb|j|, | 3180 | with length \verb|j|, |
3201 | and the call \verb|strsub(s, -i)| returns a suffix of \verb|s| | 3181 | and the call \verb|string.sub(s, -i)| returns a suffix of \verb|s| |
3202 | with length \verb|i|. | 3182 | with length \verb|i|. |
3203 | 3183 | ||
3204 | \subsubsection*{\ff \T{strupper (s)}}\DefLIB{strupper} | 3184 | \subsubsection*{\ff \T{string.upper (s)}}\DefLIB{string.upper} |
3205 | Receives a string and returns a copy of that string with all | 3185 | Receives a string and returns a copy of that string with all |
3206 | lowercase letters changed to uppercase. | 3186 | lowercase letters changed to uppercase. |
3207 | All other characters are left unchanged. | 3187 | All other characters are left unchanged. |
3208 | The definition of what a lowercase letter is depends on the current locale. | 3188 | The definition of what is a lowercase letter depends on the current locale. |
3209 | 3189 | ||
3210 | \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\DefLIB{format} | 3190 | \subsubsection*{\ff \T{string.format (formatstring, e1, e2, \ldots)}} |
3211 | \label{format} | 3191 | \DefLIB{string.format}\label{format} |
3212 | Returns a formatted version of its variable number of arguments | 3192 | Returns a formatted version of its variable number of arguments |
3213 | following the description given in its first argument (which must be a string). | 3193 | following the description given in its first argument (which must be a string). |
3214 | The format string follows the same rules as the \verb|printf| family of | 3194 | The format string follows the same rules as the \verb|printf| family of |
@@ -3224,7 +3204,7 @@ and all double quotes, returns, and backslashes in the string | |||
3224 | are correctly escaped when written. | 3204 | are correctly escaped when written. |
3225 | For instance, the call | 3205 | For instance, the call |
3226 | \begin{verbatim} | 3206 | \begin{verbatim} |
3227 | format('%q', 'a string with "quotes" and \n new line') | 3207 | string.format('%q', 'a string with "quotes" and \n new line') |
3228 | \end{verbatim} | 3208 | \end{verbatim} |
3229 | will produce the string: | 3209 | will produce the string: |
3230 | \begin{verbatim} | 3210 | \begin{verbatim} |
@@ -3245,8 +3225,8 @@ For example, \verb|"%*g"| can be simulated with | |||
3245 | String values to be formatted with | 3225 | String values to be formatted with |
3246 | \verb|%s| cannot contain embedded zeros. | 3226 | \verb|%s| cannot contain embedded zeros. |
3247 | 3227 | ||
3248 | \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} | 3228 | \subsubsection*{\ff \T{string.gsub (s, pat, repl [, n])}} |
3249 | \DefLIB{gsub} | 3229 | \DefLIB{string.gsub} |
3250 | Returns a copy of \verb|s| | 3230 | Returns a copy of \verb|s| |
3251 | in which all occurrences of the pattern \verb|pat| have been | 3231 | in which all occurrences of the pattern \verb|pat| have been |
3252 | replaced by a replacement string specified by \verb|repl|. | 3232 | replaced by a replacement string specified by \verb|repl|. |
@@ -3292,10 +3272,6 @@ Here are some examples: | |||
3292 | local t = {name="Lua", version="4.1"} | 3272 | local t = {name="Lua", version="4.1"} |
3293 | x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end) | 3273 | x = gsub("$name - $version", "%$(%w+)", function (v) return t[v] end) |
3294 | --> x="Lua - 4.1" | 3274 | --> x="Lua - 4.1" |
3295 | |||
3296 | local t = {} | ||
3297 | gsub("first second word", "%w+", function (w) tinsert(t, w) end) | ||
3298 | --> t={"first", "second", "word"; n=3} | ||
3299 | \end{verbatim} | 3275 | \end{verbatim} |
3300 | 3276 | ||
3301 | 3277 | ||
@@ -3380,7 +3356,7 @@ a single character class followed by \verb|?|, | |||
3380 | which matches 0 or 1 occurrence of a character in the class; | 3356 | which matches 0 or 1 occurrence of a character in the class; |
3381 | \item | 3357 | \item |
3382 | \T{\%\M{n}}, for \M{n} between 1 and 9; | 3358 | \T{\%\M{n}}, for \M{n} between 1 and 9; |
3383 | such item matches a sub-string equal to the \M{n}-th captured string | 3359 | such item matches a substring equal to the \M{n}-th captured string |
3384 | (see below); | 3360 | (see below); |
3385 | \item | 3361 | \item |
3386 | \T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; | 3362 | \T{\%b\M{xy}}, where \M{x} and \M{y} are two distinct characters; |
@@ -3405,7 +3381,7 @@ At other positions, | |||
3405 | \paragraph{Captures:} | 3381 | \paragraph{Captures:} |
3406 | A pattern may contain sub-patterns enclosed in parentheses; | 3382 | A pattern may contain sub-patterns enclosed in parentheses; |
3407 | they describe \Def{captures}. | 3383 | they describe \Def{captures}. |
3408 | When a match succeeds, the sub-strings of the subject string | 3384 | When a match succeeds, the substrings of the subject string |
3409 | that match captures are stored (\emph{captured}) for future use. | 3385 | that match captures are stored (\emph{captured}) for future use. |
3410 | Captures are numbered according to their left parentheses. | 3386 | Captures are numbered according to their left parentheses. |
3411 | For instance, in the pattern \verb|"(a*(.)%w(%s*))"|, | 3387 | For instance, in the pattern \verb|"(a*(.)%w(%s*))"|, |
@@ -3418,77 +3394,223 @@ and the part matching \verb|%s*| has number~3. | |||
3418 | A pattern cannot contain embedded zeros. Use \verb|%z| instead. | 3394 | A pattern cannot contain embedded zeros. Use \verb|%z| instead. |
3419 | 3395 | ||
3420 | 3396 | ||
3397 | \subsection{Table Manipulation} | ||
3398 | This library provides generic functions for table manipulation, | ||
3399 | It provides all its functions inside the table \DefLIB{table}. | ||
3400 | |||
3401 | Most functions in the table library library assume that the table | ||
3402 | represents an array or a list. | ||
3403 | For those functions, an important concept is the \emph{size} of the array. | ||
3404 | There are three ways to specify that size: | ||
3405 | \begin{itemize} | ||
3406 | \item the field \verb|"n"| --- | ||
3407 | When the table has a field \verb|"n"| with a numerical value, | ||
3408 | that value is assumed as its size. | ||
3409 | \item \verb|setn| --- | ||
3410 | You can call the \verb|table.setn| function to explicitly set | ||
3411 | the size of a table. | ||
3412 | \item implicit size --- | ||
3413 | %% TODO | ||
3414 | \end{itemize} | ||
3415 | For more details, see the descriptions of the \verb|table.getn| and | ||
3416 | \verb|table.setn| functions. | ||
3417 | |||
3418 | \subsubsection*{\ff \T{table.foreach (table, func)}}\DefLIB{table.foreach} | ||
3419 | Executes the given \verb|func| over all elements of \verb|table|. | ||
3420 | For each element, \verb|func| is called with the index and | ||
3421 | respective value as arguments. | ||
3422 | If \verb|func| returns a non-\nil{} value, | ||
3423 | then the loop is broken, and this value is returned | ||
3424 | as the final value of \verb|foreach|. | ||
3425 | |||
3426 | The behavior of \verb|foreach| is \emph{undefined} if you change | ||
3427 | the table \verb|t| during the traversal. | ||
3428 | |||
3429 | |||
3430 | \subsubsection*{\ff \T{table.foreachi (table, func)}}\DefLIB{table.foreachi} | ||
3431 | Executes the given \verb|func| over the | ||
3432 | numerical indices of \verb|table|. | ||
3433 | For each index, \verb|func| is called with the index and | ||
3434 | respective value as arguments. | ||
3435 | Indices are visited in sequential order, | ||
3436 | from~1 to \verb|n|, | ||
3437 | where \verb|n| is the size of the table \see{getn}. | ||
3438 | If \verb|func| returns a non-\nil{} value, | ||
3439 | then the loop is broken, and this value is returned | ||
3440 | as the final value of \verb|foreachi|. | ||
3441 | |||
3442 | \subsubsection*{\ff \T{table.getn (table)}}\DefLIB{table.getn}\label{getn} | ||
3443 | Returns the ``size'' of a table, when seen as a list. | ||
3444 | If the table has an \verb|n| field with a numeric value, | ||
3445 | this value is the ``size'' of the table. | ||
3446 | Otherwise, if there was a previous call to | ||
3447 | \verb|table.getn| or to \verb|table.setn| over this table, | ||
3448 | the respective value is returned. | ||
3449 | Otherwise, the ``size'' is one less the first integer index with | ||
3450 | a \nil{} value. | ||
3451 | |||
3452 | Notice that the last option happens only once for a table. | ||
3453 | If you call \verb|table.getn| again over the same table, | ||
3454 | it will return the same previous result, | ||
3455 | even if the table has been modified. | ||
3456 | The only way to change the value of \verb|table.getn| is by calling | ||
3457 | \verb|table.setn| or assigning to field \verb|"n"| in the table. | ||
3458 | |||
3459 | \subsubsection*{\ff \T{table.sort (table [, comp])}}\DefLIB{table.sort} | ||
3460 | Sorts table elements in a given order, \emph{in-place}, | ||
3461 | from \verb|table[1]| to \verb|table[n]|, | ||
3462 | where \verb|n| is the size of the table \see{getn}. | ||
3463 | If \verb|comp| is given, | ||
3464 | then it must be a function that receives two table elements, | ||
3465 | and returns true | ||
3466 | when the first is less than the second | ||
3467 | (so that \verb|not comp(a[i+1],a[i])| will be true after the sort). | ||
3468 | If \verb|comp| is not given, | ||
3469 | then the standard Lua operator \verb|<| is used instead. | ||
3470 | |||
3471 | The sort algorithm is \emph{not} stable | ||
3472 | (that is, elements considered equal by the given order | ||
3473 | may have their relative positions changed by the sort). | ||
3474 | |||
3475 | \subsubsection*{\ff \T{table.insert (table, [pos,] value)}}\DefLIB{table.insert} | ||
3476 | |||
3477 | Inserts element \verb|value| at position \verb|pos| in \verb|table|, | ||
3478 | shifting other elements up to open space, if necessary. | ||
3479 | The default value for \verb|pos| is \verb|n+1|, | ||
3480 | where \verb|n| is the size of the table \see{getn}, | ||
3481 | so that a call \verb|table.insert(t,x)| inserts \verb|x| at the end | ||
3482 | of table \verb|t|. | ||
3483 | This function also updates the size of the table, | ||
3484 | calling \verb|table.setn(table, n+1)|. | ||
3485 | |||
3486 | \subsubsection*{\ff \T{table.remove (table [, pos])}}\DefLIB{table.remove} | ||
3487 | |||
3488 | Removes from \verb|table| the element at position \verb|pos|, | ||
3489 | shifting other elements down to close the space, if necessary. | ||
3490 | Returns the value of the removed element. | ||
3491 | The default value for \verb|pos| is \verb|n|, | ||
3492 | where \verb|n| is the size of the table \see{getn}, | ||
3493 | so that a call \verb|tremove(t)| removes the last element | ||
3494 | of table \verb|t|. | ||
3495 | This function also updates the size of the table, | ||
3496 | calling \verb|table.setn(table, n-1)|. | ||
3497 | |||
3498 | \subsubsection*{\ff \T{table.setn (table, n)}}\DefLIB{table.setn} | ||
3499 | |||
3500 | Updates the ``size'' of a table. | ||
3501 | If the table has a field \verb|"n"| with a numerical value, | ||
3502 | that value is changed to the given \verb|n|. | ||
3503 | Otherwise, it updates an internal state of the \verb|table| library | ||
3504 | so that subsequent calls to \verb|table.getn(table)| return \verb|n|. | ||
3505 | |||
3506 | |||
3421 | \subsection{Mathematical Functions} \label{mathlib} | 3507 | \subsection{Mathematical Functions} \label{mathlib} |
3422 | 3508 | ||
3423 | This library is an interface to most functions of the standard C~math library. | 3509 | This library is an interface to most functions of the standard C~math library. |
3424 | (Some have slightly different names.) | 3510 | (Some have slightly different names.) |
3511 | It provides all its functions inside the table \DefLIB{math}. | ||
3425 | In addition, | 3512 | In addition, |
3426 | it registers a tag method for the binary exponentiation operator \verb|^| that | 3513 | it registers a ??tag method for the binary exponentiation operator \verb|^| |
3427 | returns \Math{x^y} when applied to numbers \verb|x^y|. | 3514 | that returns \Math{x^y} when applied to numbers \verb|x^y|. |
3428 | 3515 | ||
3429 | The library provides the following functions: | 3516 | The library provides the following functions: |
3430 | \DefLIB{abs}\DefLIB{acos}\DefLIB{asin}\DefLIB{atan} | 3517 | \DefLIB{math.abs}\DefLIB{math.acos}\DefLIB{math.asin}\DefLIB{math.atan} |
3431 | \DefLIB{atan2}\DefLIB{ceil}\DefLIB{cos}\DefLIB{def}\DefLIB{exp} | 3518 | \DefLIB{math.atan2}\DefLIB{math.ceil}\DefLIB{math.cos} |
3432 | \DefLIB{floor}\DefLIB{log}\DefLIB{log10}\DefLIB{max}\DefLIB{min} | 3519 | \DefLIB{math.def}\DefLIB{math.exp} |
3433 | \DefLIB{mod}\DefLIB{rad}\DefLIB{sin}\DefLIB{sqrt}\DefLIB{tan} | 3520 | \DefLIB{math.floor}\DefLIB{math.log}\DefLIB{math.log10} |
3434 | \DefLIB{frexp}\DefLIB{ldexp}\DefLIB{random}\DefLIB{randomseed} | 3521 | \DefLIB{math.max}\DefLIB{math.min} |
3522 | \DefLIB{math.mod}\DefLIB{math.rad}\DefLIB{math.sin} | ||
3523 | \DefLIB{math.sqrt}\DefLIB{math.tan} | ||
3524 | \DefLIB{math.frexp}\DefLIB{math.ldexp}\DefLIB{math.random} | ||
3525 | \DefLIB{math.randomseed} | ||
3435 | \begin{verbatim} | 3526 | \begin{verbatim} |
3436 | abs acos asin atan atan2 ceil cos deg exp floor log log10 | 3527 | math.abs math.acos math.asin math.atan math.atan2 |
3437 | max min mod rad sin sqrt tan frexp ldexp random randomseed | 3528 | math.ceil math.cos math.deg math.exp math.floor |
3529 | math.log math.log10 math.max math.min math.mod | ||
3530 | math.rad math.sin math.sqrt math.tan math.frexp | ||
3531 | math.ldexp math.random math.randomseed | ||
3438 | \end{verbatim} | 3532 | \end{verbatim} |
3439 | plus a global variable \IndexLIB{PI}. | 3533 | plus a variable \IndexLIB{math.pi}. |
3440 | Most of them | 3534 | Most of them |
3441 | are only interfaces to the homonymous functions in the C~library, | 3535 | are only interfaces to the homonymous functions in the C~library, |
3442 | except that, for the trigonometric functions, | 3536 | except that, for the trigonometric functions, |
3443 | all angles are expressed in \emph{degrees}, not radians. | 3537 | all angles are expressed in \emph{degrees}, not radians. |
3444 | The functions \verb|deg| and \verb|rad| can be used to convert | 3538 | The functions \verb|math.deg| and \verb|math.rad| can be used to convert |
3445 | between radians and degrees. | 3539 | between radians and degrees. |
3446 | 3540 | ||
3447 | The function \verb|max| returns the maximum | 3541 | The function \verb|math.max| returns the maximum |
3448 | value of its numeric arguments. | 3542 | value of its numeric arguments. |
3449 | Similarly, \verb|min| computes the minimum. | 3543 | Similarly, \verb|math.min| computes the minimum. |
3450 | Both can be used with 1, 2, or more arguments. | 3544 | Both can be used with 1, 2, or more arguments. |
3451 | 3545 | ||
3452 | The functions \verb|random| and \verb|randomseed| are interfaces to | 3546 | The functions \verb|math.random| and \verb|math.randomseed| |
3453 | the simple random generator functions \verb|rand| and \verb|srand|, | 3547 | are interfaces to the simple random generator functions |
3454 | provided by ANSI~C. | 3548 | \verb|rand| and \verb|srand|, provided by ANSI~C. |
3455 | (No guarantees can be given for their statistical properties.) | 3549 | (No guarantees can be given for their statistical properties.) |
3456 | When called without arguments, | 3550 | When called without arguments, |
3457 | \verb|random| returns a pseudo-random real number in the range \Math{[0,1)}. | 3551 | \verb|math.random| returns a pseudo-random real number |
3552 | in the range \Math{[0,1)}. | ||
3458 | When called with a number \Math{n}, | 3553 | When called with a number \Math{n}, |
3459 | \verb|random| returns a pseudo-random integer in the range \Math{[1,n]}. | 3554 | \verb|math.random| returns a pseudo-random integer in the range \Math{[1,n]}. |
3460 | When called with two arguments, \Math{l} and \Math{u}, | 3555 | When called with two arguments, \Math{l} and \Math{u}, |
3461 | \verb|random| returns a pseudo-random integer in the range \Math{[l,u]}. | 3556 | \verb|math.random| returns a pseudo-random integer in the range \Math{[l,u]}. |
3462 | 3557 | ||
3463 | 3558 | ||
3464 | \subsection{Input and Output Facilities} \label{libio} | 3559 | \subsection{Input and Output Facilities} \label{libio} |
3465 | 3560 | ||
3466 | All input and output operations in Lua are done, by default, | 3561 | The I/O library provides two different styles for file manipulation. |
3467 | over two \Def{file handles}: one for reading and one for writing. | 3562 | The first one uses implicit file descriptors; |
3468 | These handles are stored in two Lua global variables, | 3563 | that is, there are operations to set a default input file and a |
3469 | called \verb|_INPUT| and \verb|_OUTPUT|. | 3564 | default output file, |
3470 | The global variables | 3565 | and all input/output operations are over those default files. |
3471 | \verb|_STDIN|, \verb|_STDOUT|, and \verb|_STDERR| | 3566 | The second style uses explicit file descriptors. |
3472 | are initialized with file descriptors for | 3567 | |
3473 | \verb|stdin|, \verb|stdout|, and \verb|stderr|. | 3568 | When using implicit file descriptors, |
3474 | Initially, \verb|_INPUT=_STDIN| and \verb|_OUTPUT=_STDOUT|. | 3569 | all operations are supplied by table \DefLIB{io}. |
3475 | \DefLIB{_INPUT}\DefLIB{_OUTPUT} | 3570 | When using explicit file descriptors, |
3476 | \DefLIB{_STDIN}\DefLIB{_STDOUT}\DefLIB{_STDERR} | 3571 | the operation \DefLIB{io.open} returns a file descriptor, |
3572 | and then all operations are supplied as methods by the file descriptor. | ||
3573 | |||
3574 | Moreover, the table \verb|io| also provides | ||
3575 | three predefined file descriptors: | ||
3576 | \DefLIB{io.stdin}, \DefLIB{io.stdout}, and \DefLIB{io.stderr}, | ||
3577 | with their usual meaning from C. | ||
3477 | 3578 | ||
3478 | A file handle is a userdata containing the file stream (\verb|FILE*|), | 3579 | A file handle is a userdata containing the file stream (\verb|FILE*|), |
3479 | and with a distinctive tag created by the I/O library. | 3580 | with a distinctive metatable created by the I/O library. |
3480 | 3581 | ||
3481 | Unless otherwise stated, | 3582 | Unless otherwise stated, |
3482 | all I/O functions return \nil\ on failure and | 3583 | all I/O functions return \nil{} on failure |
3483 | some value different from \nil\ on success. | 3584 | (plus an error message as a second result) |
3585 | and some value different from \nil{} on success. | ||
3586 | |||
3587 | \subsubsection*{\ff \T{io.close ([handle])}}\DefLIB{io.close} | ||
3588 | |||
3589 | Equivalent to \verb|fh:close| over the default output file. | ||
3590 | |||
3591 | \subsubsection*{\ff \T{io.flush ()}}\DefLIB{io.flush} | ||
3592 | |||
3593 | Equivalent to \verb|fh:flush| over the default output file. | ||
3484 | 3594 | ||
3485 | \subsubsection*{\ff \T{openfile (filename, mode)}}\DefLIB{openfile} | 3595 | \subsubsection*{\ff \T{io.input ([file])}}\DefLIB{io.input} |
3596 | |||
3597 | When called with a file name, it opens the named file (in text mode), | ||
3598 | and sets its handle as the default input file | ||
3599 | (and returns nothing). | ||
3600 | When called with a file handle, | ||
3601 | it simply sets that file handle as the default input file. | ||
3602 | When called without parameters, | ||
3603 | it returns the current default input file. | ||
3604 | |||
3605 | In case of errors this function raises the error, | ||
3606 | instead of returning an error code. | ||
3607 | |||
3608 | \subsubsection*{\ff \T{io.open (filename, mode)}}\DefLIB{io.open} | ||
3486 | 3609 | ||
3487 | This function opens a file, | 3610 | This function opens a file, |
3488 | in the mode specified in the string \verb|mode|. | 3611 | in the mode specified in the string \verb|mode|. |
3489 | It returns a new file handle, | 3612 | It returns a new file handle, |
3490 | or, in case of errors, \nil\ plus a string describing the error. | 3613 | or, in case of errors, \nil{} plus an error message. |
3491 | This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. | ||
3492 | 3614 | ||
3493 | The \verb|mode| string can be any of the following: | 3615 | The \verb|mode| string can be any of the following: |
3494 | \begin{description}\leftskip=20pt | 3616 | \begin{description}\leftskip=20pt |
@@ -3504,141 +3626,41 @@ The \verb|mode| string may also have a \verb|b| at the end, | |||
3504 | which is needed in some systems to open the file in binary mode. | 3626 | which is needed in some systems to open the file in binary mode. |
3505 | This string is exactly what is used in the standard~C function \verb|fopen|. | 3627 | This string is exactly what is used in the standard~C function \verb|fopen|. |
3506 | 3628 | ||
3507 | \subsubsection*{\ff \T{closefile (handle)}}\DefLIB{closefile} | 3629 | \subsubsection*{\ff \T{io.output ([file])}}\DefLIB{io.output} |
3508 | |||
3509 | This function closes the given file. | ||
3510 | It does not modify either \verb|_INPUT| or \verb|_OUTPUT|. | ||
3511 | 3630 | ||
3512 | \subsubsection*{\ff \T{readfrom (filename)}}\DefLIB{readfrom} | 3631 | Similar to \verb|io.input|, but operates over the default output file. |
3513 | 3632 | ||
3514 | This function may be called in two ways. | 3633 | \subsubsection*{\ff \T{io.read (format1, ...)}}\DefLIB{io.read} |
3515 | When called with a file name, it opens the named file (in text mode), | ||
3516 | sets its handle as the value of \verb|_INPUT|, | ||
3517 | and returns this value. | ||
3518 | It does not close the current input file. | ||
3519 | When called without parameters, | ||
3520 | it closes the \verb|_INPUT| file, | ||
3521 | and restores \verb|stdin| as the value of \verb|_INPUT|. | ||
3522 | If this function fails, it returns \nil, | ||
3523 | plus a string describing the error. | ||
3524 | 3634 | ||
3525 | \NOTE | 3635 | Equivalent to \verb|fh:read| over the default input file. |
3526 | If \verb|filename| starts with a \verb-|-, | ||
3527 | then a \Index{piped input} is opened, via function \IndexVerb{popen}. | ||
3528 | Not all systems implement pipes. | ||
3529 | Moreover, | ||
3530 | the number of files that can be open at the same time is | ||
3531 | usually limited and depends on the system. | ||
3532 | |||
3533 | \subsubsection*{\ff \T{writeto (filename)}}\DefLIB{writeto} | ||
3534 | |||
3535 | This function may be called in two ways. | ||
3536 | When called with a file name, | ||
3537 | it opens the named file (in text mode), | ||
3538 | sets its handle as the value of \verb|_OUTPUT|, | ||
3539 | and returns this value. | ||
3540 | It does not close the current output file. | ||
3541 | Note that, if the file already exists, | ||
3542 | then it will be \emph{completely erased} with this operation. | ||
3543 | When called without parameters, | ||
3544 | this function closes the \verb|_OUTPUT| file, | ||
3545 | and restores \verb|stdout| as the value of \verb|_OUTPUT|. | ||
3546 | \index{closing a file} | ||
3547 | If this function fails, it returns \nil, | ||
3548 | plus a string describing the error. | ||
3549 | 3636 | ||
3550 | \NOTE | 3637 | \subsubsection*{\ff \T{io.tmpfile ()}}\DefLIB{io.tmpfile} |
3551 | If \verb|filename| starts with a \verb-|-, | ||
3552 | then a \Index{piped input} is opened, via function \IndexVerb{popen}. | ||
3553 | Not all systems implement pipes. | ||
3554 | Moreover, | ||
3555 | the number of files that can be open at the same time is | ||
3556 | usually limited and depends on the system. | ||
3557 | 3638 | ||
3558 | \subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto} | 3639 | Returns a handle for a temporary file. |
3640 | This file is open in read/write mode, | ||
3641 | and it is automatically removed when the program ends. | ||
3559 | 3642 | ||
3560 | Opens a file named \verb|filename| (in text mode) | 3643 | \subsubsection*{\ff \T{io.write (value1, ...)}}\DefLIB{io.write} |
3561 | sets its handle as the value of \verb|_OUTPUT|, | ||
3562 | and returns this value. | ||
3563 | Unlike the \verb|writeto| operation, | ||
3564 | this function does not erase any previous contents of the file; | ||
3565 | instead, anything written to the file is appended to its end. | ||
3566 | If this function fails, it returns \nil, | ||
3567 | plus a string describing the error. | ||
3568 | 3644 | ||
3569 | \subsubsection*{\ff \T{remove (filename)}}\DefLIB{remove} | 3645 | Equivalent to \verb|fh:write| over the default output file. |
3570 | 3646 | ||
3571 | Deletes the file with the given name. | ||
3572 | If this function fails, it returns \nil, | ||
3573 | plus a string describing the error. | ||
3574 | 3647 | ||
3575 | \subsubsection*{\ff \T{rename (name1, name2)}}\DefLIB{rename} | ||
3576 | 3648 | ||
3577 | Renames file named \verb|name1| to \verb|name2|. | 3649 | \subsubsection*{\ff \T{fh:close ([handle])}}\DefLIB{fh:close} |
3578 | If this function fails, it returns \nil, | ||
3579 | plus a string describing the error. | ||
3580 | 3650 | ||
3581 | \subsubsection*{\ff \T{flush ([filehandle])}}\DefLIB{flush} | 3651 | Closes the file \verb|fh|. |
3582 | 3652 | ||
3583 | Saves any written data to the given file. | 3653 | \subsubsection*{\ff \T{fh:flush ()}}\DefLIB{fh:flush} |
3584 | If \verb|filehandle| is not specified, | ||
3585 | then \verb|flush| flushes all open files. | ||
3586 | If this function fails, it returns \nil, | ||
3587 | plus a string describing the error. | ||
3588 | 3654 | ||
3589 | \subsubsection*{\ff \T{seek (filehandle [, whence] [, offset])}}\DefLIB{seek} | 3655 | Saves any written data to the file \verb|fh|. |
3590 | 3656 | ||
3591 | Sets and gets the file position, | 3657 | \subsubsection*{\ff \T{fh:read (format1, ...)}}\DefLIB{fh:read} |
3592 | measured in bytes from the beginning of the file, | ||
3593 | to the position given by \verb|offset| plus a base | ||
3594 | specified by the string \verb|whence|, as follows: | ||
3595 | \begin{description}\leftskip=20pt | ||
3596 | \item[``set''] base is position 0 (beginning of the file); | ||
3597 | \item[``cur''] base is current position; | ||
3598 | \item[``end''] base is end of file; | ||
3599 | \end{description} | ||
3600 | In case of success, function \verb|seek| returns the final file position, | ||
3601 | measured in bytes from the beginning of the file. | ||
3602 | If this function fails, it returns \nil, | ||
3603 | plus a string describing the error. | ||
3604 | 3658 | ||
3605 | The default value for \verb|whence| is \verb|"cur"|, | 3659 | Reads the file \verb|fh|, |
3606 | and for \verb|offset| is 0. | ||
3607 | Therefore, the call \verb|seek(file)| returns the current | ||
3608 | file position, without changing it; | ||
3609 | the call \verb|seek(file, "set")| sets the position to the | ||
3610 | beginning of the file (and returns 0); | ||
3611 | and the call \verb|seek(file, "end")| sets the position to the | ||
3612 | end of the file, and returns its size. | ||
3613 | |||
3614 | \subsubsection*{\ff \T{tmpfile ()}}\DefLIB{tmpfile} | ||
3615 | |||
3616 | Returns a handle for a temporary file. | ||
3617 | This file is open in read/write mode, | ||
3618 | and it is automatically removed when the program ends. | ||
3619 | |||
3620 | \subsubsection*{\ff \T{tmpname ()}}\DefLIB{tmpname} | ||
3621 | |||
3622 | Returns a string with a file name that can | ||
3623 | be used for a temporary file. | ||
3624 | The file must be explicitly opened before its use | ||
3625 | and removed when no longer needed. | ||
3626 | |||
3627 | This function is equivalent to the \verb|tmpnam| C~function, | ||
3628 | and many people (and even some compilers!) advise against its use, | ||
3629 | because between the time you call the function | ||
3630 | and the time you open the file, | ||
3631 | it is possible for another process | ||
3632 | to create a file with the same name. | ||
3633 | |||
3634 | \subsubsection*{\ff \T{read ([filehandle,] format1, ...)}}\DefLIB{read} | ||
3635 | |||
3636 | Reads file \verb|_INPUT|, | ||
3637 | or \verb|filehandle| if this argument is given, | ||
3638 | according to the given formats, which specify what to read. | 3660 | according to the given formats, which specify what to read. |
3639 | For each format, | 3661 | For each format, |
3640 | the function returns a string (or a number) with the characters read, | 3662 | the function returns a string (or a number) with the characters read, |
3641 | or \nil\ if it cannot read data with the specified format. | 3663 | or \nil{} if it cannot read data with the specified format. |
3642 | When called without formats, | 3664 | When called without formats, |
3643 | it uses a default format that reads the entire next line | 3665 | it uses a default format that reads the entire next line |
3644 | (see below). | 3666 | (see below). |
@@ -3650,34 +3672,61 @@ this is the only format that returns a number instead of a string. | |||
3650 | \item[``*a''] reads the whole file, starting at the current position. | 3672 | \item[``*a''] reads the whole file, starting at the current position. |
3651 | On end of file, it returns the empty string. | 3673 | On end of file, it returns the empty string. |
3652 | \item[``*l''] reads the next line (skipping the end of line), | 3674 | \item[``*l''] reads the next line (skipping the end of line), |
3653 | returning \nil\ on end of file. | 3675 | returning \nil{} on end of file. |
3654 | This is the default format. | 3676 | This is the default format. |
3655 | \item[\emph{number}] reads a string with up to that number of characters, | 3677 | \item[\emph{number}] reads a string with up to that number of characters, |
3656 | or \nil\ on end of file. | 3678 | or \nil{} on end of file. |
3657 | If number is zero, | 3679 | If number is zero, |
3658 | it reads nothing and returns an empty string, | 3680 | it reads nothing and returns an empty string, |
3659 | or \nil\ on end of file. | 3681 | or \nil{} on end of file. |
3682 | \end{description} | ||
3683 | |||
3684 | \subsubsection*{\ff \T{fh:seek ([whence] [, offset])}}\DefLIB{fh:seek} | ||
3685 | |||
3686 | Sets and gets the file position, | ||
3687 | measured in bytes from the beginning of the file, | ||
3688 | to the position given by \verb|offset| plus a base | ||
3689 | specified by the string \verb|whence|, as follows: | ||
3690 | \begin{description}\leftskip=20pt | ||
3691 | \item[``set''] base is position 0 (beginning of the file); | ||
3692 | \item[``cur''] base is current position; | ||
3693 | \item[``end''] base is end of file; | ||
3660 | \end{description} | 3694 | \end{description} |
3695 | In case of success, function \verb|seek| returns the final file position, | ||
3696 | measured in bytes from the beginning of the file. | ||
3697 | If this function fails, it returns \nil, | ||
3698 | plus a string describing the error. | ||
3699 | |||
3700 | The default value for \verb|whence| is \verb|"cur"|, | ||
3701 | and for \verb|offset| is 0. | ||
3702 | Therefore, the call \verb|file:seek()| returns the current | ||
3703 | file position, without changing it; | ||
3704 | the call \verb|file:seek("set")| sets the position to the | ||
3705 | beginning of the file (and returns 0); | ||
3706 | and the call \verb|file:seek("end")| sets the position to the | ||
3707 | end of the file, and returns its size. | ||
3661 | 3708 | ||
3662 | \subsubsection*{\ff \T{write ([filehandle, ] value1, ...)}}\DefLIB{write} | 3709 | \subsubsection*{\ff \T{fh:write (value1, ...)}}\DefLIB{fh:write} |
3663 | 3710 | ||
3664 | Writes the value of each of its arguments to | 3711 | Writes the value of each of its arguments to |
3665 | filehandle \verb|_OUTPUT|, | 3712 | the filehandle \verb|fh|. |
3666 | or to \verb|filehandle| if this argument is given. | ||
3667 | The arguments must be strings or numbers. | 3713 | The arguments must be strings or numbers. |
3668 | To write other values, | 3714 | To write other values, |
3669 | use \verb|tostring| or \verb|format| before \verb|write|. | 3715 | use \verb|tostring| or \verb|format| before \verb|write|. |
3670 | If this function fails, it returns \nil, | 3716 | If this function fails, it returns \nil, |
3671 | plus a string describing the error. | 3717 | plus a string describing the error. |
3672 | 3718 | ||
3673 | \subsection{System Facilities} \label{libiosys} | ||
3674 | 3719 | ||
3675 | \subsubsection*{\ff \T{clock ()}}\DefLIB{clock} | 3720 | \subsection{Operating System Facilities} \label{libiosys} |
3721 | |||
3722 | This library is implemented through table \DefLIB{os}. | ||
3723 | |||
3724 | \subsubsection*{\ff \T{os.clock ()}}\DefLIB{os.clock} | ||
3676 | 3725 | ||
3677 | Returns an approximation of the amount of CPU time | 3726 | Returns an approximation of the amount of CPU time |
3678 | used by the program, in seconds. | 3727 | used by the program, in seconds. |
3679 | 3728 | ||
3680 | \subsubsection*{\ff \T{date ([format [, time]])}}\DefLIB{date} | 3729 | \subsubsection*{\ff \T{os.date ([format [, time]])}}\DefLIB{os.date} |
3681 | 3730 | ||
3682 | Returns a string or a table containing date and time, | 3731 | Returns a string or a table containing date and time, |
3683 | formatted according to the given string \verb|format|. | 3732 | formatted according to the given string \verb|format|. |
@@ -3693,45 +3742,57 @@ then the date is formatted in Coordinated Universal Time. | |||
3693 | After that optional character, | 3742 | After that optional character, |
3694 | if \verb|format| is \verb|*t|, | 3743 | if \verb|format| is \verb|*t|, |
3695 | then \verb|date| returns a table with the following fields: | 3744 | then \verb|date| returns a table with the following fields: |
3696 | \verb|year|, \verb|month| (1--12), \verb|day| (1--31), | 3745 | \verb|year| (four digits), \verb|month| (1--12), \verb|day| (1--31), |
3697 | \verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--59), | 3746 | \verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--61), |
3698 | \verb|wday| (weekday, Sunday is 1), | 3747 | \verb|wday| (weekday, Sunday is 1), |
3699 | \verb|yday| (day of the year), | 3748 | \verb|yday| (day of the year), |
3700 | and \verb|isdst| (daylight saving flag). | 3749 | and \verb|isdst| (daylight saving flag, a boolean). |
3701 | 3750 | ||
3702 | If format is not \verb|*t|, | 3751 | If format is not \verb|*t|, |
3703 | then \verb|date| returns the date as a string, | 3752 | then \verb|date| returns the date as a string, |
3704 | formatted according with the same rules as the C~function \verb|strftime|. | 3753 | formatted according with the same rules as the C~function \verb|strftime|. |
3705 | When called without arguments, | 3754 | When called without arguments, |
3706 | \verb|date| returns a reasonable date and time representation that depends on | 3755 | \verb|date| returns a reasonable date and time representation that depends on |
3707 | the host system and on the current locale (thus, \verb|date()| is equivalent | 3756 | the host system and on the current locale |
3708 | to \verb|date("%c")|). | 3757 | (that is, \verb|os.date()| is equivalent to \verb|os.date("%c")|). |
3709 | 3758 | ||
3710 | \subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime} | 3759 | \subsubsection*{\ff \T{os.difftime (t1, t2)}}\DefLIB{os.difftime} |
3711 | 3760 | ||
3712 | Returns the number of seconds from time \verb|t1| to time \verb|t2|. | 3761 | Returns the number of seconds from time \verb|t1| to time \verb|t2|. |
3713 | In Posix, Windows, and some other systems, | 3762 | In Posix, Windows, and some other systems, |
3714 | this value is exactly \verb|t1|\Math{-}\verb|t2|. | 3763 | this value is exactly \verb|t1|\Math{-}\verb|t2|. |
3715 | 3764 | ||
3716 | \subsubsection*{\ff \T{execute (command)}}\DefLIB{execute} | 3765 | \subsubsection*{\ff \T{os.execute (command)}}\DefLIB{os.execute} |
3717 | 3766 | ||
3718 | This function is equivalent to the C~function \verb|system|. | 3767 | This function is equivalent to the C~function \verb|system|. |
3719 | It passes \verb|command| to be executed by an operating system shell. | 3768 | It passes \verb|command| to be executed by an operating system shell. |
3720 | It returns a status code, which is system-dependent. | 3769 | It returns a status code, which is system-dependent. |
3721 | 3770 | ||
3722 | \subsubsection*{\ff \T{exit ([code])}}\DefLIB{exit} | 3771 | \subsubsection*{\ff \T{os.exit ([code])}}\DefLIB{os.exit} |
3723 | 3772 | ||
3724 | Calls the C~function \verb|exit|, | 3773 | Calls the C~function \verb|exit|, |
3725 | with an optional \verb|code|, | 3774 | with an optional \verb|code|, |
3726 | to terminate the host program. | 3775 | to terminate the host program. |
3727 | The default value for \verb|code| is the success code. | 3776 | The default value for \verb|code| is the success code. |
3728 | 3777 | ||
3729 | \subsubsection*{\ff \T{getenv (varname)}}\DefLIB{getenv} | 3778 | \subsubsection*{\ff \T{os.getenv (varname)}}\DefLIB{os.getenv} |
3730 | 3779 | ||
3731 | Returns the value of the process environment variable \verb|varname|, | 3780 | Returns the value of the process environment variable \verb|varname|, |
3732 | or \nil\ if the variable is not defined. | 3781 | or \nil{} if the variable is not defined. |
3782 | |||
3783 | \subsubsection*{\ff \T{os.remove (filename)}}\DefLIB{os.remove} | ||
3784 | |||
3785 | Deletes the file with the given name. | ||
3786 | If this function fails, it returns \nil, | ||
3787 | plus a string describing the error. | ||
3733 | 3788 | ||
3734 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\DefLIB{setlocale} | 3789 | \subsubsection*{\ff \T{os.rename (name1, name2)}}\DefLIB{os.rename} |
3790 | |||
3791 | Renames file named \verb|name1| to \verb|name2|. | ||
3792 | If this function fails, it returns \nil, | ||
3793 | plus a string describing the error. | ||
3794 | |||
3795 | \subsubsection*{\ff \T{os.setlocale (locale [, category])}}\DefLIB{os.setlocale} | ||
3735 | 3796 | ||
3736 | This function is an interface to the C~function \verb|setlocale|. | 3797 | This function is an interface to the C~function \verb|setlocale|. |
3737 | \verb|locale| is a string specifying a locale; | 3798 | \verb|locale| is a string specifying a locale; |
@@ -3740,15 +3801,15 @@ This function is an interface to the C~function \verb|setlocale|. | |||
3740 | \verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|; | 3801 | \verb|"monetary"|, \verb|"numeric"|, or \verb|"time"|; |
3741 | the default category is \verb|"all"|. | 3802 | the default category is \verb|"all"|. |
3742 | The function returns the name of the new locale, | 3803 | The function returns the name of the new locale, |
3743 | or \nil\ if the request cannot be honored. | 3804 | or \nil{} if the request cannot be honored. |
3744 | 3805 | ||
3745 | \subsubsection*{\ff \T{time ([table])}}\DefLIB{time} | 3806 | \subsubsection*{\ff \T{os.time ([table])}}\DefLIB{os.time} |
3746 | 3807 | ||
3747 | Returns the current time when called without arguments, | 3808 | Returns the current time when called without arguments, |
3748 | or a time representing the date and time specified by the given table. | 3809 | or a time representing the date and time specified by the given table. |
3749 | This table must have fields \verb|year|, \verb|month|, and \verb|day|, | 3810 | This table must have fields \verb|year|, \verb|month|, and \verb|day|, |
3750 | and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| | 3811 | and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| |
3751 | (for a description of these fields, see the \verb|date| function). | 3812 | (for a description of these fields, see the \verb|os.date| function). |
3752 | 3813 | ||
3753 | The returned value is a number, whose meaning depends on your system. | 3814 | The returned value is a number, whose meaning depends on your system. |
3754 | In Posix, Windows, and some other systems, this number counts the number | 3815 | In Posix, Windows, and some other systems, this number counts the number |
@@ -3757,6 +3818,21 @@ In other systems, the meaning is not specified, | |||
3757 | and the number returned bt \verb|time| can be used only as an argument to | 3818 | and the number returned bt \verb|time| can be used only as an argument to |
3758 | \verb|date| and \verb|difftime|. | 3819 | \verb|date| and \verb|difftime|. |
3759 | 3820 | ||
3821 | \subsubsection*{\ff \T{os.tmpname ()}}\DefLIB{os.tmpname} | ||
3822 | |||
3823 | Returns a string with a file name that can | ||
3824 | be used for a temporary file. | ||
3825 | The file must be explicitly opened before its use | ||
3826 | and removed when no longer needed. | ||
3827 | |||
3828 | This function is equivalent to the \verb|tmpnam| C~function, | ||
3829 | and many people (and even some compilers!) advise against its use, | ||
3830 | because between the time you call the function | ||
3831 | and the time you open the file, | ||
3832 | it is possible for another process | ||
3833 | to create a file with the same name. | ||
3834 | |||
3835 | |||
3760 | \subsection{The Reflexive Debug Interface} | 3836 | \subsection{The Reflexive Debug Interface} |
3761 | 3837 | ||
3762 | The library \verb|ldblib| provides | 3838 | The library \verb|ldblib| provides |
@@ -3808,7 +3884,7 @@ This function returns the name and the value of the local variable | |||
3808 | with index \verb|local| of the function at level \verb|level| of the stack. | 3884 | with index \verb|local| of the function at level \verb|level| of the stack. |
3809 | (The first parameter or local variable has index~1, and so on, | 3885 | (The first parameter or local variable has index~1, and so on, |
3810 | until the last active local variable.) | 3886 | until the last active local variable.) |
3811 | The function returns \nil\ if there is no local | 3887 | The function returns \nil{} if there is no local |
3812 | variable with the given index, | 3888 | variable with the given index, |
3813 | and raises an error when called with a \verb|level| out of range. | 3889 | and raises an error when called with a \verb|level| out of range. |
3814 | (You can call \verb|getinfo| to check whether the level is valid.) | 3890 | (You can call \verb|getinfo| to check whether the level is valid.) |
@@ -3817,7 +3893,7 @@ and raises an error when called with a \verb|level| out of range. | |||
3817 | 3893 | ||
3818 | This function assigns the value \verb|value| to the local variable | 3894 | This function assigns the value \verb|value| to the local variable |
3819 | with index \verb|local| of the function at level \verb|level| of the stack. | 3895 | with index \verb|local| of the function at level \verb|level| of the stack. |
3820 | The function returns \nil\ if there is no local | 3896 | The function returns \nil{} if there is no local |
3821 | variable with the given index, | 3897 | variable with the given index, |
3822 | and raises an error when called with a \verb|level| out of range. | 3898 | and raises an error when called with a \verb|level| out of range. |
3823 | (You can call \verb|getinfo| to check whether the level is valid.) | 3899 | (You can call \verb|getinfo| to check whether the level is valid.) |
@@ -3858,84 +3934,83 @@ it is also frequently used as a stand-alone language. | |||
3858 | An interpreter for Lua as a stand-alone language, | 3934 | An interpreter for Lua as a stand-alone language, |
3859 | called simply \verb|lua|, | 3935 | called simply \verb|lua|, |
3860 | is provided with the standard distribution. | 3936 | is provided with the standard distribution. |
3861 | This program can be called with any sequence of the following arguments: | 3937 | The stand-alone interpreter includes |
3938 | all standard libraries plus the reflexive debug interface. | ||
3939 | Its usage is: | ||
3940 | \begin{verbatim} | ||
3941 | lua [options] [prog [args]] | ||
3942 | \end{verbatim} | ||
3943 | The options are: | ||
3862 | \begin{description}\leftskip=20pt | 3944 | \begin{description}\leftskip=20pt |
3863 | \item[\T{-sNUM}] sets the stack size to \T{NUM} | ||
3864 | (if present, this must be the first option); | ||
3865 | \item[\T{-} ] executes \verb|stdin| as a file; | 3945 | \item[\T{-} ] executes \verb|stdin| as a file; |
3866 | \item[\T{-c}] calls \verb|lua_close| after processing all arguments; | ||
3867 | \item[\T{-e} \rm\emph{stat}] executes string \emph{stat}; | 3946 | \item[\T{-e} \rm\emph{stat}] executes string \emph{stat}; |
3868 | \item[\T{-f} \rm\emph{filename}] executes file \emph{filename} with the | 3947 | \item[\T{-l} \rm\emph{file}] executes file \emph{file}; |
3869 | remaining arguments in table \verb|arg|; | 3948 | \item[\T{-i}] enters interactive mode after running \emph{prog}; |
3870 | \item[\T{-i}] enters interactive mode with prompt; | ||
3871 | \item[\T{-q}] enters interactive mode without prompt; | ||
3872 | \item[\T{-v}] prints version information; | 3949 | \item[\T{-v}] prints version information; |
3873 | \item[\T{var=}\rm\emph{value}] sets global \verb|var| to string \verb|"|\emph{value}\verb|"|; | 3950 | \item[\T{--}] stop handling options. |
3874 | \item[\emph{filename}] executes file \emph{filename}. | ||
3875 | \end{description} | 3951 | \end{description} |
3952 | After handling its options, \verb|lua| runs the given \emph{prog}, | ||
3953 | passing to it the given \emph{args}. | ||
3876 | When called without arguments, | 3954 | When called without arguments, |
3877 | \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, | 3955 | \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, |
3878 | and as \verb|lua -| otherwise. | 3956 | and as \verb|lua -| otherwise. |
3879 | 3957 | ||
3880 | All arguments are handled in order, except \verb|-c|. | 3958 | Before running any argument, |
3959 | the intepreter checks for an environment variable \IndexVerb{LUA_INIT}. | ||
3960 | If its format is \verb|@|\emph{filename}, | ||
3961 | then lua executes the file. | ||
3962 | Otherwise, lua executes the string itself. | ||
3963 | |||
3964 | All options are handled in order, except \verb|-i|. | ||
3881 | For instance, an invocation like | 3965 | For instance, an invocation like |
3882 | \begin{verbatim} | 3966 | \begin{verbatim} |
3883 | $ lua -i a=test prog.lua | 3967 | $ lua -e'a=1' -e 'print(a)' prog.lua |
3884 | \end{verbatim} | 3968 | \end{verbatim} |
3885 | will first interact with the user until an \verb|EOF| in \verb|stdin|, | 3969 | will first set \verb|a| to 1, then print \verb|a|, |
3886 | then will set \verb|a| to \verb|"test"|, | 3970 | and finally run the file \verb|prog.lua|. |
3887 | and finally will run the file \verb|prog.lua|. | 3971 | (Here, \verb|$| is the shell prompt. Your prompt may be different.) |
3888 | (Here, | 3972 | |
3889 | \verb|$| is the shell prompt. Your prompt may be different.) | 3973 | Before starting to run the program, |
3890 | 3974 | \verb|lua| collects all arguments in the command line | |
3891 | When the option \T{-f filename} is used, | 3975 | in a global table called \verb|arg|. |
3892 | all remaining arguments in the command line | 3976 | The program name is stored in index 0, |
3893 | are passed to the Lua program \verb|filename| in a table called \verb|arg|. | 3977 | the first argument after the program goes to index 1, |
3894 | In this table, | 3978 | and so on. |
3895 | the field \verb|n| gets the index of the last argument, | 3979 | The field \verb|n| gets the number of arguments after the program name. |
3896 | and the field 0 gets \verb|"filename"|. | 3980 | Any argument before the program name |
3981 | (that is, the options plus the interpreter name) | ||
3982 | goes to negative indices. | ||
3897 | For instance, in the call | 3983 | For instance, in the call |
3898 | \begin{verbatim} | 3984 | \begin{verbatim} |
3899 | $ lua a.lua -f b.lua t1 t3 | 3985 | $ lua -la.lua b.lua t1 t2 |
3900 | \end{verbatim} | 3986 | \end{verbatim} |
3901 | the interpreter first runs the file \T{a.lua}, | 3987 | the interpreter first runs the file \T{a.lua}, |
3902 | then creates a table | 3988 | then creates a table |
3903 | \begin{verbatim} | 3989 | \begin{verbatim} |
3904 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} | 3990 | arg = { [-2] = "lua", [-1] = "-la.lua", [0] = "b.lua", |
3991 | [1] = "t1", [2] = "t2"; n = 2 } | ||
3905 | \end{verbatim} | 3992 | \end{verbatim} |
3906 | and finally runs the file \T{b.lua}. | 3993 | and finally runs the file \T{b.lua}. |
3907 | 3994 | ||
3908 | The stand-alone interpreter includes | ||
3909 | all standard libraries plus the reflexive debug interface. | ||
3910 | It also provides a \verb|getargs| function that | ||
3911 | can be used to access \emph{all} command line arguments. | ||
3912 | \DefLIB{getargs} | ||
3913 | For instance, if you call Lua with the line | ||
3914 | \begin{verbatim} | ||
3915 | $ lua -c a b | ||
3916 | \end{verbatim} | ||
3917 | then a call to \verb|getargs| in \verb|a| or \verb|b| will return the table | ||
3918 | \begin{verbatim} | ||
3919 | {[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3} | ||
3920 | \end{verbatim} | ||
3921 | |||
3922 | In interactive mode, | 3995 | In interactive mode, |
3923 | a multi-line statement can be written ending intermediate | 3996 | if you write an incomplete statement, |
3924 | lines with a backslash (`\verb|\|'). | 3997 | the interpreter waits for its completion. |
3998 | |||
3925 | If the global variable \IndexVerb{_PROMPT} is defined as a string, | 3999 | If the global variable \IndexVerb{_PROMPT} is defined as a string, |
3926 | then its value is used as the prompt. | 4000 | then its value is used as the prompt. |
3927 | Therefore, the prompt can be changed directly on the command line: | 4001 | Therefore, the prompt can be changed directly on the command line: |
3928 | \begin{verbatim} | 4002 | \begin{verbatim} |
3929 | $ lua _PROMPT='myprompt> ' -i | 4003 | $ lua -e"_PROMPT='myprompt> '" -i |
3930 | \end{verbatim} | 4004 | \end{verbatim} |
4005 | (the first pair of quotes is for the shell, | ||
4006 | the second is for Lua), | ||
3931 | or in any Lua programs by assigning to \verb|_PROMPT|. | 4007 | or in any Lua programs by assigning to \verb|_PROMPT|. |
3932 | Note the use of \verb|-i| to enter interactive mode; otherwise, | 4008 | Note the use of \verb|-i| to enter interactive mode; otherwise, |
3933 | the program would end just after the assignment to \verb|_PROMPT|. | 4009 | the program would end just after the assignment to \verb|_PROMPT|. |
3934 | 4010 | ||
3935 | In Unix systems, Lua scripts can be made into executable programs | 4011 | In Unix systems, Lua scripts can be made into executable programs |
3936 | by using \verb|chmod +x| and the~\verb|#!| form, | 4012 | by using \verb|chmod +x| and the~\verb|#!| form, |
3937 | as in \verb|#!/usr/local/bin/lua|, | 4013 | as in \verb|#!/usr/local/bin/lua|. |
3938 | or \verb|#!/usr/local/bin/lua -f| to get other arguments. | ||
3939 | (Of course, | 4014 | (Of course, |
3940 | the location of the Lua interpreter may be different in your machine. | 4015 | the location of the Lua interpreter may be different in your machine. |
3941 | If \verb|lua| is in your \verb|PATH|, | 4016 | If \verb|lua| is in your \verb|PATH|, |
@@ -3945,6 +4020,8 @@ then a more portable solution is \verb|#!/usr/bin/env lua|.) | |||
3945 | %------------------------------------------------------------------------------ | 4020 | %------------------------------------------------------------------------------ |
3946 | \section*{Acknowledgments} | 4021 | \section*{Acknowledgments} |
3947 | 4022 | ||
4023 | %% TODO rever isso? | ||
4024 | |||
3948 | The authors thank CENPES/PETROBRAS which, | 4025 | The authors thank CENPES/PETROBRAS which, |
3949 | jointly with \tecgraf, used early versions of | 4026 | jointly with \tecgraf, used early versions of |
3950 | this system extensively and gave valuable comments. | 4027 | this system extensively and gave valuable comments. |
@@ -3977,7 +4054,7 @@ A function call as the last expression in a list constructor | |||
3977 | (like \verb|{a,b,f()}}|) has all its return values inserted in the list. | 4054 | (like \verb|{a,b,f()}}|) has all its return values inserted in the list. |
3978 | 4055 | ||
3979 | \item | 4056 | \item |
3980 | \rwd{global} and \rwd{in} are reserved words. | 4057 | \rwd{in} is a reserved word. |
3981 | 4058 | ||
3982 | \item | 4059 | \item |
3983 | When a literal string of the form \verb|[[...]]| starts with a newline, | 4060 | When a literal string of the form \verb|[[...]]| starts with a newline, |
@@ -3997,11 +4074,6 @@ The \verb|read| option \verb|*w| is obsolete. | |||
3997 | \item | 4074 | \item |
3998 | The \verb|format| option \verb|%n$| is obsolete. | 4075 | The \verb|format| option \verb|%n$| is obsolete. |
3999 | 4076 | ||
4000 | \item | ||
4001 | \verb|newtag| is deprecated, being replaced by \verb|newtype|. | ||
4002 | Tags created in Lua with \verb|newtype| (or \verb|newtag|) can only | ||
4003 | be used for tables. | ||
4004 | |||
4005 | \end{itemize} | 4077 | \end{itemize} |
4006 | 4078 | ||
4007 | 4079 | ||
@@ -4009,22 +4081,30 @@ be used for tables. | |||
4009 | \begin{itemize} | 4081 | \begin{itemize} |
4010 | 4082 | ||
4011 | \item | 4083 | \item |
4012 | The \verb|lua_pushuserdata| function has been replaced by | 4084 | Userdata!! |
4013 | \verb|lua_newuserdatabox|. | ||
4014 | 4085 | ||
4015 | \end{itemize} | 4086 | \end{itemize} |
4016 | 4087 | ||
4017 | %{=============================================================== | 4088 | %{=============================================================== |
4018 | \newpage | 4089 | \newpage |
4019 | \section*{The Complete Syntax of Lua} \label{BNF} | 4090 | \section*{The Complete Syntax of Lua} \label{BNF} |
4020 | |||
4021 | \addcontentsline{toc}{section}{The Complete Syntax of Lua} | 4091 | \addcontentsline{toc}{section}{The Complete Syntax of Lua} |
4022 | 4092 | ||
4093 | The notation used here is the usual extended BNF, | ||
4094 | in which | ||
4095 | \rep{\emph{a}}~means 0 or more \emph{a}'s, and | ||
4096 | \opt{\emph{a}}~means an optional \emph{a}. | ||
4097 | Non-terminals are shown in \emph{italics}, | ||
4098 | keywords are shown in {\bf bold}, | ||
4099 | and other terminal symbols are shown in {\tt typewriter} font, | ||
4100 | enclosed in single quotes. | ||
4101 | |||
4102 | |||
4023 | \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} | 4103 | \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} |
4024 | 4104 | ||
4025 | \renewcommand{\OrNL}{\\ & \Or & } | 4105 | \renewcommand{\OrNL}{\\ & \Or & } |
4026 | %\newcommand{\Nter}[1]{{\rm{\tt#1}}} | 4106 | %\newcommand{\Nter}[1]{{\rm{\tt#1}}} |
4027 | \newcommand{\Nter}[1]{#1} | 4107 | %\newcommand{\Nter}[1]{\ter{#1}} |
4028 | 4108 | ||
4029 | \index{grammar} | 4109 | \index{grammar} |
4030 | 4110 | ||
@@ -4049,7 +4129,8 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4049 | \rwd{do} block \rwd{end} | 4129 | \rwd{do} block \rwd{end} |
4050 | \OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1 | 4130 | \OrNL \rwd{for} \Nter{Name} \rep{\ter{,} \Nter{Name}} \rwd{in} explist1 |
4051 | \rwd{do} block \rwd{end} | 4131 | \rwd{do} block \rwd{end} |
4052 | \OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} | 4132 | \OrNL \rwd{function} funcname funcbody |
4133 | \OrNL \rwd{local} \rwd{function} \Nter{Name} funcbody | ||
4053 | \OrNL \rwd{local} namelist \opt{init} | 4134 | \OrNL \rwd{local} namelist \opt{init} |
4054 | } | 4135 | } |
4055 | 4136 | ||
@@ -4072,8 +4153,10 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4072 | 4153 | ||
4073 | \produc{exp}{% | 4154 | \produc{exp}{% |
4074 | \rwd{nil} | 4155 | \rwd{nil} |
4156 | \rwd{false} | ||
4157 | \rwd{true} | ||
4075 | \Or \Nter{Number} | 4158 | \Or \Nter{Number} |
4076 | \Or \Nter{Literal} | 4159 | \OrNL \Nter{Literal} |
4077 | \Or function | 4160 | \Or function |
4078 | \Or prefixexp | 4161 | \Or prefixexp |
4079 | \OrNL tableconstructor | 4162 | \OrNL tableconstructor |
@@ -4094,7 +4177,9 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4094 | \Or \Nter{Literal} | 4177 | \Or \Nter{Literal} |
4095 | } | 4178 | } |
4096 | 4179 | ||
4097 | \produc{function}{\rwd{function} \ter{(} \opt{parlist1} \ter{)} block \rwd{end}} | 4180 | \produc{function}{\rwd{function} funcbody} |
4181 | |||
4182 | \produc{funcbody}{\ter{(} \opt{parlist1} \ter{)} block \rwd{end}} | ||
4098 | 4183 | ||
4099 | \produc{parlist1}{% | 4184 | \produc{parlist1}{% |
4100 | \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}} | 4185 | \Nter{Name} \rep{\ter{,} \Nter{Name}} \opt{\ter{,} \ter{\ldots}} |