Imported from ../lua-3.0.tar.gz.
[lua.git] / doc / manual.html
blob0c3f531cf12a024930b3fcf9d03ec0b2577f95d2
1 <HEAD>
2 <TITLE>Lua 3.0 Reference Manual</TITLE>
3 </HEAD>
4 <BODY>
5 <h1>Lua 3.0 Reference Manual</h1>
7 <!-- ====================================================================== -->
8 <HR>
9 <A NAME="1."></A>
10 <H1>1 - Introduction</H1>
11 <P>
12 Lua is an extension programming language designed to support
13 general procedural programming with data description
14 facilities.
15 It is intended to be used as a light-weight, but powerful,
16 configuration language for any program that needs one.
17 Lua has been designed and implemented by
18 W.&nbsp;Celes,
19 R.&nbsp;Ierusalimschy and
20 L.&nbsp;H.&nbsp;de Figueiredo.
21 <P>
22 Lua is implemented as a library, written in C.
23 Being an extension language, Lua has no notion of a ``main'' program:
24 it only works <EM>embedded</EM> in a host client,
25 called the <EM>embedding</EM> program.
26 This host program can invoke functions to execute a piece of
27 code in Lua, can write and read Lua variables,
28 and can register C functions to be called by Lua code.
29 Through the use of C functions, Lua can be augmented to cope with
30 a wide range of different domains,
31 thus creating customized programming languages sharing a syntactical framework.
32 <P>
33 Lua is free-distribution software,
34 and provided as usual with no guarantees,
35 as stated in the copyright notice in the front page of this manual.
36 The implementation described in this manual is available
37 at the following URL's:
38 <LISTING>
39 <A HREF="http://www.tecgraf.puc-rio.br/lua/">http://www.tecgraf.puc-rio.br/lua/</A>
40 <A HREF="ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz">ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz</A>
41 </LISTING>
42 <P>
43 <P>
44 <!-- ====================================================================== -->
45 <HR>
46 <A NAME="2."></A>
47 <H1>2 - Environment and Chunks</H1>
48 <P>
49 All statements in Lua are executed in a <A NAME="global environment"><EM>global environment</EM></A>.
50 This environment, which keeps all global variables and functions,
51 is initialized at the beginning of the embedding program and
52 persists until its end.
53 <P>
54 The global environment can be manipulated by Lua code or
55 by the embedding program,
56 which can read and write global variables
57 using functions in the library that implements Lua.
58 <P>
59 <A NAME="Global variables">Global variables</A> do not need declaration.
60 Any variable is assumed to be global unless explicitly declared local
61 (see Section&nbsp;<A HREF="#localvar">4.5.5</A>).
62 Before the first assignment, the value of a global variable is <B>nil</B>;
63 this default can be changed (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
64 <P>
65 The unit of execution of Lua is called a <A NAME="chunk"><EM>chunk</EM></A>.
66 The syntax
67 \footnote{As usual, {<EM>a</EM>} means 0 or more <EM>a</EM>'s,
68 [<EM>a</EM>] means an optional <EM>a</EM> and ('<EM>a</EM>)+ means
69 one or more <EM>a</EM>'s.}
70 for chunks is:
71 <LISTING>
72 chunk ::= {stat | function} [ret]
73 </LISTING>
74 A chunk may contain statements and function definitions,
75 and may be in a file or in a string inside the host program.
76 A chunk may optionally end with a <CODE>return</CODE> statement (see Section&nbsp;<A HREF="#return">4.5.3</A>).
77 When a chunk is executed, first all its functions and statements are compiled,
78 then the statements are executed in sequential order.
79 All modifications a chunk effects on the global environment persist
80 after its end.
81 Those include modifications to global variables and definitions
82 of new functions
83 \footnote{Actually, a function definition is an
84 assignment to a global variable (see Section&nbsp;<A HREF="#TypesSec">3</A>).}.
85 <P>
86 Chunks may be pre-compiled into binary form;
87 see program <A NAME="luac"><TT>luac</TT></A> for details.
88 Text files with chunks and their binary pre-compiled forms
89 are interchangeable.
90 Lua automatically detects the file type and acts accordingly.
91 <A NAME="pre-compilation"></A>
92 <P>
93 <A NAME="TypesSec"></A>
94 <!-- ====================================================================== -->
95 <HR>
96 <A NAME="3."></A>
97 <H1>3 - Types and Tags</H1>
98 <P>
99 Lua is a dynamically typed language.
100 Variables do not have types; only values do.
101 Therefore, there are no type definitions in the language.
102 All values carry their own type.
103 Besides a type, all values also have a <A NAME="tag">tag</A>.
105 There are six <A NAME="basic types">basic types</A> in Lua: <A NAME="nil"><EM>nil</EM></A>, <A NAME="number"><EM>number</EM></A>,
106 <A NAME="string"><EM>string</EM></A>, <A NAME="function"><EM>function</EM></A>, <A NAME="userdata"><EM>userdata</EM></A>, and <A NAME="table"><EM>table</EM></A>.
107 <EM>Nil</EM> is the type of the value <B>nil</B>,
108 whose main property is to be different from any other value.
109 <EM>Number</EM> represents real (floating-point) numbers,
110 while <EM>string</EM> has the usual meaning.
111 The function <CODE>type</CODE> returns a string describing the type
112 of a given value (see Section&nbsp;<A HREF="#pdf-type">6.1</A>).
114 Functions are considered first-class values in Lua.
115 This means that functions can be stored in variables,
116 passed as arguments to other functions and returned as results.
117 When a function is defined in Lua, its body is compiled and stored
118 in a given variable.
119 Lua can call (and manipulate) functions written in Lua and
120 functions written in C.
121 They can be distinguished by their tags:
122 all Lua functions have the same tag,
123 and all C functions have the same tag,
124 which is different from the tag of a Lua function.
126 The type <EM>userdata</EM> is provided to allow
127 arbitrary <A NAME="C pointers">C pointers</A> to be stored in Lua variables.
128 It corresponds to a <CODE>void*</CODE> and has no pre-defined operations in Lua,
129 besides assignment and equality test.
130 However, by using <EM>tag methods</EM>,
131 the programmer may define operations for <EM>userdata</EM> values
132 (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
134 The type <EM>table</EM> implements <A NAME="associative arrays">associative arrays</A>,
135 that is, <A NAME="arrays">arrays</A> that can be indexed not only with numbers,
136 but with any value (except <B>nil</B>).
137 Therefore, this type may be used not only to represent ordinary arrays,
138 but also symbol tables, sets, records, etc.
139 To represent <A NAME="records">records</A>, Lua uses the field name as an index.
140 The language supports this representation by
141 providing <CODE>a.name</CODE> as syntactic sugar for <CODE>a["name"]</CODE>.
142 Tables may also carry methods.
143 Because functions are first class values,
144 table fields may contain functions.
145 The form <CODE>t:f(x)</CODE> is syntactic sugar for <CODE>t.f(t,x)</CODE>,
146 which calls the method <CODE>f</CODE> from the table <CODE>t</CODE> passing
147 itself as the first parameter (see Section&nbsp;<A HREF="#func-def">4.7</A>).
149 It is important to notice that tables are <EM>objects</EM>, and not values.
150 Variables cannot contain tables, only <EM>references</EM> to them.
151 Assignment, parameter passing and returns always manipulate references
152 to tables, and do not imply any kind of copy.
153 Moreover, tables must be explicitly created before used
154 (see Section&nbsp;<A HREF="#tableconstructor">4.6.7</A>).
156 Tags are mainly used to select tag methods when
157 some events occur (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
158 Each of the types nil, number and string has a different tag.
159 All values of each of these types have this same pre-defined tag.
160 Values of type function can have two different tags,
161 depending on whether they are Lua or C functions.
162 Finally,
163 values of type userdata and table can have
164 as many different tags as needed (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
165 Tags are created with the function <CODE>newtag</CODE>,
166 and the function <CODE>tag</CODE> returns the tag of a given value.
167 To change the tag of a given table,
168 there is the function <CODE>settag</CODE> (see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).
171 <!-- ====================================================================== -->
172 <HR>
173 <A NAME="4."></A>
174 <H1>4 - The Language</H1>
176 This section describes the lexis, the syntax and the semantics of Lua.
179 <A NAME="lexical"></A>
180 <A NAME="4.1"></A>
181 <H2>4.1 - Lexical Conventions</H2>
183 Lua is a case-sensitive language.
184 <A NAME="Identifiers">Identifiers</A> can be any string of letters, digits, and underscores,
185 not beginning with a digit.
186 The following words are reserved, and cannot be used as identifiers:
187 <A NAME="reserved words"></A>
188 <LISTING>
189 and do else elseif
190 end function if local
191 nil not or repeat
192 return then until while
193 </LISTING>
195 The following strings denote other <A NAME="tokens">tokens</A>:
196 <LISTING>
197 ~= &lt;= &gt;= &lt; &gt; == = .. + - * /
198 % ( ) { } [ ] ; , . ...
199 </LISTING>
201 <A NAME="Literal strings">Literal strings</A> can be delimited by matching single or double quotes,
202 and can contain the C-like escape sequences
203 <CODE>'\n'</CODE>, <CODE>'\t'</CODE> and <CODE>'\r'</CODE>.
204 Literal strings can also be delimited by matching <CODE>[[ ... ]]</CODE>.
205 Literals in this bracketed form may run for several lines,
206 may contain nested <CODE>[[ ... ]]</CODE> pairs,
207 and do not interpret escape sequences.
208 This form is specially convenient for
209 handling strings that contain program pieces or
210 other quoted strings.
212 <A NAME="Comments">Comments</A> start anywhere outside a string with a
213 double hyphen (<CODE>--</CODE>) and run until the end of the line.
214 Moreover,
215 the first line of a chunk file is skipped if it starts with <CODE>#</CODE>
216 \footnote{This facility allows the use of Lua as a script interpreter
217 in Unix systems (see Section&nbsp;<A HREF="#lua-sa">8</A>).}.
219 <A NAME="Numerical constants">Numerical constants</A> may be written with an optional decimal part,
220 and an optional decimal exponent.
221 Examples of valid numerical constants are:
222 <LISTING>
223 4 4.0 0.4 4.57e-3 0.3e12
224 </LISTING>
226 <A NAME="pre-processor"></A>
227 <A NAME="4.2"></A>
228 <H2>4.2 - The Pre-processor</H2>
230 All lines that start with a <CODE>$</CODE> are handled by a pre-processor.
231 The <CODE>$</CODE> can be followed by any of the following directives:
232 <DL>
233 <DT><B><TT>debug</TT></B><DD> - turn on some debugging facilities (see Section&nbsp;<A HREF="#pragma">4.9</A>).
234 <DT><B><TT>nodebug</TT></B><DD> - turn off some debugging facilities (see Section&nbsp;<A HREF="#pragma">4.9</A>).
235 <DT><B><TT>if <EM>cond</TT></EM></B><DD> - starts a conditional part.
236 If <EM>cond</EM> is false, then this part is skipped by the lexical analyzer.
237 <DT><B><TT>ifnot <EM>cond</TT></EM></B><DD> - starts a conditional part.
238 If <EM>cond</EM> is true, then this part is skipped by the lexical analyzer.
239 <DT><B><TT>end</TT></B><DD> - ends a conditional part.
240 <DT><B><TT>else</TT></B><DD> - starts an ``else'' conditional part,
241 switching the ``skip'' status.
242 <DT><B><TT>endinput</TT></B><DD> - ends the lexical parse of the file.
243 </DL>
245 Directives can be freely nested.
246 Particularly, a <CODE>$endinput</CODE> may occur inside a <CODE>$if</CODE>;
247 in that case, even the matching <CODE>$end</CODE> is not parsed.
249 A <EM>cond</EM> part may be:
250 <DL>
251 <DT><B><TT>nil</TT></B><DD> - always false.
252 <DT><B><TT>1</TT></B><DD> - always true.
253 <DT><B><EM>name</EM></B><DD> - true if the value of the
254 global variable <EM>name</EM> is different from <B>nil</B>.
255 Notice that <EM>name</EM> is evaluated before the chunk starts its execution.
256 Therefore, actions in a chunk do not affect its own conditional directives.
257 </DL>
259 <A NAME="coercion"></A>
260 <A NAME="4.3"></A>
261 <H2>4.3 - Coercion</H2>
263 Lua provides some automatic conversions between values.
264 Any arithmetic operation applied to a string tries to convert
265 that string to a number, following the usual rules.
266 Conversely, whenever a number is used when a string is expected,
267 that number is converted to a string, according to the following rule:
268 if the number is an integer, it is written without exponent or decimal point;
269 otherwise, it is formatted following the <CODE>%g</CODE>
270 conversion specification of the <CODE>printf</CODE> function in the
271 standard C library.
272 For complete control on how numbers are converted to strings,
273 use the <CODE>format</CODE> function (see Section&nbsp;<A HREF="#format">6.2</A>).
276 <A NAME="adjust"></A>
277 <A NAME="4.4"></A>
278 <H2>4.4 - Adjustment</H2>
280 Functions in Lua can return many values.
281 Because there are no type declarations,
282 the system does not know how many values a function will return,
283 or how many parameters it needs.
284 Therefore, sometimes, a list of values must be <EM>adjusted</EM>, at run time,
285 to a given length.
286 If there are more values than are needed, then the last values are thrown away.
287 If there are more needs than values, then the list is extended with as
288 many <B>nil</B>'s as needed.
289 Adjustment occurs in multiple assignment and function calls.
292 <A NAME="4.5"></A>
293 <H2>4.5 - Statements</H2>
295 Lua supports an almost conventional set of <A NAME="statements">statements</A>,
296 similar to those in Pascal or C.
297 The conventional commands include
298 assignment, control structures and procedure calls.
299 Non-conventional commands include table constructors
300 (see Section&nbsp;<A HREF="#tableconstructor">4.6.7</A>),
301 and local variable declarations (see Section&nbsp;<A HREF="#localvar">4.5.5</A>).
303 <H3>4.5.1 - Blocks</H3>
304 A <A NAME="block">block</A> is a list of statements, which are executed sequentially.
305 Any statement can be optionally followed by a semicolon:
306 <LISTING>
307 block ::= {stat sc} [ret]
308 sc ::= ['<B>;</B>']
309 </LISTING>
310 For syntactic reasons, a <A NAME="return"><TT>return</TT></A> statement can only be written
311 as the last statement of a block.
312 This restriction also avoids some ``statement not reached'' conditions.
314 <A NAME="assignment"></A>
315 <H3>4.5.2 - <A NAME="Assignment</H3>">Assignment</H3></A>
316 The language allows <A NAME="multiple assignment">multiple assignment</A>.
317 Therefore, the syntax for assignment
318 defines a list of variables on the left side,
319 and a list of expressions on the right side.
320 Both lists have their elements separated by commas:
321 <LISTING>
322 stat ::= varlist1 '<B>=</B>' explist1
323 varlist1 ::= var {'<B>,</B>' var}
324 </LISTING>
325 This statement first evaluates all values on the right side
326 and eventual indices on the left side,
327 and then makes the assignments.
328 Therefore, it can be used to exchange two values, as in
329 <LISTING>
330 x, y = y, x
331 </LISTING>
332 The two lists may have different lengths.
333 Before the assignment, the list of values is <EM>adjusted</EM> to
334 the length of the list of variables (see Section&nbsp;<A HREF="#adjust">4.4</A>).
336 A single name can denote a global or a local variable,
337 or a formal parameter:
338 <LISTING>
339 var ::= name
340 </LISTING>
341 Square brackets are used to index a table:
342 <LISTING>
343 var ::= var '<B>[</B>' exp1 '<B>]</B>'
344 </LISTING>
345 The <CODE>var</CODE> should result in a table value,
346 where the field indexed by the expression value gets the assigned value.
348 The meaning of assignments and evaluations of global variables and
349 indexed variables can be changed by tag methods (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
350 Actually,
351 an assignment <CODE>x = val</CODE>, where <CODE>x</CODE> is a global variable,
352 is equivalent to a call <CODE>setglobal('x', val)</CODE>;
353 an assignment <CODE>t[i] = val</CODE> is equivalent to
354 <CODE>settable_event(t, i, val)</CODE>.
355 See Section&nbsp;<A HREF="#tag-method">4.8</A> for a description of these functions
356 \footnote{Function <CODE>setglobal</CODE> is pre-defined in Lua.
357 Function <TT>settable_event</TT> is used only for explanation purposes.}.
359 The syntax <CODE>var.NAME</CODE> is just syntactic sugar for
360 <CODE>var["NAME"]</CODE>:
361 <LISTING>
362 var ::= var '<B>.</B>' name
363 </LISTING>
365 <H3>4.5.3 - Control Structures</H3>
366 The <A NAME="condition expression">condition expression</A> of a control structure may return any value.
367 All values different from <B>nil</B> are considered true;
368 only <B>nil</B> is considered false.
369 <TT>if</TT>'s, <TT>while</TT>'s and <TT>repeat</TT>'s have the usual meaning.
371 <A NAME="while-do"></A><A NAME="repeat-until"></A><A NAME="if-then-else"></A>
372 <LISTING>
373 stat ::= <B>while</B> exp1 <B>do</B> block <B>end</B> <BR> | <B>repeat</B> block <B>until</B> exp1 <BR> | <B>if</B> exp1 <B>then</B> block {elseif} [<B>else</B> block] <B>end</B>
374 elseif ::= <B>elseif</B> exp1 <B>then</B> block
375 </LISTING>
377 A <TT>return</TT> is used to return values from a function or a chunk.
378 <A NAME="return"></A>
380 Because they may return more than one value,
381 the syntax for a <A NAME="return statement">return statement</A> is:
382 <LISTING>
383 ret ::= <B>return</B> [explist1] [sc]
384 </LISTING>
386 <A NAME="funcstat"></A>
387 <H3>4.5.4 - Function Calls as Statements</H3>
388 Because of possible side-effects,
389 function calls can be executed as statements:
390 <LISTING>
391 stat ::= functioncall
392 </LISTING>
393 In this case, returned values are thrown away.
394 Function calls are explained in Section&nbsp;<A HREF="#functioncall">4.6.8</A>.
396 <A NAME="localvar"></A>
397 <H3>4.5.5 - Local Declarations</H3>
398 <A NAME="Local variables">Local variables</A> may be declared anywhere inside a block.
399 Their scope begins after the declaration and lasts until the
400 end of the block.
401 The declaration may include an initial assignment:
402 <LISTING>
403 stat ::= <B>local</B> declist [init]
404 declist ::= name {'<B>,</B>' name}
405 init ::= '<B>=</B>' explist1
406 </LISTING>
407 If present, an initial assignment has the same semantics
408 of a multiple assignment.
409 Otherwise, all variables are initialized with <B>nil</B>.
412 <A NAME="4.6"></A>
413 <H2>4.6 - Expressions</H2>
415 <H3>4.6.1 - <A NAME="Simple Expressions</H3>">Simple Expressions</H3></A>
416 Simple expressions are:
417 <LISTING>
418 exp ::= '<B>(</B>' exp '<B>)</B>'
419 exp ::= <B>nil</B>
420 exp ::= '<B>number</B>'
421 exp ::= '<B>literal</B>'
422 exp ::= var
423 </LISTING>
424 Numbers (numerical constants) and
425 string literals are explained in Section&nbsp;<A HREF="#lexical">4.1</A>.
426 Variables are explained in Section&nbsp;<A HREF="#assignment">4.5.2</A>.
428 An access to a global variable <CODE>x</CODE> is equivalent to a
429 call <CODE>getglobal('x')</CODE>;
430 an access to an indexed variable <CODE>t[i]</CODE> is equivalent to
431 a call <CODE>gettable_event(t, i)</CODE>.
432 See Section&nbsp;<A HREF="#tag-method">4.8</A> for a description of these functions
433 \footnote{Function <CODE>getglobal</CODE> is pre-defined in Lua.
434 Function <TT>gettable_event</TT> is used only for explanation purposes.}.
436 The non-terminal <EM>exp1</EM> is used to indicate that the values
437 returned by an expression must be adjusted to one single value:
438 <LISTING>
439 exp1 ::= exp
440 </LISTING>
442 <H3>4.6.2 - Arithmetic Operators</H3>
443 Lua supports the usual <A NAME="arithmetic operators">arithmetic operators</A>:
444 the binary <CODE>+</CODE> (addition),
445 <CODE>-</CODE> (subtraction), <CODE>*</CODE> (multiplication),
446 <CODE>/</CODE> (division) and <CODE>^</CODE> (exponentiation),
447 and unary <CODE>-</CODE> (negation).
448 If the operands are numbers, or strings that can be converted to
449 numbers, according to the rules given in Section&nbsp;<A HREF="#coercion">4.3</A>,
450 then all operations except exponentiation have the usual meaning.
451 Otherwise, an appropriate tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
452 An exponentiation always calls a tag method.
453 The standard mathematical library redefines this method for numbers,
454 giving the expected meaning to <A NAME="exponentiation">exponentiation</A>
455 (see Section&nbsp;<A HREF="#mathlib">6.3</A>).
457 <H3>4.6.3 - Relational Operators</H3>
458 Lua provides the following <A NAME="relational operators">relational operators</A>:
459 <LISTING>
460 &lt; &gt; &lt;= &gt;= ~= ==
461 </LISTING>
462 All these return <B>nil</B> as false and a value different from <B>nil</B> as true.
464 Equality first compares the types of its operands.
465 If they are different, then the result is <B>nil</B>.
466 Otherwise, their values are compared.
467 Numbers and strings are compared in the usual way.
468 Tables, userdata and functions are compared by reference,
469 that is, two tables are considered equal only if they are the same table.
470 The operator <CODE>~=</CODE> is exactly the negation of equality (<CODE>==</CODE>).
471 Note that the conversion rules of Section&nbsp;<A HREF="#coercion">4.3</A>
472 <EM>do not</EM> apply to equality comparisons.
473 Thus, <CODE>"0"==0</CODE> evaluates to false.
475 The other operators work as follows.
476 If both arguments are numbers, then they are compared as such.
477 Otherwise, if both arguments are strings,
478 their values are compared using lexicographical order.
479 Otherwise, the ``order'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
481 <H3>4.6.4 - Logical Operators</H3>
482 Like control structures, all logical operators
483 consider <B>nil</B> as false and anything else as true.
484 The <A NAME="logical operators">logical operators</A> are:
485 <A NAME="and"></A><A NAME="or"></A><A NAME="not"></A>
486 <LISTING>
487 and or not
488 </LISTING>
489 The operator <CODE>and</CODE> returns <B>nil</B> if its first argument is <B>nil</B>;
490 otherwise, it returns its second argument.
491 The operator <CODE>or</CODE> returns its first argument
492 if it is different from <B>nil</B>;
493 otherwise, it returns its second argument.
494 Both <CODE>and</CODE> and <CODE>or</CODE> use <A NAME="short-cut evaluation">short-cut evaluation</A>,
495 that is,
496 the second operand is evaluated only when necessary.
498 <H3>4.6.5 - Concatenation</H3>
499 Lua offers a string <A NAME="concatenation">concatenation</A> operator,
500 denoted by ``<A NAME=".."><TT>..</TT></A>''.
501 If operands are strings or numbers, then they are converted to
502 strings according to the rules in Section&nbsp;<A HREF="#coercion">4.3</A>.
503 Otherwise, the ``concat'' tag method is called (see Section&nbsp;<A HREF="#tag-method">4.8</A>).
505 <H3>4.6.6 - Precedence</H3>
506 <A NAME="Operator precedence">Operator precedence</A> follows the table below,
507 from the lower to the higher priority:
508 <LISTING>
509 and or
510 &lt; &gt; &lt;= &gt;= ~= ==
514 not - (unary)
516 </LISTING>
517 All binary operators are left associative,
518 except for <CODE>^</CODE> (exponentiation),
519 which is right associative.
521 <A NAME="tableconstructor"></A>
522 <H3>4.6.7 - Table Constructors</H3>
523 Table <A NAME="constructors">constructors</A> are expressions that create tables;
524 every time a constructor is evaluated, a new table is created.
525 Constructors can be used to create empty tables,
526 or to create a table and initialize some fields.
528 The general syntax for constructors is:
529 <LISTING>
530 tableconstructor ::= '<B>{</B>' fieldlist '<B>}</B>'
531 fieldlist ::= lfieldlist | ffieldlist | lfieldlist '<B>;</B>' ffieldlist
532 lfieldlist ::= [lfieldlist1]
533 ffieldlist ::= [ffieldlist1]
534 </LISTING>
536 The form <EM>lfieldlist1</EM> is used to initialize lists.
537 <LISTING>
538 lfieldlist1 ::= exp {'<B>,</B>' exp} ['<B>,</B>']
539 </LISTING>
540 The expressions in the list are assigned to consecutive numerical indices,
541 starting with 1.
542 For example:
543 <LISTING>
544 a = {"v1", "v2", 34}
545 </LISTING>
546 is essentially equivalent to:
547 <LISTING>
548 temp = {}
549 temp[1] = "v1"
550 temp[2] = "v2"
551 temp[3] = 34
552 a = temp
553 </LISTING>
555 The form <EM>ffieldlist1</EM> initializes other fields in a table:
556 <LISTING>
557 ffieldlist1 ::= ffield {'<B>,</B>' ffield} ['<B>,</B>']
558 ffield ::= '<B>[</B>' exp '<B>]</B>' \ter {= exp | name '<B>=</B>' exp}
559 </LISTING>
560 For example:
561 <LISTING>
562 a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}
563 </LISTING>
564 is essentially equivalent to:
565 <LISTING>
566 temp = {}
567 temp[f(k)] = g(y)
568 temp.x = 1 -- or temp["x"] = 1
569 temp.y = 3 -- or temp["y"] = 3
570 temp[0] = b+c
571 a = temp
572 </LISTING>
573 An expression like <CODE>{x = 1, y = 4}</CODE> is
574 in fact syntactic sugar for <CODE>{["x"] = 1, ["y"] = 4}</CODE>.
576 <A NAME="functioncall"></A>
577 <H3>4.6.8 - Function Calls</H3>
578 A <A NAME="function call">function call</A> has the following syntax:
579 <LISTING>
580 functioncall ::= var realParams
581 </LISTING>
582 Here, <EM>var</EM> can be any variable (global, local, indexed, etc).
583 If its value has type <EM>function</EM>,
584 then this function is called.
585 Otherwise, the ``function'' tag method is called,
586 having as first parameter the value of <EM>var</EM>,
587 and then the original call parameters.
589 The form:
590 <LISTING>
591 functioncall ::= var '<B>:</B>' name realParams
592 </LISTING>
593 can be used to call ``methods''.
594 A call <CODE>var:name(...)</CODE>
595 is syntactic sugar for
596 <LISTING>
597 var.name(var, ...)
598 </LISTING>
599 except that <CODE>var</CODE> is evaluated only once.
601 <LISTING>
602 realParams ::= '<B>(</B>' [explist1] '<B>)</B>'
603 realParams ::= tableconstructor
604 explist1 ::= exp1 {'<B>,</B>' exp1}
605 </LISTING>
606 All argument expressions are evaluated before the call.
607 A call of the form <CODE>f{...}</CODE> is syntactic sugar for
608 <CODE>f({...})</CODE>, that is,
609 the parameter list is a single new table.
611 Because a function can return any number of results
612 (see Section&nbsp;<A HREF="#return">4.5.3</A>),
613 the number of results must be adjusted before used.
614 If the function is called as a statement (see Section&nbsp;<A HREF="#funcstat">4.5.4</A>),
615 then its return list is adjusted to&nbsp;0,
616 thus discarding all returned values.
617 If the function is called in a place that needs a single value
618 (syntactically denoted by the non-terminal <EM>exp1</EM>),
619 then its return list is adjusted to&nbsp;1,
620 thus discarding all returned values but the first one.
621 If the function is called in a place that can hold many values
622 (syntactically denoted by the non-terminal <EM>exp</EM>),
623 then no adjustment is made.
626 <A NAME="func-def"></A>
627 <A NAME="4.7"></A>
628 <H2>4.7 - Function Definitions</H2>
630 Functions in Lua can be defined anywhere in the global level of a chunk.
631 The syntax for function definition is:
632 <LISTING>
633 function ::= <B>function</B> var '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
634 </LISTING>
636 When Lua pre-compiles a chunk,
637 all its function bodies are pre-compiled, too.
638 Then, when Lua ``executes'' the function definition,
639 its body is stored, with type <EM>function</EM>,
640 into the variable <CODE>var</CODE>.
641 It is in this sense that
642 a function definition is an assignment to a global variable.
644 Parameters act as local variables,
645 initialized with the argument values.
646 <LISTING>
647 parlist1 ::= '<B>...</B>'
648 parlist1 ::= name {'<B>,</B>' name} ['<B>,</B>' '<B>...</B>']
649 </LISTING>
650 <A NAME="vararg"></A>
652 When a function is called,
653 the list of <A NAME="arguments">arguments</A> is adjusted to
654 the length of the list of parameters (see Section&nbsp;<A HREF="#adjust">4.4</A>),
655 unless the function is a <A NAME="vararg"><EM>vararg</EM></A> function,
656 indicated by the dots (...) at the end of its parameter list.
657 A vararg function does not adjust its argument list;
658 instead, it collects any extra arguments in an implicit parameter,
659 called <A NAME="arg"><EM>arg</EM></A>.
660 This parameter is always initialized as a table,
661 with a field <CODE>n</CODE> with the number of extra arguments,
662 and the extra arguments at positions 1, 2, ...
664 As an example, suppose definitions like:
665 <LISTING>
666 function f(a, b) end
667 function g(a, b, ...) end
668 </LISTING>
669 Then, we have the following mapping from arguments to parameters:
670 <LISTING>
671 CALL PARAMETERS
673 f(3) a=3, b=nil
674 f(3, 4) a=3, b=4
675 f(3, 4, 5) a=3, b=4
677 g(3) a=3, b=nil, arg={n=0}
678 g(3, 4) a=3, b=4, arg={n=0}
679 g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
680 </LISTING>
682 Results are returned using the <CODE>return</CODE> statement (see Section&nbsp;<A HREF="#return">4.5.3</A>).
683 If control reaches the end of a function without a return instruction,
684 then the function returns with no results.
686 There is a special syntax for defining <A NAME="methods">methods</A>,
687 that is, functions that have an extra parameter <A NAME="self"><EM>self</EM></A>.
688 <LISTING>
689 function ::= <B>function</B> var '<B>:</B>' name '<B>(</B>' [parlist1] '<B>)</B>' block <B>end</B>
690 </LISTING>
691 Thus, a declaration like
692 <LISTING>
693 function v:f (...)
696 </LISTING>
697 is equivalent to
698 <LISTING>
699 function v.f (self, ...)
702 </LISTING>
703 that is, the function gets an extra formal parameter called <CODE>self</CODE>.
704 Notice that
705 the variable <CODE>v</CODE> must have been
706 previously initialized with a table value.
709 <A NAME="tag-method"></A>
710 <A NAME="4.8"></A>
711 <H2>4.8 - Tag Methods</H2>
713 Lua provides a powerful mechanism to extend its semantics,
714 called <A NAME="Tag Methods"><EM>Tag Methods</EM></A>.
715 A tag method (TM) is a programmer-defined function
716 that can be called at many key points of the evaluation of a program,
717 allowing a programmer to change the standard Lua behavior at these points.
718 Each of these points is called an <A NAME="event"><EM>event</EM></A>.
720 The tag method called for any specific event is selected
721 according to the tag of the values involved
722 in the event (see Section&nbsp;<A HREF="#TypesSec">3</A>).
723 The function <A NAME="settagmethod"><TT>settagmethod</TT></A> changes the tag method
724 associated with a given pair <EM>&lt;tag, event&gt;</EM>.
725 Its first parameter is the tag, the second the event name
726 (a string, see below),
727 and the third parameter is the new method (a function),
728 or <B>nil</B> to restore the default behavior.
729 The function returns the previous tag method.
730 Another function, <A NAME="gettagmethod"><TT>gettagmethod</TT></A>,
731 receives a tag and an event name and returns the
732 current method associated with the pair.
734 Tag methods are called in the following events,
735 identified by the given names.
736 The semantics of tag methods is better explained by a Lua function
737 describing the behavior of the interpreter at each event.
738 The function not only shows when a tag method is called,
739 but also its arguments, its results and the default behavior.
740 Please notice that the code shown here is only illustrative;
741 the real behavior is hard coded in the interpreter,
742 and it is much more efficient than this simulation.
743 All functions used in these descriptions
744 (<CODE>rawgetglobal</CODE>, <CODE>tonumber</CODE>, <CODE>call</CODE>, etc)
745 are described in Section&nbsp;<A HREF="#predefined">6.1</A>.
747 <DL>
749 <DT><B>``add'':</B><DD><A NAME="add event"></A>
750 called when a <CODE>+</CODE> operation is applied to non numerical operands.
752 The function <CODE>getbinmethod</CODE> defines how Lua chooses a tag method
753 for a binary operation.
754 First Lua tries the first operand.
755 If its tag does not define a tag method for the operation,
756 then Lua tries the second operand.
757 If it also fails, then it gets a tag method from tag&nbsp;0:
758 <LISTING>
759 function getbinmethod (op1, op2, event)
760 return gettagmethod(tag(op1), event) or
761 gettagmethod(tag(op2), event) or
762 gettagmethod(0, event)
764 </LISTING>
765 <LISTING>
766 function add_event (op1, op2)
767 local o1, o2 = tonumber(op1), tonumber(op2)
768 if o1 and o2 then -- both operands are numeric
769 return o1+o2 -- '+' here is the primitive 'add'
770 else -- at least one of the operands is not numeric.
771 local tm = getbinmethod(op1, op2, "add")
772 if tm then
773 -- call the method with both operands and an extra
774 -- argument with the event name
775 return tm(op1, op2, "add")
776 else -- no tag method available: Default behavior
777 error("unexpected type at arithmetic operation")
781 </LISTING>
783 <DT><B>``sub'':</B><DD><A NAME="sub event"></A>
784 called when a <CODE>-</CODE> operation is applied to non numerical operands.
785 Behavior similar to <CODE>"add"</CODE> event.
787 <DT><B>``mul'':</B><DD><A NAME="mul event"></A>
788 called when a <CODE>*</CODE> operation is applied to non numerical operands.
789 Behavior similar to <CODE>"add"</CODE> event.
791 <DT><B>``div'':</B><DD><A NAME="div event"></A>
792 called when a <CODE>/</CODE> operation is applied to non numerical operands.
793 Behavior similar to <CODE>"add"</CODE> event.
795 <DT><B>``pow'':</B><DD><A NAME="pow event"></A>
796 called when a <CODE>^</CODE> operation is applied.
797 <LISTING>
798 function pow_event (op1, op2)
799 local tm = getbinmethod(op1, op2, "pow")
800 if tm then
801 -- call the method with both operands and an extra
802 -- argument with the event name
803 return tm(op1, op2, "pow")
804 else -- no tag method available: Default behavior
805 error("unexpected type at arithmetic operation")
808 </LISTING>
810 <DT><B>``unm'':</B><DD><A NAME="unm event"></A>
811 called when an unary <CODE>-</CODE> operation is applied to a non numerical operand.
812 <LISTING>
813 function unm_event (op)
814 local o = tonumber(op)
815 if o then -- operand is numeric
816 return -o -- '-' here is the primitive 'unm'
817 else -- the operand is not numeric.
818 -- Try to get a tag method from the operand;
819 -- if it does not have one, try a "global" one (tag 0)
820 local tm = gettagmethod(tag(op), "unm") or
821 gettagmethod(0, "unm")
822 if tm then
823 -- call the method with the operand, nil, and an extra
824 -- argument with the event name
825 return tm(op, nil, "unm")
826 else -- no tag method available: Default behavior
827 error("unexpected type at arithmetic operation")
831 </LISTING>
833 <DT><B>``lt'':</B><DD><A NAME="lt event"></A>
834 called when a <CODE>&lt;</CODE> operation is applied to non numerical
835 or non string operands.
836 <LISTING>
837 function lt_event (op1, op2)
838 if type(op1) == "number" and type(op2) == "number" then
839 return op1 &lt; op2 -- numeric comparison
840 elseif type(op1) == "string" and type(op2) == "string" then
841 return op1 &lt; op2 -- lexicographic comparison
842 else
843 local tm = getbinmethod(op1, op2, "lt")
844 if tm then
845 return tm(op1, op2, "lt")
846 else
847 error("unexpected type at comparison");
851 </LISTING>
853 <DT><B>``gt'':</B><DD><A NAME="gt event"></A>
854 called when a <CODE>&gt;</CODE> operation is applied to non numerical
855 or non string operands.
856 Behavior similar to <CODE>"lt"</CODE> event.
858 <DT><B>``le'':</B><DD><A NAME="le event"></A>
859 called when a <CODE>&lt;=</CODE> operation is applied to non numerical
860 or non string operands.
861 Behavior similar to <CODE>"lt"</CODE> event.
863 <DT><B>``ge'':</B><DD><A NAME="ge event"></A>
864 called when a <CODE>&gt;=</CODE> operation is applied to non numerical
865 or non string operands.
866 Behavior similar to <CODE>"lt"</CODE> event.
868 <DT><B>``concat'':</B><DD><A NAME="concatenation event"></A>
869 called when a concatenation is applied to non string operands.
870 <LISTING>
871 function concat_event (op1, op2)
872 if (type(op1) == "string" or type(op1) == "number") and
873 (type(op2) == "string" or type(op2) == "number") then
874 return op1..op2 -- primitive string concatenation
875 else
876 local tm = getbinmethod(op1, op2, "concat")
877 if tm then
878 return tm(op1, op2, "concat")
879 else
880 error("unexpected type for concatenation")
884 </LISTING>
886 <DT><B>``index'':</B><DD><A NAME="index event"></A>
887 called when Lua tries to retrieve the value of an index
888 not present in a table.
889 See event <CODE>"gettable"</CODE> for its semantics.
891 <DT><B>``getglobal'':</B><DD><A NAME="getglobal event"></A>
892 called whenever Lua accesses a global variable.
893 This method can only be set for <B>nil</B> and for tags
894 created by <CODE>newtag</CODE>.
895 <LISTING>
896 function getglobal (varname)
897 local value = rawgetglobal(varname)
898 local tm = gettagmethod(tag(value), "getglobal")
899 if not tm then
900 return value
901 else
902 return tm(varname, value)
905 </LISTING>
906 Notice: the function <CODE>getglobal</CODE> is pre-defined in Lua (see Section&nbsp;<A HREF="#predefined">6.1</A>).
908 <DT><B>``setglobal'':</B><DD><A NAME="setglobal event"></A>
909 called whenever Lua assigns to a global variable.
910 This method cannot be set for numbers, strings, and tables and
911 userdata with default tags.
912 <LISTING>
913 function setglobal (varname, newvalue)
914 local oldvalue = rawgetglobal(varname)
915 local tm = gettagmethod(tag(oldvalue), "setglobal")
916 if not tm then
917 return rawsetglobal(varname, newvalue)
918 else
919 return tm(varname, oldvalue, newvalue)
922 </LISTING>
923 Notice: the function <CODE>setglobal</CODE> is pre-defined in Lua (see Section&nbsp;<A HREF="#predefined">6.1</A>).
925 <DT><B>``gettable'':</B><DD><A NAME="gettable event"></A>
926 called whenever Lua accesses an indexed variable.
927 This method cannot be set for tables with default tag.
928 <LISTING>
929 function gettable_event (table, index)
930 local tm = gettagmethod(tag(table), "gettable")
931 if tm then
932 return tm(table, index)
933 elseif type(table) ~= "table" then
934 error("indexed expression not a table");
935 else
936 local v = rawgettable(table, index)
937 tm = gettagmethod(tag(table), "index")
938 if (v == nil) and tm then
939 return tm(table, index)
940 else
941 return v
945 </LISTING>
947 <DT><B>``settable'':</B><DD><A NAME="settable event"></A>
948 called when Lua assigns to an indexed variable.
949 This method cannot be set for tables with default tag.
950 <LISTING>
951 function settable_event (table, index, value)
952 local tm = gettagmethod(tag(table), "settable")
953 if tm then
954 tm(table, index, value)
955 elseif type(table) ~= "table" then
956 error("indexed expression not a table")
957 else
958 rawsettable(table, index, value)
961 </LISTING>
963 <DT><B>``function'':</B><DD><A NAME="function event"></A>
964 called when Lua tries to call a non function value.
965 <LISTING>
966 function function_event (func, ...)
967 if type(func) == "function" then
968 return call(func, arg)
969 else
970 local tm = gettagmethod(tag(func), "function")
971 if tm then
972 local i = arg.n
973 while i &gt; 0 do
974 arg[i+1] = arg[i]
975 i = i-1
977 arg.n = arg.n+1
978 arg[1] = func
979 return call(tm, arg)
980 else
981 error("call expression not a function")
985 </LISTING>
987 <DT><B>``gc'':</B><DD><A NAME="gc event"></A>
988 called when Lua is garbage collecting an object.
989 This method cannot be set for strings, numbers, functions,
990 and userdata with default tag.
991 For each object to be collected,
992 Lua does the equivalent of the following function:
993 <LISTING>
994 function gc_event (obj)
995 local tm = gettagmethod(tag(obj), "gc")
996 if tm then
997 tm(obj)
1000 </LISTING>
1001 Moreover, at the end of a garbage collection cycle,
1002 Lua does the equivalent of the call <CODE>gc_event(nil)</CODE>.
1004 </DL>
1008 <A NAME="error"></A>
1009 <A NAME="4.9"></A>
1010 <H2>4.9 - Error Handling</H2>
1012 Because Lua is an extension language,
1013 all Lua actions start from C code calling a function from the Lua library.
1014 Whenever an error occurs during Lua compilation or execution,
1015 the <A NAME="error method"><EM>error method</EM></A> is called,
1016 and then the corresponding function from the library
1017 (<CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>, or <CODE>lua_callfunction</CODE>)
1018 is terminated returning an error condition.
1020 The only argument to the error method is a string
1021 describing the error.
1022 The default method prints this message in <CODE>stderr</CODE>.
1023 If needed, it is possible to change the error method with the
1024 function <CODE>seterrormethod</CODE>,
1025 which gets the new error handler as its only parameter
1026 (see Section&nbsp;<A HREF="#pdf-seterrormethod">6.1</A>).
1027 The standard I/O library uses this facility to redefine the error method,
1028 using the debug facilities (see Section&nbsp;<A HREF="#debugI">7</A>),
1029 in order to print some extra information,
1030 like the call stack.
1032 To provide more information about errors,
1033 Lua programs should include the compilation pragma <CODE>$debug</CODE>.
1034 <A NAME="pragma"></A>
1035 <A NAME="debug pragma"></A>
1036 When an error occurs in a program compiled with this option,
1037 the I/O error routine is able to print the number of the
1038 lines where the calls (and the error) were made.
1040 Lua code can explicitly generate an error by calling the built-in
1041 function <CODE>error</CODE> (see Section&nbsp;<A HREF="#pdf-error">6.1</A>).
1044 <!-- ====================================================================== -->
1045 <HR>
1046 <A NAME="5."></A>
1047 <H1>5 - The Application Program Interface</H1>
1049 This section describes the API for Lua, that is,
1050 the set of C functions available to the host program to communicate
1051 with the Lua library.
1052 The API functions can be classified in the following categories:
1053 <OL>
1054 <LI>exchanging values between C and Lua;
1055 <LI>executing Lua code;
1056 <LI>manipulating (reading and writing) Lua objects;
1057 <LI>calling Lua functions;
1058 <LI>C functions to be called by Lua;
1059 <LI>manipulating references to Lua Objects.
1060 </OL>
1061 All API functions and related types and constants
1062 are declared in the header file <CODE>lua.h</CODE>.
1064 <A NAME="valuesCLua"></A>
1065 <A NAME="5.1"></A>
1066 <H2>5.1 - Exchanging Values between C and Lua</H2>
1067 Because Lua has no static type system,
1068 all values passed between Lua and C have type
1069 <CODE>lua_Object</CODE><A NAME="lua_Object"></A>,
1070 which works like an abstract type in C that can hold any Lua value.
1071 Values of type <CODE>lua_Object</CODE> have no meaning outside Lua;
1072 for instance,
1073 the comparison of two <CODE>lua_Object's</CODE> is undefined.
1075 To check the type of a <CODE>lua_Object</CODE>,
1076 the following functions are available:
1077 <A NAME="lua_isnil"></A><A NAME="lua_isnumber"></A><A NAME="lua_isstring"></A>
1078 <A NAME="lua_istable"></A><A NAME="lua_iscfunction"></A><A NAME="lua_isuserdata"></A>
1079 <A NAME="lua_isfunction"></A>
1080 <LISTING>
1081 int lua_isnil (lua_Object object);
1082 int lua_isnumber (lua_Object object);
1083 int lua_isstring (lua_Object object);
1084 int lua_istable (lua_Object object);
1085 int lua_isfunction (lua_Object object);
1086 int lua_iscfunction (lua_Object object);
1087 int lua_isuserdata (lua_Object object);
1088 </LISTING>
1089 All macros return 1 if the object is compatible with the given type,
1090 and 0 otherwise.
1091 The function <CODE>lua_isnumber</CODE> accepts numbers and numerical strings,
1092 whereas
1093 <CODE>lua_isstring</CODE> accepts strings and numbers (see Section&nbsp;<A HREF="#coercion">4.3</A>),
1094 and <CODE>lua_isfunction</CODE> accepts Lua and C functions.
1096 To check the tag of a <CODE>lua_Object</CODE>,
1097 the following function is available:
1098 <A NAME="lua_tag"></A>
1099 <LISTING>
1100 int lua_tag (lua_Object object);
1101 </LISTING>
1103 To translate a value from type <CODE>lua_Object</CODE> to a specific C type,
1104 the programmer can use:
1105 <A NAME="lua_getnumber"></A><A NAME="lua_getstring"></A>
1106 <A NAME="lua_getcfunction"></A><A NAME="lua_getuserdata"></A>
1107 <LISTING>
1108 float lua_getnumber (lua_Object object);
1109 char *lua_getstring (lua_Object object);
1110 lua_CFunction lua_getcfunction (lua_Object object);
1111 void *lua_getuserdata (lua_Object object);
1112 </LISTING>
1114 <CODE>lua_getnumber</CODE> converts a <CODE>lua_Object</CODE> to a floating-point number.
1115 This <CODE>lua_Object</CODE> must be a number or a string convertible to number
1116 (see Section&nbsp;<A HREF="#coercion">4.3</A>); otherwise, the function returns&nbsp;0.
1118 <CODE>lua_getstring</CODE> converts a <CODE>lua_Object</CODE> to a string (<CODE>char*</CODE>).
1119 This <CODE>lua_Object</CODE> must be a string or a number;
1120 otherwise, the function returns&nbsp;0 (the <CODE>NULL</CODE> pointer).
1121 This function does not create a new string,
1122 but returns a pointer to a string inside the Lua environment.
1123 Because Lua has garbage collection,
1124 there is no guarantee that such pointer will be valid after the block ends
1125 (see below).
1127 <CODE>lua_getcfunction</CODE> converts a <CODE>lua_Object</CODE> to a C function.
1128 This <CODE>lua_Object</CODE> must have type <EM>CFunction</EM>;
1129 otherwise, the function returns 0 (the <CODE>NULL</CODE> pointer).
1130 The type <CODE>lua_CFunction</CODE> is explained in Section&nbsp;<A HREF="#LuacallC">5.5</A>.
1132 <CODE>lua_getuserdata</CODE> converts a <CODE>lua_Object</CODE> to <CODE>void*</CODE>.
1133 This <CODE>lua_Object</CODE> must have type <EM>userdata</EM>;
1134 otherwise, the function returns 0 (the <CODE>NULL</CODE> pointer).
1136 Because Lua has automatic memory management and garbage collection,
1137 a <CODE>lua_Object</CODE> has a limited scope,
1138 and is only valid inside the <EM>block</EM> where it was created.
1139 A C function called from Lua is a block,
1140 and its parameters are valid only until its end.
1141 It is good programming practice to convert Lua objects to C values
1142 as soon as they are available,
1143 and never to store <CODE>lua_Object</CODE>s in C global variables.
1145 A garbage collection cycle can be forced by:
1146 <A NAME="lua_collectgarbage"></A>
1147 <LISTING>
1148 long lua_collectgarbage (long limit);
1149 </LISTING>
1150 This function returns the number of objects collected.
1151 The argument <CODE>limit</CODE> makes the next cycle occur only
1152 when that number of new objects have been created.
1153 If <CODE>limit</CODE>=0, then Lua uses an adaptable heuristics to set this limit.
1156 All communication between Lua and C is done through two
1157 abstract data types, called <A NAME="lua2C"><EM>lua2C</EM></A> and <A NAME="C2lua"><EM>C2lua</EM></A>.
1158 The first one, as the name implies, is used to pass values
1159 from Lua to C: parameters when Lua calls C and results when C calls Lua.
1160 The structure C2lua is used in the reverse direction:
1161 parameters when C calls Lua and results when Lua calls C.
1163 The structure lua2C is an abstract array,
1164 which can be indexed with the function:
1165 <A NAME="lua_lua2C"></A>
1166 <LISTING>
1167 lua_Object lua_lua2C (int number);
1168 </LISTING>
1169 where <CODE>number</CODE> starts with 1.
1170 When called with a number larger than the array size,
1171 this function returns <CODE>LUA_NOOBJECT</CODE><A NAME="LUA_NOOBJECT"></A>.
1172 In this way, it is possible to write C functions that receive
1173 a variable number of parameters,
1174 and to call Lua functions that return a variable number of results.
1175 Notice that the structure lua2C cannot be directly modified by C code.
1177 The second structure, C2lua, is a stack.
1178 Pushing elements into this stack
1179 is done with the following functions:
1180 <A NAME="lua_pushnumber"></A><A NAME="lua_pushstring"></A>
1181 <A NAME="lua_pushcfunction"></A><A NAME="lua_pushusertag"></A>
1182 <A NAME="lua_pushnil"></A><A NAME="lua_pushobject"></A>
1183 <A NAME="pushing"></A>
1184 <A NAME="lua_pushuserdata"></A>
1185 <LISTING>
1186 void lua_pushnumber (double n);
1187 void lua_pushstring (char *s);
1188 void lua_pushcfunction (lua_CFunction f);
1189 void lua_pushusertag (void *u, int tag);
1190 void lua_pushnil (void);
1191 void lua_pushobject (lua_Object object);
1192 </LISTING>
1193 All of them receive a C value,
1194 convert it to a corresponding <CODE>lua_Object</CODE>,
1195 and leave the result on the top of C2lua.
1196 The function
1197 <A NAME="lua_pop"></A>
1198 <LISTING>
1199 lua_Object lua_pop (void);
1200 </LISTING>
1201 returns a reference to the object at the top of the C2lua stack,
1202 and pops it.
1204 As a general rule, all API functions pop from the stack
1205 all elements that they use.
1207 Because userdata are objects,
1208 the function <CODE>lua_pushusertag</CODE> may create a new userdata.
1209 If Lua has a userdata with the given value (<CODE>void*</CODE>) and tag,
1210 that userdata is pushed.
1211 Otherwise, a new userdata is created, with the given value and tag.
1212 If this function is called with
1213 <CODE>tag</CODE>=<CODE>LUA_ANYTAG</CODE><A NAME="LUA_ANYTAG"></A>,
1214 then Lua will try to find any userdata with the given value,
1215 no matter its tag.
1216 If there is no userdata with that value, then a new one is created,
1217 with tag=0.
1219 Userdata can have different tags,
1220 whose semantics are only known to the host program.
1221 Tags are created with the function:
1222 <A NAME="lua_newtag"></A>
1223 <LISTING>
1224 int lua_newtag (void);
1225 </LISTING>
1226 The function <CODE>lua_settag</CODE> changes the tag of
1227 the object on the top of C2lua (and pops it);
1228 the object must be a userdata or a table.
1229 <A NAME="lua_settag"></A>
1230 <LISTING>
1231 void lua_settag (int tag);
1232 </LISTING>
1233 <CODE>tag</CODE> must be a value created with <CODE>lua_newtag</CODE>.
1235 When C code calls Lua repeatedly, as in a loop,
1236 objects returned by these calls can accumulate,
1237 and may cause a stack overflow.
1238 To avoid this,
1239 nested blocks can be defined with the functions:
1240 <LISTING>
1241 void lua_beginblock (void);
1242 void lua_endblock (void);
1243 </LISTING>
1244 After the end of the block,
1245 all <CODE>lua_Object</CODE>'s created inside it are released.
1246 The use of explicit nested blocks is strongly encouraged.
1248 <A NAME="5.2"></A>
1249 <H2>5.2 - Executing Lua Code</H2>
1250 A host program can execute Lua chunks written in a file or in a string
1251 using the following functions:
1252 <A NAME="lua_dofile"></A><A NAME="lua_dostring"></A>
1253 <LISTING>
1254 int lua_dofile (char *filename);
1255 int lua_dostring (char *string);
1256 </LISTING>
1257 Both functions return an error code:
1258 0, in case of success; non zero, in case of errors.
1259 More specifically, <CODE>lua_dofile</CODE> returns 2 if for any reason
1260 it could not open the file.
1261 The function <CODE>lua_dofile</CODE>, if called with argument <CODE>NULL</CODE>,
1262 executes the <CODE>stdin</CODE> stream.
1263 Function <CODE>lua_dofile</CODE> is also able to execute pre-compiled chunks.
1264 It automatically detects whether the file is text or binary,
1265 and loads it accordingly (see program <A NAME="luac"><TT>luac</TT></A>).
1267 These functions return, in structure lua2C,
1268 any values eventually returned by the chunks.
1269 They also empty the stack C2lua.
1272 <A NAME="5.3"></A>
1273 <H2>5.3 - Manipulating Lua Objects</H2>
1274 To read the value of any global Lua variable,
1275 one uses the function:
1276 <A NAME="lua_getglobal"></A>
1277 <LISTING>
1278 lua_Object lua_getglobal (char *varname);
1279 </LISTING>
1280 As in Lua, this function may trigger a tag method.
1281 To read the real value of any global variable,
1282 without invoking any tag method,
1283 this function has a <EM>raw</EM> version:
1284 <A NAME="lua_rawgetglobal"></A>
1285 <LISTING>
1286 lua_Object lua_rawgetglobal (char *varname);
1287 </LISTING>
1289 To store a value previously pushed onto C2lua in a global variable,
1290 there is the function:
1291 <A NAME="lua_setglobal"></A>
1292 <LISTING>
1293 void lua_setglobal (char *varname);
1294 </LISTING>
1295 As in Lua, this function may trigger a tag method.
1296 To set the real value of any global variable,
1297 without invoking any tag method,
1298 this function has a <EM>raw</EM> version:
1299 <A NAME="lua_rawgetglobal"></A>
1300 <LISTING>
1301 void lua_rawsetglobal (char *varname);
1302 </LISTING>
1304 Tables can also be manipulated via the API.
1305 The function
1306 <A NAME="lua_gettable"></A>
1307 <LISTING>
1308 lua_Object lua_gettable (void);
1309 </LISTING>
1310 pops from the stack C2lua a table and an index,
1311 and returns the contents of the table at that index.
1312 As in Lua, this operation may trigger a tag method.
1313 To get the real value of any table index,
1314 without invoking any tag method,
1315 this function has a <EM>raw</EM> version:
1316 <A NAME="lua_rawgetglobal"></A>
1317 <LISTING>
1318 lua_Object lua_rawgettable (void);
1319 </LISTING>
1321 To store a value in an index,
1322 the program must push the table, the index,
1323 and the value onto C2lua,
1324 and then call the function:
1325 <A NAME="lua_settable"></A>
1326 <LISTING>
1327 void lua_settable (void);
1328 </LISTING>
1329 Again, the tag method for ``settable'' may be called.
1330 To set the real value of any table index,
1331 without invoking any tag method,
1332 this function has a <EM>raw</EM> version:
1333 <A NAME="lua_rawsettable"></A>
1334 <LISTING>
1335 void lua_rawsettable (void);
1336 </LISTING>
1338 Finally, the function
1339 <A NAME="lua_createtable"></A>
1340 <LISTING>
1341 lua_Object lua_createtable (void);
1342 </LISTING>
1343 creates and returns a new, empty table.
1346 <A NAME="5.4"></A>
1347 <H2>5.4 - Calling Lua Functions</H2>
1348 Functions defined in Lua by a chunk executed with
1349 <CODE>dofile</CODE> or <CODE>dostring</CODE> can be called from the host program.
1350 This is done using the following protocol:
1351 first, the arguments to the function are pushed onto C2lua
1352 (see Section&nbsp;<A HREF="#pushing">5.1</A>), in direct order, i.e., the first argument is pushed first.
1354 Then, the function is called using
1355 <A NAME="lua_callfunction"></A>
1356 <LISTING>
1357 int lua_callfunction (lua_Object function);
1358 </LISTING>
1359 This function returns an error code:
1360 0, in case of success; non zero, in case of errors.
1361 Finally, the results (a Lua function may return many values)
1362 are returned in structure lua2C,
1363 and can be retrieved with the macro <CODE>lua_getresult</CODE>,
1364 <A NAME="lua_getresult"></A>
1365 which is just another name to the function <CODE>lua_lua2C</CODE>.
1366 Notice that the function <CODE>lua_callfunction</CODE>
1367 pops all elements from the C2lua stack.
1369 The following example shows how a C program may do the
1370 equivalent to the Lua code:
1371 <LISTING>
1372 a = f("how", t.x, 4)
1373 </LISTING>
1374 <LISTING>
1375 lua_pushstring("how"); /* 1st argument */
1376 lua_pushobject(lua_getglobal("t")); /* push value of global 't' */
1377 lua_pushstring("x"); /* push the string 'x' */
1378 lua_pushobject(lua_gettable()); /* push result of t.x (= t['x']) */
1379 lua_pushnumber(4); /* 3th argument */
1380 lua_callfunction(lua_getglobal("f")); /* call Lua function */
1381 lua_pushobject(lua_getresult(1)); /* push first result of the call */
1382 lua_setglobal("a"); /* sets global variable 'a' */
1383 </LISTING>
1385 Some special Lua functions have exclusive interfaces.
1386 A C function can generate a Lua error calling the function
1387 <A NAME="lua_error"></A>
1388 <LISTING>
1389 void lua_error (char *message);
1390 </LISTING>
1391 This function never returns.
1392 If the C function has been called from Lua,
1393 then the corresponding Lua execution terminates,
1394 as if an error had occurred inside Lua code.
1395 Otherwise, the whole program terminates with a call to <CODE>exit(1)</CODE>.
1397 The error handler method (see Section&nbsp;<A HREF="#error">4.9</A>) can be changed with:
1398 <A NAME="lua_seterrormethod"></A>
1399 <LISTING>
1400 lua_Object lua_seterrormethod (void);
1401 </LISTING>
1402 This function sets the object at the top of C2lua
1403 as the new error method,
1404 and returns the old error method value.
1406 Tag methods can be changed with:
1407 <A NAME="lua_settagmethod"></A>
1408 <LISTING>
1409 lua_Object lua_settagmethod (int tag, char *event);
1410 </LISTING>
1411 The first parameter is the tag,
1412 the second is the event name (see Section&nbsp;<A HREF="#tag-method">4.8</A>);
1413 the new method is pushed from C2lua.
1414 This function returns a <CODE>lua_Object</CODE>,
1415 which is the old tag method value.
1416 To get just the current value of a tag method,
1417 there is the function
1418 <A NAME="lua_gettagmethod"></A>
1419 <LISTING>
1420 lua_Object lua_gettagmethod (int tag, char *event);
1421 </LISTING>
1424 <A NAME="LuacallC"></A>
1425 <A NAME="5.5"></A>
1426 <H2>5.5 - C Functions</H2>
1427 To register a C function to Lua,
1428 there is the following macro:
1429 <A NAME="lua_register"></A>
1430 <LISTING>
1431 #define lua_register(n,f) (lua_pushcfunction(f), lua_setglobal(n))
1432 /* char *n; */
1433 /* lua_CFunction f; */
1434 </LISTING>
1435 which receives the name the function will have in Lua,
1436 and a pointer to the function.
1437 This pointer must have type <CODE>lua_CFunction</CODE>,
1438 which is defined as
1439 <A NAME="lua_CFunction"></A>
1440 <LISTING>
1441 typedef void (*lua_CFunction) (void);
1442 </LISTING>
1443 that is, a pointer to a function with no parameters and no results.
1445 In order to communicate properly with Lua,
1446 a C function must follow a protocol,
1447 which defines the way parameters and results are passed.
1449 A C function receives its arguments in structure lua2C;
1450 to access them, it uses the macro <CODE>lua_getparam</CODE>, <A NAME="lua_getparam"></A>
1451 again just another name to <CODE>lua_lua2C</CODE>.
1452 To return values, a C function just pushes them onto the stack C2lua,
1453 in direct order (see Section&nbsp;<A HREF="#valuesCLua">5.1</A>).
1454 Like a Lua function, a C function called by Lua can also return
1455 many results.
1457 For some examples, see files <CODE>strlib.c</CODE>,
1458 <CODE>iolib.c</CODE> and <CODE>mathlib.c</CODE> in Lua distribution.
1460 <A NAME="5.6"></A>
1461 <H2>5.6 - References to Lua Objects</H2>
1463 As noted in Section&nbsp;<A HREF="#LuacallC">5.5</A>, <CODE>lua_Object</CODE>s are volatile.
1464 If the C code needs to keep a <CODE>lua_Object</CODE>
1465 outside block boundaries,
1466 then it must create a <A NAME="reference"><EM>reference</EM></A> to the object.
1467 The routines to manipulate references are the following:
1468 <A NAME="lua_ref"></A><A NAME="lua_getref"></A>
1469 <A NAME="lua_unref"></A>
1470 <LISTING>
1471 int lua_ref (int lock);
1472 lua_Object lua_getref (int ref);
1473 void lua_unref (int ref);
1474 </LISTING>
1475 The function <CODE>lua_ref</CODE> creates a reference
1476 to the object that is on the top of the stack,
1477 and returns this reference.
1478 If <CODE>lock</CODE> is true, the object is <EM>locked</EM>:
1479 this means the object will not be garbage collected.
1480 Notice that an unlocked reference may be garbage collected.
1481 Whenever the referenced object is needed,
1482 a call to <CODE>lua_getref</CODE>
1483 returns a handle to it;
1484 if the object has been collected,
1485 <CODE>lua_getref</CODE> returns <CODE>LUA_NOOBJECT</CODE>.
1487 When a reference is no longer needed,
1488 it can be freed with a call to <CODE>lua_unref</CODE>.
1492 <!-- ====================================================================== -->
1493 <HR>
1494 <A NAME="6."></A>
1495 <H1>6 - Predefined Functions and Libraries</H1>
1497 The set of <A NAME="predefined functions">predefined functions</A> in Lua is small but powerful.
1498 Most of them provide features that allow some degree of
1499 <A NAME="reflexivity">reflexivity</A> in the language.
1500 Some of these features cannot be simulated with the rest of the
1501 language nor with the standard Lua API.
1502 Others are just convenient interfaces to common API functions.
1504 The libraries, on the other hand, provide useful routines
1505 that are implemented directly through the standard API.
1506 Therefore, they are not necessary to the language,
1507 and are provided as separate C modules.
1508 Currently there are three standard libraries:
1509 <UL>
1510 <LI>string manipulation;
1511 <LI>mathematical functions (sin, log, etc);
1512 <LI>input and output (plus some system facilities).
1513 </UL>
1514 In order to have access to these libraries,
1515 the host program must call the functions
1516 <CODE>strlib_open</CODE>, <CODE>mathlib_open</CODE>, and <CODE>iolib_open</CODE>,
1517 declared in <CODE>lualib.h</CODE>.
1520 <A NAME="predefined"></A>
1521 <A NAME="6.1"></A>
1522 <H2>6.1 - Predefined Functions</H2>
1524 <h3> <TT>call (func, arg, [retmode])</TT></h3><A NAME="call"></A>
1525 This function calls function <CODE>func</CODE> with
1526 the arguments given by the table <CODE>arg</CODE>.
1527 The call is equivalent to
1528 <LISTING>
1529 func(arg[1], arg[2], ..., arg[arg.n])
1530 </LISTING>
1531 If <CODE>arg.n</CODE> is not defined,
1532 then Lua stops getting arguments at the first nil value.
1534 If <CODE>retmode</CODE> is absent,
1535 all results from <CODE>func</CODE> are just returned by the call.
1536 If <CODE>retmode</CODE> is equal to <CODE>"pack"</CODE>,
1537 the results are <EM>packed</EM> in a single table.<A NAME="packed results"></A>
1538 That is, <CODE>call</CODE> returns just one table;
1539 at index <CODE>n</CODE>, the table has the total number of results
1540 from the call;
1541 the first result is at index 1, etc.
1542 For instance, the following calls produce the following results:
1543 <LISTING>
1544 a = call(sin, {5}) --&gt; a = 0.0871557 = sin(5)
1545 a = call(max, {1,4,5; n=2}) --&gt; a = 4 (only 1 and 4 are arguments)
1546 t = {x=1}
1547 a = call(next, {t,nil;n=2}, "pack") --&gt; a={"x", 1; n=2}
1548 </LISTING>
1550 <h3> <TT>collectgarbage ([limit])</TT></h3><A NAME="collectgarbage"></A>
1551 Forces a garbage collection cycle.
1552 Returns the number of objects collected.
1553 An optional argument, <CODE>limit</CODE>, is a number that
1554 makes the next cycle occur when that number of new
1555 objects have been created.
1556 If absent, Lua uses an adaptable algorithm to set
1557 this limit.
1558 <CODE>collectgarbage</CODE> is equivalent to
1559 the API function <CODE>lua_collectgarbage</CODE>.
1561 <h3> <TT>dofile (filename)</TT></h3><A NAME="dofile"></A>
1562 This function receives a file name,
1563 opens it, and executes its contents as a Lua chunk,
1564 or as pre-compiled chunks.
1565 When called without arguments,
1566 it executes the contents of the standard input (<CODE>stdin</CODE>).
1567 If there is any error executing the file,
1568 then <CODE>dofile</CODE> returns <B>nil</B>.
1569 Otherwise, it returns the values returned by the chunk,
1570 or a non <B>nil</B> value if the chunk returns no values.
1571 It issues an error when called with a non string argument.
1572 <CODE>dofile</CODE> is equivalent to the API function <CODE>lua_dofile</CODE>.
1574 <h3> <TT>dostring (string [, errmethod])</TT></h3><A NAME="dostring"></A>
1575 This function executes a given string as a Lua chunk.
1576 If there is any error executing the string, it returns <B>nil</B>.
1577 Otherwise, it returns the values returned by the chunk,
1578 or a non <B>nil</B> value if the chunk returns no values.
1579 If provided, <CODE>errmethod</CODE> is temporarily set as the error method,
1580 while <CODE>string</CODE> runs.
1581 As a particular case, if <CODE>errmethod</CODE> is <B>nil</B>,
1582 no error messages will be issued during the execution of the string.
1584 <A NAME="pdf-newtag"></A>
1585 <h3> <TT>newtag ()</TT></h3><A NAME="newtag"></A>
1586 Returns a new tag.
1587 <CODE>newtag</CODE> is equivalent to the API function <CODE>lua_newtag</CODE>.
1589 <h3> <TT>next (table, index)</TT></h3><A NAME="next"></A>
1590 This function allows a program to traverse all fields of a table.
1591 Its first argument is a table and its second argument
1592 is an index in this table.
1593 It returns the next index of the table and the
1594 value associated with the index.
1595 When called with <B>nil</B> as its second argument,
1596 the function returns the first index
1597 of the table (and its associated value).
1598 When called with the last index, or with <B>nil</B> in an empty table,
1599 it returns <B>nil</B>.
1601 In Lua there is no declaration of fields;
1602 semantically, there is no difference between a
1603 field not present in a table or a field with value <B>nil</B>.
1604 Therefore, the function only considers fields with non <B>nil</B> values.
1605 The order in which the indices are enumerated is not specified,
1606 <EM>not even for numeric indices</EM>
1607 (to traverse a table in numeric order,
1608 use a counter).
1609 If the table is modified in any way during a traversal,
1610 the semantics of <CODE>next</CODE> is undefined.
1612 This function cannot be written with the standard API.
1614 <h3> <TT>nextvar (name)</TT></h3><A NAME="nextvar"></A>
1615 This function is similar to the function <CODE>next</CODE>,
1616 but iterates over the global variables.
1617 Its single argument is the name of a global variable,
1618 or <B>nil</B> to get a first name.
1619 Similarly to <CODE>next</CODE>, it returns the name of another variable
1620 and its value,
1621 or <B>nil</B> if there are no more variables.
1622 There can be no assignments to global variables during the traversal;
1623 otherwise the semantics of <CODE>nextvar</CODE> is undefined.
1625 This function cannot be written with the standard API.
1627 <h3> <TT>tostring (e)</TT></h3><A NAME="tostring"></A>
1628 This function receives an argument of any type and
1629 converts it to a string in a reasonable format.
1631 <h3> <TT>print (e1, e2, ...)</TT></h3><A NAME="print"></A>
1632 This function receives any number of arguments,
1633 and prints their values in a reasonable format.
1634 Each value is printed in a new line.
1635 This function is not intended for formatted output,
1636 but as a quick way to show a value,
1637 for instance for error messages or debugging.
1638 See Section&nbsp;<A HREF="#libio">6.4</A> for functions for formatted output.
1640 <h3> <TT>tonumber (e)</TT></h3><A NAME="tonumber"></A>
1641 This function receives one argument,
1642 and tries to convert it to a number.
1643 If the argument is already a number or a string convertible
1644 to a number (see Section&nbsp;<A HREF="#coercion">4.3</A>), then it returns that number;
1645 otherwise, it returns <B>nil</B>.
1647 <A NAME="pdf-type"></A>
1648 <h3> <TT>type (v)</TT></h3><A NAME="type"></A>
1649 This function allows Lua to test the type of a value.
1650 It receives one argument, and returns its type, coded as a string.
1651 The possible results of this function are
1652 <CODE>"nil"</CODE> (a string, not the value <B>nil</B>),
1653 <CODE>"number"</CODE>,
1654 <CODE>"string"</CODE>,
1655 <CODE>"table"</CODE>,
1656 <CODE>"function"</CODE>,
1657 and <CODE>"userdata"</CODE>.
1658 <CODE>type</CODE> is equivalent to the API function <CODE>lua_type</CODE>.
1660 <h3> <TT>tag (v)</TT></h3><A NAME="tag"></A>
1661 This function allows Lua to test the tag of a value (see Section&nbsp;<A HREF="#TypesSec">3</A>).
1662 It receives one argument, and returns its tag (a number).
1663 <CODE>tag</CODE> is equivalent to the API function <CODE>lua_tag</CODE>.
1665 <h3> <TT>settag (t, tag)</TT></h3><A NAME="settag"></A>
1666 This function sets the tag of a given table (see Section&nbsp;<A HREF="#TypesSec">3</A>).
1667 <CODE>tag</CODE> must be a value created with <CODE>newtag</CODE>
1668 (see Section&nbsp;<A HREF="#pdf-newtag">6.1</A>).
1669 For security reasons,
1670 it is impossible to change the tag of a userdata from Lua.
1672 <h3> <TT>assert (v)</TT></h3><A NAME="assert"></A>
1673 This function issues an <EM>``assertion failed!''</EM> error
1674 when its argument is <B>nil</B>.
1676 <A NAME="pdf-error"></A>
1677 <h3> <TT>error (message)</TT></h3><A NAME="error"></A>
1678 This function issues an error message and terminates
1679 the last called function from the library
1680 (<CODE>lua_dofile</CODE>, <CODE>lua_dostring</CODE>, or <CODE>lua_callfunction</CODE>).
1681 It never returns.
1682 <CODE>error</CODE> is equivalent to the API function <CODE>lua_error</CODE>.
1684 <h3> <TT>rawgettable (table, index)</TT></h3><A NAME="rawgettable"></A>
1685 Gets the real value of <CODE>table[index]</CODE>,
1686 without invoking any tag method.
1687 <CODE>table</CODE> must be a table,
1688 and <CODE>index</CODE> is any value different from <B>nil</B>.
1690 <h3> <TT>rawsettable (table, index, value)</TT></h3><A NAME="rawsettable"></A>
1691 Sets the real value <CODE>table[index]=value</CODE>,
1692 without invoking any tag method.
1693 <CODE>table</CODE> must be a table,
1694 <CODE>index</CODE> is any value different from <B>nil</B>,
1695 and <CODE>value</CODE> is any Lua value.
1697 <h3> <TT>rawsetglobal (name, value)</TT></h3><A NAME="rawsetglobal"></A>
1698 This function assigns the given value to a global variable.
1699 The string <CODE>name</CODE> does not need to be a syntactically valid variable name.
1700 Therefore, this function can set global variables with strange names like
1701 <CODE>"m v 1"</CODE> or <CODE>34</CODE>.
1702 It returns the value of its second argument.
1704 <h3> <TT>setglobal (name, value)</TT></h3><A NAME="setglobal"></A>
1705 This function assigns the given value to a global variable,
1706 or calls a tag method.
1707 Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
1709 <h3> <TT>rawgetglobal (name)</TT></h3><A NAME="rawgetglobal"></A>
1710 This function retrieves the value of a global variable.
1711 The string <CODE>name</CODE> does not need to be a
1712 syntactically valid variable name.
1714 <h3> <TT>getglobal (name)</TT></h3><A NAME="getglobal"></A>
1715 This function retrieves the value of a global variable,
1716 or calls a tag method.
1717 Its full semantics is explained in Section&nbsp;<A HREF="#tag-method">4.8</A>.
1719 <h3> <TT>seterrormethod (newmethod)</TT></h3>
1720 <A NAME="pdf-seterrormethod"></A>
1722 Sets the error handler (see Section&nbsp;<A HREF="#error">4.9</A>).
1723 <CODE>newmethod</CODE> must be a function or <B>nil</B>,
1724 in which case the error handler does nothing.
1725 Returns the old error handler.
1727 <h3> <TT>settagmethod (tag, event, newmethod)</TT></h3>
1728 <A NAME="settagmethod"></A>
1729 This function sets a new tag method to the given pair <EM>&lt;tag, event&gt;</EM>.
1730 It returns the old method.
1731 If <CODE>newmethod</CODE> is <B>nil</B>,
1732 it restores the default behavior for the given event.
1734 <h3> <TT>gettagmethod (tag, event)</TT></h3>
1735 <A NAME="gettagmethod"></A>
1736 This function returns the current tag method
1737 for a given pair <EM>&lt;tag, event&gt;</EM>.
1740 <A NAME="6.2"></A>
1741 <H2>6.2 - String Manipulation</H2>
1742 This library provides generic functions for string manipulation,
1743 such as finding and extracting substrings and pattern matching.
1744 When indexing a string, the first character is at position&nbsp;1,
1745 not&nbsp;0, as in C.
1747 <h3> <TT>strfind (str, pattern [, init [, plain]])</TT></h3>
1748 <A NAME="strfind"></A>
1749 This function looks for the first <EM>match</EM> of
1750 <CODE>pattern</CODE> in <CODE>str</CODE>.
1751 If it finds one, then it returns the indices on <CODE>str</CODE>
1752 where this occurrence starts and ends;
1753 otherwise, it returns <B>nil</B>.
1754 If the pattern specifies captures,
1755 the captured strings are returned as extra results.
1756 A third optional numerical argument specifies where to start the search;
1757 its default value is 1.
1758 A value of 1 as a fourth optional argument
1759 turns off the pattern matching facilities,
1760 so the function does a plain ``find substring'' operation,
1761 with no characters in <CODE>pattern</CODE> being considered ``magic''.
1763 <h3> <TT>strlen (s)</TT></h3><A NAME="strlen"></A>
1764 Receives a string and returns its length.
1766 <h3> <TT>strsub (s, i [, j])</TT></h3><A NAME="strsub"></A>
1767 Returns another string, which is a substring of <CODE>s</CODE>,
1768 starting at <CODE>i</CODE> and running until <CODE>j</CODE>.
1769 If <CODE>i</CODE> or <CODE>j</CODE> are negative,
1770 they are replaced by the length of the string minus their
1771 absolute value plus 1.
1772 Therefore, -1 points to the last character of <CODE>s</CODE>
1773 and -2 to the previous one.
1774 If <CODE>j</CODE> is absent, it is assumed to be equal to -1
1775 (which is the same as the string length).
1776 In particular,
1777 the call <CODE>strsub(s,1,j)</CODE> returns a prefix of <CODE>s</CODE>
1778 with length <CODE>j</CODE>,
1779 and the call <CODE>strsub(s, -i)</CODE> returns a suffix of <CODE>s</CODE>
1780 with length <CODE>i</CODE>.
1782 <h3> <TT>strlower (s)</TT></h3><A NAME="strlower"></A>
1783 Receives a string and returns a copy of that string with all
1784 upper case letters changed to lower case.
1785 All other characters are left unchanged.
1787 <h3> <TT>strupper (s)</TT></h3><A NAME="strupper"></A>
1788 Receives a string and returns a copy of that string with all
1789 lower case letters changed to upper case.
1790 All other characters are left unchanged.
1792 <h3> <TT>strrep (s, n)</TT></h3><A NAME="strrep"></A>
1793 Returns a string which is the concatenation of <CODE>n</CODE> copies of
1794 the string <CODE>s</CODE>.
1796 <h3> <TT>ascii (s [, i])</TT></h3><A NAME="ascii"></A>
1797 Returns the ASCII code of the character <CODE>s[i]</CODE>.
1798 If <CODE>i</CODE> is absent, then it is assumed to be 1.
1800 <h3> <TT>format (formatstring, e1, e2, ...)</TT></h3><A NAME="format"></A>
1801 <A NAME="format"></A>
1803 This function returns a formated version of its variable number of arguments
1804 following the description given in its first argument (which must be a string).
1805 The format string follows the same rules as the <CODE>printf</CODE> family of
1806 standard C functions.
1807 The only differences are that the options/modifiers
1808 <CODE>*</CODE>, <CODE>l</CODE>, <CODE>L</CODE>, <CODE>n</CODE>, <CODE>p</CODE>,
1809 and <CODE>h</CODE> are not supported,
1810 and there is an extra option, <CODE>q</CODE>.
1811 This option formats a string in a form suitable to be safely read
1812 back by the Lua interpreter;
1813 that is,
1814 the string is written between double quotes,
1815 and all double quotes, returns and backslashes in the string
1816 are correctly escaped when written.
1817 For instance, the call
1818 <LISTING>
1819 format('%q', 'a string with "quotes" and \n new line')
1820 </LISTING>
1821 will produce the string:
1822 <LISTING>
1823 "a string with \"quotes\" and \
1824 new line"
1825 </LISTING>
1827 The options <CODE>c</CODE>, <CODE>d</CODE>, <CODE>E</CODE>, <CODE>e</CODE>, <CODE>f</CODE>,
1828 <CODE>g</CODE> <CODE>i</CODE>, <CODE>o</CODE>, <CODE>u</CODE>, <CODE>X</CODE>, and <CODE>x</CODE> all
1829 expect a number as argument,
1830 whereas <CODE>q</CODE> and <CODE>s</CODE> expect a string.
1831 Note that the <CODE>*</CODE> modifier can be simulated by building
1832 the appropriate format string.
1833 For example, <CODE>"%*g"</CODE> can be simulated with
1834 <CODE>"%"..width.."g"</CODE>.
1836 <h3> <TT>gsub (s, pat, repl [, table] [, n])</TT></h3>
1837 <A NAME="gsub"></A>
1838 Returns a copy of <CODE>s</CODE>,
1839 where all occurrences of the pattern <CODE>pat</CODE> have been
1840 replaced by a replacement string specified by <CODE>repl</CODE>.
1841 This function also returns, as a second value,
1842 the total number of substitutions made.
1844 If <CODE>repl</CODE> is a string, then its value is used for replacement.
1845 Any sequence in <CODE>repl</CODE> of the form <CODE>%n</CODE>
1846 with <CODE>n</CODE> between 1 and 9
1847 stands for the value of the n-th captured substring.
1849 If <CODE>repl</CODE> is a function, then this function is called every time a
1850 match occurs, with the following arguments:
1851 If <CODE>table</CODE> is present, then the first argument is this table
1852 and the second one is a match counter (1 for the first call).
1853 Independently of these two optional arguments,
1854 all captured substrings are passed as arguments,
1855 in order (see below);
1856 If the value returned by this function is a string,
1857 then it is used as the replacement string;
1858 otherwise, the replacement string is the empty string.
1860 A last optional parameter <CODE>n</CODE> limits
1861 the maximum number of substitutions to occur.
1862 For instance, when <CODE>n</CODE> is 1 only the first occurrence of
1863 <CODE>pat</CODE> is replaced.
1865 See some examples below:
1866 <LISTING>
1867 x = gsub("hello world", "(%w%w*)", "%1 %1", 1)
1868 --&gt; x="hello hello world"
1870 x = gsub("home = $HOME, user = $USER", "$(%w%w*)", getenv)
1871 --&gt; x="home = /home/roberto, user = roberto" (for instance)
1873 x = gsub("4+5 = $return 4+5$", "$(.-)%$", dostring)
1874 --&gt; x="4+5 = 9"
1876 function f(t, i, v) return t[v] end
1877 t = {name="lua", version="3.0"}
1878 x = gsub("$name - $version", "$(%w%w*)", f, t)
1879 --&gt; x="lua - 3.0"
1881 t = {"apple", "orange", "lime"}
1882 x = gsub("x and x and x", "x", rawgettable, t)
1883 --&gt; x="apple and orange and lime"
1885 t = {}
1886 dummy, t.n = gsub("first second word", "(%w%w*)", rawsettable, t)
1887 --&gt; t={"first", "second", "word"; n=3}
1888 </LISTING>
1891 <A NAME="pm"></A>
1892 <h3>Patterns</h3>
1894 <H4>Character Class:</H4>
1895 a <A NAME="character class"><EM>character class</EM></A> is used to represent a set of characters.
1896 The following combinations are allowed in describing a character class:
1897 <DL>
1898 <DT><B><EM>x</EM></B><DD> (where <EM>x</EM> is any character not in the list <CODE>()%.[*-?</CODE>)
1899 - represents the character <EM>x</EM> itself.
1900 <DT><B><TT>.</TT></B><DD> - represents all characters.
1901 <DT><B><TT>%a</TT></B><DD> - represents all letters.
1902 <DT><B><TT>%A</TT></B><DD> - represents all non letter characters.
1903 <DT><B><TT>%d</TT></B><DD> - represents all digits.
1904 <DT><B><TT>%D</TT></B><DD> - represents all non digits.
1905 <DT><B><TT>%l</TT></B><DD> - represents all lower case letters.
1906 <DT><B><TT>%L</TT></B><DD> - represents all non lower case letter characters.
1907 <DT><B><TT>%s</TT></B><DD> - represents all space characters.
1908 <DT><B><TT>%S</TT></B><DD> - represents all non space characters.
1909 <DT><B><TT>%u</TT></B><DD> - represents all upper case letters.
1910 <DT><B><TT>%U</TT></B><DD> - represents all non upper case letter characters.
1911 <DT><B><TT>%w</TT></B><DD> - represents all alphanumeric characters.
1912 <DT><B><TT>%W</TT></B><DD> - represents all non alphanumeric characters.
1913 <DT><B><TT>%<EM>x</TT></EM></B><DD> (where <EM>x</EM> is any non alphanumeric character) -
1914 represents the character <EM>x</EM>.
1915 This is the standard way to escape the magic characters <CODE>()%.[*-?</CODE>.
1916 <DT><B><TT>[char-set]</TT></B><DD> -
1917 Represents the class which is the union of all
1918 characters in char-set.
1919 To include a <CODE>]</CODE> in char-set, it must be the first character.
1920 A range of characters may be specified by
1921 separating the end characters of the range with a <CODE>-</CODE>;
1922 e.g., <CODE>A-Z</CODE> specifies the upper case characters.
1923 If <CODE>-</CODE> appears as the first or last character of char-set,
1924 then it represents itself.
1925 All classes <CODE>%</CODE><EM>x</EM> described above can also be used as
1926 components in a char-set.
1927 All other characters in char-set represent themselves.
1928 <DT><B><TT>[^char-set]</TT></B><DD> -
1929 represents the complement of char-set,
1930 where char-set is interpreted as above.
1931 </DL>
1933 <H4>Pattern Item:</H4>
1934 a <A NAME="pattern item"><EM>pattern item</EM></A> may be:
1935 <UL>
1936 <LI>
1937 a single character class,
1938 which matches any single character in the class;
1939 <LI>
1940 a single character class followed by <CODE>*</CODE>,
1941 which matches 0 or more repetitions of characters in the class.
1942 These repetition items will always match the longest possible sequence.
1943 <LI>
1944 a single character class followed by <CODE>-</CODE>,
1945 which also matches 0 or more repetitions of characters in the class.
1946 Unlike <CODE>*</CODE>,
1947 these repetition items will always match the shortest possible sequence.
1948 <LI>
1949 a single character class followed by <CODE>?</CODE>,
1950 which matches 0 or 1 occurrence of a character in the class;
1951 <LI>
1952 <TT>%<EM>n</TT></EM>, for <EM>n</EM> between 1 and 9;
1953 such item matches a sub-string equal to the n-th captured string
1954 (see below);
1955 <LI>
1956 <TT>%b<EM>xy</TT></EM>, where <EM>x</EM> and <EM>y</EM> are two distinct characters;
1957 such item matches strings that start with <EM>x</EM>, end with <EM>y</EM>,
1958 and where the <EM>x</EM> and <EM>y</EM> are <EM>balanced</EM>.
1959 That means that, if one reads the string from left to write,
1960 counting plus 1 for an <EM>x</EM> and minus 1 for a <EM>y</EM>,
1961 the ending <EM>y</EM> is the first where the count reaches 0.
1962 For instance, the item <CODE>%b()</CODE> matches expressions with
1963 balanced parentheses.
1964 </UL>
1966 <H4>Pattern:</H4>
1967 a <A NAME="pattern"><EM>pattern</EM></A> is a sequence of pattern items.
1968 A <CODE>^</CODE> at the beginning of a pattern anchors the match at the
1969 beginning of the subject string.
1970 A <CODE>$</CODE> at the end of a pattern anchors the match at the
1971 end of the subject string.
1973 <H4>Captures:</H4>
1974 a pattern may contain sub-patterns enclosed in parentheses,
1975 that describe <A NAME="captures"><EM>captures</EM></A>.
1976 When a match succeeds, the sub-strings of the subject string
1977 that match captures are stored (<EM>captured</EM>) for future use.
1978 Captures are numbered according to their left parentheses.
1979 For instance, in the pattern <CODE>"(a*(.)%w(%s*))"</CODE>,
1980 the part of the string matching <CODE>"a*(.)%w(%s*)"</CODE> is
1981 stored as the first capture (and therefore has number 1);
1982 the character matching <CODE>.</CODE> is captured with number 2,
1983 and the part matching <CODE>%s*</CODE> has number 3.
1985 <A NAME="mathlib"></A>
1986 <A NAME="6.3"></A>
1987 <H2>6.3 - Mathematical Functions</H2>
1989 This library is an interface to some functions of the standard C math library.
1990 In addition, it registers a tag method for the binary operator <CODE>^</CODE> that
1991 returns <I>x^y</I> when applied to numbers <CODE>x^y</CODE>.
1993 The library provides the following functions:
1994 <A NAME="abs"></A><A NAME="acos"></A><A NAME="asin"></A><A NAME="atan"></A>
1995 <A NAME="atan2"></A><A NAME="ceil"></A><A NAME="cos"></A><A NAME="floor"></A>
1996 <A NAME="log"></A><A NAME="log10"></A><A NAME="max"></A><A NAME="min"></A>
1997 <A NAME="mod"></A><A NAME="sin"></A><A NAME="sqrt"></A><A NAME="tan"></A>
1998 <A NAME="random"></A><A NAME="randomseed"></A>
1999 <LISTING>
2000 abs acos asin atan atan2 ceil cos floor log log10
2001 max min mod sin sqrt tan random randomseed
2002 </LISTING>
2003 Most of them
2004 are only interfaces to the homonymous functions in the C library,
2005 except that, for the trigonometric functions,
2006 all angles are expressed in <EM>degrees</EM>, not radians.
2008 The function <CODE>max</CODE> returns the maximum
2009 value of its numeric arguments.
2010 Similarly, <CODE>min</CODE> computes the minimum.
2011 Both can be used with an unlimited number of arguments.
2013 The functions <CODE>random</CODE> and <CODE>randomseed</CODE> are interfaces to
2014 the simple random generator functions <CODE>rand</CODE> and <CODE>srand</CODE>,
2015 provided by ANSI C.
2016 The function <CODE>random</CODE> returns pseudo-random numbers in the
2017 range <I>[0,1)</I>.
2020 <A NAME="libio"></A>
2021 <A NAME="6.4"></A>
2022 <H2>6.4 - I/O Facilities</H2>
2024 All input and output operations in Lua are done over two
2025 <A NAME="file handles"><EM>file handles</EM></A>, one for reading and one for writing.
2026 These handles are stored in two Lua global variables,
2027 called <CODE>_INPUT</CODE> and <CODE>_OUTPUT</CODE>.
2028 The global variables
2029 <CODE>_STDIN</CODE>, <CODE>_STDOUT</CODE> and <CODE>_STDERR</CODE>
2030 are initialized with file descriptors for
2031 <CODE>stdin</CODE>, <CODE>stdout</CODE> and <CODE>stderr</CODE>.
2032 Initially, <CODE>_INPUT=_STDIN</CODE> and <CODE>_OUTPUT=_STDOUT</CODE>.
2033 <A NAME="_INPUT"></A><A NAME="_OUTPUT"></A>
2034 <A NAME="_STDIN"></A><A NAME="_STDOUT"></A><A NAME="_STDERR"></A>
2036 A file handle is a userdata containing the file stream <CODE>FILE*</CODE>,
2037 and with a distinctive tag created by the I/O library.
2040 Unless otherwise stated,
2041 all I/O functions return <B>nil</B> on failure and
2042 some value different from <B>nil</B> on success.
2044 <h3> <TT>readfrom (filename)</TT></h3><A NAME="readfrom"></A>
2046 This function may be called in two ways.
2047 When called with a file name, it opens the named file,
2048 sets its handle as the value of <CODE>_INPUT</CODE>,
2049 and returns this value.
2050 It does not close the current input file.
2051 When called without parameters,
2052 it closes the <CODE>_INPUT</CODE> file,
2053 and restores <CODE>stdin</CODE> as the value of <CODE>_INPUT</CODE>.
2055 If this function fails, it returns <B>nil</B>,
2056 plus a string describing the error.
2058 <CITE>
2059 <EM>System dependent</EM>: if <CODE>filename</CODE> starts with a <CODE>|</CODE>,
2060 then a <A NAME="piped input">piped input</A> is open, via function <A NAME="popen"><TT>popen</TT></A>.
2061 Not all systems implement pipes.
2062 Moreover,
2063 the number of files that can be open at the same time is
2064 usually limited and depends on the system.
2065 </CITE>
2067 <h3> <TT>writeto (filename)</TT></h3><A NAME="writeto"></A>
2069 This function may be called in two ways.
2070 When called with a file name,
2071 it opens the named file,
2072 sets its handle as the value of <CODE>_OUTPUT</CODE>,
2073 and returns this value.
2074 It does not close the current output file.
2075 Notice that, if the file already exists,
2076 then it will be <EM>completely erased</EM> with this operation.
2077 When called without parameters,
2078 this function closes the <CODE>_OUTPUT</CODE> file,
2079 and restores <CODE>stdout</CODE> as the value of <CODE>_OUTPUT</CODE>.
2080 <A NAME="closing a file"></A>
2082 If this function fails, it returns <B>nil</B>,
2083 plus a string describing the error.
2085 <CITE>
2086 <EM>System dependent</EM>: if <CODE>filename</CODE> starts with a <CODE>|</CODE>,
2087 then a <A NAME="piped output">piped output</A> is open, via function <A NAME="popen"><TT>popen</TT></A>.
2088 Not all systems implement pipes.
2089 Moreover,
2090 the number of files that can be open at the same time is
2091 usually limited and depends on the system.
2092 </CITE>
2094 <h3> <TT>appendto (filename)</TT></h3><A NAME="appendto"></A>
2096 This function opens a file named <CODE>filename</CODE> and sets it as the
2097 value of <CODE>_OUTPUT</CODE>.
2098 Unlike the <CODE>writeto</CODE> operation,
2099 this function does not erase any previous content of the file.
2100 If this function fails, it returns <B>nil</B>,
2101 plus a string describing the error.
2103 Notice that function <CODE>writeto</CODE> is available to close an output file.
2105 <h3> <TT>remove (filename)</TT></h3><A NAME="remove"></A>
2107 This function deletes the file with the given name.
2108 If this function fails, it returns <B>nil</B>,
2109 plus a string describing the error.
2111 <h3> <TT>rename (name1, name2)</TT></h3><A NAME="rename"></A>
2113 This function renames file named <CODE>name1</CODE> to <CODE>name2</CODE>.
2114 If this function fails, it returns <B>nil</B>,
2115 plus a string describing the error.
2117 <h3> <TT>tmpname ()</TT></h3><A NAME="tmpname"></A>
2119 This function returns a string with a file name that can safely
2120 be used for a temporary file.
2121 The file must be explicitly removed when no longer needed.
2123 <h3> <TT>read ([readpattern])</TT></h3><A NAME="read"></A>
2125 This function reads the file <CODE>_INPUT</CODE>
2126 according to a read pattern, that specifies how much to read;
2127 characters are read from the current input file until
2128 the read pattern fails or ends.
2129 The function <CODE>read</CODE> returns a string with the characters read,
2130 even if the pattern succeeds only partially,
2131 or <B>nil</B> if the read pattern fails <EM>and</EM>
2132 the result string would be empty.
2133 When called without parameters,
2134 it uses a default pattern that reads the next line
2135 (see below).
2137 A <A NAME="read pattern"><EM>read pattern</EM></A> is a sequence of read pattern items.
2138 An item may be a single character class
2139 or a character class followed by <CODE>?</CODE> or by <CODE>*</CODE>.
2140 A single character class reads the next character from the input
2141 if it belongs to the class, otherwise it fails.
2142 A character class followed by <CODE>?</CODE> reads the next character
2143 from the input if it belongs to the class;
2144 it never fails.
2145 A character class followed by <CODE>*</CODE> reads until a character that
2146 does not belong to the class, or end of file;
2147 since it can match a sequence of zero characters, it never fails.
2148 \footnote{
2149 Notice that the behavior of read patterns is different from
2150 the regular pattern matching behavior,
2151 where a <CODE>*</CODE> expands to the maximum length <EM>such that</EM>
2152 the rest of the pattern does not fail.
2153 With the read pattern behavior
2154 there is no need for backtracking the reading.
2157 A pattern item may contain sub-patterns enclosed in curly brackets,
2158 that describe <A NAME="skips"><EM>skips</EM></A>.
2159 Characters matching a skip are read,
2160 but are not included in the resulting string.
2162 Following are some examples of read patterns and their meanings:
2163 <UL>
2164 <LI><CODE>"."</CODE> returns the next character, or <B>nil</B> on end of file.
2165 <LI><CODE>".*"</CODE> reads the whole file.
2166 <LI><CODE>"[^\n]*{\n}"</CODE> returns the next line
2167 (skipping the end of line), or <B>nil</B> on end of file.
2168 This is the default pattern.
2169 <LI><CODE>"{%s*}%S%S*"</CODE> returns the next word
2170 (maximal sequence of non white-space characters),
2171 skipping spaces if necessary,
2172 or <B>nil</B> on end of file.
2173 <LI><CODE>"{%s*}[+-]?%d%d*"</CODE> returns the next integer
2174 or <B>nil</B> if the next characters do not conform to an integer format.
2175 </UL>
2177 <h3> <TT>write (value1, ...)</TT></h3><A NAME="write"></A>
2179 This function writes the value of each of its arguments to the
2180 file <CODE>_OUTPUT</CODE>.
2181 The arguments must be strings or numbers.
2182 To write other values,
2183 use <CODE>tostring</CODE> or <CODE>format</CODE> before <CODE>write</CODE>.
2184 If this function fails, it returns <B>nil</B>,
2185 plus a string describing the error.
2187 <h3> <TT>date ([format])</TT></h3><A NAME="date"></A>
2189 This function returns a string containing date and time
2190 formatted according to the given string <CODE>format</CODE>,
2191 following the same rules of the ANSI C function <CODE>strftime</CODE>.
2192 When called without arguments,
2193 it returns a reasonable date and time representation that depends on
2194 the host system.
2196 <h3> <TT>exit ([code])</TT></h3><A NAME="exit"></A>
2198 This function calls the C function <CODE>exit</CODE>,
2199 with an optional <CODE>code</CODE>,
2200 to terminate the program.
2201 The default value for <CODE>code</CODE> is 1.
2203 <h3> <TT>getenv (varname)</TT></h3><A NAME="getenv"></A>
2205 Returns the value of the environment variable <CODE>varname</CODE>,
2206 or <B>nil</B> if the variable is not defined.
2208 <h3> <TT>execute (command)</TT></h3><A NAME="execute"></A>
2210 This function is equivalent to the C function <CODE>system</CODE>.
2211 It passes <CODE>command</CODE> to be executed by an operating system shell.
2212 It returns an error code, which is system-dependent.
2215 <A NAME="debugI"></A>
2216 <!-- ====================================================================== -->
2217 <HR>
2218 <A NAME="7."></A>
2219 <H1>7 - The Debugger Interface</H1>
2221 Lua has no built-in debugging facilities.
2222 Instead, it offers a special interface,
2223 by means of functions and <EM>hooks</EM>,
2224 which allows the construction of different
2225 kinds of debuggers, profilers, and other tools
2226 that need ``inside information'' from the interpreter.
2227 This interface is declared in the header file <CODE>luadebug.h</CODE>.
2229 <A NAME="7.1"></A>
2230 <H2>7.1 - Stack and Function Information</H2>
2232 The main function to get information about the interpreter stack
2234 <LISTING>
2235 lua_Function lua_stackedfunction (int level);
2236 </LISTING>
2237 It returns a handle (<CODE>lua_Function</CODE>) to the <EM>activation record</EM>
2238 of the function executing at a given level.
2239 Level&nbsp;0 is the current running function,
2240 while level <I>n+1</I> is the function that has called level <I>n</I>.
2241 When called with a level greater than the stack depth,
2242 <CODE>lua_stackedfunction</CODE> returns <CODE>LUA_NOOBJECT</CODE>.
2244 The type <CODE>lua_Function</CODE> is just another name
2245 to <CODE>lua_Object</CODE>.
2246 Although, in this library,
2247 a <CODE>lua_Function</CODE> can be used wherever a <CODE>lua_Object</CODE> is required,
2248 when a parameter has type <CODE>lua_Function</CODE>
2249 it accepts only a handle returned by
2250 <CODE>lua_stackedfunction</CODE>.
2252 Three other functions produce extra information about a function:
2253 <LISTING>
2254 void lua_funcinfo (lua_Object func, char **filename, int *linedefined);
2255 int lua_currentline (lua_Function func);
2256 char *lua_getobjname (lua_Object o, char **name);
2257 </LISTING>
2258 <CODE>lua_funcinfo</CODE> gives the file name and the line where the
2259 given function has been defined.
2260 If the ``function'' is in fact the main code of a chunk,
2261 then <CODE>linedefined</CODE> is 0.
2262 If the function is a C function,
2263 then <CODE>linedefined</CODE> is -1, and <CODE>filename</CODE> is <CODE>"(C)"</CODE>.
2265 The function <CODE>lua_currentline</CODE> gives the current line where
2266 a given function is executing.
2267 It only works if the function has been compiled with debug
2268 information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2269 When no line information is available, it returns -1.
2271 Function <CODE>lua_getobjname</CODE> tries to find a reasonable name for
2272 a given function.
2273 Because functions in Lua are first class values,
2274 they do not have a fixed name:
2275 Some functions may be the value of many global variables,
2276 while others may be stored only in a table field.
2277 Function <CODE>lua_getobjname</CODE> first checks whether the given
2278 function is a tag method.
2279 If so, it returns the string <CODE>"tag-method"</CODE>,
2280 and <CODE>name</CODE> is set to point to the event name.
2281 Otherwise, if the given function is the value of a global variable,
2282 then <CODE>lua_getobjname</CODE> returns the string <CODE>"global"</CODE>,
2283 and <CODE>name</CODE> points to the variable name.
2284 If the given function is neither a tag method nor a global variable,
2285 then <CODE>lua_getobjname</CODE> returns the empty string,
2286 and <CODE>name</CODE> is set to <CODE>NULL</CODE>.
2288 <A NAME="7.2"></A>
2289 <H2>7.2 - Manipulating Local Variables</H2>
2291 The following functions allow the manipulation of the
2292 local variables of a given activation record.
2293 They only work if the function has been compiled with debug
2294 information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2295 <LISTING>
2296 lua_Object lua_getlocal (lua_Function func, int local_number, char **name);
2297 int lua_setlocal (lua_Function func, int local_number);
2298 </LISTING>
2299 <CODE>lua_getlocal</CODE> returns the value of a local variable,
2300 and sets <CODE>name</CODE> to point to the variable name.
2301 <CODE>local_number</CODE> is an index for local variables.
2302 The first parameter has index 1, and so on, until the
2303 last active local variable.
2304 When called with a <CODE>local_number</CODE> greater than the
2305 number of active local variables,
2306 or if the activation record has no debug information,
2307 <CODE>lua_getlocal</CODE> returns <CODE>LUA_NOOBJECT</CODE>.
2308 Formal parameters are the first local variables.
2310 The function <CODE>lua_setlocal</CODE> sets the local variable
2311 <CODE>local_number</CODE> to the value previously pushed on the stack
2312 (see Section&nbsp;<A HREF="#valuesCLua">5.1</A>).
2313 If the function succeeds, then it returns 1.
2314 If <CODE>local_number</CODE> is greater than the number
2315 of active local variables,
2316 or if the activation record has no debug information,
2317 then this function fails and returns 0.
2319 <A NAME="7.3"></A>
2320 <H2>7.3 - Hooks</H2>
2322 The Lua interpreter offers two hooks for debugging purposes:
2323 <LISTING>
2324 typedef void (*lua_CHFunction) (lua_Function func, char *file, int line);
2325 extern lua_CHFunction lua_callhook;
2327 typedef void (*lua_LHFunction) (int line);
2328 extern lua_LHFunction lua_linehook;
2329 </LISTING>
2330 The first one is called whenever the interpreter enters or leaves a
2331 function.
2332 When entering a function,
2333 its parameters are a handle to the function activation record,
2334 plus the file and the line where the function is defined (the same
2335 information which is provided by <CODE>lua_funcinfo</CODE>);
2336 when leaving a function, <CODE>func</CODE> is <CODE>LUA_NOOBJECT</CODE>,
2337 <CODE>file</CODE> is <CODE>"(return)"</CODE>, and <CODE>line</CODE> is 0.
2339 The other hook is called every time the interpreter changes
2340 the line of code it is executing.
2341 Its only parameter is the line number
2342 (the same information which is provided by the call
2343 <CODE>lua_currentline(lua_stackedfunction(0))</CODE>).
2344 This second hook is only called if the active function
2345 has been compiled with debug information (see Section&nbsp;<A HREF="#pragma">4.9</A>).
2347 A hook is disabled when its value is <CODE>NULL</CODE>,
2348 which is the initial value of both hooks.
2352 <A NAME="lua-sa"></A>
2353 <!-- ====================================================================== -->
2354 <HR>
2355 <A NAME="8."></A>
2356 <H1>8 - Lua Stand-alone</H1>
2358 Although Lua has been designed as an extension language,
2359 the language can also be used as a stand-alone interpreter.
2360 An implementation of such an interpreter,
2361 called simply <CODE>lua</CODE>,
2362 is provided with the standard distribution.
2363 This program can be called with any sequence of the following arguments:
2364 <DL>
2365 <DT><B><TT>-v</TT></B><DD> prints version information.
2366 <DT><B><TT>-</TT></B><DD> runs interactively, accepting commands from standard input
2367 until an <CODE>EOF</CODE>.
2368 <DT><B><TT>-e stat</TT></B><DD> executes <CODE>stat</CODE> as a Lua chunk.
2369 <DT><B><TT>var=exp</TT></B><DD> executes <CODE>var=exp</CODE> as a Lua chunk.
2370 <DT><B><TT>filename</TT></B><DD> executes file <CODE>filename</CODE> as a Lua chunk.
2371 </DL>
2372 All arguments are handled in order.
2373 For instance, an invocation like
2374 <LISTING>
2375 $ lua - a=1 prog.lua
2376 </LISTING>
2377 will first interact with the user until an <CODE>EOF</CODE>,
2378 then will set <CODE>a</CODE> to 1,
2379 and finally will run file <CODE>prog.lua</CODE>.
2381 Please notice that the interaction with the shell may lead to
2382 unintended results.
2383 For instance, a call like
2384 <LISTING>
2385 $ lua a="name" prog.lua
2386 </LISTING>
2387 will <EM>not</EM> set <CODE>a</CODE> to the string <CODE>"name"</CODE>.
2388 Instead, the quotes will be handled by the shell,
2389 lua will get only <CODE>a=name</CODE> to run,
2390 and <CODE>a</CODE> will finish with <B>nil</B>,
2391 because the global variable <CODE>name</CODE> has not been initialized.
2392 Instead, one should write
2393 <LISTING>
2394 $ lua 'a="name"' prog.lua
2395 </LISTING>
2397 <HR>
2398 <A NAME="Acknowledgments"></A>
2399 <h1>Acknowledgments</h1>
2401 The authors would like to thank CENPES/PETROBRAS which,
2402 jointly with TeCGraf, used extensively early versions of
2403 this system and gave valuable comments.
2404 The authors would also like to thank Carlos Henrique Levy,
2405 who found the name of the game.
2406 Lua means <EM>moon</EM> in Portuguese.
2411 <HR>
2412 <A NAME="Incompatibilities"></A>
2413 <h1>Incompatibilities with Previous Versions</h1>
2415 Although great care has been taken to avoid incompatibilities with
2416 the previous public versions of Lua,
2417 some differences had to be introduced.
2418 Here is a list of all these incompatibilities.
2420 <h2>Incompatibilities with <A NAME="version 2.5</h2>">version 2.5</h2></A>
2421 <UL>
2422 <LI>
2423 The whole fallback mechanism has been replaced by tag methods.
2424 Nevertheless, the function <CODE>setfallback</CODE> has been rewritten in
2425 a way that uses tag methods to fully emulate the old behavior
2426 of fallbacks.
2427 <LI>
2428 Tags now must be created with the function <CODE>newtag</CODE>.
2429 Nevertheless, old user defined tags are still accepted
2430 (user defined tags must be positive;
2431 <CODE>newtag</CODE> uses negative numbers).
2432 Tag methods cannot be set for such user defined tags,
2433 and fallbacks do not affect tags created by <CODE>newtag</CODE>.
2434 <LI>
2435 Lua 2.5 accepts mixed comparisons of strings and numbers,
2436 like <CODE>2&lt;"12"</CODE>, giving weird results.
2437 Now this is an error.
2438 <LI>
2439 Character <CODE>"-"</CODE> (hyphen) now is ``magic'' in pattern matching.
2440 <LI>
2441 Some API functions have been rewritten as macros.
2442 </UL>
2444 <h2>Incompatibilities with <A NAME="version 2.4</h2>">version 2.4</h2></A>
2445 The whole I/O facilities have been rewritten.
2446 We strongly encourage programmers to adapt their code
2447 to this new version.
2448 The incompatibilities between the new and the old libraries are:
2449 <UL>
2450 <LI>The format facility of function <CODE>write</CODE> has been supersed by
2451 function <CODE>format</CODE>;
2452 therefore this facility has been dropped.
2453 <LI>Function <CODE>read</CODE> now uses <EM>read patterns</EM> to specify
2454 what to read;
2455 this is incompatible with the old format options.
2456 <LI>Function <CODE>strfind</CODE> now accepts patterns,
2457 so it may have a different behavior when the pattern includes
2458 special characters.
2459 </UL>
2461 <h2>Incompatibilities with <A NAME="version 2.2</h2>">version 2.2</h2></A>
2462 <UL>
2463 <LI>
2464 Functions <CODE>date</CODE> and <CODE>time</CODE> (from <CODE>iolib</CODE>)
2465 have been superseded by the new, more powerful version of function <CODE>date</CODE>.
2466 <LI>
2467 Function <CODE>append</CODE> (from <CODE>iolib</CODE>) now returns 1 whenever it succeeds,
2468 whether the file is new or not.
2469 <LI>
2470 Function <CODE>int2str</CODE> (from <CODE>strlib</CODE>) has been superseded by new
2471 function <CODE>format</CODE>, with parameter <CODE>"%c"</CODE>.
2472 <LI>
2473 The API lock mechanism has been superseded by the reference mechanism.
2474 However, <CODE>lua.h</CODE> provides compatibility macros,
2475 so there is no need to change programs.
2476 <LI>
2477 The API function <CODE>lua_pushliteral</CODE> now is just a macro to
2478 <CODE>lua_pushstring</CODE>.
2479 </UL>
2481 <h2>Incompatibilities with <A NAME="version 2.1</h2>">version 2.1</h2></A>
2482 <UL>
2483 <LI>
2484 The function <CODE>type</CODE> now returns the string <CODE>"function"</CODE>
2485 both for C and Lua functions.
2486 Because Lua functions and C functions are compatible,
2487 this behavior is usually more useful.
2488 When needed, the second result of function <TT>type</TT> may be used
2489 to distinguish between Lua and C functions.
2490 <LI>
2491 A function definition only assigns the function value to the
2492 given variable at execution time.
2493 </UL>
2495 <h2>Incompatibilities with <A NAME="version 1.1</h2>">version 1.1</h2></A>
2496 <UL>
2497 <LI>
2498 The equality test operator now is denoted by <CODE>==</CODE>,
2499 instead of <CODE>=</CODE>.
2500 <LI>
2501 The syntax for table construction has been greatly simplified.
2502 The old <CODE>@(size)</CODE> has been substituted by <CODE>{}</CODE>.
2503 The list constructor (formerly <CODE>@[...]</CODE>) and the record
2504 constructor (formerly <CODE>@{...}</CODE>) now are both coded like
2505 <CODE>{...}</CODE>.
2506 When the construction involves a function call,
2507 like in <CODE>@func{...}</CODE>,
2508 the new syntax does not use the <CODE>@</CODE>.
2509 More important, {\em a construction function must now
2510 explicitly return the constructed table}.
2511 <LI>
2512 The function <CODE>lua_call</CODE> no longer has the parameter <CODE>nparam</CODE>.
2513 <LI>
2514 The function <CODE>lua_pop</CODE> is no longer available,
2515 since it could lead to strange behavior.
2516 In particular,
2517 to access results returned from a Lua function,
2518 the new macro <CODE>lua_getresult</CODE> should be used.
2519 <LI>
2520 The old functions <CODE>lua_storefield</CODE> and <CODE>lua_storeindexed</CODE>
2521 have been replaced by
2522 <LISTING>
2523 int lua_storesubscript (void);
2524 </LISTING>
2525 with the parameters explicitly pushed on the stack.
2526 <LI>
2527 The functionality of the function <CODE>lua_errorfunction</CODE> has been
2528 replaced by the <EM>fallback</EM> mechanism (see Section&nbsp;<A HREF="#error">4.9</A>).
2529 <LI>
2530 When calling a function from the Lua library,
2531 parameters passed through the stack
2532 must be pushed just before the corresponding call,
2533 with no intermediate calls to Lua.
2534 Special care should be taken with macros like
2535 <CODE>lua_getindexed</CODE> and <CODE>lua_getfield</CODE>.
2536 </UL>
2540 <HR>
2541 Last update:
2542 Tue Jul 1 07:55:45 EST 1997
2543 by <A HREF="http://www.tecgraf.puc-rio.br/~lhf/">lhf</A>.
2544 </BODY>
2545 </HTML>