diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1997-06-17 15:45:16 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1997-06-17 15:45:16 -0300 |
commit | 70160320b120a6afb629c8fd1ebb3005682bafb9 (patch) | |
tree | 576bc4b84c28265dee3076717ac5c3dc746f44c5 | |
parent | bfbf56f15a544633c841666e0e33bd66ef398312 (diff) | |
download | lua-70160320b120a6afb629c8fd1ebb3005682bafb9.tar.gz lua-70160320b120a6afb629c8fd1ebb3005682bafb9.tar.bz2 lua-70160320b120a6afb629c8fd1ebb3005682bafb9.zip |
first version for Lua 3.0 (with tag methods, etc)
-rw-r--r-- | manual.tex | 1005 |
1 files changed, 694 insertions, 311 deletions
@@ -1,9 +1,10 @@ | |||
1 | % $Id: manual.tex,v 1.29 1997/03/06 22:19:08 roberto Exp roberto $ | 1 | % $Id: manual.tex,v 1.30 1997/06/09 18:16:33 roberto Exp roberto $ |
2 | 2 | ||
3 | \documentstyle[fullpage,11pt,bnf]{article} | 3 | \documentstyle[fullpage,11pt,bnf]{article} |
4 | 4 | ||
5 | \newcommand{\rw}[1]{{\bf #1}} | 5 | \newcommand{\rw}[1]{{\bf #1}} |
6 | \newcommand{\see}[1]{(see Section~\ref{#1})} | 6 | \newcommand{\See}[1]{Section~\ref{#1}} |
7 | \newcommand{\see}[1]{(see \See{#1})} | ||
7 | \newcommand{\M}[1]{$#1$} | 8 | \newcommand{\M}[1]{$#1$} |
8 | \newcommand{\nil}{{\bf nil}} | 9 | \newcommand{\nil}{{\bf nil}} |
9 | \newcommand{\Line}{\rule{\linewidth}{.5mm}} | 10 | \newcommand{\Line}{\rule{\linewidth}{.5mm}} |
@@ -16,7 +17,7 @@ | |||
16 | 17 | ||
17 | \newcommand{\ff}{$\bullet$\ } | 18 | \newcommand{\ff}{$\bullet$\ } |
18 | 19 | ||
19 | \newcommand{\Version}{2.5} | 20 | \newcommand{\Version}{3.0} |
20 | 21 | ||
21 | \makeindex | 22 | \makeindex |
22 | 23 | ||
@@ -36,7 +37,7 @@ Waldemar Celes | |||
36 | \tecgraf\ --- Departamento de Inform\'atica --- PUC-Rio | 37 | \tecgraf\ --- Departamento de Inform\'atica --- PUC-Rio |
37 | } | 38 | } |
38 | 39 | ||
39 | \date{\small \verb$Date: 1997/03/06 22:19:08 $} | 40 | \date{\small \verb$Date: 1997/06/09 18:16:33 $} |
40 | 41 | ||
41 | \maketitle | 42 | \maketitle |
42 | 43 | ||
@@ -70,7 +71,7 @@ a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. | |||
70 | \begin{quotation} | 71 | \begin{quotation} |
71 | \noindent | 72 | \noindent |
72 | \footnotesize | 73 | \footnotesize |
73 | Copyright (c) 1994--1996 TeCGraf, PUC-Rio. Written by Waldemar Celes Filho, | 74 | Copyright (c) 1994--1997 TeCGraf, PUC-Rio. Written by Waldemar Celes Filho, |
74 | Roberto Ierusalimschy, Luiz Henrique de Figueiredo. All rights reserved. | 75 | Roberto Ierusalimschy, Luiz Henrique de Figueiredo. All rights reserved. |
75 | % | 76 | % |
76 | Permission is hereby granted, without written agreement and without license or | 77 | Permission is hereby granted, without written agreement and without license or |
@@ -111,9 +112,8 @@ documentation. | |||
111 | Lua is an extension programming language designed to support | 112 | Lua is an extension programming language designed to support |
112 | general procedural programming features with data description | 113 | general procedural programming features with data description |
113 | facilities. | 114 | facilities. |
114 | It is intended to be used as a | 115 | It is intended to be used as a light-weight, but powerful, |
115 | light-weight, but powerful, configuration language for any | 116 | configuration language for any program that needs one. |
116 | program that needs one. | ||
117 | Lua has been designed and implemented by | 117 | Lua has been designed and implemented by |
118 | W.~Celes, | 118 | W.~Celes, |
119 | R.~Ierusalimschy and | 119 | R.~Ierusalimschy and |
@@ -184,20 +184,22 @@ are interchangeable. | |||
184 | Lua automatically detects the file type and acts accordingly. | 184 | Lua automatically detects the file type and acts accordingly. |
185 | \index{pre-compilation} | 185 | \index{pre-compilation} |
186 | 186 | ||
187 | \section{\Index{Types}} \label{TypesSec} | 187 | \section{\Index{Types and Tags}} \label{TypesSec} |
188 | 188 | ||
189 | Lua is a dynamically typed language. | 189 | Lua is a dynamically typed language. |
190 | Variables do not have types; only values do. | 190 | Variables do not have types; only values do. |
191 | All values carry their own type. | ||
192 | Therefore, there are no type definitions in the language. | 191 | Therefore, there are no type definitions in the language. |
192 | All values carry their own type. | ||
193 | Besides a type, all values also have a \Index{tag}. | ||
193 | 194 | ||
194 | There are seven \Index{basic types} in Lua: \Def{nil}, \Def{number}, | 195 | There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, |
195 | \Def{string}, \Def{function}, \Def{CFunction}, \Def{userdata}, | 196 | \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. |
196 | and \Def{table}. | ||
197 | {\em Nil\/} is the type of the value \nil, | 197 | {\em Nil\/} is the type of the value \nil, |
198 | whose main property is to be different from any other value. | 198 | whose main property is to be different from any other value. |
199 | {\em Number\/} represents real (floating point) numbers, | 199 | {\em Number\/} represents real (floating point) numbers, |
200 | while {\em string\/} has the usual meaning. | 200 | while {\em string\/} has the usual meaning. |
201 | The function \verb|type| returns a string describing the type | ||
202 | of a given value. | ||
201 | 203 | ||
202 | Functions are considered first-class values in Lua. | 204 | Functions are considered first-class values in Lua. |
203 | This means that functions can be stored in variables, | 205 | This means that functions can be stored in variables, |
@@ -205,14 +207,18 @@ passed as arguments to other functions and returned as results. | |||
205 | When a function is defined in Lua, its body is compiled and stored | 207 | When a function is defined in Lua, its body is compiled and stored |
206 | in a given variable. | 208 | in a given variable. |
207 | Lua can call (and manipulate) functions written in Lua and | 209 | Lua can call (and manipulate) functions written in Lua and |
208 | functions written in C; the latter have type {\em CFunction}. | 210 | functions written in C. |
211 | They can be distinguished by their tags: | ||
212 | all Lua functions have the same tag, | ||
213 | which is different from the tag for all C functions. | ||
209 | 214 | ||
210 | The type {\em userdata\/} is provided to allow | 215 | The type {\em userdata\/} is provided to allow |
211 | arbitrary \Index{C pointers} to be stored in Lua variables. | 216 | arbitrary \Index{C pointers} to be stored in Lua variables. |
212 | It corresponds to \verb|void*| and has no pre-defined operations in Lua, | 217 | It corresponds to a \verb|void*| and has no pre-defined operations in Lua, |
213 | besides assignment and equality test. | 218 | besides assignment and equality test. |
214 | However, by using fallbacks, the programmer may define operations | 219 | However, by using {\em tag methods}, |
215 | for {\em userdata\/} values; \see{fallback}. | 220 | the programmer may define operations for {\em userdata\/} values |
221 | \see{tag-method}. | ||
216 | 222 | ||
217 | The type {\em table\/} implements \Index{associative arrays}, | 223 | The type {\em table\/} implements \Index{associative arrays}, |
218 | that is, \Index{arrays} that can be indexed not only with numbers, | 224 | that is, \Index{arrays} that can be indexed not only with numbers, |
@@ -236,6 +242,19 @@ to tables, and do not imply any kind of copy. | |||
236 | Moreover, tables must be explicitly created before used | 242 | Moreover, tables must be explicitly created before used |
237 | \see{tableconstructor}. | 243 | \see{tableconstructor}. |
238 | 244 | ||
245 | Tags are mainly used to select tag methods when | ||
246 | some events occur \see{tag-method}. | ||
247 | Each of the types nil, number and string have a different tag. | ||
248 | All values of each of these types have this same pre-defined tag. | ||
249 | Values of type function may have two different tags, | ||
250 | depending whether they are Lua or C functions. | ||
251 | Finally, | ||
252 | values of type userdata and table can have | ||
253 | as many different tags as needed \see{tag-method}. | ||
254 | Tags are created with the function \verb|newtag|, | ||
255 | and the function \verb|tag| returns the tag of a given value. | ||
256 | To change the tag of a given userdata or table, | ||
257 | there is the function \verb|settag| \see{pdf-newtag}. | ||
239 | 258 | ||
240 | 259 | ||
241 | \section{The Language} | 260 | \section{The Language} |
@@ -260,7 +279,7 @@ The following words are reserved, and cannot be used as identifiers: | |||
260 | The following strings denote other \Index{tokens}: | 279 | The following strings denote other \Index{tokens}: |
261 | \begin{verbatim} | 280 | \begin{verbatim} |
262 | ~= <= >= < > == = .. + - * / | 281 | ~= <= >= < > == = .. + - * / |
263 | % ( ) { } [ ] ; , . | 282 | % ( ) { } [ ] ; , . ... |
264 | \end{verbatim} | 283 | \end{verbatim} |
265 | 284 | ||
266 | \Index{Literal strings} can be delimited by matching single or double quotes, | 285 | \Index{Literal strings} can be delimited by matching single or double quotes, |
@@ -271,7 +290,8 @@ Literals in this bracketed form may run for several lines, | |||
271 | may contain nested \verb|[[ ... ]]| pairs, | 290 | may contain nested \verb|[[ ... ]]| pairs, |
272 | and do not interpret escape sequences. | 291 | and do not interpret escape sequences. |
273 | This form is specially convenient for | 292 | This form is specially convenient for |
274 | handling text that has quoted strings in it. | 293 | handling strings that contain program pieces or |
294 | other quoted strings. | ||
275 | 295 | ||
276 | \Index{Comments} start anywhere outside a string with a | 296 | \Index{Comments} start anywhere outside a string with a |
277 | double hyphen (\verb|--|) and run until the end of the line. | 297 | double hyphen (\verb|--|) and run until the end of the line. |
@@ -287,6 +307,35 @@ Examples of valid numerical constants are: | |||
287 | 4 4.0 0.4 4.57e-3 0.3e12 | 307 | 4 4.0 0.4 4.57e-3 0.3e12 |
288 | \end{verbatim} | 308 | \end{verbatim} |
289 | 309 | ||
310 | \subsection{The \Index{Pre-processor}} \label{pre-processor} | ||
311 | |||
312 | All lines that start with a \verb|$| are handled by a pre-processor. | ||
313 | The \verb|$| can be followed by any of the following directives: | ||
314 | \begin{description} | ||
315 | \item[{\tt debug}] --- turn on some debugging facilities \see{pragma}. | ||
316 | \item[{\tt nodebug}] --- turn off some debugging facilities \see{pragma}. | ||
317 | \item[{\tt if \M{cond}}] --- starts a condicional part. | ||
318 | If \M{cond} is false, this part is skiped by the lexical analizer. | ||
319 | \item[{\tt ifnot \M{cond}}] --- starts a condicional part. | ||
320 | If \M{cond} is true, this part is skiped by the lexical analizer. | ||
321 | \item[{\tt end}] --- ends a conditional part. | ||
322 | \item[{\tt else}] --- starts an ``else'' conditional part, | ||
323 | switching the ``skip'' status. | ||
324 | \item[{\tt endinput}] --- ends the lexical parse of the file. | ||
325 | \end{description} | ||
326 | |||
327 | Directives can be freely nested. | ||
328 | Particularlly, a \verb|$endinput| may ocurr inside a \verb|$if|; | ||
329 | in that case, even the matching \verb|$end| is not parsed. | ||
330 | |||
331 | A \M{cond} part may be: | ||
332 | \begin{description} | ||
333 | \item[{\tt nil}] --- always false. | ||
334 | \item[{\tt 1}] --- always true. | ||
335 | \item[\M{name}] --- true if global variable \M{name} is different from \nil. | ||
336 | Notice that this is evaluated before the chunk starts its execution. | ||
337 | Therefore, actions in a chunk do not affect its own conditional directives. | ||
338 | \end{description} | ||
290 | 339 | ||
291 | \subsection{\Index{Coercion}} \label{coercion} | 340 | \subsection{\Index{Coercion}} \label{coercion} |
292 | 341 | ||
@@ -336,7 +385,7 @@ Any statement can be optionally followed by a semicolon: | |||
336 | \end{Produc}% | 385 | \end{Produc}% |
337 | For syntactic reasons, a \IndexVerb{return} statement can only be written | 386 | For syntactic reasons, a \IndexVerb{return} statement can only be written |
338 | as the last statement of a block. | 387 | as the last statement of a block. |
339 | This restriction also avoids some ``statement not reached'' errors. | 388 | This restriction also avoids some ``statement not reached'' conditions. |
340 | 389 | ||
341 | \subsubsection{\Index{Assignment}} \label{assignment} | 390 | \subsubsection{\Index{Assignment}} \label{assignment} |
342 | The language allows \Index{multiple assignment}. | 391 | The language allows \Index{multiple assignment}. |
@@ -366,12 +415,17 @@ Square brackets are used to index a table: | |||
366 | \begin{Produc} | 415 | \begin{Produc} |
367 | \produc{var}{var \ter{[} exp1 \ter{]}} | 416 | \produc{var}{var \ter{[} exp1 \ter{]}} |
368 | \end{Produc}% | 417 | \end{Produc}% |
369 | If \verb|var| results in a table value, | 418 | The \verb|var| should result in a table value, |
370 | the field indexed by the expression value gets the assigned value. | 419 | where the field indexed by the expression value gets the assigned value. |
371 | Otherwise, the fallback {\em settable\/} is called, | 420 | |
372 | with three parameters: the value of \verb|var|, | 421 | The meaning of assignments and evaluations of global variables and |
373 | the value of expression, and the value being assigned to it; | 422 | indexed variables can be changed by tag methods \see{tag-method}. |
374 | \see{fallback}. | 423 | Actually, |
424 | an assignment \verb|x = val|, where \verb|x| is a global variable, | ||
425 | is equivalent to a call \verb|setglobal('x', val)|, | ||
426 | and an assignment \verb|t[i] = val| is equivalent to | ||
427 | \verb|settable(t, i, val)|. | ||
428 | See \See{tag-method} for a description of these ``functions''. | ||
375 | 429 | ||
376 | The syntax \verb|var.NAME| is just syntactic sugar for | 430 | The syntax \verb|var.NAME| is just syntactic sugar for |
377 | \verb|var["NAME"]|: | 431 | \verb|var["NAME"]|: |
@@ -441,6 +495,12 @@ Numbers (numerical constants) and | |||
441 | string literals are explained in Section~\ref{lexical}. | 495 | string literals are explained in Section~\ref{lexical}. |
442 | Variables are explained in Section~\ref{assignment}. | 496 | Variables are explained in Section~\ref{assignment}. |
443 | 497 | ||
498 | An access to a global variable \verb|x| is equivalent to a | ||
499 | call \verb|getglobal('x')|; | ||
500 | an access to an indexed variable \verb|t[i]| is equivalent to | ||
501 | a call \verb|gettable(t, i)|. | ||
502 | See \See{tag-method} for a description of these ``functions''. | ||
503 | |||
444 | The non-terminal \verb|exp1| is used to indicate that the values | 504 | The non-terminal \verb|exp1| is used to indicate that the values |
445 | returned by an expression must be adjusted to one single value: | 505 | returned by an expression must be adjusted to one single value: |
446 | \begin{Produc} | 506 | \begin{Produc} |
@@ -458,9 +518,9 @@ and the unary \verb|-| (negation). | |||
458 | If the operands are numbers, or strings that can be converted to | 518 | If the operands are numbers, or strings that can be converted to |
459 | numbers, according to the rules given in Section~\ref{coercion}, | 519 | numbers, according to the rules given in Section~\ref{coercion}, |
460 | then all operations except exponentiation have the usual meaning. | 520 | then all operations except exponentiation have the usual meaning. |
461 | Otherwise, the fallback ``arith'' is called \see{fallback}. | 521 | Otherwise, a tag method is called \see{tag-method}. |
462 | An exponentiation always calls this fallback. | 522 | An exponentiation always calls a tag method. |
463 | The standard mathematical library redefines this fallback, | 523 | The standard mathematical library redefines this method for numbers, |
464 | giving the expected meaning to \Index{exponentiation} | 524 | giving the expected meaning to \Index{exponentiation} |
465 | \see{mathlib}. | 525 | \see{mathlib}. |
466 | 526 | ||
@@ -469,25 +529,24 @@ Lua provides the following \Index{relational operators}: | |||
469 | \begin{verbatim} | 529 | \begin{verbatim} |
470 | < > <= >= ~= == | 530 | < > <= >= ~= == |
471 | \end{verbatim} | 531 | \end{verbatim} |
472 | All these return \nil\ as false and a value different from \nil\ | 532 | All these return \nil\ as false and a value different from \nil\ as true. |
473 | (actually the number 1) as true. | ||
474 | 533 | ||
475 | Equality first compares the types of its operands. | 534 | Equality first compares the types of its operands. |
476 | If they are different, then the result is \nil. | 535 | If they are different, then the result is \nil. |
477 | Otherwise, their values are compared. | 536 | Otherwise, their values are compared. |
478 | Numbers and strings are compared in the usual way. | 537 | Numbers and strings are compared in the usual way. |
479 | Tables, CFunctions, and functions are compared by reference, | 538 | Tables, userdatas and functions are compared by reference, |
480 | that is, two tables are considered equal only if they are the same table. | 539 | that is, two tables are considered equal only if they are the same table. |
481 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). | 540 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). |
482 | Note that the conversion rules of Section~\ref{coercion} | 541 | Note that the conversion rules of Section~\ref{coercion} |
483 | do not apply to equality comparisons. | 542 | {\em do not\/} apply to equality comparisons. |
484 | Thus, \verb|"0"==0| evaluates to false. | 543 | Thus, \verb|"0"==0| evaluates to false. |
485 | 544 | ||
486 | The other operators work as follows. | 545 | The other operators work as follows. |
487 | If both arguments are numbers, then they are compared as such. | 546 | If both arguments are numbers, then they are compared as such. |
488 | Otherwise, if both arguments can be converted to strings, | 547 | Otherwise, if both arguments are strings, |
489 | their values are compared using lexicographical order. | 548 | their values are compared using lexicographical order. |
490 | Otherwise, the ``order'' fallback is called \see{fallback}. | 549 | Otherwise, the ``order'' tag method is called \see{tag-method}. |
491 | %Note that the conversion rules of Section~\ref{coercion} | 550 | %Note that the conversion rules of Section~\ref{coercion} |
492 | %do apply to order operators. | 551 | %do apply to order operators. |
493 | %Thus, \verb|"2">"12"| evaluates to true. | 552 | %Thus, \verb|"2">"12"| evaluates to true. |
@@ -507,14 +566,14 @@ if it is different from \nil; | |||
507 | otherwise it returns its second argument. | 566 | otherwise it returns its second argument. |
508 | Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, | 567 | Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, |
509 | that is, | 568 | that is, |
510 | the second operand is evaluated only if necessary. | 569 | the second operand is evaluated only when necessary. |
511 | 570 | ||
512 | \subsubsection{Concatenation} | 571 | \subsubsection{Concatenation} |
513 | Lua offers a string \Index{concatenation} operator, | 572 | Lua offers a string \Index{concatenation} operator, |
514 | denoted by ``\IndexVerb{..}''. | 573 | denoted by ``\IndexVerb{..}''. |
515 | If operands are strings or numbers, then they are converted to | 574 | If operands are strings or numbers, then they are converted to |
516 | strings according to the rules in Section~\ref{coercion}. | 575 | strings according to the rules in Section~\ref{coercion}. |
517 | Otherwise, the fallback ``concat'' is called \see{fallback}. | 576 | Otherwise, the tag method ``concat'' is called \see{tag-method}. |
518 | 577 | ||
519 | \subsubsection{Precedence} | 578 | \subsubsection{Precedence} |
520 | \Index{Operator precedence} follows the table below, | 579 | \Index{Operator precedence} follows the table below, |
@@ -565,23 +624,29 @@ is essentialy equivalent to: | |||
565 | a = temp | 624 | a = temp |
566 | \end{verbatim} | 625 | \end{verbatim} |
567 | 626 | ||
568 | The next form initializes named fields in a table: | 627 | The form {\em ffieldlist1\/} initializes other fields in a table: |
569 | \begin{Produc} | 628 | \begin{Produc} |
570 | \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} | 629 | \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} |
571 | \produc{ffield}{name \ter{=} exp} | 630 | \produc{ffield}{\ter{[} exp \ter{]} \ter {=} exp \Or name \ter{=} exp} |
572 | \end{Produc}% | 631 | \end{Produc}% |
573 | For example: | 632 | For example: |
574 | \begin{verbatim} | 633 | \begin{verbatim} |
575 | a = {x = 1, y = 3} | 634 | a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c} |
576 | \end{verbatim} | 635 | \end{verbatim} |
577 | is essentialy equivalent to: | 636 | is essentialy equivalent to: |
578 | \begin{verbatim} | 637 | \begin{verbatim} |
579 | temp = {} | 638 | temp = {} |
639 | temp[f(k)] = g(y) | ||
580 | temp.x = 1 -- or temp["x"] = 1 | 640 | temp.x = 1 -- or temp["x"] = 1 |
581 | temp.y = 3 -- or temp["y"] = 3 | 641 | temp.y = 3 -- or temp["y"] = 3 |
642 | temp[0] = b+c | ||
582 | a = temp | 643 | a = temp |
583 | \end{verbatim} | 644 | \end{verbatim} |
584 | 645 | Notice that an expression like \verb|{x = 1, y = 4}| is | |
646 | in fact a syntactic sugar for | ||
647 | \begin{verbatim} | ||
648 | {["x"] = 1, ["y"] = 4} | ||
649 | \end{verbatim} | ||
585 | 650 | ||
586 | \subsubsection{Function Calls} \label{functioncall} | 651 | \subsubsection{Function Calls} \label{functioncall} |
587 | A \Index{function call} has the following syntax: | 652 | A \Index{function call} has the following syntax: |
@@ -589,9 +654,9 @@ A \Index{function call} has the following syntax: | |||
589 | \produc{functioncall}{var realParams} | 654 | \produc{functioncall}{var realParams} |
590 | \end{Produc}% | 655 | \end{Produc}% |
591 | Here, \verb|var| can be any variable (global, local, indexed, etc). | 656 | Here, \verb|var| can be any variable (global, local, indexed, etc). |
592 | If its value has type {\em function\/} or {\em CFunction}, | 657 | If its value has type {\em function\/}, |
593 | then this function is called. | 658 | then this function is called. |
594 | Otherwise, the ``function'' fallback is called, | 659 | Otherwise, the ``function'' tag method is called, |
595 | having as first parameter the value of \verb|var|, | 660 | having as first parameter the value of \verb|var|, |
596 | and then the original call parameters. | 661 | and then the original call parameters. |
597 | 662 | ||
@@ -612,10 +677,7 @@ except that \verb|var| is evaluated only once. | |||
612 | \produc{realParams}{tableconstructor} | 677 | \produc{realParams}{tableconstructor} |
613 | \produc{explist1}{exp1 \rep{\ter{,} exp1}} | 678 | \produc{explist1}{exp1 \rep{\ter{,} exp1}} |
614 | \end{Produc}% | 679 | \end{Produc}% |
615 | All argument expressions are evaluated before the call; | 680 | All argument expressions are evaluated before the call. |
616 | then the list of \Index{arguments} is adjusted to | ||
617 | the length of the list of parameters \see{adjust}; | ||
618 | finally, this list is assigned to the formal parameters. | ||
619 | A call of the form \verb|f{...}| is syntactic sugar for | 681 | A call of the form \verb|f{...}| is syntactic sugar for |
620 | \verb|f({...})|, that is, | 682 | \verb|f({...})|, that is, |
621 | the parameter list is a single new table. | 683 | the parameter list is a single new table. |
@@ -629,8 +691,7 @@ thus discarding all returned values. | |||
629 | If the function is called in a place that needs a single value | 691 | If the function is called in a place that needs a single value |
630 | (syntactically denoted by the non-terminal \verb|exp1|), | 692 | (syntactically denoted by the non-terminal \verb|exp1|), |
631 | then its return list is adjusted to 1, | 693 | then its return list is adjusted to 1, |
632 | thus discarding all returned values, | 694 | thus discarding all returned values but the first one. |
633 | except the first one. | ||
634 | If the function is called in a place that can hold many values | 695 | If the function is called in a place that can hold many values |
635 | (syntactically denoted by the non-terminal \verb|exp|), | 696 | (syntactically denoted by the non-terminal \verb|exp|), |
636 | then no adjustment is made. | 697 | then no adjustment is made. |
@@ -656,8 +717,39 @@ a function definition is an assignment to a global variable. | |||
656 | Parameters act as local variables, | 717 | Parameters act as local variables, |
657 | initialized with the argument values. | 718 | initialized with the argument values. |
658 | \begin{Produc} | 719 | \begin{Produc} |
659 | \produc{parlist1}{name \rep{\ter{,} name}} | 720 | \produc{parlist1}{\ter{\ldots}} |
721 | \produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} | ||
660 | \end{Produc} | 722 | \end{Produc} |
723 | \label{vararg} | ||
724 | When a function is called, | ||
725 | the list of \Index{arguments} is adjusted to | ||
726 | the length of the list of parameters \see{adjust}, | ||
727 | unless the function is a \Def{vararg} function, | ||
728 | indicated by the dots (\ldots) at the end of its parameter list. | ||
729 | A vararg function does not adjust its argument list; | ||
730 | instead, it collects any extra arguments in an implicit parameter, | ||
731 | called \Def{arg}. | ||
732 | This parameter is always initialized as a table, | ||
733 | with a field \verb|n| with the number of extra arguments, | ||
734 | and the extra arguments at positions 1, 2, \ldots. | ||
735 | |||
736 | As an example, suppose definitions like: | ||
737 | \begin{verbatim} | ||
738 | function f(a, b) end | ||
739 | function g(a, b, ...) end | ||
740 | \end{verbatim} | ||
741 | Then, we have the following mapping from arguments to parameters: | ||
742 | \begin{verbatim} | ||
743 | CALL PARAMETERS | ||
744 | |||
745 | f(3) a=3, b=nil | ||
746 | f(3, 4) a=3, b=4 | ||
747 | f(3, 4, 5) a=3, b=4 | ||
748 | |||
749 | g(3) a=3, b=nil, arg={n=0} | ||
750 | g(3, 4) a=3, b=4, arg={n=0} | ||
751 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} | ||
752 | \end{verbatim} | ||
661 | 753 | ||
662 | Results are returned using the \verb|return| statement \see{return}. | 754 | Results are returned using the \verb|return| statement \see{return}. |
663 | If control reaches the end of a function without a return instruction, | 755 | If control reaches the end of a function without a return instruction, |
@@ -683,95 +775,298 @@ end | |||
683 | \end{verbatim} | 775 | \end{verbatim} |
684 | that is, the function gets an extra formal parameter called \verb|self|. | 776 | that is, the function gets an extra formal parameter called \verb|self|. |
685 | Notice that | 777 | Notice that |
686 | the variable \verb|v| must have been previously initialized with a table value. | 778 | the variable \verb|v| must have been |
779 | previously initialized with a table value. | ||
687 | 780 | ||
688 | 781 | ||
689 | \subsection{Fallbacks} \label{fallback} | 782 | \subsection{Tag Methods} \label{tag-method} |
690 | 783 | ||
691 | Lua provides a powerful mechanism to extend its semantics, | 784 | Lua provides a powerful mechanism to extend its semantics, |
692 | called \Def{fallbacks}. | 785 | called \Def{Tag Methods}. |
693 | A fallback is a programmer defined function | 786 | A tag method (TM) is a programmer defined function |
694 | that is called whenever Lua does not know how to proceed. | 787 | that can be called in many key points of the evaluation of a program, |
788 | allowing a programmer to change the standard Lua behavior at these points. | ||
789 | Each of these points is called an \Def{event}. | ||
790 | |||
791 | The tag method called for any specific event is selected | ||
792 | accordingly with the tag~\see{TypesSec} of the values involved | ||
793 | in the event. | ||
794 | The function \IndexVerb{settagmethod} changes the tag method | ||
795 | associated with a given pair $<tag, event>$. | ||
796 | Its first parameter is the tag, the second the event name | ||
797 | (a string, see below), | ||
798 | and the third parameter is the new method (a function), | ||
799 | or \nil\ to restore the default behavior. | ||
800 | The function returns the previous tag method. | ||
801 | Another function, \IndexVerb{gettagmethod}, | ||
802 | receives a tag and an event name and returns the | ||
803 | current method associated with the pair. | ||
804 | |||
805 | Tag methods are called in the following events, | ||
806 | identified by the given names. | ||
807 | The semantics of tag methods is better explained by a Lua function | ||
808 | describing the behavior of the interpreter at each event. | ||
809 | The function not only shows when a tag method is called, | ||
810 | but also its arguments, its results and the default behavior. | ||
811 | Please notice that the code shown here is only illustrative; | ||
812 | the real behavior is hard coded in the interpreter, | ||
813 | and it is much more eficient than this simulation. | ||
814 | All functions used in these descriptions | ||
815 | (\verb|rawgetglobal|, \verb|tonumber|, \verb|call|, etc) | ||
816 | are described in \See{predefined}. | ||
695 | 817 | ||
696 | Lua supports the following fallbacks, | ||
697 | identified by the given strings: | ||
698 | \begin{description} | 818 | \begin{description} |
699 | \item[``arith'':]\index{arithmetic fallback} | 819 | |
700 | called when an arithmetic operation is applied to non numerical operands, | 820 | \item[``add'':]\index{add event} |
701 | or when the binary \verb|^| operation (exponentiation) is called. | 821 | called when a \verb|+| operation is applied to non numerical operands. |
702 | It receives three arguments: | 822 | |
703 | the two operands (the second one is \nil\ when the operation is unary minus) | 823 | The function \verb|getbinmethod| defines how Lua chooses a tag method |
704 | and one of the following strings describing the offended operator: | 824 | for a binary operation. |
705 | \begin{verbatim} | 825 | First Lua trys the first operand. |
706 | add sub mul div pow unm | 826 | If its tag does not define a tag method for the operation, |
707 | \end{verbatim} | 827 | Lua trys the second operand. |
708 | Its return value is the final result of the arithmetic operation. | 828 | If it also fails, it gets a tag method from tag 0: |
709 | The default handler issues an error. | 829 | \begin{verbatim} |
710 | \item[``order'':]\index{order fallback} | 830 | function getbinmethod (op1, op2, event) |
711 | called when an order comparison is applied to non numerical or | 831 | return gettagmethod(tag(op1), event) or |
712 | non string operands. | 832 | gettagmethod(tag(op2), event) or |
713 | It receives three arguments: | 833 | gettagmethod(0, event) |
714 | the two operands and | 834 | end |
715 | one of the following strings describing the offended operator: | 835 | \end{verbatim} |
716 | \begin{verbatim} | 836 | \begin{verbatim} |
717 | lt gt le ge | 837 | function add_event (op1, op2) |
718 | \end{verbatim} | 838 | local o1, o2 = tonumber(op1), tonumber(op2) |
719 | Its return value is the final result of the comparison operation. | 839 | if o1 and o2 then -- both operands are numeric |
720 | The default handler issues an error. | 840 | return o1+o2 -- '+' here is the primitive 'add' |
721 | \item[``concat'':]\index{concatenation fallback} | 841 | else -- at least one of the operands is not numeric. |
842 | local tm = getbinmethod(op1, op2, "add") | ||
843 | if tm then | ||
844 | -- call the method with both operands and an extra | ||
845 | -- argument with the event name | ||
846 | return tm(op1, op2, "add") | ||
847 | else -- no tag method available: Default behavior | ||
848 | error("unexpected type at arithmetic operation") | ||
849 | end | ||
850 | end | ||
851 | end | ||
852 | \end{verbatim} | ||
853 | |||
854 | \item[``sub'':]\index{sub event} | ||
855 | called when a \verb|-| operation is applied to non numerical operands. | ||
856 | Behavior is similar to \verb|"add"| event. | ||
857 | |||
858 | \item[``mul'':]\index{mul event} | ||
859 | called when a \verb|*| operation is applied to non numerical operands. | ||
860 | Behavior is similar to \verb|"add"| event. | ||
861 | |||
862 | \item[``div'':]\index{div event} | ||
863 | called when a \verb|/| operation is applied to non numerical operands. | ||
864 | Behavior is similar to \verb|"add"| event. | ||
865 | |||
866 | \item[``pow'':]\index{pow event} | ||
867 | called whenenver a \verb|^| operation is applied. | ||
868 | \begin{verbatim} | ||
869 | function pow_event (op1, op2) | ||
870 | local tm = getbinmethod(op1, op2, "pow") | ||
871 | if tm then | ||
872 | -- call the method with both operands and an extra | ||
873 | -- argument with the event name | ||
874 | return tm(op1, op2, "pow") | ||
875 | else -- no tag method available: Default behavior | ||
876 | error("unexpected type at arithmetic operation") | ||
877 | end | ||
878 | end | ||
879 | \end{verbatim} | ||
880 | |||
881 | \item[``unm'':]\index{unm event} | ||
882 | called when an unary \verb|-| operation is applied to a non numerical operand. | ||
883 | \begin{verbatim} | ||
884 | function unm_event (op) | ||
885 | local o = tonumber(op) | ||
886 | if o then -- operand is numeric | ||
887 | return -o -- '-' here is the primitive 'unm' | ||
888 | else -- the operand is not numeric. | ||
889 | -- Try to get a tag method from the operand; | ||
890 | -- if it does not have one, try a "global" one (tag 0) | ||
891 | local tm = gettagmethod(tag(op), "unm") or | ||
892 | gettagmethod(0, "unm") | ||
893 | if tm then | ||
894 | -- call the method with the operand, nil, and an extra | ||
895 | -- argument with the event name | ||
896 | return tm(op, nil, "unm") | ||
897 | else -- no tag method available: Default behavior | ||
898 | error("unexpected type at arithmetic operation") | ||
899 | end | ||
900 | end | ||
901 | end | ||
902 | \end{verbatim} | ||
903 | |||
904 | \item[``lt'':]\index{lt event} | ||
905 | called when a \verb|<| operation is applied to non numerical | ||
906 | or non string operands. | ||
907 | \begin{verbatim} | ||
908 | function lt_event (op1, op2) | ||
909 | if type(op1) == "number" and type(op2) == "number" then | ||
910 | return op1 < op2 -- numeric comparison | ||
911 | elseif type(op1) == "string" and type(op2) == "string" then | ||
912 | return op1 < op2 -- lexicographic comparison | ||
913 | else | ||
914 | local tm = getbinmethod(op1, op2, "lt") | ||
915 | if tm then | ||
916 | return tm(op1, op2, "lt") | ||
917 | else | ||
918 | error("unexpected type at comparison"); | ||
919 | end | ||
920 | end | ||
921 | end | ||
922 | \end{verbatim} | ||
923 | |||
924 | \item[``gt'':]\index{gt event} | ||
925 | called when a \verb|>| operation is applied to non numerical | ||
926 | or non string operands. | ||
927 | Behavior is similar to \verb|"lt"| event. | ||
928 | |||
929 | \item[``le'':]\index{le event} | ||
930 | called when a \verb|<=| operation is applied to non numerical | ||
931 | or non string operands. | ||
932 | Behavior is similar to \verb|"lt"| event. | ||
933 | |||
934 | \item[``ge'':]\index{ge event} | ||
935 | called when a \verb|>=| operation is applied to non numerical | ||
936 | or non string operands. | ||
937 | Behavior is similar to \verb|"lt"| event. | ||
938 | |||
939 | \item[``concat'':]\index{concatenation event} | ||
722 | called when a concatenation is applied to non string operands. | 940 | called when a concatenation is applied to non string operands. |
723 | It receives the two operands as arguments. | 941 | \begin{verbatim} |
724 | Its return value is the final result of the concatenation operation. | 942 | function concat_event (op1, op2) |
725 | The default handler issues an error. | 943 | if (type(op1) == "string" or type(op1) == "number") and |
726 | \item[``index'':]\index{index fallback} | 944 | (type(op2) == "string" or type(op2) == "number") then |
945 | return op1..op2 -- primitive string concatenation | ||
946 | else | ||
947 | local tm = getbinmethod(op1, op2, "concat") | ||
948 | if tm then | ||
949 | return tm(op1, op2, "concat") | ||
950 | else | ||
951 | error("unexpected type for concatenation") | ||
952 | end | ||
953 | end | ||
954 | end | ||
955 | \end{verbatim} | ||
956 | |||
957 | \item[``index'':]\index{index event} | ||
727 | called when Lua tries to retrieve the value of an index | 958 | called when Lua tries to retrieve the value of an index |
728 | not present in a table. | 959 | not present in a table. |
729 | It receives as arguments the table and the index. | 960 | See event \verb|"gettable"| for its semantics. |
730 | Its return value is the final result of the indexing operation. | 961 | |
731 | The default handler returns \nil. | 962 | \item[``getglobal'':]\index{getglobal event} |
732 | \item[``getglobal'':]\index{index getglobal} | 963 | called whenever Lua accesses a global variable. |
733 | called when Lua tries to retrieve the value of a global variable | 964 | \begin{verbatim} |
734 | which has a \nil\ value (or which has not been initialized). | 965 | function getglobal (varname) |
735 | It receives as argument the name of the variable. | 966 | local value = rawgetglobal(varname) |
736 | Its return value is the final result of the expression. | 967 | local tm = gettagmethod(tag(value), "getglobal") |
737 | The default handler returns \nil. | 968 | if not tm then |
738 | \item[``gettable'':]\index{gettable fallback} | 969 | return value |
739 | called when Lua tries to index a non table value. | 970 | else |
740 | It receives as arguments the non table value and the index. | 971 | return tm(varname, value) |
741 | Its return value is the final result of the indexing operation. | 972 | end |
742 | The default handler issues an error. | 973 | end |
743 | \item[``settable'':]\index{settable fallback} | 974 | \end{verbatim} |
744 | called when Lua tries to assign to an index in a non table value. | 975 | Notice: the function \verb|getglobal| is pre-defined in Lua \see{predefined}. |
745 | It receives as arguments the non table value, | 976 | |
746 | the index, and the assigned value. | 977 | \item[``setglobal'':]\index{setglobal event} |
747 | The default handler issues an error. | 978 | called whenever Lua assigns to a global variable. |
748 | \item[``function'':]\index{function fallback} | 979 | \begin{verbatim} |
980 | function setglobal (varname, newvalue) | ||
981 | local oldvalue = rawgetglobal(varname) | ||
982 | local tm = gettagmethod(tag(oldvalue), "setglobal") | ||
983 | if not tm then | ||
984 | return rawsetglobal(varname, newvalue) | ||
985 | else | ||
986 | return tm(varname, oldvalue, newvalue) | ||
987 | end | ||
988 | end | ||
989 | \end{verbatim} | ||
990 | Notice: the function \verb|setglobal| is pre-defined in Lua \see{predefined}. | ||
991 | |||
992 | \item[``gettable'':]\index{gettable event} | ||
993 | called whenever Lua accesses an indexed variable. | ||
994 | \begin{verbatim} | ||
995 | function gettable_event (table, index) | ||
996 | local tm = gettagmethod(tag(table), "gettable") | ||
997 | if tm then | ||
998 | return tm(table, index) | ||
999 | elseif type(table) ~= "table" then | ||
1000 | error("indexed expression not a table"); | ||
1001 | else | ||
1002 | local v = rawgettable(table, index) | ||
1003 | tm = gettagmethod(tag(table), "index") | ||
1004 | if (v == nil) and tm then | ||
1005 | return tm(table, index) | ||
1006 | else | ||
1007 | return v | ||
1008 | end | ||
1009 | end | ||
1010 | end | ||
1011 | \end{verbatim} | ||
1012 | |||
1013 | \item[``settable'':]\index{settable event} | ||
1014 | called whenever Lua assigns to an indexed variable. | ||
1015 | in a table. | ||
1016 | \begin{verbatim} | ||
1017 | function settable_event (table, index, value) | ||
1018 | local tm = gettagmethod(tag(table), "settable") | ||
1019 | if tm then | ||
1020 | return tm(table, index, value) | ||
1021 | elseif type(table) ~= "table" then | ||
1022 | error("indexed expression not a table") | ||
1023 | else | ||
1024 | rawsettable(table, index, value) | ||
1025 | end | ||
1026 | end | ||
1027 | \end{verbatim} | ||
1028 | |||
1029 | \item[``function'':]\index{function event} | ||
749 | called when Lua tries to call a non function value. | 1030 | called when Lua tries to call a non function value. |
750 | It receives as arguments the non function value and the | 1031 | \begin{verbatim} |
751 | arguments given in the original call. | 1032 | function function_event (func, ...) |
752 | Its return values are the final results of the call operation. | 1033 | if type(func) == "function" then |
753 | The default handler issues an error. | 1034 | return call(func, arg) |
754 | \item[``gc'':] | 1035 | else |
755 | called during garbage collection. | 1036 | local tm = gettagmethod(tag(func), "function") |
756 | It receives as argument the table being collected. | 1037 | if tm then |
757 | After each run of the collector this function is called with argument \nil, | 1038 | local i = arg.n |
758 | to signal the completion of the garbage collection. | 1039 | while i > 0 do |
759 | Because this function operates during garbage collection, | 1040 | arg[i+1] = arg[i] |
760 | it must be used with great care, | 1041 | i = i-1 |
761 | and programmers should avoid the creation of new objects | 1042 | end |
762 | (tables or strings) in this function. | 1043 | arg.n = arg.n+1 |
763 | The default handler does nothing. | 1044 | arg[1] = func |
764 | \item[``error'':]\index{error fallback} | 1045 | return call(tm, arg) |
765 | called when an error occurs. | 1046 | else |
766 | It receives as argument a string describing the error. | 1047 | error("call expression not a function") |
767 | The default handler prints the message on the standard error output | 1048 | end |
768 | (\verb|stderr|). | 1049 | end |
1050 | end | ||
1051 | \end{verbatim} | ||
1052 | |||
1053 | \item[``gc'':]\index{gc event} | ||
1054 | called when Lua is garbage collecting an object. | ||
1055 | For each object to be collected, | ||
1056 | Lua does the equivalent of the following function: | ||
1057 | \begin{verbatim} | ||
1058 | function gc_event (obj) | ||
1059 | local tm = gettagmethod(tag(obj), "gc") | ||
1060 | if tm then | ||
1061 | tm(obj) | ||
1062 | end | ||
1063 | end | ||
1064 | \end{verbatim} | ||
1065 | Moreover, at the end of a garbage collection cicle, | ||
1066 | Lua does the equivalent to the call \verb|gc_event(nil)|. | ||
1067 | |||
769 | \end{description} | 1068 | \end{description} |
770 | 1069 | ||
771 | The function \IndexVerb{setfallback} is used to change a fallback handler. | ||
772 | Its first argument is the name of a fallback condition, | ||
773 | and the second argument is the new function to be called. | ||
774 | It returns the old handler function for the given fallback. | ||
775 | 1070 | ||
776 | 1071 | ||
777 | \subsection{Error Handling} \label{error} | 1072 | \subsection{Error Handling} \label{error} |
@@ -779,27 +1074,26 @@ It returns the old handler function for the given fallback. | |||
779 | Because Lua is an extension language, | 1074 | Because Lua is an extension language, |
780 | all Lua actions start from C code calling a function from the Lua library. | 1075 | all Lua actions start from C code calling a function from the Lua library. |
781 | Whenever an error occurs during Lua compilation or execution, | 1076 | Whenever an error occurs during Lua compilation or execution, |
782 | the ``error'' fallback function is called, | 1077 | the \Def{error method} is called, |
783 | and then the corresponding function from the library | 1078 | and then the corresponding function from the library |
784 | (\verb|lua_dofile|, \verb|lua_dostring|, | 1079 | (\verb|lua_dofile|, \verb|lua_dostring|, or \verb|lua_callfunction|) |
785 | \verb|lua_call|, or \verb|lua_callfunction|) | ||
786 | is terminated returning an error condition. | 1080 | is terminated returning an error condition. |
787 | 1081 | ||
788 | The only argument to the ``error'' fallback function is a string | 1082 | The only argument to the error method is a string |
789 | describing the error. | 1083 | describing the error. |
790 | The standard I/O library redefines this fallback, | 1084 | The standard I/O library redefines this method, |
791 | using the debug facilities \see{debugI}, | 1085 | using the debug facilities \see{debugI}, |
792 | in order to print some extra information, | 1086 | in order to print some extra information, |
793 | like the call stack. | 1087 | like the call stack. |
794 | To provide more information about errors, | 1088 | To provide more information about errors, |
795 | Lua programs can include the compilation pragma \verb|$debug|. | 1089 | Lua programs can include the compilation pragma \verb|$debug|. |
796 | \index{debug pragma}\label{pragma} | 1090 | \index{debug pragma}\label{pragma} |
797 | This pragma must be written in a line by itself. | ||
798 | When an error occurs in a program compiled with this option, | 1091 | When an error occurs in a program compiled with this option, |
799 | the error routine is able to print the number of the lines where the calls | 1092 | the error routine is able to print the number of the lines where the calls |
800 | (and the error) were made. | 1093 | (and the error) were made. |
801 | If needed, it is possible to change the ``error'' fallback handler | 1094 | If needed, it is possible to change the error method with the |
802 | \see{fallback}. | 1095 | function \verb|seterrormethod|, |
1096 | which gets the new error handler as its only parameter. | ||
803 | 1097 | ||
804 | Lua code can explicitly generate an error by calling the built-in | 1098 | Lua code can explicitly generate an error by calling the built-in |
805 | function \verb|error| \see{pdf-error}. | 1099 | function \verb|error| \see{pdf-error}. |
@@ -832,12 +1126,7 @@ for instance, | |||
832 | the comparisson of two \verb|lua_Object's| is undefined. | 1126 | the comparisson of two \verb|lua_Object's| is undefined. |
833 | 1127 | ||
834 | To check the type of a \verb|lua_Object|, | 1128 | To check the type of a \verb|lua_Object|, |
835 | the following function is available: | 1129 | the following functions are available: |
836 | \Deffunc{lua_type} | ||
837 | \begin{verbatim} | ||
838 | int lua_type (lua_Object object); | ||
839 | \end{verbatim} | ||
840 | plus the following functions: | ||
841 | \Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} | 1130 | \Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} |
842 | \Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} | 1131 | \Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} |
843 | \Deffunc{lua_isfunction} | 1132 | \Deffunc{lua_isfunction} |
@@ -856,15 +1145,20 @@ The function \verb|lua_isnumber| accepts numbers and numerical strings, | |||
856 | whereas | 1145 | whereas |
857 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, | 1146 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, |
858 | and \verb|lua_isfunction| accepts Lua and C functions. | 1147 | and \verb|lua_isfunction| accepts Lua and C functions. |
859 | The function \verb|lua_type| can be used to distinguish between | 1148 | |
860 | different kinds of user data. | 1149 | To check the tag of a \verb|lua_Object|, |
1150 | the following function is available: | ||
1151 | \Deffunc{lua_tag} | ||
1152 | \begin{verbatim} | ||
1153 | int lua_tag (lua_Object object); | ||
1154 | \end{verbatim} | ||
861 | 1155 | ||
862 | To translate a value from type \verb|lua_Object| to a specific C type, | 1156 | To translate a value from type \verb|lua_Object| to a specific C type, |
863 | the programmer can use: | 1157 | the programmer can use: |
864 | \Deffunc{lua_getnumber}\Deffunc{lua_getstring} | 1158 | \Deffunc{lua_getnumber}\Deffunc{lua_getstring} |
865 | \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} | 1159 | \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} |
866 | \begin{verbatim} | 1160 | \begin{verbatim} |
867 | double lua_getnumber (lua_Object object); | 1161 | float lua_getnumber (lua_Object object); |
868 | char *lua_getstring (lua_Object object); | 1162 | char *lua_getstring (lua_Object object); |
869 | lua_CFunction lua_getcfunction (lua_Object object); | 1163 | lua_CFunction lua_getcfunction (lua_Object object); |
870 | void *lua_getuserdata (lua_Object object); | 1164 | void *lua_getuserdata (lua_Object object); |
@@ -876,10 +1170,10 @@ This \verb|lua_Object| must be a number or a string convertible to number | |||
876 | \verb|lua_getstring| converts a \verb|lua_Object| to a string (\verb|char *|). | 1170 | \verb|lua_getstring| converts a \verb|lua_Object| to a string (\verb|char *|). |
877 | This \verb|lua_Object| must be a string or a number; | 1171 | This \verb|lua_Object| must be a string or a number; |
878 | otherwise, the function returns 0 (the \verb|NULL| pointer). | 1172 | otherwise, the function returns 0 (the \verb|NULL| pointer). |
879 | This function does not create a new string, but returns a pointer to | 1173 | This function does not create a new string, |
880 | a string inside the Lua environment. | 1174 | but returns a pointer to a string inside the Lua environment. |
881 | Because Lua has garbage collection, there is no guarantee that such | 1175 | Because Lua has garbage collection, |
882 | pointer will be valid after the block ends. | 1176 | there is no guarantee that such pointer will be valid after the block ends. |
883 | 1177 | ||
884 | \verb|lua_getcfunction| converts a \verb|lua_Object| to a C function. | 1178 | \verb|lua_getcfunction| converts a \verb|lua_Object| to a C function. |
885 | This \verb|lua_Object| must have type {\em CFunction\/}; | 1179 | This \verb|lua_Object| must have type {\em CFunction\/}; |
@@ -899,6 +1193,16 @@ It is good programming practice to convert Lua objects to C values | |||
899 | as soon as they are available, | 1193 | as soon as they are available, |
900 | and never to store \verb|lua_Object|s in C global variables. | 1194 | and never to store \verb|lua_Object|s in C global variables. |
901 | 1195 | ||
1196 | A garbage collection cicle can be forced by: | ||
1197 | \Deffunc{lua_collectgarbage} | ||
1198 | \begin{verbatim} | ||
1199 | long lua_collectgarbage (long limit); | ||
1200 | \end{verbatim} | ||
1201 | This function returns the number of objects collected. | ||
1202 | The argument \verb|limit| makes the next cicle occur when that number | ||
1203 | of new objects have been created. | ||
1204 | If \verb|limit|=0, Lua uses an adaptative algorithm to set this limit. | ||
1205 | |||
902 | 1206 | ||
903 | All comunication between Lua and C is done through two | 1207 | All comunication between Lua and C is done through two |
904 | abstract data types, called \Def{lua2C} and \Def{C2lua}. | 1208 | abstract data types, called \Def{lua2C} and \Def{C2lua}. |
@@ -906,8 +1210,6 @@ The first one, as the name implies, is used to pass values | |||
906 | from Lua to C: parameters when Lua calls C and results when C calls Lua. | 1210 | from Lua to C: parameters when Lua calls C and results when C calls Lua. |
907 | The structure C2lua is used in the reverse direction: | 1211 | The structure C2lua is used in the reverse direction: |
908 | parameters when C calls Lua and results when Lua calls C. | 1212 | parameters when C calls Lua and results when Lua calls C. |
909 | Notice that the structure lua2C cannot be directly modified by C code, | ||
910 | while the structure C2lua cannot be ``read'' by C code. | ||
911 | 1213 | ||
912 | The structure lua2C is an abstract array, | 1214 | The structure lua2C is an abstract array, |
913 | which can be indexed with the function: | 1215 | which can be indexed with the function: |
@@ -917,11 +1219,11 @@ lua_Object lua_lua2C (int number); | |||
917 | \end{verbatim} | 1219 | \end{verbatim} |
918 | where \verb|number| starts with 1. | 1220 | where \verb|number| starts with 1. |
919 | When called with a number larger than the array size, | 1221 | When called with a number larger than the array size, |
920 | this function returns | 1222 | this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}. |
921 | \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}. | ||
922 | In this way, it is possible to write C functions that receive | 1223 | In this way, it is possible to write C functions that receive |
923 | a variable number of parameters, | 1224 | a variable number of parameters, |
924 | and to call Lua functions that return a variable number of results. | 1225 | and to call Lua functions that return a variable number of results. |
1226 | Notice that the structure lua2C cannot be directly modified by C code. | ||
925 | 1227 | ||
926 | The second structure, C2lua, is a stack. | 1228 | The second structure, C2lua, is a stack. |
927 | Pushing elements into this stack | 1229 | Pushing elements into this stack |
@@ -938,32 +1240,47 @@ void lua_pushusertag (void *u, int tag); | |||
938 | void lua_pushnil (void); | 1240 | void lua_pushnil (void); |
939 | void lua_pushobject (lua_Object object); | 1241 | void lua_pushobject (lua_Object object); |
940 | \end{verbatim} | 1242 | \end{verbatim} |
941 | plus the macro: | ||
942 | \begin{verbatim} | ||
943 | void lua_pushuserdata (void *u); | ||
944 | \end{verbatim} | ||
945 | All of them receive a C value, | 1243 | All of them receive a C value, |
946 | convert it to a corresponding \verb|lua_Object|, | 1244 | convert it to a corresponding \verb|lua_Object|, |
947 | and leave the result on the top of C2lua. | 1245 | and leave the result on the top of C2lua. |
1246 | The function | ||
1247 | \Deffunc{lua_pop} | ||
1248 | \begin{verbatim} | ||
1249 | lua_Object lua_pop (void); | ||
1250 | \end{verbatim} | ||
1251 | returns a reference to the object at the top of the C2lua stack, | ||
1252 | and pops it. | ||
1253 | |||
1254 | As a general rule, all API functions pop from the stack | ||
1255 | all elements that they use. | ||
1256 | |||
1257 | Because userdata are objects, | ||
1258 | the function \verb|lua_pushusertag| may create a new userdata. | ||
1259 | If Lua has a userdata with the given value (\verb|void *|) and tag, | ||
1260 | that userdata is pushed. | ||
1261 | Otherwise, a new userdata is created, with the given value and tag. | ||
1262 | If this function is called with | ||
1263 | \verb|tag|=\verb|LUA_ANYTAG|\Deffunc{LUA_ANYTAG}, | ||
1264 | then Lua will try to find any userdata with the given value, | ||
1265 | no matter its tag. | ||
1266 | If there is no userdata with that value, a new one is created, | ||
1267 | with tag=0. | ||
948 | 1268 | ||
949 | User data can have different tags, | 1269 | User data can have different tags, |
950 | whose semantics are only known to the host program. | 1270 | whose semantics are only known to the host program. |
951 | Any positive integer can be used to tag a user datum. | 1271 | Tags are created with the function: |
952 | When a user datum is retrieved, | 1272 | \Deffunc{lua_newtag} |
953 | the function \verb|lua_type| can be used to get its tag. | 1273 | \begin{verbatim} |
954 | 1274 | int lua_newtag (void); | |
955 | {\em Please note:} most functions in the Lua API | 1275 | \end{verbatim} |
956 | use the structures lua2C and C2lua, | 1276 | The function \verb|lua_settag| changes the tag of |
957 | and therefore change their contents. | 1277 | the object on the top of C2lua (and pops it); |
958 | Great care must be taken, | 1278 | the object must be a userdata or a table. |
959 | specially when pushing a sequence of objects into C2lua, | 1279 | \Deffunc{lua_settag} |
960 | to avoid using those functions. | 1280 | \begin{verbatim} |
961 | The family of functions \verb|lua_get*|, \verb|lua_is*|, | 1281 | void lua_settag (int tag); |
962 | plus the function \verb|lua_lua2C|, | 1282 | \end{verbatim} |
963 | are safe to be called without modifying these structures; | 1283 | \verb|tag| must be a value created with \verb|lua_newtag|. |
964 | the family \verb|lua_push*| does not modify lua2C. | ||
965 | All other functions may change lua2C and C2lua, | ||
966 | unless noticed otherwise. | ||
967 | 1284 | ||
968 | When C code calls Lua repeatedly, as in a loop, | 1285 | When C code calls Lua repeatedly, as in a loop, |
969 | objects returned by these calls accumulate, | 1286 | objects returned by these calls accumulate, |
@@ -995,8 +1312,10 @@ executes the \verb|stdin| stream. | |||
995 | Function \verb|lua_dofile| is also able to execute pre-compiled chunks. | 1312 | Function \verb|lua_dofile| is also able to execute pre-compiled chunks. |
996 | It automatically detects whether the file is text or binary, | 1313 | It automatically detects whether the file is text or binary, |
997 | and loads it accordingly (see program \IndexVerb{luac}). | 1314 | and loads it accordingly (see program \IndexVerb{luac}). |
998 | These functions also return, in structure lua2C, | 1315 | |
1316 | These functions return, in structure lua2C, | ||
999 | any values eventually returned by the chunks. | 1317 | any values eventually returned by the chunks. |
1318 | They also empty the stack C2lua. | ||
1000 | 1319 | ||
1001 | 1320 | ||
1002 | \subsection{Manipulating Lua Objects} | 1321 | \subsection{Manipulating Lua Objects} |
@@ -1006,37 +1325,63 @@ one uses the function: | |||
1006 | \begin{verbatim} | 1325 | \begin{verbatim} |
1007 | lua_Object lua_getglobal (char *varname); | 1326 | lua_Object lua_getglobal (char *varname); |
1008 | \end{verbatim} | 1327 | \end{verbatim} |
1009 | As in Lua, if the value of the global is \nil, | 1328 | As in Lua, this function may call a tag method. |
1010 | then the ``getglobal'' fallback is called. | 1329 | To read the real value of any global variable, |
1330 | without invoking any tag method, | ||
1331 | this function has a {\em raw\/} version: | ||
1332 | \Deffunc{lua_rawgetglobal} | ||
1333 | \begin{verbatim} | ||
1334 | lua_Object lua_rawgetglobal (char *varname); | ||
1335 | \end{verbatim} | ||
1011 | 1336 | ||
1012 | To store a value previously pushed onto C2lua in a global variable, | 1337 | To store a value previously pushed onto C2lua in a global variable, |
1013 | there is the function: | 1338 | there is the function: |
1014 | \Deffunc{lua_storeglobal} | 1339 | \Deffunc{lua_storeglobal} |
1015 | \begin{verbatim} | 1340 | \begin{verbatim} |
1016 | void lua_storeglobal (char *varname); | 1341 | void lua_setglobal (char *varname); |
1342 | \end{verbatim} | ||
1343 | As in Lua, this function may call a tag method. | ||
1344 | To set the real value of any global variable, | ||
1345 | without invoking any tag method, | ||
1346 | this function has a {\em raw\/} version: | ||
1347 | \Deffunc{lua_rawgetglobal} | ||
1348 | \begin{verbatim} | ||
1349 | void lua_rawsetglobal (char *varname); | ||
1017 | \end{verbatim} | 1350 | \end{verbatim} |
1018 | 1351 | ||
1019 | Tables can also be manipulated via the API. | 1352 | Tables can also be manipulated via the API. |
1020 | The function | 1353 | The function |
1021 | \Deffunc{lua_getsubscript} | 1354 | \Deffunc{lua_gettable} |
1022 | \begin{verbatim} | 1355 | \begin{verbatim} |
1023 | lua_Object lua_getsubscript (void); | 1356 | lua_Object lua_gettable (void); |
1024 | \end{verbatim} | 1357 | \end{verbatim} |
1025 | expects on the stack C2lua a table and an index, | 1358 | pops from the stack C2lua a table and an index, |
1026 | and returns the contents of the table at that index. | 1359 | and returns the contents of the table at that index. |
1027 | As in Lua, if the first object is not a table, | 1360 | As in Lua, this operation may call a tag method. |
1028 | or the index is not present in the table, | 1361 | To get the real value of any table index, |
1029 | the corresponding fallback is called. | 1362 | without invoking any tag method, |
1363 | this function has a {\em raw\/} version: | ||
1364 | \Deffunc{lua_rawgetglobal} | ||
1365 | \begin{verbatim} | ||
1366 | lua_Object lua_rawgettable (void); | ||
1367 | \end{verbatim} | ||
1030 | 1368 | ||
1031 | To store a value in an index, | 1369 | To store a value in an index, |
1032 | the program must push the table, the index, | 1370 | the program must push the table, the index, |
1033 | and the value onto C2lua, | 1371 | and the value onto C2lua, |
1034 | and then call the function: | 1372 | and then call the function: |
1035 | \Deffunc{lua_storesubscript} | 1373 | \Deffunc{lua_settable} |
1036 | \begin{verbatim} | 1374 | \begin{verbatim} |
1037 | void lua_storesubscript (void); | 1375 | void lua_settable (void); |
1376 | \end{verbatim} | ||
1377 | Again, the tag method for ``settable'' may be called. | ||
1378 | To set the real value of any table index, | ||
1379 | without invoking any tag method, | ||
1380 | this function has a {\em raw\/} version: | ||
1381 | \Deffunc{lua_rawsettable} | ||
1382 | \begin{verbatim} | ||
1383 | void lua_rawsettable (void); | ||
1038 | \end{verbatim} | 1384 | \end{verbatim} |
1039 | Again, the ``settable'' fallback is called if a non-table value is used. | ||
1040 | 1385 | ||
1041 | Finally, the function | 1386 | Finally, the function |
1042 | \Deffunc{lua_createtable} | 1387 | \Deffunc{lua_createtable} |
@@ -1045,33 +1390,6 @@ lua_Object lua_createtable (void); | |||
1045 | \end{verbatim} | 1390 | \end{verbatim} |
1046 | creates and returns a new, empty table. | 1391 | creates and returns a new, empty table. |
1047 | 1392 | ||
1048 | As already noted, | ||
1049 | most functions from the Lua library receive parameters through C2lua. | ||
1050 | Because other functions also use this stack, | ||
1051 | it is important that these | ||
1052 | parameters be pushed just before the corresponding call, | ||
1053 | without intermediate calls to the Lua library. | ||
1054 | For instance, suppose the user wants the value of \verb|a[i]|, | ||
1055 | where \verb|a| and \verb|i| are global Lua variables. | ||
1056 | A simplistic solution would be: | ||
1057 | \begin{verbatim} | ||
1058 | /* Warning: WRONG CODE */ | ||
1059 | lua_Object result; | ||
1060 | lua_pushobject(lua_getglobal("a")); /* push table */ | ||
1061 | lua_pushobject(lua_getglobal("i")); /* push index */ | ||
1062 | result = lua_getsubscript(); | ||
1063 | \end{verbatim} | ||
1064 | This code is incorrect because | ||
1065 | the call \verb|lua_getglobal("i")| modifies the stack, | ||
1066 | and invalidates the previous pushed value. | ||
1067 | A correct solution could be: | ||
1068 | \begin{verbatim} | ||
1069 | lua_Object result; | ||
1070 | lua_Object index = lua_getglobal("i"); | ||
1071 | lua_pushobject(lua_getglobal("a")); /* push table */ | ||
1072 | lua_pushobject(index); /* push index */ | ||
1073 | result = lua_getsubscript(); | ||
1074 | \end{verbatim} | ||
1075 | 1393 | ||
1076 | \subsection{Calling Lua Functions} | 1394 | \subsection{Calling Lua Functions} |
1077 | Functions defined in Lua by a chunk executed with | 1395 | Functions defined in Lua by a chunk executed with |
@@ -1079,39 +1397,38 @@ Functions defined in Lua by a chunk executed with | |||
1079 | This is done using the following protocol: | 1397 | This is done using the following protocol: |
1080 | first, the arguments to the function are pushed onto C2lua | 1398 | first, the arguments to the function are pushed onto C2lua |
1081 | \see{pushing}, in direct order, i.e., the first argument is pushed first. | 1399 | \see{pushing}, in direct order, i.e., the first argument is pushed first. |
1082 | Again, it is important to emphasize that, during this phase, | ||
1083 | most other Lua functions cannot be called. | ||
1084 | 1400 | ||
1085 | Then, the function is called using | 1401 | Then, the function is called using |
1086 | \Deffunc{lua_call}\Deffunc{lua_callfunction} | 1402 | \Deffunc{lua_callfunction} |
1087 | \begin{verbatim} | ||
1088 | int lua_call (char *functionname); | ||
1089 | \end{verbatim} | ||
1090 | or | ||
1091 | \begin{verbatim} | 1403 | \begin{verbatim} |
1092 | int lua_callfunction (lua_Object function); | 1404 | int lua_callfunction (lua_Object function); |
1093 | \end{verbatim} | 1405 | \end{verbatim} |
1094 | Both functions return an error code: | 1406 | This function returns an error code: |
1095 | 0, in case of success; non zero, in case of errors. | 1407 | 0, in case of success; non zero, in case of errors. |
1096 | Finally, the results (a Lua function may return many values) | 1408 | Finally, the results (a Lua function may return many values) |
1097 | are returned in structure lua2C, | 1409 | are returned in structure lua2C, |
1098 | and can be retrieved with the macro \verb|lua_getresult|, | 1410 | and can be retrieved with the macro \verb|lua_getresult|, |
1099 | \Deffunc{lua_getresult} | 1411 | \Deffunc{lua_getresult} |
1100 | which is just another name to the function \verb|lua_lua2C|. | 1412 | which is just another name to the function \verb|lua_lua2C|. |
1413 | Notice that the function \verb|lua_callfunction| | ||
1414 | pops all elements from the C2lua stack. | ||
1101 | 1415 | ||
1102 | The following example shows how a C program may call the | 1416 | The following example shows how a C program may do the |
1103 | \verb|strsub| function in Lua to extract a piece of a string: | 1417 | equivalent to the Lua code: |
1104 | \begin{verbatim} | 1418 | \begin{verbatim} |
1105 | /* assume that 's' and 'r' are strings (char *), 'i' and 'j' integers */ | 1419 | a = f(t.x, 4) |
1106 | lua_pushstring(s); /* 1st argument */ | 1420 | \end{verbatim} |
1107 | lua_pushnumber(i); /* 2nd argument */ | 1421 | \begin{verbatim} |
1108 | lua_pushnumber(j); /* 3rd argument */ | 1422 | lua_pushobject(lua_getglobal("t")); /* push value of global 't' */ |
1109 | lua_call("strsub"); /* call Lua function */ | 1423 | lua_pushstring("x"); /* push the string 'x' */ |
1110 | r = lua_getstring(lua_getresult(1)); /* r = strsub(s, i, j) */ | 1424 | lua_pushobject(lua_gettable()); /* push result of t.x (= t['x']) */ |
1425 | lua_pushnumber(4); /* 2nd argument */ | ||
1426 | lua_callfunction(lua_getglobal("f")); /* call Lua function */ | ||
1427 | lua_pushobject(lua_getresult(1)); /* push first result of the call */ | ||
1428 | lua_setglobal("a"); /* sets global variable 'a' */ | ||
1111 | \end{verbatim} | 1429 | \end{verbatim} |
1112 | 1430 | ||
1113 | Two special Lua functions have exclusive interfaces: | 1431 | Some special Lua functions have exclusive interfaces. |
1114 | \verb|error| and \verb|setfallback|. | ||
1115 | A C function can generate a Lua error calling the function | 1432 | A C function can generate a Lua error calling the function |
1116 | \Deffunc{lua_error} | 1433 | \Deffunc{lua_error} |
1117 | \begin{verbatim} | 1434 | \begin{verbatim} |
@@ -1122,19 +1439,31 @@ If the C function has been called from Lua, | |||
1122 | then the corresponding Lua execution terminates, | 1439 | then the corresponding Lua execution terminates, |
1123 | as if an error had occurred inside Lua code. | 1440 | as if an error had occurred inside Lua code. |
1124 | Otherwise, the whole program terminates with a call to \verb|exit(1)|. | 1441 | Otherwise, the whole program terminates with a call to \verb|exit(1)|. |
1125 | %%LHF: proponho lua_error(char* m, int rc), gerando exit(rc) | ||
1126 | 1442 | ||
1127 | Fallbacks can be changed with: | 1443 | The error handler method \see{error} can be changed with: |
1128 | \Deffunc{lua_setfallback} | 1444 | \Deffunc{lua_seterrormethod} |
1445 | \begin{verbatim} | ||
1446 | lua_Object lua_seterrormethod (lua_CFunction method); | ||
1447 | \end{verbatim} | ||
1448 | This function returns a \verb|lua_Object|, | ||
1449 | which is the old error method value. | ||
1450 | |||
1451 | Tag methods can be changed with: | ||
1452 | \Deffunc{lua_settagmethod} | ||
1129 | \begin{verbatim} | 1453 | \begin{verbatim} |
1130 | lua_Object lua_setfallback (char *name, lua_CFunction fallback); | 1454 | lua_Object lua_settagmethod (int tag, char *event, lua_CFunction method); |
1131 | \end{verbatim} | 1455 | \end{verbatim} |
1132 | The first parameter is the fallback name \see{fallback}, | 1456 | The first parameter is the tag, |
1133 | and the second is a CFunction to be used as the new fallback. | 1457 | the second is the event name \see{tag-method}, |
1458 | and the third is a CFunction to be used as the new method. | ||
1134 | This function returns a \verb|lua_Object|, | 1459 | This function returns a \verb|lua_Object|, |
1135 | which is the old fallback value, | 1460 | which is the old tag method value. |
1136 | or \nil\ on failure (invalid fallback name). | 1461 | To only get the current value of a tag method, |
1137 | This old value can be used for chaining fallbacks. | 1462 | there is the function |
1463 | \Deffunc{lua_gettagmethod} | ||
1464 | \begin{verbatim} | ||
1465 | lua_Object lua_gettagmethod (int tag, char *event); | ||
1466 | \end{verbatim} | ||
1138 | 1467 | ||
1139 | 1468 | ||
1140 | \subsection{C Functions} \label{LuacallC} | 1469 | \subsection{C Functions} \label{LuacallC} |
@@ -1168,39 +1497,7 @@ in direct order \see{valuesCLua}. | |||
1168 | Like a Lua function, a C function called by Lua can also return | 1497 | Like a Lua function, a C function called by Lua can also return |
1169 | many results. | 1498 | many results. |
1170 | 1499 | ||
1171 | As an example, | 1500 | For some examples, see files \verb|strlib.c|, |
1172 | the code below shows a CFunction to compute the maximum of | ||
1173 | a variable number of arguments: | ||
1174 | \begin{verbatim} | ||
1175 | void math_max (void) | ||
1176 | { | ||
1177 | int i=1; /* argument count */ | ||
1178 | double d, dmax; | ||
1179 | lua_Object o; | ||
1180 | /* the function must get at least one argument */ | ||
1181 | if ((o = lua_getparam(i++)) == LUA_NOOBJECT) | ||
1182 | lua_error("too few arguments to function `max'"); | ||
1183 | /* and this argument must be a number */ | ||
1184 | if (!lua_isnumber(o)) | ||
1185 | lua_error("incorrect argument to function `max'"); | ||
1186 | dmax = lua_getnumber(o); | ||
1187 | /* loops until there is no more arguments */ | ||
1188 | while ((o = lua_getparam(i++)) != LUA_NOOBJECT) { | ||
1189 | if (!lua_isnumber(o)) | ||
1190 | lua_error("incorrect argument to function `max'"); | ||
1191 | d = lua_getnumber(o); | ||
1192 | if (d > dmax) dmax = d; | ||
1193 | } | ||
1194 | /* push the result to be returned */ | ||
1195 | lua_pushnumber(dmax); | ||
1196 | } | ||
1197 | \end{verbatim} | ||
1198 | To be available in Lua, this function must be registered: | ||
1199 | \begin{verbatim} | ||
1200 | lua_register ("max", math_max); | ||
1201 | \end{verbatim} | ||
1202 | |||
1203 | For more examples, see files \verb|strlib.c|, | ||
1204 | \verb|iolib.c| and \verb|mathlib.c| in Lua distribution. | 1501 | \verb|iolib.c| and \verb|mathlib.c| in Lua distribution. |
1205 | 1502 | ||
1206 | \subsection{References to Lua Objects} | 1503 | \subsection{References to Lua Objects} |
@@ -1211,11 +1508,10 @@ outside block boundaries, | |||
1211 | it must create a \Def{reference} to the object. | 1508 | it must create a \Def{reference} to the object. |
1212 | The routines to manipulate references are the following: | 1509 | The routines to manipulate references are the following: |
1213 | \Deffunc{lua_ref}\Deffunc{lua_getref} | 1510 | \Deffunc{lua_ref}\Deffunc{lua_getref} |
1214 | \Deffunc{lua_pushref}\Deffunc{lua_unref} | 1511 | \Deffunc{lua_unref} |
1215 | \begin{verbatim} | 1512 | \begin{verbatim} |
1216 | int lua_ref (int lock); | 1513 | int lua_ref (int lock); |
1217 | lua_Object lua_getref (int ref); | 1514 | lua_Object lua_getref (int ref); |
1218 | void lua_pushref (int ref); | ||
1219 | void lua_unref (int ref); | 1515 | void lua_unref (int ref); |
1220 | \end{verbatim} | 1516 | \end{verbatim} |
1221 | The function \verb|lua_ref| creates a reference | 1517 | The function \verb|lua_ref| creates a reference |
@@ -1226,19 +1522,13 @@ this means the object will not be garbage collected. | |||
1226 | Notice that an unlocked reference may be garbage collected. | 1522 | Notice that an unlocked reference may be garbage collected. |
1227 | Whenever the referenced object is needed, | 1523 | Whenever the referenced object is needed, |
1228 | a call to \verb|lua_getref| | 1524 | a call to \verb|lua_getref| |
1229 | returns a handle to it, | 1525 | returns a handle to it; |
1230 | whereas \verb|lua_pushref| pushes the object on the stack. | 1526 | if the object has been collected, |
1231 | If the object has been collected, | 1527 | \verb|lua_getref| returns \verb|LUA_NOOBJECT|. |
1232 | then \verb|lua_getref| returns \verb|LUA_NOOBJECT|, | ||
1233 | and \verb|lua_pushobject| issues an error. | ||
1234 | 1528 | ||
1235 | When a reference is no longer needed, | 1529 | When a reference is no longer needed, |
1236 | it can be freed with a call to \verb|lua_unref|. | 1530 | it can be freed with a call to \verb|lua_unref|. |
1237 | 1531 | ||
1238 | The function \verb|lua_pushref| does not corrupt the | ||
1239 | structures lua2C and C2lua, and therefore is safe to | ||
1240 | be called when pushing parameters onto C2lua. | ||
1241 | |||
1242 | 1532 | ||
1243 | 1533 | ||
1244 | \section{Predefined Functions and Libraries} | 1534 | \section{Predefined Functions and Libraries} |
@@ -1266,7 +1556,44 @@ the host program must call the functions | |||
1266 | declared in \verb|lualib.h|. | 1556 | declared in \verb|lualib.h|. |
1267 | 1557 | ||
1268 | 1558 | ||
1269 | \subsection{Predefined Functions} | 1559 | \subsection{Predefined Functions} \label{predefined} |
1560 | |||
1561 | \subsection*{\ff{\tt call (func, arg, [retmode])}}\Deffunc{call} | ||
1562 | This function calls function \verb|func| with | ||
1563 | the arguments given by the table \verb|arg|. | ||
1564 | The call is equivalent to | ||
1565 | \begin{verbatim} | ||
1566 | func(arg[1], arg[2], ..., arg[arg.n]) | ||
1567 | \end{verbatim} | ||
1568 | If \verb|arg.n| is not defined, | ||
1569 | Lua gets the arguments from \verb|arg[1]| until the first nil value. | ||
1570 | |||
1571 | If \verb|retmode| is equal to \verb|"plain"| or is absent, | ||
1572 | all results from \verb|func| are just returned by the call. | ||
1573 | If \verb|retmode| is equal to \verb|"pack"|, | ||
1574 | the results are {\em packed\/} in a single table.\index{packed results} | ||
1575 | That is, \verb|call| returns just one table. | ||
1576 | At index \verb|n| the table has the total number of results | ||
1577 | from the call; | ||
1578 | the first result is at index 1, etc. | ||
1579 | |||
1580 | For instance, the following calls produce the following results: | ||
1581 | \begin{verbatim} | ||
1582 | a = call(sin, {5}) -- a = 0.0871557 = sin(5) | ||
1583 | a = call(max, {1,4,5; n=2}) -- a = 4 (only 1 and 4 are arguments) | ||
1584 | t = {x=1} | ||
1585 | a = call(next, {t,nil;n=2}, "pack") -- a={"x", 1; n=2} | ||
1586 | \end{verbatim} | ||
1587 | |||
1588 | \subsection*{\ff{\tt callgc ([nextgc])}}\Deffunc{callgc} | ||
1589 | Forces a garbage collection cicle. | ||
1590 | Returns the number of objects collected. | ||
1591 | An optional argument, \verb|nextgc|, is a number that | ||
1592 | makes the next cicle occur when that number of new | ||
1593 | objects have been created. | ||
1594 | If absent, Lua uses an adaptative algorithm to set | ||
1595 | this limit. | ||
1596 | \verb|nextgc| is simply an interface to \verb|lua_collectgarbage|. | ||
1270 | 1597 | ||
1271 | \subsubsection*{\ff{\tt dofile (filename)}}\Deffunc{dofile} | 1598 | \subsubsection*{\ff{\tt dofile (filename)}}\Deffunc{dofile} |
1272 | This function receives a file name, | 1599 | This function receives a file name, |
@@ -1287,6 +1614,10 @@ Otherwise, it returns the values returned by the chunk, | |||
1287 | or a non \nil\ value if the chunk returns no values. | 1614 | or a non \nil\ value if the chunk returns no values. |
1288 | \verb|dostring| is simply an interface to \verb|lua_dostring|. | 1615 | \verb|dostring| is simply an interface to \verb|lua_dostring|. |
1289 | 1616 | ||
1617 | \subsubsection*{\ff{\tt newtag ()}}\Deffunc{newtag}\label{pdf-newtag} | ||
1618 | Returns a new tag. | ||
1619 | \verb|newtag| is simply an interface to \verb|lua_newtag|. | ||
1620 | |||
1290 | \subsubsection*{\ff{\tt next (table, index)}}\Deffunc{next} | 1621 | \subsubsection*{\ff{\tt next (table, index)}}\Deffunc{next} |
1291 | This function allows a program to traverse all fields of a table. | 1622 | This function allows a program to traverse all fields of a table. |
1292 | Its first argument is a table and its second argument | 1623 | Its first argument is a table and its second argument |
@@ -1351,17 +1682,21 @@ The possible results of this function are | |||
1351 | \verb|"number"|, | 1682 | \verb|"number"|, |
1352 | \verb|"string"|, | 1683 | \verb|"string"|, |
1353 | \verb|"table"|, | 1684 | \verb|"table"|, |
1354 | \verb|"function"| (returned both for C functions and Lua functions), | 1685 | \verb|"function"|, |
1355 | and \verb|"userdata"|. | 1686 | and \verb|"userdata"|. |
1356 | 1687 | ||
1357 | Besides this string, the function returns a second result, | ||
1358 | which is the \Def{tag} of the value. | ||
1359 | This tag can be used to distinguish between user | ||
1360 | data with different tags, | ||
1361 | and between C functions and Lua functions. | ||
1362 | |||
1363 | \verb|type| is simply an interface to \verb|lua_type|. | 1688 | \verb|type| is simply an interface to \verb|lua_type|. |
1364 | 1689 | ||
1690 | \subsubsection*{\ff{\tt tag (v)}}\Deffunc{tag} | ||
1691 | This function allows Lua to test the tag of a value \see{TypesSec}. | ||
1692 | It receives one argument, and returns its tag (a number). | ||
1693 | |||
1694 | \subsubsection*{\ff{\tt settag (o, tag)}}\Deffunc{settag} | ||
1695 | This function sets the tag of a given object \see{TypesSec}. | ||
1696 | The object \verb|o| must be a userdata or a table. | ||
1697 | \verb|tag| must be a value created with \verb|newtag| | ||
1698 | \see{pdf-newtag}. | ||
1699 | |||
1365 | \subsubsection*{\ff{\tt assert (v)}}\Deffunc{assert} | 1700 | \subsubsection*{\ff{\tt assert (v)}}\Deffunc{assert} |
1366 | This function issues an {\em ``assertion failed!''} error | 1701 | This function issues an {\em ``assertion failed!''} error |
1367 | when its argument is \nil. | 1702 | when its argument is \nil. |
@@ -1369,27 +1704,63 @@ when its argument is \nil. | |||
1369 | \subsubsection*{\ff{\tt error (message)}}\Deffunc{error}\label{pdf-error} | 1704 | \subsubsection*{\ff{\tt error (message)}}\Deffunc{error}\label{pdf-error} |
1370 | This function issues an error message and terminates | 1705 | This function issues an error message and terminates |
1371 | the last called function from the library | 1706 | the last called function from the library |
1372 | (\verb|lua_dofile|, \verb|lua_dostring|, \ldots). | 1707 | (\verb|lua_dofile|, \verb|lua_dostring|, or \verb|lua_callfunction|). |
1373 | It never returns. | 1708 | It never returns. |
1374 | \verb|error| is simply an interface to \verb|lua_error|. | 1709 | \verb|error| is simply an interface to \verb|lua_error|. |
1375 | 1710 | ||
1376 | \subsubsection*{\ff{\tt setglobal (name, value)}}\Deffunc{setglobal} | 1711 | \subsubsection*{\ff{\tt rawgettable (table, index)}}\Deffunc{rawgettable} |
1712 | Gets the real value of \verb|table[index]|, | ||
1713 | without invoking any tag method. | ||
1714 | \verb|table| must be a table, | ||
1715 | and \verb|index| is any value different from \nil. | ||
1716 | |||
1717 | \subsubsection*{\ff{\tt rawsettable (table, index, value)}}\Deffunc{rawsettable} | ||
1718 | Sets the real value \verb|table[index]=value|, | ||
1719 | without invoking any tag method. | ||
1720 | \verb|table| must be a table, | ||
1721 | \verb|index| is any value different from \nil, | ||
1722 | and \verb|value| is any Lua value. | ||
1723 | |||
1724 | \subsubsection*{\ff{\tt rawsetglobal (name, value)}}\Deffunc{rawsetglobal} | ||
1377 | This function assigns the given value to a global variable. | 1725 | This function assigns the given value to a global variable. |
1378 | The string \verb|name| does not need to be a syntactically valid variable name. | 1726 | The string \verb|name| does not need to be a syntactically valid variable name. |
1379 | Therefore, this function can set global variables with strange names like | 1727 | Therefore, this function can set global variables with strange names like |
1380 | \verb|`m v 1'| or \verb|34|. | 1728 | \verb|`m v 1'| or \verb|34|. |
1381 | It returns the value of its second argument. | 1729 | It returns the value of its second argument. |
1382 | \verb|setglobal| is simply an interface to \verb|lua_storeglobal|. | ||
1383 | 1730 | ||
1384 | \subsubsection*{\ff{\tt getglobal (name)}}\Deffunc{getglobal} | 1731 | \subsubsection*{\ff{\tt setglobal (name, value)}}\Deffunc{setglobal} |
1732 | This function assigns the given value to a global variable, | ||
1733 | or calls a tag method. | ||
1734 | Its full semantics is explained in \See{tag-method}. | ||
1735 | |||
1736 | \subsubsection*{\ff{\tt rawgetglobal (name)}}\Deffunc{rawgetglobal} | ||
1385 | This function retrieves the value of a global variable. | 1737 | This function retrieves the value of a global variable. |
1386 | The string \verb|name| does not need to be a syntactically valid variable name. | 1738 | The string \verb|name| does not need to be a |
1739 | syntactically valid variable name. | ||
1740 | |||
1741 | \subsubsection*{\ff{\tt getglobal (name)}}\Deffunc{getglobal} | ||
1742 | This function retrieves the value of a global variable, | ||
1743 | or calls a tag method. | ||
1744 | Its full semantics is explained in \See{tag-method}. | ||
1745 | |||
1746 | \subsubsection*{\ff{\tt seterrormethod (newmethod)}} | ||
1747 | Sets the error handler \see{error}. | ||
1748 | \verb|newmethod| must be a function or \nil, | ||
1749 | in which case the error handler does nothing. | ||
1750 | Returns the old handler. | ||
1751 | |||
1752 | \subsubsection*{\ff{\tt settagmethod (tag, event, newmethod)}} | ||
1753 | \Deffunc{settagmethod} | ||
1754 | This function sets a new tag method to the given pair $<tag, event>$. | ||
1755 | It returns the old method. | ||
1756 | If \verb|newmethod| is \nil, | ||
1757 | it restores the default behavior for the given event. | ||
1758 | |||
1759 | \subsubsection*{\ff{\tt gettagmethod (tag, event)}} | ||
1760 | \Deffunc{gettagmethod} | ||
1761 | This function returns the current tag method | ||
1762 | for a given pair $<tag, event>$. | ||
1387 | 1763 | ||
1388 | \subsubsection*{\ff{\tt setfallback (fallbackname, newfallback)}} | ||
1389 | \Deffunc{setfallback} | ||
1390 | This function sets a new fallback function to the given fallback. | ||
1391 | It returns the old fallback function. | ||
1392 | \verb|setfallback| is simply an interface to \verb|lua_setfallback|. | ||
1393 | 1764 | ||
1394 | \subsection{String Manipulation} | 1765 | \subsection{String Manipulation} |
1395 | This library provides generic functions for string manipulation, | 1766 | This library provides generic functions for string manipulation, |
@@ -1418,12 +1789,18 @@ Receives a string and returns its length. | |||
1418 | \subsubsection*{\ff{\tt strsub (s, i [, j])}}\Deffunc{strsub} | 1789 | \subsubsection*{\ff{\tt strsub (s, i [, j])}}\Deffunc{strsub} |
1419 | Returns another string, which is a substring of \verb|s|, | 1790 | Returns another string, which is a substring of \verb|s|, |
1420 | starting at \verb|i| and runing until \verb|j|. | 1791 | starting at \verb|i| and runing until \verb|j|. |
1421 | If \verb|j| is absent, | 1792 | If \verb|i| or \verb|j| are negative, |
1422 | it is assumed to be equal to the length of \verb|s|. | 1793 | they are replaced by the length of the string minus their |
1423 | In particular, the call \verb|strsub(s,1,j)| returns a prefix of \verb|s| | 1794 | absolute value plus 1. |
1795 | Therefore, -1 points to the last character of \verb|s| | ||
1796 | and -2 to the previous one. | ||
1797 | If \verb|j| is absent, it is assumed to be equal to -1 | ||
1798 | (which is the same as the string length). | ||
1799 | In particular, | ||
1800 | the call \verb|strsub(s,1,j)| returns a prefix of \verb|s| | ||
1424 | with length \verb|j|, | 1801 | with length \verb|j|, |
1425 | whereas the call \verb|strsub(s,i)| returns a suffix of \verb|s|, | 1802 | and the call \verb|strsub(s, -i)| returns a suffix of \verb|s| |
1426 | starting at \verb|i|. | 1803 | with length \verb|i|. |
1427 | 1804 | ||
1428 | \subsubsection*{\ff{\tt strlower (s)}}\Deffunc{strlower} | 1805 | \subsubsection*{\ff{\tt strlower (s)}}\Deffunc{strlower} |
1429 | Receives a string and returns a copy of that string with all | 1806 | Receives a string and returns a copy of that string with all |
@@ -1612,7 +1989,7 @@ and the part matching \verb|%s*| has number 3. | |||
1612 | \subsection{Mathematical Functions} \label{mathlib} | 1989 | \subsection{Mathematical Functions} \label{mathlib} |
1613 | 1990 | ||
1614 | This library is an interface to some functions of the standard C math library. | 1991 | This library is an interface to some functions of the standard C math library. |
1615 | In addition, it registers a fallback for the binary operator \verb|^| that, | 1992 | In addition, it registers a tag method for the binary operator \verb|^| that |
1616 | returns \M{x^y} when applied to numbers \verb|x^y|. | 1993 | returns \M{x^y} when applied to numbers \verb|x^y|. |
1617 | 1994 | ||
1618 | The library provides the following functions: | 1995 | The library provides the following functions: |
@@ -1892,13 +2269,13 @@ they do not have a fixed name: | |||
1892 | Some functions may be the value of many global variables, | 2269 | Some functions may be the value of many global variables, |
1893 | while others may be stored only in a table field. | 2270 | while others may be stored only in a table field. |
1894 | Function \verb|lua_getobjname| first checks whether the given | 2271 | Function \verb|lua_getobjname| first checks whether the given |
1895 | function is a fallback. | 2272 | function is a tag method. |
1896 | If so, it returns the string \verb|"fallback"|, | 2273 | If so, it returns the string \verb|"tag-method"|, |
1897 | and \verb|name| is set to point to the fallback name. | 2274 | and \verb|name| is set to point to the event name. |
1898 | Otherwise, if the given function is the value of a global variable, | 2275 | Otherwise, if the given function is the value of a global variable, |
1899 | then \verb|lua_getobjname| returns the string \verb|"global"|, | 2276 | then \verb|lua_getobjname| returns the string \verb|"global"|, |
1900 | and \verb|name| points to the variable name. | 2277 | and \verb|name| points to the variable name. |
1901 | If the given function is neither a fallback nor a global variable, | 2278 | If the given function is neither a tag method nor a global variable, |
1902 | then \verb|lua_getobjname| returns the empty string, | 2279 | then \verb|lua_getobjname| returns the empty string, |
1903 | and \verb|name| is set to \verb|NULL|. | 2280 | and \verb|name| is set to \verb|NULL|. |
1904 | 2281 | ||
@@ -2131,3 +2508,9 @@ Special care should be taken with macros like | |||
2131 | 2508 | ||
2132 | 2509 | ||
2133 | \end{document} | 2510 | \end{document} |
2511 | |||
2512 | |||
2513 | |||
2514 | |||
2515 | |||
2516 | |||