diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2001-09-24 12:54:36 -0300 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2001-09-24 12:54:36 -0300 |
commit | c44c68450a636647caea90872582e03a30bfb6e4 (patch) | |
tree | 25264a98945539eaf5b3972ab54f3b2b65783d44 | |
parent | abdbe883a86bbc7fbf1d1bfc50756e1b42fc45b5 (diff) | |
download | lua-c44c68450a636647caea90872582e03a30bfb6e4.tar.gz lua-c44c68450a636647caea90872582e03a30bfb6e4.tar.bz2 lua-c44c68450a636647caea90872582e03a30bfb6e4.zip |
changes by lhf
-rw-r--r-- | manual.tex | 1808 |
1 files changed, 1010 insertions, 798 deletions
@@ -1,21 +1,24 @@ | |||
1 | % $Id: manual.tex,v 1.50 2001/07/19 13:36:18 roberto Exp roberto $ | 1 | % $Id: manual.tex,v 1.51 2001/07/24 17:25:03 roberto Exp roberto $ |
2 | 2 | ||
3 | \documentclass[11pt]{article} | 3 | \documentclass[11pt,twoside,draft]{article} |
4 | \usepackage{fullpage} | 4 | \usepackage{fullpage} |
5 | \usepackage{bnf} | 5 | \usepackage{bnf} |
6 | \usepackage{graphicx} | 6 | \usepackage{graphicx} |
7 | %\usepackage{times} | ||
8 | 7 | ||
8 | % no need for subscripts... | ||
9 | \catcode`\_=12 | 9 | \catcode`\_=12 |
10 | 10 | ||
11 | %\newcommand{\See}[1]{Section~\ref{#1}} | 11 | %\newcommand{\See}[1]{Section~\ref{#1}} |
12 | \newcommand{\See}[1]{\S\ref{#1}} | 12 | \newcommand{\See}[1]{\S\ref{#1}} |
13 | %\newcommand{\see}[1]{(see~\See{#1} on page \pageref{#1})} | ||
13 | \newcommand{\see}[1]{(see~\See{#1})} | 14 | \newcommand{\see}[1]{(see~\See{#1})} |
15 | \newcommand{\seepage}[1]{(see page~\pageref{#1})} | ||
14 | \newcommand{\M}[1]{{\rm\emph{#1}}} | 16 | \newcommand{\M}[1]{{\rm\emph{#1}}} |
15 | \newcommand{\T}[1]{{\tt #1}} | 17 | \newcommand{\T}[1]{{\tt #1}} |
16 | \newcommand{\Math}[1]{$#1$} | 18 | \newcommand{\Math}[1]{$#1$} |
17 | \newcommand{\nil}{{\bf nil}} | 19 | \newcommand{\nil}{{\bf nil}} |
18 | \def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} | 20 | %\def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} |
21 | \def\tecgraf{{\sf TeCGraf}} | ||
19 | 22 | ||
20 | \newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}} | 23 | \newcommand{\Index}[1]{#1\index{#1@{\lowercase{#1}}}} |
21 | \newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}} | 24 | \newcommand{\IndexVerb}[1]{\T{#1}\index{#1@{\tt #1}}} |
@@ -26,12 +29,16 @@ | |||
26 | \newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}} | 29 | \newcommand{\IndexLIB}[1]{\T{#1}\DefLIB{#1}} |
27 | \newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}} | 30 | \newcommand{\DefLIB}[1]{\index{#1@{\tt #1}}} |
28 | \newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}} | 31 | \newcommand{\DefAPI}[1]{\index{C API!#1@{\tt #1}}} |
32 | \newcommand{\IndexKW}[1]{\index{keywords!#1@{\tt #1}}} | ||
29 | 33 | ||
30 | \newcommand{\ff}{$\bullet$\ } | 34 | \newcommand{\ff}{$\bullet$\ } |
31 | 35 | ||
32 | \newcommand{\Version}{4.1 (alpha)} | 36 | \newcommand{\Version}{4.1 (alpha)} |
33 | 37 | ||
34 | % LHF | 38 | % changes to bnf.sty by LHF |
39 | \renewcommand{\Or}{$|$ } | ||
40 | \renewcommand{\rep}[1]{{\rm\{}\,#1\,{\rm\}}} | ||
41 | \renewcommand{\opt}[1]{{\rm [}\,#1\,{\,\rm]}} | ||
35 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} | 42 | \renewcommand{\ter}[1]{{\rm`{\tt#1}'}} |
36 | \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } | 43 | \newcommand{\NOTE}{\par\medskip\noindent\emph{NOTE}: } |
37 | 44 | ||
@@ -67,16 +74,16 @@ Last revised on \today | |||
67 | \newpage | 74 | \newpage |
68 | \begin{quotation} | 75 | \begin{quotation} |
69 | \parskip=10pt | 76 | \parskip=10pt |
77 | \parindent=0pt | ||
70 | \footnotesize | 78 | \footnotesize |
71 | \null\vfill | 79 | \null\vfill |
72 | 80 | ||
73 | \noindent | 81 | \noindent |
74 | Copyright \copyright\ 1994--2001 TeCGraf, PUC-Rio. All rights reserved. | 82 | Copyright \copyright\ 1994--2001 TeCGraf, PUC-Rio. All rights reserved. |
75 | 83 | ||
76 | \noindent | ||
77 | Permission is hereby granted, without written agreement and without license | 84 | Permission is hereby granted, without written agreement and without license |
78 | or royalty fees, to use, copy, modify, translate, and distribute | 85 | or royalty fees, to use, copy, modify, translate, and distribute |
79 | this software and its documentation (hereby called the "package") | 86 | this software and its documentation (hereby called the ``package'') |
80 | for any purpose, including commercial applications, subject to | 87 | for any purpose, including commercial applications, subject to |
81 | the following conditions: | 88 | the following conditions: |
82 | \begin{itemize} | 89 | \begin{itemize} |
@@ -93,27 +100,24 @@ the following conditions: | |||
93 | \end{itemize} | 100 | \end{itemize} |
94 | The authors specifically disclaim any warranties, including, but not limited | 101 | The authors specifically disclaim any warranties, including, but not limited |
95 | to, the implied warranties of merchantability and fitness for a particular | 102 | to, the implied warranties of merchantability and fitness for a particular |
96 | purpose. The package provided hereunder is on an ``as is'' basis, and the | 103 | purpose. The package provided hereunder is on an ``as~is'' basis, and the |
97 | authors have no obligation to provide maintenance, support, updates, | 104 | authors have no obligation to provide maintenance, support, updates, |
98 | enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the | 105 | enhancements, or modifications. In no event shall TeCGraf, PUC-Rio, or the |
99 | authors be held liable to any party for direct, indirect, special, | 106 | authors be held liable to any party for direct, indirect, special, |
100 | incidental, or consequential damages arising out of the use of this package | 107 | incidental, or consequential damages arising out of the use of this package |
101 | and its documentation. | 108 | and its documentation. |
102 | 109 | ||
103 | \noindent | ||
104 | The Lua language and this implementation have been entirely designed and | 110 | The Lua language and this implementation have been entirely designed and |
105 | written by Waldemar Celes, Roberto Ierusalimschy, and Luiz Henrique de | 111 | written by Waldemar Celes, Roberto Ierusalimschy, and Luiz Henrique de |
106 | Figueiredo at TeCGraf, PUC-Rio in Brazil. | 112 | Figueiredo at TeCGraf, PUC-Rio in Brazil. |
107 | 113 | ||
108 | \noindent | ||
109 | This implementation contains no third-party code. | 114 | This implementation contains no third-party code. |
110 | 115 | ||
111 | \noindent | ||
112 | Copies of this manual can be obtained at | 116 | Copies of this manual can be obtained at |
113 | \verb|http://www.lua.org|. | 117 | Lua's official web site, |
118 | \verb|www.lua.org|. | ||
114 | 119 | ||
115 | \bigskip | 120 | \bigskip |
116 | \noindent | ||
117 | The Lua logo was designed by A. Nakonechny. | 121 | The Lua logo was designed by A. Nakonechny. |
118 | Copyright \copyright\ 1998. All rights reserved. | 122 | Copyright \copyright\ 1998. All rights reserved. |
119 | \end{quotation} | 123 | \end{quotation} |
@@ -123,8 +127,8 @@ Copyright \copyright\ 1998. All rights reserved. | |||
123 | \title{\Large\bf Reference Manual of the Programming Language Lua \Version} | 127 | \title{\Large\bf Reference Manual of the Programming Language Lua \Version} |
124 | 128 | ||
125 | \author{% | 129 | \author{% |
126 | Roberto Ierusalimschy\quad | 130 | Roberto Ierusalimschy\qquad |
127 | Luiz Henrique de Figueiredo\quad | 131 | Luiz Henrique de Figueiredo\qquad |
128 | Waldemar Celes | 132 | Waldemar Celes |
129 | \vspace{1.0ex}\\ | 133 | \vspace{1.0ex}\\ |
130 | \smallskip | 134 | \smallskip |
@@ -134,7 +138,7 @@ Waldemar Celes | |||
134 | \tecgraf\ --- Computer Science Department --- PUC-Rio | 138 | \tecgraf\ --- Computer Science Department --- PUC-Rio |
135 | } | 139 | } |
136 | 140 | ||
137 | \date{{\small \tt\$Date: 2001/07/19 13:36:18 $ $}} | 141 | %\date{{\small \tt\$Date: 2001/07/24 17:25:03 $ $}} |
138 | 142 | ||
139 | \maketitle | 143 | \maketitle |
140 | 144 | ||
@@ -202,7 +206,7 @@ a intera\c{c}\~ao entre programas Lua e programas C~hospedeiros. | |||
202 | \pagestyle{plain} | 206 | \pagestyle{plain} |
203 | \pagenumbering{arabic} | 207 | \pagenumbering{arabic} |
204 | 208 | ||
205 | 209 | %------------------------------------------------------------------------------ | |
206 | \section{Introduction} | 210 | \section{Introduction} |
207 | 211 | ||
208 | Lua is an extension programming language designed to support | 212 | Lua is an extension programming language designed to support |
@@ -210,33 +214,29 @@ general procedural programming with data description | |||
210 | facilities. | 214 | facilities. |
211 | Lua is intended to be used as a powerful, light-weight | 215 | Lua is intended to be used as a powerful, light-weight |
212 | configuration language for any program that needs one. | 216 | configuration language for any program that needs one. |
213 | |||
214 | Lua is implemented as a library, written in C. | 217 | Lua is implemented as a library, written in C. |
218 | |||
215 | Being an extension language, Lua has no notion of a ``main'' program: | 219 | Being an extension language, Lua has no notion of a ``main'' program: |
216 | it only works \emph{embedded} in a host client, | 220 | it only works \emph{embedded} in a host client, |
217 | called the \emph{embedding} program. | 221 | called the \emph{embedding program} or simply the \emph{host}. |
218 | This host program can invoke functions to execute a piece of | 222 | This host program can invoke functions to execute a piece of Lua code, |
219 | code in Lua, can write and read Lua variables, | 223 | can write and read Lua variables, |
220 | and can register C~functions to be called by Lua code. | 224 | and can register C~functions to be called by Lua code. |
221 | Through the use of C~functions, Lua can be augmented to cope with | 225 | Through the use of C~functions, Lua can be augmented to cope with |
222 | a wide range of different domains, | 226 | a wide range of different domains, |
223 | thus creating customized programming languages sharing a syntactical framework. | 227 | thus creating customized programming languages sharing a syntactical framework. |
224 | 228 | ||
225 | Lua is free-distribution software, | 229 | Lua is free software, |
226 | and is provided as usual with no guarantees, | 230 | and is provided as usual with no guarantees, |
227 | as stated in its copyright notice. | 231 | as stated in its copyright notice. |
228 | The implementation described in this manual is available | 232 | The implementation described in this manual is available |
229 | at the following URL's: | 233 | at Lua's official web site, \verb|www.lua.org|. |
230 | \begin{verbatim} | ||
231 | http://www.lua.org | ||
232 | ftp://ftp.lua.org | ||
233 | \end{verbatim} | ||
234 | 234 | ||
235 | Like any other reference manual, | 235 | Like any other reference manual, |
236 | this document is dry in places. | 236 | this document is dry in places. |
237 | For a discussion of the decisions behind the design of Lua, | 237 | For a discussion of the decisions behind the design of Lua, |
238 | see the papers below, | 238 | see the papers below, |
239 | which are available at the web site above. | 239 | which are available at Lua's web site. |
240 | \begin{itemize} | 240 | \begin{itemize} |
241 | \item | 241 | \item |
242 | R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes. | 242 | R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes. |
@@ -250,14 +250,29 @@ The design and implementation of a language for extending applications. | |||
250 | L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes. | 250 | L.~H.~de Figueiredo, R.~Ierusalimschy, and W.~Celes. |
251 | Lua: an extensible embedded language. | 251 | Lua: an extensible embedded language. |
252 | \emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33. | 252 | \emph{Dr. Dobb's Journal} {\bf 21} \#12 (Dec 1996) 26--33. |
253 | \item | ||
254 | R.~Ierusalimschy, L.~H.~de Figueiredo, and W.~Celes. | ||
255 | The evolution of an extension language: a history of Lua, | ||
256 | \emph{Proceedings of V Brazilian Symposium on Programming Languages} (2001) B-14--B-28. | ||
253 | \end{itemize} | 257 | \end{itemize} |
254 | 258 | ||
255 | \section{Environment and Chunks} | 259 | %------------------------------------------------------------------------------ |
260 | \section{Lua Concepts}\label{concepts} | ||
261 | |||
262 | This section describes the main concepts of Lua as a language. | ||
263 | The syntax and semantics of Lua are described in \See{language}. | ||
264 | The discussion below is not purely conceptual; | ||
265 | it includes references to the C~API \see{API}, | ||
266 | because Lua is designed to be embedded in host programs. | ||
267 | It also includes references to the standard libraries \see{libraries}. | ||
268 | |||
269 | |||
270 | \subsection{Environment and Chunks} | ||
256 | 271 | ||
257 | All statements in Lua are executed in a \Def{global environment}. | 272 | All statements in Lua are executed in a \Def{global environment}. |
258 | This environment is initialized with a call from the embedding program to | 273 | This environment is initialized with a call from the embedding program to |
259 | \verb|lua_open| and | 274 | \verb|lua_open| and |
260 | persists until a call to \verb|lua_close|, | 275 | persists until a call to \verb|lua_close| |
261 | or the end of the embedding program. | 276 | or the end of the embedding program. |
262 | If necessary, | 277 | If necessary, |
263 | the host programmer can create multiple independent global | 278 | the host programmer can create multiple independent global |
@@ -266,34 +281,17 @@ environments, and freely switch between them \see{mangstate}. | |||
266 | The global environment can be manipulated by Lua code or | 281 | The global environment can be manipulated by Lua code or |
267 | by the embedding program, | 282 | by the embedding program, |
268 | which can read and write global variables | 283 | which can read and write global variables |
269 | using API functions from the library that implements Lua. | 284 | using the API functions from the library that implements Lua. |
270 | |||
271 | \Index{Global variables} in Lua do not need to be declared. | ||
272 | Any variable is assumed to be global unless explicitly declared local | ||
273 | \see{localvar}. | ||
274 | Before the first assignment, the value of a global variable is \nil\ % | ||
275 | (this default can be changed; see \See{tag-method}). | ||
276 | A table is used to keep all global names and values | ||
277 | (tables are explained in \See{TypesSec}). | ||
278 | 285 | ||
279 | The unit of execution of Lua is called a \Def{chunk}. | 286 | The unit of execution of Lua is called a \Def{chunk}. |
280 | A chunk is simply a sequence of statements, | 287 | A chunk is simply a sequence of statements, |
281 | which are executed sequentially. | 288 | which are executed sequentially. |
282 | Each statement can be optionally followed by a semicolon: | ||
283 | \begin{Produc} | ||
284 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} | ||
285 | \end{Produc}% | ||
286 | Statements are described in \See{stats}. | 289 | Statements are described in \See{stats}. |
287 | (The notation above is the usual extended BNF, | ||
288 | in which | ||
289 | \rep{\emph{a}} means 0 or more \emph{a}'s, | ||
290 | \opt{\emph{a}} means an optional \emph{a}, and | ||
291 | \oneormore{\emph{a}} means one or more \emph{a}'s. | ||
292 | The complete syntax of Lua is given on page~\pageref{BNF}.) | ||
293 | 290 | ||
294 | A chunk may be stored in a file or in a string inside the host program. | 291 | A chunk may be stored in a file or in a string inside the host program. |
295 | When a chunk is executed, first it is pre-compiled into bytecodes for | 292 | When a chunk is executed, first it is pre-compiled into bytecodes for |
296 | a virtual machine, and then the statements are executed in sequential order, | 293 | a virtual machine, |
294 | and then the compiled statements are executed in sequential order, | ||
297 | by simulating the virtual machine. | 295 | by simulating the virtual machine. |
298 | All modifications a chunk effects on the global environment persist | 296 | All modifications a chunk effects on the global environment persist |
299 | after the chunk ends. | 297 | after the chunk ends. |
@@ -301,38 +299,39 @@ after the chunk ends. | |||
301 | Chunks may also be pre-compiled into binary form and stored in files; | 299 | Chunks may also be pre-compiled into binary form and stored in files; |
302 | see program \IndexVerb{luac} for details. | 300 | see program \IndexVerb{luac} for details. |
303 | Text files with chunks and their binary pre-compiled forms | 301 | Text files with chunks and their binary pre-compiled forms |
304 | are interchangeable. | 302 | are interchangeable; |
305 | Lua automatically detects the file type and acts accordingly. | 303 | Lua automatically detects the file type and acts accordingly. |
306 | \index{pre-compilation} | 304 | \index{pre-compilation} |
307 | 305 | ||
308 | 306 | ||
309 | \section{\Index{Types and Tags}} \label{TypesSec} | 307 | \subsection{\Index{Values and Types}} \label{TypesSec} |
310 | 308 | ||
311 | Lua is a \emph{dynamically typed language}. | 309 | Lua is a \emph{dynamically typed language}. |
312 | This means that | 310 | This means that |
313 | variables do not have types; only values do. | 311 | variables do not have types; only values do. |
314 | Therefore, there are no type definitions in the language. | 312 | Therefore, there are no type definitions in the language. |
315 | All values carry their own type. | 313 | All values carry their own type. |
316 | Besides a type, all values also have a \IndexEmph{tag}. | 314 | Besides a type, all values also have a tag \see{tags}. |
317 | 315 | ||
318 | There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, | 316 | There are six \Index{basic types} in Lua: \Def{nil}, \Def{number}, |
319 | \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. | 317 | \Def{string}, \Def{function}, \Def{userdata}, and \Def{table}. |
320 | \emph{Nil} is the type of the value \nil, | 318 | \emph{Nil} is the type of the value \nil, |
321 | whose main property is to be different from any other value. | 319 | whose main property is to be different from any other value. |
322 | \emph{Number} represents real (double-precision floating-point) numbers, | 320 | \emph{Number} represents real |
323 | while \emph{string} has the usual meaning. | 321 | %(double-precision floating-point) |
322 | numbers. | ||
323 | \emph{String} represents arrays of characters. | ||
324 | \index{eight-bit clean} | 324 | \index{eight-bit clean} |
325 | Lua is 8-bit clean, | 325 | Lua is 8-bit clean, |
326 | and so strings may contain any 8-bit character, | 326 | and so strings may contain any 8-bit character, |
327 | including embedded zeros (\verb|'\0'|) \see{lexical}. | 327 | including embedded zeros (\verb|'\0'|) \see{lexical}. |
328 | The \verb|type| function returns a string describing the type | ||
329 | of a given value \see{pdf-type}. | ||
330 | 328 | ||
331 | Functions are considered \emph{first-class values} in Lua. | 329 | Functions are considered \emph{first-class values} in Lua. |
332 | This means that functions can be stored in variables, | 330 | This means that functions can be stored in variables, |
333 | passed as arguments to other functions, and returned as results. | 331 | passed as arguments to other functions, and returned as results. |
334 | Lua can call (and manipulate) functions written in Lua and | 332 | Lua can call (and manipulate) functions written in Lua and |
335 | functions written in C. | 333 | functions written in C |
334 | \see{functioncall}. | ||
336 | 335 | ||
337 | The type \emph{userdata} is provided to allow | 336 | The type \emph{userdata} is provided to allow |
338 | arbitrary \Index{C~pointers} to be stored in Lua variables. | 337 | arbitrary \Index{C~pointers} to be stored in Lua variables. |
@@ -340,135 +339,198 @@ This type corresponds to a \verb|void*| | |||
340 | and has no pre-defined operations in Lua, | 339 | and has no pre-defined operations in Lua, |
341 | except assignment and equality test. | 340 | except assignment and equality test. |
342 | However, by using \emph{tag methods}, | 341 | However, by using \emph{tag methods}, |
343 | the programmer can define operations for \emph{userdata} values | 342 | the programmer can define operations for userdata values |
344 | \see{tag-method}. | 343 | \see{tag-method}. |
344 | Userdata values cannot be created or modified in Lua, | ||
345 | only through the C~API. | ||
346 | This guarantees the integrity of data owned by the host program. | ||
345 | 347 | ||
346 | The type \emph{table} implements \Index{associative arrays}, | 348 | The type \emph{table} implements \Index{associative arrays}, |
347 | that is, \Index{arrays} that can be indexed not only with numbers, | 349 | that is, \Index{arrays} that can be indexed not only with numbers, |
348 | but with any value (except \nil). | 350 | but with any value (except \nil). |
349 | Therefore, this type may be used not only to represent ordinary arrays, | 351 | Moreover, |
352 | tables are \emph{heterogeneous}, | ||
353 | that is, they can contain values of all types. | ||
354 | Tables are the main data structuring mechanism in Lua; | ||
355 | they may be used not only to represent ordinary arrays, | ||
350 | but also symbol tables, sets, records, graphs, trees, etc. | 356 | but also symbol tables, sets, records, graphs, trees, etc. |
351 | Tables are the main data structuring mechanism in Lua. | ||
352 | To represent \Index{records}, Lua uses the field name as an index. | 357 | To represent \Index{records}, Lua uses the field name as an index. |
353 | The language supports this representation by | 358 | The language supports this representation by |
354 | providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. | 359 | providing \verb|a.name| as syntactic sugar for \verb|a["name"]|. |
355 | Tables may also carry \emph{methods}: | 360 | There are several convenient ways to create tables in Lua |
356 | Because functions are first class values, | 361 | \see{tableconstructor}. |
362 | |||
363 | Like indices, the value of a table field can be of any type. | ||
364 | In particular, | ||
365 | because functions are first class values, | ||
357 | table fields may contain functions. | 366 | table fields may contain functions. |
367 | So, tables may also carry \emph{methods}. | ||
358 | The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, | 368 | The form \verb|t:f(x)| is syntactic sugar for \verb|t.f(t,x)|, |
359 | which calls the method \verb|f| from the table \verb|t| passing | 369 | which calls the method \verb|f| from the table \verb|t| passing |
360 | the table itself as the first parameter \see{func-def}. | 370 | the table itself as the first parameter \see{func-def}. |
361 | 371 | ||
362 | Note that tables are \emph{objects}, and not values. | 372 | Strings, tables, functions, and userdata values are \emph{objects}: |
363 | Variables do not contain tables, only \emph{references} to them. | 373 | variables do not actually \emph{contain} these values, |
364 | Assignment, parameter passing, and returns always manipulate references | 374 | only \emph{references} to them. |
365 | to tables, and do not imply any kind of copy. | 375 | Assignment, parameter passing, and returns from functions |
366 | Moreover, tables must be explicitly created before used | 376 | always manipulate references to these values, and do not imply any kind of copy. |
367 | \see{tableconstructor}. | ||
368 | 377 | ||
378 | The library function \verb|type| returns a string describing the type | ||
379 | of a given value \see{pdf-type}. | ||
380 | |||
381 | |||
382 | \subsection{\Index{Coercion}} \label{coercion} | ||
383 | |||
384 | Lua provides automatic conversion between string and number values at run time. | ||
385 | Any arithmetic operation applied to a string tries to convert | ||
386 | that string to a number, following the usual rules. | ||
387 | Conversely, whenever a number is used when a string is expected, | ||
388 | the number is converted to a string, in a reasonable format. | ||
389 | The format is chosen so that | ||
390 | a conversion from number to string then back to number | ||
391 | reproduces the original number \emph{exactly}. | ||
392 | The conversion does not necessarily produces nice-looking text for some numbers. | ||
393 | For complete control of how numbers are converted to strings, | ||
394 | use the \verb|format| function \see{format}. | ||
395 | |||
396 | |||
397 | \subsection{Variables} | ||
398 | |||
399 | There are two kinds of variables in Lua: | ||
400 | global variables | ||
401 | and local variables. | ||
402 | \Index{Global variables} do not need to be declared. | ||
403 | Variables are assumed to be global unless explicitly declared local | ||
404 | \see{localvar}. | ||
405 | Before the first assignment, the value of a variable is \nil\ % | ||
406 | (this default can be changed for global variables; see \See{tag-method}). | ||
369 | 407 | ||
370 | \subsection{Tags} | 408 | An ordinary Lua table is used to keep all global names and values. |
409 | This table can be accessed and changed with the \verb|globals| function | ||
410 | \see{pdf-globals}. | ||
411 | |||
412 | |||
413 | \subsection{Tags}\label{tags} | ||
371 | 414 | ||
372 | Each type has a \emph{name}, | 415 | Each type has a \emph{name}, |
373 | and a numerical identifier, | 416 | which is a string, |
374 | called a \Index{tag}. | 417 | and a \IndexEmph{tag}, |
375 | Tags are mainly used by C code, | 418 | which is an integer. |
419 | Tags are mainly used by C~code, | ||
376 | to avoid the manipulation of strings. | 420 | to avoid the manipulation of strings. |
377 | Most operations over types, in the C API, | 421 | In the C~API, |
378 | require a tag to identify the type. | 422 | most operations over types require a tag to identify the type. |
379 | In Lua, all operations over types work | 423 | In Lua, all operations over types work transparently |
380 | both with type names or tags. | 424 | with both type names and tags. |
425 | The \verb|tag| function returns the tag of a given value \see{pdf-tag}. | ||
381 | 426 | ||
382 | 427 | ||
383 | \subsection{User-defined Types} | 428 | \subsection{User-defined Types} |
384 | 429 | ||
385 | Lua programs can create new types, | 430 | Lua programs can create new types, |
386 | called \Index{User-defined Types}. | 431 | called \IndexEmph{user-defined types}. |
387 | A user-defined type is always based on a base type, | 432 | A user-defined type is always based on a base type, |
388 | either a table or a userdata. | 433 | which can be either table or userdata. |
389 | Objects of an extended type have an internal structure | 434 | Objects of a user-defined type have an internal structure |
390 | identical to the corresponding base type, | 435 | identical to the corresponding base type, |
391 | but may have diferent semantics for each operation. | 436 | but the programmer may define different semantics for each operation on them |
437 | \see{tag-method}. | ||
392 | 438 | ||
393 | The \verb|newtype| function creates a new type \see{pdf-newtype}. | 439 | The \verb|newtype| function creates a new type \see{pdf-newtype} |
394 | Types created by Lua programs are always based upon tables; | 440 | with a name selected by the programmer. |
395 | types created by C can be based upon tables or upon userdata. | 441 | Types created by Lua programs are always based on tables; |
442 | types created in~C can be based on tables or on userdata. | ||
396 | The \verb|settagmethod| function defines new semantics for | 443 | The \verb|settagmethod| function defines new semantics for |
397 | the operations of this new type \see{tag-method}. | 444 | the operations of this new type \see{tag-method}. |
398 | The \verb|settype| function changes the type of a given object | 445 | The \verb|settype| function changes the type of a given object |
399 | \see{pdf-settype}. | 446 | \see{pdf-settype}. |
400 | 447 | ||
401 | 448 | ||
402 | \section{Garbage Collection}\label{GC} | 449 | \subsection{Garbage Collection}\label{GC} |
403 | 450 | ||
404 | Lua does automatic memory management. | 451 | Lua does automatic memory management. |
405 | To do that, | 452 | This means that |
406 | Lua runs a \Index{garbage collector} from time to time. | 453 | you do not have to worry about allocating memory for new objects |
407 | All objects in Lua are subjected to automatic management: | 454 | and freeing it when the objects are no longer needed. |
455 | Lua manages memory automatically by running | ||
456 | a \Index{garbage collector} from time to time | ||
457 | and | ||
458 | collecting all ``dead'' objects | ||
459 | (essentially, all objects that are no longer accessible from Lua | ||
460 | as the value of a global variable or table field). | ||
461 | All objects in Lua are subject to automatic management: | ||
408 | tables, userdata, functions, and strings. | 462 | tables, userdata, functions, and strings. |
409 | 463 | ||
464 | Using the C~API, | ||
465 | you can set garbage-collector tag methods for user-defined | ||
466 | types based on userdata \see{tag-method}. | ||
467 | Lua calls those functions when it is about to free a userdata | ||
468 | of the corresponding type. | ||
469 | Using this facility, you can coordinate Lua's garbage collection | ||
470 | with external resource management | ||
471 | (such as closing files, network or database connections, | ||
472 | or freeing your own memory). | ||
473 | |||
410 | Lua uses two numbers to control its garbage-collection cycles. | 474 | Lua uses two numbers to control its garbage-collection cycles. |
411 | One number counts how many bytes of dynamic memory Lua is using, | 475 | One number counts how many bytes of dynamic memory Lua is using, |
412 | and the other is a threshold. | 476 | and the other is a threshold. |
413 | When the number of bytes crosses the threshold, | 477 | When the number of bytes crosses the threshold, |
414 | Lua runs the garbage collector, | 478 | Lua runs the garbage collector, |
415 | which reclaims the memory of all ``dead'' objects | 479 | which reclaims the memory of all ``dead'' objects. |
416 | (that is, objects no longer accessible from Lua). | ||
417 | The byte counter is corrected, | 480 | The byte counter is corrected, |
418 | and then the threshold is reset to twice the value of the byte counter. | 481 | and then the threshold is reset to twice the value of the byte counter. |
419 | 482 | ||
420 | Through the C API, you can consult those numbers, | 483 | Through the C~API, you can query those numbers, |
421 | and change the threshold \see{GC-API}. | 484 | and change the threshold \see{GC-API}. |
422 | Setting the threshold to zero actually forces an immediate | 485 | Setting the threshold to zero actually forces an immediate |
423 | garbage-collection cycle, | 486 | garbage-collection cycle, |
424 | while setting it to a huge number stops the garbage collector. | 487 | while setting it to a huge number effectively stops the garbage collector. |
425 | Using Lua code you have a more limited control of memory management, | 488 | Using Lua code you have a more limited control over garbage-collection cycles, |
426 | through functions \verb|gcinfo| and \verb|collectgarbage|. | 489 | through the functions \verb|gcinfo| and \verb|collectgarbage| |
427 | 490 | \see{predefined}. | |
428 | |||
429 | You can set garbage-collector tag methods for user-defined | ||
430 | types based on userdata \see{tag-method}. | ||
431 | Lua calls those functions when it is about to free a userdata | ||
432 | of the corresponding type. | ||
433 | Using this facility, you can coordinate Lua's garbage collection | ||
434 | with external resourse management | ||
435 | (such as closing files or freeing your own memory). | ||
436 | 491 | ||
437 | 492 | ||
438 | \subsection{Weak Tables}\label{weak-table} | 493 | \subsection{Weak Tables}\label{weak-table} |
439 | 494 | ||
440 | A \IndexEmph{weak table} is a table whose elements are | 495 | A \IndexEmph{weak table} is a table whose elements are |
441 | \IndexEmph{weak references}. | 496 | \IndexEmph{weak references}. |
442 | A weak reference is ignored by the garbage collector, | 497 | A weak reference is ignored by the garbage collector. |
443 | so that if the only references to an object are weak references, | 498 | In other words, |
444 | the garbage collector will collect that object. | 499 | if the only references to an object are weak references, |
500 | then the garbage collector will collect that object. | ||
445 | 501 | ||
446 | A weak table can have weak keys, weak values, or both. | 502 | A weak table can have weak keys, weak values, or both. |
447 | A table with weak keys allows the collection of its keys, | 503 | A table with weak keys allows the collection of its keys, |
448 | but avoids the collection of its values. | 504 | but prevents the collection of its values. |
449 | A table with both weak keys and weak values allow the collection of both. | 505 | A table with both weak keys and weak values allows the collection of |
506 | both keys and values | ||
450 | In any case, if either the key or the value is collected, | 507 | In any case, if either the key or the value is collected, |
451 | the whole pair is removed from the table. | 508 | the whole pair is removed from the table. |
452 | The weakness of a table is controled by the | 509 | The weakness of a table is controled by the |
453 | function \verb|weakmode| \see{weakmode}. | 510 | \verb|weakmode| function \see{weakmode}. |
454 | 511 | ||
455 | 512 | ||
456 | \section{The Language} | 513 | %------------------------------------------------------------------------------ |
514 | \section{The Language}\label{language} | ||
457 | 515 | ||
458 | This section describes the lexis, the syntax, and the semantics of Lua. | 516 | This section describes the lexis, the syntax, and the semantics of Lua. |
459 | 517 | In other words, | |
518 | this section describes | ||
519 | which tokens are valid, | ||
520 | how they can be combined, | ||
521 | and what their combinations mean. | ||
460 | 522 | ||
461 | \subsection{Lexical Conventions} \label{lexical} | 523 | \subsection{Lexical Conventions} \label{lexical} |
462 | 524 | ||
463 | \IndexEmph{Identifiers} in Lua can be any string of letters, | 525 | \IndexEmph{Identifiers} in Lua can be any string of letters, |
464 | digits, and underscores, | 526 | digits, and underscores, |
465 | not beginning with a digit. | 527 | not beginning with a digit. |
466 | This coincides with the definition of identifiers in most languages, | 528 | This coincides with the definition of identifiers in most languages. |
467 | except that | 529 | (The definition of letter depends on the current locale: |
468 | the definition of letter depends on the current locale: | 530 | any character considered alphabetic by the current locale |
469 | Any character considered alphabetic by the current locale | 531 | can be used in an identifier.) |
470 | can be used in an identifier. | 532 | |
471 | The following words are \emph{reserved}, | 533 | The following \IndexEmph{keywords} are reserved, |
472 | and cannot be used as identifiers: | 534 | and cannot be used as identifiers: |
473 | \index{reserved words} | 535 | \index{reserved words} |
474 | \begin{verbatim} | 536 | \begin{verbatim} |
@@ -477,21 +539,25 @@ and cannot be used as identifiers: | |||
477 | in local nil not or | 539 | in local nil not or |
478 | repeat return then until while | 540 | repeat return then until while |
479 | \end{verbatim} | 541 | \end{verbatim} |
480 | (\rwd{global} is reserved for future use.) | 542 | (The keyword \rwd{global} is reserved for future use.) |
543 | %\IndexKW{and}\IndexKW{break}\IndexKW{do}\IndexKW{else}\IndexKW{elseif} | ||
544 | %\IndexKW{end}\IndexKW{for}\IndexKW{function}\IndexKW{global}\IndexKW{if} | ||
545 | %\IndexKW{in}\IndexKW{local}\IndexKW{nil}\IndexKW{not}\IndexKW{or} | ||
546 | %\IndexKW{repeat}\IndexKW{return}\IndexKW{then}\IndexKW{until}\IndexKW{while} | ||
481 | 547 | ||
482 | Lua is a case-sensitive language: | 548 | Lua is a case-sensitive language: |
483 | \T{and} is a reserved word, but \T{And} and \T{\'and} | 549 | \T{and} is a reserved word, but \T{And} and \T{\'and} |
484 | (if the locale permits) are two different, valid identifiers. | 550 | (if the locale permits) are two different, valid identifiers. |
485 | As a convention, identifiers starting with underscore followed by | 551 | As a convention, identifiers starting with an underscore followed by |
486 | uppercase letters (such as \verb|_INPUT|) | 552 | uppercase letters (such as \verb|_INPUT|) |
487 | are reserved for internal variables. | 553 | are reserved for internal variables. |
488 | 554 | ||
489 | The following strings denote other \Index{tokens}: | 555 | The following strings denote other \Index{tokens}: |
490 | \begin{verbatim} | 556 | \begin{verbatim} |
491 | + - * / ^ % | 557 | + - * / ^ % |
492 | ~= <= >= < > == = | 558 | ~= <= >= < > == = |
493 | ( ) { } [ ] | 559 | ( ) { } [ ] |
494 | ; : , . .. ... | 560 | ; : , . .. ... |
495 | \end{verbatim} | 561 | \end{verbatim} |
496 | 562 | ||
497 | \IndexEmph{Literal strings} | 563 | \IndexEmph{Literal strings} |
@@ -515,17 +581,20 @@ where \emph{ddd} is a sequence of up to three \emph{decimal} digits. | |||
515 | Strings in Lua may contain any 8-bit value, including embedded zeros, | 581 | Strings in Lua may contain any 8-bit value, including embedded zeros, |
516 | which can be specified as `\verb|\000|'. | 582 | which can be specified as `\verb|\000|'. |
517 | 583 | ||
518 | Literal strings can also be delimited by matching \verb|[[| \dots\ \verb|]]|. | 584 | Literal strings can also be delimited by matching \verb|[[| $\ldots$ \verb|]]|. |
519 | Literals in this bracketed form may run for several lines, | 585 | Literals in this bracketed form may run for several lines, |
520 | may contain nested \verb|[[| \dots\ \verb|]]| pairs, | 586 | may contain nested \verb|[[| $\ldots$ \verb|]]| pairs, |
521 | and do not interpret escape sequences. | 587 | and do not interpret escape sequences. |
522 | When the \verb|[[| is immediatly followed by a newline, | 588 | For convenience, |
589 | when the opening \verb|[[| is immediately followed by a newline, | ||
523 | this newline is not included in the string. | 590 | this newline is not included in the string. |
524 | This form is specially convenient for | 591 | This form is specially convenient for |
525 | writing strings that contain program pieces or | 592 | writing strings that contain program pieces or |
526 | other quoted strings. | 593 | other quoted strings. |
527 | As an example, in a system using ASCII, | 594 | As an example, in a system using ASCII |
528 | the following three literals are equivalent: | 595 | (in which |
596 | `\verb|a|' is coded as~97, newline is coded as~10, and `\verb|1|' is coded as~49), | ||
597 | the following four literals below are equivalent: | ||
529 | \begin{verbatim} | 598 | \begin{verbatim} |
530 | 1) "alo\n123\"" | 599 | 1) "alo\n123\"" |
531 | 2) '\97lo\10\04923"' | 600 | 2) '\97lo\10\04923"' |
@@ -536,13 +605,6 @@ the following three literals are equivalent: | |||
536 | 123"]] | 605 | 123"]] |
537 | \end{verbatim} | 606 | \end{verbatim} |
538 | 607 | ||
539 | \IndexEmph{Comments} start anywhere outside a string with a | ||
540 | double hyphen (\verb|--|) and run until the end of the line. | ||
541 | Moreover, | ||
542 | the first line of a chunk is skipped if it starts with \verb|#|. | ||
543 | This facility allows the use of Lua as a script interpreter | ||
544 | in Unix systems \see{lua-sa}. | ||
545 | |||
546 | \IndexEmph{Numerical constants} may be written with an optional decimal part | 608 | \IndexEmph{Numerical constants} may be written with an optional decimal part |
547 | and an optional decimal exponent. | 609 | and an optional decimal exponent. |
548 | Examples of valid numerical constants are | 610 | Examples of valid numerical constants are |
@@ -550,21 +612,57 @@ Examples of valid numerical constants are | |||
550 | 3 3.0 3.1416 314.16e-2 0.31416E1 | 612 | 3 3.0 3.1416 314.16e-2 0.31416E1 |
551 | \end{verbatim} | 613 | \end{verbatim} |
552 | 614 | ||
553 | \subsection{\Index{Coercion}} \label{coercion} | 615 | \IndexEmph{Comments} start anywhere outside a string with a |
616 | double hyphen (\verb|--|) and run until the end of the line. | ||
617 | (There are no block comments in Lua.) | ||
618 | For convenience, | ||
619 | the first line of a chunk is skipped if it starts with \verb|#|. | ||
620 | This facility allows the use of Lua as a script interpreter | ||
621 | in Unix systems \see{lua-sa}. | ||
554 | 622 | ||
555 | Lua provides some automatic conversions between values at run time. | ||
556 | Any arithmetic operation applied to a string tries to convert | ||
557 | that string to a number, following the usual rules. | ||
558 | Conversely, whenever a number is used when a string is expected, | ||
559 | that number is converted to a string, in a reasonable format. | ||
560 | The format is chosen so that | ||
561 | a conversion from number to string then back to number | ||
562 | reproduces the original number \emph{exactly}. | ||
563 | Thus, | ||
564 | the conversion does not necessarily produces nice-looking text for some numbers. | ||
565 | For complete control of how numbers are converted to strings, | ||
566 | use the \verb|format| function \see{format}. | ||
567 | 623 | ||
624 | \subsection{Variables}\label{variables} | ||
625 | |||
626 | Variables are places that store values. | ||
627 | In Lua, variables are given by simple identifiers or by table fields. | ||
628 | |||
629 | A single name can denote a global variable, a local variable, | ||
630 | or a formal parameter in a function | ||
631 | (formal parameters are just local variables): | ||
632 | \begin{Produc} | ||
633 | \produc{var}{name} | ||
634 | \end{Produc}% | ||
635 | |||
636 | Square brackets are used to index a table: | ||
637 | \begin{Produc} | ||
638 | \produc{var}{exp \ter{[} exp \ter{]}} | ||
639 | \end{Produc}% | ||
640 | The first expression should result in a table value, | ||
641 | from where the field given by the second expression gets the assigned value. | ||
642 | |||
643 | The syntax \verb|var.NAME| is just syntactic sugar for | ||
644 | \verb|var["NAME"]|: | ||
645 | \begin{Produc} | ||
646 | \produc{var}{exp \ter{.} name} | ||
647 | \end{Produc}% | ||
648 | Expressions are discussed in \See{expressions}. | ||
649 | |||
650 | The meaning of assignments and evaluations of global variables and | ||
651 | indexed variables can be changed by tag methods \see{tag-method}. | ||
652 | An assignment to a global variable \verb|x = val| | ||
653 | is equivalent to a call \verb|setglobal("x", val)| and | ||
654 | an assignment to an indexed variable \verb|t[i] = val| is equivalent to | ||
655 | \verb|settable_event(t,i,val)|. | ||
656 | An access to a global variable \verb|x| | ||
657 | is equivalent to a call \verb|getglobal("x")| and | ||
658 | an access to an indexed variable \verb|t[i]| is equivalent to | ||
659 | a call \verb|gettable_event(t,i)|. | ||
660 | Of course, | ||
661 | \verb|i| and \verb|val| can be complicated expressions. | ||
662 | See \See{tag-method} for a complete description of these functions | ||
663 | (\verb|setglobal| and \verb|getglobal| are in the basic library; | ||
664 | \T{settable\_event} and \T{gettable\_event} | ||
665 | are used for explanatory purposes only). | ||
568 | 666 | ||
569 | 667 | ||
570 | \subsection{Statements}\label{stats} | 668 | \subsection{Statements}\label{stats} |
@@ -577,6 +675,25 @@ Non-conventional commands include table constructors | |||
577 | \see{tableconstructor} | 675 | \see{tableconstructor} |
578 | and local variable declarations \see{localvar}. | 676 | and local variable declarations \see{localvar}. |
579 | 677 | ||
678 | \subsubsection{Chunks}\label{chunks} | ||
679 | The unit of execution of Lua is called a \Def{chunk}. | ||
680 | A chunk is simply a sequence of statements, | ||
681 | which are executed sequentially. | ||
682 | Each statement can be optionally followed by a semicolon: | ||
683 | \begin{Produc} | ||
684 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} | ||
685 | \end{Produc}% | ||
686 | |||
687 | The notation used above is the usual extended BNF, | ||
688 | in which | ||
689 | \rep{\emph{a}}~means 0 or more \emph{a}'s, and | ||
690 | \opt{\emph{a}}~means an optional \emph{a}. | ||
691 | Non-terminals are shown in \emph{italics}, | ||
692 | keywords are shown in {\bf bold}, | ||
693 | and other terminal symbols are shown in {\tt typewriter} font, | ||
694 | enclosed in single quotes. | ||
695 | The complete syntax of Lua in EBNF is given on page~\pageref{BNF}. | ||
696 | |||
580 | \subsubsection{Blocks} | 697 | \subsubsection{Blocks} |
581 | A \Index{block} is a list of statements; | 698 | A \Index{block} is a list of statements; |
582 | syntactically, a block is equal to a chunk: | 699 | syntactically, a block is equal to a chunk: |
@@ -603,70 +720,43 @@ The elements in both lists are separated by commas: | |||
603 | \begin{Produc} | 720 | \begin{Produc} |
604 | \produc{stat}{varlist1 \ter{=} explist1} | 721 | \produc{stat}{varlist1 \ter{=} explist1} |
605 | \produc{varlist1}{var \rep{\ter{,} var}} | 722 | \produc{varlist1}{var \rep{\ter{,} var}} |
723 | \produc{explist1}{exp \rep{\ter{,} exp}} | ||
606 | \end{Produc}% | 724 | \end{Produc}% |
725 | Expressions are discussed in \See{expressions}. | ||
726 | |||
727 | Before the assignment, | ||
728 | the list of values is \emph{adjusted} to the length of | ||
729 | the list of variables.\index{adjustment} | ||
730 | If there are more values than are needed, | ||
731 | the excess values are thrown away. | ||
732 | If there are less values than are needed, | ||
733 | the list is extended with as many \nil's as needed. | ||
734 | If the list of expressions ends with a function call, | ||
735 | then all values returned by that function call enter in the list of values, | ||
736 | before the adjust | ||
737 | (except when the call is enclosed in parentheses; see \See{expressions}). | ||
738 | |||
607 | This statement first evaluates all values on the right side | 739 | This statement first evaluates all values on the right side |
608 | and eventual indices on the left side, | 740 | and eventual indices on the left side, |
609 | and then makes the assignments. | 741 | and then makes the assignments. |
610 | So, the code | 742 | So, the code |
611 | \begin{verbatim} | 743 | \begin{verbatim} |
612 | i = 3 | 744 | i = 3 |
613 | i, a[i] = 4, 20 | 745 | i, a[i] = i+1, 20 |
614 | \end{verbatim} | 746 | \end{verbatim} |
615 | sets \verb|a[3]| to 20, but does not affect \verb|a[4]| | 747 | sets \verb|a[3]| to 20, but does not affect \verb|a[4]| |
616 | because the \verb|i| in \verb|a[i]| is evaluated | 748 | because the \verb|i| in \verb|a[i]| is evaluated |
617 | before it is assigned \verb|4|. | 749 | before it is assigned 4. |
618 | 750 | ||
619 | Multiple assignment can be used to exchange two values, as in | 751 | Multiple assignment can be used to exchange two values, as in |
620 | \begin{verbatim} | 752 | \begin{verbatim} |
621 | x, y = y, x | 753 | x, y = y, x |
622 | \end{verbatim} | 754 | \end{verbatim} |
623 | 755 | ||
624 | Before the assignment, the list of values is adjusted to | ||
625 | the length of the list of variables. | ||
626 | If there are more values than are needed, | ||
627 | the excess values are thrown away. | ||
628 | If there are less values than are needed, | ||
629 | the list is extended with as many \nil's as needed. | ||
630 | If the list of expressions (\M{explist1}) ends with a function call, | ||
631 | all values returned by the function call enter in the list of values, | ||
632 | before the adjust. | ||
633 | |||
634 | A single name can denote a global variable, a local variable, | ||
635 | or a formal parameter: | ||
636 | \begin{Produc} | ||
637 | \produc{var}{name} | ||
638 | \end{Produc}% | ||
639 | |||
640 | Square brackets are used to index a table: | ||
641 | \begin{Produc} | ||
642 | \produc{var}{exp \ter{[} exp \ter{]}} | ||
643 | \end{Produc}% | ||
644 | The first expression (\M{exp}) should result in a table value, | ||
645 | from where the field indexed by the expression \M{exp} | ||
646 | value gets the assigned value. | ||
647 | |||
648 | The syntax \verb|var.NAME| is just syntactic sugar for | ||
649 | \verb|var["NAME"]|: | ||
650 | \begin{Produc} | ||
651 | \produc{var}{exp \ter{.} name} | ||
652 | \end{Produc}% | ||
653 | |||
654 | The meaning of assignments and evaluations of global variables and | ||
655 | indexed variables can be changed by tag methods \see{tag-method}. | ||
656 | Actually, | ||
657 | an assignment \verb|x = val|, where \verb|x| is a global variable, | ||
658 | is equivalent to a call \verb|setglobal("x", val)| and | ||
659 | an assignment \verb|t[i] = val| is equivalent to | ||
660 | \verb|settable_event(t,i,val)|. | ||
661 | See \See{tag-method} for a complete description of these functions | ||
662 | (\verb|setglobal| is in the basic library; | ||
663 | \T{settable\_event} is used for explanatory purposes only). | ||
664 | |||
665 | \subsubsection{Control Structures}\label{control} | 756 | \subsubsection{Control Structures}\label{control} |
666 | The control structures | 757 | The control structures |
667 | \rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and | 758 | \rwd{if}, \rwd{while}, and \rwd{repeat} have the usual meaning and |
668 | familiar syntax | 759 | familiar syntax: |
669 | %(there is also a \rwd{for} statement; see \See{for}): | ||
670 | \index{while-do statement} | 760 | \index{while-do statement} |
671 | \index{repeat-until statement} | 761 | \index{repeat-until statement} |
672 | \index{if-then-else statement} | 762 | \index{if-then-else statement} |
@@ -677,6 +767,8 @@ familiar syntax | |||
677 | \rep{\rwd{elseif} exp \rwd{then} block} | 767 | \rep{\rwd{elseif} exp \rwd{then} block} |
678 | \opt{\rwd{else} block} \rwd{end}} | 768 | \opt{\rwd{else} block} \rwd{end}} |
679 | \end{Produc}% | 769 | \end{Produc}% |
770 | There is also a \rwd{for} statement in two flavors \see{for}. | ||
771 | |||
680 | The \Index{condition expression} \M{exp} of a | 772 | The \Index{condition expression} \M{exp} of a |
681 | control structure may return any value. | 773 | control structure may return any value. |
682 | All values different from \nil\ are considered true; | 774 | All values different from \nil\ are considered true; |
@@ -686,41 +778,51 @@ The \rwd{return} statement is used to return values | |||
686 | from a function or from a chunk. | 778 | from a function or from a chunk. |
687 | \label{return}% | 779 | \label{return}% |
688 | \index{return statement}% | 780 | \index{return statement}% |
689 | Because functions or chunks may return more than one value, | 781 | Functions and chunks may return more than one value, |
690 | the syntax for the \rwd{return} statement is | 782 | and so the syntax for the \rwd{return} statement is |
691 | \begin{Produc} | 783 | \begin{Produc} |
692 | \produc{stat}{\rwd{return} \opt{explist1}} | 784 | \produc{stat}{\rwd{return} \opt{explist1}} |
693 | \end{Produc}% | 785 | \end{Produc}% |
694 | 786 | ||
695 | The \rwd{break} statement can be used to terminate the execution of a loop, | 787 | The \rwd{break} statement can be used to terminate the execution of a |
788 | \rwd{while}, \rwd{repeat}, or \rwd{for} loop, | ||
696 | skipping to the next statement after the loop: | 789 | skipping to the next statement after the loop: |
697 | \index{break statement} | 790 | \index{break statement} |
698 | \begin{Produc} | 791 | \begin{Produc} |
699 | \produc{stat}{\rwd{break}} | 792 | \produc{stat}{\rwd{break}} |
700 | \end{Produc}% | 793 | \end{Produc}% |
701 | A \rwd{break} ends the innermost enclosing loop | 794 | A \rwd{break} ends the innermost enclosing loop. |
702 | (\rwd{while}, \rwd{repeat}, or \rwd{for}). | ||
703 | 795 | ||
704 | \NOTE | 796 | \NOTE |
705 | For syntactic reasons, \rwd{return} and \rwd{break} | 797 | For syntactic reasons, \rwd{return} and \rwd{break} |
706 | statements can only be written as the \emph{last} statements of a block. | 798 | statements can only be written as the \emph{last} statements of a block. |
707 | If it is really necessary to \rwd{return} or \rwd{break} in the | 799 | If it is really necessary to \rwd{return} or \rwd{break} in the |
708 | middle of a block, | 800 | middle of a block, |
709 | an explicit inner block can used, | 801 | then an explicit inner block can used, |
710 | as in the idiom `\verb|do return end|', | 802 | as in the idioms |
711 | because now \rwd{return} is last statement in the inner block. | 803 | `\verb|do return end|' and |
804 | `\verb|do break end|', | ||
805 | because now \rwd{return} and \rwd{break} are last statements in the inner block. | ||
806 | In practice, | ||
807 | these idioms are only used during debugging. | ||
808 | (The idiom `\verb|do return end|' can be added at the beginning of a chunk | ||
809 | for syntax checking only.) | ||
712 | 810 | ||
713 | \subsubsection{For Statement} \label{for}\index{for statement} | 811 | \subsubsection{For Statement} \label{for}\index{for statement} |
714 | 812 | ||
715 | The \rwd{for} statement has two forms, | 813 | The \rwd{for} statement has two forms, |
716 | one for numbers and one for tables. | 814 | one for numbers and one for tables. |
717 | \newpage | 815 | |
718 | The numerical \rwd{for} loop has the following syntax: | 816 | The numerical \rwd{for} loop |
817 | repeats a block of code while a control variables runs through an arithmetic progression. It has the following syntax: | ||
719 | \begin{Produc} | 818 | \begin{Produc} |
720 | \produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp} | 819 | \produc{stat}{\rwd{for} name \ter{=} exp \ter{,} exp \opt{\ter{,} exp} |
721 | \rwd{do} block \rwd{end}} | 820 | \rwd{do} block \rwd{end}} |
722 | \end{Produc}% | 821 | \end{Produc}% |
723 | A \rwd{for} statement like | 822 | The \emph{block} is repeated for \emph{name} starting at the value of |
823 | the first \emph{exp}, until it reaches the second \emph{exp} by steps of the | ||
824 | third \emph{exp}. | ||
825 | More precisely, a \rwd{for} statement like | ||
724 | \begin{verbatim} | 826 | \begin{verbatim} |
725 | for var = e1, e2, e3 do block end | 827 | for var = e1, e2, e3 do block end |
726 | \end{verbatim} | 828 | \end{verbatim} |
@@ -744,11 +846,11 @@ the block. | |||
744 | \item If the third expression (the step) is absent, then a step of~1 is used. | 846 | \item If the third expression (the step) is absent, then a step of~1 is used. |
745 | \item Both the limit and the step are evaluated only once, | 847 | \item Both the limit and the step are evaluated only once, |
746 | before the loop starts. | 848 | before the loop starts. |
747 | \item The variable \verb|var| is local to the statement; | 849 | \item You can use \rwd{break} to exit a \rwd{for} loop. |
748 | you cannot use its value after the \rwd{for} ends. | 850 | \item The loop variable \verb|var| is local to the statement; |
749 | \item You can use \rwd{break} to exit a \rwd{for}. | 851 | you cannot use its value after the \rwd{for} ends or is broken. |
750 | If you need the value of the index, | 852 | If you need the value of the loop variable \verb|var|, |
751 | assign it to another variable before breaking. | 853 | then assign it to another variable before breaking or exiting the loop. |
752 | \end{itemize} | 854 | \end{itemize} |
753 | 855 | ||
754 | The table \rwd{for} statement traverses all pairs | 856 | The table \rwd{for} statement traverses all pairs |
@@ -781,11 +883,11 @@ The name is here for explanatory purposes only. | |||
781 | the block. | 883 | the block. |
782 | \item The behavior is \emph{undefined} if you change | 884 | \item The behavior is \emph{undefined} if you change |
783 | the table \verb|_t| during the traversal. | 885 | the table \verb|_t| during the traversal. |
784 | \item The variables \verb|index| and \verb|value| are local to the statement; | 886 | \item You can use \rwd{break} to exit a \rwd{for} loop. |
887 | \item The loop variables \verb|index| and \verb|value| are local to the statement; | ||
785 | you cannot use their values after the \rwd{for} ends. | 888 | you cannot use their values after the \rwd{for} ends. |
786 | \item You can use \rwd{break} to exit a \rwd{for}. | ||
787 | If you need the value of \verb|index| or \verb|value|, | 889 | If you need the value of \verb|index| or \verb|value|, |
788 | assign them to other variables before breaking. | 890 | then assign them to other variables before breaking or exiting the loop. |
789 | \item The order that table elements are traversed is undefined, | 891 | \item The order that table elements are traversed is undefined, |
790 | \emph{even for numerical indices}. | 892 | \emph{even for numerical indices}. |
791 | If you want to traverse indices in numerical order, | 893 | If you want to traverse indices in numerical order, |
@@ -806,29 +908,29 @@ Function calls are explained in \See{functioncall}. | |||
806 | \Index{Local variables} may be declared anywhere inside a block. | 908 | \Index{Local variables} may be declared anywhere inside a block. |
807 | The declaration may include an initial assignment: | 909 | The declaration may include an initial assignment: |
808 | \begin{Produc} | 910 | \begin{Produc} |
809 | \produc{stat}{\rwd{local} declist \opt{init}} | 911 | \produc{stat}{\rwd{local} namelist \opt{\ter{=} explist1}} |
810 | \produc{declist}{name \rep{\ter{,} name}} | 912 | \produc{namelist}{name \rep{\ter{,} name}} |
811 | \produc{init}{\ter{=} explist1} | ||
812 | \end{Produc}% | 913 | \end{Produc}% |
813 | If present, an initial assignment has the same semantics | 914 | If present, an initial assignment has the same semantics |
814 | of a multiple assignment. | 915 | of a multiple assignment \see{assignment}. |
815 | Otherwise, all variables are initialized with \nil. | 916 | Otherwise, all variables are initialized with \nil. |
816 | 917 | ||
817 | A chunk is also a block, | ||
818 | and so local variables can be declared outside any explicit block. | ||
819 | |||
820 | The scope of local variables begins \emph{after} | 918 | The scope of local variables begins \emph{after} |
821 | the declaration and lasts until the end of the block. | 919 | the declaration and lasts until the end of the block. |
822 | Thus, the code | 920 | Thus, the code |
823 | \verb|local print=print| | 921 | \verb|local print=print| |
824 | creates a local variable called \verb|print| whose | 922 | creates a local variable named \verb|print| whose |
825 | initial value is that of the \emph{global} variable of the same name. | 923 | initial value is that of the \emph{global} variable of the same name. |
826 | 924 | ||
925 | A chunk is also a block \see{chunks}, | ||
926 | and so local variables can be declared outside any explicit block. | ||
927 | Such local variables die when the chunk ends. | ||
928 | |||
827 | 929 | ||
828 | \subsection{\Index{Expressions}} | 930 | \subsection{\Index{Expressions}}\label{expressions} |
829 | 931 | ||
830 | \subsubsection{\Index{Basic Expressions}} | 932 | %\subsubsection{\Index{Basic Expressions}} |
831 | The basic expressions in Lua are | 933 | The basic expressions in Lua are the following: |
832 | \begin{Produc} | 934 | \begin{Produc} |
833 | \produc{exp}{\ter{(} exp \ter{)}} | 935 | \produc{exp}{\ter{(} exp \ter{)}} |
834 | \produc{exp}{\rwd{nil}} | 936 | \produc{exp}{\rwd{nil}} |
@@ -841,25 +943,23 @@ The basic expressions in Lua are | |||
841 | \produc{exp}{tableconstructor} | 943 | \produc{exp}{tableconstructor} |
842 | \end{Produc}% | 944 | \end{Produc}% |
843 | 945 | ||
844 | An expression enclosed in parentheses always results | 946 | An expression enclosed in parentheses always results in only one value |
845 | in only one value. | 947 | (the only expressions that can result in multiple values are function calls). |
948 | Thus, | ||
949 | \verb|(f(x,y,z))| is always a single value, | ||
950 | even if \verb|f| returns several values. | ||
951 | (The value of \verb|(f(x,y,z))| is the first value returned by \verb|f| | ||
952 | or \nil\ if \verb|f| does not return any values.) | ||
846 | 953 | ||
847 | Numbers (numerical constants) and | 954 | \emph{Numbers} and \emph{literal strings} are explained in \See{lexical}; |
848 | literal strings are explained in \See{lexical}; | 955 | variables are explained in \See{variables}; |
849 | variables are explained in \See{assignment}; | ||
850 | upvalues are explained in \See{upvalue}; | 956 | upvalues are explained in \See{upvalue}; |
851 | function definitions are explained in \See{func-def}; | 957 | function definitions are explained in \See{func-def}; |
852 | function calls are explained in \See{functioncall}. | 958 | function calls are explained in \See{functioncall}; |
853 | Table constructors are explained in \See{tableconstructor}. | 959 | table constructors are explained in \See{tableconstructor}. |
854 | |||
855 | An access to a global variable \verb|x| is equivalent to a | ||
856 | call \verb|getglobal("x")| and | ||
857 | an access to an indexed variable \verb|t[i]| is equivalent to | ||
858 | a call \verb|gettable_event(t,i)|. | ||
859 | See \See{tag-method} for a description of these functions | ||
860 | (\verb|getglobal| is in the basic library; | ||
861 | \T{gettable\_event} is used for explanatory purposes only). | ||
862 | 960 | ||
961 | Expressions can also be built with arithmetic operators, relational operators, | ||
962 | and logical operadors, all of which are explained below. | ||
863 | 963 | ||
864 | \subsubsection{Arithmetic Operators} | 964 | \subsubsection{Arithmetic Operators} |
865 | Lua supports the usual \Index{arithmetic operators}: | 965 | Lua supports the usual \Index{arithmetic operators}: |
@@ -868,31 +968,44 @@ the binary \verb|+| (addition), | |||
868 | \verb|/| (division), and \verb|^| (exponentiation); | 968 | \verb|/| (division), and \verb|^| (exponentiation); |
869 | and unary \verb|-| (negation). | 969 | and unary \verb|-| (negation). |
870 | If the operands are numbers, or strings that can be converted to | 970 | If the operands are numbers, or strings that can be converted to |
871 | numbers (according to the rules given in \See{coercion}), | 971 | numbers \see{coercion}, |
872 | then all operations except exponentiation have the usual meaning. | 972 | then all operations except exponentiation have the usual meaning; |
873 | Otherwise, an appropriate tag method is called \see{tag-method}. | 973 | otherwise, an appropriate tag method is called \see{tag-method}. |
874 | An exponentiation always calls a tag method. | 974 | An exponentiation always calls a tag method. |
875 | The standard mathematical library redefines this method for numbers, | 975 | The standard mathematical library redefines this method for numbers, |
876 | giving the expected meaning to \Index{exponentiation} | 976 | giving the expected meaning to \Index{exponentiation} |
877 | \see{mathlib}. | 977 | \see{mathlib}. |
878 | 978 | ||
879 | \subsubsection{Relational Operators} | 979 | \subsubsection{Relational Operators}\label{rel-ops} |
880 | The \Index{relational operators} in Lua are | 980 | The \Index{relational operators} in Lua are |
881 | \begin{verbatim} | 981 | \begin{verbatim} |
882 | == ~= < > <= >= | 982 | == ~= < > <= >= |
883 | \end{verbatim} | 983 | \end{verbatim} |
884 | These operators return \nil\ as false and a value different from \nil\ as true. | 984 | These operators return \nil\ as false and a value different from \nil\ as true. |
885 | 985 | ||
886 | Equality (\verb|==|) first compares the tags of its operands. | 986 | Equality (\verb|==|) first compares the type of its operands. |
887 | If they are different, then the result is \nil. | 987 | If the types are different, then the result is \nil. |
888 | Otherwise, their values are compared. | 988 | Otherwise, the values of the operands are compared. |
889 | Numbers and strings are compared in the usual way. | 989 | Numbers are compared in the usual way. |
890 | Tables, userdata, and functions are compared by reference, | 990 | Strings, tables, userdata, and functions are compared \emph{by reference}, |
891 | that is, | 991 | that is, |
892 | two tables are considered equal only if they are the \emph{same} table. | 992 | two tables are considered equal only if they are the \emph{same} table. |
893 | Every time you create a new table (or userdata, or function) this | 993 | In particular, |
894 | new value is different from any previously existing value. | 994 | equality is a constant-time operation and does not depend on the size of the |
895 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). | 995 | strings or tables. |
996 | |||
997 | Every time you create a new table (or string, userdata, or function), | ||
998 | this new value is different from any previously existing value. | ||
999 | In particular, | ||
1000 | this is true for strings, | ||
1001 | even if a string is built in different ways. | ||
1002 | For example, all strings below are equal, | ||
1003 | that is, they are the \emph{same} string: | ||
1004 | \begin{verbatim} | ||
1005 | "Lua" .. " 4.1" | ||
1006 | "Lua " .. "4.1" | ||
1007 | "Lua 4.1" | ||
1008 | \end{verbatim} | ||
896 | 1009 | ||
897 | \NOTE | 1010 | \NOTE |
898 | The conversion rules of \See{coercion} | 1011 | The conversion rules of \See{coercion} |
@@ -902,27 +1015,39 @@ and \verb|t[0]| and \verb|t["0"]| denote different | |||
902 | entries in a table. | 1015 | entries in a table. |
903 | \medskip | 1016 | \medskip |
904 | 1017 | ||
1018 | The operator \verb|~=| is exactly the negation of equality (\verb|==|). | ||
1019 | |||
905 | The order operators work as follows. | 1020 | The order operators work as follows. |
906 | If both arguments are numbers, then they are compared as such. | 1021 | If both arguments are numbers, then they are compared as such. |
907 | Otherwise, if both arguments are strings, | 1022 | Otherwise, if both arguments are strings, |
908 | then their values are compared using lexicographical order. | 1023 | then their values are compared according to the current locale (see below). |
909 | Otherwise, the ``lt'' tag method is called \see{tag-method}. | 1024 | Otherwise, the ``lt'' tag method is called \see{tag-method}. |
910 | 1025 | ||
1026 | String comparison according to the current locale | ||
1027 | means that | ||
1028 | if you sort strings using \verb|<=|, | ||
1029 | then | ||
1030 | \emph{\'agua} will appear before \emph{book} | ||
1031 | and close to all other strings beginning with \emph{ag}, | ||
1032 | even though \emph{\'a}~appears after \emph{b} in the usual ISO Latin encoding. | ||
1033 | \index{string comparison} | ||
1034 | |||
1035 | |||
911 | \subsubsection{Logical Operators} | 1036 | \subsubsection{Logical Operators} |
912 | The \Index{logical operators} in Lua are | 1037 | The \Index{logical operators} in Lua are |
913 | \index{and}\index{or}\index{not} | 1038 | \index{and}\index{or}\index{not} |
914 | \begin{verbatim} | 1039 | \begin{verbatim} |
915 | and or not | 1040 | and or not |
916 | \end{verbatim} | 1041 | \end{verbatim} |
917 | Like the control structures, all logical operators | 1042 | Like the control structures \see{control}, |
918 | consider \nil\ as false and anything else as true. | 1043 | all logical operators consider \nil\ as false and anything else as true. |
919 | 1044 | ||
920 | The conjunction operator \verb|and| returns \nil\ if its first argument is \nil; | 1045 | The conjunction operator \rwd{and} returns \nil\ if its first argument is \nil; |
921 | otherwise, it returns its second argument. | 1046 | otherwise, \rwd{and} returns its second argument. |
922 | The disjunction operator \verb|or| returns its first argument | 1047 | The disjunction operator \rwd{or} returns its first argument |
923 | if it is different from \nil; | 1048 | if it is different from \nil; |
924 | otherwise, it returns its second argument. | 1049 | otherwise, \rwd{or} returns its second argument. |
925 | Both \verb|and| and \verb|or| use \Index{short-cut evaluation}, | 1050 | Both \rwd{and} and \rwd{or} use \Index{short-cut evaluation}, |
926 | that is, | 1051 | that is, |
927 | the second operand is evaluated only if necessary. | 1052 | the second operand is evaluated only if necessary. |
928 | 1053 | ||
@@ -950,14 +1075,14 @@ provided that \verb|b| is not \nil. | |||
950 | 1075 | ||
951 | \subsubsection{Concatenation} \label{concat} | 1076 | \subsubsection{Concatenation} \label{concat} |
952 | The string \Index{concatenation} operator in Lua is | 1077 | The string \Index{concatenation} operator in Lua is |
953 | denoted by two dots (`\IndexVerb{..}'). | 1078 | denoted by two dots (`\verb|..|'). |
954 | If both operands are strings or numbers, then they are converted to | 1079 | If both operands are strings or numbers, then they are converted to |
955 | strings according to the rules in \See{coercion}. | 1080 | strings according to the rules mentioned in \See{coercion}. |
956 | Otherwise, the ``concat'' tag method is called \see{tag-method}. | 1081 | Otherwise, the ``concat'' tag method is called \see{tag-method}. |
957 | 1082 | ||
958 | \subsubsection{Precedence} | 1083 | \subsubsection{Precedence} |
959 | \Index{Operator precedence} in Lua follows the table below, | 1084 | \Index{Operator precedence} in Lua follows the table below, |
960 | from the lower to the higher priority: | 1085 | from lower to higher priority: |
961 | \begin{verbatim} | 1086 | \begin{verbatim} |
962 | and or | 1087 | and or |
963 | < > <= >= ~= == | 1088 | < > <= >= ~= == |
@@ -977,6 +1102,8 @@ as long as these optimizations do not change normal results. | |||
977 | However, these optimizations may change some results | 1102 | However, these optimizations may change some results |
978 | if you define non-associative (or non-commutative) | 1103 | if you define non-associative (or non-commutative) |
979 | tag methods for these operators. | 1104 | tag methods for these operators. |
1105 | In general, | ||
1106 | you should not write code that depends on the order of evaluation. | ||
980 | 1107 | ||
981 | \subsubsection{Table Constructors} \label{tableconstructor} | 1108 | \subsubsection{Table Constructors} \label{tableconstructor} |
982 | Table \Index{constructors} are expressions that create tables; | 1109 | Table \Index{constructors} are expressions that create tables; |
@@ -989,11 +1116,12 @@ The general syntax for constructors is | |||
989 | \produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist | 1116 | \produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist |
990 | \Or ffieldlist \ter{;} lfieldlist} | 1117 | \Or ffieldlist \ter{;} lfieldlist} |
991 | \produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}} | 1118 | \produc{lfieldlist}{\opt{explist1 \opt{\ter{,}}}} |
992 | \produc{ffieldlist}{\opt{ffieldlist1}} | 1119 | \produc{ffieldlist}{\opt{ffieldlist1 \opt{\ter{,}}}} |
993 | \end{Produc}% | 1120 | \end{Produc}% |
994 | 1121 | ||
995 | The form \emph{explist1} is used to initialize lists. | 1122 | The form \emph{explist1} is used to initialize \IndexEmph{lists}. |
996 | The expressions in the list are assigned to consecutive numerical indices, | 1123 | The expressions in a list are assigned to consecutive numerical indices |
1124 | in the table, | ||
997 | starting with~1. | 1125 | starting with~1. |
998 | For example, | 1126 | For example, |
999 | \begin{verbatim} | 1127 | \begin{verbatim} |
@@ -1009,12 +1137,16 @@ is equivalent to | |||
1009 | a = temp | 1137 | a = temp |
1010 | end | 1138 | end |
1011 | \end{verbatim} | 1139 | \end{verbatim} |
1140 | |||
1012 | If the last expression in the list is a function call, | 1141 | If the last expression in the list is a function call, |
1013 | all values returned by the call enter the list \see{functioncall}. | 1142 | then all values returned by the call enter the list consecutively |
1143 | \see{functioncall}. | ||
1144 | To avoid this, | ||
1145 | enclose the function call in parentheses. | ||
1014 | 1146 | ||
1015 | The form \emph{ffieldlist1} initializes other fields in a table: | 1147 | The form \emph{ffieldlist1} initializes other fields in a table: |
1016 | \begin{Produc} | 1148 | \begin{Produc} |
1017 | \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} | 1149 | \produc{ffieldlist1}{ffield \rep{\ter{,} ffield}} |
1018 | \produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp} | 1150 | \produc{ffield}{\ter{[} exp \ter{]} \ter{=} exp \Or name \ter{=} exp} |
1019 | \end{Produc}% | 1151 | \end{Produc}% |
1020 | For example, | 1152 | For example, |
@@ -1026,8 +1158,8 @@ is equivalent to | |||
1026 | do | 1158 | do |
1027 | local temp = {} | 1159 | local temp = {} |
1028 | temp[f(k)] = g(y) | 1160 | temp[f(k)] = g(y) |
1029 | temp.x = 1 -- or temp["x"] = 1 | 1161 | temp["x"] = 1 -- or temp.x = 1 |
1030 | temp.y = 3 -- or temp["y"] = 3 | 1162 | temp["y"] = 3 -- or temp.y = 3 |
1031 | temp[0] = b+c | 1163 | temp[0] = b+c |
1032 | a = temp | 1164 | a = temp |
1033 | end | 1165 | end |
@@ -1035,7 +1167,8 @@ is equivalent to | |||
1035 | An expression like \verb|{x = 1, y = 4}| is | 1167 | An expression like \verb|{x = 1, y = 4}| is |
1036 | in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. | 1168 | in fact syntactic sugar for \verb|{["x"] = 1, ["y"] = 4}|. |
1037 | 1169 | ||
1038 | Both forms may have an optional trailing comma, | 1170 | Both forms may have an optional trailing comma |
1171 | (for convinence of machine-generated code), | ||
1039 | and can be used in the same constructor separated by | 1172 | and can be used in the same constructor separated by |
1040 | a semi-colon. | 1173 | a semi-colon. |
1041 | For example, all forms below are correct. | 1174 | For example, all forms below are correct. |
@@ -1051,7 +1184,8 @@ A \Index{function call} in Lua has the following syntax: | |||
1051 | \begin{Produc} | 1184 | \begin{Produc} |
1052 | \produc{functioncall}{exp args} | 1185 | \produc{functioncall}{exp args} |
1053 | \end{Produc}% | 1186 | \end{Produc}% |
1054 | First, \M{exp} and \M{args} are evaluated. | 1187 | In a function call, |
1188 | first \M{exp} and \M{args} are evaluated. | ||
1055 | If the value of \M{exp} has type \emph{function}, | 1189 | If the value of \M{exp} has type \emph{function}, |
1056 | then this function is called, | 1190 | then this function is called, |
1057 | with the given arguments. | 1191 | with the given arguments. |
@@ -1072,7 +1206,6 @@ except that \verb|v| is evaluated only once. | |||
1072 | Arguments have the following syntax: | 1206 | Arguments have the following syntax: |
1073 | \begin{Produc} | 1207 | \begin{Produc} |
1074 | \produc{args}{\ter{(} \opt{explist1} \ter{)}} | 1208 | \produc{args}{\ter{(} \opt{explist1} \ter{)}} |
1075 | \produc{explist1}{\rep{exp \ter{,}} exp} | ||
1076 | \produc{args}{tableconstructor} | 1209 | \produc{args}{tableconstructor} |
1077 | \produc{args}{literal} | 1210 | \produc{args}{literal} |
1078 | \end{Produc}% | 1211 | \end{Produc}% |
@@ -1096,7 +1229,9 @@ or in the middle of a list of expressions, | |||
1096 | then its return list is adjusted to~1, | 1229 | then its return list is adjusted to~1, |
1097 | thus discarding all returned values but the first one. | 1230 | thus discarding all returned values but the first one. |
1098 | If the function is called as the last element of a list of expressions, | 1231 | If the function is called as the last element of a list of expressions, |
1099 | then no adjustment is made. | 1232 | then no adjustment is made |
1233 | (unless the call is enclosed in parentheses). | ||
1234 | |||
1100 | Here are some examples: | 1235 | Here are some examples: |
1101 | \begin{verbatim} | 1236 | \begin{verbatim} |
1102 | f() -- adjusted to 0 results | 1237 | f() -- adjusted to 0 results |
@@ -1111,11 +1246,11 @@ Here are some examples: | |||
1111 | {f(), nil} -- f() is adjusted to 1 result | 1246 | {f(), nil} -- f() is adjusted to 1 result |
1112 | \end{verbatim} | 1247 | \end{verbatim} |
1113 | 1248 | ||
1114 | If you embrace a function call in parentheses, | 1249 | If you enclose a function call in parentheses, |
1115 | then it is adjusted to return exactly one value: | 1250 | then it is adjusted to return exactly one value: |
1116 | \begin{verbatim} | 1251 | \begin{verbatim} |
1117 | return x, y, (f()) -- returns x, y, and one value from f() | 1252 | return x,y,(f()) -- returns x, y, and the first value from f() |
1118 | {(f())} -- create a table with exactly one element | 1253 | {(f())} -- creates a table with exactly one element |
1119 | \end{verbatim} | 1254 | \end{verbatim} |
1120 | 1255 | ||
1121 | \subsubsection{\Index{Function Definitions}} \label{func-def} | 1256 | \subsubsection{\Index{Function Definitions}} \label{func-def} |
@@ -1132,17 +1267,17 @@ The statement | |||
1132 | \begin{verbatim} | 1267 | \begin{verbatim} |
1133 | function f () ... end | 1268 | function f () ... end |
1134 | \end{verbatim} | 1269 | \end{verbatim} |
1135 | is just syntactic sugar for | 1270 | is syntactic sugar for |
1136 | \begin{verbatim} | 1271 | \begin{verbatim} |
1137 | f = function () ... end | 1272 | f = function () ... end |
1138 | \end{verbatim} | 1273 | \end{verbatim} |
1139 | and the statement | 1274 | and the statement |
1140 | \begin{verbatim} | 1275 | \begin{verbatim} |
1141 | function v.c.f () ... end | 1276 | function t.a.b.c.f () ... end |
1142 | \end{verbatim} | 1277 | \end{verbatim} |
1143 | is syntactic sugar for | 1278 | is syntactic sugar for |
1144 | \begin{verbatim} | 1279 | \begin{verbatim} |
1145 | v.c.f = function () ... end | 1280 | t.a.b.c.f = function () ... end |
1146 | \end{verbatim} | 1281 | \end{verbatim} |
1147 | 1282 | ||
1148 | A function definition is an executable expression, | 1283 | A function definition is an executable expression, |
@@ -1150,7 +1285,7 @@ whose value has type \emph{function}. | |||
1150 | When Lua pre-compiles a chunk, | 1285 | When Lua pre-compiles a chunk, |
1151 | all its function bodies are pre-compiled too. | 1286 | all its function bodies are pre-compiled too. |
1152 | Then, whenever Lua executes the function definition, | 1287 | Then, whenever Lua executes the function definition, |
1153 | its upvalues are fixed \see{upvalue}, | 1288 | its upvalues (if any) are fixed \see{upvalue}, |
1154 | and the function is \emph{instantiated} (or \emph{closed}). | 1289 | and the function is \emph{instantiated} (or \emph{closed}). |
1155 | This function instance (or \emph{closure}) | 1290 | This function instance (or \emph{closure}) |
1156 | is the final value of the expression. | 1291 | is the final value of the expression. |
@@ -1161,7 +1296,7 @@ Parameters act as local variables, | |||
1161 | initialized with the argument values: | 1296 | initialized with the argument values: |
1162 | \begin{Produc} | 1297 | \begin{Produc} |
1163 | \produc{parlist1}{\ter{\ldots}} | 1298 | \produc{parlist1}{\ter{\ldots}} |
1164 | \produc{parlist1}{name \rep{\ter{,} name} \opt{\ter{,} \ter{\ldots}}} | 1299 | \produc{parlist1}{namelist \opt{\ter{,} \ter{\ldots}}} |
1165 | \end{Produc}% | 1300 | \end{Produc}% |
1166 | \label{vararg}% | 1301 | \label{vararg}% |
1167 | When a function is called, | 1302 | When a function is called, |
@@ -1194,9 +1329,9 @@ Then, we have the following mapping from arguments to parameters: | |||
1194 | f(r()) a=1, b=2 | 1329 | f(r()) a=1, b=2 |
1195 | 1330 | ||
1196 | g(3) a=3, b=nil, arg={n=0} | 1331 | g(3) a=3, b=nil, arg={n=0} |
1197 | g(3, 4) a=3, b=4, arg={n=0} | 1332 | g(3, 4) a=3, b=4, arg={n=0} |
1198 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} | 1333 | g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2} |
1199 | g(5, r()) a=5, b=1, arg={2, 3; n=2} | 1334 | g(5, r()) a=5, b=1, arg={2, 3; n=2} |
1200 | \end{verbatim} | 1335 | \end{verbatim} |
1201 | 1336 | ||
1202 | Results are returned using the \rwd{return} statement \see{return}. | 1337 | Results are returned using the \rwd{return} statement \see{return}. |
@@ -1207,14 +1342,13 @@ then the function returns with no results. | |||
1207 | The \emph{colon} syntax | 1342 | The \emph{colon} syntax |
1208 | is used for defining \IndexEmph{methods}, | 1343 | is used for defining \IndexEmph{methods}, |
1209 | that is, functions that have an implicit extra parameter \IndexVerb{self}. | 1344 | that is, functions that have an implicit extra parameter \IndexVerb{self}. |
1210 | 1345 | Thus, the statement | |
1211 | The statement | ||
1212 | \begin{verbatim} | 1346 | \begin{verbatim} |
1213 | function v.c:f (...) ... end | 1347 | function t.a.b.c:f (...) ... end |
1214 | \end{verbatim} | 1348 | \end{verbatim} |
1215 | is just syntactic sugar for | 1349 | is syntactic sugar for |
1216 | \begin{verbatim} | 1350 | \begin{verbatim} |
1217 | v.c.f = function (self, ...) ... end | 1351 | t.a.b.c.f = function (self, ...) ... end |
1218 | \end{verbatim} | 1352 | \end{verbatim} |
1219 | Note that the function gets an extra formal parameter called \verb|self|. | 1353 | Note that the function gets an extra formal parameter called \verb|self|. |
1220 | 1354 | ||
@@ -1237,13 +1371,14 @@ whose syntax is | |||
1237 | \end{Produc}% | 1371 | \end{Produc}% |
1238 | 1372 | ||
1239 | An upvalue is somewhat similar to a variable expression, | 1373 | An upvalue is somewhat similar to a variable expression, |
1240 | but whose value is \emph{frozen} when the function wherein it | 1374 | but whose value is \emph{frozen} when the function in which it |
1241 | appears is instantiated. | 1375 | appears is instantiated. |
1242 | The name used in an upvalue may be the name of any variable visible | 1376 | The name used in an upvalue may be the name of any variable visible |
1243 | at the point where the function is defined, | 1377 | at the point where the function is defined, |
1244 | that is, | 1378 | that is, |
1245 | global variables and local variables | 1379 | global variables and local variables |
1246 | from the \emph{immediately enclosing} function. | 1380 | from the \emph{immediately enclosing} function. |
1381 | |||
1247 | Note that when the upvalue is a table, | 1382 | Note that when the upvalue is a table, |
1248 | only the \emph{reference} to that table | 1383 | only the \emph{reference} to that table |
1249 | (which is the value of the upvalue) is frozen; | 1384 | (which is the value of the upvalue) is frozen; |
@@ -1293,8 +1428,8 @@ So, for this kind of error, Lua does not call | |||
1293 | the \verb|_ERRORMESSAGE| function; | 1428 | the \verb|_ERRORMESSAGE| function; |
1294 | instead, the corresponding function from the library | 1429 | instead, the corresponding function from the library |
1295 | returns immediately with a special error code (\verb|LUA_ERRMEM|). | 1430 | returns immediately with a special error code (\verb|LUA_ERRMEM|). |
1296 | This and other error codes are defined in \verb|lua.h|; | 1431 | This and other error codes are defined in \verb|lua.h| |
1297 | \See{luado}. | 1432 | \see{luado}. |
1298 | 1433 | ||
1299 | The only argument to \verb|_ERRORMESSAGE| is a string | 1434 | The only argument to \verb|_ERRORMESSAGE| is a string |
1300 | describing the error. | 1435 | describing the error. |
@@ -1312,9 +1447,9 @@ Lua code can ``catch'' an error using the function | |||
1312 | \verb|call| \see{pdf-call}. | 1447 | \verb|call| \see{pdf-call}. |
1313 | 1448 | ||
1314 | 1449 | ||
1315 | \subsection{Tag Methods} \label{tag-method}\index{tag method} | 1450 | \subsection{Tag Methods} \label{tag-method} |
1316 | 1451 | ||
1317 | A tag method is a programmer-defined function | 1452 | A \IndexEmph{tag method} is a programmer-defined function |
1318 | that defines how Lua operations act over user-defined types | 1453 | that defines how Lua operations act over user-defined types |
1319 | (and, sometimes, over basic types as well). | 1454 | (and, sometimes, over basic types as well). |
1320 | An \Def{event} is any operation that may invoke a tag method. | 1455 | An \Def{event} is any operation that may invoke a tag method. |
@@ -1323,8 +1458,9 @@ Lua selects the tag method called for any specific event | |||
1323 | according to the types of the values involved | 1458 | according to the types of the values involved |
1324 | in the event \see{TypesSec}. | 1459 | in the event \see{TypesSec}. |
1325 | The function \IndexLIB{settagmethod} changes the tag method | 1460 | The function \IndexLIB{settagmethod} changes the tag method |
1326 | associated with a given pair \M{(type, event)}. | 1461 | associated with a given pair (\M{type}, \M{event}). |
1327 | Its first parameter is the type (its name or its tag), | 1462 | The first parameter to \verb|settagmethod| is the type |
1463 | (represented by its name or tag), | ||
1328 | the second parameter is the event name (a string; see below), | 1464 | the second parameter is the event name (a string; see below), |
1329 | and the third parameter is the new method (a function), | 1465 | and the third parameter is the new method (a function), |
1330 | or \nil\ to restore the default behavior for the pair. | 1466 | or \nil\ to restore the default behavior for the pair. |
@@ -1344,7 +1480,7 @@ The code shown here in Lua is only illustrative; | |||
1344 | the real behavior is hard coded in the interpreter, | 1480 | the real behavior is hard coded in the interpreter, |
1345 | and it is much more efficient than this simulation. | 1481 | and it is much more efficient than this simulation. |
1346 | All functions used in these descriptions | 1482 | All functions used in these descriptions |
1347 | (\verb|rawget|, \verb|tonumber|, \verb|call|, etc.) | 1483 | (\verb|rawget|, \verb|tonumber|, \verb|call|, etc.)\ |
1348 | are described in \See{predefined}. | 1484 | are described in \See{predefined}. |
1349 | 1485 | ||
1350 | \begin{description} | 1486 | \begin{description} |
@@ -1615,7 +1751,8 @@ Lua does the equivalent of the call \verb|gc_event(nil)|. | |||
1615 | 1751 | ||
1616 | 1752 | ||
1617 | 1753 | ||
1618 | \section{The Application Program Interface} | 1754 | %------------------------------------------------------------------------------ |
1755 | \section{The Application Program Interface}\label{API} | ||
1619 | \index{C API} | 1756 | \index{C API} |
1620 | This section describes the API for Lua, that is, | 1757 | This section describes the API for Lua, that is, |
1621 | the set of C~functions available to the host program to communicate | 1758 | the set of C~functions available to the host program to communicate |
@@ -1627,17 +1764,17 @@ are declared in the header file \verb|lua.h|. | |||
1627 | Even when we use the term ``function'', | 1764 | Even when we use the term ``function'', |
1628 | any facility in the API may be provided as a \emph{macro} instead. | 1765 | any facility in the API may be provided as a \emph{macro} instead. |
1629 | All such macros use each of its arguments exactly once | 1766 | All such macros use each of its arguments exactly once |
1630 | (except for the first argument, which is always a state), | 1767 | (except for the first argument, which is always a Lua state), |
1631 | and so do not generate hidden side-effects. | 1768 | and so do not generate hidden side-effects. |
1632 | 1769 | ||
1633 | 1770 | ||
1634 | \subsection{States} \label{mangstate} | 1771 | \subsection{States} \label{mangstate} |
1635 | 1772 | ||
1636 | The Lua library is fully reentrant: | 1773 | The Lua library is fully reentrant: |
1637 | it does not have any global variables. | 1774 | it has no global variables. |
1638 | \index{state} | 1775 | \index{state} |
1639 | The whole state of the Lua interpreter | 1776 | The whole state of the Lua interpreter |
1640 | (global variables, stack, tag methods, etc.) | 1777 | (global variables, stack, tag methods, etc.)\ |
1641 | is stored in a dynamically allocated structure of type \verb|lua_State|; | 1778 | is stored in a dynamically allocated structure of type \verb|lua_State|; |
1642 | \DefAPI{lua_State} | 1779 | \DefAPI{lua_State} |
1643 | this state must be passed as the first argument to | 1780 | this state must be passed as the first argument to |
@@ -1672,7 +1809,7 @@ On the other hand, | |||
1672 | long-running programs --- | 1809 | long-running programs --- |
1673 | like a daemon or a web server --- | 1810 | like a daemon or a web server --- |
1674 | might need to release states as soon as they are not needed, | 1811 | might need to release states as soon as they are not needed, |
1675 | to avoid growing too big. | 1812 | to avoid growing too large. |
1676 | 1813 | ||
1677 | With the exception of \verb|lua_open|, | 1814 | With the exception of \verb|lua_open|, |
1678 | all functions in the Lua API need a state as their first argument. | 1815 | all functions in the Lua API need a state as their first argument. |
@@ -1680,26 +1817,26 @@ all functions in the Lua API need a state as their first argument. | |||
1680 | 1817 | ||
1681 | \subsection{Threads} | 1818 | \subsection{Threads} |
1682 | 1819 | ||
1683 | Lua offers a partial support for multiple threads. | 1820 | Lua offers a partial support for multiple threads of execution. |
1684 | If you have a C library that offers multi-threading or co-routines, | 1821 | If you have a C~library that offers multi-threading or co-routines, |
1685 | Lua can cooperate with it to implement the equivalent facility in Lua. | 1822 | then Lua can cooperate with it to implement the equivalent facility in Lua. |
1686 | The following function creates a new ``thread'' in Lua: | 1823 | The following function creates a new ``thread'' in Lua: |
1687 | \begin{verbatim} | 1824 | \begin{verbatim} |
1688 | lua_State *lua_newthread (lua_State *L, int stacksize); | 1825 | lua_State *lua_newthread (lua_State *L, int stacksize); |
1689 | \end{verbatim} | 1826 | \end{verbatim} |
1690 | \DefAPI{lua_newthread} | 1827 | \DefAPI{lua_newthread} |
1691 | The new state returned by this function shares with the original state | 1828 | The new state returned by this function shares with the original state |
1692 | all global environment (such as tables, tag methods, etc.), | 1829 | all global environment (such as tables, tag methods, etc.), |
1693 | but has an independent stack. | 1830 | but has an independent run-time stack. |
1694 | (The use of these multiple stacks must be ``syncronized'' with C. | 1831 | (The use of these multiple stacks must be ``syncronized'' with C. |
1695 | How to explain that? TO BE WRITTEN.) | 1832 | How to explain that? TO BE WRITTEN.) |
1696 | 1833 | ||
1697 | Each thread has an independent table for global variables. | 1834 | Each thread has an independent table for global variables. |
1698 | When you create a thread this table is the same as of the given state, | 1835 | When you create a thread, this table is the same as that of the given state, |
1699 | but you can change each one independently. | 1836 | but you can change each one independently. |
1700 | 1837 | ||
1701 | You destroy threads with \verb|lua_close|. | 1838 | You destroy threads with \verb|lua_close|. |
1702 | When you destroy the last thread of a global state, | 1839 | When you destroy the last thread sharing a given state, |
1703 | the state itself is also destroyed. | 1840 | the state itself is also destroyed. |
1704 | 1841 | ||
1705 | 1842 | ||
@@ -1707,7 +1844,7 @@ the state itself is also destroyed. | |||
1707 | 1844 | ||
1708 | Lua uses a \emph{stack} to pass values to and from C. | 1845 | Lua uses a \emph{stack} to pass values to and from C. |
1709 | Each element in this stack represents a Lua value | 1846 | Each element in this stack represents a Lua value |
1710 | (nil, number, string, etc.). | 1847 | (\nil, number, string, etc.). |
1711 | 1848 | ||
1712 | For convenience, | 1849 | For convenience, |
1713 | most query operations in the API do not follow a strict stack discipline. | 1850 | most query operations in the API do not follow a strict stack discipline. |
@@ -1716,7 +1853,7 @@ A positive index represents an \emph{absolute} stack position | |||
1716 | (starting at~1, not 0 as in C); | 1853 | (starting at~1, not 0 as in C); |
1717 | a negative index represents an \emph{offset} from the top of the stack. | 1854 | a negative index represents an \emph{offset} from the top of the stack. |
1718 | More specifically, if the stack has \M{n} elements, | 1855 | More specifically, if the stack has \M{n} elements, |
1719 | index~1 represents the first element | 1856 | then index~1 represents the first element |
1720 | (that is, the first element pushed onto the stack), | 1857 | (that is, the first element pushed onto the stack), |
1721 | and | 1858 | and |
1722 | index~\M{n} represents the last element; | 1859 | index~\M{n} represents the last element; |
@@ -1755,8 +1892,8 @@ when your code has loops pushing elements onto the stack. | |||
1755 | Most query functions accept as indices any value inside the | 1892 | Most query functions accept as indices any value inside the |
1756 | available stack space. | 1893 | available stack space. |
1757 | Such indices are called \emph{acceptable indices}. | 1894 | Such indices are called \emph{acceptable indices}. |
1758 | More formally, we can define an \IndexEmph{acceptable index} | 1895 | More formally, we define an \IndexEmph{acceptable index} |
1759 | as | 1896 | as follows: |
1760 | \begin{verbatim} | 1897 | \begin{verbatim} |
1761 | (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) | 1898 | (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace) |
1762 | \end{verbatim} | 1899 | \end{verbatim} |
@@ -1779,7 +1916,7 @@ and sets the stack top to that index. | |||
1779 | If the new top is larger than the old one, | 1916 | If the new top is larger than the old one, |
1780 | then the new elements are filled with \nil. | 1917 | then the new elements are filled with \nil. |
1781 | If \verb|index| is 0, then all stack elements are removed. | 1918 | If \verb|index| is 0, then all stack elements are removed. |
1782 | A useful macro defined in the API is | 1919 | A useful macro defined in the \verb|lua.h| is |
1783 | \begin{verbatim} | 1920 | \begin{verbatim} |
1784 | #define lua_pop(L,n) lua_settop(L, -(n)-1) | 1921 | #define lua_pop(L,n) lua_settop(L, -(n)-1) |
1785 | \end{verbatim} | 1922 | \end{verbatim} |
@@ -1789,22 +1926,23 @@ which pops \verb|n| elements from the stack. | |||
1789 | \verb|lua_pushvalue| pushes onto the stack a \emph{copy} of the element | 1926 | \verb|lua_pushvalue| pushes onto the stack a \emph{copy} of the element |
1790 | at the given index. | 1927 | at the given index. |
1791 | \verb|lua_remove| removes the element at the given position, | 1928 | \verb|lua_remove| removes the element at the given position, |
1792 | shifting down the elements on top of that position to fill in the gap. | 1929 | shifting down the elements above that position to fill the gap. |
1793 | \verb|lua_insert| moves the top element into the given position, | 1930 | \verb|lua_insert| moves the top element into the given position, |
1794 | shifting up the elements on top of that position to open space. | 1931 | shifting up the elements above that position to open space. |
1795 | These functions accept only valid indices. | 1932 | These functions accept only valid indices. |
1796 | As an example, if the stack starts as \verb|10 20 30 40 50| | 1933 | |
1797 | (from bottom to top), | 1934 | As an example, if the stack starts as \verb|10 20 30 40 50*| |
1935 | (from bottom to top; the \verb|*| marks the top), | ||
1798 | then | 1936 | then |
1799 | \begin{verbatim} | 1937 | \begin{verbatim} |
1800 | lua_pushvalue(L, 3) --> 10 20 30 40 50 30 | 1938 | lua_pushvalue(L, 3) --> 10 20 30 40 50 30* |
1801 | lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30 | 1939 | lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30* |
1802 | lua_remove(L, -3) --> 10 20 30 40 30 30 | 1940 | lua_remove(L, -3) --> 10 20 30 40 30 30* |
1803 | lua_remove(L, 6) --> 10 20 30 40 30 | 1941 | lua_remove(L, 6) --> 10 20 30 40 30* |
1804 | lua_insert(L, 1) --> 30 10 20 30 40 | 1942 | lua_insert(L, 1) --> 30 10 20 30 40* |
1805 | lua_insert(L, -1) --> 30 10 20 30 40 (no effect) | 1943 | lua_insert(L, -1) --> 30 10 20 30 40* (no effect) |
1806 | lua_settop(L, -3) --> 30 10 20 | 1944 | lua_settop(L, -3) --> 30 10 20* |
1807 | lua_settop(L, 6) --> 30 10 20 nil nil nil | 1945 | lua_settop(L, 6) --> 30 10 20 nil nil nil* |
1808 | \end{verbatim} | 1946 | \end{verbatim} |
1809 | 1947 | ||
1810 | 1948 | ||
@@ -1833,7 +1971,8 @@ These functions can be called with any acceptable index. | |||
1833 | \verb|lua_tag| returns the tag of a value in the stack, | 1971 | \verb|lua_tag| returns the tag of a value in the stack, |
1834 | or \verb|LUA_TNONE| for a non-valid index | 1972 | or \verb|LUA_TNONE| for a non-valid index |
1835 | (that is, if that stack position is ``empty''). | 1973 | (that is, if that stack position is ``empty''). |
1836 | The tags for the basic types are the following constants: | 1974 | The tags for the basic types are the following constants |
1975 | defined in \verb|lua.h|: | ||
1837 | \verb|LUA_TNIL|, | 1976 | \verb|LUA_TNIL|, |
1838 | \verb|LUA_TNUMBER|, | 1977 | \verb|LUA_TNUMBER|, |
1839 | \verb|LUA_TSTRING|, | 1978 | \verb|LUA_TSTRING|, |
@@ -1841,9 +1980,9 @@ The tags for the basic types are the following constants: | |||
1841 | \verb|LUA_TFUNCTION|, | 1980 | \verb|LUA_TFUNCTION|, |
1842 | \verb|LUA_TUSERDATA|. | 1981 | \verb|LUA_TUSERDATA|. |
1843 | \verb|lua_rawtag| is similar to \verb|lua_tag|, | 1982 | \verb|lua_rawtag| is similar to \verb|lua_tag|, |
1844 | but it returns the tag of the basic (raw) type of a value. | 1983 | but returns the tag of the basic (raw) type of a value. |
1845 | \verb|lua_type| is similar to \verb|lua_tag|, | 1984 | \verb|lua_type| is similar to \verb|lua_tag|, |
1846 | but it returns the type name of the given value. | 1985 | but returns the type name of the given value. |
1847 | 1986 | ||
1848 | The \verb|lua_is*| functions return~1 if the object is compatible | 1987 | The \verb|lua_is*| functions return~1 if the object is compatible |
1849 | with the given type, and 0 otherwise. | 1988 | with the given type, and 0 otherwise. |
@@ -1862,15 +2001,17 @@ The API also has functions to compare two values in the stack: | |||
1862 | int lua_lessthan (lua_State *L, int index1, int index2); | 2001 | int lua_lessthan (lua_State *L, int index1, int index2); |
1863 | \end{verbatim} | 2002 | \end{verbatim} |
1864 | \DefAPI{lua_equal} \DefAPI{lua_lessthan} | 2003 | \DefAPI{lua_equal} \DefAPI{lua_lessthan} |
1865 | These functions are equivalent to their counterparts in Lua. | 2004 | These functions are equivalent to their counterparts in Lua \see{rel-ops}. |
1866 | Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event| | 2005 | Specifically, \verb|lua_lessthan| is equivalent to the \verb|lt_event| |
1867 | described in \See{tag-method}. | 2006 | described in \See{tag-method}. |
1868 | Both functions return 0 if any of the indices are non-valid. | 2007 | Both functions return 0 if any of the indices are non-valid. |
1869 | 2008 | ||
2009 | \subsection{Getting Values from the Stack} | ||
2010 | |||
1870 | To translate a value in the stack to a specific C~type, | 2011 | To translate a value in the stack to a specific C~type, |
1871 | you can use the following conversion functions: | 2012 | you can use the following conversion functions: |
1872 | \begin{verbatim} | 2013 | \begin{verbatim} |
1873 | double lua_tonumber (lua_State *L, int index); | 2014 | lua_Number lua_tonumber (lua_State *L, int index); |
1874 | const char *lua_tostring (lua_State *L, int index); | 2015 | const char *lua_tostring (lua_State *L, int index); |
1875 | size_t lua_strlen (lua_State *L, int index); | 2016 | size_t lua_strlen (lua_State *L, int index); |
1876 | lua_CFunction lua_tocfunction (lua_State *L, int index); | 2017 | lua_CFunction lua_tocfunction (lua_State *L, int index); |
@@ -1882,28 +2023,31 @@ These functions can be called with any acceptable index. | |||
1882 | When called with a non-valid index, | 2023 | When called with a non-valid index, |
1883 | they act as if the given value had an incorrect type. | 2024 | they act as if the given value had an incorrect type. |
1884 | 2025 | ||
1885 | \verb|lua_tonumber| converts the value at the given index | 2026 | \verb|lua_tonumber| converts the Lua value at the given index |
1886 | to a floating-point number. | 2027 | to a number (by default, \verb|lua_Number| is \verb|double|). |
1887 | This value must be a number or a string convertible to number | 2028 | \DefAPI{lua_Number} |
2029 | The Lua value must be a number or a string convertible to number | ||
1888 | \see{coercion}; otherwise, \verb|lua_tonumber| returns~0. | 2030 | \see{coercion}; otherwise, \verb|lua_tonumber| returns~0. |
1889 | 2031 | ||
1890 | \verb|lua_tostring| converts a Lua value to a string | 2032 | \verb|lua_tostring| converts the Lua value at the given index to a string |
1891 | (\verb|const char*|). | 2033 | (\verb|const char*|). |
1892 | This value must be a string or a number; | 2034 | The Lua value must be a string or a number; |
1893 | otherwise, the function returns \verb|NULL|. | 2035 | otherwise, the function returns \verb|NULL|. |
1894 | If the value is a number, | 2036 | If the value is a number, |
1895 | \verb|lua_tostring| also changes the | 2037 | then \verb|lua_tostring| also |
1896 | actual value in the stack to a string. | 2038 | \emph{changes the actual value in the stack to a string}. |
1897 | This function returns a pointer to a string inside the Lua environment. | 2039 | This change confuses \verb|lua_next| when \verb|lua_tostring| is applied to keys. |
1898 | This pointer is always fully aligned. | 2040 | \verb|lua_tostring| returns a fully aligned pointer to a string inside the Lua environment. |
1899 | The strings always have a zero (\verb|'\0'|) | 2041 | This string always has a zero (\verb|'\0'|) |
1900 | after their last character (as in C), | 2042 | after its last character (as in~C), |
1901 | but may contain other zeros in their body. | 2043 | but may contain other zeros in its body. |
1902 | If you do not know whether a string may contain zeros, | 2044 | If you do not know whether a string may contain zeros, |
1903 | you can use \verb|lua_strlen| to get its actual length. | 2045 | you can use \verb|lua_strlen| to get its actual length. |
1904 | Because Lua has garbage collection, | 2046 | Because Lua has garbage collection, |
1905 | there is no guarantee that the pointer returned by \verb|lua_tostring| | 2047 | there is no guarantee that the pointer returned by \verb|lua_tostring| |
1906 | will be valid after the respective value is removed from the stack. | 2048 | will be valid after the corresponding value is removed from the stack. |
2049 | So, if you need the string after the current function returns, | ||
2050 | then you should duplicate it (or lock it; see \See{lock}). | ||
1907 | 2051 | ||
1908 | \verb|lua_tocfunction| converts a value in the stack to a C~function. | 2052 | \verb|lua_tocfunction| converts a value in the stack to a C~function. |
1909 | This value must be a C~function; | 2053 | This value must be a C~function; |
@@ -1916,12 +2060,12 @@ otherwise, \verb|lua_touserdata| returns \verb|NULL|. | |||
1916 | 2060 | ||
1917 | 2061 | ||
1918 | 2062 | ||
1919 | \subsection{Pushing values onto the Stack} | 2063 | \subsection{Pushing Values onto the Stack} |
1920 | 2064 | ||
1921 | The API has the following functions to | 2065 | The API has the following functions to |
1922 | push C~values onto the stack: | 2066 | push C~values onto the stack: |
1923 | \begin{verbatim} | 2067 | \begin{verbatim} |
1924 | void lua_pushnumber (lua_State *L, double n); | 2068 | void lua_pushnumber (lua_State *L, lua_Number n); |
1925 | void lua_pushlstring (lua_State *L, const char *s, size_t len); | 2069 | void lua_pushlstring (lua_State *L, const char *s, size_t len); |
1926 | void lua_pushstring (lua_State *L, const char *s); | 2070 | void lua_pushstring (lua_State *L, const char *s); |
1927 | void lua_pushnil (lua_State *L); | 2071 | void lua_pushnil (lua_State *L); |
@@ -1937,13 +2081,15 @@ In particular, \verb|lua_pushlstring| and \verb|lua_pushstring| | |||
1937 | make an \emph{internal copy} of the given string. | 2081 | make an \emph{internal copy} of the given string. |
1938 | \verb|lua_pushstring| can only be used to push proper C~strings | 2082 | \verb|lua_pushstring| can only be used to push proper C~strings |
1939 | (that is, strings that end with a zero and do not contain embedded zeros); | 2083 | (that is, strings that end with a zero and do not contain embedded zeros); |
1940 | otherwise you should use the more general \verb|lua_pushlstring|, | 2084 | otherwise, you should use the more general \verb|lua_pushlstring|, |
1941 | which accepts an explicit size. | 2085 | which accepts an explicit size. |
1942 | 2086 | ||
1943 | 2087 | ||
1944 | \subsection{Garbage Collection API}\label{GC-API} | 2088 | \subsection{Controlling Garbage Collection}\label{GC-API} |
1945 | 2089 | ||
1946 | Lua uses two numbers to control its garbage collection \see{GC}. | 2090 | Lua uses two numbers to control its garbage collection: |
2091 | the \emph{count} and the \emph{threshold} | ||
2092 | \see{GC}. | ||
1947 | You can access the current values of these two numbers through the | 2093 | You can access the current values of these two numbers through the |
1948 | following functions: | 2094 | following functions: |
1949 | \begin{verbatim} | 2095 | \begin{verbatim} |
@@ -1961,9 +2107,12 @@ Again, the \verb|newthreshold| value is given in Kbytes. | |||
1961 | When you call this function, | 2107 | When you call this function, |
1962 | Lua sets the new threshold and checks it against the byte counter. | 2108 | Lua sets the new threshold and checks it against the byte counter. |
1963 | If the new threshold is smaller than the byte counter, | 2109 | If the new threshold is smaller than the byte counter, |
1964 | then Lua immediately runs the garbage collector; | 2110 | then Lua immediately runs the garbage collector. |
1965 | after the collection, | 2111 | In particular |
2112 | \verb|lua_setgcthreshold(L,0)| forces a garbage collectiion. | ||
2113 | After the collection, | ||
1966 | a new threshold is set according to the previous rule. | 2114 | a new threshold is set according to the previous rule. |
2115 | %% TODO: What `previous rule'? | ||
1967 | 2116 | ||
1968 | If you want to change the adaptive behavior of the garbage collector, | 2117 | If you want to change the adaptive behavior of the garbage collector, |
1969 | you can use the garbage-collection tag method for \nil\ % | 2118 | you can use the garbage-collection tag method for \nil\ % |
@@ -1975,8 +2124,8 @@ to set your own threshold | |||
1975 | 2124 | ||
1976 | You can create new userdata with the following functions: | 2125 | You can create new userdata with the following functions: |
1977 | \begin{verbatim} | 2126 | \begin{verbatim} |
1978 | void *lua_newuserdata (lua_State *L, size_t size); | 2127 | void *lua_newuserdata (lua_State *L, size_t size); |
1979 | void lua_newuserdatabox (lua_State *L, void *u); | 2128 | void lua_newuserdatabox (lua_State *L, void *u); |
1980 | \end{verbatim} | 2129 | \end{verbatim} |
1981 | \DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox} | 2130 | \DefAPI{lua_newuserdata}\DefAPI{lua_newuserdatabox} |
1982 | The first function, \verb|lua_newuserdata|, | 2131 | The first function, \verb|lua_newuserdata|, |
@@ -1988,7 +2137,7 @@ gets a pointer and pushes on the stack a new userdata | |||
1988 | with that pointer. | 2137 | with that pointer. |
1989 | In this case, Lua does not care about the pointer's value. | 2138 | In this case, Lua does not care about the pointer's value. |
1990 | By default, all userdata are created with a standard tag, | 2139 | By default, all userdata are created with a standard tag, |
1991 | \verb|LUA_TUSERDATA|. | 2140 | \verb|LUA_TUSERDATA|, which is defined in \verb|lua.h|. |
1992 | 2141 | ||
1993 | When Lua collects a userdata created by \verb|lua_newuserdata|, | 2142 | When Lua collects a userdata created by \verb|lua_newuserdata|, |
1994 | it automatically frees its corresponding memory. | 2143 | it automatically frees its corresponding memory. |
@@ -2005,9 +2154,10 @@ User-defined types are created with the function | |||
2005 | int lua_newtype (lua_State *L, const char *name, int basictype); | 2154 | int lua_newtype (lua_State *L, const char *name, int basictype); |
2006 | \end{verbatim} | 2155 | \end{verbatim} |
2007 | \DefAPI{lua_newtype} | 2156 | \DefAPI{lua_newtype} |
2157 | where | ||
2008 | \verb|name| is the name of the new type, | 2158 | \verb|name| is the name of the new type, |
2009 | and \verb|basictype| is the basic type for objects with this new type, | 2159 | and \verb|basictype| is the basic type for objects with this new type, |
2010 | which can be \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|. | 2160 | which can be either \verb|LUA_TUSERDATA| or \verb|LUA_TTABLE|. |
2011 | 2161 | ||
2012 | The function \verb|lua_settag| changes the tag (i.e., the type) of | 2162 | The function \verb|lua_settag| changes the tag (i.e., the type) of |
2013 | the object on top of the stack (without popping it): | 2163 | the object on top of the stack (without popping it): |
@@ -2016,6 +2166,7 @@ the object on top of the stack (without popping it): | |||
2016 | \end{verbatim} | 2166 | \end{verbatim} |
2017 | \DefAPI{lua_settag} | 2167 | \DefAPI{lua_settag} |
2018 | The given \verb|tag| must be a user-defined tag, | 2168 | The given \verb|tag| must be a user-defined tag, |
2169 | %% TODO: nao pode voltar ao tag original, ie basico? | ||
2019 | and the basic type of the object must be the basic type for that | 2170 | and the basic type of the object must be the basic type for that |
2020 | tag (userdata or table). | 2171 | tag (userdata or table). |
2021 | 2172 | ||
@@ -2028,9 +2179,9 @@ and a type name to a tag: | |||
2028 | \DefAPI{lua_name2tag}\DefAPI{lua_tag2name} | 2179 | \DefAPI{lua_name2tag}\DefAPI{lua_tag2name} |
2029 | 2180 | ||
2030 | 2181 | ||
2031 | \subsection{Executing Lua Code}\label{luado} | 2182 | \subsection{Executing Lua Chunks}\label{luado} |
2032 | A host program can execute Lua chunks written in a file or in a string | 2183 | A host program can execute Lua chunks written in a file or in a string |
2033 | by using the following functions:% | 2184 | by using the following functions: |
2034 | \begin{verbatim} | 2185 | \begin{verbatim} |
2035 | int lua_dofile (lua_State *L, const char *filename); | 2186 | int lua_dofile (lua_State *L, const char *filename); |
2036 | int lua_dostring (lua_State *L, const char *string); | 2187 | int lua_dostring (lua_State *L, const char *string); |
@@ -2039,7 +2190,9 @@ by using the following functions:% | |||
2039 | \end{verbatim} | 2190 | \end{verbatim} |
2040 | \DefAPI{lua_dofile}\DefAPI{lua_dostring}\DefAPI{lua_dobuffer}% | 2191 | \DefAPI{lua_dofile}\DefAPI{lua_dostring}\DefAPI{lua_dobuffer}% |
2041 | These functions return | 2192 | These functions return |
2042 | 0 in case of success, or one of the following error codes if they fail: | 2193 | 0 in case of success, or one of the following error codes |
2194 | (defined in \verb|lua.h|) | ||
2195 | if they fail: | ||
2043 | \begin{itemize} | 2196 | \begin{itemize} |
2044 | \item \IndexAPI{LUA_ERRRUN} --- | 2197 | \item \IndexAPI{LUA_ERRRUN} --- |
2045 | error while running the chunk. | 2198 | error while running the chunk. |
@@ -2059,7 +2212,6 @@ check \verb|errno|, | |||
2059 | call \verb|strerror|, | 2212 | call \verb|strerror|, |
2060 | or call \verb|perror| to tell the user what went wrong. | 2213 | or call \verb|perror| to tell the user what went wrong. |
2061 | \end{itemize} | 2214 | \end{itemize} |
2062 | These constants are defined in \verb|lua.h|. | ||
2063 | 2215 | ||
2064 | When called with argument \verb|NULL|, | 2216 | When called with argument \verb|NULL|, |
2065 | \verb|lua_dofile| executes the \verb|stdin| stream. | 2217 | \verb|lua_dofile| executes the \verb|stdin| stream. |
@@ -2080,6 +2232,7 @@ These functions push onto the stack | |||
2080 | any values eventually returned by the chunk. | 2232 | any values eventually returned by the chunk. |
2081 | A chunk may return any number of values; | 2233 | A chunk may return any number of values; |
2082 | Lua takes care that these values fit into the stack space, | 2234 | Lua takes care that these values fit into the stack space, |
2235 | %% TODO: how? o que acontece se nao da'? | ||
2083 | but after the call the responsibility is back to you. | 2236 | but after the call the responsibility is back to you. |
2084 | If you need to push other elements after calling any of these functions, | 2237 | If you need to push other elements after calling any of these functions, |
2085 | and you want to ``play safe'', | 2238 | and you want to ``play safe'', |
@@ -2088,7 +2241,7 @@ with \verb|lua_stackspace| | |||
2088 | or remove the returned elements | 2241 | or remove the returned elements |
2089 | from the stack (if you do not need them). | 2242 | from the stack (if you do not need them). |
2090 | For instance, the following code | 2243 | For instance, the following code |
2091 | loads a chunk in a file and discards all results returned by this chunk, | 2244 | executes a chunk from a file and discards all results returned by this chunk, |
2092 | leaving the stack as it was before the call: | 2245 | leaving the stack as it was before the call: |
2093 | \begin{verbatim} | 2246 | \begin{verbatim} |
2094 | { | 2247 | { |
@@ -2098,8 +2251,18 @@ leaving the stack as it was before the call: | |||
2098 | } | 2251 | } |
2099 | \end{verbatim} | 2252 | \end{verbatim} |
2100 | 2253 | ||
2254 | \subsection{Loading Lua Chunks} | ||
2255 | You can load Lua chunks without executing them with | ||
2256 | \begin{verbatim} | ||
2257 | int lua_loadfile (lua_State *L, const char *filename); | ||
2258 | int lua_loadbuffer (lua_State *L, const char *buff, | ||
2259 | size_t size, const char *name); | ||
2260 | \end{verbatim} | ||
2261 | The compiled chunk is left as a function on top of the stack. | ||
2262 | The return values are the same as those of | ||
2263 | \verb|lua_dofile| and \verb|lua_dobuffer|. | ||
2101 | 2264 | ||
2102 | \subsection{Manipulating Global Variables in Lua} | 2265 | \subsection{Manipulating Global Variables} |
2103 | 2266 | ||
2104 | To read the value of a global Lua variable, | 2267 | To read the value of a global Lua variable, |
2105 | you call | 2268 | you call |
@@ -2108,6 +2271,8 @@ you call | |||
2108 | \end{verbatim} | 2271 | \end{verbatim} |
2109 | \DefAPI{lua_getglobal} | 2272 | \DefAPI{lua_getglobal} |
2110 | which pushes onto the stack the value of the given variable. | 2273 | which pushes onto the stack the value of the given variable. |
2274 | (The string \verb|varname| does not need to be a | ||
2275 | syntactically valid variable name.) | ||
2111 | As in Lua, this function may trigger a tag method | 2276 | As in Lua, this function may trigger a tag method |
2112 | for the ``getglobal'' event \see{tag-method}. | 2277 | for the ``getglobal'' event \see{tag-method}. |
2113 | To read the real value of a global variable, | 2278 | To read the real value of a global variable, |
@@ -2122,6 +2287,8 @@ you call | |||
2122 | \end{verbatim} | 2287 | \end{verbatim} |
2123 | \DefAPI{lua_setglobal} | 2288 | \DefAPI{lua_setglobal} |
2124 | which pops from the stack the value to be stored in the given variable. | 2289 | which pops from the stack the value to be stored in the given variable. |
2290 | (The string \verb|varname| does not need to be a | ||
2291 | syntactically valid variable name.) | ||
2125 | As in Lua, this function may trigger a tag method | 2292 | As in Lua, this function may trigger a tag method |
2126 | for the ``setglobal'' event \see{tag-method}. | 2293 | for the ``setglobal'' event \see{tag-method}. |
2127 | To set the real value of a global variable, | 2294 | To set the real value of a global variable, |
@@ -2144,19 +2311,30 @@ you call | |||
2144 | \DefAPI{lua_setglobals} | 2311 | \DefAPI{lua_setglobals} |
2145 | The table to be used is popped from the stack. | 2312 | The table to be used is popped from the stack. |
2146 | 2313 | ||
2147 | \subsection{Manipulating Tables in Lua} | 2314 | \subsection{Manipulating Tables} |
2148 | Lua tables can also be manipulated through the API. | ||
2149 | 2315 | ||
2150 | To read a value from a table, call | 2316 | Tables are created by calling |
2317 | The function | ||
2318 | \begin{verbatim} | ||
2319 | void lua_newtable (lua_State *L); | ||
2320 | \end{verbatim} | ||
2321 | \DefAPI{lua_newtable} | ||
2322 | This function creates a new, empty table and pushes it onto the stack. | ||
2323 | |||
2324 | To read a value from a table that resides somewhere in the stack, | ||
2325 | call | ||
2151 | \begin{verbatim} | 2326 | \begin{verbatim} |
2152 | void lua_gettable (lua_State *L, int index); | 2327 | void lua_gettable (lua_State *L, int index); |
2153 | \end{verbatim} | 2328 | \end{verbatim} |
2154 | \DefAPI{lua_gettable} | 2329 | \DefAPI{lua_gettable} |
2155 | where \verb|index| refers to the table. | 2330 | where \verb|index| refers to the table. |
2156 | \verb|lua_gettable| pops a key from the stack, | 2331 | \verb|lua_gettable| pops a key from the stack |
2157 | and returns (on the stack) the contents of the table at that key. | 2332 | and returns (on the stack) the contents of the table at that key. |
2158 | As in Lua, this operation may trigger a tag method | 2333 | The table is left where it was in the stack; |
2159 | for the ``gettable'' event. | 2334 | this is convenient for getting multiple values from a table. |
2335 | |||
2336 | As in Lua, this function may trigger a tag method | ||
2337 | for the ``gettable'' event \see{tag-method}. | ||
2160 | To get the real value of any table key, | 2338 | To get the real value of any table key, |
2161 | without invoking any tag method, | 2339 | without invoking any tag method, |
2162 | use the \emph{raw} version: | 2340 | use the \emph{raw} version: |
@@ -2175,6 +2353,9 @@ and then call | |||
2175 | \DefAPI{lua_settable} | 2353 | \DefAPI{lua_settable} |
2176 | where \verb|index| refers to the table. | 2354 | where \verb|index| refers to the table. |
2177 | \verb|lua_settable| pops from the stack both the key and the value. | 2355 | \verb|lua_settable| pops from the stack both the key and the value. |
2356 | The table is left where it was in the stack; | ||
2357 | this is convenient for setting multiple values in a table. | ||
2358 | |||
2178 | As in Lua, this operation may trigger a tag method | 2359 | As in Lua, this operation may trigger a tag method |
2179 | for the ``settable'' event. | 2360 | for the ``settable'' event. |
2180 | To set the real value of any table index, | 2361 | To set the real value of any table index, |
@@ -2185,12 +2366,50 @@ use the \emph{raw} version: | |||
2185 | \end{verbatim} | 2366 | \end{verbatim} |
2186 | \DefAPI{lua_rawset} | 2367 | \DefAPI{lua_rawset} |
2187 | 2368 | ||
2188 | Finally, the function | 2369 | You can traverse a table with the function |
2189 | \begin{verbatim} | 2370 | \begin{verbatim} |
2190 | void lua_newtable (lua_State *L); | 2371 | int lua_next (lua_State *L, int index); |
2191 | \end{verbatim} | 2372 | \end{verbatim} |
2192 | \DefAPI{lua_newtable} | 2373 | \DefAPI{lua_next} |
2193 | creates a new, empty table and pushes it onto the stack. | 2374 | where \verb|index| refers to the table to be traversed. |
2375 | The function pops a key from the stack, | ||
2376 | and pushes a key-value pair from the table | ||
2377 | (the ``next'' pair after the given key). | ||
2378 | If there are no more elements, then \verb|lua_next| returns 0 | ||
2379 | (and pushes nothing). | ||
2380 | Use a \nil\ key to signal the start of a traversal. | ||
2381 | |||
2382 | A typical traversal looks like this: | ||
2383 | \begin{verbatim} | ||
2384 | /* table is in the stack at index `t' */ | ||
2385 | lua_pushnil(L); /* first key */ | ||
2386 | while (lua_next(L, t) != 0) { | ||
2387 | /* `key' is at index -2 and `value' at index -1 */ | ||
2388 | printf("%s - %s\n", | ||
2389 | lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); | ||
2390 | lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */ | ||
2391 | } | ||
2392 | \end{verbatim} | ||
2393 | |||
2394 | NOTE: | ||
2395 | Do not call \verb|lua_tostring| on a key, | ||
2396 | unless you know the key is actually a string. | ||
2397 | Recall that \verb|lua_tostring| \emph{changes} the value at the given index; | ||
2398 | this confuses \verb|lua_next|. | ||
2399 | |||
2400 | The following functions control the weak mode of a table: | ||
2401 | \begin{verbatim} | ||
2402 | void lua_setweakmode (lua_State *L, int mode); | ||
2403 | int lua_getweakmode (lua_State *L, int index); | ||
2404 | \end{verbatim} | ||
2405 | \DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode} | ||
2406 | Both functions operate over the table at the top of the stack. | ||
2407 | Modes are described as bit sets, so that | ||
2408 | \verb|LUA_WEAK_KEY| means weak keys, | ||
2409 | \verb|LUA_WEAK_VALUE| means weak values, | ||
2410 | \verb"LUA_WEAK_KEY | LUA_WEAK_VALUE" means both, | ||
2411 | and zero means none. | ||
2412 | |||
2194 | 2413 | ||
2195 | \subsection{Using Tables as Arrays} | 2414 | \subsection{Using Tables as Arrays} |
2196 | The API has functions that help to use Lua tables as arrays, | 2415 | The API has functions that help to use Lua tables as arrays, |
@@ -2210,15 +2429,15 @@ at stack position \verb|index|. | |||
2210 | 2429 | ||
2211 | \verb|lua_rawseti| sets the value of the \M{n}-th element of the table | 2430 | \verb|lua_rawseti| sets the value of the \M{n}-th element of the table |
2212 | at stack position \verb|index| to the value at the top of the stack, | 2431 | at stack position \verb|index| to the value at the top of the stack, |
2213 | removing the value from the stack. | 2432 | removing this value from the stack. |
2214 | 2433 | ||
2215 | \verb|lua_getn| returns the number of elements in the table | 2434 | \verb|lua_getn| returns the number of elements in the table |
2216 | at stack position \verb|index|. | 2435 | at stack position \verb|index|. |
2217 | This number is the value of the table field \verb|n|, | 2436 | This number is the value of the table field \verb|n|, |
2218 | if it has a numeric value, | 2437 | if it has a numeric value, |
2219 | or the largest numerical index with a non-nil value in the table. | 2438 | or the largest numerical index with a non-\nil\ value in the table. |
2220 | 2439 | ||
2221 | \subsection{Calling Lua Functions} | 2440 | \subsection{Calling Functions} |
2222 | 2441 | ||
2223 | Functions defined in Lua | 2442 | Functions defined in Lua |
2224 | (and C~functions registered in Lua) | 2443 | (and C~functions registered in Lua) |
@@ -2226,7 +2445,7 @@ can be called from the host program. | |||
2226 | This is done using the following protocol: | 2445 | This is done using the following protocol: |
2227 | First, the function to be called is pushed onto the stack; | 2446 | First, the function to be called is pushed onto the stack; |
2228 | then, the arguments to the function are pushed | 2447 | then, the arguments to the function are pushed |
2229 | \see{pushing} in \emph{direct order}, that is, the first argument is pushed first. | 2448 | in \emph{direct order}, that is, the first argument is pushed first. |
2230 | Finally, the function is called using | 2449 | Finally, the function is called using |
2231 | \begin{verbatim} | 2450 | \begin{verbatim} |
2232 | int lua_call (lua_State *L, int nargs, int nresults); | 2451 | int lua_call (lua_State *L, int nargs, int nresults); |
@@ -2235,6 +2454,7 @@ Finally, the function is called using | |||
2235 | This function returns the same error codes as \verb|lua_dostring| and | 2454 | This function returns the same error codes as \verb|lua_dostring| and |
2236 | friends \see{luado}. | 2455 | friends \see{luado}. |
2237 | If you want to propagate the error, | 2456 | If you want to propagate the error, |
2457 | %% TODO: explain 'propagate'. | ||
2238 | instead of returning an error code, | 2458 | instead of returning an error code, |
2239 | use | 2459 | use |
2240 | \begin{verbatim} | 2460 | \begin{verbatim} |
@@ -2249,23 +2469,23 @@ and the function results are pushed. | |||
2249 | The number of results are adjusted to \verb|nresults|, | 2469 | The number of results are adjusted to \verb|nresults|, |
2250 | unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. | 2470 | unless \verb|nresults| is \IndexAPI{LUA_MULTRET}. |
2251 | In that case, \emph{all} results from the function are pushed. | 2471 | In that case, \emph{all} results from the function are pushed. |
2252 | The function results are pushed in direct order | 2472 | The function results are pushed onto the stack in direct order |
2253 | (the first result is pushed first), | 2473 | (the first result is pushed first), |
2254 | so that after the call the last result is on the top. | 2474 | so that after the call the last result is on the top. |
2255 | 2475 | ||
2256 | The following example shows how the host program may do the | 2476 | The following example shows how the host program may do the |
2257 | equivalent to the Lua code: | 2477 | equivalent to the Lua code: |
2258 | \begin{verbatim} | 2478 | \begin{verbatim} |
2259 | a,b = f("how", t.x, 4) | 2479 | a,b = f("how", t.x, 14) |
2260 | \end{verbatim} | 2480 | \end{verbatim} |
2261 | Here it is in~C: | 2481 | Here it is in~C: |
2262 | \begin{verbatim} | 2482 | \begin{verbatim} |
2263 | lua_getglobal(L, "t"); /* global `t' (for later use) */ | 2483 | lua_getglobal(L, "t"); /* global `t' (for later use) */ |
2264 | lua_getglobal(L, "f"); /* function to be called */ | 2484 | lua_getglobal(L, "f"); /* function to be called */ |
2265 | lua_pushstring(L, "how"); /* 1st argument */ | 2485 | lua_pushstring(L, "how"); /* 1st argument */ |
2266 | lua_pushstring(L, "x"); /* push the string `x' */ | 2486 | lua_pushstring(L, "x"); /* push the string "x" */ |
2267 | lua_gettable(L, -4); /* push result of t.x (2nd arg) */ | 2487 | lua_gettable(L, -4); /* push result of t.x (2nd arg) */ |
2268 | lua_pushnumber(L, 4); /* 3rd argument */ | 2488 | lua_pushnumber(L, 14); /* 3rd argument */ |
2269 | lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */ | 2489 | lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */ |
2270 | lua_setglobal(L, "b"); /* set global variable `b' */ | 2490 | lua_setglobal(L, "b"); /* set global variable `b' */ |
2271 | lua_setglobal(L, "a"); /* set global variable `a' */ | 2491 | lua_setglobal(L, "a"); /* set global variable `a' */ |
@@ -2277,7 +2497,7 @@ This is considered good programming practice. | |||
2277 | 2497 | ||
2278 | \medskip | 2498 | \medskip |
2279 | 2499 | ||
2280 | 2500 | %% TODO: mover essas 2 para algum lugar melhor. | |
2281 | Some special Lua functions have their own C~interfaces. | 2501 | Some special Lua functions have their own C~interfaces. |
2282 | The host program can generate a Lua error calling the function | 2502 | The host program can generate a Lua error calling the function |
2283 | \begin{verbatim} | 2503 | \begin{verbatim} |
@@ -2296,8 +2516,18 @@ the \verb|message| is passed to the error handler function, | |||
2296 | If \verb|message| is \verb|NULL|, | 2516 | If \verb|message| is \verb|NULL|, |
2297 | then \verb|_ERRORMESSAGE| is not called. | 2517 | then \verb|_ERRORMESSAGE| is not called. |
2298 | 2518 | ||
2299 | \medskip | 2519 | The function |
2520 | \begin{verbatim} | ||
2521 | void lua_concat (lua_State *L, int n); | ||
2522 | \end{verbatim} | ||
2523 | \DefAPI{lua_concat} | ||
2524 | concatenates the \verb|n| values at the top of the stack, | ||
2525 | pops them, and leaves the result at the top; | ||
2526 | \verb|n|~must be at least 2. | ||
2527 | Concatenation is done following the usual semantics of Lua | ||
2528 | \see{concat}. | ||
2300 | 2529 | ||
2530 | \subsection{Manipulating Tag Methods} | ||
2301 | Tag methods can be changed with | 2531 | Tag methods can be changed with |
2302 | \begin{verbatim} | 2532 | \begin{verbatim} |
2303 | void lua_settagmethod (lua_State *L, int tag, const char *event); | 2533 | void lua_settagmethod (lua_State *L, int tag, const char *event); |
@@ -2321,62 +2551,17 @@ to another: | |||
2321 | \DefAPI{lua_copytagmethods} | 2551 | \DefAPI{lua_copytagmethods} |
2322 | This function returns \verb|tagto|. | 2552 | This function returns \verb|tagto|. |
2323 | 2553 | ||
2324 | \medskip | ||
2325 | |||
2326 | You can traverse a table with the function | ||
2327 | \begin{verbatim} | ||
2328 | int lua_next (lua_State *L, int index); | ||
2329 | \end{verbatim} | ||
2330 | \DefAPI{lua_next} | ||
2331 | where \verb|index| refers to the table to be traversed. | ||
2332 | The function pops a key from the stack, | ||
2333 | and pushes a key-value pair from the table | ||
2334 | (the ``next'' pair after the given key). | ||
2335 | If there are no more elements, then the function returns 0 | ||
2336 | (and pushes nothing). | ||
2337 | A typical traversal looks like this: | ||
2338 | \begin{verbatim} | ||
2339 | /* table is in the stack at index `t' */ | ||
2340 | lua_pushnil(L); /* first key */ | ||
2341 | while (lua_next(L, t) != 0) { | ||
2342 | /* `key' is at index -2 and `value' at index -1 */ | ||
2343 | printf("%s - %s\n", | ||
2344 | lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); | ||
2345 | lua_pop(L, 1); /* removes `value'; keeps `index' for next iteration */ | ||
2346 | } | ||
2347 | \end{verbatim} | ||
2348 | |||
2349 | The function | ||
2350 | \begin{verbatim} | ||
2351 | void lua_concat (lua_State *L, int n); | ||
2352 | \end{verbatim} | ||
2353 | \DefAPI{lua_concat} | ||
2354 | concatenates the \verb|n| values at the top of the stack, | ||
2355 | pops them, and leaves the result at the top; | ||
2356 | \verb|n|~must be at least 2. | ||
2357 | Concatenation is done following the usual semantics of Lua | ||
2358 | \see{concat}. | ||
2359 | |||
2360 | 2554 | ||
2361 | \subsection{Defining C Functions} \label{LuacallC} | 2555 | \subsection{Defining C Functions} \label{LuacallC} |
2362 | To register a C~function to Lua, | 2556 | Lua can be extended with functions written in~C. |
2363 | there is the following convenience macro: | 2557 | These functions must be of type \verb|lua_CFunction|, |
2364 | \begin{verbatim} | ||
2365 | #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) | ||
2366 | /* const char *n; */ | ||
2367 | /* lua_CFunction f; */ | ||
2368 | \end{verbatim} | ||
2369 | \DefAPI{lua_register} | ||
2370 | which receives the name the function will have in Lua, | ||
2371 | and a pointer to the function. | ||
2372 | This pointer must have type \verb|lua_CFunction|, | ||
2373 | which is defined as | 2558 | which is defined as |
2374 | \begin{verbatim} | 2559 | \begin{verbatim} |
2375 | typedef int (*lua_CFunction) (lua_State *L); | 2560 | typedef int (*lua_CFunction) (lua_State *L); |
2376 | \end{verbatim} | 2561 | \end{verbatim} |
2377 | \DefAPI{lua_CFunction} | 2562 | \DefAPI{lua_CFunction} |
2378 | that is, a pointer to a function with integer result and a single argument, | 2563 | A C~function receives a Lua environment and returns an integer, |
2379 | a Lua environment. | 2564 | the number of values it has returned to Lua. |
2380 | 2565 | ||
2381 | In order to communicate properly with Lua, | 2566 | In order to communicate properly with Lua, |
2382 | a C~function must follow the following protocol, | 2567 | a C~function must follow the following protocol, |
@@ -2394,7 +2579,7 @@ of numerical arguments and returns their average and sum: | |||
2394 | \begin{verbatim} | 2579 | \begin{verbatim} |
2395 | static int foo (lua_State *L) { | 2580 | static int foo (lua_State *L) { |
2396 | int n = lua_gettop(L); /* number of arguments */ | 2581 | int n = lua_gettop(L); /* number of arguments */ |
2397 | double sum = 0; | 2582 | lua_Number sum = 0; |
2398 | int i; | 2583 | int i; |
2399 | for (i = 1; i <= n; i++) { | 2584 | for (i = 1; i <= n; i++) { |
2400 | if (!lua_isnumber(L, i)) | 2585 | if (!lua_isnumber(L, i)) |
@@ -2406,11 +2591,25 @@ of numerical arguments and returns their average and sum: | |||
2406 | return 2; /* number of results */ | 2591 | return 2; /* number of results */ |
2407 | } | 2592 | } |
2408 | \end{verbatim} | 2593 | \end{verbatim} |
2409 | This function may be registered in Lua as `\verb|average|' by calling | 2594 | |
2595 | To register a C~function to Lua, | ||
2596 | there is the following convenience macro: | ||
2597 | \begin{verbatim} | ||
2598 | #define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) | ||
2599 | /* const char *n; */ | ||
2600 | /* lua_CFunction f; */ | ||
2601 | \end{verbatim} | ||
2602 | \DefAPI{lua_register} | ||
2603 | which receives the name the function will have in Lua, | ||
2604 | and a pointer to the function. | ||
2605 | Thus, | ||
2606 | the C~function `\verb|foo|' above may be registered in Lua as `\verb|average|' | ||
2607 | by calling | ||
2410 | \begin{verbatim} | 2608 | \begin{verbatim} |
2411 | lua_register(L, "average", foo); | 2609 | lua_register(L, "average", foo); |
2412 | \end{verbatim} | 2610 | \end{verbatim} |
2413 | 2611 | ||
2612 | \subsection{Defining C Closures} | ||
2414 | 2613 | ||
2415 | When a C~function is created, | 2614 | When a C~function is created, |
2416 | it is possible to associate some \emph{upvalues} to it | 2615 | it is possible to associate some \emph{upvalues} to it |
@@ -2440,12 +2639,13 @@ This makes it easy to get the upvalues without knowing how many arguments | |||
2440 | the function received (recall that functions in Lua can receive any number of | 2639 | the function received (recall that functions in Lua can receive any number of |
2441 | arguments): The \M{i}-th upvalue is in the stack at index \Math{i-(n+1)}, | 2640 | arguments): The \M{i}-th upvalue is in the stack at index \Math{i-(n+1)}, |
2442 | where \M{n} is the number of upvalues. | 2641 | where \M{n} is the number of upvalues. |
2642 | (A C~function that uses upvalues must know beforehand how many it expects.) | ||
2443 | 2643 | ||
2444 | For more examples of C~functions and closures, see files | 2644 | For examples of C~functions and closures, see files |
2445 | \verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c| | 2645 | \verb|lbaselib.c|, \verb|liolib.c|, \verb|lmathlib.c|, and \verb|lstrlib.c| |
2446 | in the official Lua distribution. | 2646 | in the official Lua distribution. |
2447 | 2647 | ||
2448 | \subsection{References to Lua Objects} | 2648 | \subsection{References to Lua Values} \label{lock} |
2449 | 2649 | ||
2450 | If the C~code needs to keep a Lua value | 2650 | If the C~code needs to keep a Lua value |
2451 | outside the life span of a C~function, | 2651 | outside the life span of a C~function, |
@@ -2463,9 +2663,11 @@ the stack, creates a reference to it, | |||
2463 | and returns this reference. | 2663 | and returns this reference. |
2464 | For a \nil\ value, | 2664 | For a \nil\ value, |
2465 | the reference is always \verb|LUA_REFNIL|.\DefAPI{LUA_REFNIL} | 2665 | the reference is always \verb|LUA_REFNIL|.\DefAPI{LUA_REFNIL} |
2666 | %% TODO: why LUA_REFNIL? pode-se chamar lua_getref(L,LUA_REFNIL)? | ||
2466 | (\verb|lua.h| also defines a constant \verb|LUA_NOREF| \DefAPI{LUA_NOREF} | 2667 | (\verb|lua.h| also defines a constant \verb|LUA_NOREF| \DefAPI{LUA_NOREF} |
2467 | that | 2668 | that |
2468 | is different from any valid reference.) | 2669 | is different from any valid reference.) |
2670 | %% TODO: give example of use of LUA_NOREF | ||
2469 | If \verb|lock| is not zero, then the object is \emph{locked}: | 2671 | If \verb|lock| is not zero, then the object is \emph{locked}: |
2470 | this means the object will not be garbage collected. | 2672 | this means the object will not be garbage collected. |
2471 | \emph{Unlocked references may be garbage collected}. | 2673 | \emph{Unlocked references may be garbage collected}. |
@@ -2481,12 +2683,13 @@ it should be released with a call to \verb|lua_unref|. | |||
2481 | 2683 | ||
2482 | 2684 | ||
2483 | \subsubsection*{Registry} | 2685 | \subsubsection*{Registry} |
2686 | %% TODO: nao precisa de secao propria? explicar melhor o uso. | ||
2484 | 2687 | ||
2485 | When Lua starts, it registers a table at position | 2688 | When Lua starts, it registers a table at position |
2486 | \IndexAPI{LUA_REFREGISTRY}. | 2689 | \IndexAPI{LUA_REFREGISTRY}. |
2487 | It can be accessed through the macro | 2690 | It can be accessed through the macro |
2488 | \begin{verbatim} | 2691 | \begin{verbatim} |
2489 | #define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY) | 2692 | #define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY) |
2490 | \end{verbatim} | 2693 | \end{verbatim} |
2491 | \DefAPI{lua_getregistry} | 2694 | \DefAPI{lua_getregistry} |
2492 | This table can be used by C~libraries as a general registry mechanism. | 2695 | This table can be used by C~libraries as a general registry mechanism. |
@@ -2495,37 +2698,237 @@ as long as it chooses a key different from other libraries. | |||
2495 | 2698 | ||
2496 | 2699 | ||
2497 | 2700 | ||
2498 | \subsection{Weak Tables} | 2701 | %------------------------------------------------------------------------------ |
2702 | \section{The Debug Interface} \label{debugI} | ||
2703 | |||
2704 | Lua has no built-in debugging facilities. | ||
2705 | Instead, it offers a special interface, | ||
2706 | by means of functions and \emph{hooks}, | ||
2707 | which allows the construction of different | ||
2708 | kinds of debuggers, profilers, and other tools | ||
2709 | that need ``inside information'' from the interpreter. | ||
2710 | This interface is declared in \verb|luadebug.h|. | ||
2711 | |||
2712 | \subsection{Stack and Function Information} | ||
2713 | |||
2714 | The main function to get information about the interpreter stack is | ||
2715 | \begin{verbatim} | ||
2716 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); | ||
2717 | \end{verbatim} | ||
2718 | \DefAPI{lua_getstack} | ||
2719 | This function fills parts of a \verb|lua_Debug| structure with | ||
2720 | an identification of the \emph{activation record} | ||
2721 | of the function executing at a given level. | ||
2722 | Level~0 is the current running function, | ||
2723 | whereas level \Math{n+1} is the function that has called level \Math{n}. | ||
2724 | Usually, \verb|lua_getstack| returns 1; | ||
2725 | when called with a level greater than the stack depth, | ||
2726 | it returns 0. | ||
2499 | 2727 | ||
2500 | The following constants and functions control the weak mode of a table: | 2728 | The structure \verb|lua_Debug| is used to carry different pieces of |
2729 | information about an active function: | ||
2501 | \begin{verbatim} | 2730 | \begin{verbatim} |
2502 | #define LUA_WEAK_KEY ... | 2731 | typedef struct lua_Debug { |
2503 | #define LUA_WEAK_VALUE ... | 2732 | const char *event; /* "call", "return" */ |
2733 | int currentline; /* (l) */ | ||
2734 | const char *name; /* (n) */ | ||
2735 | const char *namewhat; /* (n) global, tag method, local, field */ | ||
2736 | int nups; /* (u) number of upvalues */ | ||
2737 | int linedefined; /* (S) */ | ||
2738 | const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ | ||
2739 | const char *source; /* (S) */ | ||
2740 | char short_src[LUA_IDSIZE]; /* (S) */ | ||
2741 | |||
2742 | /* private part */ | ||
2743 | ... | ||
2744 | } lua_Debug; | ||
2504 | \end{verbatim} | 2745 | \end{verbatim} |
2746 | \DefAPI{lua_Debug} | ||
2747 | \verb|lua_getstack| fills only the private part | ||
2748 | of this structure, for future use. | ||
2749 | To fill the other fields of \verb|lua_Debug| with useful information, | ||
2750 | call | ||
2505 | \begin{verbatim} | 2751 | \begin{verbatim} |
2506 | void lua_setweakmode (lua_State *L, int mode); | 2752 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); |
2507 | int lua_getweakmode (lua_State *L, int index); | ||
2508 | \end{verbatim} | 2753 | \end{verbatim} |
2509 | \DefAPI{lua_setweakmode}\DefAPI{lua_getweakmode} | 2754 | \DefAPI{lua_getinfo} |
2510 | Both functions operate over the table at the top of the stack. | 2755 | This function returns 0 on error |
2511 | Modes are described as bit sets, so that | 2756 | (for instance, an invalid option in \verb|what|). |
2512 | \verb|LUA_WEAK_KEY| means weak keys, | 2757 | Each character in the string \verb|what| |
2513 | \verb|LUA_WEAK_VALUE| means weak values, | 2758 | selects some fields of \verb|ar| to be filled, |
2514 | \verb|LUA_WEAK_KEY | LUA_WEAK_VALUE| means both, | 2759 | as indicated by the letter in parentheses in the definition of \verb|lua_Debug| |
2515 | and zero means none. | 2760 | above: |
2761 | `\verb|S|' fills in the fields \verb|source|, \verb|linedefined|, | ||
2762 | and \verb|what|; | ||
2763 | `\verb|l|' fills in the field \verb|currentline|, etc. | ||
2764 | Moreover, `\verb|f|' pushes onto the stack the function that is | ||
2765 | running at the given level. | ||
2766 | |||
2767 | To get information about a function that is not active (that is, | ||
2768 | it is not in the stack), | ||
2769 | you push the function onto the stack, | ||
2770 | and start the \verb|what| string with the character `\verb|>|'. | ||
2771 | For instance, to know in which line a function \verb|f| was defined, | ||
2772 | you can write | ||
2773 | \begin{verbatim} | ||
2774 | lua_Debug ar; | ||
2775 | lua_getglobal(L, "f"); | ||
2776 | lua_getinfo(L, ">S", &ar); | ||
2777 | printf("%d\n", ar.linedefined); | ||
2778 | \end{verbatim} | ||
2779 | The fields of \verb|lua_Debug| have the following meaning: | ||
2780 | \begin{description}\leftskip=20pt | ||
2781 | |||
2782 | \item[source] | ||
2783 | If the function was defined in a string, | ||
2784 | then \verb|source| is that string; | ||
2785 | if the function was defined in a file, | ||
2786 | then \verb|source| starts with a \verb|@| followed by the file name. | ||
2787 | |||
2788 | \item[short\_src] | ||
2789 | A ``printable'' version of \verb|source|, to be used in error messages. | ||
2790 | |||
2791 | \item[linedefined] | ||
2792 | the line number where the definition of the function starts. | ||
2516 | 2793 | ||
2794 | \item[what] the string \verb|"Lua"| if this is a Lua function, | ||
2795 | \verb|"C"| if this is a C~function, | ||
2796 | or \verb|"main"| if this is the main part of a chunk. | ||
2517 | 2797 | ||
2518 | \section{Standard Libraries} | 2798 | \item[currentline] |
2799 | the current line where the given function is executing. | ||
2800 | When no line information is available, | ||
2801 | \verb|currentline| is set to \Math{-1}. | ||
2802 | |||
2803 | \item[name] | ||
2804 | a reasonable name for the given function. | ||
2805 | Because functions in Lua are first class values, | ||
2806 | they do not have a fixed name: | ||
2807 | Some functions may be the value of many global variables, | ||
2808 | while others may be stored only in a table field. | ||
2809 | The \verb|lua_getinfo| function checks whether the given | ||
2810 | function is a tag method or the value of a global variable. | ||
2811 | If the given function is a tag method, | ||
2812 | then \verb|name| points to the event name. | ||
2813 | %% TODO: mas qual o tag? Agora que temos tipos com nome, seria util saber | ||
2814 | %% o tipo de TM. Em particular para mensagens de erro. | ||
2815 | If the given function is the value of a global variable, | ||
2816 | then \verb|name| points to the variable name. | ||
2817 | If the given function is neither a tag method nor a global variable, | ||
2818 | then \verb|name| is set to \verb|NULL|. | ||
2819 | |||
2820 | \item[namewhat] | ||
2821 | Explains the previous field. | ||
2822 | If the function is a global variable, | ||
2823 | \verb|namewhat| is \verb|"global"|; | ||
2824 | if the function is a tag method, | ||
2825 | \verb|namewhat| is \verb|"tag-method"|; | ||
2826 | otherwise, \verb|namewhat| is \verb|""| (the empty string). | ||
2827 | |||
2828 | \item[nups] | ||
2829 | Number of upvalues of the function. | ||
2830 | |||
2831 | \end{description} | ||
2832 | |||
2833 | |||
2834 | \subsection{Manipulating Local Variables} | ||
2835 | |||
2836 | For the manipulation of local variables, | ||
2837 | \verb|luadebug.h| uses indices: | ||
2838 | The first parameter or local variable has index~1, and so on, | ||
2839 | until the last active local variable. | ||
2840 | |||
2841 | The following functions allow the manipulation of the | ||
2842 | local variables of a given activation record: | ||
2843 | \begin{verbatim} | ||
2844 | const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); | ||
2845 | const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); | ||
2846 | \end{verbatim} | ||
2847 | \DefAPI{lua_getlocal}\DefAPI{lua_setlocal} | ||
2848 | The parameter \verb|ar| must be a valid activation record, | ||
2849 | filled by a previous call to \verb|lua_getstack| or | ||
2850 | given as argument to a hook \see{sub-hooks}. | ||
2851 | \verb|lua_getlocal| gets the index \verb|n| of a local variable, | ||
2852 | pushes its value onto the stack, | ||
2853 | and returns its name. | ||
2854 | %% TODO: why return name? | ||
2855 | \verb|lua_setlocal| assigns the value at the top of the stack | ||
2856 | to the variable and returns its name. | ||
2857 | Both functions return \verb|NULL| on failure, | ||
2858 | that is | ||
2859 | when the index is greater than | ||
2860 | the number of active local variables. | ||
2861 | |||
2862 | As an example, the following function lists the names of all | ||
2863 | local variables for a function at a given level of the stack: | ||
2864 | \begin{verbatim} | ||
2865 | int listvars (lua_State *L, int level) { | ||
2866 | lua_Debug ar; | ||
2867 | int i = 1; | ||
2868 | const char *name; | ||
2869 | if (lua_getstack(L, level, &ar) == 0) | ||
2870 | return 0; /* failure: no such level in the stack */ | ||
2871 | while ((name = lua_getlocal(L, &ar, i++)) != NULL) { | ||
2872 | printf("%s\n", name); | ||
2873 | lua_pop(L, 1); /* remove variable value */ | ||
2874 | } | ||
2875 | return 1; | ||
2876 | } | ||
2877 | \end{verbatim} | ||
2878 | |||
2879 | |||
2880 | \subsection{Hooks}\label{sub-hooks} | ||
2881 | |||
2882 | The Lua interpreter offers two hooks for debugging purposes: | ||
2883 | a \emph{call} hook and a \emph{line} hook. | ||
2884 | Both have type \verb|lua_Hook|, defined as follows: | ||
2885 | \begin{verbatim} | ||
2886 | typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); | ||
2887 | \end{verbatim} | ||
2888 | \DefAPI{lua_Hook} | ||
2889 | You can set the hooks with the following functions: | ||
2890 | \begin{verbatim} | ||
2891 | lua_Hook lua_setcallhook (lua_State *L, lua_Hook func); | ||
2892 | lua_Hook lua_setlinehook (lua_State *L, lua_Hook func); | ||
2893 | \end{verbatim} | ||
2894 | \DefAPI{lua_setcallhook}\DefAPI{lua_setlinehook} | ||
2895 | A hook is disabled when its value is \verb|NULL|, | ||
2896 | which is the initial value of both hooks. | ||
2897 | The functions \verb|lua_setcallhook| and \verb|lua_setlinehook| | ||
2898 | set their corresponding hooks and return their previous values. | ||
2899 | |||
2900 | The call hook is called whenever the | ||
2901 | interpreter enters or leaves a function. | ||
2902 | The \verb|event| field of \verb|ar| has the strings \verb|"call"| | ||
2903 | or \verb|"return"|. | ||
2904 | This \verb|ar| can then be used in calls to \verb|lua_getinfo|, | ||
2905 | \verb|lua_getlocal|, and \verb|lua_setlocal| | ||
2906 | to get more information about the function and to manipulate its | ||
2907 | local variables. | ||
2908 | |||
2909 | The line hook is called every time the interpreter changes | ||
2910 | the line of code it is executing. | ||
2911 | The \verb|event| field of \verb|ar| has the string \verb|"line"|, | ||
2912 | and the \verb|currentline| field has the line number. | ||
2913 | Again, you can use this \verb|ar| in other calls to the debug API. | ||
2914 | |||
2915 | While Lua is running a hook, it disables other calls to hooks. | ||
2916 | Therefore, if a hook calls Lua to execute a function or a chunk, | ||
2917 | this execution ocurrs without any calls to hooks. | ||
2918 | |||
2919 | |||
2920 | %------------------------------------------------------------------------------ | ||
2921 | \section{Standard Libraries}\label{libraries} | ||
2519 | 2922 | ||
2520 | The standard libraries provide useful functions | 2923 | The standard libraries provide useful functions |
2521 | that are implemented directly through the standard API. | 2924 | that are implemented directly through the standard C~API. |
2522 | Therefore, they are not necessary to the language, | 2925 | Therefore, they are not essential to the language, |
2523 | and are provided as separate C~modules. | 2926 | and are provided as separate C~modules. |
2524 | Currently, Lua has the following standard libraries: | 2927 | Currently, Lua has the following standard libraries: |
2525 | \begin{itemize} | 2928 | \begin{itemize} |
2526 | \item basic library; | 2929 | \item basic library; |
2527 | \item string manipulation; | 2930 | \item string manipulation; |
2528 | \item mathematical functions (sin, log, etc); | 2931 | \item mathematical functions (sin, log, etc.); |
2529 | \item input and output (plus some system facilities). | 2932 | \item input and output (plus some system facilities). |
2530 | \end{itemize} | 2933 | \end{itemize} |
2531 | To have access to these libraries, | 2934 | To have access to these libraries, |
@@ -2538,14 +2941,16 @@ and \verb|lua_iolibopen|, which are declared in \verb|lualib.h|. | |||
2538 | \DefAPI{lua_mathlibopen} | 2941 | \DefAPI{lua_mathlibopen} |
2539 | \DefAPI{lua_iolibopen} | 2942 | \DefAPI{lua_iolibopen} |
2540 | 2943 | ||
2944 | Lua's web site has links to Lua libraries written by users. | ||
2945 | |||
2541 | \subsection{Basic Functions} \label{predefined} | 2946 | \subsection{Basic Functions} \label{predefined} |
2542 | 2947 | ||
2543 | The basic library provides some core functions to Lua. | 2948 | The basic library provides some core functions to Lua. |
2544 | Therefore, if you do not include this library in your application, | 2949 | If you do not include this library in your application, |
2545 | you should check carefully whether you need to provide some alternative | 2950 | you should check carefully whether you need to provide some alternative |
2546 | implementation for some facilities. | 2951 | implementation for some facilities. |
2547 | (For instance, | 2952 | (For instance, |
2548 | without function \verb|_ERRORMESSAGE|, | 2953 | without an \verb|_ERRORMESSAGE| function, |
2549 | Lua is unable to show error messages.) | 2954 | Lua is unable to show error messages.) |
2550 | 2955 | ||
2551 | \subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert} | 2956 | \subsubsection*{\ff \T{_ALERT (message)}}\DefLIB{alert}\label{alert} |
@@ -2607,8 +3012,6 @@ If the new threshold is smaller than the byte counter, | |||
2607 | then Lua immediately runs the garbage collector \see{GC}. | 3012 | then Lua immediately runs the garbage collector \see{GC}. |
2608 | If \verb|limit| is absent, it defaults to zero | 3013 | If \verb|limit| is absent, it defaults to zero |
2609 | (thus forcing a garbage-collection cycle). | 3014 | (thus forcing a garbage-collection cycle). |
2610 | %\verb|collectgarbage| is equivalent to | ||
2611 | %the API function \verb|lua_setgcthreshold|. | ||
2612 | 3015 | ||
2613 | \subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}} | 3016 | \subsubsection*{\ff \T{copytagmethods (tagto, tagfrom)}} |
2614 | \DefLIB{copytagmethods} | 3017 | \DefLIB{copytagmethods} |
@@ -2617,8 +3020,7 @@ returns \verb|tagto|. | |||
2617 | 3020 | ||
2618 | \subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile} | 3021 | \subsubsection*{\ff \T{dofile (filename)}}\DefLIB{dofile} |
2619 | Receives a file name, | 3022 | Receives a file name, |
2620 | opens the named file, and executes its contents as a Lua chunk, | 3023 | opens the named file, and executes its contents as a Lua chunk. |
2621 | or as pre-compiled chunks. | ||
2622 | When called without arguments, | 3024 | When called without arguments, |
2623 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). | 3025 | \verb|dofile| executes the contents of the standard input (\verb|stdin|). |
2624 | If there is any error executing the file, | 3026 | If there is any error executing the file, |
@@ -2634,7 +3036,7 @@ It issues an error when called with a non-string argument. | |||
2634 | \subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring} | 3036 | \subsubsection*{\ff \T{dostring (string [, chunkname])}}\DefLIB{dostring} |
2635 | Executes a given string as a Lua chunk. | 3037 | Executes a given string as a Lua chunk. |
2636 | If there is any error executing the string, | 3038 | If there is any error executing the string, |
2637 | then \verb|dostring| returns \nil plus a string describing | 3039 | then \verb|dostring| returns \nil\ plus a string describing |
2638 | the error (see \verb|dofile|). | 3040 | the error (see \verb|dofile|). |
2639 | Otherwise, it returns the values returned by the chunk, | 3041 | Otherwise, it returns the values returned by the chunk, |
2640 | or a non-\nil\ value if the chunk returns no values. | 3042 | or a non-\nil\ value if the chunk returns no values. |
@@ -2650,16 +3052,15 @@ the last protected function called | |||
2650 | in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). | 3052 | in Lua: \verb|dofile|, \verb|dostring|, or \verb|call| in protected mode). |
2651 | If \verb|message| is \nil, then the error handler is not called. | 3053 | If \verb|message| is \nil, then the error handler is not called. |
2652 | Function \verb|error| never returns. | 3054 | Function \verb|error| never returns. |
2653 | %\verb|error| is equivalent to the API function \verb|lua_error|. | ||
2654 | 3055 | ||
2655 | \subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach} | 3056 | \subsubsection*{\ff \T{foreach (table, func)}}\DefLIB{foreach} |
2656 | Executes the given \verb|func| over all elements of \verb|table|. | 3057 | Executes the given \verb|func| over all elements of \verb|table|. |
2657 | For each element, the function is called with the index and | 3058 | For each element, the function is called with the index and |
2658 | respective value as arguments. | 3059 | respective value as arguments. |
2659 | If the function returns any non-\nil\ value, | 3060 | If the function returns a non-\nil\ value, |
2660 | then the loop is broken, and this value is returned | 3061 | then the loop is broken, and this value is returned |
2661 | as the final value of \verb|foreach|. | 3062 | as the final value of \verb|foreach|. |
2662 | This function could be defined in Lua: | 3063 | This function is equivalent to the following Lua function: |
2663 | \begin{verbatim} | 3064 | \begin{verbatim} |
2664 | function foreach (t, f) | 3065 | function foreach (t, f) |
2665 | for i, v in t do | 3066 | for i, v in t do |
@@ -2681,10 +3082,10 @@ respective value as arguments. | |||
2681 | Indices are visited in sequential order, | 3082 | Indices are visited in sequential order, |
2682 | from~1 to \verb|n|, | 3083 | from~1 to \verb|n|, |
2683 | where \verb|n| is the result of \verb|getn(table)| (see below). | 3084 | where \verb|n| is the result of \verb|getn(table)| (see below). |
2684 | If the function returns any non-\nil\ value, | 3085 | If the function returns a non-\nil\ value, |
2685 | then the loop is broken, and this value is returned | 3086 | then the loop is broken, and this value is returned |
2686 | as the final value of \verb|foreachi|. | 3087 | as the final value of \verb|foreachi|. |
2687 | This function could be defined in Lua: | 3088 | This function is equivalent to the following Lua function: |
2688 | \begin{verbatim} | 3089 | \begin{verbatim} |
2689 | function foreachi (t, f) | 3090 | function foreachi (t, f) |
2690 | for i=1,getn(t) do | 3091 | for i=1,getn(t) do |
@@ -2701,7 +3102,7 @@ current garbage collector threshold (also in Kbytes). | |||
2701 | 3102 | ||
2702 | \subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal} | 3103 | \subsubsection*{\ff \T{getglobal (name)}}\DefLIB{getglobal} |
2703 | Gets the value of a global variable, | 3104 | Gets the value of a global variable, |
2704 | or calls a tag method for ``getglobal''. | 3105 | possibly via a ``getglobal'' tag method. |
2705 | Its full semantics is explained in \See{tag-method}. | 3106 | Its full semantics is explained in \See{tag-method}. |
2706 | The string \verb|name| does not need to be a | 3107 | The string \verb|name| does not need to be a |
2707 | syntactically valid variable name. | 3108 | syntactically valid variable name. |
@@ -2710,9 +3111,9 @@ syntactically valid variable name. | |||
2710 | Returns the ``size'' of a table, when seen as a list. | 3111 | Returns the ``size'' of a table, when seen as a list. |
2711 | If the table has an \verb|n| field with a numeric value, | 3112 | If the table has an \verb|n| field with a numeric value, |
2712 | this value is the ``size'' of the table. | 3113 | this value is the ``size'' of the table. |
2713 | Otherwise, the ``size'' is the largest numerical index with a non-nil | 3114 | Otherwise, the ``size'' is the largest numerical index with a non-\nil\ |
2714 | value in the table. | 3115 | value in the table. |
2715 | This function could be defined in Lua: | 3116 | This function is equivalent to the following Lua function: |
2716 | \begin{verbatim} | 3117 | \begin{verbatim} |
2717 | function getn (t) | 3118 | function getn (t) |
2718 | if type(t.n) == "number" then return t.n end | 3119 | if type(t.n) == "number" then return t.n end |
@@ -2729,13 +3130,23 @@ This function could be defined in Lua: | |||
2729 | Returns the current tag method | 3130 | Returns the current tag method |
2730 | for a given pair \M{(tag, event)}. | 3131 | for a given pair \M{(tag, event)}. |
2731 | This function cannot be used to get a tag method for the ``gc'' event. | 3132 | This function cannot be used to get a tag method for the ``gc'' event. |
2732 | (Such tag methods can only be manipulated by C~code.) | 3133 | (``gc'' tag methods can only be manipulated by C~code.) |
2733 | 3134 | ||
2734 | \subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals} | 3135 | \subsubsection*{\ff \T{globals ([table])}}\DefLIB{globals}\label{pdf-globals} |
2735 | Returns the current table of globals. | 3136 | Returns the current table of globals. |
2736 | If the argument \verb|table| is given, | 3137 | If the argument \verb|table| is given, |
2737 | then it also sets this table as the table of globals. | 3138 | then it also sets this table as the table of globals. |
2738 | 3139 | ||
3140 | \subsubsection*{\ff \T{loadfile (filename)}}\DefLIB{loadfile} | ||
3141 | Similar to \verb|dofile|, | ||
3142 | but returns the contents of a Lua chunk as a function, | ||
3143 | instead of executing it. | ||
3144 | |||
3145 | \subsubsection*{\ff \T{loadstring (string [, chunkname])}}\DefLIB{loadstring} | ||
3146 | Similar to \verb|dostring|, | ||
3147 | but returns the contents of a Lua chunk as a function, | ||
3148 | instead of executing it. | ||
3149 | |||
2739 | \subsubsection*{\ff \T{newtype (name)}}\DefLIB{newtype}\label{pdf-newtype} | 3150 | \subsubsection*{\ff \T{newtype (name)}}\DefLIB{newtype}\label{pdf-newtype} |
2740 | Creates a new type with the given name | 3151 | Creates a new type with the given name |
2741 | (which can be used only for table objects). | 3152 | (which can be used only for table objects). |
@@ -2773,20 +3184,20 @@ and prints their values in \verb|stdout|, | |||
2773 | using the strings returned by \verb|tostring|. | 3184 | using the strings returned by \verb|tostring|. |
2774 | This function is not intended for formatted output, | 3185 | This function is not intended for formatted output, |
2775 | but only as a quick way to show a value, | 3186 | but only as a quick way to show a value, |
2776 | for instance for debugging. | 3187 | typically for debugging. |
2777 | See \See{libio} for functions for formatted output. | 3188 | For formatted output, see \verb|format| \see{format}. |
2778 | 3189 | ||
2779 | \subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget} | 3190 | \subsubsection*{\ff \T{rawget (table, index)}}\DefLIB{rawget} |
2780 | Gets the real value of \verb|table[index]|, | 3191 | Gets the real value of \verb|table[index]|, |
2781 | without invoking any tag method. | 3192 | without invoking any tag method. |
2782 | \verb|table| must be a table, | 3193 | \verb|table| must be a table; |
2783 | and \verb|index| is any value different from \nil. | 3194 | \verb|index| is any value different from \nil. |
2784 | 3195 | ||
2785 | \subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset} | 3196 | \subsubsection*{\ff \T{rawset (table, index, value)}}\DefLIB{rawset} |
2786 | Sets the real value of \verb|table[index]| to \verb|value|, | 3197 | Sets the real value of \verb|table[index]| to \verb|value|, |
2787 | without invoking any tag method. | 3198 | without invoking any tag method. |
2788 | \verb|table| must be a table, | 3199 | \verb|table| must be a table; |
2789 | \verb|index| is any value different from \nil, | 3200 | \verb|index| is any value different from \nil; |
2790 | and \verb|value| is any Lua value. | 3201 | and \verb|value| is any Lua value. |
2791 | 3202 | ||
2792 | \subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype} | 3203 | \subsubsection*{\ff \T{rawtype (v)}}\DefLIB{rawtype} |
@@ -2805,7 +3216,7 @@ TO BE WRITTEN. | |||
2805 | 3216 | ||
2806 | \subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal} | 3217 | \subsubsection*{\ff \T{setglobal (name, value)}}\DefLIB{setglobal} |
2807 | Sets the named global variable to the given value, | 3218 | Sets the named global variable to the given value, |
2808 | or calls a tag method for ``setglobal''. | 3219 | possibly via a ``setglobal'' tag method. |
2809 | Its full semantics is explained in \See{tag-method}. | 3220 | Its full semantics is explained in \See{tag-method}. |
2810 | The string \verb|name| does not need to be a | 3221 | The string \verb|name| does not need to be a |
2811 | syntactically valid variable name. | 3222 | syntactically valid variable name. |
@@ -2813,9 +3224,9 @@ syntactically valid variable name. | |||
2813 | \subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype} | 3224 | \subsubsection*{\ff \T{settype (t, type)}}\DefLIB{settype}\label{pdf-settype} |
2814 | Sets the type of a given table \see{TypesSec}. | 3225 | Sets the type of a given table \see{TypesSec}. |
2815 | \verb|type| must be the name or the tag of a user-defined type. | 3226 | \verb|type| must be the name or the tag of a user-defined type. |
2816 | \verb|settag| returns the value of its first argument (the table). | 3227 | \verb|settype| returns the value of its first argument (the table). |
2817 | For the safety of host programs, | 3228 | For the safety of host programs, |
2818 | it is impossible to change the tag of a userdata from Lua. | 3229 | you can only change the type of userdata from~C, not from Lua. |
2819 | 3230 | ||
2820 | \subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} | 3231 | \subsubsection*{\ff \T{settagmethod (tag, event, newmethod)}} |
2821 | \DefLIB{settagmethod} | 3232 | \DefLIB{settagmethod} |
@@ -2824,7 +3235,7 @@ returns the old method. | |||
2824 | If \verb|newmethod| is \nil, | 3235 | If \verb|newmethod| is \nil, |
2825 | then \verb|settagmethod| restores the default behavior for the given event. | 3236 | then \verb|settagmethod| restores the default behavior for the given event. |
2826 | This function cannot be used to set a tag method for the ``gc'' event. | 3237 | This function cannot be used to set a tag method for the ``gc'' event. |
2827 | (Such tag methods can only be manipulated by C~code.) | 3238 | (``gc'' tag methods can only be manipulated by C~code.) |
2828 | 3239 | ||
2829 | \subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} | 3240 | \subsubsection*{\ff \T{sort (table [, comp])}}\DefLIB{sort} |
2830 | Sorts table elements in a given order, \emph{in-place}, | 3241 | Sorts table elements in a given order, \emph{in-place}, |
@@ -2834,7 +3245,7 @@ If \verb|comp| is given, | |||
2834 | then it must be a function that receives two table elements, | 3245 | then it must be a function that receives two table elements, |
2835 | and returns true (that is, a value different from \nil) | 3246 | and returns true (that is, a value different from \nil) |
2836 | when the first is less than the second | 3247 | when the first is less than the second |
2837 | (so that \verb|not comp(a[i+1], a[i])| will be true after the sort). | 3248 | (so that \verb|not comp(a[i+1],a[i])| will be true after the sort). |
2838 | If \verb|comp| is not given, | 3249 | If \verb|comp| is not given, |
2839 | then the standard Lua operator \verb|<| is used instead. | 3250 | then the standard Lua operator \verb|<| is used instead. |
2840 | 3251 | ||
@@ -2843,9 +3254,8 @@ The sort algorithm is \emph{not} stable | |||
2843 | may have their relative positions changed by the sort). | 3254 | may have their relative positions changed by the sort). |
2844 | 3255 | ||
2845 | \subsubsection*{\ff \T{tag (v)}}\DefLIB{tag}\label{pdf-tag} | 3256 | \subsubsection*{\ff \T{tag (v)}}\DefLIB{tag}\label{pdf-tag} |
2846 | Allows Lua programs to test the tag of a value \see{TypesSec}. | 3257 | Returns the tag of a value \see{TypesSec}. |
2847 | It receives one argument, and returns its tag (a number). | 3258 | Tags are integers. |
2848 | %\verb|tag| is equivalent to the API function \verb|lua_tag|. | ||
2849 | 3259 | ||
2850 | \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} | 3260 | \subsubsection*{\ff \T{tonumber (e [, base])}}\DefLIB{tonumber} |
2851 | Tries to convert its argument to a number. | 3261 | Tries to convert its argument to a number. |
@@ -2855,7 +3265,7 @@ otherwise, it returns \nil. | |||
2855 | 3265 | ||
2856 | An optional argument specifies the base to interpret the numeral. | 3266 | An optional argument specifies the base to interpret the numeral. |
2857 | The base may be any integer between 2 and 36, inclusive. | 3267 | The base may be any integer between 2 and 36, inclusive. |
2858 | In bases above~10, the letter `A' (either upper or lower case) | 3268 | In bases above~10, the letter `A' (in either upper or lower case) |
2859 | represents~10, `B' represents~11, and so forth, with `Z' representing 35. | 3269 | represents~10, `B' represents~11, and so forth, with `Z' representing 35. |
2860 | In base 10 (the default), the number may have a decimal part, | 3270 | In base 10 (the default), the number may have a decimal part, |
2861 | as well as an optional exponent part \see{coercion}. | 3271 | as well as an optional exponent part \see{coercion}. |
@@ -2865,13 +3275,13 @@ In other bases, only unsigned integers are accepted. | |||
2865 | Receives an argument of any type and | 3275 | Receives an argument of any type and |
2866 | converts it to a string in a reasonable format. | 3276 | converts it to a string in a reasonable format. |
2867 | For complete control of how numbers are converted, | 3277 | For complete control of how numbers are converted, |
2868 | use function \verb|format|. | 3278 | use \verb|format| \see{format}. |
2869 | 3279 | ||
2870 | 3280 | ||
2871 | \subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert} | 3281 | \subsubsection*{\ff \T{tinsert (table, [pos,] value)}}\DefLIB{tinsert} |
2872 | 3282 | ||
2873 | Inserts element \verb|value| at table position \verb|pos|, | 3283 | Inserts element \verb|value| at position \verb|pos| in \verb|table|, |
2874 | shifting other elements to open space, if necessary. | 3284 | shifting other elements up to open space, if necessary. |
2875 | The default value for \verb|pos| is \verb|n+1|, | 3285 | The default value for \verb|pos| is \verb|n+1|, |
2876 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, | 3286 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, |
2877 | so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end | 3287 | so that a call \verb|tinsert(t,x)| inserts \verb|x| at the end |
@@ -2879,7 +3289,7 @@ of table \verb|t|. | |||
2879 | This function also sets or increments the field \verb|n| of the table | 3289 | This function also sets or increments the field \verb|n| of the table |
2880 | to \verb|n+1|. | 3290 | to \verb|n+1|. |
2881 | This function is equivalent to the following Lua function, | 3291 | This function is equivalent to the following Lua function, |
2882 | except that the table accesses are all \emph{raw} | 3292 | except that the table accesses in \verb|tinsert| are all \emph{raw} |
2883 | (that is, without tag methods): | 3293 | (that is, without tag methods): |
2884 | \begin{verbatim} | 3294 | \begin{verbatim} |
2885 | function tinsert (t, ...) | 3295 | function tinsert (t, ...) |
@@ -2901,7 +3311,7 @@ except that the table accesses are all \emph{raw} | |||
2901 | \subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove} | 3311 | \subsubsection*{\ff \T{tremove (table [, pos])}}\DefLIB{tremove} |
2902 | 3312 | ||
2903 | Removes from \verb|table| the element at position \verb|pos|, | 3313 | Removes from \verb|table| the element at position \verb|pos|, |
2904 | shifting other elements to close the space, if necessary. | 3314 | shifting other elements down to close the space, if necessary. |
2905 | Returns the value of the removed element. | 3315 | Returns the value of the removed element. |
2906 | The default value for \verb|pos| is \verb|n|, | 3316 | The default value for \verb|pos| is \verb|n|, |
2907 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, | 3317 | where \verb|n| is the result of \verb|getn(table)| \see{getn}, |
@@ -2909,9 +3319,8 @@ so that a call \verb|tremove(t)| removes the last element | |||
2909 | of table \verb|t|. | 3319 | of table \verb|t|. |
2910 | This function also sets or decrements the field \verb|n| of the table | 3320 | This function also sets or decrements the field \verb|n| of the table |
2911 | to \verb|n-1|. | 3321 | to \verb|n-1|. |
2912 | |||
2913 | This function is equivalent to the following Lua function, | 3322 | This function is equivalent to the following Lua function, |
2914 | except that the table accesses are all \emph{raw} | 3323 | except that the table accesses in \verb|tremove| are all \emph{raw} |
2915 | (that is, without tag methods): | 3324 | (that is, without tag methods): |
2916 | \begin{verbatim} | 3325 | \begin{verbatim} |
2917 | function tremove (t, pos) | 3326 | function tremove (t, pos) |
@@ -2929,7 +3338,9 @@ except that the table accesses are all \emph{raw} | |||
2929 | \end{verbatim} | 3338 | \end{verbatim} |
2930 | 3339 | ||
2931 | \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} | 3340 | \subsubsection*{\ff \T{type (v)}}\DefLIB{type}\label{pdf-type} |
2932 | Returns the type name of its only argument. | 3341 | Returns the type name of a value. |
3342 | Type names are strings and are set with \verb|settype| for user-defined types. | ||
3343 | For other types, \verb|type| is equivalent to \verb|rawtype|. | ||
2933 | 3344 | ||
2934 | \subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack} | 3345 | \subsubsection*{\ff \T{unpack (list)}}\DefLIB{unpack} |
2935 | Returns all elements from the given list. | 3346 | Returns all elements from the given list. |
@@ -2938,15 +3349,15 @@ This function is equivalent to | |||
2938 | return list[1], list[2], ..., list[n] | 3349 | return list[1], list[2], ..., list[n] |
2939 | \end{verbatim} | 3350 | \end{verbatim} |
2940 | except that the above code can be valid only for a fixed \M{n}. | 3351 | except that the above code can be valid only for a fixed \M{n}. |
2941 | The number of returned values, \M{n}, | 3352 | The number \M{n} of returned values |
2942 | is the result of \verb|getn(list)| \see{getn}, | 3353 | is the result of \verb|getn(list)| \seepage{getn}. |
2943 | 3354 | ||
2944 | \subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode} | 3355 | \subsubsection*{\ff \T{weakmode (table, mode)}}\DefLIB{weakmode}\label{weakmode} |
2945 | 3356 | ||
2946 | Controls the weakness of a table. | 3357 | Controls the weakness of a table. |
2947 | When \verb|mode| is \verb|"?"|, | 3358 | When \verb|mode| is \verb|"?"|, |
2948 | returns the current mode of the table, as a string; | 3359 | \verb|weakmode| returns the current mode of the table, as a string; |
2949 | otherwise, sets the weakmode of the table to the given mode (also a string). | 3360 | otherwise, it sets the weakmode of the table to the given mode (also a string). |
2950 | Valid mode strings are \verb|"k"| for weak keys, | 3361 | Valid mode strings are \verb|"k"| for weak keys, |
2951 | \verb|"v"| for weak values, | 3362 | \verb|"v"| for weak values, |
2952 | \verb|"kv"| for both, | 3363 | \verb|"kv"| for both, |
@@ -2958,8 +3369,7 @@ This library provides generic functions for string manipulation, | |||
2958 | such as finding and extracting substrings and pattern matching. | 3369 | such as finding and extracting substrings and pattern matching. |
2959 | When indexing a string in Lua, the first character is at position~1 | 3370 | When indexing a string in Lua, the first character is at position~1 |
2960 | (not at~0, as in C). | 3371 | (not at~0, as in C). |
2961 | Also, | 3372 | Indices are allowed to be negative and are interpreted as indexing backwards, |
2962 | indices are allowed to be negative and are interpreted as indexing backwards, | ||
2963 | from the end of the string. Thus, the last character is at position \Math{-1}, | 3373 | from the end of the string. Thus, the last character is at position \Math{-1}, |
2964 | and so on. | 3374 | and so on. |
2965 | 3375 | ||
@@ -2974,16 +3384,15 @@ Numerical codes are not necessarily portable across platforms. | |||
2974 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\DefLIB{strchar} | 3384 | \subsubsection*{\ff \T{strchar (i1, i2, \ldots)}}\DefLIB{strchar} |
2975 | Receives 0 or more integers. | 3385 | Receives 0 or more integers. |
2976 | Returns a string with length equal to the number of arguments, | 3386 | Returns a string with length equal to the number of arguments, |
2977 | wherein each character has the internal numerical code equal | 3387 | in which each character has the internal numerical code equal |
2978 | to its correspondent argument. | 3388 | to its correspondent argument. |
2979 | 3389 | ||
2980 | \NOTE | 3390 | \NOTE |
2981 | Numerical codes are not necessarily portable across platforms. | 3391 | Numerical codes are not necessarily portable across platforms. |
2982 | 3392 | ||
2983 | \subsubsection*{\ff \T{strfind (s, pattern [, init [, plain]])}} | 3393 | \subsubsection*{\ff \T{strfind (s, pattern [, init [, plain]])}}\DefLIB{strfind} |
2984 | \DefLIB{strfind} | ||
2985 | Looks for the first \emph{match} of | 3394 | Looks for the first \emph{match} of |
2986 | \verb|pattern| in \verb|s|. | 3395 | \verb|pattern| in the string \verb|s|. |
2987 | If it finds one, then \verb|strfind| returns the indices of \verb|s| | 3396 | If it finds one, then \verb|strfind| returns the indices of \verb|s| |
2988 | where this occurrence starts and ends; | 3397 | where this occurrence starts and ends; |
2989 | otherwise, it returns \nil. | 3398 | otherwise, it returns \nil. |
@@ -3006,10 +3415,9 @@ and so \verb|"a\000b\000c"| has length 5. | |||
3006 | 3415 | ||
3007 | \subsubsection*{\ff \T{strlower (s)}}\DefLIB{strlower} | 3416 | \subsubsection*{\ff \T{strlower (s)}}\DefLIB{strlower} |
3008 | Receives a string and returns a copy of that string with all | 3417 | Receives a string and returns a copy of that string with all |
3009 | upper case letters changed to lower case. | 3418 | uppercase letters changed to lowercase. |
3010 | All other characters are left unchanged. | 3419 | All other characters are left unchanged. |
3011 | The definition of what is an upper-case | 3420 | The definition of what an uppercase letter is depends on the current locale. |
3012 | letter depends on the current locale. | ||
3013 | 3421 | ||
3014 | \subsubsection*{\ff \T{strrep (s, n)}}\DefLIB{strrep} | 3422 | \subsubsection*{\ff \T{strrep (s, n)}}\DefLIB{strrep} |
3015 | Returns a string that is the concatenation of \verb|n| copies of | 3423 | Returns a string that is the concatenation of \verb|n| copies of |
@@ -3018,7 +3426,7 @@ the string \verb|s|. | |||
3018 | \subsubsection*{\ff \T{strsub (s, i [, j])}}\DefLIB{strsub} | 3426 | \subsubsection*{\ff \T{strsub (s, i [, j])}}\DefLIB{strsub} |
3019 | Returns another string, which is a substring of \verb|s|, | 3427 | Returns another string, which is a substring of \verb|s|, |
3020 | starting at \verb|i| and running until \verb|j|; | 3428 | starting at \verb|i| and running until \verb|j|; |
3021 | \verb|i| and \verb|j| may be negative, | 3429 | \verb|i| and \verb|j| may be negative. |
3022 | If \verb|j| is absent, then it is assumed to be equal to \Math{-1} | 3430 | If \verb|j| is absent, then it is assumed to be equal to \Math{-1} |
3023 | (which is the same as the string length). | 3431 | (which is the same as the string length). |
3024 | In particular, | 3432 | In particular, |
@@ -3029,10 +3437,9 @@ with length \verb|i|. | |||
3029 | 3437 | ||
3030 | \subsubsection*{\ff \T{strupper (s)}}\DefLIB{strupper} | 3438 | \subsubsection*{\ff \T{strupper (s)}}\DefLIB{strupper} |
3031 | Receives a string and returns a copy of that string with all | 3439 | Receives a string and returns a copy of that string with all |
3032 | lower case letters changed to upper case. | 3440 | lowercase letters changed to uppercase. |
3033 | All other characters are left unchanged. | 3441 | All other characters are left unchanged. |
3034 | The definition of what is a lower case | 3442 | The definition of what a lowercase letter is depends on the current locale. |
3035 | letter depends on the current locale. | ||
3036 | 3443 | ||
3037 | \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\DefLIB{format} | 3444 | \subsubsection*{\ff \T{format (formatstring, e1, e2, \ldots)}}\DefLIB{format} |
3038 | \label{format} | 3445 | \label{format} |
@@ -3081,8 +3488,8 @@ replaced by a replacement string specified by \verb|repl|. | |||
3081 | the total number of substitutions made. | 3488 | the total number of substitutions made. |
3082 | 3489 | ||
3083 | If \verb|repl| is a string, then its value is used for replacement. | 3490 | If \verb|repl| is a string, then its value is used for replacement. |
3084 | Any sequence in \verb|repl| of the form \verb|%n| | 3491 | Any sequence in \verb|repl| of the form \verb|%|\M{n}, |
3085 | with \verb|n| between 1 and 9 | 3492 | with \M{n} between 1 and 9, |
3086 | stands for the value of the \M{n}-th captured substring. | 3493 | stands for the value of the \M{n}-th captured substring. |
3087 | 3494 | ||
3088 | If \verb|repl| is a function, then this function is called every time a | 3495 | If \verb|repl| is a function, then this function is called every time a |
@@ -3114,11 +3521,11 @@ Here are some examples: | |||
3114 | x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) | 3521 | x = gsub("4+5 = $return 4+5$", "%$(.-)%$", dostring) |
3115 | --> x="4+5 = 9" | 3522 | --> x="4+5 = 9" |
3116 | 3523 | ||
3117 | local t = {name="lua", version="4.0"} | 3524 | local t = {name="Lua", version="4.1"} |
3118 | x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) | 3525 | x = gsub("$name - $version", "%$(%w+)", function (v) return %t[v] end) |
3119 | --> x="lua - 4.0" | 3526 | --> x="Lua - 4.1" |
3120 | 3527 | ||
3121 | t = {n=0} | 3528 | local t = {n=0} |
3122 | gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) | 3529 | gsub("first second word", "(%w+)", function (w) tinsert(%t, w) end) |
3123 | --> t={"first", "second", "word"; n=3} | 3530 | --> t={"first", "second", "word"; n=3} |
3124 | \end{verbatim} | 3531 | \end{verbatim} |
@@ -3129,7 +3536,7 @@ Here are some examples: | |||
3129 | \paragraph{Character Class:} | 3536 | \paragraph{Character Class:} |
3130 | a \Def{character class} is used to represent a set of characters. | 3537 | a \Def{character class} is used to represent a set of characters. |
3131 | The following combinations are allowed in describing a character class: | 3538 | The following combinations are allowed in describing a character class: |
3132 | \begin{description} | 3539 | \begin{description}\leftskip=20pt |
3133 | \item[\emph{x}] (where \emph{x} is not one of the magic characters | 3540 | \item[\emph{x}] (where \emph{x} is not one of the magic characters |
3134 | \verb|^$()%.[]*+-?|) | 3541 | \verb|^$()%.[]*+-?|) |
3135 | --- represents the character \emph{x} itself. | 3542 | --- represents the character \emph{x} itself. |
@@ -3137,10 +3544,10 @@ The following combinations are allowed in describing a character class: | |||
3137 | \item[\T{\%a}] --- represents all letters. | 3544 | \item[\T{\%a}] --- represents all letters. |
3138 | \item[\T{\%c}] --- represents all control characters. | 3545 | \item[\T{\%c}] --- represents all control characters. |
3139 | \item[\T{\%d}] --- represents all digits. | 3546 | \item[\T{\%d}] --- represents all digits. |
3140 | \item[\T{\%l}] --- represents all lower case letters. | 3547 | \item[\T{\%l}] --- represents all lowercase letters. |
3141 | \item[\T{\%p}] --- represents all punctuation characters. | 3548 | \item[\T{\%p}] --- represents all punctuation characters. |
3142 | \item[\T{\%s}] --- represents all space characters. | 3549 | \item[\T{\%s}] --- represents all space characters. |
3143 | \item[\T{\%u}] --- represents all upper case letters. | 3550 | \item[\T{\%u}] --- represents all uppercase letters. |
3144 | \item[\T{\%w}] --- represents all alphanumeric characters. | 3551 | \item[\T{\%w}] --- represents all alphanumeric characters. |
3145 | \item[\T{\%x}] --- represents all hexadecimal digits. | 3552 | \item[\T{\%x}] --- represents all hexadecimal digits. |
3146 | \item[\T{\%z}] --- represents the character with representation 0. | 3553 | \item[\T{\%z}] --- represents the character with representation 0. |
@@ -3151,33 +3558,33 @@ We recommend that any punctuation character (even the non magic) | |||
3151 | should be preceded by a \verb|%| | 3558 | should be preceded by a \verb|%| |
3152 | when used to represent itself in a pattern. | 3559 | when used to represent itself in a pattern. |
3153 | 3560 | ||
3154 | \item[\T{[char-set]}] --- | 3561 | \item[\T{[\M{set}]}] --- |
3155 | represents the class which is the union of all | 3562 | represents the class which is the union of all |
3156 | characters in \verb|char-set|. | 3563 | characters in \M{set}. |
3157 | A range of characters may be specified by | 3564 | A range of characters may be specified by |
3158 | separating the end characters of the range with a \verb|-|. | 3565 | separating the end characters of the range with a \verb|-|. |
3159 | All classes \verb|%|\emph{x} described above may also be used as | 3566 | All classes \verb|%|\emph{x} described above may also be used as |
3160 | components in a char-set. | 3567 | components in \M{set}. |
3161 | All other characters in char-set represent themselves. | 3568 | All other characters in \M{set} represent themselves. |
3162 | For example, \verb|[%w_]| (or \verb|[_%w]|) | 3569 | For example, \verb|[%w_]| (or \verb|[_%w]|) |
3163 | represents all alphanumeric characters plus the underscore, | 3570 | represents all alphanumeric characters plus the underscore, |
3164 | \verb|[0-7]| represents the octal digits, | 3571 | \verb|[0-7]| represents the octal digits, |
3165 | and \verb|[0-7%l%-]| represents the octal digits plus | 3572 | and \verb|[0-7%l%-]| represents the octal digits plus |
3166 | the lower case letters plus the \verb|-| character. | 3573 | the lowercase letters plus the \verb|-| character. |
3167 | 3574 | ||
3168 | The interaction between ranges and classes is not defined. | 3575 | The interaction between ranges and classes is not defined. |
3169 | Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]| | 3576 | Therefore, patterns like \verb|[%a-z]| or \verb|[a-%%]| |
3170 | have no meaning. | 3577 | have no meaning. |
3171 | 3578 | ||
3172 | \item[\T{[\^\null char-set]}] --- | 3579 | \item[\T{[\^\null\M{set}]}] --- |
3173 | represents the complement of \verb|char-set|, | 3580 | represents the complement of \M{set}, |
3174 | where \verb|char-set| is interpreted as above. | 3581 | where \M{set} is interpreted as above. |
3175 | \end{description} | 3582 | \end{description} |
3176 | For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), | 3583 | For all classes represented by single letters (\verb|%a|, \verb|%c|, \ldots), |
3177 | the corresponding upper-case letter represents the complement of the class. | 3584 | the corresponding uppercase letter represents the complement of the class. |
3178 | For instance, \verb|%S| represents all non-space characters. | 3585 | For instance, \verb|%S| represents all non-space characters. |
3179 | 3586 | ||
3180 | The definitions of letter, space, etc. depend on the current locale. | 3587 | The definitions of letter, space, etc.\ depend on the current locale. |
3181 | In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|. | 3588 | In particular, the class \verb|[a-z]| may not be equivalent to \verb|%l|. |
3182 | The second form should be preferred for portability. | 3589 | The second form should be preferred for portability. |
3183 | 3590 | ||
@@ -3199,7 +3606,7 @@ These repetition items will always match the longest possible sequence; | |||
3199 | a single character class followed by \verb|-|, | 3606 | a single character class followed by \verb|-|, |
3200 | which also matches 0 or more repetitions of characters in the class. | 3607 | which also matches 0 or more repetitions of characters in the class. |
3201 | Unlike \verb|*|, | 3608 | Unlike \verb|*|, |
3202 | these repetition items will always match the shortest possible sequence; | 3609 | these repetition items will always match the \emph{shortest} possible sequence; |
3203 | \item | 3610 | \item |
3204 | a single character class followed by \verb|?|, | 3611 | a single character class followed by \verb|?|, |
3205 | which matches 0 or 1 occurrence of a character in the class; | 3612 | which matches 0 or 1 occurrence of a character in the class; |
@@ -3228,7 +3635,7 @@ At other positions, | |||
3228 | \verb|^| and \verb|$| have no special meaning and represent themselves. | 3635 | \verb|^| and \verb|$| have no special meaning and represent themselves. |
3229 | 3636 | ||
3230 | \paragraph{Captures:} | 3637 | \paragraph{Captures:} |
3231 | A pattern may contain sub-patterns enclosed in parentheses, | 3638 | A pattern may contain sub-patterns enclosed in parentheses; |
3232 | they describe \Def{captures}. | 3639 | they describe \Def{captures}. |
3233 | When a match succeeds, the sub-strings of the subject string | 3640 | When a match succeeds, the sub-strings of the subject string |
3234 | that match captures are stored (\emph{captured}) for future use. | 3641 | that match captures are stored (\emph{captured}) for future use. |
@@ -3245,8 +3652,10 @@ A pattern cannot contain embedded zeros. Use \verb|%z| instead. | |||
3245 | 3652 | ||
3246 | \subsection{Mathematical Functions} \label{mathlib} | 3653 | \subsection{Mathematical Functions} \label{mathlib} |
3247 | 3654 | ||
3248 | This library is an interface to some functions of the standard C~math library. | 3655 | This library is an interface to most functions of the standard C~math library. |
3249 | In addition, it registers a tag method for the binary operator \verb|^| that | 3656 | (Some have slightly different names.) |
3657 | In addition, | ||
3658 | it registers a tag method for the binary exponentiation operator \verb|^| that | ||
3250 | returns \Math{x^y} when applied to numbers \verb|x^y|. | 3659 | returns \Math{x^y} when applied to numbers \verb|x^y|. |
3251 | 3660 | ||
3252 | The library provides the following functions: | 3661 | The library provides the following functions: |
@@ -3274,20 +3683,20 @@ Both can be used with 1, 2, or more arguments. | |||
3274 | 3683 | ||
3275 | The functions \verb|random| and \verb|randomseed| are interfaces to | 3684 | The functions \verb|random| and \verb|randomseed| are interfaces to |
3276 | the simple random generator functions \verb|rand| and \verb|srand|, | 3685 | the simple random generator functions \verb|rand| and \verb|srand|, |
3277 | provided by ANSI C. | 3686 | provided by ANSI~C. |
3278 | (No guarantees can be given for their statistical properties.) | 3687 | (No guarantees can be given for their statistical properties.) |
3279 | The function \verb|random|, when called without arguments, | 3688 | When called without arguments, |
3280 | returns a pseudo-random real number in the range \Math{[0,1)}. | 3689 | \verb|random| returns a pseudo-random real number in the range \Math{[0,1)}. |
3281 | When called with a number \Math{n}, | 3690 | When called with a number \Math{n}, |
3282 | \verb|random| returns a pseudo-random integer in the range \Math{[1,n]}. | 3691 | \verb|random| returns a pseudo-random integer in the range \Math{[1,n]}. |
3283 | When called with two arguments, \Math{l} and \Math{u}, | 3692 | When called with two arguments, \Math{l} and \Math{u}, |
3284 | \verb|random| returns a pseudo-random integer in the range \Math{[l,u]}. | 3693 | \verb|random| returns a pseudo-random integer in the range \Math{[l,u]}. |
3285 | 3694 | ||
3286 | 3695 | ||
3287 | \subsection{I/O Facilities} \label{libio} | 3696 | \subsection{Input and Output Facilities} \label{libio} |
3288 | 3697 | ||
3289 | All input and output operations in Lua are done, by default, | 3698 | All input and output operations in Lua are done, by default, |
3290 | over two \Def{file handles}, one for reading and one for writing. | 3699 | over two \Def{file handles}: one for reading and one for writing. |
3291 | These handles are stored in two Lua global variables, | 3700 | These handles are stored in two Lua global variables, |
3292 | called \verb|_INPUT| and \verb|_OUTPUT|. | 3701 | called \verb|_INPUT| and \verb|_OUTPUT|. |
3293 | The global variables | 3702 | The global variables |
@@ -3314,7 +3723,7 @@ or, in case of errors, \nil\ plus a string describing the error. | |||
3314 | This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. | 3723 | This function does not modify either \verb|_INPUT| or \verb|_OUTPUT|. |
3315 | 3724 | ||
3316 | The \verb|mode| string can be any of the following: | 3725 | The \verb|mode| string can be any of the following: |
3317 | \begin{description} | 3726 | \begin{description}\leftskip=20pt |
3318 | \item[``r''] read mode; | 3727 | \item[``r''] read mode; |
3319 | \item[``w''] write mode; | 3728 | \item[``w''] write mode; |
3320 | \item[``a''] append mode; | 3729 | \item[``a''] append mode; |
@@ -3381,7 +3790,8 @@ usually limited and depends on the system. | |||
3381 | \subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto} | 3790 | \subsubsection*{\ff \T{appendto (filename)}}\DefLIB{appendto} |
3382 | 3791 | ||
3383 | Opens a file named \verb|filename| (in text mode) | 3792 | Opens a file named \verb|filename| (in text mode) |
3384 | and sets its handle as the value of \verb|_OUTPUT|. | 3793 | sets its handle as the value of \verb|_OUTPUT|, |
3794 | and returns this value. | ||
3385 | Unlike the \verb|writeto| operation, | 3795 | Unlike the \verb|writeto| operation, |
3386 | this function does not erase any previous contents of the file; | 3796 | this function does not erase any previous contents of the file; |
3387 | instead, anything written to the file is appended to its end. | 3797 | instead, anything written to the file is appended to its end. |
@@ -3414,14 +3824,14 @@ Sets and gets the file position, | |||
3414 | measured in bytes from the beginning of the file, | 3824 | measured in bytes from the beginning of the file, |
3415 | to the position given by \verb|offset| plus a base | 3825 | to the position given by \verb|offset| plus a base |
3416 | specified by the string \verb|whence|, as follows: | 3826 | specified by the string \verb|whence|, as follows: |
3417 | \begin{description} | 3827 | \begin{description}\leftskip=20pt |
3418 | \item[``set''] base is position 0 (beginning of the file); | 3828 | \item[``set''] base is position 0 (beginning of the file); |
3419 | \item[``cur''] base is current position; | 3829 | \item[``cur''] base is current position; |
3420 | \item[``end''] base is end of file; | 3830 | \item[``end''] base is end of file; |
3421 | \end{description} | 3831 | \end{description} |
3422 | In case of success, function \verb|seek| returns the final file position, | 3832 | In case of success, function \verb|seek| returns the final file position, |
3423 | measured in bytes from the beginning of the file. | 3833 | measured in bytes from the beginning of the file. |
3424 | If the call fails, it returns \nil, | 3834 | If this function fails, it returns \nil, |
3425 | plus a string describing the error. | 3835 | plus a string describing the error. |
3426 | 3836 | ||
3427 | The default value for \verb|whence| is \verb|"cur"|, | 3837 | The default value for \verb|whence| is \verb|"cur"|, |
@@ -3446,8 +3856,8 @@ be used for a temporary file. | |||
3446 | The file must be explicitly opened before its use | 3856 | The file must be explicitly opened before its use |
3447 | and removed when no longer needed. | 3857 | and removed when no longer needed. |
3448 | 3858 | ||
3449 | This function is equivalent to the \verb|tmpnam| C function, | 3859 | This function is equivalent to the \verb|tmpnam| C~function, |
3450 | and many people advise against its use, | 3860 | and many people (and even some compilers!) advise against its use, |
3451 | because between the time you call the function | 3861 | because between the time you call the function |
3452 | and the time you open the file, | 3862 | and the time you open the file, |
3453 | it is possible for another process | 3863 | it is possible for another process |
@@ -3462,11 +3872,11 @@ For each format, | |||
3462 | the function returns a string (or a number) with the characters read, | 3872 | the function returns a string (or a number) with the characters read, |
3463 | or \nil\ if it cannot read data with the specified format. | 3873 | or \nil\ if it cannot read data with the specified format. |
3464 | When called without formats, | 3874 | When called without formats, |
3465 | it uses a default format that reads the next line | 3875 | it uses a default format that reads the entire next line |
3466 | (see below). | 3876 | (see below). |
3467 | 3877 | ||
3468 | The available formats are | 3878 | The available formats are |
3469 | \begin{description} | 3879 | \begin{description}\leftskip=20pt |
3470 | \item[``*n''] reads a number; | 3880 | \item[``*n''] reads a number; |
3471 | this is the only format that returns a number instead of a string. | 3881 | this is the only format that returns a number instead of a string. |
3472 | \item[``*a''] reads the whole file, starting at the current position. | 3882 | \item[``*a''] reads the whole file, starting at the current position. |
@@ -3474,17 +3884,17 @@ On end of file, it returns the empty string. | |||
3474 | \item[``*u\emph{string}''] reads until the first occurence of | 3884 | \item[``*u\emph{string}''] reads until the first occurence of |
3475 | \emph{string} in the file. | 3885 | \emph{string} in the file. |
3476 | The string itself is read, but it is not included in the result. | 3886 | The string itself is read, but it is not included in the result. |
3477 | If it cannot finds the string, | 3887 | If \verb|read| cannot finds the string, |
3478 | reads (and returns) the file until its end, | 3888 | it reads (and returns) the file until its end, |
3479 | or \nil\ if the file was already on its end. | 3889 | or \nil\ if the file was already at its end. |
3480 | \item[``*l''] equivalent to \verb|"*u\n"|. | 3890 | \item[``*l''] equivalent to \verb|"*u\n"|. |
3481 | Reads the next line (skipping the end of line), | 3891 | Reads the next line (skipping the end of line), |
3482 | returning \nil\ on end of file. | 3892 | returning \nil\ on end of file. |
3483 | This is the default format. | 3893 | This is the default format. |
3484 | \item[\emph{number}] reads a string with up to that number of characters, | 3894 | \item[\emph{number}] reads a string with up to that number of characters, |
3485 | or \nil\ on end of file. | 3895 | or \nil\ on end of file. |
3486 | Particularly, if number is zero, | 3896 | If number is zero, |
3487 | reads nothing and returns an empty string, | 3897 | it reads nothing and returns an empty string, |
3488 | or \nil\ on end of file. | 3898 | or \nil\ on end of file. |
3489 | \end{description} | 3899 | \end{description} |
3490 | 3900 | ||
@@ -3517,29 +3927,30 @@ this is the time to be formatted | |||
3517 | Otherwise, \verb|date| formats the current time. | 3927 | Otherwise, \verb|date| formats the current time. |
3518 | 3928 | ||
3519 | If \verb|format| starts with \verb|!|, | 3929 | If \verb|format| starts with \verb|!|, |
3520 | the date is formatted in Coordinated Universal Time. | 3930 | then the date is formatted in Coordinated Universal Time. |
3521 | 3931 | ||
3522 | After that optional character, | 3932 | After that optional character, |
3523 | if \verb|format| is \verb|*t|, | 3933 | if \verb|format| is \verb|*t|, |
3524 | the function returns a table with the following fields: | 3934 | then \verb|date| returns a table with the following fields: |
3525 | \verb|year|, \verb|month| (1-12), \verb|day| (1-31), | 3935 | \verb|year|, \verb|month| (1--12), \verb|day| (1--31), |
3526 | \verb|hour| (0-23), \verb|min| (0-59), \verb|sec| (0-59), | 3936 | \verb|hour| (0--23), \verb|min| (0--59), \verb|sec| (0--59), |
3527 | \verb|wday| (weekday, Sunday is 1), | 3937 | \verb|wday| (weekday, Sunday is 1), |
3528 | \verb|yday| (day of the year), | 3938 | \verb|yday| (day of the year), |
3529 | and \verb|isdst| (daylight saving flag). | 3939 | and \verb|isdst| (daylight saving flag). |
3530 | 3940 | ||
3531 | If format is not \verb|*t|, the function returns the date | 3941 | If format is not \verb|*t|, |
3532 | as a string, formatted according with the | 3942 | then \verb|date| returns the date as a string, |
3533 | same rules of the ANSI~C function \verb|strftime|. | 3943 | formatted according with the same rules of the C~function \verb|strftime|. |
3534 | When called without arguments, | 3944 | When called without arguments, |
3535 | it returns a reasonable date and time representation that depends on | 3945 | \verb|date| returns a reasonable date and time representation that depends on |
3536 | the host system and on the current locale. | 3946 | the host system and on the current locale (thus, \verb|date()| is equivalent |
3947 | to \verb|date("%c")|). | ||
3537 | 3948 | ||
3538 | \subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime} | 3949 | \subsubsection*{\ff \T{difftime (t1, t2)}}\DefLIB{difftime} |
3539 | 3950 | ||
3540 | Returns the number of seconds from time \verb|t1| to time \verb|t2|. | 3951 | Returns the number of seconds from time \verb|t1| to time \verb|t2|. |
3541 | In Posix, Windows, and some other systems, | 3952 | In Posix, Windows, and some other systems, |
3542 | this value is exactly \Math{t1-t2}. | 3953 | this value is exactly \verb|t1|\Math{-}\verb|t2|. |
3543 | 3954 | ||
3544 | \subsubsection*{\ff \T{execute (command)}}\DefLIB{execute} | 3955 | \subsubsection*{\ff \T{execute (command)}}\DefLIB{execute} |
3545 | 3956 | ||
@@ -3551,7 +3962,7 @@ It returns a status code, which is system-dependent. | |||
3551 | 3962 | ||
3552 | Calls the C~function \verb|exit|, | 3963 | Calls the C~function \verb|exit|, |
3553 | with an optional \verb|code|, | 3964 | with an optional \verb|code|, |
3554 | to terminate the program. | 3965 | to terminate the host program. |
3555 | The default value for \verb|code| is the success code. | 3966 | The default value for \verb|code| is the success code. |
3556 | 3967 | ||
3557 | \subsubsection*{\ff \T{getenv (varname)}}\DefLIB{getenv} | 3968 | \subsubsection*{\ff \T{getenv (varname)}}\DefLIB{getenv} |
@@ -3561,7 +3972,7 @@ or \nil\ if the variable is not defined. | |||
3561 | 3972 | ||
3562 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\DefLIB{setlocale} | 3973 | \subsubsection*{\ff \T{setlocale (locale [, category])}}\DefLIB{setlocale} |
3563 | 3974 | ||
3564 | This function is an interface to the ANSI~C function \verb|setlocale|. | 3975 | This function is an interface to the C~function \verb|setlocale|. |
3565 | \verb|locale| is a string specifying a locale; | 3976 | \verb|locale| is a string specifying a locale; |
3566 | \verb|category| is an optional string describing which category to change: | 3977 | \verb|category| is an optional string describing which category to change: |
3567 | \verb|"all"|, \verb|"collate"|, \verb|"ctype"|, | 3978 | \verb|"all"|, \verb|"collate"|, \verb|"ctype"|, |
@@ -3572,8 +3983,8 @@ or \nil\ if the request cannot be honored. | |||
3572 | 3983 | ||
3573 | \subsubsection*{\ff \T{time ([table])}}\DefLIB{time} | 3984 | \subsubsection*{\ff \T{time ([table])}}\DefLIB{time} |
3574 | 3985 | ||
3575 | Returns the current time (when called without arguments), | 3986 | Returns the current time when called without arguments, |
3576 | or a time representing the date/time specified by the given table. | 3987 | or a time representing the date and time specified by the given table. |
3577 | This table must have fields \verb|year|, \verb|month|, and \verb|day|, | 3988 | This table must have fields \verb|year|, \verb|month|, and \verb|day|, |
3578 | and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| | 3989 | and may have fields \verb|hour|, \verb|min|, \verb|sec|, and \verb|isdst| |
3579 | (for a description of these fields, see the \verb|date| function). | 3990 | (for a description of these fields, see the \verb|date| function). |
@@ -3582,223 +3993,8 @@ The returned value is a number, whose meaning depends on your system. | |||
3582 | In Posix, Windows, and some other systems, this number counts the number | 3993 | In Posix, Windows, and some other systems, this number counts the number |
3583 | of seconds since some given start time (the ``epoch''). | 3994 | of seconds since some given start time (the ``epoch''). |
3584 | In other systems, the meaning is not specified, | 3995 | In other systems, the meaning is not specified, |
3585 | and such number can be used only as an argument to | 3996 | and the number returned bt \verb|time| can be used only as an argument to |
3586 | functions \verb|date| and \verb|difftime|. | 3997 | \verb|date| and \verb|difftime|. |
3587 | |||
3588 | |||
3589 | \section{The Debug Interface} \label{debugI} | ||
3590 | |||
3591 | Lua has no built-in debugging facilities. | ||
3592 | Instead, it offers a special interface, | ||
3593 | by means of functions and \emph{hooks}, | ||
3594 | which allows the construction of different | ||
3595 | kinds of debuggers, profilers, and other tools | ||
3596 | that need ``inside information'' from the interpreter. | ||
3597 | This interface is declared in \verb|luadebug.h|. | ||
3598 | |||
3599 | \subsection{Stack and Function Information} | ||
3600 | |||
3601 | The main function to get information about the interpreter stack is | ||
3602 | \begin{verbatim} | ||
3603 | int lua_getstack (lua_State *L, int level, lua_Debug *ar); | ||
3604 | \end{verbatim} | ||
3605 | \DefAPI{lua_getstack} | ||
3606 | It fills parts of a \verb|lua_Debug| structure with | ||
3607 | an identification of the \emph{activation record} | ||
3608 | of the function executing at a given level. | ||
3609 | Level~0 is the current running function, | ||
3610 | whereas level \Math{n+1} is the function that has called level \Math{n}. | ||
3611 | Usually, \verb|lua_getstack| returns 1; | ||
3612 | when called with a level greater than the stack depth, | ||
3613 | it returns 0. | ||
3614 | |||
3615 | The structure \verb|lua_Debug| is used to carry different pieces of | ||
3616 | information about an active function: | ||
3617 | \begin{verbatim} | ||
3618 | typedef struct lua_Debug { | ||
3619 | const char *event; /* "call", "return" */ | ||
3620 | int currentline; /* (l) */ | ||
3621 | const char *name; /* (n) */ | ||
3622 | const char *namewhat; /* (n) global, tag method, local, field */ | ||
3623 | int nups; /* (u) number of upvalues */ | ||
3624 | int linedefined; /* (S) */ | ||
3625 | const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ | ||
3626 | const char *source; /* (S) */ | ||
3627 | char short_src[LUA_IDSIZE]; /* (S) */ | ||
3628 | |||
3629 | /* private part */ | ||
3630 | ... | ||
3631 | } lua_Debug; | ||
3632 | \end{verbatim} | ||
3633 | \DefAPI{lua_Debug} | ||
3634 | \verb|lua_getstack| fills only the private part | ||
3635 | of this structure, for future use. | ||
3636 | To fill in the other fields of \verb|lua_Debug| with useful information, | ||
3637 | call | ||
3638 | \begin{verbatim} | ||
3639 | int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); | ||
3640 | \end{verbatim} | ||
3641 | \DefAPI{lua_getinfo} | ||
3642 | This function returns 0 on error | ||
3643 | (e.g., an invalid option in \verb|what|). | ||
3644 | Each character in the string \verb|what| | ||
3645 | selects some fields of \verb|ar| to be filled, | ||
3646 | as indicated by the letter in parentheses in the definition of \verb|lua_Debug|: | ||
3647 | `\verb|S|' fills in the fields \verb|source|, \verb|linedefined|, | ||
3648 | and \verb|what|; | ||
3649 | `\verb|l|' fills in the field \verb|currentline|, etc. | ||
3650 | Moreover, `\verb|f|' pushes onto the stack the function that is | ||
3651 | running at the given level. | ||
3652 | |||
3653 | To get information about a function that is not active (that is, | ||
3654 | it is not in the stack), | ||
3655 | you push the function onto the stack, | ||
3656 | and start the \verb|what| string with the character \verb|>|. | ||
3657 | For instance, to know in which line a function \verb|f| was defined, | ||
3658 | you can write | ||
3659 | \begin{verbatim} | ||
3660 | lua_Debug ar; | ||
3661 | lua_getglobal(L, "f"); | ||
3662 | lua_getinfo(L, ">S", &ar); | ||
3663 | printf("%d\n", ar.linedefined); | ||
3664 | \end{verbatim} | ||
3665 | The fields of \verb|lua_Debug| have the following meaning: | ||
3666 | \begin{description} | ||
3667 | |||
3668 | \item[source] | ||
3669 | If the function was defined in a string, | ||
3670 | \verb|source| is that string; | ||
3671 | if the function was defined in a file, | ||
3672 | \verb|source| starts with a \verb|@| followed by the file name. | ||
3673 | |||
3674 | \item[short\_src] | ||
3675 | A ``printable'' version of \verb|source|, to be used in error messages. | ||
3676 | |||
3677 | \item[linedefined] | ||
3678 | the line number where the definition of the function starts. | ||
3679 | |||
3680 | \item[what] the string \verb|"Lua"| if this is a Lua function, | ||
3681 | \verb|"C"| if this is a C~function, | ||
3682 | or \verb|"main"| if this is the main part of a chunk. | ||
3683 | |||
3684 | \item[currentline] | ||
3685 | the current line where the given function is executing. | ||
3686 | When no line information is available, | ||
3687 | \verb|currentline| is set to \Math{-1}. | ||
3688 | |||
3689 | \item[name] | ||
3690 | a reasonable name for the given function. | ||
3691 | Because functions in Lua are first class values, | ||
3692 | they do not have a fixed name: | ||
3693 | Some functions may be the value of many global variables, | ||
3694 | while others may be stored only in a table field. | ||
3695 | The \verb|lua_getinfo| function checks whether the given | ||
3696 | function is a tag method or the value of a global variable. | ||
3697 | If the given function is a tag method, | ||
3698 | then \verb|name| points to the event name. | ||
3699 | If the given function is the value of a global variable, | ||
3700 | then \verb|name| points to the variable name. | ||
3701 | If the given function is neither a tag method nor a global variable, | ||
3702 | then \verb|name| is set to \verb|NULL|. | ||
3703 | |||
3704 | \item[namewhat] | ||
3705 | Explains the previous field. | ||
3706 | If the function is a global variable, | ||
3707 | \verb|namewhat| is \verb|"global"|; | ||
3708 | if the function is a tag method, | ||
3709 | \verb|namewhat| is \verb|"tag-method"|; | ||
3710 | otherwise \verb|namewhat| is \verb|""| (the empty string). | ||
3711 | |||
3712 | \item[nups] | ||
3713 | Number of upvalues of a function. | ||
3714 | |||
3715 | \end{description} | ||
3716 | |||
3717 | |||
3718 | \subsection{Manipulating Local Variables} | ||
3719 | |||
3720 | For the manipulation of local variables, | ||
3721 | \verb|luadebug.h| uses indices: | ||
3722 | The first parameter or local variable has index~1, and so on, | ||
3723 | until the last active local variable. | ||
3724 | |||
3725 | The following functions allow the manipulation of the | ||
3726 | local variables of a given activation record. | ||
3727 | \begin{verbatim} | ||
3728 | const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); | ||
3729 | const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); | ||
3730 | \end{verbatim} | ||
3731 | \DefAPI{lua_getlocal}\DefAPI{lua_setlocal} | ||
3732 | The parameter \verb|ar| must be a valid activation record, | ||
3733 | filled by a previous call to \verb|lua_getstack| or | ||
3734 | given as argument to a hook \see{sub-hooks}. | ||
3735 | Function \verb|lua_getlocal| gets the index of a local variable | ||
3736 | (\verb|n|), pushes its value onto the stack, | ||
3737 | and returns its name. | ||
3738 | For \verb|lua_setlocal|, | ||
3739 | you push the new value onto the stack, | ||
3740 | and the function assigns that value to the variable and returns its name. | ||
3741 | Both functions return \verb|NULL| on failure; | ||
3742 | that happens if the index is greater than | ||
3743 | the number of active local variables. | ||
3744 | |||
3745 | As an example, the following function lists the names of all | ||
3746 | local variables for a function at a given level of the stack: | ||
3747 | \begin{verbatim} | ||
3748 | int listvars (lua_State *L, int level) { | ||
3749 | lua_Debug ar; | ||
3750 | int i = 1; | ||
3751 | const char *name; | ||
3752 | if (lua_getstack(L, level, &ar) == 0) | ||
3753 | return 0; /* failure: no such level in the stack */ | ||
3754 | while ((name = lua_getlocal(L, &ar, i++)) != NULL) { | ||
3755 | printf("%s\n", name); | ||
3756 | lua_pop(L, 1); /* remove variable value */ | ||
3757 | } | ||
3758 | return 1; | ||
3759 | } | ||
3760 | \end{verbatim} | ||
3761 | |||
3762 | |||
3763 | \subsection{Hooks}\label{sub-hooks} | ||
3764 | |||
3765 | The Lua interpreter offers two hooks for debugging purposes: | ||
3766 | a \emph{call} hook and a \emph{line} hook. | ||
3767 | Both have the same type, | ||
3768 | \begin{verbatim} | ||
3769 | typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); | ||
3770 | \end{verbatim} | ||
3771 | \DefAPI{lua_Hook} | ||
3772 | and you can set them with the following functions: | ||
3773 | \begin{verbatim} | ||
3774 | lua_Hook lua_setcallhook (lua_State *L, lua_Hook func); | ||
3775 | lua_Hook lua_setlinehook (lua_State *L, lua_Hook func); | ||
3776 | \end{verbatim} | ||
3777 | \DefAPI{lua_setcallhook}\DefAPI{lua_setlinehook} | ||
3778 | A hook is disabled when its value is \verb|NULL|, | ||
3779 | which is the initial value of both hooks. | ||
3780 | The functions \verb|lua_setcallhook| and \verb|lua_setlinehook| | ||
3781 | set their corresponding hooks and return their previous values. | ||
3782 | |||
3783 | The call hook is called whenever the | ||
3784 | interpreter enters or leaves a function. | ||
3785 | The \verb|event| field of \verb|ar| has the strings \verb|"call"| | ||
3786 | or \verb|"return"|. | ||
3787 | This \verb|ar| can then be used in calls to \verb|lua_getinfo|, | ||
3788 | \verb|lua_getlocal|, and \verb|lua_setlocal| | ||
3789 | to get more information about the function and to manipulate its | ||
3790 | local variables. | ||
3791 | |||
3792 | The line hook is called every time the interpreter changes | ||
3793 | the line of code it is executing. | ||
3794 | The \verb|event| field of \verb|ar| has the string \verb|"line"|, | ||
3795 | and the \verb|currentline| field has the line number. | ||
3796 | Again, you can use this \verb|ar| in other calls to the debug API. | ||
3797 | |||
3798 | While Lua is running a hook, it disables other calls to hooks. | ||
3799 | Therefore, if a hook calls Lua to execute a function or a chunk, | ||
3800 | this execution ocurrs without any calls to hooks. | ||
3801 | |||
3802 | 3998 | ||
3803 | \subsection{The Reflexive Debug Interface} | 3999 | \subsection{The Reflexive Debug Interface} |
3804 | 4000 | ||
@@ -3811,7 +4007,7 @@ by calling \verb|lua_dblibopen|. | |||
3811 | 4007 | ||
3812 | You should exert great care when using this library. | 4008 | You should exert great care when using this library. |
3813 | The functions provided here should be used exclusively for debugging | 4009 | The functions provided here should be used exclusively for debugging |
3814 | and similar tasks (e.g., profiling). | 4010 | and similar tasks, such as profiling. |
3815 | Please resist the temptation to use them as a | 4011 | Please resist the temptation to use them as a |
3816 | usual programming tool: | 4012 | usual programming tool: |
3817 | They can be \emph{very} slow. | 4013 | They can be \emph{very} slow. |
@@ -3835,7 +4031,8 @@ then \verb|getinfo| returns \nil. | |||
3835 | The returned table contains all the fields returned by \verb|lua_getinfo|, | 4031 | The returned table contains all the fields returned by \verb|lua_getinfo|, |
3836 | with the string \verb|what| describing what to get. | 4032 | with the string \verb|what| describing what to get. |
3837 | The default for \verb|what| is to get all information available. | 4033 | The default for \verb|what| is to get all information available. |
3838 | The option \verb|f|, if present, | 4034 | If present, |
4035 | the option \verb|f| | ||
3839 | adds a field named \verb|func| with the function itself. | 4036 | adds a field named \verb|func| with the function itself. |
3840 | 4037 | ||
3841 | For instance, the expression \verb|getinfo(1,"n").name| returns | 4038 | For instance, the expression \verb|getinfo(1,"n").name| returns |
@@ -3862,6 +4059,7 @@ with index \verb|local| of the function at level \verb|level| of the stack. | |||
3862 | The function returns \nil\ if there is no local | 4059 | The function returns \nil\ if there is no local |
3863 | variable with the given index, | 4060 | variable with the given index, |
3864 | and raises an error when called with a \verb|level| out of range. | 4061 | and raises an error when called with a \verb|level| out of range. |
4062 | (You can call \verb|getinfo| to check whether the level is valid.) | ||
3865 | 4063 | ||
3866 | \subsubsection*{\ff \T{setcallhook (hook)}}\DefLIB{setcallhook} | 4064 | \subsubsection*{\ff \T{setcallhook (hook)}}\DefLIB{setcallhook} |
3867 | 4065 | ||
@@ -3876,7 +4074,7 @@ the function being called or returning | |||
3876 | and level~1 is the hook function). | 4074 | and level~1 is the hook function). |
3877 | When called without arguments, | 4075 | When called without arguments, |
3878 | this function turns off call hooks. | 4076 | this function turns off call hooks. |
3879 | \verb|setcallhook| returns the old hook. | 4077 | \verb|setcallhook| returns the old call hook. |
3880 | 4078 | ||
3881 | \subsubsection*{\ff \T{setlinehook (hook)}}\DefLIB{setlinehook} | 4079 | \subsubsection*{\ff \T{setlinehook (hook)}}\DefLIB{setlinehook} |
3882 | 4080 | ||
@@ -3887,14 +4085,15 @@ The only argument to the line hook is the line number the interpreter | |||
3887 | is about to execute. | 4085 | is about to execute. |
3888 | When called without arguments, | 4086 | When called without arguments, |
3889 | this function turns off line hooks. | 4087 | this function turns off line hooks. |
3890 | \verb|setlinehook| returns the old hook. | 4088 | \verb|setlinehook| returns the old line hook. |
3891 | 4089 | ||
3892 | 4090 | ||
4091 | %------------------------------------------------------------------------------ | ||
3893 | \section{\Index{Lua Stand-alone}} \label{lua-sa} | 4092 | \section{\Index{Lua Stand-alone}} \label{lua-sa} |
3894 | 4093 | ||
3895 | Although Lua has been designed as an extension language, | 4094 | Although Lua has been designed as an extension language, |
3896 | to be embedded in a host C~program, | 4095 | to be embedded in a host C~program, |
3897 | it is frequently used as a stand-alone language. | 4096 | it is also frequently used as a stand-alone language. |
3898 | An interpreter for Lua as a stand-alone language, | 4097 | An interpreter for Lua as a stand-alone language, |
3899 | called simply \verb|lua|, | 4098 | called simply \verb|lua|, |
3900 | is provided with the standard distribution. | 4099 | is provided with the standard distribution. |
@@ -3903,15 +4102,15 @@ This program can be called with any sequence of the following arguments: | |||
3903 | \item[\T{-sNUM}] sets the stack size to \T{NUM} | 4102 | \item[\T{-sNUM}] sets the stack size to \T{NUM} |
3904 | (if present, this must be the first option); | 4103 | (if present, this must be the first option); |
3905 | \item[\T{-} ] executes \verb|stdin| as a file; | 4104 | \item[\T{-} ] executes \verb|stdin| as a file; |
3906 | \item[\T{-c}] calls \verb|lua_close| after running all arguments; | 4105 | \item[\T{-c}] calls \verb|lua_close| after processing all arguments; |
3907 | \item[\T{-e} \rm\emph{stat}] executes string \verb|stat|; | 4106 | \item[\T{-e} \rm\emph{stat}] executes string \emph{stat}; |
3908 | \item[\T{-f filename}] executes file \verb|filename| with the | 4107 | \item[\T{-f} \rm\emph{filename}] executes file \emph{filename} with the |
3909 | remaining arguments in table \verb|arg|; | 4108 | remaining arguments in table \verb|arg|; |
3910 | \item[\T{-i}] enters interactive mode with prompt; | 4109 | \item[\T{-i}] enters interactive mode with prompt; |
3911 | \item[\T{-q}] enters interactive mode without prompt; | 4110 | \item[\T{-q}] enters interactive mode without prompt; |
3912 | \item[\T{-v}] prints version information; | 4111 | \item[\T{-v}] prints version information; |
3913 | \item[\T{var=value}] sets global \verb|var| to string \verb|"value"|; | 4112 | \item[\T{var=}\rm\emph{value}] sets global \verb|var| to string \verb|"|\emph{value}\verb|"|; |
3914 | \item[\T{filename}] executes file \verb|filename|. | 4113 | \item[\emph{filename}] executes file \emph{filename}. |
3915 | \end{description} | 4114 | \end{description} |
3916 | When called without arguments, | 4115 | When called without arguments, |
3917 | \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, | 4116 | \verb|lua| behaves as \verb|lua -v -i| when \verb|stdin| is a terminal, |
@@ -3944,9 +4143,12 @@ then creates a table | |||
3944 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} | 4143 | arg = {"t1", "t3"; n = 2, [0] = "b.lua"} |
3945 | \end{verbatim} | 4144 | \end{verbatim} |
3946 | and finally runs the file \T{b.lua}. | 4145 | and finally runs the file \T{b.lua}. |
3947 | \DefLIB{getargs} | 4146 | |
3948 | The stand-alone interpreter also provides a \verb|getargs| function that | 4147 | The stand-alone interpreter includes |
4148 | all standard libraries plus the reflexive debug interface. | ||
4149 | It also provides a \verb|getargs| function that | ||
3949 | can be used to access \emph{all} command line arguments. | 4150 | can be used to access \emph{all} command line arguments. |
4151 | \DefLIB{getargs} | ||
3950 | For instance, if you call Lua with the line | 4152 | For instance, if you call Lua with the line |
3951 | \begin{verbatim} | 4153 | \begin{verbatim} |
3952 | $ lua -c a b | 4154 | $ lua -c a b |
@@ -3957,7 +4159,7 @@ then a call to \verb|getargs| in \verb|a| or \verb|b| will return the table | |||
3957 | \end{verbatim} | 4159 | \end{verbatim} |
3958 | 4160 | ||
3959 | In interactive mode, | 4161 | In interactive mode, |
3960 | a multi-line statement can be written finishing intermediate | 4162 | a multi-line statement can be written ending intermediate |
3961 | lines with a backslash (`\verb|\|'). | 4163 | lines with a backslash (`\verb|\|'). |
3962 | If the global variable \IndexVerb{_PROMPT} is defined as a string, | 4164 | If the global variable \IndexVerb{_PROMPT} is defined as a string, |
3963 | then its value is used as the prompt. | 4165 | then its value is used as the prompt. |
@@ -3966,19 +4168,26 @@ Therefore, the prompt can be changed directly on the command line: | |||
3966 | $ lua _PROMPT='myprompt> ' -i | 4168 | $ lua _PROMPT='myprompt> ' -i |
3967 | \end{verbatim} | 4169 | \end{verbatim} |
3968 | or in any Lua programs by assigning to \verb|_PROMPT|. | 4170 | or in any Lua programs by assigning to \verb|_PROMPT|. |
4171 | Note the use of \verb|-i| to enter interactive mode; otherwise, | ||
4172 | the program would end just after the assignment to \verb|_PROMPT|. | ||
3969 | 4173 | ||
3970 | In Unix systems, Lua scripts can be made into executable programs | 4174 | In Unix systems, Lua scripts can be made into executable programs |
3971 | by using \verb|chmod +x| and the~\verb|#!| form, | 4175 | by using \verb|chmod +x| and the~\verb|#!| form, |
3972 | as in \verb|#!/usr/local/bin/lua|, | 4176 | as in \verb|#!/usr/local/bin/lua|, |
3973 | or \verb|#!/usr/local/bin/lua -f| to get other arguments. | 4177 | or \verb|#!/usr/local/bin/lua -f| to get other arguments. |
4178 | (Of course, | ||
4179 | the location of the Lua interpreter may be different in your machine. | ||
4180 | If \verb|lua| is in your \verb|PATH|, | ||
4181 | then a more portable solution is \verb|#!/usr/bin/env lua|.) | ||
3974 | 4182 | ||
3975 | 4183 | ||
4184 | %------------------------------------------------------------------------------ | ||
3976 | \section*{Acknowledgments} | 4185 | \section*{Acknowledgments} |
3977 | 4186 | ||
3978 | The authors would like to thank CENPES/PETROBRAS which, | 4187 | The authors thank CENPES/PETROBRAS which, |
3979 | jointly with \tecgraf, used early versions of | 4188 | jointly with \tecgraf, used early versions of |
3980 | this system extensively and gave valuable comments. | 4189 | this system extensively and gave valuable comments. |
3981 | The authors would also like to thank Carlos Henrique Levy, | 4190 | The authors also thank Carlos Henrique Levy, |
3982 | who found the name of the game. | 4191 | who found the name of the game. |
3983 | Lua means ``moon'' in Portuguese. | 4192 | Lua means ``moon'' in Portuguese. |
3984 | 4193 | ||
@@ -4045,6 +4254,7 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4045 | \end{itemize} | 4254 | \end{itemize} |
4046 | 4255 | ||
4047 | %{=============================================================== | 4256 | %{=============================================================== |
4257 | \newpage | ||
4048 | \section*{The Complete Syntax of Lua} \label{BNF} | 4258 | \section*{The Complete Syntax of Lua} \label{BNF} |
4049 | 4259 | ||
4050 | \addcontentsline{toc}{section}{The Complete Syntax of Lua} | 4260 | \addcontentsline{toc}{section}{The Complete Syntax of Lua} |
@@ -4057,8 +4267,6 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4057 | 4267 | ||
4058 | \index{grammar} | 4268 | \index{grammar} |
4059 | 4269 | ||
4060 | |||
4061 | |||
4062 | \begin{Produc} | 4270 | \begin{Produc} |
4063 | 4271 | ||
4064 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} | 4272 | \produc{chunk}{\rep{stat \opt{\ter{;}}}} |
@@ -4081,7 +4289,7 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4081 | \OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp | 4289 | \OrNL \rwd{for} \Nter{name} \ter{,} \Nter{name} \rwd{in} exp |
4082 | \rwd{do} block \rwd{end} | 4290 | \rwd{do} block \rwd{end} |
4083 | \OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} | 4291 | \OrNL \rwd{function} funcname \ter{(} \opt{parlist1} \ter{)} block \rwd{end} |
4084 | \OrNL \rwd{local} declist \opt{init} | 4292 | \OrNL \rwd{local} namelist \opt{init} |
4085 | } | 4293 | } |
4086 | 4294 | ||
4087 | \produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} | 4295 | \produc{funcname}{\Nter{name} \rep{\ter{.} \Nter{name}} |
@@ -4097,7 +4305,7 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4097 | 4305 | ||
4098 | \produc{varorfunc}{var \Or functioncall} | 4306 | \produc{varorfunc}{var \Or functioncall} |
4099 | 4307 | ||
4100 | \produc{declist}{\Nter{name} \rep{\ter{,} \Nter{name}}} | 4308 | \produc{namelist}{\Nter{name} \rep{\ter{,} \Nter{name}}} |
4101 | 4309 | ||
4102 | \produc{init}{\ter{=} explist1} | 4310 | \produc{init}{\ter{=} explist1} |
4103 | 4311 | ||
@@ -4160,6 +4368,10 @@ The \verb|lua_pushuserdata| function has been replaced by | |||
4160 | \produc{unop}{\ter{-} \Or \rwd{not}} | 4368 | \produc{unop}{\ter{-} \Or \rwd{not}} |
4161 | 4369 | ||
4162 | \end{Produc} | 4370 | \end{Produc} |
4371 | |||
4372 | |||
4373 | \NOTE | ||
4374 | This grammar is not (yet) consistent with the productions in the text. | ||
4163 | %}=============================================================== | 4375 | %}=============================================================== |
4164 | 4376 | ||
4165 | % Index | 4377 | % Index |