diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1995-11-16 18:46:02 -0200 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 1995-11-16 18:46:02 -0200 |
commit | 07d64e78b69422ed165e2af796daae2b06cc8b83 (patch) | |
tree | 51a7a5ea3f06e5d8de8e7f26edf645108c2819a4 | |
parent | fa649fbc26494bf829406a8d94c974a873ab0451 (diff) | |
download | lua-07d64e78b69422ed165e2af796daae2b06cc8b83.tar.gz lua-07d64e78b69422ed165e2af796daae2b06cc8b83.tar.bz2 lua-07d64e78b69422ed165e2af796daae2b06cc8b83.zip |
reference manual
-rw-r--r-- | manual.tex | 1741 |
1 files changed, 1741 insertions, 0 deletions
diff --git a/manual.tex b/manual.tex new file mode 100644 index 00000000..584808e6 --- /dev/null +++ b/manual.tex | |||
@@ -0,0 +1,1741 @@ | |||
1 | \documentstyle[A4,11pt,bnf]{article} | ||
2 | |||
3 | \newcommand{\rw}[1]{{\bf #1}} | ||
4 | \newcommand{\see}[1]{see Section~\ref{#1}} | ||
5 | \newcommand{\nil}{{\bf nil}} | ||
6 | \newcommand{\Line}{\rule{\linewidth}{.5mm}} | ||
7 | \def\tecgraf{{\sf TeC\kern-.21em\lower.7ex\hbox{Graf}}} | ||
8 | |||
9 | \newcommand{\Index}[1]{#1\index{#1}} | ||
10 | \newcommand{\IndexVerb}[1]{{\tt #1}\index{#1}} | ||
11 | \newcommand{\Def}[1]{{\em #1}\index{#1}} | ||
12 | \newcommand{\Deffunc}[1]{\index{{\tt #1}}} | ||
13 | |||
14 | |||
15 | |||
16 | \begin{document} | ||
17 | |||
18 | \title{Reference Manual of the Programming Language Lua 2.2} | ||
19 | |||
20 | \author{% | ||
21 | Roberto Ierusalimschy\quad | ||
22 | Luiz Henrique de Figueiredo\quad | ||
23 | Waldemar Celes Filho | ||
24 | \vspace{1.0ex}\\ | ||
25 | %\small \tecgraf \ --- PUC-Rio\\ | ||
26 | \smallskip | ||
27 | \small\tt roberto,lhf,celes@icad.puc-rio.br | ||
28 | \vspace{2.0ex}\\ | ||
29 | %MCC 08/95 --- | ||
30 | Departamento de Inform\'atica --- PUC-Rio | ||
31 | } | ||
32 | |||
33 | \date{November, 1995} | ||
34 | |||
35 | \maketitle | ||
36 | |||
37 | |||
38 | \begin{abstract} | ||
39 | \noindent | ||
40 | Lua is an extension programming language designed to be used | ||
41 | as a configuration language for any program that needs one. | ||
42 | This document describes version 2.2 of the Lua programming language and the | ||
43 | API that allows interaction between Lua programs and its host C program. | ||
44 | It also presents some examples of using the main features of the system. | ||
45 | \end{abstract} | ||
46 | |||
47 | \vspace{4ex} | ||
48 | \begin{quotation} | ||
49 | \small | ||
50 | \begin{center}{\bf Sum\'ario}\end{center} | ||
51 | \vspace{1ex} | ||
52 | \noindent | ||
53 | Lua \'e uma linguagem de extens\~ao projetada para ser usada como | ||
54 | linguagem de configura\c{c}\~ao em qualquer programa que precise de | ||
55 | uma. | ||
56 | Este documento descreve a vers\~ao 2.2 da linguagem de programa\c{c}\~ao Lua e a | ||
57 | Interface de Programa\c{c}\~ao que permite a intera\c{c}\~ao entre programas Lua | ||
58 | e o programa C hospedeiro. | ||
59 | O documento tamb\'em apresenta alguns exemplos de uso das principais | ||
60 | ca\-racte\-r\'{\i}sticas do sistema. | ||
61 | \end{quotation} | ||
62 | |||
63 | |||
64 | \section{Introduction} | ||
65 | |||
66 | Lua is an extension programming language designed to support | ||
67 | general procedural programming features with data description | ||
68 | facilities. | ||
69 | It is supposed to be used as a configuration language for any | ||
70 | program that needs one. | ||
71 | Its main extensions are related to object-oriented facilities, | ||
72 | and fallbacks, | ||
73 | but it has some other minor contributions. | ||
74 | Lua has been designed and implemented by | ||
75 | W.~Celes~F., L.~H.~de Figueiredo and R.~Ierusalimschy. | ||
76 | |||
77 | Lua is implemented as a library, written in C. | ||
78 | Being an extension language, Lua has no notion of a ``main'' program: | ||
79 | it only works {\em embedded} in a host client, | ||
80 | called the {\em embedding} program. | ||
81 | This host program can invoke functions to execute a piece of | ||
82 | code in Lua, can write and read Lua variables, | ||
83 | and can register C functions to be called by Lua code. | ||
84 | Through the use of C functions, Lua can be augmented to cope with | ||
85 | rather different domains, | ||
86 | thus creating customized programming languages sharing a syntactical framework. | ||
87 | |||
88 | Lua is free distribution software, | ||
89 | and provided as usual with no guarantees. | ||
90 | The implementation described in this manual is available | ||
91 | by anonymous ftp from | ||
92 | \begin{verbatim} | ||
93 | ftp.icad.puc-rio.br:/pub/lua/lua-2.2.tar.gz | ||
94 | \end{verbatim} | ||
95 | or by WWW (World Wide Web) from | ||
96 | \begin{verbatim} | ||
97 | http://www.inf.puc-rio.br/~roberto/lua.html | ||
98 | \end{verbatim} | ||
99 | |||
100 | |||
101 | \section{Environment and Modules} | ||
102 | |||
103 | All statements in Lua are executed in a \Def{global environment}. | ||
104 | This environment, which keeps all global variables and functions, | ||
105 | is initialized at the beginning of the embedding program and | ||
106 | persists until its end. | ||
107 | |||
108 | The global environment can be manipulated by Lua code or | ||
109 | by the embedding program, | ||
110 | which can read and write global variables | ||
111 | using functions in the library that implements Lua. | ||
112 | |||
113 | \Index{Global variables} do not need declaration. | ||
114 | Any variable is assumed to be global unless explicitly declared local | ||
115 | (see local declarations, Section~\ref{localvar}). | ||
116 | Before the first assignment, the value of a global variable is \nil. | ||
117 | |||
118 | The unit of execution of Lua is called a \Def{chunk}. | ||
119 | The syntax for chunks is:% | ||
120 | \footnote{As usual, \rep{{\em a}} means 0 or more {\em a\/}'s, | ||
121 | \opt{{\em a}} means an optional {\em a} and \oneormore{{\em a}} means | ||
122 | one or more {\em a\/}'s.} | ||
123 | \begin{Produc} | ||
124 | \produc{chunk}{\rep{statement \Or function}} | ||
125 | \end{Produc}% | ||
126 | A chunk may contain statements and function definitions, | ||
127 | and may be in a file or in a string inside the host program. | ||
128 | When a chunk is executed, first all its functions and statements are compiled, | ||
129 | then the statements are executed in sequential order. | ||
130 | All modifications a chunk effects on the global environment persist | ||
131 | after its end. | ||
132 | Those include modifications to global variables and definitions | ||
133 | of new functions% | ||
134 | \footnote{Actually, a function definition is an | ||
135 | assignment to a global variable; \see{TypesSec}.}. | ||
136 | |||
137 | |||
138 | |||
139 | \section{\Index{Types}} \label{TypesSec} | ||
140 | |||
141 | Lua is a dynamically typed language. | ||
142 | Variables do not have types; only values do. | ||
143 | All values carry their own type. | ||
144 | Therefore, there are no type definitions in the language. | ||
145 | |||
146 | There are seven \Index{basic types} in Lua: \Def{nil}, \Def{number}, | ||
147 | \Def{string}, \Def{function}, \Def{CFunction}, \Def{userdata}, | ||
148 | and \Def{table}. | ||
149 | {\em Nil} is the type of the value \nil, | ||
150 | whose main property is to be different from any other value. | ||
151 | {\em Number} represents real (floating point) numbers, | ||
152 | while {\em string} has the usual meaning. | ||
153 | |||
154 | Functions are considered first-class values in Lua. | ||
155 | This means that functions can be stored in variables, | ||
156 | passed as arguments to other functions and returned as results. | ||
157 | When a function is defined in Lua, its body is compiled and stored | ||
158 | in a given variable. | ||
159 | Lua can call (and manipulate) functions written in Lua and | ||
160 | functions written in C; the latter have type {\em CFunction\/}. | ||
161 | |||
162 | The type {\em userdata} is provided to allow | ||
163 | arbitrary \Index{C pointers} to be stored in Lua variables. | ||
164 | It corresponds to \verb'void*' and has no pre-defined operations in Lua, | ||
165 | besides assignment and equality test. | ||
166 | However, by using fallbacks, the programmer may define operations | ||
167 | for {\em userdata} values; \see{fallback}. | ||
168 | |||
169 | The type {\em table} implements \Index{associative arrays}, | ||
170 | that is, \Index{arrays} which can be indexed not only with numbers, | ||
171 | but with any value (except \nil). | ||
172 | Therefore, this type may be used not only to represent ordinary arrays, | ||
173 | but also symbol tables, sets, records, etc. | ||
174 | To represent \Index{records}, Lua uses the field name as an index. | ||
175 | The language supports this representation by | ||
176 | providing \verb'a.name' as syntactic sugar for \verb'a["name"]'. | ||
177 | Tables may also carry methods. | ||
178 | Because functions are first class values, | ||
179 | table fields may contain functions. | ||
180 | The form \verb't:f(x)' is syntactic sugar for \verb't.f(t,x)', | ||
181 | which calls the method \verb'f' from the table \verb't' passing | ||
182 | itself as the first parameter. | ||
183 | |||
184 | It is important to notice that tables are objects, and not values. | ||
185 | Variables cannot contain tables, only references to them. | ||
186 | Assignment, parameter passing and returns always manipulate references | ||
187 | to tables, and do not imply any kind of copy. | ||
188 | Moreover, tables must be explicitly created before used; | ||
189 | \see{tableconstructor}. | ||
190 | |||
191 | |||
192 | |||
193 | \section{The Language} | ||
194 | |||
195 | This section describes the lexis, syntax and semantics of Lua. | ||
196 | |||
197 | |||
198 | \subsection{Lexical Conventions} \label{lexical} | ||
199 | |||
200 | Lua is a case sensitive language. | ||
201 | \Index{Identifiers} can be any string of letters, digits, and underscores, | ||
202 | not beginning with a digit. | ||
203 | The following words are reserved, and cannot be used as identifiers: | ||
204 | \index{reserved words} | ||
205 | \begin{verbatim} | ||
206 | and do else elseif end | ||
207 | function if local nil not | ||
208 | or repeat return until then while | ||
209 | \end{verbatim} | ||
210 | |||
211 | The following strings denote other \Index{tokens}: | ||
212 | \begin{verbatim} | ||
213 | ~= <= >= < > == = .. + - * / | ||
214 | % ( ) { } [ ] ; , . | ||
215 | \end{verbatim} | ||
216 | |||
217 | \Index{Literal strings} can be delimited by matching single or double quotes, | ||
218 | and can contain the C-like escape sequences | ||
219 | \verb-'\n'-, \verb-'\t'- and \verb-'\r'-. | ||
220 | Literal strings can also be delimited by matching \verb'[[ ... ]]'. | ||
221 | Literals in this last form may run for several lines, | ||
222 | may contain nested \verb'[[ ... ]]', | ||
223 | and do not interpret escape sequences. | ||
224 | |||
225 | \Index{Comments} start anywhere outside a string with a | ||
226 | double hyphen (\verb'--') and run until the end of the line. | ||
227 | |||
228 | \Index{Numerical constants} may be written with an optional decimal part, | ||
229 | and an optional decimal exponent. | ||
230 | Examples of valid numerical constants are: | ||
231 | \begin{verbatim} | ||
232 | 4 4. .4 4.57e-3 .3e12 | ||
233 | \end{verbatim} | ||
234 | |||
235 | |||
236 | \subsection{\Index{Coercion}} \label{coercion} | ||
237 | |||
238 | Lua provides some automatic conversions. | ||
239 | Any arithmetic operation applied to a string tries to convert | ||
240 | that string to a number, following the usual rules. | ||
241 | Conversely, whenever a number is used when a string is expected, | ||
242 | that number is converted to a string, according to the following rule: | ||
243 | if the number is an integer, it is written without exponent or decimal point; | ||
244 | otherwise, it is formatted following the ``\verb'%g''' | ||
245 | conversion specification of the standard \verb'printf' C function. | ||
246 | |||
247 | |||
248 | |||
249 | \subsection{\Index{Adjustment}} \label{adjust} | ||
250 | |||
251 | Functions in Lua can return many values. | ||
252 | Because there are no type declarations, | ||
253 | the system does not know how many values a function will return, | ||
254 | or how many parameters it needs. | ||
255 | Therefore, sometimes, a list of values must be {\em adjusted\/}, at run time, | ||
256 | to a given length. | ||
257 | If there are more values than are needed, the last values are thrown away. | ||
258 | If there are more needs than values, the list is extended with as | ||
259 | many \nil's as needed. | ||
260 | Adjustment occurs in multiple assignment and function calls. | ||
261 | |||
262 | |||
263 | \subsection{Statements} | ||
264 | |||
265 | Lua supports an almost conventional set of \Index{statements}. | ||
266 | The conventional commands include | ||
267 | assignment, control structures and procedure calls. | ||
268 | Non-conventional commands include table constructors, | ||
269 | explained in Section \ref{tableconstructor}, | ||
270 | and local variable declarations. | ||
271 | |||
272 | \subsubsection{Blocks} | ||
273 | A \Index{block} is a list of statements, executed sequentially. | ||
274 | Any statement can be optionally followed by a semicolon. | ||
275 | \begin{Produc} | ||
276 | \produc{block}{\rep{stat sc} \opt{ret sc}} | ||
277 | \produc{sc}{\opt{\ter{;}}} | ||
278 | \end{Produc}% | ||
279 | For syntactic reasons, a \Index{return statement} can only be written | ||
280 | as the last statement of a block. | ||
281 | This restriction also avoids some ``statement not reached'' errors. | ||
282 | |||
283 | \subsubsection{\Index{Assignment}} \label{assignment} | ||
284 | The language allows \Index{multiple assignment}. | ||
285 | Therefore, the syntax defines a list of variables on the left side, | ||
286 | and a list of expressions on the right side. | ||
287 | Both lists have their elements separated by commas. | ||
288 | \begin{Produc} | ||
289 | \produc{stat}{varlist1 \ter{=} explist1} | ||
290 | \produc{varlist1}{var \rep{\ter{,} var}} | ||
291 | \end{Produc}% | ||
292 | This statement first evaluates all values on the right side | ||
293 | and eventual indices on the left side, | ||
294 | and then makes the assignments. | ||
295 | Therefore, it can be used to exchange two values, as in | ||
296 | \begin{verbatim} | ||
297 | x, y = y, x | ||
298 | \end{verbatim} | ||
299 | Before the assignment, the list of values is {\em adjusted} to | ||
300 | the length of the list of variables; \see{adjust}. | ||
301 | |||
302 | \begin{Produc} | ||
303 | \produc{var}{name} | ||
304 | \end{Produc}% | ||
305 | A single name can denote a global or a local variable, | ||
306 | or a formal parameter. | ||
307 | \begin{Produc} | ||
308 | \produc{var}{var \ter{[} exp1 \ter{]}} | ||
309 | \end{Produc}% | ||
310 | Square brackets are used to index a table. | ||
311 | If \verb'var' results in a table value, | ||
312 | the field indexed by the expression value gets the assigned value. | ||
313 | Otherwise, the fallback {\em settable} is called, | ||
314 | with three parameters: the value of \verb'var', | ||
315 | the value of expression, and the value being assigned to it; | ||
316 | \see{fallback}. | ||
317 | \begin{Produc} | ||
318 | \produc{var}{var \ter{.} name} | ||
319 | \end{Produc}% | ||
320 | The syntax \verb'var.NAME' is just syntactic sugar for | ||
321 | \verb'var["NAME"]'. | ||
322 | |||
323 | \subsubsection{Control Structures} | ||
324 | The \Index{condition expression} of a control structure can return any value. | ||
325 | All values different from \nil\ are considered true, | ||
326 | while \nil\ is considered false. | ||
327 | {\tt if}'s, {\tt while}'s and {\tt repeat}'s have the usual meaning. | ||
328 | |||
329 | \index{while-do}\index{repeat-until}\index{if-then-else} | ||
330 | \begin{Produc} | ||
331 | \produc{stat}{\rwd{while} exp1 \rwd{do} block \rwd{end} \OrNL | ||
332 | \rwd{repeat} block \rwd{until} exp1 \OrNL | ||
333 | \rwd{if} exp1 \rwd{then} block \rep{elseif} | ||
334 | \opt{\rwd{else} block} \rwd{end}} | ||
335 | \produc{elseif}{\rwd{elseif} exp1 \rwd{then} block} | ||
336 | \end{Produc} | ||
337 | |||
338 | A {\tt return} is used to return values from a function. \label{return} | ||
339 | Because a function may return more than one value, | ||
340 | the syntax for a \Index{return statement} is: | ||
341 | \begin{Produc} | ||
342 | \produc{ret}{\rwd{return} explist} | ||
343 | \end{Produc} | ||
344 | |||
345 | \subsubsection{Expressions as Statements} \label{statexp} | ||
346 | All expressions with possible side-effects can be | ||
347 | executed as statements. | ||
348 | These include function calls and table constructors: | ||
349 | \begin{Produc} | ||
350 | \produc{stat}{functioncall} | ||
351 | \produc{stat}{tableconstructor} | ||
352 | \end{Produc}% | ||
353 | Eventual returned values are thrown away. | ||
354 | Function calls are explained in Section \ref{functioncall}; | ||
355 | constructors are the subject of Section \ref{tableconstructor}. | ||
356 | |||
357 | \subsubsection{Local Declarations} \label{localvar} | ||
358 | \Index{Local variables} can be declared anywhere inside a block. | ||
359 | Their scope begins after the declaration and lasts until the | ||
360 | end of the block. | ||
361 | The declaration may include an initial assignment: | ||
362 | \begin{Produc} | ||
363 | \produc{stat}{\rwd{local} declist \opt{init}} | ||
364 | \produc{declist}{name \rep{\ter{,} name}} | ||
365 | \produc{init}{\ter{=} explist1} | ||
366 | \end{Produc}% | ||
367 | If there is an initial assignment, it has the same semantics | ||
368 | of a multiple assignment. | ||
369 | Otherwise, all variables are initialized with \nil. | ||
370 | |||
371 | |||
372 | \subsection{\Index{Expressions}} | ||
373 | |||
374 | \subsubsection{\Index{Simple Expressions}} | ||
375 | Simple expressions are: | ||
376 | \begin{Produc} | ||
377 | \produc{exp}{\ter{(} exp \ter{)}} | ||
378 | \produc{exp}{\rwd{nil}} | ||
379 | \produc{exp}{\ter{number}} | ||
380 | \produc{exp}{\ter{literal}} | ||
381 | \produc{exp}{var} | ||
382 | \end{Produc}% | ||
383 | Numbers (numerical constants) and | ||
384 | string literals are explained in Section~\ref{lexical}. | ||
385 | Variables are explained in Section~\ref{assignment}. | ||
386 | |||
387 | \subsubsection{Arithmetic Operators} | ||
388 | Lua supports the usual \Index{arithmetic operators}. | ||
389 | These operators are the binary | ||
390 | \verb'+', \verb'-', \verb'*', \verb'/' and \verb'^' (exponentiation), | ||
391 | and the unary \verb'-'. | ||
392 | If the operands are numbers, or strings that can be converted to | ||
393 | numbers, according to the rules given in Section \ref{coercion}, | ||
394 | all operations but exponentiation have the usual meaning. | ||
395 | Otherwise, the fallback ``arith'' is called; \see{fallback}. | ||
396 | An exponentiation always calls this fallback. | ||
397 | The standard mathematical library redefines this fallback, | ||
398 | giving the expected meaning to \Index{exponentiation}; | ||
399 | \see{mathlib}. | ||
400 | |||
401 | \subsubsection{Relational Operators} | ||
402 | Lua offers the following \Index{relational operators}: | ||
403 | \begin{verbatim} | ||
404 | < > <= >= ~= == | ||
405 | \end{verbatim} | ||
406 | All return \nil\ as false and 1 as true. | ||
407 | |||
408 | Equality first compares the types of its operands. | ||
409 | If they are different, the result is \nil. | ||
410 | Otherwise, their values are compared. | ||
411 | Numbers and strings are compared in the usual way. | ||
412 | Tables, CFunctions, and functions are compared by reference, | ||
413 | that is, two tables are considered equal only if they are the same table. | ||
414 | The operator \verb'~=' is exactly the negation of equality (\verb'='). | ||
415 | |||
416 | The other operators work as follows. | ||
417 | If both arguments are numbers, they are compared as such. | ||
418 | Otherwise, if both arguments can be converted to strings, | ||
419 | their values are compared using lexicographical order. | ||
420 | Otherwise, the fallback ``order'' is called; \see{fallback}. | ||
421 | |||
422 | \subsubsection{Logical Operators} | ||
423 | All logical operators, like control structures, | ||
424 | consider \nil\ as false and anything else as true. | ||
425 | The \Index{logical operators} are: | ||
426 | \index{and}\index{or}\index{not} | ||
427 | \begin{verbatim} | ||
428 | and or not | ||
429 | \end{verbatim} | ||
430 | The operators \verb'and' and \verb'or' use \Index{short-cut evaluation}, | ||
431 | that is, | ||
432 | the second operand is evaluated only if necessary. | ||
433 | |||
434 | \subsubsection{Concatenation} | ||
435 | Lua offers a string \Index{concatenation} operator, | ||
436 | denoted by ``\IndexVerb{..}''. | ||
437 | If operands are strings or numbers, they are converted to | ||
438 | strings according to the rules in Section \ref{coercion}. | ||
439 | Otherwise, the fallback ``concat'' is called; \see{fallback}. | ||
440 | |||
441 | \subsubsection{Precedence} | ||
442 | \Index{Operator precedence} follows the table below, | ||
443 | from the lower to the higher priority: | ||
444 | \begin{verbatim} | ||
445 | and or | ||
446 | < > <= >= ~= = | ||
447 | .. | ||
448 | + - | ||
449 | * / | ||
450 | not - (unary) | ||
451 | ^ | ||
452 | \end{verbatim} | ||
453 | All binary operators are left associative, except for \verb'^', | ||
454 | which is right associative. | ||
455 | |||
456 | \subsubsection{Table Constructors} \label{tableconstructor} | ||
457 | Table \Index{constructors} are expressions that create tables; | ||
458 | every time a constructor is evaluated, a new table is created. | ||
459 | Constructors can be used to create empty tables, | ||
460 | or to create a table and initialize some fields. | ||
461 | |||
462 | The general syntax for constructors is: | ||
463 | \begin{Produc} | ||
464 | \produc{tableconstructor}{\ter{\{} fieldlist \ter{\}}} | ||
465 | \produc{fieldlist}{lfieldlist \Or ffieldlist \Or lfieldlist \ter{;} ffieldlist} | ||
466 | \produc{lfieldlist}{\opt{lfieldlist1}} | ||
467 | \produc{ffieldlist}{\opt{ffieldlist1}} | ||
468 | \end{Produc} | ||
469 | |||
470 | The form {\em lfieldlist1} is used to initialize lists. | ||
471 | \begin{Produc} | ||
472 | \produc{lfieldlist1}{exp \rep{\ter{,} exp} \opt{\ter{,}}} | ||
473 | \end{Produc}% | ||
474 | The expressions in the list are assigned to consecutive numerical indexes, | ||
475 | starting with 1. | ||
476 | As an example: | ||
477 | \begin{verbatim} | ||
478 | a = {"v1", "v2", 34} | ||
479 | \end{verbatim} | ||
480 | is equivalent to: | ||
481 | \begin{verbatim} | ||
482 | temp = {} | ||
483 | temp[1] = "v1" | ||
484 | temp[2] = "v2" | ||
485 | temp[3] = 34 | ||
486 | a = temp | ||
487 | \end{verbatim} | ||
488 | |||
489 | The next form initializes named fields in a table. | ||
490 | \begin{Produc} | ||
491 | \produc{ffieldlist1}{ffield \rep{\ter{,} ffield} \opt{\ter{,}}} | ||
492 | \produc{ffield}{name \ter{=} exp} | ||
493 | \end{Produc}% | ||
494 | As an example: | ||
495 | \begin{verbatim} | ||
496 | a = {x = 1, y = 3} | ||
497 | \end{verbatim} | ||
498 | is equivalent to: | ||
499 | \begin{verbatim} | ||
500 | temp = {} | ||
501 | temp.x = 1 | ||
502 | temp.y = 3 | ||
503 | a = temp | ||
504 | \end{verbatim} | ||
505 | |||
506 | |||
507 | \subsubsection{Function Calls} \label{functioncall} | ||
508 | A \Index{function call} has the following syntax: | ||
509 | \begin{Produc} | ||
510 | \produc{functioncall}{var realParams} | ||
511 | \end{Produc}% | ||
512 | Here, \verb'var' can be any variable (global, local, indexed, etc). | ||
513 | If its type is {\em function\/} or {\em CFunction\/}, | ||
514 | this function is called. | ||
515 | Otherwise, the fallback ``function'' is called, | ||
516 | having as first parameter the value of \verb'var', | ||
517 | and then the original call parameters. | ||
518 | |||
519 | The form: | ||
520 | \begin{Produc} | ||
521 | \produc{functioncall}{var \ter{:} name realParams} | ||
522 | \end{Produc}% | ||
523 | can be used to call ``methods''. | ||
524 | A call \verb'var:name(...)' | ||
525 | is syntactic sugar for | ||
526 | \begin{verbatim} | ||
527 | var.name(var, ...) | ||
528 | \end{verbatim} | ||
529 | except that \verb'var' is evaluated only once. | ||
530 | |||
531 | \begin{Produc} | ||
532 | \produc{realParams}{\ter{(} \opt{explist1} \ter{)}} | ||
533 | \produc{realParams}{tableconstructor} | ||
534 | \produc{explist1}{exp1 \rep{\ter{,} exp1}} | ||
535 | \end{Produc}% | ||
536 | All argument expressions are evaluated before the call; | ||
537 | then the list of \Index{arguments} is adjusted to | ||
538 | the length of the list of parameters (\see{adjust}); | ||
539 | finally, this list is assigned to the formal parameters. | ||
540 | A call of the form \verb'f{...}' is syntactic sugar for | ||
541 | \verb'f({...})', that is, | ||
542 | the parameter list is a single new table. | ||
543 | |||
544 | Because a function can return any number of results | ||
545 | (\see{return}), | ||
546 | the number of results must be adjusted before used. | ||
547 | If the function is called as an statement (\see{statexp}), | ||
548 | its return list is adjusted to 0. | ||
549 | If the function is called in a place that needs a single value | ||
550 | (syntactically denoted by the non-terminal \verb'exp1'), | ||
551 | its return list is adjusted to 1. | ||
552 | If the function is called in a place that can hold many values | ||
553 | (syntactically denoted by the non-terminal \verb'exp'), | ||
554 | no adjustment is done. | ||
555 | |||
556 | |||
557 | \subsection{\Index{Function Definitions}} | ||
558 | |||
559 | Functions in Lua can be defined anywhere in the global level of a module. | ||
560 | The syntax for function definition is: | ||
561 | \begin{Produc} | ||
562 | \produc{function}{\rwd{function} var \ter{(} \opt{parlist1} \ter{)} | ||
563 | block \rwd{end}} | ||
564 | \end{Produc} | ||
565 | |||
566 | When Lua pre-compiles a chunk, | ||
567 | all its function bodies are pre-compiled, too. | ||
568 | Then, when Lua ``executes'' the function definition, | ||
569 | its body is stored, with type {\em function}, | ||
570 | into the variable \verb'var'. | ||
571 | |||
572 | Parameters act as local variables, | ||
573 | initialized with the argument values. | ||
574 | \begin{Produc} | ||
575 | \produc{parlist1}{'name' \rep{\ter{,} name}} | ||
576 | \end{Produc} | ||
577 | |||
578 | Results are returned using the \verb'return' statement (\see{return}). | ||
579 | If control reaches the end of a function without a return instruction, | ||
580 | the function returns with no results. | ||
581 | |||
582 | There is a special syntax for definition of \Index{methods}, | ||
583 | that is, functions which have an extra parameter \Def{self}. | ||
584 | \begin{Produc} | ||
585 | \produc{function}{\rwd{function} var \ter{:} name \ter{(} \opt{parlist1} | ||
586 | \ter{)} block \rwd{end}} | ||
587 | \end{Produc}% | ||
588 | A declaration like | ||
589 | \begin{verbatim} | ||
590 | function v:f (...) | ||
591 | ... | ||
592 | end | ||
593 | \end{verbatim} | ||
594 | is equivalent to | ||
595 | \begin{verbatim} | ||
596 | function v.f (self, ...) | ||
597 | ... | ||
598 | end | ||
599 | \end{verbatim} | ||
600 | that is, the function gets an extra formal parameter called \verb'self'. | ||
601 | Notice that | ||
602 | the variable \verb'v' must be previously initialized with a table value. | ||
603 | |||
604 | |||
605 | \subsection{Fallbacks} \label{fallback} | ||
606 | |||
607 | Lua provides a powerful mechanism to extend its semantics, | ||
608 | called \Def{fallbacks}. | ||
609 | Basically, a fallback is a programmer defined function | ||
610 | which is called whenever Lua does not know how to proceed. | ||
611 | |||
612 | Lua supports the following fallbacks, | ||
613 | identified by the given strings: | ||
614 | \begin{description} | ||
615 | \item[``arith'']\index{arithmetic fallback} | ||
616 | called when an arithmetic operation is applied to non numerical operands, | ||
617 | or when the binary \verb'^' operation is called. | ||
618 | It receives three arguments: | ||
619 | the two operands (the second one is nil when the operation is unary minus) | ||
620 | and one of the following strings describing the offended operator: | ||
621 | \begin{verbatim} | ||
622 | add sub mul div pow unm | ||
623 | \end{verbatim} | ||
624 | Its return value is the final result of the arithmetic operation. | ||
625 | The default function issues an error. | ||
626 | \item[``order'']\index{order fallback} | ||
627 | called when an order comparison is applied to non numerical or | ||
628 | non string operands. | ||
629 | It receives three arguments: | ||
630 | the two operands and | ||
631 | one of the following strings describing the offended operator: | ||
632 | \begin{verbatim} | ||
633 | lt gt le ge | ||
634 | \end{verbatim} | ||
635 | Its return value is the final result of the comparison operation. | ||
636 | The default function issues an error. | ||
637 | \item[``concat'']\index{concatenation fallback} | ||
638 | called when a concatenation is applied to non string operands. | ||
639 | It receives the two operands as arguments. | ||
640 | Its return value is the final result of the concatenation operation. | ||
641 | The default function issues an error. | ||
642 | \item[``index'']\index{index fallback} | ||
643 | called when Lua tries to retrieve the value of an index | ||
644 | not present in a table. | ||
645 | It receives as arguments the table and the index. | ||
646 | Its return value is the final result of the indexing operation. | ||
647 | The default function returns nil. | ||
648 | \item[``gettable'']\index{gettable fallback} | ||
649 | called when Lua tries to index a non table value. | ||
650 | It receives as arguments the non table value and the index. | ||
651 | Its return value is the final result of the indexing operation. | ||
652 | The default function issues an error. | ||
653 | \item[``settable'']\index{settable fallback} | ||
654 | called when Lua tries to assign indexed a non table value. | ||
655 | It receives as arguments the non table value, | ||
656 | the index, and the assigned value. | ||
657 | The default function issues an error. | ||
658 | \item[``function'']\index{function falback} | ||
659 | called when Lua tries to call a non function value. | ||
660 | It receives as arguments the non function value and the | ||
661 | arguments given in the original call. | ||
662 | Its return values are the final results of the call operation. | ||
663 | The default function issues an error. | ||
664 | \item[``gc''] | ||
665 | called during garbage collection. | ||
666 | It receives as argument the table being collected. | ||
667 | After each run of the collector this function is called with argument nil. | ||
668 | Because this function operates during garbage collection, | ||
669 | it must be used with great care, | ||
670 | and programmers should avoid the creation of new objects | ||
671 | (tables or strings) in this function. | ||
672 | The default function does nothing. | ||
673 | \item[``error'']\index{error fallback} | ||
674 | called when an error occurs. | ||
675 | It receives as argument a string describing the error. | ||
676 | The default function prints the message on the standard error output. | ||
677 | \end{description} | ||
678 | |||
679 | The function \IndexVerb{setfallback} is used to change a fallback action. | ||
680 | Its first argument is a string describing the fallback, | ||
681 | and the second the new function to be called. | ||
682 | It returns the old function for the given fallback. | ||
683 | |||
684 | Section \ref{exfallback} shows an example of the use of fallbacks. | ||
685 | |||
686 | |||
687 | \subsection{Error Handling} \label{error} | ||
688 | |||
689 | Because Lua is an extension language, | ||
690 | all Lua actions start from C code calling a function from the Lua library. | ||
691 | Whenever an error occurs during Lua compilation or execution, | ||
692 | an error fallback function is called, | ||
693 | and then the corresponding function from the library | ||
694 | (\verb'lua_dofile', \verb'lua_dostring', | ||
695 | \verb'lua_call', and \verb'lua_callfunction') | ||
696 | is terminated returning an error condition. | ||
697 | |||
698 | The only argument to the error fallback function is a string describing | ||
699 | the error and some extra informations, | ||
700 | like current line (when the error is at compilation) | ||
701 | or current function (when the error is at execution). | ||
702 | For more information about an error, | ||
703 | the Lua program can include the compilation pragma \verb'$debug'. | ||
704 | \index{debug pragma} | ||
705 | This pragma must be written in a line by itself. | ||
706 | When an error occurs in a program compiled with this option, | ||
707 | the error message includes extra information showing the stack of calls. | ||
708 | |||
709 | The standard error routine only prints the error message | ||
710 | to \verb'stderr'. | ||
711 | If needed, it is possible to change the error fallback routine; | ||
712 | \see{fallback}. | ||
713 | |||
714 | Lua code can generate an error by calling the function \verb'error'. | ||
715 | Its optional parameter is a string, | ||
716 | which is used as the error message. | ||
717 | |||
718 | |||
719 | \section{The Application Program Interface} | ||
720 | |||
721 | This section describes the API for Lua, that is, | ||
722 | the set of C functions available to the host program to communicate | ||
723 | with the library. | ||
724 | The API functions can be classified in the following categories: | ||
725 | \begin{enumerate} | ||
726 | \item executing Lua code; | ||
727 | \item converting values between C and Lua; | ||
728 | \item manipulating (reading and writing) Lua objects; | ||
729 | \item calling Lua functions; | ||
730 | \item C functions to be called by Lua; | ||
731 | \item locking Lua Objects. | ||
732 | \end{enumerate} | ||
733 | All API functions are declared in the file \verb'lua.h'. | ||
734 | |||
735 | \subsection{Executing Lua Code} | ||
736 | A host program can execute Lua programs written in a file or in a string, | ||
737 | using the following functions: | ||
738 | \Deffunc{lua_dofile}\Deffunc{lua_dostring} | ||
739 | \begin{verbatim} | ||
740 | int lua_dofile (char *filename); | ||
741 | int lua_dostring (char *string); | ||
742 | \end{verbatim} | ||
743 | Both functions return an error code: | ||
744 | 0, in case of success; non zero, in case of errors. | ||
745 | The function \verb'lua_dofile', if called with argument NULL (0), | ||
746 | executes the ``file'' {\tt stdin}. | ||
747 | |||
748 | \subsection{Converting Values between C and Lua} \label{valuesCLua} | ||
749 | Because Lua has no static type system, | ||
750 | all values passed between Lua and C have type \IndexVerb{lua\_Object}, | ||
751 | which works like an abstract type in C that can hold any Lua value. | ||
752 | |||
753 | Lua has automatic memory management, and garbage collection. | ||
754 | Because of that, a \verb'lua_Object' has a limited scope, | ||
755 | and is only valid inside the {\em block\/} where it was created. | ||
756 | A C function called from Lua is a block, | ||
757 | and its parameters are valid only until its end. | ||
758 | A good programming practice is to convert Lua objects to C values | ||
759 | as soon as they are available, | ||
760 | and never to store \verb'lua_Object's in C global variables. | ||
761 | |||
762 | When C code calls Lua repeatedly, as in a loop, | ||
763 | objects returned by these calls accumulate, | ||
764 | and may create a memory problem. | ||
765 | To avoid this, | ||
766 | nested blocks can be defined with the functions: | ||
767 | \begin{verbatim} | ||
768 | void lua_beginblock (void); | ||
769 | void lua_endblock (void); | ||
770 | \end{verbatim} | ||
771 | After the end of the block, | ||
772 | all \verb'lua_Object''s created inside it are released. | ||
773 | |||
774 | To check the type of a \verb'lua_Object', | ||
775 | the following function is available: | ||
776 | \Deffunc{lua_type} | ||
777 | \begin{verbatim} | ||
778 | int lua_type (lua_Object object); | ||
779 | \end{verbatim} | ||
780 | plus the following macros: | ||
781 | \Deffunc{lua_isnil}\Deffunc{lua_isnumber}\Deffunc{lua_isstring} | ||
782 | \Deffunc{lua_istable}\Deffunc{lua_iscfunction}\Deffunc{lua_isuserdata} | ||
783 | \begin{verbatim} | ||
784 | int lua_isnil (lua_Object object); | ||
785 | int lua_isnumber (lua_Object object); | ||
786 | int lua_isstring (lua_Object object); | ||
787 | int lua_istable (lua_Object object); | ||
788 | int lua_iscfunction (lua_Object object); | ||
789 | int lua_isuserdata (lua_Object object); | ||
790 | \end{verbatim} | ||
791 | All macros return 1 if the object has the given type, | ||
792 | and 0 otherwise. | ||
793 | |||
794 | The function \verb'lua_type' can be used to distinguish between | ||
795 | different kinds of user data; see below. | ||
796 | |||
797 | To translate a value from type \verb'lua_Object' to a specific C type, | ||
798 | the programmer can use: | ||
799 | \Deffunc{lua_getnumber}\Deffunc{lua_getstring} | ||
800 | \Deffunc{lua_getcfunction}\Deffunc{lua_getuserdata} | ||
801 | \begin{verbatim} | ||
802 | double lua_getnumber (lua_Object object); | ||
803 | char *lua_getstring (lua_Object object); | ||
804 | lua_CFunction lua_getcfunction (lua_Object object); | ||
805 | void *lua_getuserdata (lua_Object object); | ||
806 | \end{verbatim} | ||
807 | \verb'lua_getnumber' converts a \verb'lua_Object' to a float. | ||
808 | This \verb'lua_Object' must be a number or a string convertible to number | ||
809 | (\see{coercion}); otherwise, the function returns 0. | ||
810 | |||
811 | \verb'lua_getstring' converts a \verb'lua_Object' to a string (\verb'char *'). | ||
812 | This \verb'lua_Object' must be a string or a number; | ||
813 | otherwise, the function returns 0 (the null pointer). | ||
814 | This function does not create a new string, but returns a pointer to | ||
815 | a string inside the Lua environment. | ||
816 | Because Lua has garbage collection, there is no guarantee that such | ||
817 | pointer will be valid after the block ends. | ||
818 | |||
819 | \verb'lua_getcfunction' converts a \verb'lua_Object' to a C function. | ||
820 | This \verb'lua_Object' must have type {\em CFunction\/}; | ||
821 | otherwise, the function returns 0 (the null pointer). | ||
822 | The type \verb'lua_CFunction' is explained in Section~\ref{LuacallC}. | ||
823 | |||
824 | \verb'lua_getuserdata' converts a \verb'lua_Object' to \verb'void*'. | ||
825 | This \verb'lua_Object' must have type {\em userdata\/}; | ||
826 | otherwise, the function returns 0 (the null pointer). | ||
827 | |||
828 | The reverse process, that is, passing a specific C value to Lua, | ||
829 | is done by using the following functions: | ||
830 | \Deffunc{lua_pushnumber}\Deffunc{lua_pushstring}\Deffunc{lua_pushliteral} | ||
831 | \Deffunc{lua_pushcfunction}\Deffunc{lua_pushusertag}\Deffunc{lua_pushuserdata} | ||
832 | \begin{verbatim} | ||
833 | void lua_pushnumber (double n); | ||
834 | void lua_pushstring (char *s); | ||
835 | void lua_pushliteral (char *s); | ||
836 | void lua_pushcfunction (lua_CFunction f); | ||
837 | void lua_pushusertag (void *u, int tag); | ||
838 | \end{verbatim} | ||
839 | plus the macro: | ||
840 | \begin{verbatim} | ||
841 | void lua_pushuserdata (void *u); | ||
842 | \end{verbatim} | ||
843 | All of them receive a C value, | ||
844 | convert it to a correspondent \verb'lua_Object', | ||
845 | and leave the result on the top of the Lua stack, | ||
846 | where it can be assigned to a Lua variable, | ||
847 | passed as paramenter to a Lua function, etc (see below). \label{pushing} | ||
848 | \verb'lua_pushliteral' is like \verb'lua_pushstring', | ||
849 | but also puts the string in the Lua literal table. | ||
850 | This avoids the string to be garbage collected, | ||
851 | and therefore has a better overall performance. | ||
852 | As a rule, when the string to be pushed is a literal, | ||
853 | \verb'lua_pushliteral' should be used. | ||
854 | |||
855 | User data can have different tags, | ||
856 | whose semantics are defined by the host program. | ||
857 | Any positive integer can be used to tag a user data. | ||
858 | When a user data is retrieved, | ||
859 | the function \verb'lua_type' can be used to get its tag. | ||
860 | |||
861 | To complete the set, | ||
862 | the value \nil\ or a \verb'lua_Object' can also be pushed onto the stack, | ||
863 | with: | ||
864 | \Deffunc{lua_pushnil}\Deffunc{lua_pushobject} | ||
865 | \begin{verbatim} | ||
866 | void lua_pushnil (void); | ||
867 | void lua_pushobject (lua_Object object); | ||
868 | \end{verbatim} | ||
869 | |||
870 | |||
871 | \subsection{Manipulating Lua Objects} | ||
872 | To read the value of any global Lua variable, | ||
873 | one can use the function: | ||
874 | \Deffunc{lua_getglobal} | ||
875 | \begin{verbatim} | ||
876 | lua_Object lua_getglobal (char *varname); | ||
877 | \end{verbatim} | ||
878 | To store a value previously pushed onto the stack in a global variable, | ||
879 | there is the function: | ||
880 | \Deffunc{lua_storeglobal} | ||
881 | \begin{verbatim} | ||
882 | void lua_storeglobal (char *varname); | ||
883 | \end{verbatim} | ||
884 | |||
885 | Tables can also be manipulated via the API. | ||
886 | The function | ||
887 | \Deffunc{lua_getsubscript} | ||
888 | \begin{verbatim} | ||
889 | lua_Object lua_getsubscript (void); | ||
890 | \end{verbatim} | ||
891 | expects on the stack a table and an index, | ||
892 | and returns the contents of the table at that index. | ||
893 | As in Lua, if the first object is not a table, | ||
894 | or the index is not present in the table, | ||
895 | the correspondent fallback is called. | ||
896 | |||
897 | For compatibility with previous versions of the API, | ||
898 | the following macros are supported: | ||
899 | \Deffunc{lua_getindexed}\Deffunc{lua_getfield} | ||
900 | \begin{verbatim} | ||
901 | lua_Object lua_getindexed (lua_Object table, float index); | ||
902 | lua_Object lua_getfield (lua_Object table, char *field); | ||
903 | \end{verbatim} | ||
904 | The first one is used for numeric indices, | ||
905 | while the second can be used for any string index. | ||
906 | |||
907 | To store a value in an index, | ||
908 | the program must push onto the stack the table, the index, | ||
909 | and the value, | ||
910 | and then call the function: | ||
911 | \Deffunc{lua_storesubscript} | ||
912 | \begin{verbatim} | ||
913 | void lua_storesubscript (void); | ||
914 | \end{verbatim} | ||
915 | Again, the correspondent fallback is called if needed. | ||
916 | |||
917 | Finally, the function | ||
918 | \Deffunc{lua_createtable} | ||
919 | \begin{verbatim} | ||
920 | lua_Object lua_createtable (void); | ||
921 | \end{verbatim} | ||
922 | creates a new table. | ||
923 | |||
924 | {\em Please Notice:\/} | ||
925 | Most functions from the Lua library receive parameters through the stack. | ||
926 | Because other functions also use the stack, | ||
927 | it is important that these | ||
928 | parameters be pushed just before the correspondent call, | ||
929 | without intermediate calls to the Lua library. | ||
930 | For instance, suppose the user wants the value of \verb'a[i]'. | ||
931 | A simplistic solution would be: | ||
932 | \begin{verbatim} | ||
933 | /* Warning: WRONG CODE */ | ||
934 | lua_Object result; | ||
935 | lua_pushobject(lua_getglobal("a")); /* push table */ | ||
936 | lua_pushobject(lua_getglobal("i")); /* push index */ | ||
937 | result = lua_getsubscript(); | ||
938 | \end{verbatim} | ||
939 | However, the call \verb'lua_getglobal("i")' modifies the stack, | ||
940 | and invalidates the previous pushed value. | ||
941 | A correct solution could be: | ||
942 | \begin{verbatim} | ||
943 | lua_Object result; | ||
944 | lua_Object index = lua_getglobal("i"); | ||
945 | lua_pushobject(lua_getglobal("a")); /* push table */ | ||
946 | lua_pushobject(index); /* push index */ | ||
947 | result = lua_getsubscript(); | ||
948 | \end{verbatim} | ||
949 | |||
950 | \subsection{Calling Lua Functions} | ||
951 | Functions defined in Lua by a chunk executed with | ||
952 | \verb'dofile' or \verb'dostring' can be called from the host program. | ||
953 | This is done using the following protocol: | ||
954 | first, the arguments to the function are pushed onto the Lua stack | ||
955 | (\see{pushing}), in direct order, i.e., the first argument is pushed first. | ||
956 | Again, it is important to emphasize that, during this phase, | ||
957 | no other Lua function can be called. | ||
958 | |||
959 | Then, the function is called using | ||
960 | \Deffunc{lua_call}\Deffunc{lua_callfunction} | ||
961 | \begin{verbatim} | ||
962 | int lua_call (char *functionname); | ||
963 | \end{verbatim} | ||
964 | or | ||
965 | \begin{verbatim} | ||
966 | int lua_callfunction (lua_Object function); | ||
967 | \end{verbatim} | ||
968 | Both functions return an error code: | ||
969 | 0, in case of success; non zero, in case of errors. | ||
970 | Finally, the returned values (a Lua function may return many values) | ||
971 | can be retrieved with the macro | ||
972 | \Deffunc{lua_getresult} | ||
973 | \begin{verbatim} | ||
974 | lua_Object lua_getresult (int number); | ||
975 | \end{verbatim} | ||
976 | where \verb'number' is the order of the result, starting with 1. | ||
977 | When called with a number larger than the actual number of results, | ||
978 | this function returns \verb'LUA_NOOBJECT'. | ||
979 | |||
980 | Two special Lua functions have exclusive interfaces: | ||
981 | \verb'error' and \verb'setfallback'. | ||
982 | A C function can generate a Lua error calling the function | ||
983 | \Deffunc{lua_error} | ||
984 | \begin{verbatim} | ||
985 | void lua_error (char *message); | ||
986 | \end{verbatim} | ||
987 | This function never returns. | ||
988 | If the C function has been called from Lua, | ||
989 | the corresponding Lua execution terminates, | ||
990 | as if an error had occurred inside Lua code. | ||
991 | Otherwise, the whole program terminates. | ||
992 | |||
993 | Fallbacks can be changed with: | ||
994 | \Deffunc{lua_setfallback} | ||
995 | \begin{verbatim} | ||
996 | lua_Object lua_setfallback (char *name, lua_CFunction fallback); | ||
997 | \end{verbatim} | ||
998 | The first parameter is the fallback name, | ||
999 | and the second a CFunction to be used as the new fallback. | ||
1000 | This function returns a \verb'lua_Object', | ||
1001 | which is the old fallback value, | ||
1002 | or nil on fail (invalid fallback name). | ||
1003 | This old value can be used for chaining fallbacks. | ||
1004 | |||
1005 | An example of C code calling a Lua function is shown in | ||
1006 | Section~\ref{exLuacall}. | ||
1007 | |||
1008 | |||
1009 | \subsection{C Functions} \label{LuacallC} | ||
1010 | To register a C function to Lua, | ||
1011 | there is the following macro: | ||
1012 | \Deffunc{lua_register} | ||
1013 | \begin{verbatim} | ||
1014 | #define lua_register(n,f) (lua_pushcfunction(f), lua_storeglobal(n)) | ||
1015 | /* char *n; */ | ||
1016 | /* lua_CFunction f; */ | ||
1017 | \end{verbatim} | ||
1018 | which receives the name the function will have in Lua, | ||
1019 | and a pointer to the function. | ||
1020 | This pointer must have type \verb'lua_CFunction', | ||
1021 | which is defined as | ||
1022 | \Deffunc{lua_CFunction} | ||
1023 | \begin{verbatim} | ||
1024 | typedef void (*lua_CFunction) (void); | ||
1025 | \end{verbatim} | ||
1026 | that is, a pointer to a function with no parameters and no results. | ||
1027 | |||
1028 | In order to communicate properly with Lua, | ||
1029 | a C function must follow a protocol, | ||
1030 | which defines the way parameters and results are passed. | ||
1031 | |||
1032 | To access its arguments, a C function calls: | ||
1033 | \Deffunc{lua_getparam} | ||
1034 | \begin{verbatim} | ||
1035 | lua_Object lua_getparam (int number); | ||
1036 | \end{verbatim} | ||
1037 | where \verb'number' starts with 1 to get the first argument. | ||
1038 | When called with a number larger than the actual number of arguments, | ||
1039 | this function returns \IndexVerb{LUA\_NOOBJECT}. | ||
1040 | In this way, it is possible to write functions that work with | ||
1041 | a variable number of parameters. | ||
1042 | |||
1043 | To return values, a C function just pushes them onto the stack, | ||
1044 | in direct order; \see{valuesCLua}. | ||
1045 | Like a Lua function, a C function called by Lua can also return | ||
1046 | many results. | ||
1047 | |||
1048 | Section~\ref{exCFunction} presents an example of a CFunction. | ||
1049 | |||
1050 | |||
1051 | \subsection{Locking Lua Objects} | ||
1052 | |||
1053 | As already noted, \verb'lua_Object's are volatile. | ||
1054 | If the C code needs to keep a \verb'lua_Object' | ||
1055 | outside block boundaries, | ||
1056 | it has to {\em lock} the object. | ||
1057 | The routines to manipulate locking are the following: | ||
1058 | \Deffunc{lua_lock}\Deffunc{lua_getlocked} | ||
1059 | \Deffunc{lua_pushlocked}\Deffunc{lua_unlock} | ||
1060 | \begin{verbatim} | ||
1061 | int lua_lock (void); | ||
1062 | lua_Object lua_getlocked (int ref); | ||
1063 | void lua_pushlocked (int ref); | ||
1064 | void lua_unlock (int ref); | ||
1065 | \end{verbatim} | ||
1066 | The function \verb'lua_lock' locks the object | ||
1067 | which is on the top of the stack, | ||
1068 | and returns a reference to it. | ||
1069 | Whenever the locked object is needed, | ||
1070 | a call to \verb'lua_getlocked' | ||
1071 | returns a handle to it, | ||
1072 | while \verb'lua_pushlocked' pushes the handle on the stack. | ||
1073 | When a locked object is no longer needed, | ||
1074 | it can be unlocked with a call to \verb'lua_unlock'. | ||
1075 | |||
1076 | |||
1077 | |||
1078 | \section{Predefined Functions and Libraries} | ||
1079 | |||
1080 | The set of \Index{predefined functions} in Lua is small but powerful. | ||
1081 | Most of them provide features that allows some degree of | ||
1082 | \Index{reflexivity} in the language. | ||
1083 | Many of these features cannot be simulated with the rest of the | ||
1084 | Language nor with the standard API. | ||
1085 | |||
1086 | The libraries, on the other hand, provide useful routines | ||
1087 | that are implemented directly through the standard API. | ||
1088 | Therefore, they are not necessary to the language, | ||
1089 | and are provided as separated C modules. | ||
1090 | Currently there are three standard libraries: | ||
1091 | \begin{itemize} | ||
1092 | \item string manipulation; | ||
1093 | \item mathematical functions (sin, cos, etc); | ||
1094 | \item input and output. | ||
1095 | \end{itemize} | ||
1096 | In order to have access to these libraries, | ||
1097 | the host program must call the functions | ||
1098 | \verb-strlib_open-, \verb-mathlib_open-, and \verb-iolib_open-, | ||
1099 | declared in \verb-lualib.h-. | ||
1100 | |||
1101 | |||
1102 | \subsection{Predefined Functions} | ||
1103 | |||
1104 | \subsubsection*{{\tt dofile (filename)}}\Deffunc{dofile} | ||
1105 | This function receives a file name, | ||
1106 | opens it and executes its contents as a Lua chunk. | ||
1107 | It returns 1 if there are no errors, \nil\ otherwise. | ||
1108 | |||
1109 | \subsubsection*{{\tt dostring (string)}}\Deffunc{dostring} | ||
1110 | This function executes a given string as a Lua chunk. | ||
1111 | It returns 1 if there are no errors, \nil\ otherwise. | ||
1112 | |||
1113 | \subsubsection*{{\tt next (table, index)}}\Deffunc{next} | ||
1114 | This function allows a program to traverse all fields of a table. | ||
1115 | Its first argument is a table and its second argument | ||
1116 | is an index in this table. | ||
1117 | It returns the next index of the table and the | ||
1118 | value associated with the index. | ||
1119 | When called with \nil\ as its second argument, | ||
1120 | the function returns the first index | ||
1121 | of the table (and its associated value). | ||
1122 | When called with the last index, or with \nil\ in an empty table, | ||
1123 | it returns \nil. | ||
1124 | |||
1125 | In Lua there is no declaration of fields; | ||
1126 | semantically, there is no difference between a | ||
1127 | field not present in a table or a field with value \nil. | ||
1128 | Therefore, the function only considers fields with non nil values. | ||
1129 | The order the indices are enumerated is not specified, | ||
1130 | {\em even for numeric indices}. | ||
1131 | |||
1132 | See Section \ref{exnext} for an example of the use of this function. | ||
1133 | |||
1134 | \subsubsection*{{\tt nextvar (name)}}\Deffunc{nextvar} | ||
1135 | This function is similar to the function \verb'next', | ||
1136 | but it iterates over the global variables. | ||
1137 | Its single argument is the name of a global variable, | ||
1138 | or \nil\ to get a first name. | ||
1139 | Similarly to \verb'next', it returns the name of another variable | ||
1140 | and its value, | ||
1141 | or \nil\ if there are no more variables. | ||
1142 | See Section \ref{exnext} for an example of the use of this function. | ||
1143 | |||
1144 | \subsubsection*{{\tt print (e1, e2, ...)}}\Deffunc{print} | ||
1145 | This function receives any number of arguments, | ||
1146 | and prints their values in a reasonable format. | ||
1147 | Each value is printed in a new line. | ||
1148 | This function is not intended for formatted output, | ||
1149 | but as a quick way to show a value, | ||
1150 | for instance for error messages or debugging. | ||
1151 | See Section~\ref{libio} for functions for formatted output. | ||
1152 | |||
1153 | \subsubsection*{{\tt tonumber (e)}}\Deffunc{tonumber} | ||
1154 | This function receives one argument, | ||
1155 | and tries to convert it to a number. | ||
1156 | If the argument is already a number or a string convertible | ||
1157 | to a number (\see{coercion}), it returns that number; | ||
1158 | otherwise, it returns \nil. | ||
1159 | |||
1160 | \subsubsection*{{\tt type (v)}}\Deffunc{type} | ||
1161 | This function allows Lua to test the type of a value. | ||
1162 | It receives one argument, and returns its type, coded as a string. | ||
1163 | The possible results of this function are | ||
1164 | \verb'"nil"' (a string, not the value \nil), | ||
1165 | \verb'"number"', | ||
1166 | \verb'"string"', | ||
1167 | \verb'"table"', | ||
1168 | \verb'"function"' (returned both for C functions and Lua functions), | ||
1169 | and \verb'"userdata"'. | ||
1170 | |||
1171 | Besides this string, the function returns a second result, | ||
1172 | which is the \Def{tag} of the value. | ||
1173 | This tag can be used to distinguish between user | ||
1174 | data with different tags, | ||
1175 | and between C functions and Lua functions. | ||
1176 | |||
1177 | \subsubsection*{{\tt error (message)}}\Deffunc{error} | ||
1178 | This function issues an error message and terminates | ||
1179 | the last called function from the library | ||
1180 | (\verb'lua_dofile', \verb'lua_dostring', \ldots). | ||
1181 | It never returns. | ||
1182 | |||
1183 | \subsubsection*{{\tt setglobal (name, value)}}\Deffunc{setglobal} | ||
1184 | This function assigns the given value to a global variable. | ||
1185 | The string \verb'name' does not need to be a syntactically valid variable name. | ||
1186 | Therefore, this function can set global variables with strange names like | ||
1187 | \verb'm v 1' or \verb'34'. | ||
1188 | |||
1189 | \subsubsection*{{\tt getglobal (name)}}\Deffunc{getglobal} | ||
1190 | This function retrieves the value of a global variable. | ||
1191 | The string \verb'name' does not need to be a syntactically valid variable name. | ||
1192 | |||
1193 | \subsubsection*{{\tt setfallback (fallbackname, newfallback)}} | ||
1194 | \Deffunc{setfallback} | ||
1195 | This function sets a new fallback function to the given fallback. | ||
1196 | It returns the old fallback function. | ||
1197 | |||
1198 | \subsection{String Manipulation} | ||
1199 | This library provides generic functions for string manipulation, | ||
1200 | such as finding and extracting substrings. | ||
1201 | When indexing a string, the first character has position 1. | ||
1202 | See Section \ref{exstring} for some examples on string manipulation | ||
1203 | in Lua. | ||
1204 | |||
1205 | \subsubsection*{{\tt strfind (str, substr, [init, [end]])}} | ||
1206 | \Deffunc{strfind} | ||
1207 | Receives two string arguments, | ||
1208 | and returns a number. | ||
1209 | This number indicates the first position where the second argument appears | ||
1210 | in the first argument. | ||
1211 | If the second argument is not a substring of the first one, | ||
1212 | then \verb'strfind' returns \nil. | ||
1213 | A third optional numerical argument specifies where to start the search. | ||
1214 | Another optional numerical argument specifies where to stop it. | ||
1215 | |||
1216 | \subsubsection*{{\tt strlen (s)}}\Deffunc{strlen} | ||
1217 | Receives a string and returns its length. | ||
1218 | |||
1219 | \subsubsection*{{\tt strsub (s, i, [j])}}\Deffunc{strsub} | ||
1220 | Returns another string, which is a substring of \verb's', | ||
1221 | starting at \verb'i' and runing until \verb'j'. | ||
1222 | If \verb'j' is absent, | ||
1223 | it is assumed to be equal to the length of \verb's'. | ||
1224 | Particularly, the call \verb'strsub(s,1,j)' returns a prefix of \verb's' | ||
1225 | with length \verb'j', | ||
1226 | while the call \verb'strsub(s,i)' returns a suffix of \verb's', | ||
1227 | starting at \verb'i'. | ||
1228 | |||
1229 | \subsubsection*{{\tt strlower (s)}}\Deffunc{strlower} | ||
1230 | Receives a string and returns a copy of that string with all | ||
1231 | upper case letters changed to lower case. | ||
1232 | All other characters are left unchanged. | ||
1233 | |||
1234 | \subsubsection*{{\tt strupper (s)}}\Deffunc{strupper} | ||
1235 | Receives a string and returns a copy of that string with all | ||
1236 | lower case letters changed to upper case. | ||
1237 | All other characters are left unchanged. | ||
1238 | |||
1239 | \subsubsection*{{\tt ascii (s, [i])}}\Deffunc{ascii} | ||
1240 | Returns the ascii code of the character \verb's[i]'. | ||
1241 | If \verb'i' is absent, it is assumed to be 1. | ||
1242 | |||
1243 | \subsubsection*{{\tt int2str (\{i\})}}\Deffunc{int2str} | ||
1244 | Receives 0 or more numbers. | ||
1245 | Returns a string with length equal to the number of arguments, | ||
1246 | wherein each character has ascii value equal | ||
1247 | to its correspondent argument. | ||
1248 | |||
1249 | \subsection{Mathematical Functions} \label{mathlib} | ||
1250 | |||
1251 | This library is an interface to some functions of the standard C math library. | ||
1252 | Moreover, it registers a fallback for the binary operator \verb'^' which, | ||
1253 | when applied to numbers \verb'x^y', returns $x^y$. | ||
1254 | |||
1255 | The library provides the following functions: | ||
1256 | \Deffunc{abs}\Deffunc{acos}\Deffunc{asin}\Deffunc{atan} | ||
1257 | \Deffunc{atan2}\Deffunc{ceil}\Deffunc{cos}\Deffunc{floor} | ||
1258 | \Deffunc{log}\Deffunc{log10}\Deffunc{max}\Deffunc{min} | ||
1259 | \Deffunc{mod}\Deffunc{sin}\Deffunc{sqrt}\Deffunc{tan} | ||
1260 | \begin{verbatim} | ||
1261 | abs acos asin atan atan2 ceil cos floor | ||
1262 | log log10 max min mod sin sqrt tan | ||
1263 | \end{verbatim} | ||
1264 | Most of them | ||
1265 | are only interfaces to the homonymous functions in the C library, | ||
1266 | except that, for the trigonometric functions, | ||
1267 | all angles are expressed in degrees. | ||
1268 | |||
1269 | The function \verb'max' returns the maximum | ||
1270 | value of its numeric arguments. | ||
1271 | Similarly, \verb'min' computes the minimum. | ||
1272 | Both can be used with an unlimited number of arguments. | ||
1273 | |||
1274 | The function \verb'mod' is equivalent to the \verb'%' operator in C. | ||
1275 | |||
1276 | |||
1277 | \subsection{I/O Facilities} \label{libio} | ||
1278 | |||
1279 | All I/O operations in Lua are done over two {\em current} files, | ||
1280 | one for reading and one for writing. | ||
1281 | Initially, the current input file is \verb'stdin', | ||
1282 | and the current output file is \verb'stdout'. | ||
1283 | |||
1284 | Unless otherwise stated, | ||
1285 | all I/O functions return 1 on success and \nil\ on failure. | ||
1286 | |||
1287 | \subsubsection*{{\tt readfrom (filename)}}\Deffunc{readfrom} | ||
1288 | |||
1289 | This function opens a file named \verb'filename' and sets it as the | ||
1290 | {\em current} input file. | ||
1291 | When called without parameters, | ||
1292 | this function closes the current input file, | ||
1293 | and restores \verb'stdin' as the current input file. | ||
1294 | |||
1295 | {\em System dependent:} if \verb'filename' starts with a \verb'|', | ||
1296 | then a \Index{piped input} is open, via function \IndexVerb{popen}. | ||
1297 | |||
1298 | \subsubsection*{{\tt writeto (filename)}}\Deffunc{writeto} | ||
1299 | |||
1300 | This function opens a file named \verb'filename' and sets it as the | ||
1301 | {\em current} output file. | ||
1302 | Notice that, if the file already exists, it is completely erased with this | ||
1303 | operation. | ||
1304 | When called without parameters, | ||
1305 | this function closes the current output file, | ||
1306 | and restores \verb'stdout' as the current output file. | ||
1307 | \index{closing a file} | ||
1308 | |||
1309 | {\em System dependent:} if \verb'filename' starts with a \verb'|', | ||
1310 | then a \Index{piped output} is open, via function \IndexVerb{popen}. | ||
1311 | |||
1312 | \subsubsection*{{\tt appendto (filename)}}\Deffunc{appendto} | ||
1313 | |||
1314 | This function opens a file named \verb'filename' and sets it as the | ||
1315 | {\em current} output file. | ||
1316 | Unlike the \verb'writeto' operation, | ||
1317 | this function does not erase any previous content of the file. | ||
1318 | This function returns 2 if the file already exists, | ||
1319 | 1 if it creates a new file, and \nil\ on failure. | ||
1320 | |||
1321 | \subsubsection*{{\tt remove (filename)}}\Deffunc{remove} | ||
1322 | |||
1323 | This function deletes the file with the given name. | ||
1324 | |||
1325 | \subsubsection*{{\tt read ([format])}}\Deffunc{read} | ||
1326 | |||
1327 | This function returns a value read from the current input. | ||
1328 | An optional string argument specifies the way the input is interpreted. | ||
1329 | |||
1330 | Without a format argument, {\tt read} first skips blanks, tabs and newlines. | ||
1331 | Then it checks whether the current character is \verb'"' or \verb-'-. | ||
1332 | If so, it reads a string up to the ending quotation mark, | ||
1333 | and returns this string, without the quotation marks. | ||
1334 | Otherwise it reads up to a blank, tab or newline. | ||
1335 | |||
1336 | The format string can have the following format: | ||
1337 | \begin{verbatim} | ||
1338 | ?[n] | ||
1339 | \end{verbatim} | ||
1340 | where \verb'?' can be: | ||
1341 | \begin{description} | ||
1342 | \item['s' or 'S'] to read a string; | ||
1343 | \item['f' or 'F'] to read a real number; | ||
1344 | \item['i' or 'I'] to read an integer. | ||
1345 | \end{description} | ||
1346 | The optional \verb'n' is a number which specifies how many characters | ||
1347 | must be read to compose the input value. | ||
1348 | Particularly, the format \verb'"s1"' reads a single character. | ||
1349 | |||
1350 | \subsubsection*{{\tt readuntil (char)}}\Deffunc{readuntil} | ||
1351 | |||
1352 | Reads the current input until the first ocurrence of the given character. | ||
1353 | Returns the string read. | ||
1354 | The character itself is not read. | ||
1355 | |||
1356 | \subsubsection*{{\tt write (value, [format])}}\Deffunc{write} | ||
1357 | |||
1358 | This function writes the value of its first argument to the current output. | ||
1359 | An optional second argument specifies the format to be used. | ||
1360 | This format is given as a string, composed of four parts. | ||
1361 | The first part is the only one not optional, and must be one of the | ||
1362 | following characters: | ||
1363 | \begin{description} | ||
1364 | \item['s' or 'S'] to write strings; | ||
1365 | \item['f' or 'F'] to write floats; | ||
1366 | \item['i' or 'I'] to write integers. | ||
1367 | \end{description} | ||
1368 | These characters can be followed by | ||
1369 | \begin{verbatim} | ||
1370 | [?][m][.n] | ||
1371 | \end{verbatim} | ||
1372 | where: | ||
1373 | \begin{description} | ||
1374 | \item[\verb'?'] indicates justification inside the field. | ||
1375 | \begin{itemize} | ||
1376 | \item['\verb'<''] right justification (default); | ||
1377 | \item['\verb'>''] left justification; | ||
1378 | \item['\verb'|''] center justification. | ||
1379 | \end{itemize} | ||
1380 | \item[\verb'm'] Indicates the field size in characters. | ||
1381 | \item[\verb'.n'] For reals, indicates the number of digital places. | ||
1382 | For integers, it is the minimum number of digits. | ||
1383 | This option has no meaning for strings. | ||
1384 | \end{description} | ||
1385 | |||
1386 | When called without a format string, | ||
1387 | this function writes numbers using the \verb'%g' format | ||
1388 | and strings with \verb'%s'. | ||
1389 | |||
1390 | % \subsubsection*{{\tt debug ()}} | ||
1391 | % This function, when called, repeatedly presents a prompt \verb'lua_debug> ' | ||
1392 | % in the error output stream (\verb'stderr'), | ||
1393 | % reads a line from the standard input, | ||
1394 | % and executes (``dostring'') the line. | ||
1395 | % The loop ends when the user types \verb'cont' to the prompt. | ||
1396 | % This function then returns and the execution of the program continues. | ||
1397 | |||
1398 | |||
1399 | \section{Some Examples} | ||
1400 | |||
1401 | This section gives examples showing some features of Lua. | ||
1402 | It does not intend to cover the whole language, | ||
1403 | but only to illustrate some interesting uses of the system. | ||
1404 | |||
1405 | |||
1406 | \subsection{The Functions {\tt next} and {\tt nextvar}} \label{exnext} | ||
1407 | \Deffunc{next}\Deffunc{nextvar} | ||
1408 | This example shows how to use the function \verb'next' to iterate | ||
1409 | over the fields of a table. | ||
1410 | Function \Def{clone} receives any table and returns a clone of it. | ||
1411 | \begin{verbatim} | ||
1412 | function clone (t) -- t is a table | ||
1413 | local new_t = {} -- creates a new table | ||
1414 | local i, v = next(t, nil) -- i is an index of t, v = t[i] | ||
1415 | while i do | ||
1416 | new_t[i] = v | ||
1417 | i, v = next(t, i) -- get next index | ||
1418 | end | ||
1419 | return new_t | ||
1420 | end | ||
1421 | \end{verbatim} | ||
1422 | |||
1423 | The next example prints the names of all global variables | ||
1424 | in the system with non nil values: | ||
1425 | \begin{verbatim} | ||
1426 | function printGlobalVariables () | ||
1427 | local i, v = nextvar(nil) | ||
1428 | while i do | ||
1429 | print(i) | ||
1430 | i, v = nextvar(i) | ||
1431 | end | ||
1432 | end | ||
1433 | \end{verbatim} | ||
1434 | |||
1435 | |||
1436 | \subsection{String Manipulation} \label{exstring} | ||
1437 | |||
1438 | The first example is a function to trim extra blanks at the beginning | ||
1439 | and end of a string. | ||
1440 | \begin{verbatim} | ||
1441 | function trim(s) | ||
1442 | local l = 1 | ||
1443 | while strsub(s,l,l) == ' ' do | ||
1444 | l = l+1 | ||
1445 | end | ||
1446 | local r = strlen(s) | ||
1447 | while strsub(s,r,r) == ' ' do | ||
1448 | r = r-1 | ||
1449 | end | ||
1450 | return strsub(s,l,r) | ||
1451 | end | ||
1452 | \end{verbatim} | ||
1453 | |||
1454 | The second example shows a function that eliminates all blanks | ||
1455 | of a string. | ||
1456 | \begin{verbatim} | ||
1457 | function remove_blanks (s) | ||
1458 | local b = strfind(s, ' ') | ||
1459 | while b do | ||
1460 | s = strsub(s, 1, b-1) .. strsub(s, b+1) | ||
1461 | b = strfind(s, ' ') | ||
1462 | end | ||
1463 | return s | ||
1464 | end | ||
1465 | \end{verbatim} | ||
1466 | |||
1467 | |||
1468 | \subsection{\Index{Persistence}} | ||
1469 | Because of its reflexive facilities, | ||
1470 | persistence in Lua can be achieved within the language. | ||
1471 | This section shows some ways to store and retrieve values in Lua, | ||
1472 | using a text file written in the language itself as the storage media. | ||
1473 | |||
1474 | To store a single value with a name, | ||
1475 | the following code is enough: | ||
1476 | \begin{verbatim} | ||
1477 | function store (name, value) | ||
1478 | write('\n' .. name .. '=') | ||
1479 | write_value(value) | ||
1480 | end | ||
1481 | \end{verbatim} | ||
1482 | \begin{verbatim} | ||
1483 | function write_value (value) | ||
1484 | local t = type(value) | ||
1485 | if t == 'nil' then write('nil') | ||
1486 | elseif t == 'number' then write(value) | ||
1487 | elseif t == 'string' then write('[[' .. value .. ']]') | ||
1488 | end | ||
1489 | end | ||
1490 | \end{verbatim} | ||
1491 | In order to restore this value, a \verb'lua_dofile' suffices. | ||
1492 | |||
1493 | Storing tables is a little more complex. | ||
1494 | Assuming that the table is a tree, | ||
1495 | and all indices are identifiers | ||
1496 | (that is, the tables are being used as records), | ||
1497 | its value can be written directly with table constructors. | ||
1498 | First, the function \verb'write_value' is changed to | ||
1499 | \begin{verbatim} | ||
1500 | function write_value (value) | ||
1501 | local t = type(value) | ||
1502 | if t == 'nil' then write('nil') | ||
1503 | elseif t == 'number' then write(value) | ||
1504 | elseif t == 'string' then write('"' .. value .. '"') | ||
1505 | elseif t == 'table' then write_record(value) | ||
1506 | end | ||
1507 | end | ||
1508 | \end{verbatim} | ||
1509 | The function \verb'write_record' is: | ||
1510 | \begin{verbatim} | ||
1511 | function write_record(t) | ||
1512 | local i, v = next(t, nil) | ||
1513 | write('{') -- starts constructor | ||
1514 | while i do | ||
1515 | store(i, v) | ||
1516 | write(', ') | ||
1517 | i, v = next(t, i) | ||
1518 | end | ||
1519 | write('}') -- closes constructor | ||
1520 | end | ||
1521 | \end{verbatim} | ||
1522 | |||
1523 | |||
1524 | \subsection{Inheritance} \label{exfallback} | ||
1525 | The fallback for absent indices can be used to implement many | ||
1526 | kinds of \Index{inheritance} in Lua. | ||
1527 | As an example, | ||
1528 | the following code implements single inheritance: | ||
1529 | \begin{verbatim} | ||
1530 | function Index (t,f) | ||
1531 | if f == 'parent' then -- to avoid loop | ||
1532 | return OldIndex(t,f) | ||
1533 | end | ||
1534 | local p = t.parent | ||
1535 | if type(p) == 'table' then | ||
1536 | return p[f] | ||
1537 | else | ||
1538 | return OldIndex(t,f) | ||
1539 | end | ||
1540 | end | ||
1541 | |||
1542 | OldIndex = setfallback("index", Index) | ||
1543 | \end{verbatim} | ||
1544 | Whenever Lua attempts to access an absent field in a table, | ||
1545 | it calls the fallback function \verb'Index'. | ||
1546 | If the table has a field \verb'parent' with a table value, | ||
1547 | then Lua attempts to access the desired field in this parent object. | ||
1548 | This process is repeated ``upwards'' until a value | ||
1549 | for the field is found or the object has no parent. | ||
1550 | In the latter case, the previous fallback is called to supply a value | ||
1551 | for the field. | ||
1552 | |||
1553 | When better performance is needed, | ||
1554 | the same fallback may be implemented in C, | ||
1555 | as illustrated in Figure~\ref{Cinher}. | ||
1556 | \begin{figure} | ||
1557 | \Line | ||
1558 | \begin{verbatim} | ||
1559 | int lockedParentName; /* stores the lock index for the string "parent" */ | ||
1560 | int lockedOldIndex; /* previous fallback function */ | ||
1561 | |||
1562 | void callOldFallback (lua_Object table, lua_Object index) | ||
1563 | { | ||
1564 | lua_Object oldIndex = lua_getlocked(lockedOldIndex); | ||
1565 | lua_pushobject(table); | ||
1566 | lua_pushobject(index); | ||
1567 | lua_callfunction(oldIndex); | ||
1568 | } | ||
1569 | |||
1570 | void Index (void) | ||
1571 | { | ||
1572 | lua_Object table = lua_getparam(1); | ||
1573 | lua_Object index = lua_getparam(2); | ||
1574 | lua_Object parent; | ||
1575 | if (lua_isstring(index) && strcmp(lua_getstring(index), "parent") == 0) | ||
1576 | { | ||
1577 | callOldFallback(table, index); | ||
1578 | return; | ||
1579 | } | ||
1580 | lua_pushobject(table); | ||
1581 | lua_pushlocked(lockedParentName); | ||
1582 | parent = lua_getsubscript(); | ||
1583 | if (lua_istable(parent)) | ||
1584 | { | ||
1585 | lua_pushobject(parent); | ||
1586 | lua_pushobject(index); | ||
1587 | /* return result from getsubscript */ | ||
1588 | lua_pushobject(lua_getsubscript()); | ||
1589 | } | ||
1590 | else | ||
1591 | callOldFallback(table, index); | ||
1592 | } | ||
1593 | \end{verbatim} | ||
1594 | \caption{Inheritance in C.\label{Cinher}} | ||
1595 | \Line | ||
1596 | \end{figure} | ||
1597 | This code must be registered with: | ||
1598 | \begin{verbatim} | ||
1599 | lua_pushliteral("parent"); | ||
1600 | lockedParentName = lua_lock(); | ||
1601 | lua_pushobject(lua_setfallback("index", Index)); | ||
1602 | lockedOldIndex = lua_lock(); | ||
1603 | \end{verbatim} | ||
1604 | Notice how the string \verb'"parent"' is kept | ||
1605 | locked in Lua for optimal performance. | ||
1606 | |||
1607 | \subsection{A CFunction} \label{exCFunction}\index{functions in C} | ||
1608 | A CFunction to compute the maximum of a variable number of arguments | ||
1609 | is shown in Figure~\ref{Cmax}. | ||
1610 | \begin{figure} | ||
1611 | \Line | ||
1612 | \begin{verbatim} | ||
1613 | void math_max (void) | ||
1614 | { | ||
1615 | int i=1; /* number of arguments */ | ||
1616 | double d, dmax; | ||
1617 | lua_Object o; | ||
1618 | /* the function must get at least one argument */ | ||
1619 | if ((o = lua_getparam(i++)) == LUA_NOOBJECT) | ||
1620 | lua_error ("too few arguments to function `max'"); | ||
1621 | /* and this argument must be a number */ | ||
1622 | if (!lua_isnumber(o)) | ||
1623 | lua_error ("incorrect argument to function `max'"); | ||
1624 | dmax = lua_getnumber (o); | ||
1625 | /* loops until there is no more arguments */ | ||
1626 | while ((o = lua_getparam(i++)) != LUA_NOOBJECT) | ||
1627 | { | ||
1628 | if (!lua_isnumber(o)) | ||
1629 | lua_error ("incorrect argument to function `max'"); | ||
1630 | d = lua_getnumber (o); | ||
1631 | if (d > dmax) dmax = d; | ||
1632 | } | ||
1633 | /* push the result to be returned */ | ||
1634 | lua_pushnumber (dmax); | ||
1635 | } | ||
1636 | \end{verbatim} | ||
1637 | \caption{C function {\tt math\_max}.\label{Cmax}} | ||
1638 | \Line | ||
1639 | \end{figure} | ||
1640 | After registered with | ||
1641 | \begin{verbatim} | ||
1642 | lua_register ("max", math_max); | ||
1643 | \end{verbatim} | ||
1644 | this function is available in Lua, as follows: | ||
1645 | \begin{verbatim} | ||
1646 | i = max(4, 5, 10, -34) -- i receives 10 | ||
1647 | \end{verbatim} | ||
1648 | |||
1649 | |||
1650 | \subsection{Calling Lua Functions} \label{exLuacall} | ||
1651 | |||
1652 | This example illustrates how a C function can call the Lua function | ||
1653 | \verb'remove_blanks' presented in Section~\ref{exstring}. | ||
1654 | \begin{verbatim} | ||
1655 | void remove_blanks (char *s) | ||
1656 | { | ||
1657 | lua_pushstring(s); /* prepare parameter */ | ||
1658 | lua_call("remove_blanks"); /* call Lua function */ | ||
1659 | strcpy(s, lua_getstring(lua_getresult(1))); /* copy result back to 's' */ | ||
1660 | } | ||
1661 | \end{verbatim} | ||
1662 | |||
1663 | |||
1664 | \section*{Acknowledgments} | ||
1665 | |||
1666 | The authors would like to thank CENPES/PETROBR\'AS which, | ||
1667 | jointly with TeCGraf, used extensively early versions of | ||
1668 | this system and gave valuable comments. | ||
1669 | The authors would also like to thank Carlos Henrique Levy, | ||
1670 | who found the name of the game% | ||
1671 | \footnote{BTW, Lua means {\em moon} in Portuguese.}. | ||
1672 | |||
1673 | |||
1674 | |||
1675 | \appendix | ||
1676 | |||
1677 | \section{Incompatibilities with Previous Versions} | ||
1678 | |||
1679 | Although great care has been taken to avoid incompatibilities with | ||
1680 | the previous public versions of Lua, | ||
1681 | some differences had to be introduced. | ||
1682 | Here is a list of all these differences. | ||
1683 | |||
1684 | \subsection*{Incompatibilities with \Index{version 2.1}} | ||
1685 | \begin{itemize} | ||
1686 | \item | ||
1687 | The function {\tt type} now returns the string {\tt function} | ||
1688 | both for C and Lua functions. | ||
1689 | Because Lua functions and C functions are compatible, | ||
1690 | this behavior is usually more useful. | ||
1691 | When needed, the second result of function {\tt type} may be used | ||
1692 | to distinguish between Lua and C functions. | ||
1693 | \item | ||
1694 | A function definition only assigns the function value to the | ||
1695 | given variable at execution time. | ||
1696 | \end{itemize} | ||
1697 | |||
1698 | \subsection*{Incompatibilities with \Index{version 1.1}} | ||
1699 | \begin{itemize} | ||
1700 | \item | ||
1701 | The equality test operator now is denoted by \verb'==', | ||
1702 | instead of \verb'='. | ||
1703 | \item | ||
1704 | The syntax for table construction has been greatly simplified. | ||
1705 | The old \verb'@(size)' has been substituted by \verb'{}'. | ||
1706 | The list constructor (formerly \verb'@[...]') and the record | ||
1707 | constructor (formerly \verb'@{...}') now are both coded like | ||
1708 | \verb'{...}'. | ||
1709 | When the construction involves a function call, | ||
1710 | like in \verb'@func{...}', | ||
1711 | the new syntax does not use the \verb'@'. | ||
1712 | More important, {\em a construction function must now | ||
1713 | explicitly return the constructed table}. | ||
1714 | \item | ||
1715 | The function \verb'lua_call' no longer has the parameter \verb'nparam'. | ||
1716 | \item | ||
1717 | The function \verb'lua_pop' is no longer available, | ||
1718 | since it could lead to strange behavior. | ||
1719 | In particular, | ||
1720 | to access results returned from a Lua function, | ||
1721 | the new macro \verb'lua_getresult' should be used. | ||
1722 | \item | ||
1723 | The old functions \verb'lua_storefield' and \verb'lua_storeindexed' | ||
1724 | have been replaced by | ||
1725 | \begin{verbatim} | ||
1726 | int lua_storesubscript (void); | ||
1727 | \end{verbatim} | ||
1728 | with the parameters explicitly pushed on the stack. | ||
1729 | \item | ||
1730 | The functionality of the function \verb'lua_errorfunction' has been | ||
1731 | replaced by the {\em fallback} mechanism; \see{error}. | ||
1732 | \item | ||
1733 | When calling a function from the Lua library, | ||
1734 | parameters passed through the stack | ||
1735 | must be pushed just before the correspondent call, | ||
1736 | with no intermediate calls to Lua. | ||
1737 | Special care should be taken with macros like | ||
1738 | \verb'lua_getindexed' and \verb'lua_getfield'. | ||
1739 | \end{itemize} | ||
1740 | |||
1741 | \end{document} | ||