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