diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2000-09-18 16:41:16 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2000-09-18 16:41:16 -0300 |
commit | 6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117 (patch) | |
tree | 29b1976e0a5895051a1838f283565e5d91f67e1d | |
parent | 42ca3105acab0eab0bd99af58e2bbdff111325f1 (diff) | |
download | lua-6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117.tar.gz lua-6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117.tar.bz2 lua-6ec4a0ef767f2a49983b4e2eb1d3fdb1fd331117.zip |
updates by lhf
-rw-r--r-- | manual.tex | 2183 |
1 files changed, 1154 insertions, 1029 deletions
@@ -1,4 +1,4 @@ | |||
1 | % $Id: manual.tex,v 1.41 2000/08/14 19:18:14 roberto Exp roberto $ | 1 | % $Id: manual.tex,v 1.42 2000/08/30 18:58:46 roberto Exp roberto $ |
2 | 2 | ||
3 | \documentclass[11pt]{article} | 3 | \documentclass[11pt]{article} |
4 | \usepackage{fullpage,bnf} | 4 | \usepackage{fullpage,bnf} |
@@ -28,7 +28,7 @@ | |||
28 | % LHF | 28 | % LHF |
29 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} | 29 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} |
30 | \newcommand{\Nter}[1]{{\rm{\tt#1}}} | 30 | \newcommand{\Nter}[1]{{\rm{\tt#1}}} |
31 | \newcommand{\NOTE}{\par\noindent\emph{NOTE}: } | 31 | \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } |
32 | 32 | ||
33 | \makeindex | 33 | \makeindex |
34 | 34 | ||
@@ -70,28 +70,29 @@ Copyright \copyright\ 1994--2000 TeCGraf, PUC-Rio. All rights reserved. | |||
70 | 70 | ||
71 | \noindent | 71 | \noindent |
72 | Permission is hereby granted, without written agreement and without license | 72 | Permission is hereby granted, without written agreement and without license |
73 | or royalty fees, to use, copy, modify, and distribute this software and its | 73 | or royalty fees, to use, copy, modify, translate, and distribute |
74 | documentation for any purpose, including commercial applications, subject to | 74 | this software and its documentation (hereby called the "package") |
75 | for any purpose, including commercial applications, subject to | ||
75 | the following conditions: | 76 | the following conditions: |
76 | \begin{itemize} | 77 | \begin{itemize} |
77 | \item The above copyright notice and this permission notice shall appear in all | 78 | \item The above copyright notice and this permission notice shall appear in all |
78 | copies or substantial portions of this software. | 79 | copies or substantial portions of this package. |
79 | 80 | ||
80 | \item The origin of this software must not be misrepresented; you must not | 81 | \item The origin of this package must not be misrepresented; you must not |
81 | claim that you wrote the original software. If you use this software in a | 82 | claim that you wrote the original package. If you use this package in a |
82 | product, an acknowledgment in the product documentation would be greatly | 83 | product, an acknowledgment in the product documentation would be greatly |
83 | appreciated (but it is not required). | 84 | appreciated (but it is not required). |
84 | 85 | ||
85 | \item Altered source versions must be plainly marked as such, and must not be | 86 | \item Altered source versions must be plainly marked as such, and must not be |
86 | misrepresented as being the original software. | 87 | misrepresented as being the original package. |
87 | \end{itemize} | 88 | \end{itemize} |
88 | The authors specifically disclaim any warranties, including, but not limited | 89 | The authors specifically disclaim any warranties, including, but not limited |
89 | to, the implied warranties of merchantability and fitness for a particular | 90 | to, the implied warranties of merchantability and fitness for a particular |
90 | purpose. The software provided hereunder is on an ``as is'' basis, and the | 91 | purpose. The package provided hereunder is on an ``as is'' basis, and the |
91 | authors have no obligation to provide maintenance, support, updates, | 92 | authors have no obligation to provide maintenance, support, updates, |
92 | enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the | 93 | enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the |
93 | authors be held liable to any party for direct, indirect, special, | 94 | authors be held liable to any party for direct, indirect, special, |
94 | incidental, or consequential damages arising out of the use of this software | 95 | incidental, or consequential damages arising out of the use of this package |
95 | and its documentation. | 96 | and its documentation. |
96 | 97 | ||
97 | \noindent | 98 | \noindent |
@@ -105,11 +106,16 @@ This implementation contains no third-party code. | |||
105 | \noindent | 106 | \noindent |
106 | Copies of this manual can be obtained at | 107 | Copies of this manual can be obtained at |
107 | \verb|http://www.tecgraf.puc-rio.br/lua/|. | 108 | \verb|http://www.tecgraf.puc-rio.br/lua/|. |
109 | |||
110 | \bigskip | ||
111 | \noindent | ||
112 | The Lua logo was designed by A. Nakonechny. | ||
113 | Copyright \copyright\ 1998. All rights reserved. | ||
108 | \end{quotation} | 114 | \end{quotation} |
109 | %}=============================================================== | 115 | %}=============================================================== |
110 | \newpage | 116 | \newpage |
111 | 117 | ||
112 | \title{Reference Manual of the Programming Language Lua \Version} | 118 | \title{\Large\bf Reference Manual of the Programming Language Lua \Version} |
113 | 119 | ||
114 | \author{% | 120 | \author{% |
115 | Roberto Ierusalimschy\quad | 121 | Roberto Ierusalimschy\quad |
@@ -123,12 +129,15 @@ Waldemar Celes | |||
123 | \tecgraf\ --- Computer Science Department --- PUC-Rio | 129 | \tecgraf\ --- Computer Science Department --- PUC-Rio |
124 | } | 130 | } |
125 | 131 | ||
126 | \date{{\small \tt\$Date: 2000/08/14 19:18:14 $ $}} | 132 | \date{{\small \tt\$Date: 2000/08/30 18:58:46 $ $}} |
127 | 133 | ||
128 | \maketitle | 134 | \maketitle |
129 | 135 | ||
130 | \thispagestyle{empty} | 136 | \pagestyle{plain} |
131 | \pagestyle{empty} | 137 | \pagenumbering{roman} |
138 | |||
139 | %\thispagestyle{empty} | ||
140 | %\pagestyle{empty} | ||
132 | 141 | ||
133 | \begin{abstract} | 142 | \begin{abstract} |
134 | \noindent | 143 | \noindent |
@@ -151,8 +160,8 @@ and | |||
151 | rapid prototyping. | 160 | rapid prototyping. |
152 | 161 | ||
153 | This document describes version \Version\ of the Lua programming language | 162 | This document describes version \Version\ of the Lua programming language |
154 | and the API that allows interaction between Lua programs and their | 163 | and the Application Program Interface (API) |
155 | host C programs. | 164 | that allows interaction between Lua programs and their host C~programs. |
156 | \end{abstract} | 165 | \end{abstract} |
157 | 166 | ||
158 | \def\abstractname{Resumo} | 167 | \def\abstractname{Resumo} |
@@ -160,7 +169,7 @@ host C programs. | |||
160 | \noindent | 169 | \noindent |
161 | Lua \'e uma linguagem de programa\c{c}\~ao | 170 | Lua \'e uma linguagem de programa\c{c}\~ao |
162 | poderosa e leve, | 171 | poderosa e leve, |
163 | projetada para extender aplica\c{c}\~oes. | 172 | projetada para estender aplica\c{c}\~oes. |
164 | Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral. | 173 | Lua tamb\'em \'e frequentemente usada como uma linguagem de prop\'osito geral. |
165 | Lua combina programa\c{c}\~ao procedural | 174 | Lua combina programa\c{c}\~ao procedural |
166 | (com sintaxe semelhante \`a de Pascal) | 175 | (com sintaxe semelhante \`a de Pascal) |
@@ -178,7 +187,7 @@ e prototipagem r\'apida. | |||
178 | 187 | ||
179 | Este documento descreve a vers\~ao \Version\ da linguagem de | 188 | Este documento descreve a vers\~ao \Version\ da linguagem de |
180 | programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite | 189 | programa\c{c}\~ao Lua e a Interface de Programa\c{c}\~ao (API) que permite |
181 | a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. | 190 | a intera\c{c}\~ao entre programas Lua e programas C~hospedeiros. |
182 | \end{abstract} | 191 | \end{abstract} |
183 | 192 | ||
184 | \newpage | 193 | \newpage |
@@ -188,6 +197,7 @@ a intera\c{c}\~ao entre programas Lua e programas C hospedeiros. | |||
188 | 197 | ||
189 | \newpage | 198 | \newpage |
190 | \setcounter{page}{1} | 199 | \setcounter{page}{1} |
200 | \pagenumbering{arabic} | ||
191 | \pagestyle{plain} | 201 | \pagestyle{plain} |
192 | 202 | ||
193 | 203 | ||
@@ -211,13 +221,13 @@ a wide range of different domains, | |||
211 | thus creating customized programming languages sharing a syntactical framework. | 221 | thus creating customized programming languages sharing a syntactical framework. |
212 | 222 | ||
213 | Lua is free-distribution software, | 223 | Lua is free-distribution software, |
214 | and provided as usual with no guarantees, | 224 | and is provided as usual with no guarantees, |
215 | as stated in its copyright notice. | 225 | as stated in its copyright notice. |
216 | The implementation described in this manual is available | 226 | The implementation described in this manual is available |
217 | at the following URL's: | 227 | at the following URL's: |
218 | \begin{verbatim} | 228 | \begin{verbatim} |
219 | http://www.tecgraf.puc-rio.br/lua/ | 229 | http://www.tecgraf.puc-rio.br/lua/ |
220 | ftp://ftp.tecgraf.puc-rio.br/pub/lua/ | 230 | ftp://ftp.tecgraf.puc-rio.br/pub/lua/ |
221 | \end{verbatim} | 231 | \end{verbatim} |
222 | 232 | ||
223 | Like any other reference manual, | 233 | Like any other reference manual, |
@@ -244,10 +254,11 @@ Lua: an extensible embedded language. | |||
244 | 254 | ||
245 | All statements in Lua are executed in a \Def{global environment}. | 255 | All statements in Lua are executed in a \Def{global environment}. |
246 | This environment is initialized with a call from the embedding program to | 256 | This environment is initialized with a call from the embedding program to |
247 | \verb|lua_newstate| and | 257 | \verb|lua_open| and |
248 | persists until a call to \verb|lua_close|, | 258 | persists until a call to \verb|lua_close|, |
249 | or the end of the embedding program. | 259 | or the end of the embedding program. |
250 | Optionally, a user can create multiple independent global | 260 | If necessary, |
261 | the host programmer can create multiple independent global | ||
251 | environments, and freely switch between them \see{mangstate}. | 262 | environments, and freely switch between them \see{mangstate}. |
252 | 263 | ||
253 | The global environment can be manipulated by Lua code or | 264 | The global environment can be manipulated by Lua code or |
@@ -255,13 +266,13 @@ by the embedding program, | |||
255 | which can read and write global variables | 266 | which can read and write global variables |
256 | using API functions from the library that implements Lua. | 267 | using API functions from the library that implements Lua. |
257 | 268 | ||
258 | \Index{Global variables} do not need declaration. | 269 | \Index{Global variables} in Lua do not need to be declared. |
259 | Any variable is assumed to be global unless explicitly declared local | 270 | Any variable is assumed to be global unless explicitly declared local |
260 | \see{localvar}. | 271 | \see{localvar}. |
261 | Before the first assignment, the value of a global variable is \nil; | 272 | Before the first assignment, the value of a global variable is \nil; |
262 | this default can be changed \see{tag-method}. | 273 | this default can be changed \see{tag-method}. |
263 | A ``table of globals'' (called \emph{tog}) is used to keep all | 274 | A table is used to keep all global names and values |
264 | global names and values. | 275 | (tables are explained in \See{TypesSec}). |
265 | 276 | ||
266 | The unit of execution of Lua is called a \Def{chunk}. | 277 | The unit of execution of Lua is called a \Def{chunk}. |
267 | A chunk is simply a sequence of statements, | 278 | A chunk is simply a sequence of statements, |
@@ -275,11 +286,12 @@ Statements are described in \See{stats}. | |||
275 | in which | 286 | in which |
276 | \rep{\emph{a}} means 0 or more \emph{a}'s, | 287 | \rep{\emph{a}} means 0 or more \emph{a}'s, |
277 | \opt{\emph{a}} means an optional \emph{a}, and | 288 | \opt{\emph{a}} means an optional \emph{a}, and |
278 | \oneormore{\emph{a}} means one or more \emph{a}'s.) | 289 | \oneormore{\emph{a}} means one or more \emph{a}'s. |
290 | The complete syntax of Lua is given on page~\pageref{BNF}.) | ||
279 | 291 | ||
280 | A chunk may be in a file or in a string inside the host program. | 292 | A chunk may be stored in a file or in a string inside the host program. |
281 | When a chunk is executed, first all its code is pre-compiled, | 293 | When a chunk is executed, first it is pre-compiled into bytecodes for |
282 | and then the statements are executed in sequential order. | 294 | a virtual machine, and then the statements are executed in sequential order. |
283 | All modifications a chunk effects on the global environment persist | 295 | All modifications a chunk effects on the global environment persist |
284 | after the chunk ends. | 296 | after the chunk ends. |
285 | 297 | ||
@@ -305,7 +317,8 @@ There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, | |||
305 | whose main property is to be different from any other value. | 317 | whose main property is to be different from any other value. |
306 | \emph{Number} represents real (double-precision floating-point) numbers, | 318 | \emph{Number} represents real (double-precision floating-point) numbers, |
307 | while \emph{string} has the usual meaning. | 319 | while \emph{string} has the usual meaning. |
308 | Lua is \Index{eight-bit clean}, | 320 | \index{eight-bit clean} |
321 | Lua is 8-bit clean, | ||
309 | and so strings may contain any 8-bit character, | 322 | and so strings may contain any 8-bit character, |
310 | \emph{including} embedded zeros (\verb|'\0'|) \see{lexical}. | 323 | \emph{including} embedded zeros (\verb|'\0'|) \see{lexical}. |
311 | The \verb|type| function returns a string describing the type | 324 | The \verb|type| function returns a string describing the type |
@@ -325,8 +338,9 @@ of a given value \see{pdf-tag}. | |||
325 | 338 | ||
326 | The type \emph{userdata} is provided to allow | 339 | The type \emph{userdata} is provided to allow |
327 | arbitrary \Index{C pointers} to be stored in Lua variables. | 340 | arbitrary \Index{C pointers} to be stored in Lua variables. |
328 | It corresponds to a \verb|void*| and has no pre-defined operations in Lua, | 341 | This type corresponds to a \verb|void*| |
329 | besides assignment and equality test. | 342 | and has no pre-defined operations in Lua, |
343 | except for assignment and equality test. | ||
330 | However, by using \emph{tag methods}, | 344 | However, by using \emph{tag methods}, |
331 | the programmer can define operations for \emph{userdata} values | 345 | the programmer can define operations for \emph{userdata} values |
332 | \see{tag-method}. | 346 | \see{tag-method}. |
@@ -345,31 +359,32 @@ Because functions are first class values, | |||
345 | table fields may contain functions. | 359 | table fields may contain functions. |
346 | The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, | 360 | The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, |
347 | which calls the method \verb|f| from the table \verb|t| passing | 361 | which calls the method \verb|f| from the table \verb|t| passing |
348 | itself as the first parameter \see{func-def}. | 362 | the table itself as the first parameter \see{func-def}. |
349 | 363 | ||
350 | Note that tables are \emph{objects}, and not values. | 364 | Note that tables are \emph{objects}, and not values. |
351 | Variables cannot contain tables, only \emph{references} to them. | 365 | Variables do not contain tables, only \emph{references} to them. |
352 | Assignment, parameter passing, and returns always manipulate references | 366 | Assignment, parameter passing, and returns always manipulate references |
353 | to tables, and do not imply any kind of copy. | 367 | to tables, and do not imply any kind of copy. |
354 | Moreover, tables must be explicitly created before used | 368 | Moreover, tables must be explicitly created before used |
355 | \see{tableconstructor}. | 369 | \see{tableconstructor}. |
356 | 370 | ||
357 | Tags are mainly used to select \emph{tag methods} when | ||
358 | some events occur. | ||
359 | Tag methods are the main mechanism for extending the | ||
360 | semantics of Lua \see{tag-method}. | ||
361 | Each of the types \M{nil}, \M{number}, and \M{string} has a different tag. | 371 | Each of the types \M{nil}, \M{number}, and \M{string} has a different tag. |
362 | All values of each of these types have the same pre-defined tag. | 372 | All values of each of these types have the same pre-defined tag. |
363 | Values of type \M{function} can have two different tags, | 373 | Values of type \M{function} can have two different tags, |
364 | depending on whether they are Lua functions or C~functions. | 374 | depending on whether they are Lua functions or C~functions. |
365 | Finally, | 375 | Finally, |
366 | values of type \M{userdata} and \M{table} have | 376 | values of type \M{userdata} and \M{table} can have variable tags, |
367 | variable tags, assigned by the program \see{tag-method}. | 377 | assigned by the programmer \see{tag-method}. |
368 | Tags are created with the function \verb|newtag|, | 378 | The function \verb|tag| returns the tag of a given value. |
369 | and the function \verb|tag| returns the tag of a given value. | 379 | User tags are created with the function \verb|newtag|, |
370 | To change the tag of a given table, | 380 | The function \verb|settag| \see{pdf-newtag} |
371 | there is the function \verb|settag| \see{pdf-newtag}. | 381 | is used to change the tag of a table. |
382 | The data of userdata can only be set from~C. | ||
372 | 383 | ||
384 | Tags are mainly used to select \emph{tag methods} when | ||
385 | some events occur. | ||
386 | Tag methods are the main mechanism for extending the | ||
387 | semantics of Lua \see{tag-method}. | ||
373 | 388 | ||
374 | \section{The Language} | 389 | \section{The Language} |
375 | 390 | ||
@@ -389,12 +404,12 @@ can be used in an identifier. | |||
389 | The following words are \emph{reserved}, and cannot be used as identifiers: | 404 | The following words are \emph{reserved}, and cannot be used as identifiers: |
390 | \index{reserved words} | 405 | \index{reserved words} |
391 | \begin{verbatim} | 406 | \begin{verbatim} |
392 | and break do else | 407 | and break do else elseif |
393 | elseif end for function | 408 | end for function if in |
394 | if local nil not | 409 | local nil not or repeat |
395 | or repeat return then | 410 | return then until while |
396 | until while | ||
397 | \end{verbatim} | 411 | \end{verbatim} |
412 | |||
398 | Lua is a case-sensitive language: | 413 | Lua is a case-sensitive language: |
399 | \T{and} is a reserved word, but \T{And} and \T{\'and} | 414 | \T{and} is a reserved word, but \T{And} and \T{\'and} |
400 | (if the locale permits) are two different, valid identifiers. | 415 | (if the locale permits) are two different, valid identifiers. |
@@ -404,34 +419,34 @@ are reserved for internal variables. | |||
404 | 419 | ||
405 | The following strings denote other \Index{tokens}: | 420 | The following strings denote other \Index{tokens}: |
406 | \begin{verbatim} | 421 | \begin{verbatim} |
407 | ~= <= >= < > == = + - * / % | 422 | ~= <= >= < > == = + - * / % |
408 | ( ) { } [ ] ; , . .. ... | 423 | ( ) { } [ ] ; , . .. ... |
409 | \end{verbatim} | 424 | \end{verbatim} |
410 | 425 | ||
411 | \IndexEmph{Literal strings} | 426 | \IndexEmph{Literal strings} |
412 | can be delimited by matching single or double quotes, | 427 | can be delimited by matching single or double quotes, |
413 | and can contain the C-like escape sequences | 428 | and can contain the C-like escape sequences |
414 | \verb|'\a'| (bell), | 429 | `\verb|\a|' (bell), |
415 | \verb|'\b'| (backspace), | 430 | `\verb|\b|' (backspace), |
416 | \verb|'\f'| (form feed), | 431 | `\verb|\f|' (form feed), |
417 | \verb|'\n'| (newline), | 432 | `\verb|\n|' (newline), |
418 | \verb|'\r'| (carriage return), | 433 | `\verb|\r|' (carriage return), |
419 | \verb|'\t'| (horizontal tab), | 434 | `\verb|\t|' (horizontal tab), |
420 | \verb|'\v'| (vertical tab), | 435 | `\verb|\v|' (vertical tab), |
421 | \verb|'\\'|, (backslash), | 436 | `\verb|\\|' (backslash), |
422 | \verb|'\"'|, (double quote), | 437 | `\verb|\"|' (double quote), |
423 | \verb|'\''| (single quote), | 438 | `\verb|\'|' (single quote), |
424 | and \verb|'\|\emph{newline}\verb|'| (that is, a backslash followed by a real newline, | 439 | and `\verb|\|\emph{newline}' (that is, a backslash followed by a real newline, |
425 | which results in a newline in the string). | 440 | which results in a newline in the string). |
426 | A character in a string may also be specified by its numerical value, | 441 | A character in a string may also be specified by its numerical value, |
427 | through the escape sequence \verb|'\ddd'|, | 442 | through the escape sequence `\verb|\|\emph{ddd}', |
428 | where \verb|ddd| is a sequence of up to three \emph{decimal} digits. | 443 | where \emph{ddd} is a sequence of up to three \emph{decimal} digits. |
429 | Strings in Lua may contain any 8-bit value, including embedded zeros, | 444 | Strings in Lua may contain any 8-bit value, including embedded zeros, |
430 | which can be specified as \verb|'\000'|. | 445 | which can be specified as `\verb|\000|'. |
431 | 446 | ||
432 | Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|. | 447 | Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|. |
433 | Literals in this bracketed form may run for several lines, | 448 | Literals in this bracketed form may run for several lines, |
434 | may contain nested \verb|[[ ... ]]| pairs, | 449 | may contain nested \verb|[[| \dots\ \verb|]]| pairs, |
435 | and do not interpret escape sequences. | 450 | and do not interpret escape sequences. |
436 | This form is specially convenient for | 451 | This form is specially convenient for |
437 | writing strings that contain program pieces or | 452 | writing strings that contain program pieces or |
@@ -439,25 +454,24 @@ other quoted strings. | |||
439 | As an example, in a system using ASCII, | 454 | As an example, in a system using ASCII, |
440 | the following three literals are equivalent: | 455 | the following three literals are equivalent: |
441 | \begin{verbatim} | 456 | \begin{verbatim} |
442 | 1) "alo\n123\"" | 457 | 1) "alo\n123\"" |
443 | 2) '\97lo\10\04923"' | 458 | 2) '\97lo\10\04923"' |
444 | 3) [[alo | 459 | 3) [[alo |
445 | 123"]] | 460 | 123"]] |
446 | \end{verbatim} | 461 | \end{verbatim} |
447 | 462 | ||
448 | 463 | \IndexEmph{Comments} start anywhere outside a string with a | |
449 | \Index{Comments} start anywhere outside a string with a | ||
450 | double hyphen (\verb|--|) and run until the end of the line. | 464 | double hyphen (\verb|--|) and run until the end of the line. |
451 | Moreover, | 465 | Moreover, |
452 | the first line of a chunk is skipped if it starts with \verb|#|. | 466 | the first line of a chunk is skipped if it starts with \verb|#|. |
453 | This facility allows the use of Lua as a script interpreter | 467 | This facility allows the use of Lua as a script interpreter |
454 | in Unix systems \see{lua-sa}. | 468 | in Unix systems \see{lua-sa}. |
455 | 469 | ||
456 | \Index{Numerical constants} may be written with an optional decimal part, | 470 | \IndexEmph{Numerical constants} may be written with an optional decimal part |
457 | and an optional decimal exponent. | 471 | and an optional decimal exponent. |
458 | Examples of valid numerical constants are | 472 | Examples of valid numerical constants are |
459 | \begin{verbatim} | 473 | \begin{verbatim} |
460 | 3 3.0 3.1416 314.16e-2 0.31416E1 | 474 | 3 3.0 3.1416 314.16e-2 0.31416E1 |
461 | \end{verbatim} | 475 | \end{verbatim} |
462 | 476 | ||
463 | \subsection{\Index{Coercion}} \label{coercion} | 477 | \subsection{\Index{Coercion}} \label{coercion} |
@@ -490,7 +504,7 @@ then the excess values are thrown away. | |||
490 | If there are less values than are needed, | 504 | If there are less values than are needed, |
491 | then the list is extended with as many \nil's as needed. | 505 | then the list is extended with as many \nil's as needed. |
492 | This adjustment occurs in multiple assignments \see{assignment} | 506 | This adjustment occurs in multiple assignments \see{assignment} |
493 | and function calls \see{functioncall}. | 507 | and in function calls \see{functioncall}. |
494 | 508 | ||
495 | 509 | ||
496 | \subsection{Statements}\label{stats} | 510 | \subsection{Statements}\label{stats} |
@@ -505,7 +519,7 @@ and local variable declarations \see{localvar}. | |||
505 | 519 | ||
506 | \subsubsection{Blocks} | 520 | \subsubsection{Blocks} |
507 | A \Index{block} is a list of statements; | 521 | A \Index{block} is a list of statements; |
508 | syntatically, this is equal to a chunk: | 522 | syntactically, a block is equal to a chunk: |
509 | \begin{Produc} | 523 | \begin{Produc} |
510 | \produc{block}{chunk} | 524 | \produc{block}{chunk} |
511 | \end{Produc}% | 525 | \end{Produc}% |
@@ -518,15 +532,15 @@ This is useful to control the scope of local variables \see{localvar}, | |||
518 | and to add a \rwd{return} or \rwd{break} statement in the middle | 532 | and to add a \rwd{return} or \rwd{break} statement in the middle |
519 | of another block; for instance, | 533 | of another block; for instance, |
520 | \begin{verbatim} | 534 | \begin{verbatim} |
521 | do return end -- return is the last statement in this block | 535 | do return end -- return is the last statement in this block |
522 | \end{verbatim} | 536 | \end{verbatim} |
523 | 537 | ||
524 | \subsubsection{\Index{Assignment}} \label{assignment} | 538 | \subsubsection{\Index{Assignment}} \label{assignment} |
525 | The language allows \Index{multiple assignment}. | 539 | Lua allows \Index{multiple assignment}. |
526 | Therefore, the syntax for assignment | 540 | Therefore, the syntax for assignment |
527 | defines a list of variables on the left side | 541 | defines a list of variables on the left side |
528 | and a list of expressions on the right side. | 542 | and a list of expressions on the right side. |
529 | Both lists have their elements separated by commas: | 543 | The elements in both lists are separated by commas: |
530 | \begin{Produc} | 544 | \begin{Produc} |
531 | \produc{stat}{varlist1 \ter{=} explist1} | 545 | \produc{stat}{varlist1 \ter{=} explist1} |
532 | \produc{varlist1}{var \rep{\ter{,} var}} | 546 | \produc{varlist1}{var \rep{\ter{,} var}} |
@@ -536,14 +550,16 @@ and eventual indices on the left side, | |||
536 | and then makes the assignments. | 550 | and then makes the assignments. |
537 | So | 551 | So |
538 | \begin{verbatim} | 552 | \begin{verbatim} |
539 | i = 3 | 553 | i = 3 |
540 | i, a[i] = 4, 20 | 554 | i, a[i] = 4, 20 |
541 | \end{verbatim} | 555 | \end{verbatim} |
542 | sets \verb|a[3]| to 20, but does not affect \verb|a[4]|. | 556 | sets \verb|a[3]| to 20, but does not affect \verb|a[4]| |
557 | because the \verb|i| in \verb|a[i]| is evaluated | ||
558 | before it is assigned \verb|4|. | ||
543 | 559 | ||
544 | Multiple assignment can be used to exchange two values, as in | 560 | Multiple assignment can be used to exchange two values, as in |
545 | \begin{verbatim} | 561 | \begin{verbatim} |
546 | x, y = y, x | 562 | x, y = y, x |
547 | \end{verbatim} | 563 | \end{verbatim} |
548 | 564 | ||
549 | The two lists in a multiple assignment may have different lengths. | 565 | The two lists in a multiple assignment may have different lengths. |
@@ -578,11 +594,11 @@ is equivalent to a call \verb|setglobal("x", val)|; | |||
578 | an assignment \verb|t[i] = val| is equivalent to | 594 | an assignment \verb|t[i] = val| is equivalent to |
579 | \verb|settable_event(t,i,val)|. | 595 | \verb|settable_event(t,i,val)|. |
580 | See \See{tag-method} for a complete description of these functions. | 596 | See \See{tag-method} for a complete description of these functions. |
581 | (The function \verb|setglobal| is pre-defined in Lua. | 597 | (The function \verb|setglobal| is defined in the basic library. |
582 | The function \T{settable\_event} is used only for explanatory purposes.) | 598 | The function \T{settable\_event} is used only for explanatory purposes.) |
583 | 599 | ||
584 | \subsubsection{Control Structures} | 600 | \subsubsection{Control Structures} |
585 | The control structures | 601 | The control structures |
586 | \index{while-do}\index{repeat-until}\index{if-then-else}% | 602 | \index{while-do}\index{repeat-until}\index{if-then-else}% |
587 | \T{if}, \T{while}, and \T{repeat} have the usual meaning and | 603 | \T{if}, \T{while}, and \T{repeat} have the usual meaning and |
588 | familiar syntax: | 604 | familiar syntax: |
@@ -632,20 +648,20 @@ The numerical \rwd{for} loop has the following syntax: | |||
632 | \end{Produc}% | 648 | \end{Produc}% |
633 | A \rwd{for} statement like | 649 | A \rwd{for} statement like |
634 | \begin{verbatim} | 650 | \begin{verbatim} |
635 | for var=e1,e2,e3 do block end | 651 | for var = e1 ,e2, e3 do block end |
636 | \end{verbatim} | 652 | \end{verbatim} |
637 | is equivalent to the following code: | 653 | is equivalent to the code: |
638 | \begin{verbatim} | 654 | \begin{verbatim} |
639 | do | 655 | do |
640 | local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) | 656 | local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) |
641 | if not (var and _limit and _step) then error() end | 657 | if not (var and _limit and _step) then error() end |
642 | while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do | 658 | while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do |
643 | block | 659 | block |
644 | var = var+_step | 660 | var = var+_step |
645 | end | 661 | end |
646 | end | 662 | end |
647 | \end{verbatim} | 663 | \end{verbatim} |
648 | Notice the following: | 664 | Note the following: |
649 | \begin{itemize}\itemsep=0pt | 665 | \begin{itemize}\itemsep=0pt |
650 | \item \verb|_limit| and \verb|_step| are invisible variables. | 666 | \item \verb|_limit| and \verb|_step| are invisible variables. |
651 | The names are here for explanatory purposes only. | 667 | The names are here for explanatory purposes only. |
@@ -662,7 +678,7 @@ assign it to another variable before breaking. | |||
662 | \end{itemize} | 678 | \end{itemize} |
663 | 679 | ||
664 | The table \rwd{for} statement traverses all pairs | 680 | The table \rwd{for} statement traverses all pairs |
665 | index--value of a given table. | 681 | (index,value) of a given table. |
666 | It has the following syntax: | 682 | It has the following syntax: |
667 | \begin{Produc} | 683 | \begin{Produc} |
668 | \produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp1 | 684 | \produc{stat}{\rwd{for} name \ter{,} name \rwd{in} exp1 |
@@ -670,34 +686,33 @@ It has the following syntax: | |||
670 | \end{Produc}% | 686 | \end{Produc}% |
671 | A \rwd{for} statement like | 687 | A \rwd{for} statement like |
672 | \begin{verbatim} | 688 | \begin{verbatim} |
673 | for index, value in exp do block end | 689 | for index, value in exp do block end |
674 | \end{verbatim} | 690 | \end{verbatim} |
675 | is equivalent to the following code: | 691 | is equivalent to the code: |
676 | \begin{verbatim} | 692 | \begin{verbatim} |
677 | do | 693 | do |
678 | local _t = exp | 694 | local _t = exp |
679 | local index, value = next(t, nil) | 695 | local index, value = next(t, nil) |
680 | while index do | 696 | while index do |
681 | block | 697 | block |
682 | index, value = next(t, index) | 698 | index, value = next(t, index) |
683 | end | 699 | end |
684 | end | 700 | end |
685 | \end{verbatim} | 701 | \end{verbatim} |
686 | Notice the following: | 702 | Note the following: |
687 | \begin{itemize}\itemsep=0pt | 703 | \begin{itemize}\itemsep=0pt |
688 | \item \verb|_t| is an invisible variable. | 704 | \item \verb|_t| is an invisible variable. |
689 | The name is here for explanatory purposes only. | 705 | The name is here for explanatory purposes only. |
690 | \item The behavior is undefined if you assign to \verb|index| inside | 706 | \item The behavior is \emph{undefined} if you assign to \verb|index| inside |
691 | the block. | 707 | the block. |
692 | \item The behavior is undefined if you create | 708 | \item The behavior is \emph{undefined} if you change |
693 | new indices in table \verb|_t| during the traversal. | 709 | the table \verb|_t| during the traversal. |
694 | However, it is safe to change the values associated with present indices. | ||
695 | \item The variables \verb|index| and \verb|value| are local to the statement; | 710 | \item The variables \verb|index| and \verb|value| are local to the statement; |
696 | you cannot use their values after the \rwd{for} ends. | 711 | you cannot use their values after the \rwd{for} ends. |
697 | \item You can use \rwd{break} to exit a \rwd{for}. | 712 | \item You can use \rwd{break} to exit a \rwd{for}. |
698 | If you need the value of \verb|index| or \verb|value|, | 713 | If you need the value of \verb|index| or \verb|value|, |
699 | assign them to other variables before breaking. | 714 | assign them to other variables before breaking. |
700 | \item The order that table elements are traversed is completely undefined, | 715 | \item The order that table elements are traversed is undefined, |
701 | \emph{even for numerical indices}. | 716 | \emph{even for numerical indices}. |
702 | If you want to traverse indices in numerical order, | 717 | If you want to traverse indices in numerical order, |
703 | use a numerical \rwd{for}. | 718 | use a numerical \rwd{for}. |
@@ -725,6 +740,9 @@ If present, an initial assignment has the same semantics | |||
725 | of a multiple assignment. | 740 | of a multiple assignment. |
726 | Otherwise, all variables are initialized with \nil. | 741 | Otherwise, all variables are initialized with \nil. |
727 | 742 | ||
743 | A chunk is also a block, | ||
744 | so local variables can be declared outside any explicit block. | ||
745 | |||
728 | The scope of local variables begins \emph{after} | 746 | The scope of local variables begins \emph{after} |
729 | the declaration and lasts until the end of the block. | 747 | the declaration and lasts until the end of the block. |
730 | Thus, the code | 748 | Thus, the code |
@@ -762,7 +780,7 @@ call \verb|getglobal("x")|; | |||
762 | an access to an indexed variable \verb|t[i]| is equivalent to | 780 | an access to an indexed variable \verb|t[i]| is equivalent to |
763 | a call \verb|gettable_event(t,i)|. | 781 | a call \verb|gettable_event(t,i)|. |
764 | See \See{tag-method} for a description of these functions. | 782 | See \See{tag-method} for a description of these functions. |
765 | (Function \verb|getglobal| is pre-defined in Lua. | 783 | (Function \verb|getglobal| is defined in the basic library. |
766 | Function \T{gettable\_event} is used only for explanatory purposes.) | 784 | Function \T{gettable\_event} is used only for explanatory purposes.) |
767 | 785 | ||
768 | The non-terminal \M{exp1} is used to indicate that the values | 786 | The non-terminal \M{exp1} is used to indicate that the values |
@@ -775,7 +793,7 @@ returned by an expression must be adjusted to one single value: | |||
775 | Lua supports the usual \Index{arithmetic operators}: | 793 | Lua supports the usual \Index{arithmetic operators}: |
776 | the binary \verb|+| (addition), | 794 | the binary \verb|+| (addition), |
777 | \verb|-| (subtraction), \verb|*| (multiplication), | 795 | \verb|-| (subtraction), \verb|*| (multiplication), |
778 | \verb|/| (division) and \verb|^| (exponentiation), | 796 | \verb|/| (division), and \verb|^| (exponentiation); |
779 | and unary \verb|-| (negation). | 797 | and unary \verb|-| (negation). |
780 | If the operands are numbers, or strings that can be converted to | 798 | If the operands are numbers, or strings that can be converted to |
781 | numbers (according to the rules given in \See{coercion}), | 799 | numbers (according to the rules given in \See{coercion}), |
@@ -787,13 +805,13 @@ giving the expected meaning to \Index{exponentiation} | |||
787 | \see{mathlib}. | 805 | \see{mathlib}. |
788 | 806 | ||
789 | \subsubsection{Relational Operators} | 807 | \subsubsection{Relational Operators} |
790 | Lua provides the following \Index{relational operators}: | 808 | The \Index{relational operators} in Lua are |
791 | \begin{verbatim} | 809 | \begin{verbatim} |
792 | == ~= < > <= >= | 810 | == ~= < > <= >= |
793 | \end{verbatim} | 811 | \end{verbatim} |
794 | All these return \nil\ as false and a value different from \nil\ as true. | 812 | These operators return \nil\ as false and a value different from \nil\ as true. |
795 | 813 | ||
796 | Equality first compares the tags of its operands. | 814 | Equality (\verb|==|) first compares the tags of its operands. |
797 | If they are different, then the result is \nil. | 815 | If they are different, then the result is \nil. |
798 | Otherwise, their values are compared. | 816 | Otherwise, their values are compared. |
799 | Numbers and strings are compared in the usual way. | 817 | Numbers and strings are compared in the usual way. |
@@ -807,6 +825,7 @@ The conversion rules of \See{coercion} | |||
807 | Thus, \verb|"0"==0| evaluates to \emph{false}, | 825 | Thus, \verb|"0"==0| evaluates to \emph{false}, |
808 | and \verb|t[0]| and \verb|t["0"]| denote different | 826 | and \verb|t[0]| and \verb|t["0"]| denote different |
809 | entries in a table. | 827 | entries in a table. |
828 | \medskip | ||
810 | 829 | ||
811 | The order operators work as follows. | 830 | The order operators work as follows. |
812 | If both arguments are numbers, then they are compared as such. | 831 | If both arguments are numbers, then they are compared as such. |
@@ -815,13 +834,14 @@ then their values are compared using lexicographical order. | |||
815 | Otherwise, the ``lt'' tag method is called \see{tag-method}. | 834 | Otherwise, the ``lt'' tag method is called \see{tag-method}. |
816 | 835 | ||
817 | \subsubsection{Logical Operators} | 836 | \subsubsection{Logical Operators} |
818 | The \Index{logical operators} are | 837 | The \Index{logical operators} in Lua are |
819 | \index{and}\index{or}\index{not} | 838 | \index{and}\index{or}\index{not} |
820 | \begin{verbatim} | 839 | \begin{verbatim} |
821 | and or not | 840 | and or not |
822 | \end{verbatim} | 841 | \end{verbatim} |
823 | Like control structures, all logical operators | 842 | Like the control structures, all logical operators |
824 | consider \nil\ as false and anything else as true. | 843 | consider \nil\ as false and anything else as true. |
844 | |||
825 | The conjunction operator \verb|and| returns \nil\ if its first argument is \nil; | 845 | The conjunction operator \verb|and| returns \nil\ if its first argument is \nil; |
826 | otherwise, it returns its second argument. | 846 | otherwise, it returns its second argument. |
827 | The disjunction operator \verb|or| returns its first argument | 847 | The disjunction operator \verb|or| returns its first argument |
@@ -831,40 +851,46 @@ Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, | |||
831 | that is, | 851 | that is, |
832 | the second operand is evaluated only when necessary. | 852 | the second operand is evaluated only when necessary. |
833 | 853 | ||
834 | There are two useful Lua idioms with logical operators. | 854 | There are two useful Lua idioms that use logical operators. |
835 | The first idiom is \verb|x = x or v|, | 855 | The first idiom is |
856 | \begin{verbatim} | ||
857 | x = x or v | ||
858 | \end{verbatim} | ||
836 | which is equivalent to | 859 | which is equivalent to |
837 | \begin{verbatim} | 860 | \begin{verbatim} |
838 | if x == nil then x = v end | 861 | if x == nil then x = v end |
839 | \end{verbatim} | 862 | \end{verbatim} |
840 | i.e., it sets \verb|x| to a default value \verb|v| when | 863 | This idiom sets \verb|x| to a default value \verb|v| when \verb|x| is not set. |
841 | \verb|x| is not set. | 864 | |
842 | The other idiom is \verb|x = a and b or c|, | 865 | The second idiom is |
843 | which should be read as \verb|x = a and (b or c)|, | 866 | \begin{verbatim} |
844 | is equivalent to | 867 | x = a and b or c |
868 | \end{verbatim} | ||
869 | which should be read as \verb|x = a and (b or c)|. | ||
870 | This idiom is equivalent to | ||
845 | \begin{verbatim} | 871 | \begin{verbatim} |
846 | if a then x = b else x = c end | 872 | if a then x = b else x = c end |
847 | \end{verbatim} | 873 | \end{verbatim} |
848 | provided that \verb|b| is not \nil. | 874 | provided that \verb|b| is not \nil. |
849 | 875 | ||
850 | \subsubsection{Concatenation} | 876 | \subsubsection{Concatenation} \label{concat} |
851 | The string \Index{concatenation} operator in Lua is | 877 | The string \Index{concatenation} operator in Lua is |
852 | denoted by ``\IndexVerb{..}''. | 878 | denoted by two dots (`\IndexVerb{..}'). |
853 | If both operands are strings or numbers, they are converted to | 879 | If both operands are strings or numbers, then they are converted to |
854 | strings according to the rules in \See{coercion}. | 880 | strings according to the rules in \See{coercion}. |
855 | Otherwise, the ``concat'' tag method is called \see{tag-method}. | 881 | Otherwise, the ``concat'' tag method is called \see{tag-method}. |
856 | 882 | ||
857 | \subsubsection{Precedence} | 883 | \subsubsection{Precedence} |
858 | \Index{Operator precedence} follows the table below, | 884 | \Index{Operator precedence} in Lua follows the table below, |
859 | from the lower to the higher priority: | 885 | from the lower to the higher priority: |
860 | \begin{verbatim} | 886 | \begin{verbatim} |
861 | and or | 887 | and or |
862 | < > <= >= ~= == | 888 | < > <= >= ~= == |
863 | .. | 889 | .. |
864 | + - | 890 | + - |
865 | * / | 891 | * / |
866 | not - (unary) | 892 | not - (unary) |
867 | ^ | 893 | ^ |
868 | \end{verbatim} | 894 | \end{verbatim} |
869 | All binary operators are left associative, | 895 | All binary operators are left associative, |
870 | except for \verb|^| (exponentiation), | 896 | except for \verb|^| (exponentiation), |
@@ -899,17 +925,17 @@ The expressions in the list are assigned to consecutive numerical indices, | |||
899 | starting with 1. | 925 | starting with 1. |
900 | For example, | 926 | For example, |
901 | \begin{verbatim} | 927 | \begin{verbatim} |
902 | a = {"v1", "v2", 34} | 928 | a = {"v1", "v2", 34} |
903 | \end{verbatim} | 929 | \end{verbatim} |
904 | is equivalent to | 930 | is equivalent to |
905 | \begin{verbatim} | 931 | \begin{verbatim} |
906 | do | 932 | do |
907 | local temp = {} | 933 | local temp = {} |
908 | temp[1] = "v1" | 934 | temp[1] = "v1" |
909 | temp[2] = "v2" | 935 | temp[2] = "v2" |
910 | temp[3] = 34 | 936 | temp[3] = 34 |
911 | a = temp | 937 | a = temp |
912 | end | 938 | end |
913 | \end{verbatim} | 939 | \end{verbatim} |
914 | 940 | ||
915 | The form \emph{ffieldlist1} initializes other fields in a table: | 941 | The form \emph{ffieldlist1} initializes other fields in a table: |
@@ -919,18 +945,18 @@ The form \emph{ffieldlist1} initializes other fields in a table: | |||
919 | \end{Produc}% | 945 | \end{Produc}% |
920 | For example, | 946 | For example, |
921 | \begin{verbatim} | 947 | \begin{verbatim} |
922 | a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c} | 948 | a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c} |
923 | \end{verbatim} | 949 | \end{verbatim} |
924 | is equivalent to | 950 | is equivalent to |
925 | \begin{verbatim} | 951 | \begin{verbatim} |
926 | do | 952 | do |
927 | local temp = {} | 953 | local temp = {} |
928 | temp[f(k)] = g(y) | 954 | temp[f(k)] = g(y) |
929 | temp.x = 1 -- or temp["x"] = 1 | 955 | temp.x = 1 -- or temp["x"] = 1 |
930 | temp.y = 3 -- or temp["y"] = 3 | 956 | temp.y = 3 -- or temp["y"] = 3 |
931 | temp[0] = b+c | 957 | temp[0] = b+c |
932 | a = temp | 958 | a = temp |
933 | end | 959 | end |
934 | \end{verbatim} | 960 | \end{verbatim} |
935 | An expression like \verb|{x = 1, y = 4}| is | 961 | An expression like \verb|{x = 1, y = 4}| is |
936 | in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. | 962 | in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. |
@@ -940,14 +966,14 @@ and can be used in the same constructor separated by | |||
940 | a semi-colon. | 966 | a semi-colon. |
941 | For example, all forms below are correct. | 967 | For example, all forms below are correct. |
942 | \begin{verbatim} | 968 | \begin{verbatim} |
943 | x = {;} | 969 | x = {;} |
944 | x = {"a", "b",} | 970 | x = {"a", "b",} |
945 | x = {type="list"; "a", "b"} | 971 | x = {type="list"; "a", "b"} |
946 | x = {f(0), f(1), f(2),; n=3,} | 972 | x = {f(0), f(1), f(2),; n=3,} |
947 | \end{verbatim} | 973 | \end{verbatim} |
948 | 974 | ||
949 | \subsubsection{Function Calls} \label{functioncall} | 975 | \subsubsection{Function Calls} \label{functioncall} |
950 | A \Index{function call} has the following syntax: | 976 | A \Index{function call} in Lua has the following syntax: |
951 | \begin{Produc} | 977 | \begin{Produc} |
952 | \produc{functioncall}{varorfunc args} | 978 | \produc{functioncall}{varorfunc args} |
953 | \end{Produc}% | 979 | \end{Produc}% |
@@ -964,12 +990,9 @@ The form | |||
964 | \produc{functioncall}{varorfunc \ter{:} name args} | 990 | \produc{functioncall}{varorfunc \ter{:} name args} |
965 | \end{Produc}% | 991 | \end{Produc}% |
966 | can be used to call ``methods''. | 992 | can be used to call ``methods''. |
967 | A call \verb|varorfunc:name(...)| | 993 | A call \verb|v:name(...)| |
968 | is syntactic sugar for | 994 | is syntactic sugar for \verb|v.name(v, ...)|, |
969 | \begin{verbatim} | 995 | except that \verb|v| is evaluated only once. |
970 | varorfunc.name(varorfunc, ...) | ||
971 | \end{verbatim} | ||
972 | except that \verb|varorfunc| is evaluated only once. | ||
973 | 996 | ||
974 | Arguments have the following syntax: | 997 | Arguments have the following syntax: |
975 | \begin{Produc} | 998 | \begin{Produc} |
@@ -1003,16 +1026,16 @@ then no adjustment is made. | |||
1003 | The only places that can hold many values | 1026 | The only places that can hold many values |
1004 | is the last (or the only) expression in an assignment, | 1027 | is the last (or the only) expression in an assignment, |
1005 | in an argument list, or in a return statement. | 1028 | in an argument list, or in a return statement. |
1006 | Here are some examples. | 1029 | Here are some examples: |
1007 | \begin{verbatim} | 1030 | \begin{verbatim} |
1008 | f(); -- adjusted to 0 results | 1031 | f(); -- adjusted to 0 results |
1009 | g(f(), x); -- f() is adjusted to 1 result | 1032 | g(f(), x); -- f() is adjusted to 1 result |
1010 | g(x, f()); -- g gets x plus all values returned by f() | 1033 | g(x, f()); -- g gets x plus all values returned by f() |
1011 | a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) | 1034 | a,b,c = f(), x; -- f() is adjusted to 1 result (and c gets nil) |
1012 | a,b,c = x, f(); -- f() is adjusted to 2 | 1035 | a,b,c = x, f(); -- f() is adjusted to 2 |
1013 | a,b,c = f(); -- f() is adjusted to 3 | 1036 | a,b,c = f(); -- f() is adjusted to 3 |
1014 | return f(); -- returns all values returned by f() | 1037 | return f(); -- returns all values returned by f() |
1015 | return x,y,f(); -- returns a, b, and all values returned by f() | 1038 | return x,y,f(); -- returns a, b, and all values returned by f() |
1016 | \end{verbatim} | 1039 | \end{verbatim} |
1017 | 1040 | ||
1018 | \subsubsection{\Index{Function Definitions}} \label{func-def} | 1041 | \subsubsection{\Index{Function Definitions}} \label{func-def} |
@@ -1027,33 +1050,25 @@ The syntax for function definition is | |||
1027 | \end{Produc}% | 1050 | \end{Produc}% |
1028 | The statement | 1051 | The statement |
1029 | \begin{verbatim} | 1052 | \begin{verbatim} |
1030 | function f () | 1053 | function f () ... end |
1031 | ... | ||
1032 | end | ||
1033 | \end{verbatim} | 1054 | \end{verbatim} |
1034 | is just syntactic sugar for | 1055 | is just syntactic sugar for |
1035 | \begin{verbatim} | 1056 | \begin{verbatim} |
1036 | f = function () | 1057 | f = function () ... end |
1037 | ... | ||
1038 | end | ||
1039 | \end{verbatim} | 1058 | \end{verbatim} |
1040 | and the statement | 1059 | and the statement |
1041 | \begin{verbatim} | 1060 | \begin{verbatim} |
1042 | function o.f () | 1061 | function v.f () ... end |
1043 | ... | ||
1044 | end | ||
1045 | \end{verbatim} | 1062 | \end{verbatim} |
1046 | is syntactic sugar for | 1063 | is syntactic sugar for |
1047 | \begin{verbatim} | 1064 | \begin{verbatim} |
1048 | o.f = function () | 1065 | v.f = function () ... end |
1049 | ... | ||
1050 | end | ||
1051 | \end{verbatim} | 1066 | \end{verbatim} |
1052 | 1067 | ||
1053 | A function definition is an executable expression, | 1068 | A function definition is an executable expression, |
1054 | whose value has type \emph{function}. | 1069 | whose value has type \emph{function}. |
1055 | When Lua pre-compiles a chunk, | 1070 | When Lua pre-compiles a chunk, |
1056 | all its function bodies are pre-compiled, too. | 1071 | all its function bodies are pre-compiled too. |
1057 | Then, whenever Lua executes the function definition, | 1072 | Then, whenever Lua executes the function definition, |
1058 | its upvalues are fixed \see{upvalue}, | 1073 | its upvalues are fixed \see{upvalue}, |
1059 | and the function is \emph{instantiated} (or \emph{closed}). | 1074 | and the function is \emph{instantiated} (or \emph{closed}). |
@@ -1074,7 +1089,7 @@ the list of \Index{arguments} is adjusted to | |||
1074 | the length of the list of parameters \see{adjust}, | 1089 | the length of the list of parameters \see{adjust}, |
1075 | unless the function is a \Def{vararg} function, | 1090 | unless the function is a \Def{vararg} function, |
1076 | which is | 1091 | which is |
1077 | indicated by the dots (\ldots) at the end of its parameter list. | 1092 | indicated by three dots (`\verb|...|') at the end of its parameter list. |
1078 | A vararg function does not adjust its argument list; | 1093 | A vararg function does not adjust its argument list; |
1079 | instead, it collects all extra arguments into an implicit parameter, | 1094 | instead, it collects all extra arguments into an implicit parameter, |
1080 | called \IndexVerb{arg}. | 1095 | called \IndexVerb{arg}. |
@@ -1084,24 +1099,24 @@ and the extra arguments at positions 1,~2,~\ldots,\M{n}. | |||
1084 | 1099 | ||
1085 | As an example, consider the following definitions: | 1100 | As an example, consider the following definitions: |
1086 | \begin{verbatim} | 1101 | \begin{verbatim} |
1087 | function f(a, b) end | 1102 | function f(a, b) end |
1088 | function g(a, b, ...) end | 1103 | function g(a, b, ...) end |
1089 | function r() return 1,2,3 end | 1104 | function r() return 1,2,3 end |
1090 | \end{verbatim} | 1105 | \end{verbatim} |
1091 | Then, we have the following mapping from arguments to parameters: | 1106 | Then, we have the following mapping from arguments to parameters: |
1092 | \begin{verbatim} | 1107 | \begin{verbatim} |
1093 | CALL PARAMETERS | 1108 | CALL PARAMETERS |
1094 | 1109 | ||
1095 | f(3) a=3, b=nil | 1110 | f(3) a=3, b=nil |
1096 | f(3, 4) a=3, b=4 | 1111 | f(3, 4) a=3, b=4 |
1097 | f(3, 4, 5) a=3, b=4 | 1112 | f(3, 4, 5) a=3, b=4 |
1098 | f(r(), 10) a=1, b=10 | 1113 | f(r(), 10) a=1, b=10 |
1099 | f(r()) a=1, b=2 | 1114 | f(r()) a=1, b=2 |
1100 | 1115 | ||
1101 | g(3) a=3, b=nil, arg={n=0} | 1116 | g(3) a=3, b=nil, arg={n=0} |
1102 | g(3, 4) a=3, b=4, arg={n=0} | 1117 | g(3, 4) a=3, b=4, arg={n=0} |
1103 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} | 1118 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} |
1104 | g(5, r()) a=5, b=1, arg={2, 3; n=2} | 1119 | g(5, r()) a=5, b=1, arg={2, 3; n=2} |
1105 | \end{verbatim} | 1120 | \end{verbatim} |
1106 | 1121 | ||
1107 | Results are returned using the \rwd{return} statement \see{return}. | 1122 | Results are returned using the \rwd{return} statement \see{return}. |
@@ -1113,22 +1128,18 @@ The syntax | |||
1113 | \begin{Produc} | 1128 | \begin{Produc} |
1114 | \produc{funcname}{name \ter{:} name} | 1129 | \produc{funcname}{name \ter{:} name} |
1115 | \end{Produc}% | 1130 | \end{Produc}% |
1116 | is used for defining \Index{methods}, | 1131 | is used for defining \IndexEmph{methods}, |
1117 | that is, functions that have an implicit extra parameter \IndexVerb{self}: | 1132 | that is, functions that have an implicit extra parameter \IndexVerb{self}: |
1118 | Thus, the statement | 1133 | Thus, the statement |
1119 | \begin{verbatim} | 1134 | \begin{verbatim} |
1120 | function v:f (...) | 1135 | function v:f (...) ... end |
1121 | ... | ||
1122 | end | ||
1123 | \end{verbatim} | 1136 | \end{verbatim} |
1124 | is equivalent to | 1137 | is equivalent to |
1125 | \begin{verbatim} | 1138 | \begin{verbatim} |
1126 | v.f = function (self, ...) | 1139 | v.f = function (self, ...) ... end |
1127 | ... | ||
1128 | end | ||
1129 | \end{verbatim} | 1140 | \end{verbatim} |
1130 | that is, the function gets an extra formal parameter called \verb|self|. | 1141 | Note that the function gets an extra formal parameter called \verb|self|. |
1131 | Note that the variable \verb|v| must have been | 1142 | Note also that \verb|v| must have been |
1132 | previously initialized with a table value. | 1143 | previously initialized with a table value. |
1133 | 1144 | ||
1134 | 1145 | ||
@@ -1153,32 +1164,34 @@ but whose value is \emph{frozen} when the function wherein it | |||
1153 | appears is instantiated. | 1164 | appears is instantiated. |
1154 | The name used in an upvalue may be the name of any variable visible | 1165 | The name used in an upvalue may be the name of any variable visible |
1155 | at the point where the function is defined, | 1166 | at the point where the function is defined, |
1156 | that is | 1167 | that is, |
1157 | global variables and local variables from the immediately enclosing function. | 1168 | global variables and local variables from the immediately enclosing function. |
1158 | Notice that when the upvalue is a table, | 1169 | Note that when the upvalue is a table, |
1159 | only the reference to that table | 1170 | only the \emph{reference} to that table |
1160 | (which is the value of the upvalue) is frozen; | 1171 | (which is the value of the upvalue) is frozen; |
1161 | the table contents can be changed at will. | 1172 | the table contents can be changed at will. |
1173 | Using table values as upvalues is a technique for having | ||
1174 | writable but private state attached to functions. | ||
1162 | 1175 | ||
1163 | Here are some examples: | 1176 | Here are some examples: |
1164 | \begin{verbatim} | 1177 | \begin{verbatim} |
1165 | a,b,c = 1,2,3 -- global variables | 1178 | a,b,c = 1,2,3 -- global variables |
1166 | local d | 1179 | local d |
1167 | function f (x) | 1180 | function f (x) |
1168 | local b = {} -- x and b are local to f; b shadows the global b | 1181 | local b = {} -- x and b are local to f; b shadows the global b |
1169 | local g = function (a) | 1182 | local g = function (a) |
1170 | local y -- a and y are local to g | 1183 | local y -- a and y are local to g |
1171 | p = a -- OK, access local 'a' | 1184 | p = a -- OK, access local `a' |
1172 | p = c -- OK, access global 'c' | 1185 | p = c -- OK, access global `c' |
1173 | p = b -- ERROR: cannot access a variable in outer scope | 1186 | p = b -- ERROR: cannot access a variable in outer scope |
1174 | p = %b -- OK, access frozen value of 'b' (local to 'f') | 1187 | p = %b -- OK, access frozen value of `b' (local to `f') |
1175 | %b = 3 -- ERROR: cannot change an upvalue | 1188 | %b = 3 -- ERROR: cannot change an upvalue |
1176 | %b.x = 3 -- OK, change the table contents | 1189 | %b.x = 3 -- OK, change the table contents |
1177 | p = %c -- OK, access frozen value of global 'c' | 1190 | p = %c -- OK, access frozen value of global `c' |
1178 | p = %y -- ERROR: 'y' is not visible where 'g' is defined | 1191 | p = %y -- ERROR: `y' is not visible where `g' is defined |
1179 | p = %d -- ERROR: 'd' is not visible where 'g' is defined | 1192 | p = %d -- ERROR: `d' is not visible where `g' is defined |
1180 | end -- g | 1193 | end -- g |
1181 | end -- f | 1194 | end -- f |
1182 | \end{verbatim} | 1195 | \end{verbatim} |
1183 | 1196 | ||
1184 | 1197 | ||
@@ -1195,27 +1208,28 @@ and then the corresponding function from the library | |||
1195 | \verb|lua_dobuffer|, or \verb|lua_callfunction|) | 1208 | \verb|lua_dobuffer|, or \verb|lua_callfunction|) |
1196 | is terminated, returning an error condition. | 1209 | is terminated, returning an error condition. |
1197 | 1210 | ||
1198 | Memory allocation error is an exception to the previous rule. | 1211 | Memory allocation errors are an exception to the previous rule. |
1199 | When a \verb|malloc| fails, Lua may not be able to execute the | 1212 | When memory allocation fails, Lua may not be able to execute the |
1200 | \verb|_ERRORMESSAGE| function. | 1213 | \verb|_ERRORMESSAGE| function. |
1201 | So, for this kind of error, Lua does not call | 1214 | So, for this kind of error, Lua does not call |
1202 | the \verb|_ERRORMESSAGE| function; | 1215 | the \verb|_ERRORMESSAGE| function; |
1203 | instead, the corresponding function from the library | 1216 | instead, the corresponding function from the library |
1204 | returns immeditely with a special error code. | 1217 | returns immediately with a special error code (\verb|LUA_ERRMEM|). |
1218 | This and other error codes are defined in \verb|lua.h|. | ||
1205 | 1219 | ||
1206 | The only argument to \verb|_ERRORMESSAGE| is a string | 1220 | The only argument to \verb|_ERRORMESSAGE| is a string |
1207 | describing the error. | 1221 | describing the error. |
1208 | The default definition for | 1222 | The default definition for |
1209 | this function calls \verb|_ALERT|, \Deffunc{_ALERT} | 1223 | this function calls \verb|_ALERT|, \Deffunc{_ALERT} |
1210 | which prints the message to \verb|stderr| \see{alert}. | 1224 | which prints the message to \verb|stderr| \see{alert}. |
1211 | The standard I/O library redefines \verb|_ERRORMESSAGE|, | 1225 | The standard I/O library redefines \verb|_ERRORMESSAGE| |
1212 | and uses the debug facilities \see{debugI} | 1226 | and uses the debug facilities \see{debugI} |
1213 | to print some extra information, | 1227 | to print some extra information, |
1214 | such as a call stack traceback. | 1228 | such as a call stack traceback. |
1215 | 1229 | ||
1216 | Lua code can explicitly generate an error by calling the built-in | 1230 | Lua code can explicitly generate an error by calling the |
1217 | function \verb|error| \see{pdf-error}. | 1231 | function \verb|error| \see{pdf-error}. |
1218 | Lua code can ``catch'' an error using the built-in function | 1232 | Lua code can ``catch'' an error using the function |
1219 | \verb|call| \see{pdf-call}. | 1233 | \verb|call| \see{pdf-call}. |
1220 | 1234 | ||
1221 | 1235 | ||
@@ -1238,7 +1252,7 @@ Its first parameter is the tag, the second parameter is the event name | |||
1238 | and the third parameter is the new method (a function), | 1252 | and the third parameter is the new method (a function), |
1239 | or \nil\ to restore the default behavior for the pair. | 1253 | or \nil\ to restore the default behavior for the pair. |
1240 | The \verb|settagmethod| function returns the previous tag method for that pair. | 1254 | The \verb|settagmethod| function returns the previous tag method for that pair. |
1241 | Another function, \IndexVerb{gettagmethod}, | 1255 | A companion function \IndexVerb{gettagmethod} |
1242 | receives a tag and an event name and returns the | 1256 | receives a tag and an event name and returns the |
1243 | current method associated with the pair. | 1257 | current method associated with the pair. |
1244 | 1258 | ||
@@ -1260,41 +1274,38 @@ are described in \See{predefined}. | |||
1260 | \item[``add'':]\index{add event} | 1274 | \item[``add'':]\index{add event} |
1261 | called when a \verb|+| operation is applied to non-numerical operands. | 1275 | called when a \verb|+| operation is applied to non-numerical operands. |
1262 | 1276 | ||
1263 | The function \verb|getbinmethod| defines how Lua chooses a tag method | 1277 | The function \verb|getbinmethod| below defines how Lua chooses a tag method |
1264 | for a binary operation. | 1278 | for a binary operation. |
1265 | First, Lua tries the first operand. | 1279 | First, Lua tries the first operand. |
1266 | If its tag does not define a tag method for the operation, | 1280 | If its tag does not define a tag method for the operation, |
1267 | then Lua tries the second operand. | 1281 | then Lua tries the second operand. |
1268 | If it also fails, then it gets a tag method from tag~0: | 1282 | If it also fails, then it gets a tag method from tag~0. |
1269 | \begin{verbatim} | 1283 | \begin{verbatim} |
1270 | function getbinmethod (op1, op2, event) | 1284 | function getbinmethod (op1, op2, event) |
1271 | return gettagmethod(tag(op1), event) or | 1285 | return gettagmethod(tag(op1), event) or |
1272 | gettagmethod(tag(op2), event) or | 1286 | gettagmethod(tag(op2), event) or |
1273 | gettagmethod(0, event) | 1287 | gettagmethod(0, event) |
1274 | end | 1288 | end |
1275 | \end{verbatim} | 1289 | \end{verbatim} |
1276 | Using this function, | 1290 | Using this function, |
1277 | the tag method for the ``add' event is | 1291 | the tag method for the ``add'' event is |
1278 | \begin{verbatim} | 1292 | \begin{verbatim} |
1279 | function add_event (op1, op2) | 1293 | function add_event (op1, op2) |
1280 | local o1, o2 = tonumber(op1), tonumber(op2) | 1294 | local o1, o2 = tonumber(op1), tonumber(op2) |
1281 | if o1 and o2 then -- both operands are numeric | 1295 | if o1 and o2 then -- both operands are numeric |
1282 | return o1+o2 -- '+' here is the primitive 'add' | 1296 | return o1+o2 -- '+' here is the primitive 'add' |
1283 | else -- at least one of the operands is not numeric | 1297 | else -- at least one of the operands is not numeric |
1284 | local tm = getbinmethod(op1, op2, "add") | 1298 | local tm = getbinmethod(op1, op2, "add") |
1285 | if tm then | 1299 | if tm then |
1286 | -- call the method with both operands and an extra | 1300 | -- call the method with both operands and an extra |
1287 | -- argument with the event name | 1301 | -- argument with the event name |
1288 | return tm(op1, op2, "add") | 1302 | return tm(op1, op2, "add") |
1289 | else -- no tag method available: default behavior | 1303 | else -- no tag method available: default behavior |
1290 | error("unexpected type at arithmetic operation") | 1304 | error("unexpected type at arithmetic operation") |
1291 | end | 1305 | end |
1292 | end | 1306 | end |
1293 | end | 1307 | end |
1294 | \end{verbatim} | 1308 | \end{verbatim} |
1295 | |||
1296 | All global variables are kept in a table. | ||
1297 | You can get this table calling the \verb|globals| function. | ||
1298 | 1309 | ||
1299 | \item[``sub'':]\index{sub event} | 1310 | \item[``sub'':]\index{sub event} |
1300 | called when a \verb|-| operation is applied to non-numerical operands. | 1311 | called when a \verb|-| operation is applied to non-numerical operands. |
@@ -1309,41 +1320,42 @@ called when a \verb|/| operation is applied to non-numerical operands. | |||
1309 | Behavior similar to the ``add'' event. | 1320 | Behavior similar to the ``add'' event. |
1310 | 1321 | ||
1311 | \item[``pow'':]\index{pow event} | 1322 | \item[``pow'':]\index{pow event} |
1312 | called when a \verb|^| operation (exponentiation) is applied. | 1323 | called when a \verb|^| operation (exponentiation) is applied, |
1324 | even for numerical operands. | ||
1313 | \begin{verbatim} | 1325 | \begin{verbatim} |
1314 | function pow_event (op1, op2) | 1326 | function pow_event (op1, op2) |
1315 | local tm = getbinmethod(op1, op2, "pow") | 1327 | local tm = getbinmethod(op1, op2, "pow") |
1316 | if tm then | 1328 | if tm then |
1317 | -- call the method with both operands and an extra | 1329 | -- call the method with both operands and an extra |
1318 | -- argument with the event name | 1330 | -- argument with the event name |
1319 | return tm(op1, op2, "pow") | 1331 | return tm(op1, op2, "pow") |
1320 | else -- no tag method available: default behavior | 1332 | else -- no tag method available: default behavior |
1321 | error("unexpected type at arithmetic operation") | 1333 | error("unexpected type at arithmetic operation") |
1322 | end | 1334 | end |
1323 | end | 1335 | end |
1324 | \end{verbatim} | 1336 | \end{verbatim} |
1325 | 1337 | ||
1326 | \item[``unm'':]\index{unm event} | 1338 | \item[``unm'':]\index{unm event} |
1327 | called when a unary \verb|-| operation is applied to a non-numerical operand. | 1339 | called when a unary \verb|-| operation is applied to a non-numerical operand. |
1328 | \begin{verbatim} | 1340 | \begin{verbatim} |
1329 | function unm_event (op) | 1341 | function unm_event (op) |
1330 | local o = tonumber(op) | 1342 | local o = tonumber(op) |
1331 | if o then -- operand is numeric | 1343 | if o then -- operand is numeric |
1332 | return -o -- '-' here is the primitive 'unm' | 1344 | return -o -- '-' here is the primitive 'unm' |
1333 | else -- the operand is not numeric. | 1345 | else -- the operand is not numeric. |
1334 | -- Try to get a tag method from the operand; | 1346 | -- Try to get a tag method from the operand; |
1335 | -- if it does not have one, try a "global" one (tag 0) | 1347 | -- if it does not have one, try a "global" one (tag 0) |
1336 | local tm = gettagmethod(tag(op), "unm") or | 1348 | local tm = gettagmethod(tag(op), "unm") or |
1337 | gettagmethod(0, "unm") | 1349 | gettagmethod(0, "unm") |
1338 | if tm then | 1350 | if tm then |
1339 | -- call the method with the operand, nil, and an extra | 1351 | -- call the method with the operand, nil, and an extra |
1340 | -- argument with the event name | 1352 | -- argument with the event name |
1341 | return tm(op, nil, "unm") | 1353 | return tm(op, nil, "unm") |
1342 | else -- no tag method available: default behavior | 1354 | else -- no tag method available: default behavior |
1343 | error("unexpected type at arithmetic operation") | 1355 | error("unexpected type at arithmetic operation") |
1344 | end | 1356 | end |
1345 | end | 1357 | end |
1346 | end | 1358 | end |
1347 | \end{verbatim} | 1359 | \end{verbatim} |
1348 | 1360 | ||
1349 | \item[``lt'':]\index{lt event} | 1361 | \item[``lt'':]\index{lt event} |
@@ -1351,51 +1363,51 @@ called when an order operation is applied to non-numerical | |||
1351 | or non-string operands. | 1363 | or non-string operands. |
1352 | It corresponds to the \verb|<| operator. | 1364 | It corresponds to the \verb|<| operator. |
1353 | \begin{verbatim} | 1365 | \begin{verbatim} |
1354 | function lt_event (op1, op2) | 1366 | function lt_event (op1, op2) |
1355 | if type(op1) == "number" and type(op2) == "number" then | 1367 | if type(op1) == "number" and type(op2) == "number" then |
1356 | return op1 < op2 -- numeric comparison | 1368 | return op1 < op2 -- numeric comparison |
1357 | elseif type(op1) == "string" and type(op2) == "string" then | 1369 | elseif type(op1) == "string" and type(op2) == "string" then |
1358 | return op1 < op2 -- lexicographic comparison | 1370 | return op1 < op2 -- lexicographic comparison |
1359 | else | 1371 | else |
1360 | local tm = getbinmethod(op1, op2, "lt") | 1372 | local tm = getbinmethod(op1, op2, "lt") |
1361 | if tm then | 1373 | if tm then |
1362 | return tm(op1, op2, "lt") | 1374 | return tm(op1, op2, "lt") |
1363 | else | 1375 | else |
1364 | error("unexpected type at comparison"); | 1376 | error("unexpected type at comparison"); |
1365 | end | 1377 | end |
1366 | end | 1378 | end |
1367 | end | 1379 | end |
1368 | \end{verbatim} | 1380 | \end{verbatim} |
1369 | The other order operators use this tag method according to the | 1381 | The other order operators use this tag method according to the |
1370 | usual equivalences: | 1382 | usual equivalences: |
1371 | \begin{verbatim} | 1383 | \begin{verbatim} |
1372 | a>b <=> b<a | 1384 | a>b <=> b<a |
1373 | a<=b <=> not (b<a) | 1385 | a<=b <=> not (b<a) |
1374 | a>=b <=> not (a<b) | 1386 | a>=b <=> not (a<b) |
1375 | \end{verbatim} | 1387 | \end{verbatim} |
1376 | 1388 | ||
1377 | \item[``concat'':]\index{concatenation event} | 1389 | \item[``concat'':]\index{concatenation event} |
1378 | called when a concatenation is applied to non-string operands. | 1390 | called when a concatenation is applied to non-string operands. |
1379 | \begin{verbatim} | 1391 | \begin{verbatim} |
1380 | function concat_event (op1, op2) | 1392 | function concat_event (op1, op2) |
1381 | if (type(op1) == "string" or type(op1) == "number") and | 1393 | if (type(op1) == "string" or type(op1) == "number") and |
1382 | (type(op2) == "string" or type(op2) == "number") then | 1394 | (type(op2) == "string" or type(op2) == "number") then |
1383 | return op1..op2 -- primitive string concatenation | 1395 | return op1..op2 -- primitive string concatenation |
1384 | else | 1396 | else |
1385 | local tm = getbinmethod(op1, op2, "concat") | 1397 | local tm = getbinmethod(op1, op2, "concat") |
1386 | if tm then | 1398 | if tm then |
1387 | return tm(op1, op2, "concat") | 1399 | return tm(op1, op2, "concat") |
1388 | else | 1400 | else |
1389 | error("unexpected type for concatenation") | 1401 | error("unexpected type for concatenation") |
1390 | end | 1402 | end |
1391 | end | 1403 | end |
1392 | end | 1404 | end |
1393 | \end{verbatim} | 1405 | \end{verbatim} |
1394 | 1406 | ||
1395 | \item[``index'':]\index{index event} | 1407 | \item[``index'':]\index{index event} |
1396 | called when Lua tries to retrieve the value of an index | 1408 | called when Lua tries to retrieve the value of an index |
1397 | not present in a table. | 1409 | not present in a table. |
1398 | See event ``gettable'' for its semantics. | 1410 | See the ``gettable'' event for its semantics. |
1399 | 1411 | ||
1400 | \item[``getglobal'':]\index{getglobal event} | 1412 | \item[``getglobal'':]\index{getglobal event} |
1401 | called whenever Lua needs the value of a global variable. | 1413 | called whenever Lua needs the value of a global variable. |
@@ -1404,112 +1416,113 @@ created by \verb|newtag|. | |||
1404 | Note that | 1416 | Note that |
1405 | the tag is that of the \emph{current value} of the global variable. | 1417 | the tag is that of the \emph{current value} of the global variable. |
1406 | \begin{verbatim} | 1418 | \begin{verbatim} |
1407 | function getglobal (varname) | 1419 | function getglobal (varname) |
1408 | -- access the table of globals | 1420 | -- access the table of globals |
1409 | local value = rawget(globals(), varname) | 1421 | local value = rawget(globals(), varname) |
1410 | local tm = gettagmethod(tag(value), "getglobal") | 1422 | local tm = gettagmethod(tag(value), "getglobal") |
1411 | if not tm then | 1423 | if not tm then |
1412 | return value | 1424 | return value |
1413 | else | 1425 | else |
1414 | return tm(varname, value) | 1426 | return tm(varname, value) |
1415 | end | 1427 | end |
1416 | end | 1428 | end |
1417 | \end{verbatim} | 1429 | \end{verbatim} |
1418 | The function \verb|getglobal| is pre-defined in Lua \see{predefined}. | 1430 | The function \verb|getglobal| is defined in the basic library~\see{predefined}. |
1419 | 1431 | ||
1420 | \item[``setglobal'':]\index{setglobal event} | 1432 | \item[``setglobal'':]\index{setglobal event} |
1421 | called whenever Lua assigns to a global variable. | 1433 | called whenever Lua assigns to a global variable. |
1422 | This method cannot be set for numbers, strings, and tables and | 1434 | This method cannot be set for numbers, strings, and tables and |
1423 | userdata with default tags. | 1435 | userdata with the default tag. |
1424 | \begin{verbatim} | 1436 | \begin{verbatim} |
1425 | function setglobal (varname, newvalue) | 1437 | function setglobal (varname, newvalue) |
1426 | local oldvalue = rawget(globals(), varname) | 1438 | local oldvalue = rawget(globals(), varname) |
1427 | local tm = gettagmethod(tag(oldvalue), "setglobal") | 1439 | local tm = gettagmethod(tag(oldvalue), "setglobal") |
1428 | if not tm then | 1440 | if not tm then |
1429 | rawset(globals(), varname, newvalue) | 1441 | rawset(globals(), varname, newvalue) |
1430 | else | 1442 | else |
1431 | tm(varname, oldvalue, newvalue) | 1443 | tm(varname, oldvalue, newvalue) |
1432 | end | 1444 | end |
1433 | end | 1445 | end |
1434 | \end{verbatim} | 1446 | \end{verbatim} |
1435 | The function \verb|setglobal| is pre-defined in Lua \see{predefined}. | 1447 | The function \verb|setglobal| is defined in the basic library~\see{predefined}. |
1436 | 1448 | ||
1437 | \item[``gettable'':]\index{gettable event} | 1449 | \item[``gettable'':]\index{gettable event} |
1438 | called whenever Lua accesses an indexed variable. | 1450 | called whenever Lua accesses an indexed variable. |
1439 | This method cannot be set for tables with default tag. | 1451 | This method cannot be set for tables with the default tag. |
1440 | \begin{verbatim} | 1452 | \begin{verbatim} |
1441 | function gettable_event (table, index) | 1453 | function gettable_event (table, index) |
1442 | local tm = gettagmethod(tag(table), "gettable") | 1454 | local tm = gettagmethod(tag(table), "gettable") |
1443 | if tm then | 1455 | if tm then |
1444 | return tm(table, index) | 1456 | return tm(table, index) |
1445 | elseif type(table) ~= "table" then | 1457 | elseif type(table) ~= "table" then |
1446 | error("indexed expression not a table"); | 1458 | error("indexed expression not a table"); |
1447 | else | 1459 | else |
1448 | local v = rawget(table, index) | 1460 | local v = rawget(table, index) |
1449 | tm = gettagmethod(tag(table), "index") | 1461 | tm = gettagmethod(tag(table), "index") |
1450 | if v == nil and tm then | 1462 | if v == nil and tm then |
1451 | return tm(table, index) | 1463 | return tm(table, index) |
1452 | else | 1464 | else |
1453 | return v | 1465 | return v |
1454 | end | 1466 | end |
1455 | end | 1467 | end |
1456 | end | 1468 | end |
1457 | \end{verbatim} | 1469 | \end{verbatim} |
1458 | 1470 | ||
1459 | \item[``settable'':]\index{settable event} | 1471 | \item[``settable'':]\index{settable event} |
1460 | called when Lua assigns to an indexed variable. | 1472 | called when Lua assigns to an indexed variable. |
1461 | This method cannot be set for tables with default tag. | 1473 | This method cannot be set for tables with the default tag. |
1462 | \begin{verbatim} | 1474 | \begin{verbatim} |
1463 | function settable_event (table, index, value) | 1475 | function settable_event (table, index, value) |
1464 | local tm = gettagmethod(tag(table), "settable") | 1476 | local tm = gettagmethod(tag(table), "settable") |
1465 | if tm then | 1477 | if tm then |
1466 | tm(table, index, value) | 1478 | tm(table, index, value) |
1467 | elseif type(table) ~= "table" then | 1479 | elseif type(table) ~= "table" then |
1468 | error("indexed expression not a table") | 1480 | error("indexed expression not a table") |
1469 | else | 1481 | else |
1470 | rawset(table, index, value) | 1482 | rawset(table, index, value) |
1471 | end | 1483 | end |
1472 | end | 1484 | end |
1473 | \end{verbatim} | 1485 | \end{verbatim} |
1474 | 1486 | ||
1475 | \item[``function'':]\index{function event} | 1487 | \item[``function'':]\index{function event} |
1476 | called when Lua tries to call a non-function value. | 1488 | called when Lua tries to call a non-function value. |
1477 | \begin{verbatim} | 1489 | \begin{verbatim} |
1478 | function function_event (func, ...) | 1490 | function function_event (func, ...) |
1479 | if type(func) == "function" then | 1491 | if type(func) == "function" then |
1480 | return call(func, arg) | 1492 | return call(func, arg) |
1481 | else | 1493 | else |
1482 | local tm = gettagmethod(tag(func), "function") | 1494 | local tm = gettagmethod(tag(func), "function") |
1483 | if tm then | 1495 | if tm then |
1484 | for i=arg.n,1,-1 do | 1496 | for i=arg.n,1,-1 do |
1485 | arg[i+1] = arg[i] | 1497 | arg[i+1] = arg[i] |
1486 | end | 1498 | end |
1487 | arg.n = arg.n+1 | 1499 | arg.n = arg.n+1 |
1488 | arg[1] = func | 1500 | arg[1] = func |
1489 | return call(tm, arg) | 1501 | return call(tm, arg) |
1490 | else | 1502 | else |
1491 | error("call expression not a function") | 1503 | error("call expression not a function") |
1492 | end | 1504 | end |
1493 | end | 1505 | end |
1494 | end | 1506 | end |
1495 | \end{verbatim} | 1507 | \end{verbatim} |
1496 | 1508 | ||
1497 | \item[``gc'':]\index{gc event} | 1509 | \item[``gc'':]\index{gc event} |
1498 | called when Lua is ``garbage collecting'' a userdata. | 1510 | called when Lua is ``garbage collecting'' a userdata. |
1499 | This tag method can be set only from~C, | 1511 | This tag method can be set only from~C, |
1500 | and cannot be set for a userdata with default tag. | 1512 | and cannot be set for a userdata with the default tag. |
1501 | For each userdata to be collected, | 1513 | For each userdata to be collected, |
1502 | Lua does the equivalent of the following function: | 1514 | Lua does the equivalent of the following function: |
1503 | \begin{verbatim} | 1515 | \begin{verbatim} |
1504 | function gc_event (obj) | 1516 | function gc_event (obj) |
1505 | local tm = gettagmethod(tag(obj), "gc") | 1517 | local tm = gettagmethod(tag(obj), "gc") |
1506 | if tm then | 1518 | if tm then |
1507 | tm(obj) | 1519 | tm(obj) |
1508 | end | 1520 | end |
1509 | end | 1521 | end |
1510 | \end{verbatim} | 1522 | \end{verbatim} |
1511 | Moreover, at the end of a garbage collection cycle, | 1523 | Moreover, at the end of a garbage collection cycle, |
1512 | Lua does the equivalent of the call \verb|gc_event(nil)|. | 1524 | Lua does the equivalent of the call \verb|gc_event(nil)|. |
1525 | (This may change in the final 4.0 version.) | ||
1513 | 1526 | ||
1514 | \end{description} | 1527 | \end{description} |
1515 | 1528 | ||
@@ -1520,261 +1533,293 @@ Lua does the equivalent of the call \verb|gc_event(nil)|. | |||
1520 | 1533 | ||
1521 | This section describes the API for Lua, that is, | 1534 | This section describes the API for Lua, that is, |
1522 | the set of C~functions available to the host program to communicate | 1535 | the set of C~functions available to the host program to communicate |
1523 | with the Lua library. | 1536 | with Lua. |
1524 | The API functions can be classified into the following categories: | ||
1525 | \begin{enumerate} | ||
1526 | \item managing states; | ||
1527 | \item exchanging values between C and Lua; | ||
1528 | \item executing Lua code; | ||
1529 | \item manipulating (reading and writing) Lua objects; | ||
1530 | \item calling Lua functions; | ||
1531 | \item defining C~functions to be called by Lua; | ||
1532 | \item manipulating references to Lua Objects. | ||
1533 | \end{enumerate} | ||
1534 | All API functions and related types and constants | 1537 | All API functions and related types and constants |
1535 | are declared in the header file \verb|lua.h|. | 1538 | are declared in the header file \verb|lua.h|. |
1536 | 1539 | ||
1537 | \NOTE | 1540 | \NOTE |
1538 | Even when we use the term \emph{function}, | 1541 | Even when we use the term ``function'', |
1539 | \emph{any facility in the API may be provided as a macro instead}. | 1542 | any facility in the API may be provided as a \emph{macro} instead. |
1540 | All such macros use each of its arguments exactly once, | 1543 | All such macros use each of its arguments exactly once, |
1541 | and so do not generate hidden side-effects. | 1544 | and so do not generate hidden side-effects. |
1542 | 1545 | ||
1543 | 1546 | ||
1544 | \subsection{States} \label{mangstate} | 1547 | \subsection{States} \label{mangstate} |
1545 | 1548 | ||
1546 | The Lua library is reentrant: | 1549 | The Lua library is fully reentrant: |
1547 | it does not have any global variable. | 1550 | it does not have any global variable. |
1548 | The whole state of the Lua interpreter | 1551 | The whole state of the Lua interpreter |
1549 | (global variables, stack, tag methods, etc.) | 1552 | (global variables, stack, tag methods, etc.) |
1550 | is stored in a dynamic structure; \Deffunc{lua_State} | 1553 | is stored in a dynamically allocated structure; \Deffunc{lua_State} |
1551 | this state must be passed as the first argument to almost | 1554 | this state must be passed as the first argument to |
1552 | every function in the library. | 1555 | every function in the library (except \verb|lua_open| below). |
1553 | 1556 | ||
1554 | Before calling any API function, | 1557 | Before calling any API function, |
1555 | you must create a state. | 1558 | you must create a state. |
1556 | This is done by calling\Deffunc{lua_newstate} | 1559 | This is done by calling\Deffunc{lua_open} |
1557 | \begin{verbatim} | 1560 | \begin{verbatim} |
1558 | lua_State *lua_newstate (int stacksize, int builtin); | 1561 | lua_State *lua_open (int stacksize); |
1559 | \end{verbatim} | 1562 | \end{verbatim} |
1560 | The arguments to this function are | 1563 | The sole argument to this function is the stack size for the interpreter. |
1561 | the stack size for the interpreter and a boolean that | 1564 | (Each function call needs one stack position for each argument, local variable |
1562 | indicates whether the predefined functions should be loaded or not. | 1565 | and temporary values, plus one position for book-keeping. |
1563 | Each function call needs one stack position for each local variable | ||
1564 | and temporary variables, plus one position for book-keeping. | ||
1565 | The stack must also have some 20 extra positions available. | 1566 | The stack must also have some 20 extra positions available. |
1566 | For very small implementations, without recursive functions, | 1567 | For very small implementations, without recursive functions, |
1567 | a stack size of 100 should be enough. | 1568 | a stack size of 100 should be enough.) |
1568 | A value 0 for \verb|stacksize| uses a default size of 1024 positions. | 1569 | If \verb|stacksize| is zero, |
1569 | For instance, the call | 1570 | then a default size is used (the default is 1024). |
1570 | \begin{verbatim} | ||
1571 | lua_State *L = lua_newstate(0, 1); | ||
1572 | \end{verbatim} | ||
1573 | creates a new state with a stack of 1024 positions | ||
1574 | and with the predefined functions loaded; | ||
1575 | the call | ||
1576 | \begin{verbatim} | ||
1577 | lua_State *L = lua_newstate(100, 0) | ||
1578 | \end{verbatim} | ||
1579 | creates a new state with a stack of 100 positions, | ||
1580 | without the predefined functions. | ||
1581 | When you create a state without the builtin function, | ||
1582 | you must provide by yourself any function that your interpreter may need | ||
1583 | (such as \verb|_ALERT| and \verb|_ERRORMESSAGE| for error report, etc.). | ||
1584 | 1571 | ||
1585 | To release a state, you call | 1572 | To release a state created with \verb|lua_open|, call |
1586 | \begin{verbatim} | 1573 | \begin{verbatim} |
1587 | void lua_close (lua_State *L); | 1574 | void lua_close (lua_State *L); |
1588 | \end{verbatim} | 1575 | \end{verbatim} |
1589 | This function destroys all objects in the current Lua environment | 1576 | This function destroys all objects in the given Lua environment |
1590 | (calling the corresponding garbage collection tag methods) | 1577 | (calling the corresponding garbage-collection tag methods) |
1591 | and frees all dynamic memory used by the state. | 1578 | and frees all dynamic memory used by that state. |
1592 | Frequently, you do not need to call this function, | 1579 | Usually, you do not need to call this function, |
1593 | because all resources are naturally released when the program ends. | 1580 | because all resources are naturally released when your program ends. |
1594 | On the other hand, | 1581 | On the other hand, |
1595 | long-running programs --- | 1582 | long-running programs --- |
1596 | like a daemon or web server, for example --- | 1583 | like a daemon or a web server --- |
1597 | might need to release states as soon as they are not needed, | 1584 | might need to release states as soon as they are not needed, |
1598 | to avoid growing too big. | 1585 | to avoid growing too big. |
1599 | 1586 | ||
1600 | With the exception of \verb|lua_newstate|, | 1587 | With the exception of \verb|lua_open|, |
1601 | all functions in the API need a state as their first argument. | 1588 | all functions in the API need a state as their first argument. |
1602 | 1589 | ||
1603 | 1590 | ||
1604 | \subsection{Exchanging Values between C and Lua} \label{valuesCLua} | 1591 | \subsection{The Stack and Indices} |
1605 | Because Lua has no static type system, | 1592 | |
1606 | all values passed between Lua and C have type | 1593 | Lua uses a \emph{stack} to pass values to and from C. |
1607 | \verb|lua_Object|\Deffunc{lua_Object}, | 1594 | Each element in this stack represents a Lua value |
1608 | which works like an abstract type in C that can hold any Lua value. | 1595 | (nil, number, string, etc.). |
1609 | Values of type \verb|lua_Object| have no meaning outside Lua; | 1596 | |
1610 | for instance, | 1597 | For convenience, |
1611 | you cannot compare two \verb|lua_Object|s directly. | 1598 | most query operations in the API do not follow a strict stack discipline. |
1612 | Instead, you should use the following function: | 1599 | Instead, they can refer to any element in the stack by using an \emph{index}: |
1613 | \Deffunc{lua_equal} | 1600 | A positive index represents an \emph{absolute} stack position |
1614 | \begin{verbatim} | 1601 | (starting at 1, not 0 as in C); |
1615 | int lua_equal (lua_State *L, lua_Object o1, lua_Object o2); | 1602 | a negative index represents an \emph{offset} from the top of the stack. |
1616 | \end{verbatim} | 1603 | More specifically, if the stack has \M{n} elements, |
1617 | 1604 | index 1 represents the first element | |
1618 | To check the type of a \verb|lua_Object|, | 1605 | (that is, the first element pushed onto the stack), |
1606 | index \M{n} represents the last element; | ||
1607 | index \Math{-1} also represents the last element | ||
1608 | (that is, the element at the top), | ||
1609 | and index \Math{-n} represents the first element. | ||
1610 | We say that an index is \emph{valid} | ||
1611 | if it lays between 1 and the stack top | ||
1612 | (that is, \verb|(1 <= abs(index) <= top)|). | ||
1613 | \index{stack index} \index{valid index} | ||
1614 | |||
1615 | At any time, you can get the index of the top element by calling | ||
1616 | \Deffunc{lua_gettop} | ||
1617 | \begin{verbatim} | ||
1618 | int lua_gettop (lua_State *L); | ||
1619 | \end{verbatim} | ||
1620 | Because indices start at 1, | ||
1621 | the result of \verb|lua_gettop| is equal to the number of elements in the stack | ||
1622 | (0 means an empty stack). | ||
1623 | |||
1624 | When you interact with Lua API, | ||
1625 | \emph{you are responsible for controlling stack overflow}. | ||
1626 | The function \Deffunc{lua_stackspace} | ||
1627 | \begin{verbatim} | ||
1628 | int lua_stackspace (lua_State *L); | ||
1629 | \end{verbatim} | ||
1630 | returns the number of stack positions still available. | ||
1631 | Whenever Lua calls C, \Deffunc{LUA_MINSTACK} | ||
1632 | it ensures that | ||
1633 | at least \verb|LUA_MINSTACK| positions are still available. | ||
1634 | \verb|LUA_MINSTACK| is defined in \verb|lua.h| and is at least~16, | ||
1635 | and so you have to worry about stack space only | ||
1636 | when your code has loops pushing elements onto the stack. | ||
1637 | |||
1638 | Most query functions accept as indices any value inside the | ||
1639 | available stack space. | ||
1640 | Such indices are called \emph{acceptable indices}. | ||
1641 | More formally, we can define an \IndexEmph{acceptable index} | ||
1642 | as | ||
1643 | \begin{verbatim} | ||
1644 | (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) | ||
1645 | \end{verbatim} | ||
1646 | (Note that 0 is not an acceptable index.) | ||
1647 | |||
1648 | \subsection{Stack Manipulation} | ||
1649 | The API offers the following functions for basic stack manipulation: | ||
1650 | \Deffunc{lua_settop}\Deffunc{lua_pushvalue} | ||
1651 | \Deffunc{lua_remove}\Deffunc{lua_insert} | ||
1652 | \begin{verbatim} | ||
1653 | void lua_settop (lua_State *L, int index); | ||
1654 | void lua_pushvalue (lua_State *L, int index); | ||
1655 | void lua_remove (lua_State *L, int index); | ||
1656 | void lua_insert (lua_State *L, int index); | ||
1657 | \end{verbatim} | ||
1658 | |||
1659 | \verb|lua_settop| accepts any acceptable index, | ||
1660 | or 0, | ||
1661 | and sets the stack top to that index. | ||
1662 | If the new top is larger than the old one, | ||
1663 | then the new elements are filled with \nil. | ||
1664 | If \verb|index| is 0, then all stack elements are removed. | ||
1665 | A useful macro defined in the API is | ||
1666 | \begin{verbatim} | ||
1667 | #define lua_pop(L,n) lua_settop(L, -(n)-1) | ||
1668 | \end{verbatim} | ||
1669 | which pops \verb|n| elements from the stack. | ||
1670 | |||
1671 | \verb|lua_pushvalue| pushes onto the stack a copy of the element | ||
1672 | at the given index. | ||
1673 | \verb|lua_remove| removes the element at the given position, | ||
1674 | shifting down the elements on top of that position to fill in the gap. | ||
1675 | \verb|lua_insert| moves the top element into the given position, | ||
1676 | shifting up the elements on top of that position to open space. | ||
1677 | These functions accept only valid indices. | ||
1678 | As an example, if the stack starts as \verb|10 20 30 40 50| | ||
1679 | (from bottom to top), | ||
1680 | then | ||
1681 | \begin{verbatim} | ||
1682 | lua_pushvalue(L, 3) --> 10 20 30 40 50 30 | ||
1683 | lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30 | ||
1684 | lua_remove(L, -3) --> 10 20 30 40 30 30 | ||
1685 | lua_remove(L, 6) --> 10 20 30 40 30 | ||
1686 | lua_insert(L, 1) --> 30 10 20 30 40 | ||
1687 | lua_insert(L, -1) --> 30 10 20 30 40 (no effect) | ||
1688 | lua_settop(L, -3) --> 30 10 20 | ||
1689 | lua_settop(L, 6) --> 30 10 20 nil nil nil | ||
1690 | \end{verbatim} | ||
1691 | |||
1692 | |||
1693 | \subsection{Querying the Stack} | ||
1694 | |||
1695 | To check the type of a stack element, | ||
1619 | the following functions are available: | 1696 | the following functions are available: |
1620 | \Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} | 1697 | \Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} |
1621 | \Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} | 1698 | \Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} |
1622 | \Deffunc{lua_isfunction} | 1699 | \Deffunc{lua_isfunction}\Deffunc{lua_type} |
1623 | \Deffunc{lua_type} | 1700 | \begin{verbatim} |
1624 | \begin{verbatim} | 1701 | const char *lua_type (lua_State *L, int index); |
1625 | int lua_isnil (lua_State *L, lua_Object object); | 1702 | int lua_tag (lua_State *L, int index); |
1626 | int lua_isnumber (lua_State *L, lua_Object object); | 1703 | int lua_isnil (lua_State *L, int index); |
1627 | int lua_isstring (lua_State *L, lua_Object object); | 1704 | int lua_isnumber (lua_State *L, int index); |
1628 | int lua_istable (lua_State *L, lua_Object object); | 1705 | int lua_isstring (lua_State *L, int index); |
1629 | int lua_isfunction (lua_State *L, lua_Object object); | 1706 | int lua_istable (lua_State *L, int index); |
1630 | int lua_iscfunction (lua_State *L, lua_Object object); | 1707 | int lua_isfunction (lua_State *L, int index); |
1631 | int lua_isuserdata (lua_State *L, lua_Object object); | 1708 | int lua_iscfunction (lua_State *L, int index); |
1632 | const char *lua_type (lua_State *L, lua_Object object); | 1709 | int lua_isuserdata (lua_State *L, int index); |
1633 | \end{verbatim} | 1710 | \end{verbatim} |
1711 | These functions can be called with any acceptable index. | ||
1712 | |||
1713 | \verb|lua_type| returns one of the following strings, | ||
1714 | describing the type of the given object: | ||
1715 | \verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|, | ||
1716 | \verb|"function"|, \verb|"userdata"|; or \verb|"NO VALUE"|, | ||
1717 | if the index is non-valid (that is, if that stack position is ``empty''). | ||
1718 | |||
1719 | \verb|lua_tag| returns the tag of a value, | ||
1720 | or \verb|LUA_NOTAG| for a non-valid index. | ||
1721 | (Very dirty trick: some type names start with the same letter (Number-Nil); | ||
1722 | others have the second letter in common (nUmber-fUnction). | ||
1723 | However, you can use the emph{third} letter as a unique scalar | ||
1724 | identification for each type.) | ||
1725 | |||
1634 | The \verb|lua_is*| functions return 1 if the object is compatible | 1726 | The \verb|lua_is*| functions return 1 if the object is compatible |
1635 | with the given type, and 0 otherwise. | 1727 | with the given type, and 0 otherwise. |
1636 | The function \verb|lua_isnumber| accepts numbers and numerical strings, | 1728 | They always return 0 for a non-valid index. |
1729 | \verb|lua_isnumber| accepts numbers and numerical strings, | ||
1637 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, | 1730 | \verb|lua_isstring| accepts strings and numbers \see{coercion}, |
1638 | and \verb|lua_isfunction| accepts Lua functions and C~functions. | 1731 | and \verb|lua_isfunction| accepts both Lua functions and C~functions. |
1639 | To distinguish between Lua functions and C~functions, | 1732 | To distinguish between Lua functions and C~functions, |
1640 | you should use \verb|lua_iscfunction|. | 1733 | you should use \verb|lua_iscfunction|. |
1641 | To distinguish between numbers and numerical strings, | 1734 | To distinguish between numbers and numerical strings, |
1642 | you can use \verb|lua_type|. | 1735 | you can use \verb|lua_type|. |
1643 | The \verb|lua_type| returns one of the following strings, | ||
1644 | describing the type of the given object: | ||
1645 | \verb|"nil"|, \verb|"number"|, \verb|"string"|, \verb|"table"|, | ||
1646 | \verb|"function"|, \verb|"userdata"|, or \verb|"NOOBJECT"|. | ||
1647 | 1736 | ||
1648 | To get the tag of a \verb|lua_Object|, | 1737 | The API also has functions to compare two values in the stack: |
1649 | use the following function: | ||
1650 | \Deffunc{lua_tag} | ||
1651 | \begin{verbatim} | 1738 | \begin{verbatim} |
1652 | int lua_tag (lua_State *L, lua_Object object); | 1739 | int lua_equal (lua_State *L, int index1, int index2); |
1740 | int lua_lessthan (lua_State *L, int index1, int index2); | ||
1653 | \end{verbatim} | 1741 | \end{verbatim} |
1742 | These functions are equivalent to their counterparts in Lua. | ||
1743 | Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event| | ||
1744 | described in~\ref{tag-method}. | ||
1745 | Both functions return 0 if any of the indices are non-valid. | ||
1654 | 1746 | ||
1655 | To translate a value from type \verb|lua_Object| to a specific C type, | 1747 | To translate a value in the stack to a specific C~type, |
1656 | you can use the following conversion functions: | 1748 | you can use the following conversion functions: |
1657 | \Deffunc{lua_getnumber}\Deffunc{lua_getstring}\Deffunc{lua_strlen} | 1749 | \Deffunc{lua_tonumber}\Deffunc{lua_tostring}\Deffunc{lua_strlen} |
1658 | \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} | 1750 | \Deffunc{lua_tocfunction}\Deffunc{lua_touserdata} |
1659 | \begin{verbatim} | 1751 | \begin{verbatim} |
1660 | double lua_getnumber (lua_State *L, lua_Object object); | 1752 | double lua_tonumber (lua_State *L, int index); |
1661 | const char *lua_getstring (lua_State *L, lua_Object object); | 1753 | const char *lua_tostring (lua_State *L, int index); |
1662 | size_t lua_strlen (lua_State *L, lua_Object object); | 1754 | size_t lua_strlen (lua_State *L, int index); |
1663 | lua_CFunction lua_getcfunction (lua_State *L, lua_Object object); | 1755 | lua_CFunction lua_tocfunction (lua_State *L, int index); |
1664 | void *lua_getuserdata (lua_State *L, lua_Object object); | 1756 | void *lua_touserdata (lua_State *L, int index); |
1665 | \end{verbatim} | 1757 | \end{verbatim} |
1758 | These functions can be called with any acceptable index. | ||
1759 | When called with a non-valid index, | ||
1760 | they act as if the given value had an incorrect type. | ||
1666 | 1761 | ||
1667 | \verb|lua_getnumber| converts a \verb|lua_Object| to a floating-point number. | 1762 | \verb|lua_tonumber| converts the value at the given index |
1668 | This \verb|lua_Object| must be a number or a string convertible to number | 1763 | to a floating-point number. |
1669 | \see{coercion}; otherwise, \verb|lua_getnumber| returns~0. | 1764 | This value must be a number or a string convertible to number |
1765 | \see{coercion}; otherwise, \verb|lua_tonumber| returns~0. | ||
1670 | 1766 | ||
1671 | \verb|lua_getstring| converts a \verb|lua_Object| to a string | 1767 | \verb|lua_tostring| converts a Lua value to a string |
1672 | (\verb|const char*|). | 1768 | (\verb|const char*|). |
1673 | This \verb|lua_Object| must be a string or a number; | 1769 | This value must be a string or a number; |
1674 | otherwise, the function returns \verb|NULL|. | 1770 | otherwise, the function returns \verb|NULL|. |
1675 | This function does not create a new string, | 1771 | This function returns a pointer to a string inside the Lua environment. |
1676 | but returns a pointer to a string inside the Lua environment. | ||
1677 | Those strings always have a 0 after their last character (like in C), | 1772 | Those strings always have a 0 after their last character (like in C), |
1678 | but may contain other zeros in their body. | 1773 | but may contain other zeros in their body. |
1679 | If you do not know whether a string may contain zeros, | 1774 | If you do not know whether a string may contain zeros, |
1680 | you should use \verb|lua_strlen| to get the actual length. | 1775 | you should use \verb|lua_strlen| to get its actual length. |
1681 | Because Lua has garbage collection, | 1776 | Because Lua has garbage collection, |
1682 | there is no guarantee that the pointer returned by \verb|lua_getstring| | 1777 | there is no guarantee that the pointer returned by \verb|lua_tostring| |
1683 | will be valid after the block ends | 1778 | will be valid after the respective value is removed from the stack. |
1684 | \see{GC}. | ||
1685 | 1779 | ||
1686 | \verb|lua_getcfunction| converts a \verb|lua_Object| to a C~function. | 1780 | \verb|lua_tocfunction| converts a value in the stack to a C~function. |
1687 | This \verb|lua_Object| must be a C~function; | 1781 | This value must be a C~function; |
1688 | otherwise, \verb|lua_getcfunction| returns \verb|NULL|. | 1782 | otherwise, \verb|lua_tocfunction| returns \verb|NULL|. |
1689 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. | 1783 | The type \verb|lua_CFunction| is explained in \See{LuacallC}. |
1690 | 1784 | ||
1691 | \verb|lua_getuserdata| converts a \verb|lua_Object| to \verb|void*|. | 1785 | \verb|lua_touserdata| converts a value to \verb|void*|. |
1692 | This \verb|lua_Object| must have type \emph{userdata}; | 1786 | This value must have type \emph{userdata}; |
1693 | otherwise, \verb|lua_getuserdata| returns \verb|NULL|. | 1787 | otherwise, \verb|lua_touserdata| returns \verb|NULL|. |
1694 | 1788 | ||
1695 | \subsection{Communication between Lua and C}\label{Lua-C-protocol} | 1789 | |
1696 | 1790 | ||
1697 | All communication between Lua and C is done through two | 1791 | \subsection{Pushing values onto the Stack} |
1698 | abstract data types, called \Def{lua2C} and \Def{C2lua}. | 1792 | |
1699 | The first one, as the name implies, is used to pass values | 1793 | The API has the following functions to |
1700 | from Lua to C: | 1794 | push C~values onto the stack: |
1701 | parameters when Lua calls C and results when C calls Lua. | ||
1702 | The structure C2lua is used in the reverse direction: | ||
1703 | parameters when C calls Lua and results when Lua calls C. | ||
1704 | |||
1705 | The structure lua2C is an \emph{abstract array} | ||
1706 | that can be indexed with the function: | ||
1707 | \Deffunc{lua_lua2C} | ||
1708 | \begin{verbatim} | ||
1709 | lua_Object lua_lua2C (lua_State *L, int number); | ||
1710 | \end{verbatim} | ||
1711 | where \verb|number| starts with 1. | ||
1712 | When called with a number larger than the array size, | ||
1713 | this function returns \verb|LUA_NOOBJECT|\Deffunc{LUA_NOOBJECT}. | ||
1714 | In this way, it is possible to write C~functions that receive | ||
1715 | a variable number of parameters, | ||
1716 | and to call Lua functions that return a variable number of results. | ||
1717 | Note that the structure lua2C cannot be directly modified by C code. | ||
1718 | |||
1719 | The structure C2lua is an \emph{abstract stack}. | ||
1720 | Pushing elements into this stack | ||
1721 | is done with the following functions: | ||
1722 | \Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} | 1795 | \Deffunc{lua_pushnumber}\Deffunc{lua_pushlstring}\Deffunc{lua_pushstring} |
1723 | \Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag} | 1796 | \Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag} |
1724 | \Deffunc{lua_pushnil}\Deffunc{lua_pushobject} | 1797 | \Deffunc{lua_pushnil}\Deffunc{lua_pushuserdata}\label{pushing} |
1725 | \Deffunc{lua_pushuserdata}\label{pushing} | 1798 | \begin{verbatim} |
1726 | \begin{verbatim} | 1799 | void lua_pushnumber (lua_State *L, double n); |
1727 | void lua_pushnumber (lua_State *L, double n); | 1800 | void lua_pushlstring (lua_State *L, const char *s, size_t len); |
1728 | void lua_pushlstring (lua_State *L, const char *s, size_t len); | 1801 | void lua_pushstring (lua_State *L, const char *s); |
1729 | void lua_pushstring (lua_State *L, const char *s); | 1802 | void lua_pushusertag (lua_State *L, void *u, int tag); |
1730 | void lua_pushusertag (lua_State *L, void *u, int tag); | 1803 | void lua_pushnil (lua_State *L); |
1731 | void lua_pushnil (lua_State *L); | 1804 | void lua_pushcfunction (lua_State *L, lua_CFunction f); |
1732 | void lua_pushobject (lua_State *L, lua_Object object); | 1805 | \end{verbatim} |
1733 | void lua_pushcfunction (lua_State *L, lua_CFunction f); /* macro */ | 1806 | These functions receive a C~value, |
1734 | \end{verbatim} | 1807 | convert it to a corresponding Lua value, |
1735 | All of them receive a C value, | 1808 | and push the result onto the stack. |
1736 | convert it to a corresponding \verb|lua_Object|, | 1809 | In particular, \verb|lua_pushlstring| and \verb|lua_pushstring| |
1737 | and leave the result on the top of C2lua. | 1810 | make an \emph{internal copy} of the given string. |
1738 | In particular, functions \verb|lua_pushlstring| and \verb|lua_pushstring| | 1811 | \verb|lua_pushstring| can only be used to push proper C~strings |
1739 | make an internal copy of the given string. | ||
1740 | Function \verb|lua_pushstring| can only be used to push proper C strings | ||
1741 | (that is, strings that end with a zero and do not contain embedded zeros); | 1812 | (that is, strings that end with a zero and do not contain embedded zeros); |
1742 | otherwise you should use the more general \verb|lua_pushlstring|. | 1813 | otherwise you should use the more general \verb|lua_pushlstring|, |
1743 | The function | 1814 | which accepts an explicit size. |
1744 | \Deffunc{lua_pop} | ||
1745 | \begin{verbatim} | ||
1746 | lua_Object lua_pop (lua_State *L); | ||
1747 | \end{verbatim} | ||
1748 | returns a reference to the object at the top of the C2lua stack, | ||
1749 | and pops it. | ||
1750 | 1815 | ||
1751 | When C code calls Lua repeatedly, as in a loop, | ||
1752 | objects returned by these calls accumulate, | ||
1753 | and may cause a stack overflow. | ||
1754 | To avoid this, | ||
1755 | nested blocks can be defined with the functions | ||
1756 | \begin{verbatim} | ||
1757 | void lua_beginblock (lua_State *L); | ||
1758 | void lua_endblock (lua_State *L); | ||
1759 | \end{verbatim} | ||
1760 | At the end of a block, | ||
1761 | Lua releases all \verb|lua_Object|s created inside the block, | ||
1762 | and empties the C2lua stack. | ||
1763 | 1816 | ||
1764 | \subsection{Garbage Collection}\label{GC} | 1817 | \subsection{Garbage Collection}\label{GC} |
1765 | Because Lua has automatic memory management and garbage collection, | ||
1766 | a \verb|lua_Object| has a limited scope, | ||
1767 | and is only valid inside the \emph{block} where it has been created. | ||
1768 | A C~function called from Lua is a block, | ||
1769 | and its parameters are valid only until its end. | ||
1770 | It is good programming practice to convert Lua objects to C values | ||
1771 | as soon as they are available, | ||
1772 | and never to store \verb|lua_Object|s in C global variables. | ||
1773 | 1818 | ||
1774 | A garbage collection cycle can be forced by: | 1819 | A garbage collection cycle can be forced by: |
1775 | \Deffunc{lua_collectgarbage} | 1820 | \Deffunc{lua_collectgarbage} |
1776 | \begin{verbatim} | 1821 | \begin{verbatim} |
1777 | long lua_collectgarbage (lua_State *L, long limit); | 1822 | long lua_collectgarbage (lua_State *L, long limit); |
1778 | \end{verbatim} | 1823 | \end{verbatim} |
1779 | This function returns the number of objects collected. | 1824 | This function returns the number of objects collected. |
1780 | The argument \verb|limit| makes the next cycle occur only | 1825 | The argument \verb|limit| makes the next cycle occur only |
@@ -1802,37 +1847,39 @@ whose semantics are only known to the host program. | |||
1802 | Tags are created with the function | 1847 | Tags are created with the function |
1803 | \Deffunc{lua_newtag} | 1848 | \Deffunc{lua_newtag} |
1804 | \begin{verbatim} | 1849 | \begin{verbatim} |
1805 | int lua_newtag (lua_State *L); | 1850 | int lua_newtag (lua_State *L); |
1806 | \end{verbatim} | 1851 | \end{verbatim} |
1807 | The function \verb|lua_settag| changes the tag of | 1852 | The function \verb|lua_settag| changes the tag of |
1808 | the object on the top of C2lua (and pops it); | 1853 | the object on top of the stack (and pops it): |
1809 | the object must be a userdata or a table: | ||
1810 | \Deffunc{lua_settag} | 1854 | \Deffunc{lua_settag} |
1811 | \begin{verbatim} | 1855 | \begin{verbatim} |
1812 | void lua_settag (lua_State *L, int tag); | 1856 | void lua_settag (lua_State *L, int tag); |
1813 | \end{verbatim} | 1857 | \end{verbatim} |
1814 | The given \verb|tag| must be a value created with \verb|lua_newtag|. | 1858 | The object must be a userdata or a table; |
1859 | the given \verb|tag| must be a value created with \verb|lua_newtag|. | ||
1815 | 1860 | ||
1816 | \subsection{Executing Lua Code} | 1861 | \subsection{Executing Lua Code} |
1817 | A host program can execute Lua chunks written in a file or in a string | 1862 | A host program can execute Lua chunks written in a file or in a string |
1818 | using the following functions:% | 1863 | by using the following functions:% |
1819 | \Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer} | 1864 | \Deffunc{lua_dofile}\Deffunc{lua_dostring}\Deffunc{lua_dobuffer}% |
1820 | \begin{verbatim} | 1865 | \begin{verbatim} |
1821 | int lua_dofile (lua_State *L, const char *filename); | 1866 | int lua_dofile (lua_State *L, const char *filename); |
1822 | int lua_dostring (lua_State *L, const char *string); | 1867 | int lua_dostring (lua_State *L, const char *string); |
1823 | int lua_dobuffer (lua_State *L, const char *buff, | 1868 | int lua_dobuffer (lua_State *L, const char *buff, |
1824 | size_t size, const char *name); | 1869 | size_t size, const char *name); |
1825 | \end{verbatim} | 1870 | \end{verbatim} |
1826 | All these functions return | 1871 | These functions return |
1827 | 0, in case of success, or one of the following error codes: | 1872 | 0 in case of success, or one of the following error codes if they fail |
1873 | (these constants are defined in \verb|lua.h|.): | ||
1828 | \begin{itemize} | 1874 | \begin{itemize} |
1829 | \item \verb|LUA_ERRRUN| --- | 1875 | \item \verb|LUA_ERRRUN| --- |
1830 | error while running the chunk. | 1876 | error while running the chunk. |
1831 | \item \verb|LUA_ERRSYNTAX| --- | 1877 | \item \verb|LUA_ERRSYNTAX| --- |
1832 | syntax error during pre-compilation. | 1878 | syntax error during pre-compilation. |
1833 | \item \verb|LUA_ERRMEM| --- | 1879 | \item \verb|LUA_ERRMEM| --- |
1834 | memory allocation error; | 1880 | memory allocation error. |
1835 | for such errors, Lua does not call the \verb|LUA_ERRORMESSAGE| function. | 1881 | For such errors, Lua does not call the \verb|_ERRORMESSAGE| function |
1882 | \see{error}. | ||
1836 | \item \verb|LUA_ERRFILE| --- | 1883 | \item \verb|LUA_ERRFILE| --- |
1837 | error opening the file (only for \verb|lua_dofile|). | 1884 | error opening the file (only for \verb|lua_dofile|). |
1838 | In this case, | 1885 | In this case, |
@@ -1844,88 +1891,118 @@ or call \verb|perror| to tell the user what went wrong. | |||
1844 | 1891 | ||
1845 | When called with argument \verb|NULL|, | 1892 | When called with argument \verb|NULL|, |
1846 | \verb|lua_dofile| executes the \verb|stdin| stream. | 1893 | \verb|lua_dofile| executes the \verb|stdin| stream. |
1847 | Functions \verb|lua_dofile| and \verb|lua_dobuffer| | 1894 | \verb|lua_dofile| and \verb|lua_dobuffer| |
1848 | are both able to execute pre-compiled chunks. | 1895 | are both able to execute pre-compiled chunks. |
1849 | They automatically detect whether the chunk is text or binary, | 1896 | They automatically detect whether the chunk is text or binary, |
1850 | and load it accordingly (see program \IndexVerb{luac}). | 1897 | and load it accordingly (see program \IndexVerb{luac}). |
1851 | Function \verb|lua_dostring| executes only source code, | 1898 | \verb|lua_dostring| executes only source code, |
1852 | given in textual form. | 1899 | given in textual form. |
1853 | 1900 | ||
1854 | The third parameter to \verb|lua_dobuffer| (\verb|name|) | 1901 | The third parameter to \verb|lua_dobuffer| |
1855 | is the ``name of the chunk'', | 1902 | is the ``name of the chunk'', |
1856 | used in error messages and debug information. | 1903 | used in error messages and debug information. |
1857 | If \verb|name| is \verb|NULL|, | 1904 | If \verb|name| is \verb|NULL|, |
1858 | then Lua gives a default name to the chunk. | 1905 | then Lua gives a default name to the chunk. |
1859 | 1906 | ||
1860 | These functions return, in structure lua2C, | 1907 | These functions push onto the stack |
1861 | any values eventually returned by the chunks. | 1908 | any values eventually returned by the chunks. |
1862 | They also empty the stack C2lua. | 1909 | A chunk may return any number of values; |
1910 | Lua takes care that these values fit into the stack space, | ||
1911 | but after the call the responsibility is back with you. | ||
1912 | If you need to push other elements after calling any of these functions, | ||
1913 | and you want to play safe, | ||
1914 | you must either check the stack space or remove the returned elements | ||
1915 | from the stack (if you do not need them). | ||
1916 | For instance, the following code | ||
1917 | loads a chunk in a file and discards all results returned by this chunk, | ||
1918 | leaving the stack as it was before the call: | ||
1919 | \begin{verbatim} | ||
1920 | { | ||
1921 | int oldtop = lua_gettop(L); | ||
1922 | lua_dofile(L, filename); | ||
1923 | lua_settop(L, oldtop); | ||
1924 | } | ||
1925 | \end{verbatim} | ||
1926 | |||
1863 | 1927 | ||
1928 | \subsection{Manipulating Global Variables in Lua} | ||
1864 | 1929 | ||
1865 | \subsection{Manipulating Lua Objects} | 1930 | To read the value of a global Lua variable, |
1866 | To read the value of any global Lua variable, | 1931 | you call |
1867 | one uses the function | ||
1868 | \Deffunc{lua_getglobal} | 1932 | \Deffunc{lua_getglobal} |
1869 | \begin{verbatim} | 1933 | \begin{verbatim} |
1870 | lua_Object lua_getglobal (lua_State *L, const char *varname); | 1934 | void lua_getglobal (lua_State *L, const char *varname); |
1871 | \end{verbatim} | 1935 | \end{verbatim} |
1936 | which pushes onto the stack the value of the given variable. | ||
1872 | As in Lua, this function may trigger a tag method | 1937 | As in Lua, this function may trigger a tag method |
1873 | for the ``getglobal'' event. | 1938 | for the ``getglobal'' event. |
1874 | To read the real value of a global variable, | 1939 | To read the real value of a global variable, |
1875 | without invoking any tag method, | 1940 | without invoking any tag method, |
1876 | use the \emph{lua_rawget} function over the table of globals. | 1941 | use the \verb|lua_rawget| function over the table of globals |
1942 | (see below). | ||
1877 | 1943 | ||
1878 | To store a value previously pushed onto C2lua in a global variable, | 1944 | To store a value in a global variable, |
1879 | there is the function | 1945 | you call |
1880 | \Deffunc{lua_setglobal} | 1946 | \Deffunc{lua_setglobal} |
1881 | \begin{verbatim} | 1947 | \begin{verbatim} |
1882 | void lua_setglobal (lua_State *L, const char *varname); | 1948 | void lua_setglobal (lua_State *L, const char *varname); |
1883 | \end{verbatim} | 1949 | \end{verbatim} |
1950 | which pops from the stack the value to be stored in the given variable. | ||
1884 | As in Lua, this function may trigger a tag method | 1951 | As in Lua, this function may trigger a tag method |
1885 | for the ``setglobal'' event. | 1952 | for the ``setglobal'' event. |
1886 | To set the real value of a global variable, | 1953 | To set the real value of a global variable, |
1887 | without invoking any tag method, | 1954 | without invoking any tag method, |
1888 | use the \emph{lua_rawset} function over the table of globals. | 1955 | use the \verb|lua_rawset| function over the table of globals. |
1889 | 1956 | ||
1890 | To get the table of globals, | 1957 | All global variables are kept in an ordinary Lua table. |
1891 | you should call | 1958 | You can get this table calling |
1892 | \Deffunc{lua_pushglobals} | 1959 | \Deffunc{lua_getglobals} |
1893 | \begin{verbatim} | 1960 | \begin{verbatim} |
1894 | void lua_pushglobals (lua_State *L); | 1961 | void lua_getglobals (lua_State *L); |
1895 | \end{verbatim} | 1962 | \end{verbatim} |
1963 | which pushes the current table of globals onto the stack. | ||
1896 | To set another table as the table of globals, | 1964 | To set another table as the table of globals, |
1897 | you use | 1965 | you call |
1898 | \Deffunc{lua_setglobals} | 1966 | \Deffunc{lua_setglobals} |
1899 | \begin{verbatim} | 1967 | \begin{verbatim} |
1900 | void lua_setglobals (lua_State *L, lua_Object newtable); | 1968 | void lua_setglobals (lua_State *L); |
1901 | \end{verbatim} | 1969 | \end{verbatim} |
1970 | The table to be used is popped from the stack. | ||
1971 | |||
1972 | \subsection{Manipulating Tables in Lua} | ||
1973 | Lua tables can also be manipulated through the API. | ||
1902 | 1974 | ||
1903 | Tables can also be manipulated via the API. | 1975 | To read the value of in a table, |
1904 | The function | 1976 | the table must reside somewhere in the stack. |
1977 | With this set, | ||
1978 | you call | ||
1905 | \Deffunc{lua_gettable} | 1979 | \Deffunc{lua_gettable} |
1906 | \begin{verbatim} | 1980 | \begin{verbatim} |
1907 | lua_Object lua_gettable (lua_State *L); | 1981 | void lua_gettable (lua_State *L, int index); |
1908 | \end{verbatim} | 1982 | \end{verbatim} |
1909 | pops a table and an index from the stack C2lua, | 1983 | where \verb|index| refers to the table. |
1910 | and returns the contents of the table at that index. | 1984 | \verb|lua_gettable| pops a key from the stack, |
1985 | and returns (on the stack) the contents of the table at that key. | ||
1911 | As in Lua, this operation may trigger a tag method | 1986 | As in Lua, this operation may trigger a tag method |
1912 | for the ``gettable'' event. | 1987 | for the ``gettable'' event. |
1913 | To get the real value of any table index, | 1988 | To get the real value of any table key, |
1914 | without invoking any tag method, | 1989 | without invoking any tag method, |
1915 | use the \emph{raw} version: | 1990 | use the \emph{raw} version: |
1916 | \Deffunc{lua_rawget} | 1991 | \Deffunc{lua_rawget} |
1917 | \begin{verbatim} | 1992 | \begin{verbatim} |
1918 | lua_Object lua_rawget (lua_State *L); | 1993 | void lua_rawget (lua_State *L, int index); |
1919 | \end{verbatim} | 1994 | \end{verbatim} |
1920 | 1995 | ||
1921 | To store a value in an index, | 1996 | To store a value into a table that resides somewhere in the stack, |
1922 | the program must push the table, the index, and the value onto C2lua | 1997 | you push the key and the value onto the stack |
1923 | (in this order), | 1998 | (in this order), |
1924 | and then call the function | 1999 | and then call |
1925 | \Deffunc{lua_settable} | 2000 | \Deffunc{lua_settable} |
1926 | \begin{verbatim} | 2001 | \begin{verbatim} |
1927 | void lua_settable (lua_State *L); | 2002 | void lua_settable (lua_State *L, int index); |
1928 | \end{verbatim} | 2003 | \end{verbatim} |
2004 | where \verb|index| refers to the table. | ||
2005 | \verb|lua_settable| pops from the stack both the key and the value. | ||
1929 | As in Lua, this operation may trigger a tag method | 2006 | As in Lua, this operation may trigger a tag method |
1930 | for the ``settable'' event. | 2007 | for the ``settable'' event. |
1931 | To set the real value of any table index, | 2008 | To set the real value of any table index, |
@@ -1933,125 +2010,158 @@ without invoking any tag method, | |||
1933 | use the \emph{raw} version: | 2010 | use the \emph{raw} version: |
1934 | \Deffunc{lua_rawset} | 2011 | \Deffunc{lua_rawset} |
1935 | \begin{verbatim} | 2012 | \begin{verbatim} |
1936 | void lua_rawset (lua_State *L); | 2013 | void lua_rawset (lua_State *L, int index); |
1937 | \end{verbatim} | 2014 | \end{verbatim} |
1938 | 2015 | ||
1939 | Finally, the function | 2016 | Finally, the function |
1940 | \Deffunc{lua_createtable} | 2017 | \Deffunc{lua_newtable} |
2018 | \begin{verbatim} | ||
2019 | void lua_newtable (lua_State *L); | ||
2020 | \end{verbatim} | ||
2021 | creates a new, empty table and and pushes it onto the stack. | ||
2022 | |||
2023 | \subsection{Using Tables as Arrays} | ||
2024 | The API has functions that help to use Lua tables as arrays, | ||
2025 | that is, | ||
2026 | tables indexed by numbers only: | ||
2027 | \Deffunc{lua_rawgeti} | ||
2028 | \Deffunc{lua_rawseti} | ||
2029 | \Deffunc{lua_getn} | ||
1941 | \begin{verbatim} | 2030 | \begin{verbatim} |
1942 | lua_Object lua_createtable (lua_State *L); | 2031 | void lua_rawgeti (lua_State *L, int index, int n); |
2032 | void lua_rawseti (lua_State *L, int index, int n); | ||
2033 | int lua_getn (lua_State *L, int index); | ||
1943 | \end{verbatim} | 2034 | \end{verbatim} |
1944 | creates and returns a new, empty table. | ||
1945 | 2035 | ||
2036 | \verb|lua_rawgeti| gets the value of the \verb|n|-th element of the table | ||
2037 | at stack position \verb|index|. | ||
2038 | |||
2039 | \verb|lua_rawseti| sets the value of the \verb|n|-th element of the table | ||
2040 | at stack position \verb|index| to the value at the top of the stack. | ||
2041 | |||
2042 | \verb|lua_getn| returns the number of elements in the table | ||
2043 | at stack position \verb|index|. | ||
2044 | This number is the value of the table field \verb|n|, | ||
2045 | if it has a numeric value, | ||
2046 | or | ||
2047 | the largest numerical index with a non-nil value in the table. | ||
1946 | 2048 | ||
1947 | \subsection{Calling Lua Functions} | 2049 | \subsection{Calling Lua Functions} |
1948 | Functions defined in Lua by a chunk | 2050 | |
2051 | Functions defined in Lua | ||
1949 | can be called from the host program. | 2052 | can be called from the host program. |
1950 | This is done using the following protocol: | 2053 | This is done using the following protocol: |
1951 | first, the arguments to the function are pushed onto C2lua | 2054 | First, the function to be called is pushed onto the stack; |
1952 | \see{pushing}, in direct order, i.e., the first argument is pushed first. | 2055 | then, the arguments to the function are pushed |
1953 | Then, the function is called using | 2056 | \see{pushing} in direct order, i.e., the first argument is pushed first. |
1954 | \Deffunc{lua_callfunction} | 2057 | Finally, the function is called using |
1955 | \begin{verbatim} | 2058 | \Deffunc{lua_call} |
1956 | int lua_callfunction (lua_State *L, lua_Object function); | 2059 | \begin{verbatim} |
1957 | \end{verbatim} | 2060 | int lua_call (lua_State *L, int nargs, int nresults); |
1958 | This function returns the same error codes that \verb|lua_dostring|. | 2061 | \end{verbatim} |
1959 | Finally, the results are returned in structure lua2C | 2062 | This function returns the same error codes as \verb|lua_dostring|. |
1960 | (recall that a Lua function may return many values), | 2063 | Here, |
1961 | and can be retrieved with the macro \verb|lua_getresult|, | 2064 | \verb|nargs| is the number of arguments that you pushed onto the stack. |
1962 | \Deffunc{lua_getresult} | 2065 | All arguments and the function value are popped from the stack, |
1963 | which is just another name for the function \verb|lua_lua2C|. | 2066 | and the function results are pushed. |
1964 | Note that \verb|lua_callfunction| | 2067 | The number of results are adjusted \see{adjust} to \verb|nresults|, |
1965 | pops all elements from the C2lua stack. | 2068 | unless \verb|nresults| is \IndexVerb{LUA_MULTRET}. |
2069 | In that case, \emph{all} results from the function are pushed. | ||
2070 | The function results are pushed in direct order | ||
2071 | (the first result is pushed first), | ||
2072 | so that after the call the last result is on the top. | ||
1966 | 2073 | ||
1967 | The following example shows how the host program may do the | 2074 | The following example shows how the host program may do the |
1968 | equivalent to the Lua code: | 2075 | equivalent to the Lua code: |
1969 | \begin{verbatim} | 2076 | \begin{verbatim} |
1970 | a,b = f("how", t.x, 4) | 2077 | a,b = f("how", t.x, 4) |
1971 | \end{verbatim} | 2078 | \end{verbatim} |
2079 | Here it is in~C: | ||
1972 | \begin{verbatim} | 2080 | \begin{verbatim} |
1973 | lua_pushstring(L, "how"); /* 1st argument */ | 2081 | lua_getglobal(L, "t"); /* global `t' (for later use) */ |
1974 | lua_pushobject(L, lua_getglobal(L, "t")) /* push value of global 't' */ | 2082 | lua_getglobal(L, "f"); /* function to be called */ |
1975 | lua_pushstring(L, "x"); /* push the string 'x' */ | 2083 | lua_pushstring(L, "how"); /* 1st argument */ |
1976 | lua_pushobject(L, lua_gettable(L)); /* push result of t.x (2nd arg) */ | 2084 | lua_pushstring(L, "x"); /* push the string `x' */ |
1977 | lua_pushnumber(L, 4); /* 3rd argument */ | 2085 | lua_gettable(L, -4); /* push result of t.x (2nd arg) */ |
1978 | lua_callfunction(L, lua_getglobal(L, "f")); /* call `f' */ | 2086 | lua_pushnumber(L, 4); /* 3rd argument */ |
1979 | lua_pushobject(L, lua_getresult(L, 1)); /* push first result of the call */ | 2087 | lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */ |
1980 | lua_setglobal(L, "a"); /* set global variable 'a' */ | 2088 | lua_setglobal(L, "b"); /* set global variable `b' */ |
1981 | lua_pushobject(L, lua_getresult(L, 2)); /* push second result of the call */ | 2089 | lua_setglobal(L, "a"); /* set global variable `a' */ |
1982 | lua_setglobal(L, "b"); /* set global variable 'b' */ | 2090 | lua_pop(L, 1); /* remove `t' from the stack */ |
1983 | \end{verbatim} | 2091 | \end{verbatim} |
2092 | Notice that the code above is ``balanced'': | ||
2093 | at its end the stack is back to its original configuration. | ||
2094 | This is considered good programming practice. | ||
1984 | 2095 | ||
1985 | Some special Lua functions have direct interfaces. | 2096 | Some special Lua functions have their own C~interfaces. |
1986 | The host program can generate a Lua error calling the function | 2097 | The host program can generate a Lua error calling the function |
1987 | \Deffunc{lua_error} | 2098 | \Deffunc{lua_error} |
1988 | \begin{verbatim} | 2099 | \begin{verbatim} |
1989 | void lua_error (lua_State *L, const char *message); | 2100 | void lua_error (lua_State *L, const char *message); |
1990 | \end{verbatim} | 2101 | \end{verbatim} |
1991 | This function never returns. | 2102 | This function never returns. |
1992 | If \verb|lua_error| is called from a C~function that has been called from Lua, | 2103 | If \verb|lua_error| is called from a C~function that has been called from Lua, |
1993 | then the corresponding Lua execution terminates, | 2104 | then the corresponding Lua execution terminates, |
1994 | as if an error had occurred inside Lua code. | 2105 | as if an error had occurred inside Lua code. |
1995 | Otherwise, the whole host program terminates with a call to \verb|exit(1)|. | 2106 | Otherwise, the whole host program terminates with a call to |
2107 | \verb|exit(EXIT_FAILURE)|. | ||
1996 | Before terminating execution, | 2108 | Before terminating execution, |
1997 | the \verb|message| is passed to the error handler function, | 2109 | the \verb|message| is passed to the error handler function, |
1998 | \verb|_ERRORMESSAGE| \see{error}. | 2110 | \verb|_ERRORMESSAGE| \see{error}. |
1999 | If \verb|message| is \verb|NULL|, | 2111 | If \verb|message| is \verb|NULL|, |
2000 | then \verb|_ERRORMESSAGE| is not called. | 2112 | then \verb|_ERRORMESSAGE| is not called. |
2001 | 2113 | ||
2002 | Tag methods can be changed with: \Deffunc{lua_settagmethod} | 2114 | Tag methods can be changed with \Deffunc{lua_settagmethod} |
2003 | \begin{verbatim} | 2115 | \begin{verbatim} |
2004 | lua_Object lua_settagmethod (lua_State *L, int tag, const char *event); | 2116 | void lua_settagmethod (lua_State *L, int tag, const char *event); |
2005 | \end{verbatim} | 2117 | \end{verbatim} |
2006 | The first parameter is the tag, | 2118 | The second parameter is the tag, |
2007 | and the second is the event name \see{tag-method}; | 2119 | and the third is the event name \see{tag-method}; |
2008 | the new method is pushed from C2lua. | 2120 | the new method is popped from the stack, |
2009 | This function returns a \verb|lua_Object|, | 2121 | and the old one is pushed in its place. |
2010 | which is the old tag method value. | 2122 | To just get the current value of a tag method, |
2011 | To get just the current value of a tag method, | ||
2012 | use the function \Deffunc{lua_gettagmethod} | 2123 | use the function \Deffunc{lua_gettagmethod} |
2013 | \begin{verbatim} | 2124 | \begin{verbatim} |
2014 | lua_Object lua_gettagmethod (lua_State *L, int tag, const char *event); | 2125 | void lua_gettagmethod (lua_State *L, int tag, const char *event); |
2015 | \end{verbatim} | 2126 | \end{verbatim} |
2016 | 2127 | ||
2017 | It is also possible to copy all tag methods from one tag | 2128 | It is also possible to copy all tag methods from one tag |
2018 | to another: \Deffunc{lua_copytagmethods} | 2129 | to another: \Deffunc{lua_copytagmethods} |
2019 | \begin{verbatim} | 2130 | \begin{verbatim} |
2020 | int lua_copytagmethods (lua_State *L, int tagto, int tagfrom); | 2131 | int lua_copytagmethods (lua_State *L, int tagto, int tagfrom); |
2021 | \end{verbatim} | 2132 | \end{verbatim} |
2022 | This function returns \verb|tagto|. | 2133 | This function returns \verb|tagto|. |
2023 | 2134 | ||
2024 | You can traverse a table with the function \Deffunc{lua_next} | 2135 | You can traverse a table with the function \Deffunc{lua_next} |
2025 | \begin{verbatim} | 2136 | \begin{verbatim} |
2026 | int lua_next (lua_State *L, lua_Object t, int i); | 2137 | int lua_next (lua_State *L, int index); |
2027 | \end{verbatim} | 2138 | \end{verbatim} |
2028 | Its first argument is the table to be traversed, | 2139 | \verb|index| refers to the table to be traversed. |
2029 | and the second is a \emph{cursor}; | 2140 | The function pops a key from the stack, |
2030 | this cursor starts at 0, | 2141 | and pushes a key-value pair from the table |
2031 | and for each call the function returns a value to | 2142 | (the ``next'' pair after the given key). |
2032 | be used in the next call, | 2143 | If there are no more elements, then the function returns 0 |
2033 | or 0 to signal the end of the traversal. | 2144 | (and pushes nothing). |
2034 | The function also returns, in the lua2C array, | ||
2035 | a key-value pair from the table. | ||
2036 | A typical traversal looks like this: | 2145 | A typical traversal looks like this: |
2037 | \begin{verbatim} | 2146 | \begin{verbatim} |
2038 | int i; | 2147 | /* table is in the stack at index `t' */ |
2039 | lua_Object t; | 2148 | lua_pushnil(L); /* first key */ |
2040 | ... /* gets the table at `t' */ | 2149 | while (lua_next(L, t) != 0) { |
2041 | i = 0; | 2150 | /* `key' is at index -2 and `value' at index -1 */ |
2042 | lua_beginblock(L); | 2151 | printf("%s - %s\n", lua_type(L, -2), lua_type(L, -1)); |
2043 | while ((i = lua_next(L, t, i)) != 0) { | 2152 | lua_pop(L, 1); /* removes `value'; keeps `index' for next iteration */ |
2044 | lua_Object key = lua_getresult(L, 1); | 2153 | } |
2045 | lua_Object value = lua_getresult(L, 2); | 2154 | \end{verbatim} |
2046 | ... /* uses `key' and `value' */ | 2155 | |
2047 | lua_endblock(L); | 2156 | The function \Deffunc{lua_concat} |
2048 | lua_beginblock(L); /* reopens a block */ | 2157 | \begin{verbatim} |
2049 | } | 2158 | void lua_concat (lua_State *L, int n); |
2050 | lua_endblock(L); | 2159 | \end{verbatim} |
2051 | \end{verbatim} | 2160 | concatenates the \verb|n| values at the top of the stack, |
2052 | The pairs of \verb|lua_beginblock|/\verb|lua_endblock| remove the | 2161 | pops them, and leaves the result at the top. |
2053 | results of each iteration from the stack. | 2162 | \verb|n|~must be at least 2. |
2054 | Without them, a traversal of a large table may overflow the stack. | 2163 | Concatenation is done following the usual semantics of Lua |
2164 | \see{concat}. | ||
2055 | 2165 | ||
2056 | 2166 | ||
2057 | \subsection{Defining C Functions} \label{LuacallC} | 2167 | \subsection{Defining C Functions} \label{LuacallC} |
@@ -2059,9 +2169,9 @@ To register a C~function to Lua, | |||
2059 | there is the following convenience macro: | 2169 | there is the following convenience macro: |
2060 | \Deffunc{lua_register} | 2170 | \Deffunc{lua_register} |
2061 | \begin{verbatim} | 2171 | \begin{verbatim} |
2062 | #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) | 2172 | #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) |
2063 | /* const char *n; */ | 2173 | /* const char *n; */ |
2064 | /* lua_CFunction f; */ | 2174 | /* lua_CFunction f; */ |
2065 | \end{verbatim} | 2175 | \end{verbatim} |
2066 | which receives the name the function will have in Lua, | 2176 | which receives the name the function will have in Lua, |
2067 | and a pointer to the function. | 2177 | and a pointer to the function. |
@@ -2069,110 +2179,142 @@ This pointer must have type \verb|lua_CFunction|, | |||
2069 | which is defined as | 2179 | which is defined as |
2070 | \Deffunc{lua_CFunction} | 2180 | \Deffunc{lua_CFunction} |
2071 | \begin{verbatim} | 2181 | \begin{verbatim} |
2072 | typedef void (*lua_CFunction) (lua_State *L); | 2182 | typedef int (*lua_CFunction) (lua_State *L); |
2073 | \end{verbatim} | 2183 | \end{verbatim} |
2074 | that is, a pointer to a function with no results and a single argument, | 2184 | that is, a pointer to a function with integer result and a single argument, |
2075 | a Lua environment. | 2185 | a Lua environment. |
2076 | 2186 | ||
2077 | In order to communicate properly with Lua, | 2187 | In order to communicate properly with Lua, |
2078 | a C~function must follow a protocol, | 2188 | a C~function must follow the following protocol, |
2079 | which defines the way parameters and results are passed. | 2189 | which defines the way parameters and results are passed: |
2080 | 2190 | A C~function receives its arguments from Lua in the stack, | |
2081 | A C~function receives its arguments in structure lua2C; | 2191 | in direct order (first argument is pushed first). |
2082 | to access them, it uses the macro \verb|lua_getparam|, \Deffunc{lua_getparam} | 2192 | To return values to Lua, a C~function just pushes them onto the stack, |
2083 | again just another name for \verb|lua_lua2C|. | 2193 | in direct order, |
2084 | To return values, a C~function just pushes them onto the stack C2lua, | 2194 | %\see{valuesCLua}, |
2085 | in direct order \see{valuesCLua}. | 2195 | and returns the number of results. |
2086 | Like a Lua function, a C~function called by Lua can also return | 2196 | Like a Lua function, a C~function called by Lua can also return |
2087 | many results. | 2197 | many results. |
2088 | 2198 | ||
2199 | As an example, the following function receives a variable number | ||
2200 | of numerical arguments and returns their average and sum: | ||
2201 | \begin{verbatim} | ||
2202 | static int foo (lua_State *L) { | ||
2203 | int n = lua_gettop(L); /* number of arguments */ | ||
2204 | double sum = 0; | ||
2205 | int i; | ||
2206 | for (i = 1; i <= n; i++) { | ||
2207 | if (!lua_isnumber(L, i)) | ||
2208 | lua_error(L, "incorrect argument to function `foo'"); | ||
2209 | sum += lua_tonumber(L, i); | ||
2210 | } | ||
2211 | lua_pushnumber(L, sum/n); /* first result */ | ||
2212 | lua_pushnumber(L, sum); /* second result */ | ||
2213 | return 2; /* number of results */ | ||
2214 | } | ||
2215 | \end{verbatim} | ||
2216 | This function may be registered in Lua as \verb|average| by calling | ||
2217 | \begin{verbatim} | ||
2218 | lua_register(L, "average", foo); | ||
2219 | \end{verbatim} | ||
2220 | |||
2221 | |||
2089 | When a C~function is created, | 2222 | When a C~function is created, |
2090 | it is possible to associate some \emph{upvalues} to it | 2223 | it is possible to associate some \emph{upvalues} to it |
2091 | \see{upvalue}, | 2224 | \see{upvalue}, |
2092 | thus creating a C closure; | 2225 | thus creating a \IndexEmph{C~closure}; |
2093 | these values are passed to the function whenever it is called, | 2226 | these values are passed to the function whenever it is called, |
2094 | as common arguments. | 2227 | as common arguments. |
2095 | To associate upvalues to a C~function, | 2228 | To associate upvalues to a C~function, |
2096 | first these values must be pushed on C2lua. | 2229 | first these values should be pushed onto the stack. |
2097 | Then the function \Deffunc{lua_pushcclosure} | 2230 | Then the function \Deffunc{lua_pushcclosure} |
2098 | \begin{verbatim} | 2231 | \begin{verbatim} |
2099 | void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); | 2232 | void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n); |
2100 | \end{verbatim} | 2233 | \end{verbatim} |
2101 | is used to put the C~function on C2lua, | 2234 | is used to push the C~function onto the stack, |
2102 | with the argument \verb|n| telling how many upvalues must be | 2235 | with the argument \verb|n| telling how many upvalues should be |
2103 | associated with the function; | 2236 | associated with the function |
2237 | (these upvalues are popped from the stack); | ||
2104 | in fact, the macro \verb|lua_pushcfunction| is defined as | 2238 | in fact, the macro \verb|lua_pushcfunction| is defined as |
2105 | \verb|lua_pushcclosure| with \verb|n| set to 0. | 2239 | \verb|lua_pushcclosure| with \verb|n| set to 0. |
2106 | Then, whenever the C~function is called, | 2240 | Then, whenever the C~function is called, |
2107 | these upvalues are inserted as the first arguments \M{n} to the function, | 2241 | these upvalues are inserted as the \emph{last} arguments to the function, |
2108 | before the actual arguments provided in the call. | 2242 | after the actual arguments provided in the call. |
2243 | This makes it easy to get the upvalues without knowing how many arguments | ||
2244 | the function received (recall that functions in Lua can receive any number of | ||
2245 | arguments): The \M{i}-th upvalue is in the stack at index \Math{i-n+1}, | ||
2246 | where \M{n} is the number of upvalues. | ||
2109 | 2247 | ||
2110 | For some examples of C~functions, see files \verb|lstrlib.c|, | 2248 | For more examples of C~functions and closures, see files |
2111 | \verb|liolib.c| and \verb|lmathlib.c| in the official Lua distribution. | 2249 | \verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c| |
2250 | in the official Lua distribution. | ||
2112 | 2251 | ||
2113 | \subsection{References to Lua Objects} | 2252 | \subsection{References to Lua Objects} |
2114 | 2253 | ||
2115 | As noted in \See{GC}, \verb|lua_Object|s are volatile. | 2254 | As noted in \See{GC}, Lua values are volatile. |
2116 | If the C code needs to keep a \verb|lua_Object| | 2255 | If the C~code needs to keep a Lua value |
2117 | outside block boundaries, | 2256 | outside the life span of a C~function, |
2118 | then it must create a \Def{reference} to the object. | 2257 | then it must create a \Def{reference} to the value. |
2119 | The routines to manipulate references are the following: | 2258 | The routines to manipulate references are the following: |
2120 | \Deffunc{lua_ref}\Deffunc{lua_pushref} | 2259 | \Deffunc{lua_ref}\Deffunc{lua_getref} |
2121 | \Deffunc{lua_unref} | 2260 | \Deffunc{lua_unref} |
2122 | \begin{verbatim} | 2261 | \begin{verbatim} |
2123 | int lua_ref (lua_State *L, int lock); | 2262 | int lua_ref (lua_State *L, int lock); |
2124 | int lua_pushref (lua_State *L, int ref); | 2263 | int lua_getref (lua_State *L, int ref); |
2125 | void lua_unref (lua_State *L, int ref); | 2264 | void lua_unref (lua_State *L, int ref); |
2126 | \end{verbatim} | 2265 | \end{verbatim} |
2127 | The function \verb|lua_ref| creates a reference | 2266 | |
2128 | to the object that is on the top of the stack, | 2267 | \verb|lua_ref| pops a value from |
2268 | the stack, creates a reference to it, | ||
2129 | and returns this reference. | 2269 | and returns this reference. |
2130 | For a \nil\ object, | 2270 | For a \nil\ value, |
2131 | the reference is always \verb|LUA_REFNIL|;\Deffunc{LUA_REFNIL} | 2271 | the reference is always \verb|LUA_REFNIL|.\Deffunc{LUA_REFNIL} |
2132 | otherwise, it is a non-negative integer. | ||
2133 | The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF} | 2272 | The constant \verb|LUA_NOREF| \Deffunc{LUA_NOREF} |
2134 | is different from any valid reference. | 2273 | is different from any valid reference. |
2135 | If \verb|lock| is true, then the object is \emph{locked}: | 2274 | If \verb|lock| is true, then the object is \emph{locked}: |
2136 | this means the object will not be garbage collected. | 2275 | this means the object will not be garbage collected. |
2137 | \emph{Unlocked references may be garbage collected}. | 2276 | \emph{Unlocked references may be garbage collected}. |
2277 | |||
2138 | Whenever the referenced object is needed in~C, | 2278 | Whenever the referenced object is needed in~C, |
2139 | a call to \verb|lua_pushref| | 2279 | a call to \verb|lua_getref| |
2140 | pushes that object into the C2lua stack; | 2280 | pushes that object onto the stack; |
2141 | if the object has been collected, | 2281 | if the object has been collected, |
2142 | \verb|lua_getref| returns 0 (and does not push anything). | 2282 | \verb|lua_getref| returns 0 (and does not push anything). |
2143 | 2283 | ||
2144 | When a reference is no longer needed, | 2284 | When a reference is no longer needed, |
2145 | it can be released with a call to \verb|lua_unref|. | 2285 | it should be released with a call to \verb|lua_unref|. |
2146 | |||
2147 | 2286 | ||
2148 | 2287 | ||
2149 | \section{Predefined Functions and Libraries} | ||
2150 | 2288 | ||
2151 | The set of \Index{predefined functions} in Lua is small but powerful. | 2289 | \section{Standard Libraries} |
2152 | Most of them provide features that allow some degree of | ||
2153 | \Index{reflexivity} in the language. | ||
2154 | Some of these features cannot be simulated with the rest of the | ||
2155 | language nor with the standard Lua API. | ||
2156 | Others are just convenient interfaces to common API functions. | ||
2157 | 2290 | ||
2158 | The libraries, on the other hand, provide useful routines | 2291 | The standard libraries provide useful routines |
2159 | that are implemented directly through the standard API. | 2292 | that are implemented directly through the standard API. |
2160 | Therefore, they are not necessary to the language, | 2293 | Therefore, they are not necessary to the language, |
2161 | and are provided as separate C modules. | 2294 | and are provided as separate C~modules. |
2162 | Currently, there are three standard libraries: | 2295 | Currently, Lua has the following standard libraries: |
2163 | \begin{itemize} | 2296 | \begin{itemize} |
2297 | \item basic library; | ||
2164 | \item string manipulation; | 2298 | \item string manipulation; |
2165 | \item mathematical functions (sin, log, etc); | 2299 | \item mathematical functions (sin, log, etc); |
2166 | \item input and output (plus some system facilities). | 2300 | \item input and output (plus some system facilities). |
2167 | \end{itemize} | 2301 | \end{itemize} |
2168 | To have access to these libraries, | 2302 | To have access to these libraries, |
2169 | the C host program must call the functions | 2303 | the C~host program must call the functions |
2304 | \verb|lua_baselibopen|, | ||
2170 | \verb|lua_strlibopen|, \verb|lua_mathlibopen|, | 2305 | \verb|lua_strlibopen|, \verb|lua_mathlibopen|, |
2171 | and \verb|lua_iolibopen|, declared in \verb|lualib.h|. | 2306 | and \verb|lua_iolibopen|, declared in \verb|lualib.h|. |
2172 | \Deffunc{lua_strlibopen}\Deffunc{lua_mathlibopen}\Deffunc{lua_iolibopen} | 2307 | \Deffunc{lua_strlibopen}\Deffunc{lua_mathlibopen}\Deffunc{lua_iolibopen} |
2173 | 2308 | ||
2309 | The basic library provides some core functions to Lua. | ||
2310 | Therefore, if you do not include this library in your application, | ||
2311 | you should check carefully whether you need to provide some alternative | ||
2312 | implementation for some facilities. | ||
2313 | (For instance, without function \verb|_ERRORMESSAGE|, | ||
2314 | defined in the basic library, Lua is unable to show error messages.) | ||
2315 | |||
2174 | 2316 | ||
2175 | \subsection{Predefined Functions} \label{predefined} | 2317 | \subsection{Basic Functions} \label{predefined} |
2176 | 2318 | ||
2177 | \subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} | 2319 | \subsubsection*{\ff \T{_ALERT (message)}}\Deffunc{alert}\label{alert} |
2178 | Prints its only string argument to \IndexVerb{stderr}. | 2320 | Prints its only string argument to \IndexVerb{stderr}. |
@@ -2188,12 +2330,12 @@ Issues an \emph{``assertion failed!''} error | |||
2188 | when its argument \verb|v| is \nil. | 2330 | when its argument \verb|v| is \nil. |
2189 | This function is equivalent to the following Lua function: | 2331 | This function is equivalent to the following Lua function: |
2190 | \begin{verbatim} | 2332 | \begin{verbatim} |
2191 | function assert (v, m) | 2333 | function assert (v, m) |
2192 | if not v then | 2334 | if not v then |
2193 | m = m or "" | 2335 | m = m or "" |
2194 | error("assertion failed! " .. m) | 2336 | error("assertion failed! " .. m) |
2195 | end | 2337 | end |
2196 | end | 2338 | end |
2197 | \end{verbatim} | 2339 | \end{verbatim} |
2198 | 2340 | ||
2199 | \subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call} | 2341 | \subsubsection*{\ff \T{call (func, arg [, mode [, errhandler]])}}\Deffunc{call} |
@@ -2202,26 +2344,10 @@ Calls function \verb|func| with | |||
2202 | the arguments given by the table \verb|arg|. | 2344 | the arguments given by the table \verb|arg|. |
2203 | The call is equivalent to | 2345 | The call is equivalent to |
2204 | \begin{verbatim} | 2346 | \begin{verbatim} |
2205 | func(arg[1], arg[2], ..., arg[n]) | 2347 | func(arg[1], arg[2], ..., arg[n]) |
2206 | \end{verbatim} | 2348 | \end{verbatim} |
2207 | where \verb|n| is the result of \verb|getn(arg)| \see{getn}. | 2349 | where \verb|n| is the result of \verb|getn(arg)| \see{getn}. |
2208 | 2350 | All results from \verb|func| are simply returned by \verb|call|. | |
2209 | By default, | ||
2210 | all results from \verb|func| are simply returned by \verb|call|. | ||
2211 | If the string \verb|mode| contains \verb|"p"|, | ||
2212 | then the results are \emph{packed} in a single table.\index{packed results} | ||
2213 | That is, \verb|call| returns just one table; | ||
2214 | at index \verb|n|, the table has the total number of results | ||
2215 | from the call; | ||
2216 | the first result is at index 1, etc. | ||
2217 | For instance, the following calls produce the following results: | ||
2218 | \begin{verbatim} | ||
2219 | a = call(sin, {5}) --> a = 0.0871557 = sin(5) | ||
2220 | a = call(max, {1,4,5; n=2}) --> a = 4 (only 1 and 4 are arguments) | ||
2221 | a = call(max, {1,4,5; n=2}, "p") --> a = {4; n=1} | ||
2222 | t = {x=1} | ||
2223 | a = call(next, {t,nil;n=2}, "p") --> a={"x", 1; n=2} | ||
2224 | \end{verbatim} | ||
2225 | 2351 | ||
2226 | By default, | 2352 | By default, |
2227 | if an error occurs during the call to \verb|func|, | 2353 | if an error occurs during the call to \verb|func|, |
@@ -2289,8 +2415,8 @@ If \verb|message| is \nil, then the error handler is not called. | |||
2289 | Function \verb|error| never returns. | 2415 | Function \verb|error| never returns. |
2290 | \verb|error| is equivalent to the API function \verb|lua_error|. | 2416 | \verb|error| is equivalent to the API function \verb|lua_error|. |
2291 | 2417 | ||
2292 | \subsubsection*{\ff \T{foreach (table, function)}}\Deffunc{foreach} | 2418 | \subsubsection*{\ff \T{foreach (table, func)}}\Deffunc{foreach} |
2293 | Executes the given \verb|function| over all elements of \verb|table|. | 2419 | Executes the given \verb|func| over all elements of \verb|table|. |
2294 | For each element, the function is called with the index and | 2420 | For each element, the function is called with the index and |
2295 | respective value as arguments. | 2421 | respective value as arguments. |
2296 | If the function returns any non-\nil\ value, | 2422 | If the function returns any non-\nil\ value, |
@@ -2299,22 +2425,20 @@ as the final value of \verb|foreach|. | |||
2299 | 2425 | ||
2300 | This function could be defined in Lua: | 2426 | This function could be defined in Lua: |
2301 | \begin{verbatim} | 2427 | \begin{verbatim} |
2302 | function foreach (t, f) | 2428 | function foreach (t, f) |
2303 | for i, v in t do | 2429 | for i, v in t do |
2304 | local res = f(i, v) | 2430 | local res = f(i, v) |
2305 | if res then return res end | 2431 | if res then return res end |
2306 | end | 2432 | end |
2307 | end | 2433 | end |
2308 | \end{verbatim} | 2434 | \end{verbatim} |
2309 | 2435 | ||
2310 | You may change the \emph{values} of existing | 2436 | The behavior of \verb|foreach| is \emph{undefined} if you change |
2311 | fields in the table during the traversal, | 2437 | the table \verb|_t| during the traversal. |
2312 | but if you create new indices, | ||
2313 | the semantics of \verb|foreach| is undefined. | ||
2314 | 2438 | ||
2315 | 2439 | ||
2316 | \subsubsection*{\ff \T{foreachi (table, function)}}\Deffunc{foreachi} | 2440 | \subsubsection*{\ff \T{foreachi (table, func)}}\Deffunc{foreachi} |
2317 | Executes the given \verb|function| over the | 2441 | Executes the given \verb|func| over the |
2318 | numerical indices of \verb|table|. | 2442 | numerical indices of \verb|table|. |
2319 | For each index, the function is called with the index and | 2443 | For each index, the function is called with the index and |
2320 | respective value as arguments. | 2444 | respective value as arguments. |
@@ -2327,18 +2451,14 @@ as the final value of \verb|foreachi|. | |||
2327 | 2451 | ||
2328 | This function could be defined in Lua: | 2452 | This function could be defined in Lua: |
2329 | \begin{verbatim} | 2453 | \begin{verbatim} |
2330 | function foreachi (t, f) | 2454 | function foreachi (t, f) |
2331 | for i=1,getn(t) do | 2455 | for i=1,getn(t) do |
2332 | local res = f(i, t[i]) | 2456 | local res = f(i, t[i]) |
2333 | if res then return res end | 2457 | if res then return res end |
2334 | end | 2458 | end |
2335 | end | 2459 | end |
2336 | \end{verbatim} | 2460 | \end{verbatim} |
2337 | 2461 | ||
2338 | You may change the \emph{values} of existing fields in the | ||
2339 | table during the traversal, | ||
2340 | but if you create new indices (even non-numeric), | ||
2341 | the semantics of \verb|foreachi| is undefined. | ||
2342 | 2462 | ||
2343 | \subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} | 2463 | \subsubsection*{\ff \T{foreachvar (function)}}\Deffunc{foreachvar} |
2344 | This function is obsolete. | 2464 | This function is obsolete. |
@@ -2360,14 +2480,14 @@ Otherwise, the size is the largest numerical index with a non-nil | |||
2360 | value in the table. | 2480 | value in the table. |
2361 | This function could be defined in Lua: | 2481 | This function could be defined in Lua: |
2362 | \begin{verbatim} | 2482 | \begin{verbatim} |
2363 | function getn (t) | 2483 | function getn (t) |
2364 | if type(t.n) == 'number' then return t.n end | 2484 | if type(t.n) == 'number' then return t.n end |
2365 | local max = 0 | 2485 | local max = 0 |
2366 | for i, _ in t do | 2486 | for i, _ in t do |
2367 | if type(i) == 'number' and i>max then max=i end | 2487 | if type(i) == 'number' and i>max then max=i end |
2368 | end | 2488 | end |
2369 | return max | 2489 | return max |
2370 | end | 2490 | end |
2371 | \end{verbatim} | 2491 | \end{verbatim} |
2372 | 2492 | ||
2373 | \subsubsection*{\ff \T{gettagmethod (tag, event)}} | 2493 | \subsubsection*{\ff \T{gettagmethod (tag, event)}} |
@@ -2375,10 +2495,10 @@ This function could be defined in Lua: | |||
2375 | Returns the current tag method | 2495 | Returns the current tag method |
2376 | for a given pair \M{(tag, event)}. | 2496 | for a given pair \M{(tag, event)}. |
2377 | 2497 | ||
2378 | \subsubsection*{\ff \T{globals ([newtable])}}\Deffunc{globals} | 2498 | \subsubsection*{\ff \T{globals ([table])}}\Deffunc{globals} |
2379 | Returns the current table of globals. | 2499 | Returns the current table of globals. |
2380 | If the argument \verb|newtable| is given, | 2500 | If the argument \verb|table| is given, |
2381 | set this table as the new table of globals. | 2501 | then it sets this table as the table of globals. |
2382 | 2502 | ||
2383 | \subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} | 2503 | \subsubsection*{\ff \T{newtag ()}}\Deffunc{newtag}\label{pdf-newtag} |
2384 | Returns a new tag. | 2504 | Returns a new tag. |
@@ -2395,7 +2515,7 @@ When called with \nil\ as its second argument, | |||
2395 | of the table and its associated value. | 2515 | of the table and its associated value. |
2396 | When called with the last index, | 2516 | When called with the last index, |
2397 | or with \nil\ in an empty table, | 2517 | or with \nil\ in an empty table, |
2398 | it returns \nil. | 2518 | \verb|next| returns \nil. |
2399 | If the second argument is absent, then it is interpreted as \nil. | 2519 | If the second argument is absent, then it is interpreted as \nil. |
2400 | 2520 | ||
2401 | Lua has no declaration of fields; | 2521 | Lua has no declaration of fields; |
@@ -2407,10 +2527,8 @@ The order in which the indices are enumerated is not specified, | |||
2407 | (to traverse a table in numeric order, | 2527 | (to traverse a table in numeric order, |
2408 | use a counter or the function \verb|foreachi|). | 2528 | use a counter or the function \verb|foreachi|). |
2409 | 2529 | ||
2410 | You may change the \emph{values} of existing fields in the | 2530 | The behavior of \verb|next| is \emph{undefined} if you change |
2411 | table during the traversal, | 2531 | the table during the traversal. |
2412 | but if you create new indices, | ||
2413 | the semantics of \verb|next| is undefined. | ||
2414 | 2532 | ||
2415 | \subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} | 2533 | \subsubsection*{\ff \T{nextvar (name)}}\Deffunc{nextvar} |
2416 | This function is obsolete. | 2534 | This function is obsolete. |
@@ -2424,25 +2542,18 @@ but only as a quick way to show a value, | |||
2424 | for instance for debugging. | 2542 | for instance for debugging. |
2425 | See \See{libio} for functions for formatted output. | 2543 | See \See{libio} for functions for formatted output. |
2426 | 2544 | ||
2427 | \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} | ||
2428 | This function is obsolete. | ||
2429 | Use \verb|rawget(globals(), name)| instead. | ||
2430 | |||
2431 | \subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable} | ||
2432 | This function was renamed to \verb|rawget|. | ||
2433 | |||
2434 | \subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget} | 2545 | \subsubsection*{\ff \T{rawget (table, index)}}\Deffunc{rawget} |
2435 | Gets the real value of \verb|table[index]|, | 2546 | Gets the real value of \verb|table[index]|, |
2436 | without invoking any tag method. | 2547 | without invoking any tag method. |
2437 | \verb|table| must be a table, | 2548 | \verb|table| must be a table, |
2438 | and \verb|index| is any value different from \nil. | 2549 | and \verb|index| is any value different from \nil. |
2439 | 2550 | ||
2440 | \subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} | 2551 | \subsubsection*{\ff \T{rawgetglobal (name)}}\Deffunc{rawgetglobal} |
2441 | This function is obsolete. | 2552 | This function is obsolete. |
2442 | Use \verb|rawset(globals(), name, value)| instead. | 2553 | Use \verb|rawget(globals(), name)| instead. |
2443 | 2554 | ||
2444 | \subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} | 2555 | \subsubsection*{\ff \T{rawgettable (table, index)}}\Deffunc{rawgettable} |
2445 | This function was renamed to \verb|rawset|. | 2556 | This function has been renamed to \verb|rawget|. |
2446 | 2557 | ||
2447 | \subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset} | 2558 | \subsubsection*{\ff \T{rawset (table, index, value)}}\Deffunc{rawset} |
2448 | Sets the real value of \verb|table[index]| to \verb|value|, | 2559 | Sets the real value of \verb|table[index]| to \verb|value|, |
@@ -2451,6 +2562,13 @@ without invoking any tag method. | |||
2451 | \verb|index| is any value different from \nil, | 2562 | \verb|index| is any value different from \nil, |
2452 | and \verb|value| is any Lua value. | 2563 | and \verb|value| is any Lua value. |
2453 | 2564 | ||
2565 | \subsubsection*{\ff \T{rawsetglobal (name, value)}}\Deffunc{rawsetglobal} | ||
2566 | This function is obsolete. | ||
2567 | Use \verb|rawset(globals(), name, value)| instead. | ||
2568 | |||
2569 | \subsubsection*{\ff \T{rawsettable (table, index, value)}}\Deffunc{rawsettable} | ||
2570 | This function has been renamed to \verb|rawset|. | ||
2571 | |||
2454 | \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} | 2572 | \subsubsection*{\ff \T{setglobal (name, value)}}\Deffunc{setglobal} |
2455 | Sets the named global variable to the given value, | 2573 | Sets the named global variable to the given value, |
2456 | or calls a tag method for ``setglobal''. | 2574 | or calls a tag method for ``setglobal''. |
@@ -2529,22 +2647,23 @@ This function also sets or increments the field \verb|n| of the table | |||
2529 | to \verb|n+1|. | 2647 | to \verb|n+1|. |
2530 | 2648 | ||
2531 | This function is equivalent to the following Lua function, | 2649 | This function is equivalent to the following Lua function, |
2532 | except that the table accesses are all \emph{raw} (that is, without tag methods): | 2650 | except that the table accesses are all \emph{raw} |
2533 | \begin{verbatim} | 2651 | (that is, without tag methods): |
2534 | function tinsert (t, ...) | 2652 | \begin{verbatim} |
2535 | local pos, value | 2653 | function tinsert (t, ...) |
2536 | local n = getn(t) | 2654 | local pos, value |
2537 | if arg.n == 1 then | 2655 | local n = getn(t) |
2538 | pos, value = n+1, arg[1] | 2656 | if arg.n == 1 then |
2539 | else | 2657 | pos, value = n+1, arg[1] |
2540 | pos, value = arg[1], arg[2] | 2658 | else |
2541 | end | 2659 | pos, value = arg[1], arg[2] |
2542 | t.n = n+1; | 2660 | end |
2543 | for i=n,pos,-1 do | 2661 | t.n = n+1; |
2544 | t[i+1] = t[i] | 2662 | for i=n,pos,-1 do |
2545 | end | 2663 | t[i+1] = t[i] |
2546 | t[pos] = value | 2664 | end |
2547 | end | 2665 | t[pos] = value |
2666 | end | ||
2548 | \end{verbatim} | 2667 | \end{verbatim} |
2549 | 2668 | ||
2550 | \subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove} | 2669 | \subsubsection*{\ff \T{tremove (table [, pos])}}\Deffunc{tremove} |
@@ -2560,20 +2679,21 @@ This function also sets or decrements the field \verb|n| of the table | |||
2560 | to \verb|n-1|. | 2679 | to \verb|n-1|. |
2561 | 2680 | ||
2562 | This function is equivalent to the following Lua function, | 2681 | This function is equivalent to the following Lua function, |
2563 | except that the table accesses are all \emph{raw} (that is, without tag methods): | 2682 | except that the table accesses are all \emph{raw} |
2564 | \begin{verbatim} | 2683 | (that is, without tag methods): |
2565 | function tremove (t, pos) | 2684 | \begin{verbatim} |
2566 | local n = getn(t) | 2685 | function tremove (t, pos) |
2567 | if n<=0 then return end | 2686 | local n = getn(t) |
2568 | pos = pos or n | 2687 | if n<=0 then return end |
2569 | local value = t[pos] | 2688 | pos = pos or n |
2570 | for i=pos,n-1 do | 2689 | local value = t[pos] |
2571 | t[i] = t[i+1] | 2690 | for i=pos,n-1 do |
2572 | end | 2691 | t[i] = t[i+1] |
2573 | t[n] = nil | 2692 | end |
2574 | t.n = n-1 | 2693 | t[n] = nil |
2575 | return value | 2694 | t.n = n-1 |
2576 | end | 2695 | return value |
2696 | end | ||
2577 | \end{verbatim} | 2697 | \end{verbatim} |
2578 | 2698 | ||
2579 | \subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} | 2699 | \subsubsection*{\ff \T{type (v)}}\Deffunc{type}\label{pdf-type} |
@@ -2592,7 +2712,7 @@ and \verb|"userdata"|. | |||
2592 | \subsection{String Manipulation} | 2712 | \subsection{String Manipulation} |
2593 | This library provides generic functions for string manipulation, | 2713 | This library provides generic functions for string manipulation, |
2594 | such as finding and extracting substrings and pattern matching. | 2714 | such as finding and extracting substrings and pattern matching. |
2595 | When indexing a string, the first character is at position~1 | 2715 | When indexing a string in Lua, the first character is at position~1 |
2596 | (not at~0, as in C). | 2716 | (not at~0, as in C). |
2597 | 2717 | ||
2598 | \subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte} | 2718 | \subsubsection*{\ff \T{strbyte (s [, i])}}\Deffunc{strbyte} |
@@ -2604,7 +2724,7 @@ absolute value plus 1. | |||
2604 | Therefore, \Math{-1} points to the last character of \verb|s|. | 2724 | Therefore, \Math{-1} points to the last character of \verb|s|. |
2605 | 2725 | ||
2606 | \NOTE | 2726 | \NOTE |
2607 | \emph{numerical codes are not necessarily portable across platforms}. | 2727 | Numerical codes are not necessarily portable across platforms. |
2608 | 2728 | ||
2609 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar} | 2729 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\Deffunc{strchar} |
2610 | Receives 0 or more integers. | 2730 | Receives 0 or more integers. |
@@ -2613,7 +2733,7 @@ wherein each character has the internal numerical code equal | |||
2613 | to its correspondent argument. | 2733 | to its correspondent argument. |
2614 | 2734 | ||
2615 | \NOTE | 2735 | \NOTE |
2616 | \emph{numerical codes are not necessarily portable across platforms}. | 2736 | Numerical codes are not necessarily portable across platforms. |
2617 | 2737 | ||
2618 | \subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} | 2738 | \subsubsection*{\ff \T{strfind (str, pattern [, init [, plain]])}} |
2619 | \Deffunc{strfind} | 2739 | \Deffunc{strfind} |
@@ -2638,7 +2758,8 @@ with no characters in \verb|pattern| being considered ``magic''. | |||
2638 | \subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen} | 2758 | \subsubsection*{\ff \T{strlen (s)}}\Deffunc{strlen} |
2639 | Receives a string and returns its length. | 2759 | Receives a string and returns its length. |
2640 | The empty string \verb|""| has length 0. | 2760 | The empty string \verb|""| has length 0. |
2641 | Embedded zeros are counted. | 2761 | Embedded zeros are counted, |
2762 | and so \verb|"a\000b\000c"| has length 5. | ||
2642 | 2763 | ||
2643 | \subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower} | 2764 | \subsubsection*{\ff \T{strlower (s)}}\Deffunc{strlower} |
2644 | Receives a string and returns a copy of that string with all | 2765 | Receives a string and returns a copy of that string with all |
@@ -2691,7 +2812,7 @@ and all double quotes, returns, and backslashes in the string | |||
2691 | are correctly escaped when written. | 2812 | are correctly escaped when written. |
2692 | For instance, the call | 2813 | For instance, the call |
2693 | \begin{verbatim} | 2814 | \begin{verbatim} |
2694 | format('%q', 'a string with "quotes" and \n new line') | 2815 | format('%q', 'a string with "quotes" and \n new line') |
2695 | \end{verbatim} | 2816 | \end{verbatim} |
2696 | will produce the string: | 2817 | will produce the string: |
2697 | \begin{verbatim} | 2818 | \begin{verbatim} |
@@ -2719,8 +2840,8 @@ For example, \verb|"%*g"| can be simulated with | |||
2719 | \verb|"%"..width.."g"|. | 2840 | \verb|"%"..width.."g"|. |
2720 | 2841 | ||
2721 | \NOTE | 2842 | \NOTE |
2722 | \emph{Neither the format string nor the string values to be formatted with | 2843 | Neither the format string nor the string values to be formatted with |
2723 | \T{format} can contain embedded zeros.} | 2844 | \T{format} can contain embedded zeros. |
2724 | 2845 | ||
2725 | \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} | 2846 | \subsubsection*{\ff \T{gsub (s, pat, repl [, n])}} |
2726 | \Deffunc{gsub} | 2847 | \Deffunc{gsub} |
@@ -2749,28 +2870,28 @@ For instance, when \verb|n| is 1 only the first occurrence of | |||
2749 | 2870 | ||
2750 | Here are some examples: | 2871 | Here are some examples: |
2751 | \begin{verbatim} | 2872 | \begin{verbatim} |
2752 | x = gsub("hello world", "(%w+)", "%1 %1") | 2873 | x = gsub("hello world", "(%w+)", "%1 %1") |
2753 | --> x="hello hello world world" | 2874 | --> x="hello hello world world" |
2754 | 2875 | ||
2755 | x = gsub("hello world", "(%w+)", "%1 %1", 1) | 2876 | x = gsub("hello world", "(%w+)", "%1 %1", 1) |
2756 | --> x="hello hello world" | 2877 | --> x="hello hello world" |
2757 | 2878 | ||
2758 | x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") | 2879 | x = gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") |
2759 | --> x="world hello Lua from" | 2880 | --> x="world hello Lua from" |
2760 | 2881 | ||
2761 | x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv) | 2882 | x = gsub("home = $HOME, user = $USER", "%$(%w+)", getenv) |
2762 | --> x="home = /home/roberto, user = roberto" (for instance) | 2883 | --> x="home = /home/roberto, user = roberto" (for instance) |
2763 | 2884 | ||
2764 | x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) | 2885 | x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) |
2765 | --> x="4+5 = 9" | 2886 | --> x="4+5 = 9" |
2766 | 2887 | ||
2767 | local t = {name="lua", version="4.0"} | 2888 | local t = {name="lua", version="4.0"} |
2768 | x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) | 2889 | x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) |
2769 | --> x="lua - 4.0" | 2890 | --> x="lua - 4.0" |
2770 | 2891 | ||
2771 | t = {n=0} | 2892 | t = {n=0} |
2772 | gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) | 2893 | gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) |
2773 | --> t={"first", "second", "word"; n=3} | 2894 | --> t={"first", "second", "word"; n=3} |
2774 | \end{verbatim} | 2895 | \end{verbatim} |
2775 | 2896 | ||
2776 | 2897 | ||
@@ -2896,7 +3017,7 @@ Use \verb|%z| instead.} | |||
2896 | 3017 | ||
2897 | \subsection{Mathematical Functions} \label{mathlib} | 3018 | \subsection{Mathematical Functions} \label{mathlib} |
2898 | 3019 | ||
2899 | This library is an interface to some functions of the standard C math library. | 3020 | This library is an interface to some functions of the standard C~math library. |
2900 | In addition, it registers a tag method for the binary operator \verb|^| that | 3021 | In addition, it registers a tag method for the binary operator \verb|^| that |
2901 | returns \Math{x^y} when applied to numbers \verb|x^y|. | 3022 | returns \Math{x^y} when applied to numbers \verb|x^y|. |
2902 | 3023 | ||
@@ -2908,9 +3029,8 @@ The library provides the following functions: | |||
2908 | \Deffunc{frexp}\Deffunc{ldexp} | 3029 | \Deffunc{frexp}\Deffunc{ldexp} |
2909 | \Deffunc{random}\Deffunc{randomseed} | 3030 | \Deffunc{random}\Deffunc{randomseed} |
2910 | \begin{verbatim} | 3031 | \begin{verbatim} |
2911 | abs acos asin atan atan2 ceil cos deg floor log log10 | 3032 | abs acos asin atan atan2 ceil cos deg floor log log10 |
2912 | max min mod rad sin sqrt tan frexp ldexp | 3033 | max min mod rad sin sqrt tan frexp ldexp random randomseed |
2913 | random randomseed | ||
2914 | \end{verbatim} | 3034 | \end{verbatim} |
2915 | plus a global variable \IndexVerb{PI}. | 3035 | plus a global variable \IndexVerb{PI}. |
2916 | Most of them | 3036 | Most of them |
@@ -2999,15 +3119,14 @@ and restores \verb|stdin| as the value of \verb|_INPUT|. | |||
2999 | If this function fails, it returns \nil, | 3119 | If this function fails, it returns \nil, |
3000 | plus a string describing the error. | 3120 | plus a string describing the error. |
3001 | 3121 | ||
3002 | \begin{quotation} | 3122 | \NOTE |
3003 | \noindent | 3123 | (system dependency) |
3004 | \emph{System dependent}: if \verb|filename| starts with a \verb-|-, | 3124 | if \verb|filename| starts with a \verb-|-, |
3005 | then a \Index{piped input} is opened, via function \IndexVerb{popen}. | 3125 | then a \Index{piped input} is opened, via function \IndexVerb{popen}. |
3006 | Not all systems implement pipes. | 3126 | Not all systems implement pipes. |
3007 | Moreover, | 3127 | Moreover, |
3008 | the number of files that can be open at the same time is | 3128 | the number of files that can be open at the same time is |
3009 | usually limited and depends on the system. | 3129 | usually limited and depends on the system. |
3010 | \end{quotation} | ||
3011 | 3130 | ||
3012 | \subsubsection*{\ff \T{writeto (filename)}}\Deffunc{writeto} | 3131 | \subsubsection*{\ff \T{writeto (filename)}}\Deffunc{writeto} |
3013 | 3132 | ||
@@ -3027,15 +3146,14 @@ and restores \verb|stdout| as the value of \verb|_OUTPUT|. | |||
3027 | If this function fails, it returns \nil, | 3146 | If this function fails, it returns \nil, |
3028 | plus a string describing the error. | 3147 | plus a string describing the error. |
3029 | 3148 | ||
3030 | \begin{quotation} | 3149 | \NOTE |
3031 | \noindent | 3150 | (system dependency) |
3032 | \emph{System dependent}: if \verb|filename| starts with a \verb-|-, | 3151 | if \verb|filename| starts with a \verb-|-, |
3033 | then a \Index{piped output} is opened, via function \IndexVerb{popen}. | 3152 | then a \Index{piped input} is opened, via function \IndexVerb{popen}. |
3034 | Not all systems implement pipes. | 3153 | Not all systems implement pipes. |
3035 | Moreover, | 3154 | Moreover, |
3036 | the number of files that can be open at the same time is | 3155 | the number of files that can be open at the same time is |
3037 | usually limited and depends on the system. | 3156 | usually limited and depends on the system. |
3038 | \end{quotation} | ||
3039 | 3157 | ||
3040 | \subsubsection*{\ff \T{appendto (filename)}}\Deffunc{appendto} | 3158 | \subsubsection*{\ff \T{appendto (filename)}}\Deffunc{appendto} |
3041 | 3159 | ||
@@ -3138,6 +3256,13 @@ use \verb|tostring| or \verb|format| before \verb|write|. | |||
3138 | If this function fails, it returns \nil, | 3256 | If this function fails, it returns \nil, |
3139 | plus a string describing the error. | 3257 | plus a string describing the error. |
3140 | 3258 | ||
3259 | \subsection{System Facilities} \label{libiosys} | ||
3260 | |||
3261 | \subsubsection*{\ff \T{clock ()}}\Deffunc{clock} | ||
3262 | |||
3263 | Returns an approximation of the amount of CPU time | ||
3264 | used by the program, in seconds. | ||
3265 | |||
3141 | \subsubsection*{\ff \T{date ([format])}}\Deffunc{date} | 3266 | \subsubsection*{\ff \T{date ([format])}}\Deffunc{date} |
3142 | 3267 | ||
3143 | Returns a string containing date and time | 3268 | Returns a string containing date and time |
@@ -3147,10 +3272,11 @@ When called without arguments, | |||
3147 | it returns a reasonable date and time representation that depends on | 3272 | it returns a reasonable date and time representation that depends on |
3148 | the host system and on the current locale. | 3273 | the host system and on the current locale. |
3149 | 3274 | ||
3150 | \subsubsection*{\ff \T{clock ()}}\Deffunc{clock} | 3275 | \subsubsection*{\ff \T{execute (command)}}\Deffunc{execute} |
3151 | 3276 | ||
3152 | Returns an approximation of the amount of CPU time | 3277 | This function is equivalent to the C~function \verb|system|. |
3153 | used by the program, in seconds. | 3278 | It passes \verb|command| to be executed by an operating system shell. |
3279 | It returns a status code, which is system-dependent. | ||
3154 | 3280 | ||
3155 | \subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit} | 3281 | \subsubsection*{\ff \T{exit ([code])}}\Deffunc{exit} |
3156 | 3282 | ||
@@ -3164,12 +3290,6 @@ The default value for \verb|code| is the success code. | |||
3164 | Returns the value of the process environment variable \verb|varname|, | 3290 | Returns the value of the process environment variable \verb|varname|, |
3165 | or \nil\ if the variable is not defined. | 3291 | or \nil\ if the variable is not defined. |
3166 | 3292 | ||
3167 | \subsubsection*{\ff \T{execute (command)}}\Deffunc{execute} | ||
3168 | |||
3169 | This function is equivalent to the C~function \verb|system|. | ||
3170 | It passes \verb|command| to be executed by an operating system shell. | ||
3171 | It returns a status code, which is system-dependent. | ||
3172 | |||
3173 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} | 3293 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\Deffunc{setlocale} |
3174 | 3294 | ||
3175 | This function is an interface to the ANSI~C function \verb|setlocale|. | 3295 | This function is an interface to the ANSI~C function \verb|setlocale|. |
@@ -3190,15 +3310,14 @@ by means of functions and \emph{hooks}, | |||
3190 | which allows the construction of different | 3310 | which allows the construction of different |
3191 | kinds of debuggers, profilers, and other tools | 3311 | kinds of debuggers, profilers, and other tools |
3192 | that need ``inside information'' from the interpreter. | 3312 | that need ``inside information'' from the interpreter. |
3193 | This interface is declared in the header file \verb|luadebug.h|, | 3313 | This interface is declared in \verb|luadebug.h|. |
3194 | and has \emph{no} single-state variant. | ||
3195 | 3314 | ||
3196 | \subsection{Stack and Function Information} | 3315 | \subsection{Stack and Function Information} |
3197 | 3316 | ||
3198 | \Deffunc{lua_getstack} | 3317 | \Deffunc{lua_getstack} |
3199 | The main function to get information about the interpreter stack is | 3318 | The main function to get information about the interpreter stack is |
3200 | \begin{verbatim} | 3319 | \begin{verbatim} |
3201 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); | 3320 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); |
3202 | \end{verbatim} | 3321 | \end{verbatim} |
3203 | It fills parts of a \verb|lua_Debug| structure with | 3322 | It fills parts of a \verb|lua_Debug| structure with |
3204 | an identification of the \emph{activation record} | 3323 | an identification of the \emph{activation record} |
@@ -3210,29 +3329,30 @@ when called with a level greater than the stack depth, | |||
3210 | it returns 0. | 3329 | it returns 0. |
3211 | 3330 | ||
3212 | \Deffunc{lua_Debug} | 3331 | \Deffunc{lua_Debug} |
3213 | The structure \verb|lua_Debug| is used to carry different pieces of information | 3332 | The structure \verb|lua_Debug| is used to carry different pieces of |
3214 | about an active function: | 3333 | information about an active function: |
3215 | \begin{verbatim} | 3334 | \begin{verbatim} |
3216 | typedef struct lua_Debug { | 3335 | typedef struct lua_Debug { |
3217 | const char *event; /* "call", "return" */ | 3336 | const char *event; /* "call", "return" */ |
3218 | const char *source; /* (S) */ | 3337 | int currentline; /* (l) */ |
3219 | int linedefined; /* (S) */ | 3338 | const char *name; /* (n) */ |
3220 | const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ | 3339 | const char *namewhat; /* (n) global, tag method, local, field */ |
3221 | int currentline; /* (l) */ | 3340 | int nups; /* (u) number of upvalues */ |
3222 | const char *name; /* (n) */ | 3341 | int linedefined; /* (S) */ |
3223 | const char *namewhat; /* (n) global, tag method, local, field */ | 3342 | const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ |
3224 | int nups; /* (u) number of upvalues */ | 3343 | const char *source; /* (S) */ |
3225 | lua_Object func; /* (f) function being executed */ | 3344 | char short_src[LUA_IDSIZE]; /* (S) */ |
3226 | /* private part */ | 3345 | |
3227 | ... | 3346 | /* private part */ |
3228 | } lua_Debug; | 3347 | ... |
3229 | \end{verbatim} | 3348 | } lua_Debug; |
3230 | The \verb|lua_getstack| function fills only the private part | 3349 | \end{verbatim} |
3350 | \verb|lua_getstack| fills only the private part | ||
3231 | of this structure, for future use. | 3351 | of this structure, for future use. |
3232 | To fill in the other fields of \verb|lua_Debug| with useful information, | 3352 | To fill in the other fields of \verb|lua_Debug| with useful information, |
3233 | call \Deffunc{lua_getinfo} | 3353 | call \Deffunc{lua_getinfo} |
3234 | \begin{verbatim} | 3354 | \begin{verbatim} |
3235 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); | 3355 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); |
3236 | \end{verbatim} | 3356 | \end{verbatim} |
3237 | This function returns 0 on error | 3357 | This function returns 0 on error |
3238 | (e.g., an invalid option in \verb|what|). | 3358 | (e.g., an invalid option in \verb|what|). |
@@ -3242,19 +3362,20 @@ as indicated by the letter in parentheses in the definition of \verb|lua_Debug|: | |||
3242 | An \verb|S| fills in the fields \verb|source|, \verb|linedefined|, | 3362 | An \verb|S| fills in the fields \verb|source|, \verb|linedefined|, |
3243 | and \verb|what|; | 3363 | and \verb|what|; |
3244 | \verb|l| fills in the field \verb|currentline|, etc. | 3364 | \verb|l| fills in the field \verb|currentline|, etc. |
3365 | Moreover, character \verb|f| pushes onto the stack the function that is | ||
3366 | running at the given level. | ||
3245 | 3367 | ||
3246 | To get information about a function that is not active (that is, | 3368 | To get information about a function that is not active (that is, |
3247 | it is not in the stack), | 3369 | it is not in the stack), |
3248 | you set the \verb|func| field of the \verb|lua_Debug| structure | 3370 | you push the function onto the stack, |
3249 | with the function, | ||
3250 | and start the \verb|what| string with the character \verb|>|. | 3371 | and start the \verb|what| string with the character \verb|>|. |
3251 | For instance, to know in which line a function \verb|f| was defined, | 3372 | For instance, to know in which line a function \verb|f| was defined, |
3252 | you can write | 3373 | you can write |
3253 | \begin{verbatim} | 3374 | \begin{verbatim} |
3254 | lua_Debug ar; | 3375 | lua_Debug ar; |
3255 | ar.func = lua_getglobal(L, "f"); | 3376 | lua_getglobal(L, "f"); |
3256 | lua_getinfo(L, ">S", &ar); | 3377 | lua_getinfo(L, ">S", &ar); |
3257 | printf("%d\n", ar.linedefined); | 3378 | printf("%d\n", ar.linedefined); |
3258 | \end{verbatim} | 3379 | \end{verbatim} |
3259 | 3380 | ||
3260 | The fields of \verb|lua_Debug| have the following meaning: | 3381 | The fields of \verb|lua_Debug| have the following meaning: |
@@ -3266,6 +3387,9 @@ If the function was defined in a string, | |||
3266 | if the function was defined in a file, | 3387 | if the function was defined in a file, |
3267 | \verb|source| starts with a \verb|@| followed by the file name. | 3388 | \verb|source| starts with a \verb|@| followed by the file name. |
3268 | 3389 | ||
3390 | \item[short_src] | ||
3391 | A ``printable'' version of \verb|source|, to be used in error messages. | ||
3392 | |||
3269 | \item[linedefined] | 3393 | \item[linedefined] |
3270 | the line number where the definition of the function starts. | 3394 | the line number where the definition of the function starts. |
3271 | 3395 | ||
@@ -3304,60 +3428,51 @@ otherwise \verb|namewhat| is \verb|""| (the empty string). | |||
3304 | \item[nups] | 3428 | \item[nups] |
3305 | Number of upvalues of a function. | 3429 | Number of upvalues of a function. |
3306 | 3430 | ||
3307 | \item[func] | ||
3308 | The function being executed, as a \verb|lua_Object|. | ||
3309 | |||
3310 | \end{description} | 3431 | \end{description} |
3311 | 3432 | ||
3312 | 3433 | ||
3313 | \subsection{Manipulating Local Variables} | 3434 | \subsection{Manipulating Local Variables} |
3314 | 3435 | ||
3315 | For the manipulation of local variables, | 3436 | For the manipulation of local variables, |
3316 | \verb|luadebug.h| defines the following record: | 3437 | \verb|luadebug.h| uses indices: |
3317 | \begin{verbatim} | 3438 | The first parameter has index 1, and so on, |
3318 | struct lua_Localvar { | 3439 | until the last active local variable. |
3319 | int index; | ||
3320 | const char *name; | ||
3321 | lua_Object value; | ||
3322 | }; | ||
3323 | \end{verbatim} | ||
3324 | where \verb|index| is an index for local variables | ||
3325 | (the first parameter has index 1, and so on, | ||
3326 | until the last active local variable). | ||
3327 | 3440 | ||
3328 | \Deffunc{lua_getlocal}\Deffunc{lua_setlocal} | 3441 | \Deffunc{lua_getlocal}\Deffunc{lua_setlocal} |
3329 | The following functions allow the manipulation of the | 3442 | The following functions allow the manipulation of the |
3330 | local variables of a given activation record. | 3443 | local variables of a given activation record. |
3331 | \begin{verbatim} | 3444 | \begin{verbatim} |
3332 | int lua_getlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); | 3445 | const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); |
3333 | int lua_setlocal (lua_State *L, const lua_Debug *ar, lua_Localvar *v); | 3446 | const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); |
3334 | \end{verbatim} | 3447 | \end{verbatim} |
3335 | The parameter \verb|ar| must be a valid activation record, | 3448 | The parameter \verb|ar| must be a valid activation record, |
3336 | filled by a previous call to \verb|lua_getstack| or | 3449 | filled by a previous call to \verb|lua_getstack| or |
3337 | given as argument to a hook \see{sub-hooks}. | 3450 | given as argument to a hook \see{sub-hooks}. |
3338 | To use \verb|lua_getlocal|, | 3451 | Function \verb|lua_getlocal| gets the index of a local variable |
3339 | you fill the \verb|index| field of \verb|v| with the index | 3452 | (\verb|n|), pushes its value onto the stack, |
3340 | of a local variable; then the function fills the fields | 3453 | and returns its name. |
3341 | \verb|name| and \verb|value| with the name and the current | ||
3342 | value of that variable. | ||
3343 | For \verb|lua_setlocal|, | 3454 | For \verb|lua_setlocal|, |
3344 | you fill the \verb|index| and the \verb|value| fields of \verb|v|, | 3455 | you push the new value onto the stack, |
3345 | and the function assigns that value to the variable. | 3456 | and the function assigns that value to the variable and returns its name. |
3346 | Both functions return 0 on failure; | 3457 | Both functions return NULL on failure; |
3347 | that happens if the index is greater than the number of active local variables. | 3458 | that happens if the index is greater than |
3459 | the number of active local variables. | ||
3348 | 3460 | ||
3349 | As an example, the following function lists the names of all | 3461 | As an example, the following function lists the names of all |
3350 | local variables for a function in a given level of the stack: | 3462 | local variables for a function in a given level of the stack: |
3351 | \begin{verbatim} | 3463 | \begin{verbatim} |
3352 | int listvars (lua_State *L, int level) { | 3464 | int listvars (lua_State *L, int level) { |
3353 | lua_Debug ar; | 3465 | lua_Debug ar; |
3354 | lua_Localvar v; | 3466 | int i = 1; |
3355 | if (lua_getstack(L, level, &ar) == 0) | 3467 | const char *name; |
3356 | return 0; /* failure: no such level on the stack */ | 3468 | if (lua_getstack(L, level, &ar) == 0) |
3357 | for (v.index = 1; lua_getlocal(L, &ar, &v); v.index++) | 3469 | return 0; /* failure: no such level in the stack */ |
3358 | printf("%s\n", v.name); | 3470 | while ((name = lua_getlocal(L, &ar, i++)) != NULL) { |
3359 | return 1; | 3471 | printf("%s\n", name); |
3360 | } | 3472 | lua_pop(L, 1); /* remove variable value */ |
3473 | } | ||
3474 | return 1; | ||
3475 | } | ||
3361 | \end{verbatim} | 3476 | \end{verbatim} |
3362 | 3477 | ||
3363 | 3478 | ||
@@ -3367,13 +3482,13 @@ The Lua interpreter offers two hooks for debugging purposes: | |||
3367 | a \emph{call} hook and a \emph{line} hook. | 3482 | a \emph{call} hook and a \emph{line} hook. |
3368 | Both have the same type, | 3483 | Both have the same type, |
3369 | \begin{verbatim} | 3484 | \begin{verbatim} |
3370 | typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); | 3485 | typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); |
3371 | \end{verbatim} | 3486 | \end{verbatim} |
3372 | and you can set them with the following functions: | 3487 | and you can set them with the following functions: |
3373 | \Deffunc{lua_Hook}\Deffunc{lua_setcallhook}\Deffunc{lua_setlinehook} | 3488 | \Deffunc{lua_Hook}\Deffunc{lua_setcallhook}\Deffunc{lua_setlinehook} |
3374 | \begin{verbatim} | 3489 | \begin{verbatim} |
3375 | lua_Hook lua_setcallhook (lua_State *L, lua_Hook func); | 3490 | lua_Hook lua_setcallhook (lua_State *L, lua_Hook func); |
3376 | lua_Hook lua_setlinehook (lua_State *L, lua_Hook func); | 3491 | lua_Hook lua_setlinehook (lua_State *L, lua_Hook func); |
3377 | \end{verbatim} | 3492 | \end{verbatim} |
3378 | A hook is disabled when its value is \verb|NULL|, | 3493 | A hook is disabled when its value is \verb|NULL|, |
3379 | which is the initial value of both hooks. | 3494 | which is the initial value of both hooks. |
@@ -3496,14 +3611,14 @@ this function turns off line hooks. | |||
3496 | \section{\Index{Lua Stand-alone}} \label{lua-sa} | 3611 | \section{\Index{Lua Stand-alone}} \label{lua-sa} |
3497 | 3612 | ||
3498 | Although Lua has been designed as an extension language, | 3613 | Although Lua has been designed as an extension language, |
3499 | the language is frequently used as a stand-alone interpreter. | 3614 | it is frequently used as a stand-alone language. |
3500 | An implementation of such an interpreter, | 3615 | An interpreter for Lua as a stand-alone language, |
3501 | called simply \verb|lua|, | 3616 | called simply \verb|lua|, |
3502 | is provided with the standard distribution. | 3617 | is provided with the standard distribution. |
3503 | 3618 | ||
3504 | This program can be called with any sequence of the following arguments: | 3619 | This program can be called with any sequence of the following arguments: |
3505 | \begin{description} | 3620 | \begin{description}\leftskip=20pt |
3506 | \item[\T{-}] executes \verb|stdin| as a file; | 3621 | \item[\T{-} ] executes \verb|stdin| as a file; |
3507 | \item[\T{-c}] calls \verb|lua_close| after running all arguments; | 3622 | \item[\T{-c}] calls \verb|lua_close| after running all arguments; |
3508 | \item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; | 3623 | \item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; |
3509 | \item[\T{-f filename}] executes file \verb|filename| with the | 3624 | \item[\T{-f filename}] executes file \verb|filename| with the |
@@ -3518,49 +3633,54 @@ When called without arguments, | |||
3518 | Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, | 3633 | Lua behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, |
3519 | and as \verb|lua -| otherwise. | 3634 | and as \verb|lua -| otherwise. |
3520 | 3635 | ||
3521 | All arguments are handled in order. | 3636 | All arguments are handled in order, except \verb|-c|. |
3522 | For instance, an invocation like | 3637 | For instance, an invocation like |
3523 | \begin{verbatim} | 3638 | \begin{verbatim} |
3524 | $ lua -i a=test prog.lua | 3639 | $ lua -i a=test prog.lua |
3525 | \end{verbatim} | 3640 | \end{verbatim} |
3526 | will first interact with the user until an \verb|EOF| in \verb|stdin|, | 3641 | will first interact with the user until an \verb|EOF| in \verb|stdin|, |
3527 | then will set \verb|a| to \verb|"test"|, | 3642 | then will set \verb|a| to \verb|"test"|, |
3528 | and finally will run the file \verb|prog.lua|. | 3643 | and finally will run the file \verb|prog.lua|. |
3644 | (Here, | ||
3645 | \verb|$| is the shell prompt. Your prompt may be different.) | ||
3529 | 3646 | ||
3530 | When the option \T{-f filename} is used, | 3647 | When the option \T{-f filename} is used, |
3531 | all following arguments from the command line | 3648 | all remaining arguments in the command line |
3532 | are passed to the Lua program in a table called \verb|arg|. | 3649 | are passed to the Lua program in a table called \verb|arg|. |
3533 | The field \verb|n| gets the index of the last argument, | 3650 | In this table, |
3651 | the field \verb|n| gets the index of the last argument, | ||
3534 | and the field 0 gets the \T{filename}. | 3652 | and the field 0 gets the \T{filename}. |
3535 | For instance, in the call | 3653 | For instance, in the call |
3536 | \begin{verbatim} | 3654 | \begin{verbatim} |
3537 | $ lua a.lua -f b.lua t1 t3 | 3655 | $ lua a.lua -f b.lua t1 t3 |
3538 | \end{verbatim} | 3656 | \end{verbatim} |
3539 | the interpreter first runs the file \T{a.lua}, | 3657 | the interpreter first runs the file \T{a.lua}, |
3540 | then creates a table \T{arg}, | 3658 | then creates a table \T{arg}, |
3541 | \begin{verbatim} | 3659 | \begin{verbatim} |
3542 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} | 3660 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} |
3543 | \end{verbatim} | 3661 | \end{verbatim} |
3544 | and then runs the file \T{b.lua}. | 3662 | and then runs the file \T{b.lua}. |
3663 | \Deffunc{getargs} | ||
3545 | The stand-alone interpreter also provides a \verb|getargs| function that | 3664 | The stand-alone interpreter also provides a \verb|getargs| function that |
3546 | can be used to access \emph{all} command line arguments. | 3665 | can be used to access \emph{all} command line arguments. |
3547 | For instance, if you call Lua with the line | 3666 | For instance, if you call Lua with the line |
3548 | \begin{verbatim} | 3667 | \begin{verbatim} |
3549 | > lua -d a b | 3668 | $ lua -c a b |
3550 | \end{verbatim} | 3669 | \end{verbatim} |
3551 | and the file \verb|a| (or \verb|b|) calls \verb|getargs|, | 3670 | and the file \verb|a| (or \verb|b|) calls \verb|getargs|, |
3552 | the call will return the table | 3671 | the call will return the table |
3553 | \verb|{[0] = "lua", [1] = "-d", [2] = "a", [3] = "b", n = 3}|. | 3672 | \begin{verbatim} |
3554 | \Deffunc{getargs} | 3673 | {[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3} |
3674 | \end{verbatim} | ||
3555 | 3675 | ||
3556 | In interactive mode, | 3676 | In interactive mode, |
3557 | a multi-line statement can be written finishing intermediate | 3677 | a multi-line statement can be written finishing intermediate |
3558 | lines with a backslash (\verb|\|). | 3678 | lines with a backslash (`\verb|\|'). |
3559 | If the global variable \verb|_PROMPT| is defined as a string, | 3679 | If the global variable \verb|_PROMPT| is defined as a string, |
3560 | its value is used as the prompt. \index{_PROMPT} | 3680 | then its value is used as the prompt. \index{_PROMPT} |
3561 | Therefore, the prompt can be changed like below: | 3681 | Therefore, the prompt can be changed directly on the command line: |
3562 | \begin{verbatim} | 3682 | \begin{verbatim} |
3563 | $ lua _PROMPT='myprompt> ' -i | 3683 | $ lua _PROMPT='myprompt> ' -i |
3564 | \end{verbatim} | 3684 | \end{verbatim} |
3565 | 3685 | ||
3566 | In Unix systems, Lua scripts can be made into executable programs | 3686 | In Unix systems, Lua scripts can be made into executable programs |
@@ -3582,21 +3702,25 @@ Lua means ``moon'' in Portuguese. | |||
3582 | \appendix | 3702 | \appendix |
3583 | 3703 | ||
3584 | \section*{Incompatibilities with Previous Versions} | 3704 | \section*{Incompatibilities with Previous Versions} |
3705 | \addcontentsline{toc}{section}{Incompatibilities with Previous Versions} | ||
3585 | 3706 | ||
3586 | Although great care has been taken to avoid incompatibilities with | 3707 | Lua 4.0 is a major revision of the language. |
3708 | We took a great care to avoid incompatibilities with | ||
3587 | the previous public versions of Lua, | 3709 | the previous public versions of Lua, |
3588 | some differences had to be introduced. | 3710 | some differences had to be introduced. |
3589 | Here is a list of all these incompatibilities. | 3711 | Here is a list of all these incompatibilities. |
3590 | 3712 | ||
3713 | |||
3591 | \subsection*{Incompatibilities with \Index{version 3.2}} | 3714 | \subsection*{Incompatibilities with \Index{version 3.2}} |
3592 | 3715 | ||
3593 | \subsubsection*{Changes in the Language} | 3716 | \subsubsection*{Changes in the Language} |
3594 | \begin{itemize} | 3717 | \begin{itemize} |
3595 | 3718 | ||
3596 | \item | 3719 | \item |
3597 | All pragmas (\verb|$debug|, \verb|$if|, \ldots) are deprecated. | 3720 | All pragmas (\verb|$debug|, \verb|$if|, \ldots) have been removed. |
3598 | 3721 | ||
3599 | \item \rwd{for}, \rwd{break}, and \rwd{in} now are reserved words. | 3722 | \item |
3723 | \rwd{for}, \rwd{break}, and \rwd{in} now are reserved words. | ||
3600 | 3724 | ||
3601 | \item | 3725 | \item |
3602 | Garbage-collection tag methods for tables is now deprecated. | 3726 | Garbage-collection tag methods for tables is now deprecated. |
@@ -3607,8 +3731,8 @@ There is now only one tag method for order operators. | |||
3607 | \item | 3731 | \item |
3608 | In nested function calls like \verb|f(g(x))| | 3732 | In nested function calls like \verb|f(g(x))| |
3609 | \emph{all} return values from \verb|g| are passed as arguments to \verb|f|. | 3733 | \emph{all} return values from \verb|g| are passed as arguments to \verb|f|. |
3610 | (This only happens when \verb|g| is the last | 3734 | This only happens when \verb|g| is the last |
3611 | [or the only] argument to \verb|f|.) | 3735 | or the only argument to \verb|f|. |
3612 | 3736 | ||
3613 | \item | 3737 | \item |
3614 | The pre-compiler may assume that some operators are associative, | 3738 | The pre-compiler may assume that some operators are associative, |
@@ -3625,22 +3749,30 @@ have non-associative tag methods. | |||
3625 | \begin{itemize} | 3749 | \begin{itemize} |
3626 | 3750 | ||
3627 | \item | 3751 | \item |
3752 | When traversing a table with \verb|next| or \verb|foreach|, | ||
3753 | the table cannot be modified in any way. | ||
3754 | |||
3755 | \item | ||
3628 | General read patterns are now deprecated. | 3756 | General read patterns are now deprecated. |
3629 | 3757 | ||
3630 | \item | 3758 | \item |
3631 | The functions \verb|rawgettable| and \verb|rawsettable| | 3759 | The functions \verb|rawgettable| and \verb|rawsettable| |
3632 | were renamed to \verb|rawget| and \verb|rawset|. | 3760 | have been renamed to \verb|rawget| and \verb|rawset|. |
3633 | 3761 | ||
3634 | \item | 3762 | \item |
3635 | The functions \verb|foreachvar|, \verb|nextvar|, | 3763 | The functions \verb|foreachvar|, \verb|nextvar|, |
3636 | \verb|rawsetglobal|, and \verb|rawgetglobal| are deprecated. | 3764 | \verb|rawsetglobal|, and \verb|rawgetglobal| are deprecated. |
3637 | You can get their functionality using table operations | 3765 | You can get their functionality using table operations |
3638 | over the table of globals. | 3766 | over the table of globals, |
3767 | which is returned by \verb|globals|. | ||
3639 | 3768 | ||
3640 | \item | 3769 | \item |
3641 | \verb|setglobal| and \verb|sort| no longer return a value; | 3770 | \verb|setglobal| and \verb|sort| no longer return a value; |
3642 | \verb|type| no longer returns a second value. | 3771 | \verb|type| no longer returns a second value. |
3643 | 3772 | ||
3773 | \item | ||
3774 | The \verb|p| option in function \verb|call| is deprecated. | ||
3775 | |||
3644 | \end{itemize} | 3776 | \end{itemize} |
3645 | 3777 | ||
3646 | 3778 | ||
@@ -3648,42 +3780,35 @@ over the table of globals. | |||
3648 | \begin{itemize} | 3780 | \begin{itemize} |
3649 | 3781 | ||
3650 | \item | 3782 | \item |
3651 | The whole API is now reentrant, | 3783 | The API has been completely rewritten: |
3652 | which means that all functions have | 3784 | It is now fully reentrant and much clearer. |
3653 | an extra first argument, a Lua state. | ||
3654 | You can still use the old format: | ||
3655 | If you define \verb|LUA_SINGLESTATE| before including \verb|lua.h|, | ||
3656 | all functions from the old API are defined as macros. | ||
3657 | You will also have to define a variable | ||
3658 | \begin{verbatim} | ||
3659 | lua_State *lua_state = NULL; | ||
3660 | \end{verbatim} | ||
3661 | somewhere in your program. | ||
3662 | 3785 | ||
3663 | \item | 3786 | \item |
3664 | The debug API has been completely rewritten. | 3787 | The debug API has been completely rewritten. |
3665 | 3788 | ||
3666 | \item | 3789 | %\item |
3667 | A \verb|const| qualifier has been added to \verb|char *| | 3790 | %A \verb|const| qualifier has been added to \verb|char*| |
3668 | in all API functions that handle C~strings. | 3791 | %in all API functions that handle C~strings. |
3669 | 3792 | % | |
3670 | \item | 3793 | %\item |
3671 | Some types \verb|long| were changed to \verb|size_t|. | 3794 | %Some variables of type \verb|long| were changed to \verb|size_t|. |
3672 | 3795 | % | |
3673 | \item | 3796 | %\item |
3674 | \verb|luaL_openlib| no longer automatically calls \verb|lua_open|. | 3797 | %\verb|luaL_openlib| no longer automatically calls \verb|lua_open|. |
3675 | So, | 3798 | %So, |
3676 | you must now explicitly call \verb|lua_open| before opening | 3799 | %you must now explicitly call \verb|lua_open| before opening |
3677 | the standard libraries. | 3800 | %the standard libraries. |
3678 | 3801 | % | |
3679 | \item | 3802 | %\item |
3680 | \verb|lua_type| now returns a string describing the type, | 3803 | %\verb|lua_type| now returns a string describing the type, |
3681 | and is no longer a synonym for \verb|lua_tag|. | 3804 | %and is no longer a synonym for \verb|lua_tag|. |
3682 | 3805 | ||
3683 | \end{itemize} | 3806 | \end{itemize} |
3684 | 3807 | ||
3685 | %{=============================================================== | 3808 | %{=============================================================== |
3686 | \section*{The complete syntax of Lua} | 3809 | \section*{The Complete Syntax of Lua} \label{BNF} |
3810 | |||
3811 | \addcontentsline{toc}{section}{The complete syntax of Lua} | ||
3687 | 3812 | ||
3688 | \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} | 3813 | \renewenvironment{Produc}{\vspace{0.8ex}\par\noindent\hspace{3ex}\it\begin{tabular}{rrl}}{\end{tabular}\vspace{0.8ex}\par\noindent} |
3689 | 3814 | ||
@@ -3803,8 +3928,8 @@ and is no longer a synonym for \verb|lua_tag|. | |||
3803 | 3928 | ||
3804 | \newcommand{\indexentry}[2]{\item {#1} #2} | 3929 | \newcommand{\indexentry}[2]{\item {#1} #2} |
3805 | \begin{theindex} | 3930 | \begin{theindex} |
3931 | \addcontentsline{toc}{section}{Index} | ||
3806 | \input{manual.id} | 3932 | \input{manual.id} |
3807 | \end{theindex} | 3933 | \end{theindex} |
3808 | 3934 | ||
3809 | |||
3810 | \end{document} | 3935 | \end{document} |