]> git.lizzy.rs Git - metalua.git/blob - doc/lua/manual.html
6b137ff6e6f4e00a56af8ca196c48aec314e398a
[metalua.git] / doc / lua / manual.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
2 <html>
3
4 <head>
5 <title>Lua 5.1 Reference Manual</title>
6 <link rel="stylesheet" href="lua.css">
7 <link rel="stylesheet" href="manual.css">
8 </head>
9
10 <body>
11
12 <hr>
13 <h1>
14 <a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
15 Lua 5.1 Reference Manual
16 </h1>
17
18 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
19 <p>
20 <small>
21 Copyright &copy; 2006-2007 Lua.org, PUC-Rio.
22 Freely available under the terms of the
23 <a href="http://www.lua.org/license.html#5">Lua license</a>.
24 </small>
25 <hr>
26 <p>
27
28 <a href="contents.html#contents">contents</A>
29 &middot;
30 <a href="contents.html#index">index</A>
31
32 <!-- ====================================================================== -->
33 <p>
34
35
36
37
38
39 <h1>1 - <a name="1">Introduction</a></h1>
40
41 <p>
42 Lua is an extension programming language designed to support
43 general procedural programming with data description
44 facilities.
45 It also offers good support for object-oriented programming,
46 functional programming, and data-driven programming.
47 Lua is intended to be used as a powerful, light-weight
48 scripting language for any program that needs one.
49 Lua is implemented as a library, written in <em>clean</em> C
50 (that is, in the common subset of ANSI&nbsp;C and C++).
51
52
53 <p>
54 Being an extension language, Lua has no notion of a "main" program:
55 it only works <em>embedded</em> in a host client,
56 called the <em>embedding program</em> or simply the <em>host</em>.
57 This host program can invoke functions to execute a piece of Lua code,
58 can write and read Lua variables,
59 and can register C&nbsp;functions to be called by Lua code.
60 Through the use of C&nbsp;functions, Lua can be augmented to cope with
61 a wide range of different domains,
62 thus creating customized programming languages sharing a syntactical framework.
63 The Lua distribution includes a sample host program called <code>lua</code>,
64 which uses the Lua library to offer a complete, stand-alone Lua interpreter.
65
66
67 <p>
68 Lua is free software,
69 and is provided as usual with no guarantees,
70 as stated in its license.
71 The implementation described in this manual is available
72 at Lua's official web site, <code>www.lua.org</code>.
73
74
75 <p>
76 Like any other reference manual,
77 this document is dry in places.
78 For a discussion of the decisions behind the design of Lua,
79 see the technical papers available at Lua's web site.
80 For a detailed introduction to programming in Lua,
81 see Roberto's book, <em>Programming in Lua (Second Edition)</em>.
82
83
84
85 <h1>2 - <a name="2">The Language</a></h1>
86
87 <p>
88 This section describes the lexis, the syntax, and the semantics of Lua.
89 In other words,
90 this section describes
91 which tokens are valid,
92 how they can be combined,
93 and what their combinations mean.
94
95
96 <p>
97 The language constructs will be explained using the usual extended BNF notation,
98 in which
99 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
100 [<em>a</em>]&nbsp;means an optional <em>a</em>.
101 Non-terminals are shown like non-terminal,
102 keywords are shown like <b>kword</b>,
103 and other terminal symbols are shown like `<b>=</b>&acute;.
104 The complete syntax of Lua can be found at the end of this manual.
105
106
107
108 <h2>2.1 - <a name="2.1">Lexical Conventions</a></h2>
109
110 <p>
111 <em>Names</em>
112 (also called <em>identifiers</em>)
113 in Lua can be any string of letters,
114 digits, and underscores,
115 not beginning with a digit.
116 This coincides with the definition of names in most languages.
117 (The definition of letter depends on the current locale:
118 any character considered alphabetic by the current locale
119 can be used in an identifier.)
120 Identifiers are used to name variables and table fields.
121
122
123 <p>
124 The following <em>keywords</em> are reserved
125 and cannot be used as names:
126
127
128 <pre>
129      and       break     do        else      elseif
130      end       false     for       function  if
131      in        local     nil       not       or
132      repeat    return    then      true      until     while
133 </pre>
134
135 <p>
136 Lua is a case-sensitive language:
137 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
138 are two different, valid names.
139 As a convention, names starting with an underscore followed by
140 uppercase letters (such as <code>_VERSION</code>)
141 are reserved for internal global variables used by Lua.
142
143
144 <p>
145 The following strings denote other tokens:
146
147 <pre>
148      +     -     *     /     %     ^     #
149      ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
150      (     )     {     }     [     ]
151      ;     :     ,     .     ..    ...
152 </pre>
153
154 <p>
155 <em>Literal strings</em>
156 can be delimited by matching single or double quotes,
157 and can contain the following C-like escape sequences:
158 '<code>\a</code>' (bell),
159 '<code>\b</code>' (backspace),
160 '<code>\f</code>' (form feed),
161 '<code>\n</code>' (newline),
162 '<code>\r</code>' (carriage return),
163 '<code>\t</code>' (horizontal tab),
164 '<code>\v</code>' (vertical tab),
165 '<code>\\</code>' (backslash),
166 '<code>\"</code>' (quotation mark [double quote]),
167 and '<code>\'</code>' (apostrophe [single quote]).
168 Moreover, a backslash followed by a real newline
169 results in a newline in the string.
170 A character in a string may also be specified by its numerical value
171 using the escape sequence <code>\<em>ddd</em></code>,
172 where <em>ddd</em> is a sequence of up to three decimal digits.
173 (Note that if a numerical escape is to be followed by a digit,
174 it must be expressed using exactly three digits.)
175 Strings in Lua may contain any 8-bit value, including embedded zeros,
176 which can be specified as '<code>\0</code>'.
177
178
179 <p>
180 To put a double (single) quote, a newline, a backslash,
181 or an embedded zero
182 inside a literal string enclosed by double (single) quotes
183 you must use an escape sequence.
184 Any other character may be directly inserted into the literal.
185 (Some control characters may cause problems for the file system,
186 but Lua has no problem with them.)
187
188
189 <p>
190 Literal strings can also be defined using a long format
191 enclosed by <em>long brackets</em>.
192 We define an <em>opening long bracket of level <em>n</em></em> as an opening
193 square bracket followed by <em>n</em> equal signs followed by another
194 opening square bracket.
195 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
196 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
197 and so on.
198 A <em>closing long bracket</em> is defined similarly;
199 for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
200 A long string starts with an opening long bracket of any level and
201 ends at the first closing long bracket of the same level.
202 Literals in this bracketed form may run for several lines,
203 do not interpret any escape sequences,
204 and ignore long brackets of any other level.
205 They may contain anything except a closing bracket of the proper level.
206
207
208 <p>
209 For convenience,
210 when the opening long bracket is immediately followed by a newline,
211 the newline is not included in the string.
212 As an example, in a system using ASCII
213 (in which '<code>a</code>' is coded as&nbsp;97,
214 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
215 the five literals below denote the same string:
216
217 <pre>
218      a = 'alo\n123"'
219      a = "alo\n123\""
220      a = '\97lo\10\04923"'
221      a = [[alo
222      123"]]
223      a = [==[
224      alo
225      123"]==]
226 </pre>
227
228 <p>
229 A <em>numerical constant</em> may be written with an optional decimal part
230 and an optional decimal exponent.
231 Lua also accepts integer hexadecimal constants,
232 by prefixing them with <code>0x</code>.
233 Examples of valid numerical constants are
234
235 <pre>
236      3   3.0   3.1416   314.16e-2   0.31416E1   0xff   0x56
237 </pre>
238
239 <p>
240 A <em>comment</em> starts with a double hyphen (<code>--</code>)
241 anywhere outside a string.
242 If the text immediately after <code>--</code> is not an opening long bracket,
243 the comment is a <em>short comment</em>,
244 which runs until the end of the line.
245 Otherwise, it is a <em>long comment</em>,
246 which runs until the corresponding closing long bracket.
247 Long comments are frequently used to disable code temporarily.
248
249
250
251
252
253 <h2>2.2 - <a name="2.2">Values and Types</a></h2>
254
255 <p>
256 Lua is a <em>dynamically typed language</em>.
257 This means that
258 variables do not have types; only values do.
259 There are no type definitions in the language.
260 All values carry their own type.
261
262
263 <p>
264 All values in Lua are <em>first-class values</em>.
265 This means that all values can be stored in variables,
266 passed as arguments to other functions, and returned as results.
267
268
269 <p>
270 There are eight basic types in Lua:
271 <em>nil</em>, <em>boolean</em>, <em>number</em>,
272 <em>string</em>, <em>function</em>, <em>userdata</em>,
273 <em>thread</em>, and <em>table</em>.
274 <em>Nil</em> is the type of the value <b>nil</b>,
275 whose main property is to be different from any other value;
276 it usually represents the absence of a useful value.
277 <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
278 Both <b>nil</b> and <b>false</b> make a condition false;
279 any other value makes it true.
280 <em>Number</em> represents real (double-precision floating-point) numbers.
281 (It is easy to build Lua interpreters that use other
282 internal representations for numbers,
283 such as single-precision float or long integers;
284 see file <code>luaconf.h</code>.)
285 <em>String</em> represents arrays of characters.
286
287 Lua is 8-bit clean:
288 strings may contain any 8-bit character,
289 including embedded zeros ('<code>\0</code>') (see <a href="#2.1">&sect;2.1</a>).
290
291
292 <p>
293 Lua can call (and manipulate) functions written in Lua and
294 functions written in C
295 (see <a href="#2.5.8">&sect;2.5.8</a>).
296
297
298 <p>
299 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
300 be stored in Lua variables.
301 This type corresponds to a block of raw memory
302 and has no pre-defined operations in Lua,
303 except assignment and identity test.
304 However, by using <em>metatables</em>,
305 the programmer can define operations for userdata values
306 (see <a href="#2.8">&sect;2.8</a>).
307 Userdata values cannot be created or modified in Lua,
308 only through the C&nbsp;API.
309 This guarantees the integrity of data owned by the host program.
310
311
312 <p>
313 The type <em>thread</em> represents independent threads of execution
314 and it is used to implement coroutines (see <a href="#2.11">&sect;2.11</a>).
315 Do not confuse Lua threads with operating-system threads.
316 Lua supports coroutines on all systems,
317 even those that do not support threads.
318
319
320 <p>
321 The type <em>table</em> implements associative arrays,
322 that is, arrays that can be indexed not only with numbers,
323 but with any value (except <b>nil</b>).
324 Tables can be <em>heterogeneous</em>;
325 that is, they can contain values of all types (except <b>nil</b>).
326 Tables are the sole data structuring mechanism in Lua;
327 they may be used to represent ordinary arrays,
328 symbol tables, sets, records, graphs, trees, etc.
329 To represent records, Lua uses the field name as an index.
330 The language supports this representation by
331 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
332 There are several convenient ways to create tables in Lua
333 (see <a href="#2.5.7">&sect;2.5.7</a>).
334
335
336 <p>
337 Like indices,
338 the value of a table field can be of any type (except <b>nil</b>).
339 In particular,
340 because functions are first-class values,
341 table fields may contain functions.
342 Thus tables may also carry <em>methods</em> (see <a href="#2.5.9">&sect;2.5.9</a>).
343
344
345 <p>
346 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
347 variables do not actually <em>contain</em> these values,
348 only <em>references</em> to them.
349 Assignment, parameter passing, and function returns
350 always manipulate references to such values;
351 these operations do not imply any kind of copy.
352
353
354 <p>
355 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
356 of a given value.
357
358
359
360 <h3>2.2.1 - <a name="2.2.1">Coercion</a></h3>
361
362 <p>
363 Lua provides automatic conversion between
364 string and number values at run time.
365 Any arithmetic operation applied to a string tries to convert
366 this string to a number, following the usual conversion rules.
367 Conversely, whenever a number is used where a string is expected,
368 the number is converted to a string, in a reasonable format.
369 For complete control over how numbers are converted to strings,
370 use the <code>format</code> function from the string library
371 (see <a href="#pdf-string.format"><code>string.format</code></a>).
372
373
374
375
376
377
378
379 <h2>2.3 - <a name="2.3">Variables</a></h2>
380
381 <p>
382 Variables are places that store values.
383
384 There are three kinds of variables in Lua:
385 global variables, local variables, and table fields.
386
387
388 <p>
389 A single name can denote a global variable or a local variable
390 (or a function's formal parameter,
391 which is a particular kind of local variable):
392
393 <pre>
394         var ::= Name
395 </pre><p>
396 Name denotes identifiers, as defined in <a href="#2.1">&sect;2.1</a>.
397
398
399 <p>
400 Any variable is assumed to be global unless explicitly declared
401 as a local (see <a href="#2.4.7">&sect;2.4.7</a>).
402 Local variables are <em>lexically scoped</em>:
403 local variables can be freely accessed by functions
404 defined inside their scope (see <a href="#2.6">&sect;2.6</a>).
405
406
407 <p>
408 Before the first assignment to a variable, its value is <b>nil</b>.
409
410
411 <p>
412 Square brackets are used to index a table:
413
414 <pre>
415         var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
416 </pre><p>
417 The meaning of accesses to global variables 
418 and table fields can be changed via metatables.
419 An access to an indexed variable <code>t[i]</code> is equivalent to
420 a call <code>gettable_event(t,i)</code>.
421 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
422 <code>gettable_event</code> function.
423 This function is not defined or callable in Lua.
424 We use it here only for explanatory purposes.)
425
426
427 <p>
428 The syntax <code>var.Name</code> is just syntactic sugar for
429 <code>var["Name"]</code>:
430
431 <pre>
432         var ::= prefixexp `<b>.</b>&acute; Name
433 </pre>
434
435 <p>
436 All global variables live as fields in ordinary Lua tables,
437 called <em>environment tables</em> or simply
438 <em>environments</em> (see <a href="#2.9">&sect;2.9</a>).
439 Each function has its own reference to an environment,
440 so that all global variables in this function
441 will refer to this environment table.
442 When a function is created,
443 it inherits the environment from the function that created it.
444 To get the environment table of a Lua function,
445 you call <a href="#pdf-getfenv"><code>getfenv</code></a>.
446 To replace it,
447 you call <a href="#pdf-setfenv"><code>setfenv</code></a>.
448 (You can only manipulate the environment of C&nbsp;functions
449 through the debug library; (see <a href="#5.9">&sect;5.9</a>).)
450
451
452 <p>
453 An access to a global variable <code>x</code>
454 is equivalent to <code>_env.x</code>,
455 which in turn is equivalent to
456
457 <pre>
458      gettable_event(_env, "x")
459 </pre><p>
460 where <code>_env</code> is the environment of the running function.
461 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
462 <code>gettable_event</code> function.
463 This function is not defined or callable in Lua.
464 Similarly, the <code>_env</code> variable is not defined in Lua.
465 We use them here only for explanatory purposes.)
466
467
468
469
470
471 <h2>2.4 - <a name="2.4">Statements</a></h2>
472
473 <p>
474 Lua supports an almost conventional set of statements,
475 similar to those in Pascal or C.
476 This set includes
477 assignment, control structures, function calls,
478 and variable declarations.
479
480
481
482 <h3>2.4.1 - <a name="2.4.1">Chunks</a></h3>
483
484 <p>
485 The unit of execution of Lua is called a <em>chunk</em>.
486 A chunk is simply a sequence of statements,
487 which are executed sequentially.
488 Each statement can be optionally followed by a semicolon:
489
490 <pre>
491         chunk ::= {stat [`<b>;</b>&acute;]}
492 </pre><p>
493 There are no empty statements and thus '<code>;;</code>' is not legal.
494
495
496 <p>
497 Lua handles a chunk as the body of an anonymous function 
498 with a variable number of arguments
499 (see <a href="#2.5.9">&sect;2.5.9</a>).
500 As such, chunks can define local variables,
501 receive arguments, and return values.
502
503
504 <p>
505 A chunk may be stored in a file or in a string inside the host program.
506 When a chunk is executed, first it is pre-compiled into instructions for
507 a virtual machine,
508 and then the compiled code is executed
509 by an interpreter for the virtual machine.
510
511
512 <p>
513 Chunks may also be pre-compiled into binary form;
514 see program <code>luac</code> for details.
515 Programs in source and compiled forms are interchangeable;
516 Lua automatically detects the file type and acts accordingly.
517
518
519
520
521
522
523 <h3>2.4.2 - <a name="2.4.2">Blocks</a></h3><p>
524 A block is a list of statements;
525 syntactically, a block is the same as a chunk:
526
527 <pre>
528         block ::= chunk
529 </pre>
530
531 <p>
532 A block may be explicitly delimited to produce a single statement:
533
534 <pre>
535         stat ::= <b>do</b> block <b>end</b>
536 </pre><p>
537 Explicit blocks are useful
538 to control the scope of variable declarations.
539 Explicit blocks are also sometimes used to
540 add a <b>return</b> or <b>break</b> statement in the middle
541 of another block (see <a href="#2.4.4">&sect;2.4.4</a>).
542
543
544
545
546
547 <h3>2.4.3 - <a name="2.4.3">Assignment</a></h3>
548
549 <p>
550 Lua allows multiple assignment.
551 Therefore, the syntax for assignment
552 defines a list of variables on the left side
553 and a list of expressions on the right side.
554 The elements in both lists are separated by commas:
555
556 <pre>
557         stat ::= varlist1 `<b>=</b>&acute; explist1
558         varlist1 ::= var {`<b>,</b>&acute; var}
559         explist1 ::= exp {`<b>,</b>&acute; exp}
560 </pre><p>
561 Expressions are discussed in <a href="#2.5">&sect;2.5</a>.
562
563
564 <p>
565 Before the assignment,
566 the list of values is <em>adjusted</em> to the length of
567 the list of variables.
568 If there are more values than needed,
569 the excess values are thrown away.
570 If there are fewer values than needed,
571 the list is extended with as many  <b>nil</b>'s as needed.
572 If the list of expressions ends with a function call,
573 then all values returned by this call enter in the list of values,
574 before the adjustment
575 (except when the call is enclosed in parentheses; see <a href="#2.5">&sect;2.5</a>).
576
577
578 <p>
579 The assignment statement first evaluates all its expressions
580 and only then are the assignments performed.
581 Thus the code
582
583 <pre>
584      i = 3
585      i, a[i] = i+1, 20
586 </pre><p>
587 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
588 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
589 before it is assigned&nbsp;4.
590 Similarly, the line
591
592 <pre>
593      x, y = y, x
594 </pre><p>
595 exchanges the values of <code>x</code> and <code>y</code>.
596
597
598 <p>
599 The meaning of assignments to global variables
600 and table fields can be changed via metatables.
601 An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
602 <code>settable_event(t,i,val)</code>.
603 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
604 <code>settable_event</code> function.
605 This function is not defined or callable in Lua.
606 We use it here only for explanatory purposes.)
607
608
609 <p>
610 An assignment to a global variable <code>x = val</code>
611 is equivalent to the assignment
612 <code>_env.x = val</code>,
613 which in turn is equivalent to
614
615 <pre>
616      settable_event(_env, "x", val)
617 </pre><p>
618 where <code>_env</code> is the environment of the running function.
619 (The <code>_env</code> variable is not defined in Lua.
620 We use it here only for explanatory purposes.)
621
622
623
624
625
626 <h3>2.4.4 - <a name="2.4.4">Control Structures</a></h3><p>
627 The control structures
628 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
629 familiar syntax:
630
631
632
633
634 <pre>
635         stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
636         stat ::= <b>repeat</b> block <b>until</b> exp
637         stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
638 </pre><p>
639 Lua also has a <b>for</b> statement, in two flavors (see <a href="#2.4.5">&sect;2.4.5</a>).
640
641
642 <p>
643 The condition expression of a
644 control structure may return any value.
645 Both <b>false</b> and <b>nil</b> are considered false.
646 All values different from <b>nil</b> and <b>false</b> are considered true
647 (in particular, the number 0 and the empty string are also true).
648
649
650 <p>
651 In the <b>repeat</b>&ndash;<b>until</b> loop,
652 the inner block does not end at the <b>until</b> keyword,
653 but only after the condition.
654 So, the condition can refer to local variables
655 declared inside the loop block.
656
657
658 <p>
659 The <b>return</b> statement is used to return values
660 from a function or a chunk (which is just a function).
661
662 Functions and chunks may return more than one value,
663 so the syntax for the <b>return</b> statement is
664
665 <pre>
666         stat ::= <b>return</b> [explist1]
667 </pre>
668
669 <p>
670 The <b>break</b> statement is used to terminate the execution of a
671 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
672 skipping to the next statement after the loop:
673
674
675 <pre>
676         stat ::= <b>break</b>
677 </pre><p>
678 A <b>break</b> ends the innermost enclosing loop.
679
680
681 <p>
682 The <b>return</b> and <b>break</b>
683 statements can only be written as the <em>last</em> statement of a block.
684 If it is really necessary to <b>return</b> or <b>break</b> in the
685 middle of a block,
686 then an explicit inner block can be used,
687 as in the idioms
688 <code>do return end</code> and <code>do break end</code>,
689 because now <b>return</b> and <b>break</b> are the last statements in
690 their (inner) blocks.
691
692
693
694
695
696 <h3>2.4.5 - <a name="2.4.5">For Statement</a></h3>
697
698 <p>
699
700 The <b>for</b> statement has two forms:
701 one numeric and one generic.
702
703
704 <p>
705 The numeric <b>for</b> loop repeats a block of code while a
706 control variable runs through an arithmetic progression.
707 It has the following syntax:
708
709 <pre>
710         stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
711 </pre><p>
712 The <em>block</em> is repeated for <em>name</em> starting at the value of
713 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
714 third <em>exp</em>.
715 More precisely, a <b>for</b> statement like
716
717 <pre>
718      for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
719 </pre><p>
720 is equivalent to the code:
721
722 <pre>
723      do
724        local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
725        if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
726        while (<em>step</em> &gt; 0 and <em>var</em> &lt;= <em>limit</em>) or (<em>step</em> &lt;= 0 and <em>var</em> &gt;= <em>limit</em>) do
727          local v = <em>var</em>
728          <em>block</em>
729          <em>var</em> = <em>var</em> + <em>step</em>
730        end
731      end
732 </pre><p>
733 Note the following:
734
735 <ul>
736
737 <li>
738 All three control expressions are evaluated only once,
739 before the loop starts.
740 They must all result in numbers.
741 </li>
742
743 <li>
744 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
745 The names are here for explanatory purposes only.
746 </li>
747
748 <li>
749 If the third expression (the step) is absent,
750 then a step of&nbsp;1 is used.
751 </li>
752
753 <li>
754 You can use <b>break</b> to exit a <b>for</b> loop.
755 </li>
756
757 <li>
758 The loop variable <code>v</code> is local to the loop;
759 you cannot use its value after the <b>for</b> ends or is broken.
760 If you need this value,
761 assign it to another variable before breaking or exiting the loop.
762 </li>
763
764 </ul>
765
766 <p>
767 The generic <b>for</b> statement works over functions,
768 called <em>iterators</em>.
769 On each iteration, the iterator function is called to produce a new value,
770 stopping when this new value is <b>nil</b>.
771 The generic <b>for</b> loop has the following syntax:
772
773 <pre>
774         stat ::= <b>for</b> namelist <b>in</b> explist1 <b>do</b> block <b>end</b>
775         namelist ::= Name {`<b>,</b>&acute; Name}
776 </pre><p>
777 A <b>for</b> statement like
778
779 <pre>
780      for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
781 </pre><p>
782 is equivalent to the code:
783
784 <pre>
785      do
786        local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
787        while true do
788          local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
789          <em>var</em> = <em>var_1</em>
790          if <em>var</em> == nil then break end
791          <em>block</em>
792        end
793      end
794 </pre><p>
795 Note the following:
796
797 <ul>
798
799 <li>
800 <code><em>explist</em></code> is evaluated only once.
801 Its results are an <em>iterator</em> function,
802 a <em>state</em>,
803 and an initial value for the first <em>iterator variable</em>.
804 </li>
805
806 <li>
807 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
808 The names are here for explanatory purposes only.
809 </li>
810
811 <li>
812 You can use <b>break</b> to exit a <b>for</b> loop.
813 </li>
814
815 <li>
816 The loop variables <code><em>var_i</em></code> are local to the loop;
817 you cannot use their values after the <b>for</b> ends.
818 If you need these values,
819 then assign them to other variables before breaking or exiting the loop.
820 </li>
821
822 </ul>
823
824
825
826
827 <h3>2.4.6 - <a name="2.4.6">Function Calls as Statements</a></h3><p>
828 To allow possible side-effects,
829 function calls can be executed as statements:
830
831 <pre>
832         stat ::= functioncall
833 </pre><p>
834 In this case, all returned values are thrown away.
835 Function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>.
836
837
838
839
840
841 <h3>2.4.7 - <a name="2.4.7">Local Declarations</a></h3><p>
842 Local variables may be declared anywhere inside a block.
843 The declaration may include an initial assignment:
844
845 <pre>
846         stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist1]
847 </pre><p>
848 If present, an initial assignment has the same semantics
849 of a multiple assignment (see <a href="#2.4.3">&sect;2.4.3</a>).
850 Otherwise, all variables are initialized with <b>nil</b>.
851
852
853 <p>
854 A chunk is also a block (see <a href="#2.4.1">&sect;2.4.1</a>),
855 and so local variables can be declared in a chunk outside any explicit block.
856 The scope of such local variables extends until the end of the chunk.
857
858
859 <p>
860 The visibility rules for local variables are explained in <a href="#2.6">&sect;2.6</a>.
861
862
863
864
865
866
867
868 <h2>2.5 - <a name="2.5">Expressions</a></h2>
869
870 <p>
871 The basic expressions in Lua are the following:
872
873 <pre>
874         exp ::= prefixexp
875         exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
876         exp ::= Number
877         exp ::= String
878         exp ::= function
879         exp ::= tableconstructor
880         exp ::= `<b>...</b>&acute;
881         exp ::= exp binop exp
882         exp ::= unop exp
883         prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
884 </pre>
885
886 <p>
887 Numbers and literal strings are explained in <a href="#2.1">&sect;2.1</a>;
888 variables are explained in <a href="#2.3">&sect;2.3</a>;
889 function definitions are explained in <a href="#2.5.9">&sect;2.5.9</a>;
890 function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>;
891 table constructors are explained in <a href="#2.5.7">&sect;2.5.7</a>.
892 Vararg expressions,
893 denoted by three dots ('<code>...</code>'), can only be used when
894 directly inside a vararg function;
895 they are explained in <a href="#2.5.9">&sect;2.5.9</a>.
896
897
898 <p>
899 Binary operators comprise arithmetic operators (see <a href="#2.5.1">&sect;2.5.1</a>),
900 relational operators (see <a href="#2.5.2">&sect;2.5.2</a>), logical operators (see <a href="#2.5.3">&sect;2.5.3</a>),
901 and the concatenation operator (see <a href="#2.5.4">&sect;2.5.4</a>).
902 Unary operators comprise the unary minus (see <a href="#2.5.1">&sect;2.5.1</a>),
903 the unary <b>not</b> (see <a href="#2.5.3">&sect;2.5.3</a>),
904 and the unary <em>length operator</em> (see <a href="#2.5.5">&sect;2.5.5</a>).
905
906
907 <p>
908 Both function calls and vararg expressions may result in multiple values.
909 If the expression is used as a statement (see <a href="#2.4.6">&sect;2.4.6</a>)
910 (only possible for function calls),
911 then its return list is adjusted to zero elements,
912 thus discarding all returned values.
913 If the expression is used as the last (or the only) element
914 of a list of expressions,
915 then no adjustment is made
916 (unless the call is enclosed in parentheses).
917 In all other contexts,
918 Lua adjusts the result list to one element,
919 discarding all values except the first one.
920
921
922 <p>
923 Here are some examples:
924
925 <pre>
926      f()                -- adjusted to 0 results
927      g(f(), x)          -- f() is adjusted to 1 result
928      g(x, f())          -- g gets x plus all results from f()
929      a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
930      a,b = ...          -- a gets the first vararg parameter, b gets
931                         -- the second (both a and b may get nil if there
932                         -- is no corresponding vararg parameter)
933      
934      a,b,c = x, f()     -- f() is adjusted to 2 results
935      a,b,c = f()        -- f() is adjusted to 3 results
936      return f()         -- returns all results from f()
937      return ...         -- returns all received vararg parameters
938      return x,y,f()     -- returns x, y, and all results from f()
939      {f()}              -- creates a list with all results from f()
940      {...}              -- creates a list with all vararg parameters
941      {f(), nil}         -- f() is adjusted to 1 result
942 </pre>
943
944 <p>
945 An expression enclosed in parentheses always results in only one value.
946 Thus,
947 <code>(f(x,y,z))</code> is always a single value,
948 even if <code>f</code> returns several values.
949 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
950 or <b>nil</b> if <code>f</code> does not return any values.)
951
952
953
954 <h3>2.5.1 - <a name="2.5.1">Arithmetic Operators</a></h3><p>
955 Lua supports the usual arithmetic operators:
956 the binary <code>+</code> (addition),
957 <code>-</code> (subtraction), <code>*</code> (multiplication),
958 <code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
959 and unary <code>-</code> (negation).
960 If the operands are numbers, or strings that can be converted to
961 numbers (see <a href="#2.2.1">&sect;2.2.1</a>),
962 then all operations have the usual meaning.
963 Exponentiation works for any exponent.
964 For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
965 Modulo is defined as
966
967 <pre>
968      a % b == a - math.floor(a/b)*b
969 </pre><p>
970 That is, it is the remainder of a division that rounds
971 the quotient towards minus infinity.
972
973
974
975
976
977 <h3>2.5.2 - <a name="2.5.2">Relational Operators</a></h3><p>
978 The relational operators in Lua are
979
980 <pre>
981      ==    ~=    &lt;     &gt;     &lt;=    &gt;=
982 </pre><p>
983 These operators always result in <b>false</b> or <b>true</b>.
984
985
986 <p>
987 Equality (<code>==</code>) first compares the type of its operands.
988 If the types are different, then the result is <b>false</b>.
989 Otherwise, the values of the operands are compared.
990 Numbers and strings are compared in the usual way.
991 Objects (tables, userdata, threads, and functions)
992 are compared by <em>reference</em>:
993 two objects are considered equal only if they are the <em>same</em> object.
994 Every time you create a new object
995 (a table, userdata, thread, or function),
996 this new object is different from any previously existing object.
997
998
999 <p>
1000 You can change the way that Lua compares tables and userdata 
1001 by using the "eq" metamethod (see <a href="#2.8">&sect;2.8</a>).
1002
1003
1004 <p>
1005 The conversion rules of <a href="#2.2.1">&sect;2.2.1</a>
1006 <em>do not</em> apply to equality comparisons.
1007 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
1008 and <code>t[0]</code> and <code>t["0"]</code> denote different
1009 entries in a table.
1010
1011
1012 <p>
1013 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
1014
1015
1016 <p>
1017 The order operators work as follows.
1018 If both arguments are numbers, then they are compared as such.
1019 Otherwise, if both arguments are strings,
1020 then their values are compared according to the current locale.
1021 Otherwise, Lua tries to call the "lt" or the "le"
1022 metamethod (see <a href="#2.8">&sect;2.8</a>).
1023
1024
1025
1026
1027
1028 <h3>2.5.3 - <a name="2.5.3">Logical Operators</a></h3><p>
1029 The logical operators in Lua are
1030 <b>and</b>, <b>or</b>, and <b>not</b>.
1031 Like the control structures (see <a href="#2.4.4">&sect;2.4.4</a>),
1032 all logical operators consider both <b>false</b> and <b>nil</b> as false
1033 and anything else as true.
1034
1035
1036 <p>
1037 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
1038 The conjunction operator <b>and</b> returns its first argument
1039 if this value is <b>false</b> or <b>nil</b>;
1040 otherwise, <b>and</b> returns its second argument.
1041 The disjunction operator <b>or</b> returns its first argument
1042 if this value is different from <b>nil</b> and <b>false</b>;
1043 otherwise, <b>or</b> returns its second argument.
1044 Both <b>and</b> and <b>or</b> use short-cut evaluation;
1045 that is,
1046 the second operand is evaluated only if necessary.
1047 Here are some examples:
1048
1049 <pre>
1050      10 or 20            --&gt; 10
1051      10 or error()       --&gt; 10
1052      nil or "a"          --&gt; "a"
1053      nil and 10          --&gt; nil
1054      false and error()   --&gt; false
1055      false and nil       --&gt; false
1056      false or nil        --&gt; nil
1057      10 and 20           --&gt; 20
1058 </pre><p>
1059 (In this manual,
1060 --> indicates the result of the preceding expression.)
1061
1062
1063
1064
1065
1066 <h3>2.5.4 - <a name="2.5.4">Concatenation</a></h3><p>
1067 The string concatenation operator in Lua is
1068 denoted by two dots ('<code>..</code>').
1069 If both operands are strings or numbers, then they are converted to
1070 strings according to the rules mentioned in <a href="#2.2.1">&sect;2.2.1</a>.
1071 Otherwise, the "concat" metamethod is called (see <a href="#2.8">&sect;2.8</a>).
1072
1073
1074
1075
1076
1077 <h3>2.5.5 - <a name="2.5.5">The Length Operator</a></h3>
1078
1079 <p>
1080 The length operator is denoted by the unary operator <code>#</code>.
1081 The length of a string is its number of bytes
1082 (that is, the usual meaning of string length when each
1083 character is one byte).
1084
1085
1086 <p>
1087 The length of a table <code>t</code> is defined to be any
1088 integer index <code>n</code>
1089 such that <code>t[n]</code> is not <b>nil</b> and <code>t[n+1]</code> is <b>nil</b>;
1090 moreover, if <code>t[1]</code> is <b>nil</b>, <code>n</code> may be zero.
1091 For a regular array, with non-nil values from 1 to a given <code>n</code>,
1092 its length is exactly that <code>n</code>,
1093 the index of its last value.
1094 If the array has "holes"
1095 (that is, <b>nil</b> values between other non-nil values),
1096 then <code>#t</code> may be any of the indices that
1097 directly precedes a <b>nil</b> value
1098 (that is, it may consider any such <b>nil</b> value as the end of
1099 the array). 
1100
1101
1102
1103
1104
1105 <h3>2.5.6 - <a name="2.5.6">Precedence</a></h3><p>
1106 Operator precedence in Lua follows the table below,
1107 from lower to higher priority:
1108
1109 <pre>
1110      or
1111      and
1112      &lt;     &gt;     &lt;=    &gt;=    ~=    ==
1113      ..
1114      +     -
1115      *     /     %
1116      not   #     - (unary)
1117      ^
1118 </pre><p>
1119 As usual,
1120 you can use parentheses to change the precedences of an expression.
1121 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
1122 operators are right associative.
1123 All other binary operators are left associative.
1124
1125
1126
1127
1128
1129 <h3>2.5.7 - <a name="2.5.7">Table Constructors</a></h3><p>
1130 Table constructors are expressions that create tables.
1131 Every time a constructor is evaluated, a new table is created.
1132 Constructors can be used to create empty tables,
1133 or to create a table and initialize some of its fields.
1134 The general syntax for constructors is
1135
1136 <pre>
1137         tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
1138         fieldlist ::= field {fieldsep field} [fieldsep]
1139         field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
1140         fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
1141 </pre>
1142
1143 <p>
1144 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
1145 with key <code>exp1</code> and value <code>exp2</code>.
1146 A field of the form <code>name = exp</code> is equivalent to
1147 <code>["name"] = exp</code>.
1148 Finally, fields of the form <code>exp</code> are equivalent to
1149 <code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
1150 starting with 1.
1151 Fields in the other formats do not affect this counting.
1152 For example,
1153
1154 <pre>
1155      a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
1156 </pre><p>
1157 is equivalent to
1158
1159 <pre>
1160      do
1161        local t = {}
1162        t[f(1)] = g
1163        t[1] = "x"         -- 1st exp
1164        t[2] = "y"         -- 2nd exp
1165        t.x = 1            -- t["x"] = 1
1166        t[3] = f(x)        -- 3rd exp
1167        t[30] = 23
1168        t[4] = 45          -- 4th exp
1169        a = t
1170      end
1171 </pre>
1172
1173 <p>
1174 If the last field in the list has the form <code>exp</code>
1175 and the expression is a function call or a vararg expression,
1176 then all values returned by this expression enter the list consecutively
1177 (see <a href="#2.5.8">&sect;2.5.8</a>).
1178 To avoid this,
1179 enclose the function call (or the vararg expression)
1180 in parentheses (see <a href="#2.5">&sect;2.5</a>).
1181
1182
1183 <p>
1184 The field list may have an optional trailing separator,
1185 as a convenience for machine-generated code.
1186
1187
1188
1189
1190
1191 <h3>2.5.8 - <a name="2.5.8">Function Calls</a></h3><p>
1192 A function call in Lua has the following syntax:
1193
1194 <pre>
1195         functioncall ::= prefixexp args
1196 </pre><p>
1197 In a function call,
1198 first prefixexp and args are evaluated.
1199 If the value of prefixexp has type <em>function</em>,
1200 then this function is called
1201 with the given arguments.
1202 Otherwise, the prefixexp "call" metamethod is called,
1203 having as first parameter the value of prefixexp,
1204 followed by the original call arguments
1205 (see <a href="#2.8">&sect;2.8</a>).
1206
1207
1208 <p>
1209 The form
1210
1211 <pre>
1212         functioncall ::= prefixexp `<b>:</b>&acute; Name args
1213 </pre><p>
1214 can be used to call "methods".
1215 A call <code>v:name(<em>args</em>)</code>
1216 is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
1217 except that <code>v</code> is evaluated only once.
1218
1219
1220 <p>
1221 Arguments have the following syntax:
1222
1223 <pre>
1224         args ::= `<b>(</b>&acute; [explist1] `<b>)</b>&acute;
1225         args ::= tableconstructor
1226         args ::= String
1227 </pre><p>
1228 All argument expressions are evaluated before the call.
1229 A call of the form <code>f{<em>fields</em>}</code> is
1230 syntactic sugar for <code>f({<em>fields</em>})</code>;
1231 that is, the argument list is a single new table.
1232 A call of the form <code>f'<em>string</em>'</code>
1233 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
1234 is syntactic sugar for <code>f('<em>string</em>')</code>;
1235 that is, the argument list is a single literal string.
1236
1237
1238 <p>
1239 As an exception to the free-format syntax of Lua,
1240 you cannot put a line break before the '<code>(</code>' in a function call.
1241 This restriction avoids some ambiguities in the language.
1242 If you write
1243
1244 <pre>
1245      a = f
1246      (g).x(a)
1247 </pre><p>
1248 Lua would see that as a single statement, <code>a = f(g).x(a)</code>.
1249 So, if you want two statements, you must add a semi-colon between them.
1250 If you actually want to call <code>f</code>,
1251 you must remove the line break before <code>(g)</code>.
1252
1253
1254 <p>
1255 A call of the form <code>return</code> <em>functioncall</em> is called
1256 a <em>tail call</em>.
1257 Lua implements <em>proper tail calls</em>
1258 (or <em>proper tail recursion</em>):
1259 in a tail call,
1260 the called function reuses the stack entry of the calling function.
1261 Therefore, there is no limit on the number of nested tail calls that
1262 a program can execute.
1263 However, a tail call erases any debug information about the
1264 calling function.
1265 Note that a tail call only happens with a particular syntax,
1266 where the <b>return</b> has one single function call as argument;
1267 this syntax makes the calling function return exactly
1268 the returns of the called function.
1269 So, none of the following examples are tail calls:
1270
1271 <pre>
1272      return (f(x))        -- results adjusted to 1
1273      return 2 * f(x)
1274      return x, f(x)       -- additional results
1275      f(x); return         -- results discarded
1276      return x or f(x)     -- results adjusted to 1
1277 </pre>
1278
1279
1280
1281
1282 <h3>2.5.9 - <a name="2.5.9">Function Definitions</a></h3>
1283
1284 <p>
1285 The syntax for function definition is
1286
1287 <pre>
1288         function ::= <b>function</b> funcbody
1289         funcbody ::= `<b>(</b>&acute; [parlist1] `<b>)</b>&acute; block <b>end</b>
1290 </pre>
1291
1292 <p>
1293 The following syntactic sugar simplifies function definitions:
1294
1295 <pre>
1296         stat ::= <b>function</b> funcname funcbody
1297         stat ::= <b>local</b> <b>function</b> Name funcbody
1298         funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
1299 </pre><p>
1300 The statement
1301
1302 <pre>
1303      function f () <em>body</em> end
1304 </pre><p>
1305 translates to
1306
1307 <pre>
1308      f = function () <em>body</em> end
1309 </pre><p>
1310 The statement
1311
1312 <pre>
1313      function t.a.b.c.f () <em>body</em> end
1314 </pre><p>
1315 translates to
1316
1317 <pre>
1318      t.a.b.c.f = function () <em>body</em> end
1319 </pre><p>
1320 The statement
1321
1322 <pre>
1323      local function f () <em>body</em> end
1324 </pre><p>
1325 translates to
1326
1327 <pre>
1328      local f; f = function () <em>body</em> end
1329 </pre><p>
1330 <em>not</em> to
1331
1332 <pre>
1333      local f = function () <em>body</em> end
1334 </pre><p>
1335 (This only makes a difference when the body of the function
1336 contains references to <code>f</code>.)
1337
1338
1339 <p>
1340 A function definition is an executable expression,
1341 whose value has type <em>function</em>.
1342 When Lua pre-compiles a chunk,
1343 all its function bodies are pre-compiled too.
1344 Then, whenever Lua executes the function definition,
1345 the function is <em>instantiated</em> (or <em>closed</em>).
1346 This function instance (or <em>closure</em>)
1347 is the final value of the expression.
1348 Different instances of the same function
1349 may refer to different  external local variables
1350 and may have different environment tables.
1351
1352
1353 <p>
1354 Parameters act as local variables that are
1355 initialized with the argument values:
1356
1357 <pre>
1358         parlist1 ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
1359 </pre><p>
1360 When a function is called,
1361 the list of arguments is adjusted to
1362 the length of the list of parameters,
1363 unless the function is a variadic or <em>vararg function</em>,
1364 which is
1365 indicated by three dots ('<code>...</code>') at the end of its parameter list.
1366 A vararg function does not adjust its argument list;
1367 instead, it collects all extra arguments and supplies them
1368 to the function through a <em>vararg expression</em>,
1369 which is also written as three dots.
1370 The value of this expression is a list of all actual extra arguments,
1371 similar to a function with multiple results.
1372 If a vararg expression is used inside another expression
1373 or in the middle of a list of expressions,
1374 then its return list is adjusted to one element.
1375 If the expression is used as the last element of a list of expressions,
1376 then no adjustment is made
1377 (unless the call is enclosed in parentheses).
1378
1379
1380 <p>
1381 As an example, consider the following definitions:
1382
1383 <pre>
1384      function f(a, b) end
1385      function g(a, b, ...) end
1386      function r() return 1,2,3 end
1387 </pre><p>
1388 Then, we have the following mapping from arguments to parameters and
1389 to the vararg expression:
1390
1391 <pre>
1392      CALL            PARAMETERS
1393      
1394      f(3)             a=3, b=nil
1395      f(3, 4)          a=3, b=4
1396      f(3, 4, 5)       a=3, b=4
1397      f(r(), 10)       a=1, b=10
1398      f(r())           a=1, b=2
1399      
1400      g(3)             a=3, b=nil, ... --&gt;  (nothing)
1401      g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
1402      g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
1403      g(5, r())        a=5, b=1,   ... --&gt;  2  3
1404 </pre>
1405
1406 <p>
1407 Results are returned using the <b>return</b> statement (see <a href="#2.4.4">&sect;2.4.4</a>).
1408 If control reaches the end of a function
1409 without encountering a <b>return</b> statement,
1410 then the function returns with no results.
1411
1412
1413 <p>
1414 The <em>colon</em> syntax
1415 is used for defining <em>methods</em>,
1416 that is, functions that have an implicit extra parameter <code>self</code>.
1417 Thus, the statement
1418
1419 <pre>
1420      function t.a.b.c:f (<em>params</em>) <em>body</em> end
1421 </pre><p>
1422 is syntactic sugar for
1423
1424 <pre>
1425      t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
1426 </pre>
1427
1428
1429
1430
1431
1432
1433 <h2>2.6 - <a name="2.6">Visibility Rules</a></h2>
1434
1435 <p>
1436
1437 Lua is a lexically scoped language.
1438 The scope of variables begins at the first statement <em>after</em>
1439 their declaration and lasts until the end of the innermost block that
1440 includes the declaration.
1441 Consider the following example:
1442
1443 <pre>
1444      x = 10                -- global variable
1445      do                    -- new block
1446        local x = x         -- new 'x', with value 10
1447        print(x)            --&gt; 10
1448        x = x+1
1449        do                  -- another block
1450          local x = x+1     -- another 'x'
1451          print(x)          --&gt; 12
1452        end
1453        print(x)            --&gt; 11
1454      end
1455      print(x)              --&gt; 10  (the global one)
1456 </pre>
1457
1458 <p>
1459 Notice that, in a declaration like <code>local x = x</code>,
1460 the new <code>x</code> being declared is not in scope yet,
1461 and so the second <code>x</code> refers to the outside variable.
1462
1463
1464 <p>
1465 Because of the lexical scoping rules,
1466 local variables can be freely accessed by functions
1467 defined inside their scope.
1468 A local variable used by an inner function is called
1469 an <em>upvalue</em>, or <em>external local variable</em>,
1470 inside the inner function.
1471
1472
1473 <p>
1474 Notice that each execution of a <b>local</b> statement
1475 defines new local variables.
1476 Consider the following example:
1477
1478 <pre>
1479      a = {}
1480      local x = 20
1481      for i=1,10 do
1482        local y = 0
1483        a[i] = function () y=y+1; return x+y end
1484      end
1485 </pre><p>
1486 The loop creates ten closures
1487 (that is, ten instances of the anonymous function).
1488 Each of these closures uses a different <code>y</code> variable,
1489 while all of them share the same <code>x</code>.
1490
1491
1492
1493
1494
1495 <h2>2.7 - <a name="2.7">Error Handling</a></h2>
1496
1497 <p>
1498 Because Lua is an embedded extension language,
1499 all Lua actions start from C&nbsp;code in the host program
1500 calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
1501 Whenever an error occurs during Lua compilation or execution,
1502 control returns to C,
1503 which can take appropriate measures
1504 (such as printing an error message).
1505
1506
1507 <p>
1508 Lua code can explicitly generate an error by calling the
1509 <a href="#pdf-error"><code>error</code></a> function.
1510 If you need to catch errors in Lua,
1511 you can use the <a href="#pdf-pcall"><code>pcall</code></a> function.
1512
1513
1514
1515
1516
1517 <h2>2.8 - <a name="2.8">Metatables</a></h2>
1518
1519 <p>
1520 Every value in Lua may have a <em>metatable</em>.
1521 This <em>metatable</em> is an ordinary Lua table
1522 that defines the behavior of the original value
1523 under certain special operations.
1524 You can change several aspects of the behavior
1525 of operations over a value by setting specific fields in its metatable.
1526 For instance, when a non-numeric value is the operand of an addition,
1527 Lua checks for a function in the field <code>"__add"</code> in its metatable.
1528 If it finds one,
1529 Lua calls this function to perform the addition.
1530
1531
1532 <p>
1533 We call the keys in a metatable <em>events</em>
1534 and the values <em>metamethods</em>.
1535 In the previous example, the event is <code>"add"</code> 
1536 and the metamethod is the function that performs the addition.
1537
1538
1539 <p>
1540 You can query the metatable of any value
1541 through the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
1542
1543
1544 <p>
1545 You can replace the metatable of tables
1546 through the <a href="#pdf-setmetatable"><code>setmetatable</code></a>
1547 function.
1548 You cannot change the metatable of other types from Lua
1549 (except using the debug library);
1550 you must use the C&nbsp;API for that.
1551
1552
1553 <p>
1554 Tables and userdata have individual metatables
1555 (although multiple tables and userdata can share their metatables);
1556 values of all other types share one single metatable per type.
1557 So, there is one single metatable for all numbers,
1558 and for all strings, etc.
1559
1560
1561 <p>
1562 A metatable may control how an object behaves in arithmetic operations,
1563 order comparisons, concatenation, length operation, and indexing.
1564 A metatable can also define a function to be called when a userdata
1565 is garbage collected.
1566 For each of these operations Lua associates a specific key
1567 called an <em>event</em>.
1568 When Lua performs one of these operations over a value,
1569 it checks whether this value has a metatable with the corresponding event.
1570 If so, the value associated with that key (the metamethod)
1571 controls how Lua will perform the operation.
1572
1573
1574 <p>
1575 Metatables control the operations listed next.
1576 Each operation is identified by its corresponding name.
1577 The key for each operation is a string with its name prefixed by
1578 two underscores, '<code>__</code>';
1579 for instance, the key for operation "add" is the
1580 string <code>"__add"</code>.
1581 The semantics of these operations is better explained by a Lua function
1582 describing how the interpreter executes the operation.
1583
1584
1585 <p>
1586 The code shown here in Lua is only illustrative;
1587 the real behavior is hard coded in the interpreter
1588 and it is much more efficient than this simulation.
1589 All functions used in these descriptions
1590 (<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
1591 are described in <a href="#5.1">&sect;5.1</a>.
1592 In particular, to retrieve the metamethod of a given object,
1593 we use the expression
1594
1595 <pre>
1596      metatable(obj)[event]
1597 </pre><p>
1598 This should be read as
1599
1600 <pre>
1601      rawget(getmetatable(obj) or {}, event)
1602 </pre><p>
1603
1604 That is, the access to a metamethod does not invoke other metamethods,
1605 and the access to objects with no metatables does not fail
1606 (it simply results in <b>nil</b>).
1607
1608
1609
1610 <ul>
1611
1612 <li><b>"add":</b>
1613 the <code>+</code> operation.
1614
1615
1616
1617 <p>
1618 The function <code>getbinhandler</code> below defines how Lua chooses a handler
1619 for a binary operation.
1620 First, Lua tries the first operand.
1621 If its type does not define a handler for the operation,
1622 then Lua tries the second operand.
1623
1624 <pre>
1625      function getbinhandler (op1, op2, event)
1626        return metatable(op1)[event] or metatable(op2)[event]
1627      end
1628 </pre><p>
1629 By using this function,
1630 the behavior of the <code>op1 + op2</code> is
1631
1632 <pre>
1633      function add_event (op1, op2)
1634        local o1, o2 = tonumber(op1), tonumber(op2)
1635        if o1 and o2 then  -- both operands are numeric?
1636          return o1 + o2   -- '+' here is the primitive 'add'
1637        else  -- at least one of the operands is not numeric
1638          local h = getbinhandler(op1, op2, "__add")
1639          if h then
1640            -- call the handler with both operands
1641            return h(op1, op2)
1642          else  -- no handler available: default behavior
1643            error(&middot;&middot;&middot;)
1644          end
1645        end
1646      end
1647 </pre><p>
1648 </li>
1649
1650 <li><b>"sub":</b>
1651 the <code>-</code> operation.
1652
1653 Behavior similar to the "add" operation.
1654 </li>
1655
1656 <li><b>"mul":</b>
1657 the <code>*</code> operation.
1658
1659 Behavior similar to the "add" operation.
1660 </li>
1661
1662 <li><b>"div":</b>
1663 the <code>/</code> operation.
1664
1665 Behavior similar to the "add" operation.
1666 </li>
1667
1668 <li><b>"mod":</b>
1669 the <code>%</code> operation.
1670
1671 Behavior similar to the "add" operation,
1672 with the operation
1673 <code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
1674 </li>
1675
1676 <li><b>"pow":</b>
1677 the <code>^</code> (exponentiation) operation.
1678
1679 Behavior similar to the "add" operation,
1680 with the function <code>pow</code> (from the C&nbsp;math library)
1681 as the primitive operation.
1682 </li>
1683
1684 <li><b>"unm":</b>
1685 the unary <code>-</code> operation.
1686
1687
1688 <pre>
1689      function unm_event (op)
1690        local o = tonumber(op)
1691        if o then  -- operand is numeric?
1692          return -o  -- '-' here is the primitive 'unm'
1693        else  -- the operand is not numeric.
1694          -- Try to get a handler from the operand
1695          local h = metatable(op).__unm
1696          if h then
1697            -- call the handler with the operand
1698            return h(op)
1699          else  -- no handler available: default behavior
1700            error(&middot;&middot;&middot;)
1701          end
1702        end
1703      end
1704 </pre><p>
1705 </li>
1706
1707 <li><b>"concat":</b>
1708 the <code>..</code> (concatenation) operation.
1709
1710
1711 <pre>
1712      function concat_event (op1, op2)
1713        if (type(op1) == "string" or type(op1) == "number") and
1714           (type(op2) == "string" or type(op2) == "number") then
1715          return op1 .. op2  -- primitive string concatenation
1716        else
1717          local h = getbinhandler(op1, op2, "__concat")
1718          if h then
1719            return h(op1, op2)
1720          else
1721            error(&middot;&middot;&middot;)
1722          end
1723        end
1724      end
1725 </pre><p>
1726 </li>
1727
1728 <li><b>"len":</b>
1729 the <code>#</code> operation.
1730
1731
1732 <pre>
1733      function len_event (op)
1734        if type(op) == "string" then
1735          return strlen(op)         -- primitive string length
1736        elseif type(op) == "table" then
1737          return #op                -- primitive table length
1738        else
1739          local h = metatable(op).__len
1740          if h then
1741            -- call the handler with the operand
1742            return h(op)
1743          else  -- no handler available: default behavior
1744            error(&middot;&middot;&middot;)
1745          end
1746        end
1747      end
1748 </pre><p>
1749 See <a href="#2.5.5">&sect;2.5.5</a> for a description of the length of a table.
1750 </li>
1751
1752 <li><b>"eq":</b>
1753 the <code>==</code> operation.
1754
1755 The function <code>getcomphandler</code> defines how Lua chooses a metamethod
1756 for comparison operators.
1757 A metamethod only is selected when both objects
1758 being compared have the same type
1759 and the same metamethod for the selected operation.
1760
1761 <pre>
1762      function getcomphandler (op1, op2, event)
1763        if type(op1) ~= type(op2) then return nil end
1764        local mm1 = metatable(op1)[event]
1765        local mm2 = metatable(op2)[event]
1766        if mm1 == mm2 then return mm1 else return nil end
1767      end
1768 </pre><p>
1769 The "eq" event is defined as follows:
1770
1771 <pre>
1772      function eq_event (op1, op2)
1773        if type(op1) ~= type(op2) then  -- different types?
1774          return false   -- different objects
1775        end
1776        if op1 == op2 then   -- primitive equal?
1777          return true   -- objects are equal
1778        end
1779        -- try metamethod
1780        local h = getcomphandler(op1, op2, "__eq")
1781        if h then
1782          return h(op1, op2)
1783        else
1784          return false
1785        end
1786      end
1787 </pre><p>
1788 <code>a ~= b</code> is equivalent to <code>not (a == b)</code>.
1789 </li>
1790
1791 <li><b>"lt":</b>
1792 the <code>&lt;</code> operation.
1793
1794
1795 <pre>
1796      function lt_event (op1, op2)
1797        if type(op1) == "number" and type(op2) == "number" then
1798          return op1 &lt; op2   -- numeric comparison
1799        elseif type(op1) == "string" and type(op2) == "string" then
1800          return op1 &lt; op2   -- lexicographic comparison
1801        else
1802          local h = getcomphandler(op1, op2, "__lt")
1803          if h then
1804            return h(op1, op2)
1805          else
1806            error(&middot;&middot;&middot;);
1807          end
1808        end
1809      end
1810 </pre><p>
1811 <code>a &gt; b</code> is equivalent to <code>b &lt; a</code>.
1812 </li>
1813
1814 <li><b>"le":</b>
1815 the <code>&lt;=</code> operation.
1816
1817
1818 <pre>
1819      function le_event (op1, op2)
1820        if type(op1) == "number" and type(op2) == "number" then
1821          return op1 &lt;= op2   -- numeric comparison
1822        elseif type(op1) == "string" and type(op2) == "string" then
1823          return op1 &lt;= op2   -- lexicographic comparison
1824        else
1825          local h = getcomphandler(op1, op2, "__le")
1826          if h then
1827            return h(op1, op2)
1828          else
1829            h = getcomphandler(op1, op2, "__lt")
1830            if h then
1831              return not h(op2, op1)
1832            else
1833              error(&middot;&middot;&middot;);
1834            end
1835          end
1836        end
1837      end
1838 </pre><p>
1839 <code>a &gt;= b</code> is equivalent to <code>b &lt;= a</code>.
1840 Note that, in the absence of a "le" metamethod,
1841 Lua tries the "lt", assuming that <code>a &lt;= b</code> is
1842 equivalent to <code>not (b &lt; a)</code>.
1843 </li>
1844
1845 <li><b>"index":</b>
1846 The indexing access <code>table[key]</code>.
1847
1848
1849 <pre>
1850      function gettable_event (table, key)
1851        local h
1852        if type(table) == "table" then
1853          local v = rawget(table, key)
1854          if v ~= nil then return v end
1855          h = metatable(table).__index
1856          if h == nil then return nil end
1857        else
1858          h = metatable(table).__index
1859          if h == nil then
1860            error(&middot;&middot;&middot;);
1861          end
1862        end
1863        if type(h) == "function" then
1864          return h(table, key)      -- call the handler
1865        else return h[key]          -- or repeat operation on it
1866        end
1867      end
1868 </pre><p>
1869 </li>
1870
1871 <li><b>"newindex":</b>
1872 The indexing assignment <code>table[key] = value</code>.
1873
1874
1875 <pre>
1876      function settable_event (table, key, value)
1877        local h
1878        if type(table) == "table" then
1879          local v = rawget(table, key)
1880          if v ~= nil then rawset(table, key, value); return end
1881          h = metatable(table).__newindex
1882          if h == nil then rawset(table, key, value); return end
1883        else
1884          h = metatable(table).__newindex
1885          if h == nil then
1886            error(&middot;&middot;&middot;);
1887          end
1888        end
1889        if type(h) == "function" then
1890          return h(table, key,value)    -- call the handler
1891        else h[key] = value             -- or repeat operation on it
1892        end
1893      end
1894 </pre><p>
1895 </li>
1896
1897 <li><b>"call":</b>
1898 called when Lua calls a value.
1899
1900
1901 <pre>
1902      function function_event (func, ...)
1903        if type(func) == "function" then
1904          return func(...)   -- primitive call
1905        else
1906          local h = metatable(func).__call
1907          if h then
1908            return h(func, ...)
1909          else
1910            error(&middot;&middot;&middot;)
1911          end
1912        end
1913      end
1914 </pre><p>
1915 </li>
1916
1917 </ul>
1918
1919
1920
1921
1922 <h2>2.9 - <a name="2.9">Environments</a></h2>
1923
1924 <p>
1925 Besides metatables,
1926 objects of types thread, function, and userdata
1927 have another table associated with them,
1928 called their <em>environment</em>.
1929 Like metatables, environments are regular tables and
1930 multiple objects can share the same environment.
1931
1932
1933 <p>
1934 Environments associated with userdata have no meaning for Lua.
1935 It is only a convenience feature for programmers to associate a table to
1936 a userdata.
1937
1938
1939 <p>
1940 Environments associated with threads are called
1941 <em>global environments</em>.
1942 They are used as the default environment for their threads and
1943 non-nested functions created by the thread
1944 (through <a href="#pdf-loadfile"><code>loadfile</code></a>, <a href="#pdf-loadstring"><code>loadstring</code></a> or <a href="#pdf-load"><code>load</code></a>)
1945 and can be directly accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1946
1947
1948 <p>
1949 Environments associated with C&nbsp;functions can be directly
1950 accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1951 They are used as the default environment for other C&nbsp;functions
1952 created by the function.
1953
1954
1955 <p>
1956 Environments associated with Lua functions are used to resolve
1957 all accesses to global variables within the function (see <a href="#2.3">&sect;2.3</a>).
1958 They are used as the default environment for other Lua functions
1959 created by the function.
1960
1961
1962 <p>
1963 You can change the environment of a Lua function or the
1964 running thread by calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
1965 You can get the environment of a Lua function or the running thread
1966 by calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
1967 To manipulate the environment of other objects
1968 (userdata, C&nbsp;functions, other threads) you must
1969 use the C&nbsp;API.
1970
1971
1972
1973
1974
1975 <h2>2.10 - <a name="2.10">Garbage Collection</a></h2>
1976
1977 <p>
1978 Lua performs automatic memory management.
1979 This means that
1980 you have to worry neither about allocating memory for new objects
1981 nor about freeing it when the objects are no longer needed.
1982 Lua manages memory automatically by running
1983 a <em>garbage collector</em> from time to time
1984 to collect all <em>dead objects</em>
1985 (that is, these objects that are no longer accessible from Lua).
1986 All objects in Lua are subject to automatic management:
1987 tables, userdata, functions, threads, and strings.
1988
1989
1990 <p>
1991 Lua implements an incremental mark-and-sweep collector.
1992 It uses two numbers to control its garbage-collection cycles:
1993 the <em>garbage-collector pause</em> and
1994 the <em>garbage-collector step multiplier</em>.
1995
1996
1997 <p>
1998 The garbage-collector pause
1999 controls how long the collector waits before starting a new cycle.
2000 Larger values make the collector less aggressive.
2001 Values smaller than 1 mean the collector will not wait to
2002 start a new cycle.
2003 A value of 2 means that the collector waits for the total memory in use
2004 to double before starting a new cycle.
2005
2006
2007 <p>
2008 The step multiplier
2009 controls the relative speed of the collector relative to
2010 memory allocation.
2011 Larger values make the collector more aggressive but also increase
2012 the size of each incremental step.
2013 Values smaller than 1 make the collector too slow and
2014 may result in  the collector never finishing a cycle.
2015 The default, 2, means that the collector runs at "twice"
2016 the speed of memory allocation.
2017
2018
2019 <p>
2020 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
2021 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
2022 Both get percentage points as arguments
2023 (so an argument of 100 means a real value of 1).
2024 With these functions you can also control 
2025 the collector directly (e.g., stop and restart it).
2026
2027
2028
2029 <h3>2.10.1 - <a name="2.10.1">Garbage-Collection Metamethods</a></h3>
2030
2031 <p>
2032 Using the C&nbsp;API,
2033 you can set garbage-collector metamethods for userdata (see <a href="#2.8">&sect;2.8</a>).
2034 These metamethods are also called <em>finalizers</em>.
2035 Finalizers allow you to coordinate Lua's garbage collection
2036 with external resource management
2037 (such as closing files, network or database connections,
2038 or freeing your own memory).
2039
2040
2041 <p>
2042 Garbage userdata with a field <code>__gc</code> in their metatables are not
2043 collected immediately by the garbage collector.
2044 Instead, Lua puts them in a list.
2045 After the collection,
2046 Lua does the equivalent of the following function
2047 for each userdata in that list:
2048
2049 <pre>
2050      function gc_event (udata)
2051        local h = metatable(udata).__gc
2052        if h then
2053          h(udata)
2054        end
2055      end
2056 </pre>
2057
2058 <p>
2059 At the end of each garbage-collection cycle,
2060 the finalizers for userdata are called in <em>reverse</em>
2061 order of their creation,
2062 among those collected in that cycle.
2063 That is, the first finalizer to be called is the one associated
2064 with the userdata created last in the program.
2065
2066
2067
2068
2069
2070 <h3>2.10.2 - <a name="2.10.2">Weak Tables</a></h3>
2071
2072 <p>
2073 A <em>weak table</em> is a table whose elements are
2074 <em>weak references</em>.
2075 A weak reference is ignored by the garbage collector.
2076 In other words,
2077 if the only references to an object are weak references,
2078 then the garbage collector will collect this object.
2079
2080
2081 <p>
2082 A weak table can have weak keys, weak values, or both.
2083 A table with weak keys allows the collection of its keys,
2084 but prevents the collection of its values.
2085 A table with both weak keys and weak values allows the collection of
2086 both keys and values.
2087 In any case, if either the key or the value is collected,
2088 the whole pair is removed from the table.
2089 The weakness of a table is controlled by the
2090 <code>__mode</code> field of its metatable.
2091 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
2092 the keys in the table are weak.
2093 If <code>__mode</code> contains '<code>v</code>',
2094 the values in the table are weak.
2095
2096
2097 <p>
2098 After you use a table as a metatable,
2099 you should not change the value of its field <code>__mode</code>.
2100 Otherwise, the weak behavior of the tables controlled by this
2101 metatable is undefined.
2102
2103
2104
2105
2106
2107
2108
2109 <h2>2.11 - <a name="2.11">Coroutines</a></h2>
2110
2111 <p>
2112 Lua supports coroutines,
2113 also called <em>collaborative multithreading</em>.
2114 A coroutine in Lua represents an independent thread of execution.
2115 Unlike threads in multithread systems, however,
2116 a coroutine only suspends its execution by explicitly calling
2117 a yield function.
2118
2119
2120 <p>
2121 You create a coroutine with a call to <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
2122 Its sole argument is a function
2123 that is the main function of the coroutine.
2124 The <code>create</code> function only creates a new coroutine and
2125 returns a handle to it (an object of type <em>thread</em>);
2126 it does not start the coroutine execution.
2127
2128
2129 <p>
2130 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2131 passing as its first argument
2132 the thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2133 the coroutine starts its execution,
2134 at the first line of its main function.
2135 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
2136 to the coroutine main function.
2137 After the coroutine starts running,
2138 it runs until it terminates or <em>yields</em>.
2139
2140
2141 <p>
2142 A coroutine can terminate its execution in two ways:
2143 normally, when its main function returns
2144 (explicitly or implicitly, after the last instruction);
2145 and abnormally, if there is an unprotected error.
2146 In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
2147 plus any values returned by the coroutine main function.
2148 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
2149 plus an error message.
2150
2151
2152 <p>
2153 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2154 When a coroutine yields,
2155 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
2156 even if the yield happens inside nested function calls
2157 (that is, not in the main function,
2158 but in a function directly or indirectly called by the main function).
2159 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
2160 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2161 The next time you resume the same coroutine,
2162 it continues its execution from the point where it yielded,
2163 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
2164 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2165
2166
2167 <p>
2168 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2169 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
2170 but instead of returning the coroutine itself,
2171 it returns a function that, when called, resumes the coroutine.
2172 Any arguments passed to this function
2173 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2174 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2175 except the first one (the boolean error code).
2176 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2177 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
2178 any error is propagated to the caller.
2179
2180
2181 <p>
2182 As an example,
2183 consider the following code:
2184
2185 <pre>
2186      function foo (a)
2187        print("foo", a)
2188        return coroutine.yield(2*a)
2189      end
2190      
2191      co = coroutine.create(function (a,b)
2192            print("co-body", a, b)
2193            local r = foo(a+1)
2194            print("co-body", r)
2195            local r, s = coroutine.yield(a+b, a-b)
2196            print("co-body", r, s)
2197            return b, "end"
2198      end)
2199             
2200      print("main", coroutine.resume(co, 1, 10))
2201      print("main", coroutine.resume(co, "r"))
2202      print("main", coroutine.resume(co, "x", "y"))
2203      print("main", coroutine.resume(co, "x", "y"))
2204 </pre><p>
2205 When you run it, it produces the following output:
2206
2207 <pre>
2208      co-body 1       10
2209      foo     2
2210      
2211      main    true    4
2212      co-body r
2213      main    true    11      -9
2214      co-body x       y
2215      main    true    10      end
2216      main    false   cannot resume dead coroutine
2217 </pre>
2218
2219
2220
2221
2222 <h1>3 - <a name="3">The Application Program Interface</a></h1>
2223
2224 <p>
2225
2226 This section describes the C&nbsp;API for Lua, that is,
2227 the set of C&nbsp;functions available to the host program to communicate
2228 with Lua.
2229 All API functions and related types and constants
2230 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2231
2232
2233 <p>
2234 Even when we use the term "function",
2235 any facility in the API may be provided as a macro instead.
2236 All such macros use each of their arguments exactly once
2237 (except for the first argument, which is always a Lua state),
2238 and so do not generate any hidden side-effects.
2239
2240
2241 <p>
2242 As in most C&nbsp;libraries,
2243 the Lua API functions do not check their arguments for validity or consistency.
2244 However, you can change this behavior by compiling Lua
2245 with a proper definition for the macro <a name="pdf-luai_apicheck"><code>luai_apicheck</code></a>,
2246 in file <code>luaconf.h</code>.
2247
2248
2249
2250 <h2>3.1 - <a name="3.1">The Stack</a></h2>
2251
2252 <p>
2253 Lua uses a <em>virtual stack</em> to pass values to and from C.
2254 Each element in this stack represents a Lua value
2255 (<b>nil</b>, number, string, etc.).
2256
2257
2258 <p>
2259 Whenever Lua calls C, the called function gets a new stack,
2260 which is independent of previous stacks and of stacks of
2261 C&nbsp;functions that are still active.
2262 This stack initially contains any arguments to the C&nbsp;function
2263 and it is where the C&nbsp;function pushes its results
2264 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2265
2266
2267 <p>
2268 For convenience,
2269 most query operations in the API do not follow a strict stack discipline.
2270 Instead, they can refer to any element in the stack
2271 by using an <em>index</em>:
2272 A positive index represents an <em>absolute</em> stack position
2273 (starting at&nbsp;1);
2274 a negative index represents an <em>offset</em> relative to the top of the stack.
2275 More specifically, if the stack has <em>n</em> elements,
2276 then index&nbsp;1 represents the first element
2277 (that is, the element that was pushed onto the stack first)
2278 and
2279 index&nbsp;<em>n</em> represents the last element;
2280 index&nbsp;-1 also represents the last element
2281 (that is, the element at the&nbsp;top)
2282 and index <em>-n</em> represents the first element.
2283 We say that an index is <em>valid</em>
2284 if it lies between&nbsp;1 and the stack top
2285 (that is, if <code>1 &le; abs(index) &le; top</code>).
2286  
2287
2288
2289
2290
2291
2292 <h2>3.2 - <a name="3.2">Stack Size</a></h2>
2293
2294 <p>
2295 When you interact with Lua API,
2296 you are responsible for ensuring consistency.
2297 In particular,
2298 <em>you are responsible for controlling stack overflow</em>.
2299 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2300 to grow the stack size.
2301
2302
2303 <p>
2304 Whenever Lua calls C,
2305 it ensures that at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> stack positions are available.
2306 <code>LUA_MINSTACK</code> is defined as 20,
2307 so that usually you do not have to worry about stack space
2308 unless your code has loops pushing elements onto the stack.
2309
2310
2311 <p>
2312 Most query functions accept as indices any value inside the
2313 available stack space, that is, indices up to the maximum stack size
2314 you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2315 Such indices are called <em>acceptable indices</em>.
2316 More formally, we define an <em>acceptable index</em>
2317 as follows:
2318
2319 <pre>
2320      (index &lt; 0 &amp;&amp; abs(index) &lt;= top) ||
2321      (index &gt; 0 &amp;&amp; index &lt;= stackspace)
2322 </pre><p>
2323 Note that 0 is never an acceptable index.
2324
2325
2326
2327
2328
2329 <h2>3.3 - <a name="3.3">Pseudo-Indices</a></h2>
2330
2331 <p>
2332 Unless otherwise noted,
2333 any function that accepts valid indices can also be called with
2334 <em>pseudo-indices</em>,
2335 which represent some Lua values that are accessible to C&nbsp;code
2336 but which are not in the stack.
2337 Pseudo-indices are used to access the thread environment,
2338 the function environment,
2339 the registry,
2340 and the upvalues of a C&nbsp;function (see <a href="#3.4">&sect;3.4</a>).
2341
2342
2343 <p>
2344 The thread environment (where global variables live) is
2345 always at pseudo-index <a name="pdf-LUA_GLOBALSINDEX"><code>LUA_GLOBALSINDEX</code></a>.
2346 The environment of the running C&nbsp;function is always
2347 at pseudo-index <a name="pdf-LUA_ENVIRONINDEX"><code>LUA_ENVIRONINDEX</code></a>.
2348
2349
2350 <p>
2351 To access and change the value of global variables,
2352 you can use regular table operations over an environment table.
2353 For instance, to access the value of a global variable, do
2354
2355 <pre>
2356      lua_getfield(L, LUA_GLOBALSINDEX, varname);
2357 </pre>
2358
2359
2360
2361
2362 <h2>3.4 - <a name="3.4">C Closures</a></h2>
2363
2364 <p>
2365 When a C&nbsp;function is created,
2366 it is possible to associate some values with it,
2367 thus creating a <em>C&nbsp;closure</em>;
2368 these values are called <em>upvalues</em> and are
2369 accessible to the function whenever it is called
2370 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
2371
2372
2373 <p>
2374 Whenever a C&nbsp;function is called,
2375 its upvalues are located at specific pseudo-indices.
2376 These pseudo-indices are produced by the macro
2377 <a name="lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2378 The first value associated with a function is at position
2379 <code>lua_upvalueindex(1)</code>, and so on.
2380 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2381 where <em>n</em> is greater than the number of upvalues of the
2382 current function,
2383 produces an acceptable (but invalid) index.
2384
2385
2386
2387
2388
2389 <h2>3.5 - <a name="3.5">Registry</a></h2>
2390
2391 <p>
2392 Lua provides a <em>registry</em>,
2393 a pre-defined table that can be used by any C&nbsp;code to
2394 store whatever Lua value it needs to store.
2395 This table is always located at pseudo-index
2396 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
2397 Any C&nbsp;library can store data into this table,
2398 but it should take care to choose keys different from those used
2399 by other libraries, to avoid collisions.
2400 Typically, you should use as key a string containing your library name
2401 or a light userdata with the address of a C&nbsp;object in your code.
2402
2403
2404 <p>
2405 The integer keys in the registry are used by the reference mechanism,
2406 implemented by the auxiliary library,
2407 and therefore should not be used for other purposes.
2408
2409
2410
2411
2412
2413 <h2>3.6 - <a name="3.6">Error Handling in C</a></h2>
2414
2415 <p>
2416 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2417 (You can also choose to use exceptions if you use C++;
2418 see file <code>luaconf.h</code>.)
2419 When Lua faces any error
2420 (such as memory allocation errors, type errors, syntax errors,
2421 and runtime errors)
2422 it <em>raises</em> an error;
2423 that is, it does a long jump.
2424 A <em>protected environment</em> uses <code>setjmp</code>
2425 to set a recover point;
2426 any error jumps to the most recent active recover point.
2427
2428
2429 <p>
2430 Almost any function in the API may raise an error,
2431 for instance due to a memory allocation error.
2432 The following functions run in protected mode
2433 (that is, they create a protected environment to run),
2434 so they never raise an error:
2435 <a href="#lua_newstate"><code>lua_newstate</code></a>, <a href="#lua_close"><code>lua_close</code></a>, <a href="#lua_load"><code>lua_load</code></a>,
2436 <a href="#lua_pcall"><code>lua_pcall</code></a>, and <a href="#lua_cpcall"><code>lua_cpcall</code></a>.
2437
2438
2439 <p>
2440 Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2441
2442
2443
2444
2445
2446 <h2>3.7 - <a name="3.7">Functions and Types</a></h2>
2447
2448 <p>
2449 Here we list all functions and types from the C&nbsp;API in
2450 alphabetical order.
2451
2452
2453
2454 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2455 <pre>typedef void * (*lua_Alloc) (void *ud,
2456                              void *ptr,
2457                              size_t osize,
2458                              size_t nsize);</pre>
2459
2460 <p>
2461 The type of the memory-allocation function used by Lua states.
2462 The allocator function must provide a
2463 functionality similar to <code>realloc</code>,
2464 but not exactly the same.
2465 Its arguments are
2466 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2467 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2468 <code>osize</code>, the original size of the block;
2469 <code>nsize</code>, the new size of the block.
2470 <code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
2471 When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
2472 if <code>osize</code> is not zero,
2473 it should free the block pointed to by <code>ptr</code>.
2474 When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
2475 if and only if it cannot fill the request.
2476 When <code>nsize</code> is not zero and <code>osize</code> is zero,
2477 the allocator should behave like <code>malloc</code>.
2478 When <code>nsize</code> and <code>osize</code> are not zero,
2479 the allocator behaves like <code>realloc</code>.
2480 Lua assumes that the allocator never fails when
2481 <code>osize &gt;= nsize</code>.
2482
2483
2484 <p>
2485 Here is a simple implementation for the allocator function.
2486 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2487
2488 <pre>
2489      static void *l_alloc (void *ud, void *ptr, size_t osize,
2490                                                 size_t nsize) {
2491        (void)ud;  (void)osize;  /* not used */
2492        if (nsize == 0) {
2493          free(ptr);
2494          return NULL;
2495        }
2496        else
2497          return realloc(ptr, nsize);
2498      }
2499 </pre><p>
2500 This code assumes
2501 that <code>free(NULL)</code> has no effect and that
2502 <code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2503 ANSI&nbsp;C ensures both behaviors.
2504
2505
2506
2507
2508
2509 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3>
2510 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2511
2512 <p>
2513 Sets a new panic function and returns the old one.
2514
2515
2516 <p>
2517 If an error happens outside any protected environment,
2518 Lua calls a <em>panic function</em>
2519 and then calls <code>exit(EXIT_FAILURE)</code>,
2520 thus exiting the host application.
2521 Your panic function may avoid this exit by
2522 never returning (e.g., doing a long jump).
2523
2524
2525 <p>
2526 The panic function can access the error message at the top of the stack.
2527
2528
2529
2530
2531
2532 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3>
2533 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
2534
2535 <p>
2536 Calls a function.
2537
2538
2539 <p>
2540 To call a function you must use the following protocol:
2541 first, the function to be called is pushed onto the stack;
2542 then, the arguments to the function are pushed
2543 in direct order;
2544 that is, the first argument is pushed first.
2545 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
2546 <code>nargs</code> is the number of arguments that you pushed onto the stack.
2547 All arguments and the function value are popped from the stack
2548 when the function is called.
2549 The function results are pushed onto the stack when the function returns.
2550 The number of results is adjusted to <code>nresults</code>,
2551 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
2552 In this case, <em>all</em> results from the function are pushed.
2553 Lua takes care that the returned values fit into the stack space.
2554 The function results are pushed onto the stack in direct order
2555 (the first result is pushed first),
2556 so that after the call the last result is on the top of the stack.
2557
2558
2559 <p>
2560 Any error inside the called function is propagated upwards
2561 (with a <code>longjmp</code>).
2562
2563
2564 <p>
2565 The following example shows how the host program may do the
2566 equivalent to this Lua code:
2567
2568 <pre>
2569      a = f("how", t.x, 14)
2570 </pre><p>
2571 Here it is in&nbsp;C:
2572
2573 <pre>
2574      lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
2575      lua_pushstring(L, "how");                        /* 1st argument */
2576      lua_getfield(L, LUA_GLOBALSINDEX, "t");   /* table to be indexed */
2577      lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
2578      lua_remove(L, -2);                  /* remove 't' from the stack */
2579      lua_pushinteger(L, 14);                          /* 3rd argument */
2580      lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
2581      lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global 'a' */
2582 </pre><p>
2583 Note that the code above is "balanced":
2584 at its end, the stack is back to its original configuration.
2585 This is considered good programming practice.
2586
2587
2588
2589
2590
2591 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
2592 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
2593
2594 <p>
2595 Type for C&nbsp;functions.
2596
2597
2598 <p>
2599 In order to communicate properly with Lua,
2600 a C&nbsp;function must use the following protocol,
2601 which defines the way parameters and results are passed:
2602 a C&nbsp;function receives its arguments from Lua in its stack
2603 in direct order (the first argument is pushed first).
2604 So, when the function starts,
2605 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
2606 The first argument (if any) is at index 1
2607 and its last argument is at index <code>lua_gettop(L)</code>.
2608 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
2609 in direct order (the first result is pushed first),
2610 and returns the number of results.
2611 Any other value in the stack below the results will be properly
2612 discarded by Lua.
2613 Like a Lua function, a C&nbsp;function called by Lua can also return
2614 many results.
2615
2616
2617 <p>
2618 As an example, the following function receives a variable number
2619 of numerical arguments and returns their average and sum:
2620
2621 <pre>
2622      static int foo (lua_State *L) {
2623        int n = lua_gettop(L);    /* number of arguments */
2624        lua_Number sum = 0;
2625        int i;
2626        for (i = 1; i &lt;= n; i++) {
2627          if (!lua_isnumber(L, i)) {
2628            lua_pushstring(L, "incorrect argument");
2629            lua_error(L);
2630          }
2631          sum += lua_tonumber(L, i);
2632        }
2633        lua_pushnumber(L, sum/n);        /* first result */
2634        lua_pushnumber(L, sum);         /* second result */
2635        return 2;                   /* number of results */
2636      }
2637 </pre>
2638
2639
2640
2641
2642 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3>
2643 <pre>int lua_checkstack (lua_State *L, int extra);</pre>
2644
2645 <p>
2646 Ensures that there are at least <code>extra</code> free stack slots in the stack.
2647 It returns false if it cannot grow the stack to that size.
2648 This function never shrinks the stack;
2649 if the stack is already larger than the new size,
2650 it is left unchanged.
2651
2652
2653
2654
2655
2656 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3>
2657 <pre>void lua_close (lua_State *L);</pre>
2658
2659 <p>
2660 Destroys all objects in the given Lua state
2661 (calling the corresponding garbage-collection metamethods, if any)
2662 and frees all dynamic memory used by this state.
2663 On several platforms, you may not need to call this function,
2664 because all resources are naturally released when the host program ends.
2665 On the other hand, long-running programs,
2666 such as a daemon or a web server,
2667 might need to release states as soon as they are not needed,
2668 to avoid growing too large.
2669
2670
2671
2672
2673
2674 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3>
2675 <pre>void lua_concat (lua_State *L, int n);</pre>
2676
2677 <p>
2678 Concatenates the <code>n</code> values at the top of the stack,
2679 pops them, and leaves the result at the top.
2680 If <code>n</code>&nbsp;is&nbsp;1, the result is the single string on the stack
2681 (that is, the function does nothing);
2682 if <code>n</code> is 0, the result is the empty string.
2683 Concatenation is done following the usual semantics of Lua
2684 (see <a href="#2.5.4">&sect;2.5.4</a>).
2685
2686
2687
2688
2689
2690 <hr><h3><a name="lua_cpcall"><code>lua_cpcall</code></a></h3>
2691 <pre>int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);</pre>
2692
2693 <p>
2694 Calls the C&nbsp;function <code>func</code> in protected mode.
2695 <code>func</code> starts with only one element in its stack,
2696 a light userdata containing <code>ud</code>.
2697 In case of errors,
2698 <a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
2699 plus the error object on the top of the stack;
2700 otherwise, it returns zero, and does not change the stack.
2701 All values returned by <code>func</code> are discarded.
2702
2703
2704
2705
2706
2707 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3>
2708 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
2709
2710 <p>
2711 Creates a new empty table and pushes it onto the stack.
2712 The new table has space pre-allocated
2713 for <code>narr</code> array elements and <code>nrec</code> non-array elements.
2714 This pre-allocation is useful when you know exactly how many elements
2715 the table will have.
2716 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
2717
2718
2719
2720
2721
2722 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3>
2723 <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
2724
2725 <p>
2726 Dumps a function as a binary chunk.
2727 Receives a Lua function on the top of the stack
2728 and produces a binary chunk that,
2729 if loaded again,
2730 results in a function equivalent to the one dumped.
2731 As it produces parts of the chunk,
2732 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
2733 with the given <code>data</code>
2734 to write them.
2735
2736
2737 <p>
2738 The value returned is the error code returned by the last
2739 call to the writer;
2740 0&nbsp;means no errors.
2741
2742
2743 <p>
2744 This function does not pop the Lua function from the stack.
2745
2746
2747
2748
2749
2750 <hr><h3><a name="lua_equal"><code>lua_equal</code></a></h3>
2751 <pre>int lua_equal (lua_State *L, int index1, int index2);</pre>
2752
2753 <p>
2754 Returns 1 if the two values in acceptable indices <code>index1</code> and
2755 <code>index2</code> are equal,
2756 following the semantics of the Lua <code>==</code> operator
2757 (that is, may call metamethods).
2758 Otherwise returns&nbsp;0.
2759 Also returns&nbsp;0 if any of the indices is non valid.
2760
2761
2762
2763
2764
2765 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3>
2766 <pre>int lua_error (lua_State *L);</pre>
2767
2768 <p>
2769 Generates a Lua error.
2770 The error message (which can actually be a Lua value of any type)
2771 must be on the stack top.
2772 This function does a long jump,
2773 and therefore never returns.
2774 (see <a href="#luaL_error"><code>luaL_error</code></a>).
2775
2776
2777
2778
2779
2780 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3>
2781 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
2782
2783 <p>
2784 Controls the garbage collector.
2785
2786
2787 <p>
2788 This function performs several tasks,
2789 according to the value of the parameter <code>what</code>:
2790
2791 <ul>
2792
2793 <li><b><code>LUA_GCSTOP</code>:</b>
2794 stops the garbage collector.
2795 </li>
2796
2797 <li><b><code>LUA_GCRESTART</code>:</b>
2798 restarts the garbage collector.
2799 </li>
2800
2801 <li><b><code>LUA_GCCOLLECT</code>:</b>
2802 performs a full garbage-collection cycle.
2803 </li>
2804
2805 <li><b><code>LUA_GCCOUNT</code>:</b>
2806 returns the current amount of memory (in Kbytes) in use by Lua.
2807 </li>
2808
2809 <li><b><code>LUA_GCCOUNTB</code>:</b>
2810 returns the remainder of dividing the current amount of bytes of
2811 memory in use by Lua by 1024.
2812 </li>
2813
2814 <li><b><code>LUA_GCSTEP</code>:</b>
2815 performs an incremental step of garbage collection.
2816 The step "size" is controlled by <code>data</code>
2817 (larger values mean more steps) in a non-specified way.
2818 If you want to control the step size
2819 you must experimentally tune the value of <code>data</code>.
2820 The function returns 1 if the step finished a
2821 garbage-collection cycle.
2822 </li>
2823
2824 <li><b><code>LUA_GCSETPAUSE</code>:</b>
2825 sets <code>data</code>/100 as the new value
2826 for the <em>pause</em> of the collector (see <a href="#2.10">&sect;2.10</a>).
2827 The function returns the previous value of the pause.
2828 </li>
2829
2830 <li><b><code>LUA_GCSETSTEPMUL</code>:</b>
2831 sets <code>data</code>/100 as the new value for the <em>step multiplier</em> of
2832 the collector (see <a href="#2.10">&sect;2.10</a>).
2833 The function returns the previous value of the step multiplier.
2834 </li>
2835
2836 </ul>
2837
2838
2839
2840
2841 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3>
2842 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
2843
2844 <p>
2845 Returns the memory-allocation function of a given state.
2846 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
2847 opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
2848
2849
2850
2851
2852
2853 <hr><h3><a name="lua_getfenv"><code>lua_getfenv</code></a></h3>
2854 <pre>void lua_getfenv (lua_State *L, int index);</pre>
2855
2856 <p>
2857 Pushes onto the stack the environment table of
2858 the value at the given index.
2859
2860
2861
2862
2863
2864 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3>
2865 <pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
2866
2867 <p>
2868 Pushes onto the stack the value <code>t[k]</code>,
2869 where <code>t</code> is the value at the given valid index <code>index</code>.
2870 As in Lua, this function may trigger a metamethod
2871 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2872
2873
2874
2875
2876
2877 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3>
2878 <pre>void lua_getglobal (lua_State *L, const char *name);</pre>
2879
2880 <p>
2881 Pushes onto the stack the value of the global <code>name</code>.
2882 It is defined as a macro:
2883
2884 <pre>
2885      #define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, s)
2886 </pre>
2887
2888
2889
2890
2891 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3>
2892 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
2893
2894 <p>
2895 Pushes onto the stack the metatable of the value at the given
2896 acceptable index.
2897 If the index is not valid,
2898 or if the value does not have a metatable,
2899 the function returns&nbsp;0 and pushes nothing on the stack.
2900
2901
2902
2903
2904
2905 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3>
2906 <pre>void lua_gettable (lua_State *L, int index);</pre>
2907
2908 <p>
2909 Pushes onto the stack the value <code>t[k]</code>,
2910 where <code>t</code> is the value at the given valid index <code>index</code>
2911 and <code>k</code> is the value at the top of the stack.
2912
2913
2914 <p>
2915 This function pops the key from the stack
2916 (putting the resulting value in its place).
2917 As in Lua, this function may trigger a metamethod
2918 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2919
2920
2921
2922
2923
2924 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3>
2925 <pre>int lua_gettop (lua_State *L);</pre>
2926
2927 <p>
2928 Returns the index of the top element in the stack.
2929 Because indices start at&nbsp;1,
2930 this result is equal to the number of elements in the stack
2931 (and so 0&nbsp;means an empty stack).
2932
2933
2934
2935
2936
2937 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3>
2938 <pre>void lua_insert (lua_State *L, int index);</pre>
2939
2940 <p>
2941 Moves the top element into the given valid index,
2942 shifting up the elements above this index to open space.
2943 Cannot be called with a pseudo-index,
2944 because a pseudo-index is not an actual stack position.
2945
2946
2947
2948
2949
2950 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
2951 <pre>typedef ptrdiff_t lua_Integer;</pre>
2952
2953 <p>
2954 The type used by the Lua API to represent integral values.
2955
2956
2957 <p>
2958 By default it is a <code>ptrdiff_t</code>,
2959 which is usually the largest signed integral type the machine handles
2960 "comfortably".
2961
2962
2963
2964
2965
2966 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3>
2967 <pre>int lua_isboolean (lua_State *L, int index);</pre>
2968
2969 <p>
2970 Returns 1 if the value at the given acceptable index has type boolean,
2971 and 0&nbsp;otherwise.
2972
2973
2974
2975
2976
2977 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3>
2978 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
2979
2980 <p>
2981 Returns 1 if the value at the given acceptable index is a C&nbsp;function,
2982 and 0&nbsp;otherwise.
2983
2984
2985
2986
2987
2988 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3>
2989 <pre>int lua_isfunction (lua_State *L, int index);</pre>
2990
2991 <p>
2992 Returns 1 if the value at the given acceptable index is a function
2993 (either C or Lua), and 0&nbsp;otherwise.
2994
2995
2996
2997
2998
2999 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3>
3000 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3001
3002 <p>
3003 Returns 1 if the value at the given acceptable index is a light userdata,
3004 and 0&nbsp;otherwise.
3005
3006
3007
3008
3009
3010 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3>
3011 <pre>int lua_isnil (lua_State *L, int index);</pre>
3012
3013 <p>
3014 Returns 1 if the value at the given acceptable index is <b>nil</b>,
3015 and 0&nbsp;otherwise.
3016
3017
3018
3019
3020
3021 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3>
3022 <pre>int lua_isnone (lua_State *L, int index);</pre>
3023
3024 <p>
3025 Returns 1 if the the given acceptable index is not valid
3026 (that is, it refers to an element outside the current stack),
3027 and 0&nbsp;otherwise.
3028
3029
3030
3031
3032
3033 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3>
3034 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3035
3036 <p>
3037 Returns 1 if the the given acceptable index is not valid
3038 (that is, it refers to an element outside the current stack)
3039 or if the value at this index is <b>nil</b>,
3040 and 0&nbsp;otherwise.
3041
3042
3043
3044
3045
3046 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3>
3047 <pre>int lua_isnumber (lua_State *L, int index);</pre>
3048
3049 <p>
3050 Returns 1 if the value at the given acceptable index is a number
3051 or a string convertible to a number,
3052 and 0&nbsp;otherwise.
3053
3054
3055
3056
3057
3058 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3>
3059 <pre>int lua_isstring (lua_State *L, int index);</pre>
3060
3061 <p>
3062 Returns 1 if the value at the given acceptable index is a string
3063 or a number (which is always convertible to a string),
3064 and 0&nbsp;otherwise.
3065
3066
3067
3068
3069
3070 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3>
3071 <pre>int lua_istable (lua_State *L, int index);</pre>
3072
3073 <p>
3074 Returns 1 if the value at the given acceptable index is a table,
3075 and 0&nbsp;otherwise.
3076
3077
3078
3079
3080
3081 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3>
3082 <pre>int lua_isthread (lua_State *L, int index);</pre>
3083
3084 <p>
3085 Returns 1 if the value at the given acceptable index is a thread,
3086 and 0&nbsp;otherwise.
3087
3088
3089
3090
3091
3092 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3>
3093 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
3094
3095 <p>
3096 Returns 1 if the value at the given acceptable index is a userdata
3097 (either full or light), and 0&nbsp;otherwise.
3098
3099
3100
3101
3102
3103 <hr><h3><a name="lua_lessthan"><code>lua_lessthan</code></a></h3>
3104 <pre>int lua_lessthan (lua_State *L, int index1, int index2);</pre>
3105
3106 <p>
3107 Returns 1 if the value at acceptable index <code>index1</code> is smaller
3108 than the value at acceptable index <code>index2</code>,
3109 following the semantics of the Lua <code>&lt;</code> operator
3110 (that is, may call metamethods).
3111 Otherwise returns&nbsp;0.
3112 Also returns&nbsp;0 if any of the indices is non valid.
3113
3114
3115
3116
3117
3118 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3>
3119 <pre>int lua_load (lua_State *L,
3120               lua_Reader reader,
3121               void *data,
3122               const char *chunkname);</pre>
3123
3124 <p>
3125 Loads a Lua chunk.
3126 If there are no errors,
3127 <a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
3128 function on top of the stack.
3129 Otherwise, it pushes an error message.
3130 The return values of <a href="#lua_load"><code>lua_load</code></a> are:
3131
3132 <ul>
3133
3134 <li><b>0:</b> no errors;</li>
3135
3136 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
3137 syntax error during pre-compilation;</li>
3138
3139 <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3140 memory allocation error.</li>
3141
3142 </ul>
3143
3144 <p>
3145 This function only loads a chunk;
3146 it does not run it.
3147
3148
3149 <p>
3150 <a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
3151 and loads it accordingly (see program <code>luac</code>).
3152
3153
3154 <p>
3155 The <a href="#lua_load"><code>lua_load</code></a> function uses a user-supplied <code>reader</code> function
3156 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3157 The <code>data</code> argument is an opaque value passed to the reader function.
3158
3159
3160 <p>
3161 The <code>chunkname</code> argument gives a name to the chunk,
3162 which is used for error messages and in debug information (see <a href="#3.8">&sect;3.8</a>).
3163
3164
3165
3166
3167
3168 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3>
3169 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3170
3171 <p>
3172 Creates a new, independent state.
3173 Returns <code>NULL</code> if cannot create the state
3174 (due to lack of memory).
3175 The argument <code>f</code> is the allocator function;
3176 Lua does all memory allocation for this state through this function.
3177 The second argument, <code>ud</code>, is an opaque pointer that Lua
3178 simply passes to the allocator in every call.
3179
3180
3181
3182
3183
3184 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3>
3185 <pre>void lua_newtable (lua_State *L);</pre>
3186
3187 <p>
3188 Creates a new empty table and pushes it onto the stack.
3189 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3190
3191
3192
3193
3194
3195 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3>
3196 <pre>lua_State *lua_newthread (lua_State *L);</pre>
3197
3198 <p>
3199 Creates a new thread, pushes it on the stack,
3200 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3201 The new state returned by this function shares with the original state
3202 all global objects (such as tables),
3203 but has an independent execution stack.
3204
3205
3206 <p>
3207 There is no explicit function to close or to destroy a thread.
3208 Threads are subject to garbage collection,
3209 like any Lua object.
3210
3211
3212
3213
3214
3215 <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3>
3216 <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3217
3218 <p>
3219 This function allocates a new block of memory with the given size,
3220 pushes onto the stack a new full userdata with the block address,
3221 and returns this address.
3222
3223
3224 <p>
3225 Userdata represent C&nbsp;values in Lua.
3226 A <em>full userdata</em> represents a block of memory.
3227 It is an object (like a table):
3228 you must create it, it can have its own metatable,
3229 and you can detect when it is being collected.
3230 A full userdata is only equal to itself (under raw equality).
3231
3232
3233 <p>
3234 When Lua collects a full userdata with a <code>gc</code> metamethod,
3235 Lua calls the metamethod and marks the userdata as finalized.
3236 When this userdata is collected again then
3237 Lua frees its corresponding memory.
3238
3239
3240
3241
3242
3243 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3>
3244 <pre>int lua_next (lua_State *L, int index);</pre>
3245
3246 <p>
3247 Pops a key from the stack,
3248 and pushes a key-value pair from the table at the given index
3249 (the "next" pair after the given key).
3250 If there are no more elements in the table,
3251 then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3252
3253
3254 <p>
3255 A typical traversal looks like this:
3256
3257 <pre>
3258      /* table is in the stack at index 't' */
3259      lua_pushnil(L);  /* first key */
3260      while (lua_next(L, t) != 0) {
3261        /* uses 'key' (at index -2) and 'value' (at index -1) */
3262        printf("%s - %s\n",
3263               lua_typename(L, lua_type(L, -2)),
3264               lua_typename(L, lua_type(L, -1)));
3265        /* removes 'value'; keeps 'key' for next iteration */
3266        lua_pop(L, 1);
3267      }
3268 </pre>
3269
3270 <p>
3271 While traversing a table,
3272 do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3273 unless you know that the key is actually a string.
3274 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
3275 the value at the given index;
3276 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3277
3278
3279
3280
3281
3282 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3283 <pre>typedef double lua_Number;</pre>
3284
3285 <p>
3286 The type of numbers in Lua.
3287 By default, it is double, but that can be changed in <code>luaconf.h</code>.
3288
3289
3290 <p>
3291 Through the configuration file you can change
3292 Lua to operate with another type for numbers (e.g., float or long).
3293
3294
3295
3296
3297
3298 <hr><h3><a name="lua_objlen"><code>lua_objlen</code></a></h3>
3299 <pre>size_t lua_objlen (lua_State *L, int index);</pre>
3300
3301 <p>
3302 Returns the "length" of the value at the given acceptable index:
3303 for strings, this is the string length;
3304 for tables, this is the result of the length operator ('<code>#</code>');
3305 for userdata, this is the size of the block of memory allocated
3306 for the userdata;
3307 for other values, it is&nbsp;0.
3308
3309
3310
3311
3312
3313 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3>
3314 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);</pre>
3315
3316 <p>
3317 Calls a function in protected mode.
3318
3319
3320 <p>
3321 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3322 in <a href="#lua_call"><code>lua_call</code></a>.
3323 If there are no errors during the call,
3324 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
3325 However, if there is any error,
3326 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3327 pushes a single value on the stack (the error message),
3328 and returns an error code.
3329 Like <a href="#lua_call"><code>lua_call</code></a>,
3330 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3331 and its arguments from the stack.
3332
3333
3334 <p>
3335 If <code>errfunc</code> is 0,
3336 then the error message returned on the stack
3337 is exactly the original error message.
3338 Otherwise, <code>errfunc</code> is the stack index of an
3339 <em>error handler function</em>.
3340 (In the current implementation, this index cannot be a pseudo-index.)
3341 In case of runtime errors,
3342 this function will be called with the error message
3343 and its return value will be the message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3344
3345
3346 <p>
3347 Typically, the error handler function is used to add more debug
3348 information to the error message, such as a stack traceback.
3349 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3350 since by then the stack has unwound.
3351
3352
3353 <p>
3354 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
3355 or one of the following error codes
3356 (defined in <code>lua.h</code>):
3357
3358 <ul>
3359
3360 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b>
3361 a runtime error.
3362 </li>
3363
3364 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3365 memory allocation error.
3366 For such errors, Lua does not call the error handler function.
3367 </li>
3368
3369 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
3370 error while running the error handler function.
3371 </li>
3372
3373 </ul>
3374
3375
3376
3377
3378 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3>
3379 <pre>void lua_pop (lua_State *L, int n);</pre>
3380
3381 <p>
3382 Pops <code>n</code> elements from the stack.
3383
3384
3385
3386
3387
3388 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3>
3389 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
3390
3391 <p>
3392 Pushes a boolean value with value <code>b</code> onto the stack.
3393
3394
3395
3396
3397
3398 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3>
3399 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
3400
3401 <p>
3402 Pushes a new C&nbsp;closure onto the stack.
3403
3404
3405 <p>
3406 When a C&nbsp;function is created,
3407 it is possible to associate some values with it,
3408 thus creating a C&nbsp;closure (see <a href="#3.4">&sect;3.4</a>);
3409 these values are then accessible to the function whenever it is called.
3410 To associate values with a C&nbsp;function,
3411 first these values should be pushed onto the stack
3412 (when there are multiple values, the first value is pushed first).
3413 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
3414 is called to create and push the C&nbsp;function onto the stack,
3415 with the argument <code>n</code> telling how many values should be
3416 associated with the function.
3417 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
3418
3419
3420
3421
3422
3423 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3>
3424 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
3425
3426 <p>
3427 Pushes a C&nbsp;function onto the stack.
3428 This function receives a pointer to a C function
3429 and pushes onto the stack a Lua value of type <code>function</code> that,
3430 when called, invokes the corresponding C&nbsp;function.
3431
3432
3433 <p>
3434 Any function to be registered in Lua must
3435 follow the correct protocol to receive its parameters
3436 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
3437
3438
3439 <p>
3440 <code>lua_pushcfunction</code> is defined as a macro:
3441
3442 <pre>
3443      #define lua_pushcfunction(L,f)  lua_pushcclosure(L,f,0)
3444 </pre>
3445
3446
3447
3448
3449 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3>
3450 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
3451
3452 <p>
3453 Pushes onto the stack a formatted string
3454 and returns a pointer to this string.
3455 It is similar to the C&nbsp;function <code>sprintf</code>,
3456 but has some important differences:
3457
3458 <ul>
3459
3460 <li>
3461 You do not have to allocate space for the result:
3462 the result is a Lua string and Lua takes care of memory allocation
3463 (and deallocation, through garbage collection).
3464 </li>
3465
3466 <li>
3467 The conversion specifiers are quite restricted.
3468 There are no flags, widths, or precisions.
3469 The conversion specifiers can only be
3470 '<code>%%</code>' (inserts a '<code>%</code>' in the string),
3471 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
3472 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
3473 '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
3474 '<code>%d</code>' (inserts an <code>int</code>), and
3475 '<code>%c</code>' (inserts an <code>int</code> as a character).
3476 </li>
3477
3478 </ul>
3479
3480
3481
3482
3483 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3>
3484 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
3485
3486 <p>
3487 Pushes a number with value <code>n</code> onto the stack.
3488
3489
3490
3491
3492
3493 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3>
3494 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
3495
3496 <p>
3497 Pushes a light userdata onto the stack.
3498
3499
3500 <p>
3501 Userdata represent C&nbsp;values in Lua.
3502 A <em>light userdata</em> represents a pointer.
3503 It is a value (like a number):
3504 you do not create it, it has no individual metatable,
3505 and it is not collected (as it was never created).
3506 A light userdata is equal to "any"
3507 light userdata with the same C&nbsp;address.
3508
3509
3510
3511
3512
3513 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3>
3514 <pre>void lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
3515
3516 <p>
3517 Pushes the string pointed to by <code>s</code> with size <code>len</code>
3518 onto the stack.
3519 Lua makes (or reuses) an internal copy of the given string,
3520 so the memory at <code>s</code> can be freed or reused immediately after
3521 the function returns.
3522 The string can contain embedded zeros.
3523
3524
3525
3526
3527
3528 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3>
3529 <pre>void lua_pushnil (lua_State *L);</pre>
3530
3531 <p>
3532 Pushes a nil value onto the stack.
3533
3534
3535
3536
3537
3538 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3>
3539 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
3540
3541 <p>
3542 Pushes a number with value <code>n</code> onto the stack.
3543
3544
3545
3546
3547
3548 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3>
3549 <pre>void lua_pushstring (lua_State *L, const char *s);</pre>
3550
3551 <p>
3552 Pushes the zero-terminated string pointed to by <code>s</code>
3553 onto the stack.
3554 Lua makes (or reuses) an internal copy of the given string,
3555 so the memory at <code>s</code> can be freed or reused immediately after
3556 the function returns.
3557 The string cannot contain embedded zeros;
3558 it is assumed to end at the first zero.
3559
3560
3561
3562
3563
3564 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3>
3565 <pre>int lua_pushthread (lua_State *L);</pre>
3566
3567 <p>
3568 Pushes the thread represented by <code>L</code> onto the stack.
3569 Returns 1 if this thread is the main thread of its state.
3570
3571
3572
3573
3574
3575 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3>
3576 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
3577
3578 <p>
3579 Pushes a copy of the element at the given valid index
3580 onto the stack.
3581
3582
3583
3584
3585
3586 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3>
3587 <pre>const char *lua_pushvfstring (lua_State *L,
3588                               const char *fmt,
3589                               va_list argp);</pre>
3590
3591 <p>
3592 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
3593 instead of a variable number of arguments.
3594
3595
3596
3597
3598
3599 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3>
3600 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
3601
3602 <p>
3603 Returns 1 if the two values in acceptable indices <code>index1</code> and
3604 <code>index2</code> are primitively equal
3605 (that is, without calling metamethods).
3606 Otherwise returns&nbsp;0.
3607 Also returns&nbsp;0 if any of the indices are non valid.
3608
3609
3610
3611
3612
3613 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3>
3614 <pre>void lua_rawget (lua_State *L, int index);</pre>
3615
3616 <p>
3617 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
3618 (i.e., without metamethods).
3619
3620
3621
3622
3623
3624 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3>
3625 <pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
3626
3627 <p>
3628 Pushes onto the stack the value <code>t[n]</code>,
3629 where <code>t</code> is the value at the given valid index <code>index</code>.
3630 The access is raw;
3631 that is, it does not invoke metamethods.
3632
3633
3634
3635
3636
3637 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3>
3638 <pre>void lua_rawset (lua_State *L, int index);</pre>
3639
3640 <p>
3641 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
3642 (i.e., without metamethods).
3643
3644
3645
3646
3647
3648 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3>
3649 <pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
3650
3651 <p>
3652 Does the equivalent of <code>t[n] = v</code>,
3653 where <code>t</code> is the value at the given valid index <code>index</code>
3654 and <code>v</code> is the value at the top of the stack,
3655
3656
3657 <p>
3658 This function pops the value from the stack.
3659 The assignment is raw;
3660 that is, it does not invoke metamethods.
3661
3662
3663
3664
3665
3666 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
3667 <pre>typedef const char * (*lua_Reader) (lua_State *L,
3668                                     void *data,
3669                                     size_t *size);</pre>
3670
3671 <p>
3672 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
3673 Every time it needs another piece of the chunk,
3674 <a href="#lua_load"><code>lua_load</code></a> calls the reader,
3675 passing along its <code>data</code> parameter.
3676 The reader must return a pointer to a block of memory
3677 with a new piece of the chunk
3678 and set <code>size</code> to the block size.
3679 The block must exist until the reader function is called again.
3680 To signal the end of the chunk, the reader must return <code>NULL</code>.
3681 The reader function may return pieces of any size greater than zero.
3682
3683
3684
3685
3686
3687 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3>
3688 <pre>void lua_register (lua_State *L,
3689                    const char *name,
3690                    lua_CFunction f);</pre>
3691
3692 <p>
3693 Sets the C function <code>f</code> as the new value of global <code>name</code>.
3694 It is defined as a macro:
3695
3696 <pre>
3697      #define lua_register(L,n,f) \
3698             (lua_pushcfunction(L, f), lua_setglobal(L, n))
3699 </pre>
3700
3701
3702
3703
3704 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3>
3705 <pre>void lua_remove (lua_State *L, int index);</pre>
3706
3707 <p>
3708 Removes the element at the given valid index,
3709 shifting down the elements above this index to fill the gap.
3710 Cannot be called with a pseudo-index,
3711 because a pseudo-index is not an actual stack position.
3712
3713
3714
3715
3716
3717 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3>
3718 <pre>void lua_replace (lua_State *L, int index);</pre>
3719
3720 <p>
3721 Moves the top element into the given position (and pops it),
3722 without shifting any element
3723 (therefore replacing the value at the given position).
3724
3725
3726
3727
3728
3729 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3>
3730 <pre>int lua_resume (lua_State *L, int narg);</pre>
3731
3732 <p>
3733 Starts and resumes a coroutine in a given thread.
3734
3735
3736 <p>
3737 To start a coroutine, you first create a new thread
3738 (see <a href="#lua_newthread"><code>lua_newthread</code></a>);
3739 then you push onto its stack the main function plus any arguments;
3740 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
3741 with <code>narg</code> being the number of arguments.
3742 This call returns when the coroutine suspends or finishes its execution.
3743 When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
3744 or all values returned by the body function.
3745 <a href="#lua_resume"><code>lua_resume</code></a> returns
3746 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
3747 0 if the coroutine finishes its execution
3748 without errors,
3749 or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
3750 In case of errors,
3751 the stack is not unwound,
3752 so you can use the debug API over it.
3753 The error message is on the top of the stack.
3754 To restart a coroutine, you put on its stack only the values to
3755 be passed as results from <code>yield</code>,
3756 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
3757
3758
3759
3760
3761
3762 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3>
3763 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
3764
3765 <p>
3766 Changes the allocator function of a given state to <code>f</code>
3767 with user data <code>ud</code>.
3768
3769
3770
3771
3772
3773 <hr><h3><a name="lua_setfenv"><code>lua_setfenv</code></a></h3>
3774 <pre>int lua_setfenv (lua_State *L, int index);</pre>
3775
3776 <p>
3777 Pops a table from the stack and sets it as
3778 the new environment for the value at the given index.
3779 If the value at the given index is
3780 neither a function nor a thread nor a userdata,
3781 <a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0.
3782 Otherwise it returns 1.
3783
3784
3785
3786
3787
3788 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3>
3789 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
3790
3791 <p>
3792 Does the equivalent to <code>t[k] = v</code>,
3793 where <code>t</code> is the value at the given valid index <code>index</code>
3794 and <code>v</code> is the value at the top of the stack,
3795
3796
3797 <p>
3798 This function pops the value from the stack.
3799 As in Lua, this function may trigger a metamethod
3800 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3801
3802
3803
3804
3805
3806 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3>
3807 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
3808
3809 <p>
3810 Pops a value from the stack and
3811 sets it as the new value of global <code>name</code>.
3812 It is defined as a macro:
3813
3814 <pre>
3815      #define lua_setglobal(L,s)   lua_setfield(L, LUA_GLOBALSINDEX, s)
3816 </pre>
3817
3818
3819
3820
3821 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3>
3822 <pre>int lua_setmetatable (lua_State *L, int index);</pre>
3823
3824 <p>
3825 Pops a table from the stack and
3826 sets it as the new metatable for the value at the given
3827 acceptable index.
3828
3829
3830
3831
3832
3833 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3>
3834 <pre>void lua_settable (lua_State *L, int index);</pre>
3835
3836 <p>
3837 Does the equivalent to <code>t[k] = v</code>,
3838 where <code>t</code> is the value at the given valid index <code>index</code>,
3839 <code>v</code> is the value at the top of the stack,
3840 and <code>k</code> is the value just below the top.
3841
3842
3843 <p>
3844 This function pops both the key and the value from the stack.
3845 As in Lua, this function may trigger a metamethod
3846 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3847
3848
3849
3850
3851
3852 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3>
3853 <pre>void lua_settop (lua_State *L, int index);</pre>
3854
3855 <p>
3856 Accepts any acceptable index, or&nbsp;0,
3857 and sets the stack top to this index.
3858 If the new top is larger than the old one,
3859 then the new elements are filled with <b>nil</b>.
3860 If <code>index</code> is&nbsp;0, then all stack elements are removed.
3861
3862
3863
3864
3865
3866 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
3867 <pre>typedef struct lua_State lua_State;</pre>
3868
3869 <p>
3870 Opaque structure that keeps the whole state of a Lua interpreter.
3871 The Lua library is fully reentrant:
3872 it has no global variables.
3873 All information about a state is kept in this structure.
3874
3875
3876 <p>
3877 A pointer to this state must be passed as the first argument to
3878 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
3879 which creates a Lua state from scratch.
3880
3881
3882
3883
3884
3885 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3>
3886 <pre>int lua_status (lua_State *L);</pre>
3887
3888 <p>
3889 Returns the status of the thread <code>L</code>.
3890
3891
3892 <p>
3893 The status can be 0 for a normal thread,
3894 an error code if the thread finished its execution with an error,
3895 or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
3896
3897
3898
3899
3900
3901 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3>
3902 <pre>int lua_toboolean (lua_State *L, int index);</pre>
3903
3904 <p>
3905 Converts the Lua value at the given acceptable index to a C&nbsp;boolean
3906 value (0&nbsp;or&nbsp;1).
3907 Like all tests in Lua,
3908 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
3909 different from <b>false</b> and <b>nil</b>;
3910 otherwise it returns 0.
3911 It also returns 0 when called with a non-valid index.
3912 (If you want to accept only actual boolean values,
3913 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
3914
3915
3916
3917
3918
3919 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3>
3920 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
3921
3922 <p>
3923 Converts a value at the given acceptable index to a C&nbsp;function.
3924 That value must be a C&nbsp;function;
3925 otherwise, returns <code>NULL</code>.
3926
3927
3928
3929
3930
3931 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3>
3932 <pre>lua_Integer lua_tointeger (lua_State *L, int idx);</pre>
3933
3934 <p>
3935 Converts the Lua value at the given acceptable index
3936 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
3937 The Lua value must be a number or a string convertible to a number
3938 (see <a href="#2.2.1">&sect;2.2.1</a>);
3939 otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns&nbsp;0.
3940
3941
3942 <p>
3943 If the number is not an integer,
3944 it is truncated in some non-specified way.
3945
3946
3947
3948
3949
3950 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3>
3951 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
3952
3953 <p>
3954 Converts the Lua value at the given acceptable index to a C&nbsp;string.
3955 If <code>len</code> is not <code>NULL</code>,
3956 it also sets <code>*len</code> with the string length.
3957 The Lua value must be a string or a number;
3958 otherwise, the function returns <code>NULL</code>.
3959 If the value is a number,
3960 then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
3961 <em>changes the actual value in the stack to a string</em>.
3962 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
3963 when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys during a table traversal.)
3964
3965
3966 <p>
3967 <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
3968 to a string inside the Lua state.
3969 This string always has a zero ('<code>\0</code>')
3970 after its last character (as in&nbsp;C),
3971 but may contain other zeros in its body.
3972 Because Lua has garbage collection,
3973 there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
3974 will be valid after the corresponding value is removed from the stack.
3975
3976
3977
3978
3979
3980 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3>
3981 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
3982
3983 <p>
3984 Converts the Lua value at the given acceptable index
3985 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
3986 The Lua value must be a number or a string convertible to a number
3987 (see <a href="#2.2.1">&sect;2.2.1</a>);
3988 otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns&nbsp;0.
3989
3990
3991
3992
3993
3994 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3>
3995 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
3996
3997 <p>
3998 Converts the value at the given acceptable index to a generic
3999 C&nbsp;pointer (<code>void*</code>).
4000 The value may be a userdata, a table, a thread, or a function;
4001 otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
4002 Different objects will give different pointers.
4003 There is no way to convert the pointer back to its original value.
4004
4005
4006 <p>
4007 Typically this function is used only for debug information.
4008
4009
4010
4011
4012
4013 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3>
4014 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
4015
4016 <p>
4017 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4018
4019
4020
4021
4022
4023 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3>
4024 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4025
4026 <p>
4027 Converts the value at the given acceptable index to a Lua thread
4028 (represented as <code>lua_State*</code>).
4029 This value must be a thread;
4030 otherwise, the function returns <code>NULL</code>.
4031
4032
4033
4034
4035
4036 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3>
4037 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
4038
4039 <p>
4040 If the value at the given acceptable index is a full userdata,
4041 returns its block address.
4042 If the value is a light userdata,
4043 returns its pointer.
4044 Otherwise, returns <code>NULL</code>.
4045
4046
4047
4048
4049
4050 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3>
4051 <pre>int lua_type (lua_State *L, int index);</pre>
4052
4053 <p>
4054 Returns the type of the value in the given acceptable index,
4055 or <code>LUA_TNONE</code> for a non-valid index
4056 (that is, an index to an "empty" stack position).
4057 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4058 defined in <code>lua.h</code>:
4059 <code>LUA_TNIL</code>,
4060 <code>LUA_TNUMBER</code>,
4061 <code>LUA_TBOOLEAN</code>,
4062 <code>LUA_TSTRING</code>,
4063 <code>LUA_TTABLE</code>,
4064 <code>LUA_TFUNCTION</code>,
4065 <code>LUA_TUSERDATA</code>,
4066 <code>LUA_TTHREAD</code>,
4067 and
4068 <code>LUA_TLIGHTUSERDATA</code>.
4069
4070
4071
4072
4073
4074 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3>
4075 <pre>const char *lua_typename  (lua_State *L, int tp);</pre>
4076
4077 <p>
4078 Returns the name of the type encoded by the value <code>tp</code>,
4079 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4080
4081
4082
4083
4084
4085 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4086 <pre>typedef int (*lua_Writer) (lua_State *L,
4087                            const void* p,
4088                            size_t sz,
4089                            void* ud);</pre>
4090
4091 <p>
4092 The writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4093 Every time it produces another piece of chunk,
4094 <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4095 passing along the buffer to be written (<code>p</code>),
4096 its size (<code>sz</code>),
4097 and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4098
4099
4100 <p>
4101 The writer returns an error code:
4102 0&nbsp;means no errors;
4103 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4104 calling the writer again.
4105
4106
4107
4108
4109
4110 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3>
4111 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4112
4113 <p>
4114 Exchange values between different threads of the <em>same</em> global state.
4115
4116
4117 <p>
4118 This function pops <code>n</code> values from the stack <code>from</code>,
4119 and pushes them onto the stack <code>to</code>.
4120
4121
4122
4123
4124
4125 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3>
4126 <pre>int lua_yield  (lua_State *L, int nresults);</pre>
4127
4128 <p>
4129 Yields a coroutine.
4130
4131
4132 <p>
4133 This function should only be called as the
4134 return expression of a C&nbsp;function, as follows:
4135
4136 <pre>
4137      return lua_yield (L, nresults);
4138 </pre><p>
4139 When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
4140 the running coroutine suspends its execution,
4141 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
4142 The parameter <code>nresults</code> is the number of values from the stack
4143 that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
4144
4145
4146
4147
4148
4149
4150
4151 <h2>3.8 - <a name="3.8">The Debug Interface</a></h2>
4152
4153 <p>
4154 Lua has no built-in debugging facilities.
4155 Instead, it offers a special interface
4156 by means of functions and <em>hooks</em>.
4157 This interface allows the construction of different
4158 kinds of debuggers, profilers, and other tools
4159 that need "inside information" from the interpreter.
4160
4161
4162
4163 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
4164 <pre>typedef struct lua_Debug {
4165   int event;
4166   const char *name;           /* (n) */
4167   const char *namewhat;       /* (n) */
4168   const char *what;           /* (S) */
4169   const char *source;         /* (S) */
4170   int currentline;            /* (l) */
4171   int nups;                   /* (u) number of upvalues */
4172   int linedefined;            /* (S) */
4173   int lastlinedefined;        /* (S) */
4174   char short_src[LUA_IDSIZE]; /* (S) */
4175   /* private part */
4176   <em>other fields</em>
4177 } lua_Debug;</pre>
4178
4179 <p>
4180 A structure used to carry different pieces of
4181 information about an active function.
4182 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
4183 of this structure, for later use.
4184 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
4185 call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4186
4187
4188 <p>
4189 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
4190
4191 <ul>
4192
4193 <li><b><code>source</code>:</b>
4194 If the function was defined in a string,
4195 then <code>source</code> is that string.
4196 If the function was defined in a file,
4197 then <code>source</code> starts with a '<code>@</code>' followed by the file name.
4198 </li>
4199
4200 <li><b><code>short_src</code>:</b>
4201 a "printable" version of <code>source</code>, to be used in error messages.
4202 </li>
4203
4204 <li><b><code>linedefined</code>:</b>
4205 the line number where the definition of the function starts.
4206 </li>
4207
4208 <li><b><code>lastlinedefined</code>:</b>
4209 the line number where the definition of the function ends.
4210 </li>
4211
4212 <li><b><code>what</code>:</b>
4213 the string <code>"Lua"</code> if the function is a Lua function,
4214 <code>"C"</code> if it is a C&nbsp;function,
4215 <code>"main"</code> if it is the main part of a chunk,
4216 and <code>"tail"</code> if it was a function that did a tail call.
4217 In the latter case,
4218 Lua has no other information about the function.
4219 </li>
4220
4221 <li><b><code>currentline</code>:</b>
4222 the current line where the given function is executing.
4223 When no line information is available,
4224 <code>currentline</code> is set to -1.
4225 </li>
4226
4227 <li><b><code>name</code>:</b>
4228 a reasonable name for the given function.
4229 Because functions in Lua are first-class values,
4230 they do not have a fixed name:
4231 some functions may be the value of multiple global variables,
4232 while others may be stored only in a table field.
4233 The <code>lua_getinfo</code> function checks how the function was
4234 called to find a suitable name.
4235 If it cannot find a name,
4236 then <code>name</code> is set to <code>NULL</code>.
4237 </li>
4238
4239 <li><b><code>namewhat</code>:</b>
4240 explains the <code>name</code> field.
4241 The value of <code>namewhat</code> can be
4242 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
4243 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
4244 according to how the function was called.
4245 (Lua uses the empty string when no other option seems to apply.)
4246 </li>
4247
4248 <li><b><code>nups</code>:</b>
4249 the number of upvalues of the function.
4250 </li>
4251
4252 </ul>
4253
4254
4255
4256
4257 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3>
4258 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
4259
4260 <p>
4261 Returns the current hook function.
4262
4263
4264
4265
4266
4267 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3>
4268 <pre>int lua_gethookcount (lua_State *L);</pre>
4269
4270 <p>
4271 Returns the current hook count.
4272
4273
4274
4275
4276
4277 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3>
4278 <pre>int lua_gethookmask (lua_State *L);</pre>
4279
4280 <p>
4281 Returns the current hook mask.
4282
4283
4284
4285
4286
4287 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3>
4288 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
4289
4290 <p>
4291 Returns information about a specific function or function invocation.
4292
4293
4294 <p>
4295 To get information about a function invocation,
4296 the parameter <code>ar</code> must be a valid activation record that was
4297 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4298 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4299
4300
4301 <p>
4302 To get information about a function you push it onto the stack
4303 and start the <code>what</code> string with the character '<code>&gt;</code>'.
4304 (In that case,
4305 <code>lua_getinfo</code> pops the function in the top of the stack.)
4306 For instance, to know in which line a function <code>f</code> was defined,
4307 you can write the following code:
4308
4309 <pre>
4310      lua_Debug ar;
4311      lua_getfield(L, LUA_GLOBALSINDEX, "f");  /* get global 'f' */
4312      lua_getinfo(L, "&gt;S", &amp;ar);
4313      printf("%d\n", ar.linedefined);
4314 </pre>
4315
4316 <p>
4317 Each character in the string <code>what</code>
4318 selects some fields of the structure <code>ar</code> to be filled or
4319 a value to be pushed on the stack:
4320
4321 <ul>
4322
4323 <li><b>'<code>n</code>':</b> fills in the field <code>name</code> and <code>namewhat</code>;
4324 </li>
4325
4326 <li><b>'<code>S</code>':</b>
4327 fills in the fields <code>source</code>, <code>short_src</code>,
4328 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
4329 </li>
4330
4331 <li><b>'<code>l</code>':</b> fills in the field <code>currentline</code>;
4332 </li>
4333
4334 <li><b>'<code>u</code>':</b> fills in the field <code>nups</code>;
4335 </li>
4336
4337 <li><b>'<code>f</code>':</b>
4338 pushes onto the stack the function that is
4339 running at the given level;
4340 </li>
4341
4342 <li><b>'<code>L</code>':</b>
4343 pushes onto the stack a table whose indices are the
4344 numbers of the lines that are valid on the function.
4345 (A <em>valid line</em> is a line with some associated code,
4346 that is, a line where you can put a break point.
4347 Non-valid lines include empty lines and comments.)
4348 </li>
4349
4350 </ul>
4351
4352 <p>
4353 This function returns 0 on error
4354 (for instance, an invalid option in <code>what</code>).
4355
4356
4357
4358
4359
4360 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3>
4361 <pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4362
4363 <p>
4364 Gets information about a local variable of a given activation record.
4365 The parameter <code>ar</code> must be a valid activation record that was
4366 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4367 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4368 The index <code>n</code> selects which local variable to inspect
4369 (1 is the first parameter or active local variable, and so on,
4370 until the last active local variable).
4371 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
4372 and returns its name.
4373
4374
4375 <p>
4376 Variable names starting with '<code>(</code>' (open parentheses)
4377 represent internal variables
4378 (loop control variables, temporaries, and C&nbsp;function locals).
4379
4380
4381 <p>
4382 Returns <code>NULL</code> (and pushes nothing)
4383 when the index is greater than
4384 the number of active local variables.
4385
4386
4387
4388
4389
4390 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3>
4391 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
4392
4393 <p>
4394 Get information about the interpreter runtime stack.
4395
4396
4397 <p>
4398 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
4399 an identification of the <em>activation record</em>
4400 of the function executing at a given level.
4401 Level&nbsp;0 is the current running function,
4402 whereas level <em>n+1</em> is the function that has called level <em>n</em>.
4403 When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
4404 when called with a level greater than the stack depth,
4405 it returns 0.
4406
4407
4408
4409
4410
4411 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3>
4412 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
4413
4414 <p>
4415 Gets information about a closure's upvalue.
4416 (For Lua functions,
4417 upvalues are the external local variables that the function uses,
4418 and that are consequently included in its closure.)
4419 <a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
4420 pushes the upvalue's value onto the stack,
4421 and returns its name.
4422 <code>funcindex</code> points to the closure in the stack.
4423 (Upvalues have no particular order,
4424 as they are active through the whole function.
4425 So, they are numbered in an arbitrary order.)
4426
4427
4428 <p>
4429 Returns <code>NULL</code> (and pushes nothing)
4430 when the index is greater than the number of upvalues.
4431 For C&nbsp;functions, this function uses the empty string <code>""</code>
4432 as a name for all upvalues.
4433
4434
4435
4436
4437
4438 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
4439 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
4440
4441 <p>
4442 Type for debugging hook functions.
4443
4444
4445 <p>
4446 Whenever a hook is called, its <code>ar</code> argument has its field
4447 <code>event</code> set to the specific event that triggered the hook.
4448 Lua identifies these events with the following constants:
4449 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
4450 <a name="pdf-LUA_HOOKTAILRET"><code>LUA_HOOKTAILRET</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
4451 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
4452 Moreover, for line events, the field <code>currentline</code> is also set.
4453 To get the value of any other field in <code>ar</code>,
4454 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4455 For return events, <code>event</code> may be <code>LUA_HOOKRET</code>,
4456 the normal value, or <code>LUA_HOOKTAILRET</code>.
4457 In the latter case, Lua is simulating a return from
4458 a function that did a tail call;
4459 in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4460
4461
4462 <p>
4463 While Lua is running a hook, it disables other calls to hooks.
4464 Therefore, if a hook calls back Lua to execute a function or a chunk,
4465 this execution occurs without any calls to hooks.
4466
4467
4468
4469
4470
4471 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3>
4472 <pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
4473
4474 <p>
4475 Sets the debugging hook function.
4476
4477
4478 <p>
4479 Argument <code>f</code> is the hook function.
4480 <code>mask</code> specifies on which events the hook will be called:
4481 it is formed by a bitwise or of the constants
4482 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
4483 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
4484 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
4485 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
4486 The <code>count</code> argument is only meaningful when the mask
4487 includes <code>LUA_MASKCOUNT</code>.
4488 For each event, the hook is called as explained below:
4489
4490 <ul>
4491
4492 <li><b>The call hook:</b> is called when the interpreter calls a function.
4493 The hook is called just after Lua enters the new function,
4494 before the function gets its arguments.
4495 </li>
4496
4497 <li><b>The return hook:</b> is called when the interpreter returns from a function.
4498 The hook is called just before Lua leaves the function.
4499 You have no access to the values to be returned by the function.
4500 </li>
4501
4502 <li><b>The line hook:</b> is called when the interpreter is about to
4503 start the execution of a new line of code,
4504 or when it jumps back in the code (even to the same line).
4505 (This event only happens while Lua is executing a Lua function.)
4506 </li>
4507
4508 <li><b>The count hook:</b> is called after the interpreter executes every
4509 <code>count</code> instructions.
4510 (This event only happens while Lua is executing a Lua function.)
4511 </li>
4512
4513 </ul>
4514
4515 <p>
4516 A hook is disabled by setting <code>mask</code> to zero.
4517
4518
4519
4520
4521
4522 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3>
4523 <pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4524
4525 <p>
4526 Sets the value of a local variable of a given activation record.
4527 Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
4528 (see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
4529 <a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
4530 to the variable and returns its name.
4531 It also pops the value from the stack.
4532
4533
4534 <p>
4535 Returns <code>NULL</code> (and pops nothing)
4536 when the index is greater than
4537 the number of active local variables.
4538
4539
4540
4541
4542
4543 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3>
4544 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
4545
4546 <p>
4547 Sets the value of a closure's upvalue.
4548 It assigns the value at the top of the stack
4549 to the upvalue and returns its name.
4550 It also pops the value from the stack.
4551 Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
4552 (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
4553
4554
4555 <p>
4556 Returns <code>NULL</code> (and pops nothing)
4557 when the index is greater than the number of upvalues.
4558
4559
4560
4561
4562
4563
4564
4565 <h1>4 - <a name="4">The Auxiliary Library</a></h1>
4566
4567 <p>
4568
4569 The <em>auxiliary library</em> provides several convenient functions
4570 to interface C with Lua.
4571 While the basic API provides the primitive functions for all 
4572 interactions between C and Lua,
4573 the auxiliary library provides higher-level functions for some
4574 common tasks.
4575
4576
4577 <p>
4578 All functions from the auxiliary library
4579 are defined in header file <code>lauxlib.h</code> and
4580 have a prefix <code>luaL_</code>.
4581
4582
4583 <p>
4584 All functions in the auxiliary library are built on
4585 top of the basic API,
4586 and so they provide nothing that cannot be done with this API.
4587
4588
4589 <p>
4590 Several functions in the auxiliary library are used to
4591 check C&nbsp;function arguments.
4592 Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
4593 All of these functions raise an error if the check is not satisfied.
4594 Because the error message is formatted for arguments
4595 (e.g., "<code>bad argument #1</code>"),
4596 you should not use these functions for other stack values.
4597
4598
4599
4600 <h2>4.1 - <a name="4.1">Functions and Types</a></h2>
4601
4602 <p>
4603 Here we list all functions and types from the auxiliary library
4604 in alphabetical order.
4605
4606
4607
4608 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3>
4609 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
4610
4611 <p>
4612 Adds the character <code>c</code> to the buffer <code>B</code>
4613 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4614
4615
4616
4617
4618
4619 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3>
4620 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
4621
4622 <p>
4623 Adds the string pointed to by <code>s</code> with length <code>l</code> to
4624 the buffer <code>B</code>
4625 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4626 The string may contain embedded zeros.
4627
4628
4629
4630
4631
4632 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3>
4633 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
4634
4635 <p>
4636 Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
4637 a string of length <code>n</code> previously copied to the
4638 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
4639
4640
4641
4642
4643
4644 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3>
4645 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
4646
4647 <p>
4648 Adds the zero-terminated string pointed to by <code>s</code>
4649 to the buffer <code>B</code>
4650 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4651 The string may not contain embedded zeros.
4652
4653
4654
4655
4656
4657 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3>
4658 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
4659
4660 <p>
4661 Adds the value at the top of the stack
4662 to the buffer <code>B</code>
4663 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4664 Pops the value.
4665
4666
4667 <p>
4668 This is the only function on string buffers that can (and must)
4669 be called with an extra element on the stack,
4670 which is the value to be added to the buffer.
4671
4672
4673
4674
4675
4676 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3>
4677 <pre>void luaL_argcheck (lua_State *L,
4678                     int cond,
4679                     int narg,
4680                     const char *extramsg);</pre>
4681
4682 <p>
4683 Checks whether <code>cond</code> is true.
4684 If not, raises an error with the following message,
4685 where <code>func</code> is retrieved from the call stack:
4686
4687 <pre>
4688      bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4689 </pre>
4690
4691
4692
4693
4694 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3>
4695 <pre>int luaL_argerror (lua_State *L, int narg, const char *extramsg);</pre>
4696
4697 <p>
4698 Raises an error with the following message,
4699 where <code>func</code> is retrieved from the call stack:
4700
4701 <pre>
4702      bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4703 </pre>
4704
4705 <p>
4706 This function never returns,
4707 but it is an idiom to use it in C&nbsp;functions
4708 as <code>return luaL_argerror(<em>args</em>)</code>.
4709
4710
4711
4712
4713
4714 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
4715 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
4716
4717 <p>
4718 Type for a <em>string buffer</em>.
4719
4720
4721 <p>
4722 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
4723 Its pattern of use is as follows:
4724
4725 <ul>
4726
4727 <li>First you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
4728
4729 <li>Then you initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
4730
4731 <li>
4732 Then you add string pieces to the buffer calling any of
4733 the <code>luaL_add*</code> functions.
4734 </li>
4735
4736 <li>
4737 You finish by calling <code>luaL_pushresult(&amp;b)</code>.
4738 This call leaves the final string on the top of the stack.
4739 </li>
4740
4741 </ul>
4742
4743 <p>
4744 During its normal operation,
4745 a string buffer uses a variable number of stack slots.
4746 So, while using a buffer, you cannot assume that you know where
4747 the top of the stack is.
4748 You can use the stack between successive calls to buffer operations
4749 as long as that use is balanced;
4750 that is,
4751 when you call a buffer operation,
4752 the stack is at the same level
4753 it was immediately after the previous buffer operation.
4754 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
4755 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
4756 level when the buffer was initialized,
4757 plus the final string on its top.
4758
4759
4760
4761
4762
4763 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3>
4764 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
4765
4766 <p>
4767 Initializes a buffer <code>B</code>.
4768 This function does not allocate any space;
4769 the buffer must be declared as a variable
4770 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4771
4772
4773
4774
4775
4776 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3>
4777 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
4778
4779 <p>
4780 Calls a metamethod.
4781
4782
4783 <p>
4784 If the object at index <code>obj</code> has a metatable and this
4785 metatable has a field <code>e</code>,
4786 this function calls this field and passes the object as its only argument.
4787 In this case this function returns 1 and pushes onto the
4788 stack the value returned by the call.
4789 If there is no metatable or no metamethod,
4790 this function returns 0 (without pushing any value on the stack).
4791
4792
4793
4794
4795
4796 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3>
4797 <pre>void luaL_checkany (lua_State *L, int narg);</pre>
4798
4799 <p>
4800 Checks whether the function has an argument
4801 of any type (including <b>nil</b>) at position <code>narg</code>.
4802
4803
4804
4805
4806
4807 <hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3>
4808 <pre>int luaL_checkint (lua_State *L, int narg);</pre>
4809
4810 <p>
4811 Checks whether the function argument <code>narg</code> is a number
4812 and returns this number cast to an <code>int</code>.
4813
4814
4815
4816
4817
4818 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3>
4819 <pre>lua_Integer luaL_checkinteger (lua_State *L, int narg);</pre>
4820
4821 <p>
4822 Checks whether the function argument <code>narg</code> is a number
4823 and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
4824
4825
4826
4827
4828
4829 <hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3>
4830 <pre>long luaL_checklong (lua_State *L, int narg);</pre>
4831
4832 <p>
4833 Checks whether the function argument <code>narg</code> is a number
4834 and returns this number cast to a <code>long</code>.
4835
4836
4837
4838
4839
4840 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3>
4841 <pre>const char *luaL_checklstring (lua_State *L, int narg, size_t *l);</pre>
4842
4843 <p>
4844 Checks whether the function argument <code>narg</code> is a string
4845 and returns this string;
4846 if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
4847 with the string's length.
4848
4849
4850
4851
4852
4853 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3>
4854 <pre>lua_Number luaL_checknumber (lua_State *L, int narg);</pre>
4855
4856 <p>
4857 Checks whether the function argument <code>narg</code> is a number
4858 and returns this number.
4859
4860
4861
4862
4863
4864 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3>
4865 <pre>int luaL_checkoption (lua_State *L,
4866                       int narg,
4867                       const char *def,
4868                       const char *const lst[]);</pre>
4869
4870 <p>
4871 Checks whether the function argument <code>narg</code> is a string and
4872 searches for this string in the array <code>lst</code>
4873 (which must be NULL-terminated).
4874 Returns the index in the array where the string was found.
4875 Raises an error if the argument is not a string or
4876 if the string cannot be found.
4877
4878
4879 <p>
4880 If <code>def</code> is not <code>NULL</code>,
4881 the function uses <code>def</code> as a default value when
4882 there is no argument <code>narg</code> or if this argument is <b>nil</b>.
4883
4884
4885 <p>
4886 This is a useful function for mapping strings to C&nbsp;enums.
4887 (The usual convention in Lua libraries is
4888 to use strings instead of numbers to select options.)
4889
4890
4891
4892
4893
4894 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3>
4895 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
4896
4897 <p>
4898 Grows the stack size to <code>top + sz</code> elements,
4899 raising an error if the stack cannot grow to that size.
4900 <code>msg</code> is an additional text to go into the error message.
4901
4902
4903
4904
4905
4906 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3>
4907 <pre>const char *luaL_checkstring (lua_State *L, int narg);</pre>
4908
4909 <p>
4910 Checks whether the function argument <code>narg</code> is a string
4911 and returns this string.
4912
4913
4914
4915
4916
4917 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3>
4918 <pre>void luaL_checktype (lua_State *L, int narg, int t);</pre>
4919
4920 <p>
4921 Checks whether the function argument <code>narg</code> has type <code>t</code>.
4922
4923
4924
4925
4926
4927 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3>
4928 <pre>void *luaL_checkudata (lua_State *L, int narg, const char *tname);</pre>
4929
4930 <p>
4931 Checks whether the function argument <code>narg</code> is a userdata
4932 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
4933
4934
4935
4936
4937
4938 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3>
4939 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
4940
4941 <p>
4942 Loads and runs the given file.
4943 It is defined as the following macro:
4944
4945 <pre>
4946      (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
4947 </pre><p>
4948 It returns 0 if there are no errors
4949 or 1 in case of errors.
4950
4951
4952
4953
4954
4955 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3>
4956 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
4957
4958 <p>
4959 Loads and runs the given string.
4960 It is defined as the following macro:
4961
4962 <pre>
4963      (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
4964 </pre><p>
4965 It returns 0 if there are no errors
4966 or 1 in case of errors.
4967
4968
4969
4970
4971
4972 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3>
4973 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
4974
4975 <p>
4976 Raises an error.
4977 The error message format is given by <code>fmt</code>
4978 plus any extra arguments,
4979 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
4980 It also adds at the beginning of the message the file name and
4981 the line number where the error occurred,
4982 if this information is available.
4983
4984
4985 <p>
4986 This function never returns,
4987 but it is an idiom to use it in C&nbsp;functions
4988 as <code>return luaL_error(<em>args</em>)</code>.
4989
4990
4991
4992
4993
4994 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3>
4995 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
4996
4997 <p>
4998 Pushes onto the stack the field <code>e</code> from the metatable
4999 of the object at index <code>obj</code>.
5000 If the object does not have a metatable,
5001 or if the metatable does not have this field,
5002 returns 0 and pushes nothing.
5003
5004
5005
5006
5007
5008 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3>
5009 <pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
5010
5011 <p>
5012 Pushes onto the stack the metatable associated with name <code>tname</code>
5013 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5014
5015
5016
5017
5018
5019 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3>
5020 <pre>const char *luaL_gsub (lua_State *L,
5021                        const char *s,
5022                        const char *p,
5023                        const char *r);</pre>
5024
5025 <p>
5026 Creates a copy of string <code>s</code> by replacing
5027 any occurrence of the string <code>p</code>
5028 with the string <code>r</code>.
5029 Pushes the resulting string on the stack and returns it.
5030
5031
5032
5033
5034
5035 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3>
5036 <pre>int luaL_loadbuffer (lua_State *L,
5037                      const char *buff,
5038                      size_t sz,
5039                      const char *name);</pre>
5040
5041 <p>
5042 Loads a buffer as a Lua chunk.
5043 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
5044 buffer pointed to by <code>buff</code> with size <code>sz</code>.
5045
5046
5047 <p>
5048 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5049 <code>name</code> is the chunk name,
5050 used for debug information and error messages.
5051
5052
5053
5054
5055
5056 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3>
5057 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
5058
5059 <p>
5060 Loads a file as a Lua chunk.
5061 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
5062 named <code>filename</code>.
5063 If <code>filename</code> is <code>NULL</code>,
5064 then it loads from the standard input.
5065 The first line in the file is ignored if it starts with a <code>#</code>.
5066
5067
5068 <p>
5069 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
5070 but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
5071 if it cannot open/read the file.
5072
5073
5074 <p>
5075 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5076 it does not run it.
5077
5078
5079
5080
5081
5082 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3>
5083 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
5084
5085 <p>
5086 Loads a string as a Lua chunk.
5087 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
5088 the zero-terminated string <code>s</code>.
5089
5090
5091 <p>
5092 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5093
5094
5095 <p>
5096 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5097 it does not run it.
5098
5099
5100
5101
5102
5103 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3>
5104 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
5105
5106 <p>
5107 If the registry already has the key <code>tname</code>,
5108 returns 0.
5109 Otherwise,
5110 creates a new table to be used as a metatable for userdata,
5111 adds it to the registry with key <code>tname</code>,
5112 and returns 1.
5113
5114
5115 <p>
5116 In both cases pushes onto the stack the final value associated
5117 with <code>tname</code> in the registry.
5118
5119
5120
5121
5122
5123 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3>
5124 <pre>lua_State *luaL_newstate (void);</pre>
5125
5126 <p>
5127 Creates a new Lua state.
5128 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
5129 allocator based on the standard&nbsp;C <code>realloc</code> function
5130 and then sets a panic function (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) that prints
5131 an error message to the standard error output in case of fatal
5132 errors.
5133
5134
5135 <p>
5136 Returns the new state,
5137 or <code>NULL</code> if there is a memory allocation error.
5138
5139
5140
5141
5142
5143 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3>
5144 <pre>void luaL_openlibs (lua_State *L);</pre>
5145
5146 <p>
5147 Opens all standard Lua libraries into the given state.
5148
5149
5150
5151
5152
5153 <hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3>
5154 <pre>int luaL_optint (lua_State *L, int narg, int d);</pre>
5155
5156 <p>
5157 If the function argument <code>narg</code> is a number,
5158 returns this number cast to an <code>int</code>.
5159 If this argument is absent or is <b>nil</b>,
5160 returns <code>d</code>.
5161 Otherwise, raises an error.
5162
5163
5164
5165
5166
5167 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3>
5168 <pre>lua_Integer luaL_optinteger (lua_State *L,
5169                              int narg,
5170                              lua_Integer d);</pre>
5171
5172 <p>
5173 If the function argument <code>narg</code> is a number,
5174 returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
5175 If this argument is absent or is <b>nil</b>,
5176 returns <code>d</code>.
5177 Otherwise, raises an error.
5178
5179
5180
5181
5182
5183 <hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3>
5184 <pre>long luaL_optlong (lua_State *L, int narg, long d);</pre>
5185
5186 <p>
5187 If the function argument <code>narg</code> is a number,
5188 returns this number cast to a <code>long</code>.
5189 If this argument is absent or is <b>nil</b>,
5190 returns <code>d</code>.
5191 Otherwise, raises an error.
5192
5193
5194
5195
5196
5197 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3>
5198 <pre>const char *luaL_optlstring (lua_State *L,
5199                              int narg,
5200                              const char *d,
5201                              size_t *l);</pre>
5202
5203 <p>
5204 If the function argument <code>narg</code> is a string,
5205 returns this string.
5206 If this argument is absent or is <b>nil</b>,
5207 returns <code>d</code>.
5208 Otherwise, raises an error.
5209
5210
5211 <p>
5212 If <code>l</code> is not <code>NULL</code>,
5213 fills the position <code>*l</code> with the results's length.
5214
5215
5216
5217
5218
5219 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3>
5220 <pre>lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);</pre>
5221
5222 <p>
5223 If the function argument <code>narg</code> is a number,
5224 returns this number.
5225 If this argument is absent or is <b>nil</b>,
5226 returns <code>d</code>.
5227 Otherwise, raises an error.
5228
5229
5230
5231
5232
5233 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3>
5234 <pre>const char *luaL_optstring (lua_State *L,
5235                             int narg,
5236                             const char *d);</pre>
5237
5238 <p>
5239 If the function argument <code>narg</code> is a string,
5240 returns this string.
5241 If this argument is absent or is <b>nil</b>,
5242 returns <code>d</code>.
5243 Otherwise, raises an error.
5244
5245
5246
5247
5248
5249 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3>
5250 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
5251
5252 <p>
5253 Returns an address to a space of size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>
5254 where you can copy a string to be added to buffer <code>B</code>
5255 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5256 After copying the string into this space you must call
5257 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add 
5258 it to the buffer.
5259
5260
5261
5262
5263
5264 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3>
5265 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
5266
5267 <p>
5268 Finishes the use of buffer <code>B</code> leaving the final string on
5269 the top of the stack.
5270
5271
5272
5273
5274
5275 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3>
5276 <pre>int luaL_ref (lua_State *L, int t);</pre>
5277
5278 <p>
5279 Creates and returns a <em>reference</em>,
5280 in the table at index <code>t</code>,
5281 for the object at the top of the stack (and pops the object).
5282
5283
5284 <p>
5285 A reference is a unique integer key.
5286 As long as you do not manually add integer keys into table <code>t</code>,
5287 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
5288 You can retrieve an object referred by reference <code>r</code>
5289 by calling <code>lua_rawgeti(L, t, r)</code>.
5290 Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
5291
5292
5293 <p>
5294 If the object at the top of the stack is <b>nil</b>,
5295 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
5296 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
5297 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
5298
5299
5300
5301
5302
5303 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
5304 <pre>typedef struct luaL_Reg {
5305   const char *name;
5306   lua_CFunction func;
5307 } luaL_Reg;</pre>
5308
5309 <p>
5310 Type for arrays of functions to be registered by
5311 <a href="#luaL_register"><code>luaL_register</code></a>.
5312 <code>name</code> is the function name and <code>func</code> is a pointer to
5313 the function.
5314 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
5315 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
5316
5317
5318
5319
5320
5321 <hr><h3><a name="luaL_register"><code>luaL_register</code></a></h3>
5322 <pre>void luaL_register (lua_State *L,
5323                     const char *libname,
5324                     const luaL_Reg *l);</pre>
5325
5326 <p>
5327 Opens a library.
5328
5329
5330 <p>
5331 When called with <code>libname</code> equal to <code>NULL</code>,
5332 it simply registers all functions in the list <code>l</code>
5333 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
5334
5335
5336 <p>
5337 When called with a non-null <code>libname</code>,
5338 <code>luaL_register</code> creates a new table <code>t</code>,
5339 sets it as the value of the global variable <code>libname</code>,
5340 sets it as the value of <code>package.loaded[libname]</code>,
5341 and registers on it all functions in the list <code>l</code>.
5342 If there is a table in <code>package.loaded[libname]</code> or in
5343 variable <code>libname</code>,
5344 reuses this table instead of creating a new one.
5345
5346
5347 <p>
5348 In any case the function leaves the table
5349 on the top of the stack.
5350
5351
5352
5353
5354
5355 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3>
5356 <pre>const char *luaL_typename (lua_State *L, int idx);</pre>
5357
5358 <p>
5359 Returns the name of the type of the value at index <code>idx</code>.
5360
5361
5362
5363
5364
5365 <hr><h3><a name="luaL_typerror"><code>luaL_typerror</code></a></h3>
5366 <pre>int luaL_typerror (lua_State *L, int narg, const char *tname);</pre>
5367
5368 <p>
5369 Generates an error with a message like the following:
5370
5371 <pre>
5372      <em>location</em>: bad argument <em>narg</em> to '<em>func</em>' (<em>tname</em> expected, got <em>rt</em>)
5373 </pre><p>
5374 where <code><em>location</em></code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
5375 <code><em>func</em></code> is the name of the current function,
5376 and <code><em>rt</em></code> is the type name of the actual argument.
5377
5378
5379
5380
5381
5382 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3>
5383 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
5384
5385 <p>
5386 Releases reference <code>ref</code> from the table at index <code>t</code>
5387 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
5388 The entry is removed from the table,
5389 so that the referred object can be collected.
5390 The reference <code>ref</code> is also freed to be used again.
5391
5392
5393 <p>
5394 If <code>ref</code> is <a href="#pdf-LUA_NOREF"><code>LUA_NOREF</code></a> or <a href="#pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>,
5395 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
5396
5397
5398
5399
5400
5401 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3>
5402 <pre>void luaL_where (lua_State *L, int lvl);</pre>
5403
5404 <p>
5405 Pushes onto the stack a string identifying the current position
5406 of the control at level <code>lvl</code> in the call stack.
5407 Typically this string has the following format:
5408
5409 <pre>
5410      <em>chunkname</em>:<em>currentline</em>:
5411 </pre><p>
5412 Level&nbsp;0 is the running function,
5413 level&nbsp;1 is the function that called the running function,
5414 etc.
5415
5416
5417 <p>
5418 This function is used to build a prefix for error messages.
5419
5420
5421
5422
5423
5424
5425
5426 <h1>5 - <a name="5">Standard Libraries</a></h1>
5427
5428 <p>
5429 The standard Lua libraries provide useful functions
5430 that are implemented directly through the C&nbsp;API.
5431 Some of these functions provide essential services to the language
5432 (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
5433 others provide access to "outside" services (e.g., I/O);
5434 and others could be implemented in Lua itself,
5435 but are quite useful or have critical performance requirements that
5436 deserve an implementation in C (e.g., <code>sort</code>).
5437
5438
5439 <p>
5440 All libraries are implemented through the official C&nbsp;API
5441 and are provided as separate C&nbsp;modules.
5442 Currently, Lua has the following standard libraries:
5443
5444 <ul>
5445
5446 <li>basic library;</li>
5447
5448 <li>package library;</li>
5449
5450 <li>string manipulation;</li>
5451
5452 <li>table manipulation;</li>
5453
5454 <li>mathematical functions (sin, log, etc.);</li>
5455
5456 <li>input and output;</li>
5457
5458 <li>operating system facilities;</li>
5459
5460 <li>debug facilities.</li>
5461
5462 </ul><p>
5463 Except for the basic and package libraries,
5464 each library provides all its functions as fields of a global table
5465 or as methods of its objects.
5466
5467
5468 <p>
5469 To have access to these libraries,
5470 the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
5471 which opens all standard libraries.
5472 Alternatively,
5473 it can open them individually by calling
5474 <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
5475 <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
5476 <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
5477 <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
5478 <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
5479 <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O and the Operating System libraries),
5480 and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
5481 These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>
5482 and should not be called directly:
5483 you must call them like any other Lua C&nbsp;function,
5484 e.g., by using <a href="#lua_call"><code>lua_call</code></a>.
5485
5486
5487
5488 <h2>5.1 - <a name="5.1">Basic Functions</a></h2>
5489
5490 <p>
5491 The basic library provides some core functions to Lua.
5492 If you do not include this library in your application,
5493 you should check carefully whether you need to provide 
5494 implementations for some of its facilities.
5495
5496
5497 <p>
5498 <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
5499 Issues an  error when
5500 the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
5501 otherwise, returns all its arguments.
5502 <code>message</code> is an error message;
5503 when absent, it defaults to "assertion failed!"
5504
5505
5506
5507
5508 <p>
5509 <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage (opt [, arg])</code></a></h3>
5510
5511
5512 <p>
5513 This function is a generic interface to the garbage collector.
5514 It performs different functions according to its first argument, <code>opt</code>:
5515
5516 <ul>
5517
5518 <li><b>"stop":</b>
5519 stops the garbage collector.
5520 </li>
5521
5522 <li><b>"restart":</b>
5523 restarts the garbage collector.
5524 </li>
5525
5526 <li><b>"collect":</b>
5527 performs a full garbage-collection cycle.
5528 </li>
5529
5530 <li><b>"count":</b>
5531 returns the total memory in use by Lua (in Kbytes).
5532 </li>
5533
5534 <li><b>"step":</b>
5535 performs a garbage-collection step.
5536 The step "size" is controlled by <code>arg</code>
5537 (larger values mean more steps) in a non-specified way.
5538 If you want to control the step size
5539 you must experimentally tune the value of <code>arg</code>.
5540 Returns <b>true</b> if the step finished a collection cycle.
5541 </li>
5542
5543 <li><b>"setpause":</b>
5544 sets <code>arg</code>/100 as the new value for the <em>pause</em> of
5545 the collector (see <a href="#2.10">&sect;2.10</a>).
5546 </li>
5547
5548 <li><b>"setstepmul":</b>
5549 sets <code>arg</code>/100 as the new value for the <em>step multiplier</em> of
5550 the collector (see <a href="#2.10">&sect;2.10</a>).
5551 </li>
5552
5553 </ul>
5554
5555
5556
5557 <p>
5558 <hr><h3><a name="pdf-dofile"><code>dofile (filename)</code></a></h3>
5559 Opens the named file and executes its contents as a Lua chunk.
5560 When called without arguments,
5561 <code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
5562 Returns all values returned by the chunk.
5563 In case of errors, <code>dofile</code> propagates the error
5564 to its caller (that is, <code>dofile</code> does not run in protected mode).
5565
5566
5567
5568
5569 <p>
5570 <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
5571 Terminates the last protected function called
5572 and returns <code>message</code> as the error message.
5573 Function <code>error</code> never returns.
5574
5575
5576 <p>
5577 Usually, <code>error</code> adds some information about the error position
5578 at the beginning of the message.
5579 The <code>level</code> argument specifies how to get the error position.
5580 With level&nbsp;1 (the default), the error position is where the
5581 <code>error</code> function was called.
5582 Level&nbsp;2 points the error to where the function
5583 that called <code>error</code> was called; and so on.
5584 Passing a level&nbsp;0 avoids the addition of error position information
5585 to the message.
5586
5587
5588
5589
5590 <p>
5591 <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
5592 A global variable (not a function) that
5593 holds the global environment (that is, <code>_G._G = _G</code>).
5594 Lua itself does not use this variable;
5595 changing its value does not affect any environment,
5596 nor vice-versa.
5597 (Use <a href="#pdf-setfenv"><code>setfenv</code></a> to change environments.)
5598
5599
5600
5601
5602 <p>
5603 <hr><h3><a name="pdf-getfenv"><code>getfenv ([f])</code></a></h3>
5604 Returns the current environment in use by the function.
5605 <code>f</code> can be a Lua function or a number
5606 that specifies the function at that stack level:
5607 Level&nbsp;1 is the function calling <code>getfenv</code>.
5608 If the given function is not a Lua function,
5609 or if <code>f</code> is 0,
5610 <code>getfenv</code> returns the global environment.
5611 The default for <code>f</code> is 1.
5612
5613
5614
5615
5616 <p>
5617 <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
5618
5619
5620 <p>
5621 If <code>object</code> does not have a metatable, returns <b>nil</b>.
5622 Otherwise,
5623 if the object's metatable has a <code>"__metatable"</code> field,
5624 returns the associated value.
5625 Otherwise, returns the metatable of the given object.
5626
5627
5628
5629
5630 <p>
5631 <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
5632
5633
5634 <p>
5635 Returns three values: an iterator function, the table <code>t</code>, and 0,
5636 so that the construction
5637
5638 <pre>
5639      for i,v in ipairs(t) do <em>body</em> end
5640 </pre><p>
5641 will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), &middot;&middot;&middot;,
5642 up to the first integer key absent from the table.
5643
5644
5645
5646
5647 <p>
5648 <hr><h3><a name="pdf-load"><code>load (func [, chunkname])</code></a></h3>
5649
5650
5651 <p>
5652 Loads a chunk using function <code>func</code> to get its pieces.
5653 Each call to <code>func</code> must return a string that concatenates
5654 with previous results.
5655 A return of <b>nil</b> (or no value) signals the end of the chunk.
5656
5657
5658 <p>
5659 If there are no errors, 
5660 returns the compiled chunk as a function;
5661 otherwise, returns <b>nil</b> plus the error message.
5662 The environment of the returned function is the global environment.
5663
5664
5665 <p>
5666 <code>chunkname</code> is used as the chunk name for error messages
5667 and debug information.
5668
5669
5670
5671
5672 <p>
5673 <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename])</code></a></h3>
5674
5675
5676 <p>
5677 Similar to <a href="#pdf-load"><code>load</code></a>,
5678 but gets the chunk from file <code>filename</code>
5679 or from the standard input,
5680 if no file name is given.
5681
5682
5683
5684
5685 <p>
5686 <hr><h3><a name="pdf-loadstring"><code>loadstring (string [, chunkname])</code></a></h3>
5687
5688
5689 <p>
5690 Similar to <a href="#pdf-load"><code>load</code></a>,
5691 but gets the chunk from the given string.
5692
5693
5694 <p>
5695 To load and run a given string, use the idiom
5696
5697 <pre>
5698      assert(loadstring(s))()
5699 </pre>
5700
5701
5702
5703 <p>
5704 <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
5705
5706
5707 <p>
5708 Allows a program to traverse all fields of a table.
5709 Its first argument is a table and its second argument
5710 is an index in this table.
5711 <code>next</code> returns the next index of the table
5712 and its associated value.
5713 When called with <b>nil</b> as its second argument,
5714 <code>next</code> returns an initial index
5715 and its associated value.
5716 When called with the last index,
5717 or with <b>nil</b> in an empty table,
5718 <code>next</code> returns <b>nil</b>.
5719 If the second argument is absent, then it is interpreted as <b>nil</b>.
5720 In particular,
5721 you can use <code>next(t)</code> to check whether a table is empty.
5722
5723
5724 <p>
5725 The order in which the indices are enumerated is not specified,
5726 <em>even for numeric indices</em>.
5727 (To traverse a table in numeric order,
5728 use a numerical <b>for</b> or the <a href="#pdf-ipairs"><code>ipairs</code></a> function.)
5729
5730
5731 <p>
5732 The behavior of <code>next</code> is <em>undefined</em> if,
5733 during the traversal,
5734 you assign any value to a non-existent field in the table.
5735 You may however modify existing fields.
5736 In particular, you may clear existing fields.
5737
5738
5739
5740
5741 <p>
5742 <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
5743
5744
5745 <p>
5746 Returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
5747 so that the construction
5748
5749 <pre>
5750      for k,v in pairs(t) do <em>body</em> end
5751 </pre><p>
5752 will iterate over all key&ndash;value pairs of table <code>t</code>.
5753
5754
5755 <p>
5756 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
5757 the table during its traversal.
5758
5759
5760
5761
5762 <p>
5763 <hr><h3><a name="pdf-pcall"><code>pcall (f, arg1, &middot;&middot;&middot;)</code></a></h3>
5764
5765
5766 <p>
5767 Calls function <code>f</code> with
5768 the given arguments in <em>protected mode</em>.
5769 This means that any error inside&nbsp;<code>f</code> is not propagated;
5770 instead, <code>pcall</code> catches the error
5771 and returns a status code.
5772 Its first result is the status code (a boolean),
5773 which is true if the call succeeds without errors.
5774 In such case, <code>pcall</code> also returns all results from the call,
5775 after this first result.
5776 In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
5777
5778
5779
5780
5781 <p>
5782 <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
5783 Receives any number of arguments,
5784 and prints their values to <code>stdout</code>,
5785 using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert them to strings.
5786 <code>print</code> is not intended for formatted output,
5787 but only as a quick way to show a value,
5788 typically for debugging.
5789 For formatted output, use <a href="#pdf-string.format"><code>string.format</code></a>.
5790
5791
5792
5793
5794 <p>
5795 <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
5796 Checks whether <code>v1</code> is equal to <code>v2</code>,
5797 without invoking any metamethod.
5798 Returns a boolean.
5799
5800
5801
5802
5803 <p>
5804 <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
5805 Gets the real value of <code>table[index]</code>,
5806 without invoking any metamethod.
5807 <code>table</code> must be a table;
5808 <code>index</code> may be any value.
5809
5810
5811
5812
5813 <p>
5814 <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
5815 Sets the real value of <code>table[index]</code> to <code>value</code>,
5816 without invoking any metamethod.
5817 <code>table</code> must be a table,
5818 <code>index</code> any value different from <b>nil</b>,
5819 and <code>value</code> any Lua value.
5820
5821
5822 <p>
5823 This function returns <code>table</code>.
5824
5825
5826
5827
5828 <p>
5829 <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
5830
5831
5832 <p>
5833 If <code>index</code> is a number,
5834 returns all arguments after argument number <code>index</code>.
5835 Otherwise, <code>index</code> must be the string <code>"#"</code>,
5836 and <code>select</code> returns the total number of extra arguments it received.
5837
5838
5839
5840
5841 <p>
5842 <hr><h3><a name="pdf-setfenv"><code>setfenv (f, table)</code></a></h3>
5843
5844
5845 <p>
5846 Sets the environment to be used by the given function.
5847 <code>f</code> can be a Lua function or a number
5848 that specifies the function at that stack level:
5849 Level&nbsp;1 is the function calling <code>setfenv</code>.
5850 <code>setfenv</code> returns the given function.
5851
5852
5853 <p>
5854 As a special case, when <code>f</code> is 0 <code>setfenv</code> changes
5855 the environment of the running thread.
5856 In this case, <code>setfenv</code> returns no values.
5857
5858
5859
5860
5861 <p>
5862 <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
5863
5864
5865 <p>
5866 Sets the metatable for the given table.
5867 (You cannot change the metatable of other types from Lua, only from&nbsp;C.)
5868 If <code>metatable</code> is <b>nil</b>,
5869 removes the metatable of the given table.
5870 If the original metatable has a <code>"__metatable"</code> field,
5871 raises an error.
5872
5873
5874 <p>
5875 This function returns <code>table</code>.
5876
5877
5878
5879
5880 <p>
5881 <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
5882 Tries to convert its argument to a number.
5883 If the argument is already a number or a string convertible
5884 to a number, then <code>tonumber</code> returns this number;
5885 otherwise, it returns <b>nil</b>.
5886
5887
5888 <p>
5889 An optional argument specifies the base to interpret the numeral.
5890 The base may be any integer between 2 and 36, inclusive.
5891 In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
5892 represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
5893 with '<code>Z</code>' representing 35.
5894 In base 10 (the default), the number may have a decimal part,
5895 as well as an optional exponent part (see <a href="#2.1">&sect;2.1</a>).
5896 In other bases, only unsigned integers are accepted.
5897
5898
5899
5900
5901 <p>
5902 <hr><h3><a name="pdf-tostring"><code>tostring (e)</code></a></h3>
5903 Receives an argument of any type and
5904 converts it to a string in a reasonable format.
5905 For complete control of how numbers are converted,
5906 use <a href="#pdf-string.format"><code>string.format</code></a>.
5907
5908
5909 <p>
5910 If the metatable of <code>e</code> has a <code>"__tostring"</code> field,
5911 then <code>tostring</code> calls the corresponding value
5912 with <code>e</code> as argument,
5913 and uses the result of the call as its result.
5914
5915
5916
5917
5918 <p>
5919 <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
5920 Returns the type of its only argument, coded as a string.
5921 The possible results of this function are
5922 "<code>nil</code>" (a string, not the value <b>nil</b>),
5923 "<code>number</code>",
5924 "<code>string</code>",
5925 "<code>boolean</code>",
5926 "<code>table</code>",
5927 "<code>function</code>",
5928 "<code>thread</code>",
5929 and "<code>userdata</code>".
5930
5931
5932
5933
5934 <p>
5935 <hr><h3><a name="pdf-unpack"><code>unpack (list [, i [, j]])</code></a></h3>
5936 Returns the elements from the given table.
5937 This function is equivalent to
5938
5939 <pre>
5940      return list[i], list[i+1], &middot;&middot;&middot;, list[j]
5941 </pre><p>
5942 except that the above code can be written only for a fixed number
5943 of elements.
5944 By default, <code>i</code> is&nbsp;1 and <code>j</code> is the length of the list,
5945 as defined by the length operator (see <a href="#2.5.5">&sect;2.5.5</a>).
5946
5947
5948
5949
5950 <p>
5951 <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
5952 A global variable (not a function) that
5953 holds a string containing the current interpreter version.
5954 The current contents of this variable is "<code>Lua 5.1</code>".
5955
5956
5957
5958
5959 <p>
5960 <hr><h3><a name="pdf-xpcall"><code>xpcall (f, err)</code></a></h3>
5961
5962
5963 <p>
5964 This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
5965 except that you can set a new error handler.
5966
5967
5968 <p>
5969 <code>xpcall</code> calls function <code>f</code> in protected mode,
5970 using <code>err</code> as the error handler.
5971 Any error inside <code>f</code> is not propagated;
5972 instead, <code>xpcall</code> catches the error,
5973 calls the <code>err</code> function with the original error object,
5974 and returns a status code.
5975 Its first result is the status code (a boolean),
5976 which is true if the call succeeds without errors.
5977 In this case, <code>xpcall</code> also returns all results from the call,
5978 after this first result.
5979 In case of any error,
5980 <code>xpcall</code> returns <b>false</b> plus the result from <code>err</code>.
5981
5982
5983
5984
5985
5986
5987
5988 <h2>5.2 - <a name="5.2">Coroutine Manipulation</a></h2>
5989
5990 <p>
5991 The operations related to coroutines comprise a sub-library of
5992 the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
5993 See <a href="#2.11">&sect;2.11</a> for a general description of coroutines.
5994
5995
5996 <p>
5997 <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
5998
5999
6000 <p>
6001 Creates a new coroutine, with body <code>f</code>.
6002 <code>f</code> must be a Lua function.
6003 Returns this new coroutine,
6004 an object with type <code>"thread"</code>.
6005
6006
6007
6008
6009 <p>
6010 <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
6011
6012
6013 <p>
6014 Starts or continues the execution of coroutine <code>co</code>.
6015 The first time you resume a coroutine,
6016 it starts running its body.
6017 The values <code>val1</code>, &middot;&middot;&middot; are passed
6018 as the arguments to the body function.
6019 If the coroutine has yielded,
6020 <code>resume</code> restarts it;
6021 the values <code>val1</code>, &middot;&middot;&middot; are passed
6022 as the results from the yield.
6023
6024
6025 <p>
6026 If the coroutine runs without any errors,
6027 <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
6028 (if the coroutine yields) or any values returned by the body function
6029 (if the coroutine terminates).
6030 If there is any error,
6031 <code>resume</code> returns <b>false</b> plus the error message.
6032
6033
6034
6035
6036 <p>
6037 <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
6038
6039
6040 <p>
6041 Returns the running coroutine,
6042 or <b>nil</b> when called by the main thread.
6043
6044
6045
6046
6047 <p>
6048 <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
6049
6050
6051 <p>
6052 Returns the status of coroutine <code>co</code>, as a string:
6053 <code>"running"</code>,
6054 if the coroutine is running (that is, it called <code>status</code>);
6055 <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
6056 or if it has not started running yet;
6057 <code>"normal"</code> if the coroutine is active but not running
6058 (that is, it has resumed another coroutine);
6059 and <code>"dead"</code> if the coroutine has finished its body function,
6060 or if it has stopped with an error.
6061
6062
6063
6064
6065 <p>
6066 <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
6067
6068
6069 <p>
6070 Creates a new coroutine, with body <code>f</code>.
6071 <code>f</code> must be a Lua function.
6072 Returns a function that resumes the coroutine each time it is called.
6073 Any arguments passed to the function behave as the
6074 extra arguments to <code>resume</code>.
6075 Returns the same values returned by <code>resume</code>,
6076 except the first boolean.
6077 In case of error, propagates the error.
6078
6079
6080
6081
6082 <p>
6083 <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
6084
6085
6086 <p>
6087 Suspends the execution of the calling coroutine.
6088 The coroutine cannot be running a C&nbsp;function,
6089 a metamethod, or an iterator.
6090 Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
6091
6092
6093
6094
6095
6096
6097
6098 <h2>5.3 - <a name="5.3">Modules</a></h2>
6099
6100 <p>
6101 The package library provides basic
6102 facilities for loading and building modules in Lua.
6103 It exports two of its functions directly in the global environment:
6104 <a href="#pdf-require"><code>require</code></a> and <a href="#pdf-module"><code>module</code></a>.
6105 Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
6106
6107
6108 <p>
6109 <hr><h3><a name="pdf-module"><code>module (name [, &middot;&middot;&middot;])</code></a></h3>
6110
6111
6112 <p>
6113 Creates a module.
6114 If there is a table in <code>package.loaded[name]</code>,
6115 this table is the module.
6116 Otherwise, if there is a global table <code>t</code> with the given name,
6117 this table is the module.
6118 Otherwise creates a new table <code>t</code> and
6119 sets it as the value of the global <code>name</code> and
6120 the value of <code>package.loaded[name]</code>.
6121 This function also initializes <code>t._NAME</code> with the given name,
6122 <code>t._M</code> with the module (<code>t</code> itself),
6123 and <code>t._PACKAGE</code> with the package name
6124 (the full module name minus last component; see below).
6125 Finally, <code>module</code> sets <code>t</code> as the new environment
6126 of the current function and the new value of <code>package.loaded[name]</code>,
6127 so that <a href="#pdf-require"><code>require</code></a> returns <code>t</code>.
6128
6129
6130 <p>
6131 If <code>name</code> is a compound name
6132 (that is, one with components separated by dots),
6133 <code>module</code> creates (or reuses, if they already exist)
6134 tables for each component.
6135 For instance, if <code>name</code> is <code>a.b.c</code>,
6136 then <code>module</code> stores the module table in field <code>c</code> of
6137 field <code>b</code> of global <code>a</code>.
6138
6139
6140 <p>
6141 This function may receive optional <em>options</em> after
6142 the module name,
6143 where each option is a function to be applied over the module.
6144
6145
6146
6147
6148 <p>
6149 <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
6150
6151
6152 <p>
6153 Loads the given module.
6154 The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
6155 to determine whether <code>modname</code> is already loaded.
6156 If it is, then <code>require</code> returns the value stored
6157 at <code>package.loaded[modname]</code>.
6158 Otherwise, it tries to find a <em>loader</em> for the module.
6159
6160
6161 <p>
6162 To find a loader,
6163 first <code>require</code> queries <code>package.preload[modname]</code>.
6164 If it has a value,
6165 this value (which should be a function) is the loader.
6166 Otherwise <code>require</code> searches for a Lua loader using the
6167 path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
6168 If that also fails, it searches for a C&nbsp;loader using the
6169 path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
6170 If that also fails,
6171 it tries an <em>all-in-one</em> loader (see below).
6172
6173
6174 <p>
6175 When loading a C&nbsp;library,
6176 <code>require</code> first uses a dynamic link facility to link the
6177 application with the library.
6178 Then it tries to find a C&nbsp;function inside this library to
6179 be used as the loader.
6180 The name of this C&nbsp;function is the string "<code>luaopen_</code>"
6181 concatenated with a copy of the module name where each dot
6182 is replaced by an underscore.
6183 Moreover, if the module name has a hyphen,
6184 its prefix up to (and including) the first hyphen is removed.
6185 For instance, if the module name is <code>a.v1-b.c</code>,
6186 the function name will be <code>luaopen_b_c</code>.
6187
6188
6189 <p>
6190 If <code>require</code> finds neither a Lua library nor a
6191 C&nbsp;library for a module,
6192 it calls the <em>all-in-one loader</em>.
6193 This loader searches the C&nbsp;path for a library for
6194 the root name of the given module.
6195 For instance, when requiring <code>a.b.c</code>,
6196 it will search for a C&nbsp;library for <code>a</code>.
6197 If found, it looks into it for an open function for
6198 the submodule;
6199 in our example, that would be <code>luaopen_a_b_c</code>.
6200 With this facility, a package can pack several C&nbsp;submodules
6201 into one single library,
6202 with each submodule keeping its original open function.
6203
6204
6205 <p>
6206 Once a loader is found,
6207 <code>require</code> calls the loader with a single argument, <code>modname</code>.
6208 If the loader returns any value,
6209 <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
6210 If the loader returns no value and
6211 has not assigned any value to <code>package.loaded[modname]</code>,
6212 then <code>require</code> assigns <b>true</b> to this entry.
6213 In any case, <code>require</code> returns the
6214 final value of <code>package.loaded[modname]</code>.
6215
6216
6217 <p>
6218 If there is any error loading or running the module,
6219 or if it cannot find any loader for the module,
6220 then <code>require</code> signals an error. 
6221
6222
6223
6224
6225 <p>
6226 <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
6227
6228
6229 <p>
6230 The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
6231
6232
6233 <p>
6234 Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
6235 it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
6236 using the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
6237 (plus another default path defined in <code>luaconf.h</code>).
6238
6239
6240
6241
6242 <p>
6243
6244 <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
6245
6246
6247 <p>
6248 A table used by <a href="#pdf-require"><code>require</code></a> to control which
6249 modules are already loaded.
6250 When you require a module <code>modname</code> and
6251 <code>package.loaded[modname]</code> is not false,
6252 <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
6253
6254
6255
6256
6257 <p>
6258 <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
6259
6260
6261 <p>
6262 Dynamically links the host program with the C&nbsp;library <code>libname</code>.
6263 Inside this library, looks for a function <code>funcname</code>
6264 and returns this function as a C&nbsp;function.
6265 (So, <code>funcname</code> must follow the protocol (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>)).
6266
6267
6268 <p>
6269 This is a low-level function.
6270 It completely bypasses the package and module system.
6271 Unlike <a href="#pdf-require"><code>require</code></a>,
6272 it does not perform any path searching and
6273 does not automatically adds extensions.
6274 <code>libname</code> must be the complete file name of the C&nbsp;library,
6275 including if necessary a path and extension.
6276 <code>funcname</code> must be the exact name exported by the C&nbsp;library
6277 (which may depend on the C&nbsp;compiler and linker used).
6278
6279
6280 <p>
6281 This function is not supported by ANSI C.
6282 As such, it is only available on some platforms
6283 (Windows, Linux, Mac OS X, Solaris, BSD,
6284 plus other Unix systems that support the <code>dlfcn</code> standard).
6285
6286
6287
6288
6289 <p>
6290 <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
6291
6292
6293 <p>
6294 The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
6295
6296
6297 <p>
6298 At start-up, Lua initializes this variable with
6299 the value of the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
6300 with a default path defined in <code>luaconf.h</code>,
6301 if the environment variable is not defined.
6302 Any "<code>;;</code>" in the value of the environment variable
6303 is replaced by the default path.
6304
6305
6306 <p>
6307 A path is a sequence of <em>templates</em> separated by semicolons.
6308 For each template, <a href="#pdf-require"><code>require</code></a> will change each interrogation
6309 mark in the template by <code>filename</code>,
6310 which is <code>modname</code> with each dot replaced by a
6311 "directory separator" (such as "<code>/</code>" in Unix);
6312 then it will try to load the resulting file name.
6313 So, for instance, if the Lua path is
6314
6315 <pre>
6316      "./?.lua;./?.lc;/usr/local/?/init.lua"
6317 </pre><p>
6318 the search for a Lua loader for module <code>foo</code>
6319 will try to load the files
6320 <code>./foo.lua</code>, <code>./foo.lc</code>, and
6321 <code>/usr/local/foo/init.lua</code>, in that order.
6322
6323
6324
6325
6326 <p>
6327 <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
6328
6329
6330 <p>
6331 A table to store loaders for specific modules
6332 (see <a href="#pdf-require"><code>require</code></a>).
6333
6334
6335
6336
6337 <p>
6338 <hr><h3><a name="pdf-package.seeall"><code>package.seeall (module)</code></a></h3>
6339
6340
6341 <p>
6342 Sets a metatable for <code>module</code> with
6343 its <code>__index</code> field referring to the global environment,
6344 so that this module inherits values
6345 from the global environment.
6346 To be used as an option to function <a href="#pdf-module"><code>module</code></a>.
6347
6348
6349
6350
6351
6352
6353
6354 <h2>5.4 - <a name="5.4">String Manipulation</a></h2>
6355
6356 <p>
6357 This library provides generic functions for string manipulation,
6358 such as finding and extracting substrings, and pattern matching.
6359 When indexing a string in Lua, the first character is at position&nbsp;1
6360 (not at&nbsp;0, as in C).
6361 Indices are allowed to be negative and are interpreted as indexing backwards,
6362 from the end of the string.
6363 Thus, the last character is at position -1, and so on.
6364
6365
6366 <p>
6367 The string library provides all its functions inside the table
6368 <a name="pdf-string"><code>string</code></a>.
6369 It also sets a metatable for strings
6370 where the <code>__index</code> field points to the <code>string</code> table.
6371 Therefore, you can use the string functions in object-oriented style.
6372 For instance, <code>string.byte(s, i)</code>
6373 can be written as <code>s:byte(i)</code>.
6374
6375
6376 <p>
6377 <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
6378 Returns the internal numerical codes of the characters <code>s[i]</code>,
6379 <code>s[i+1]</code>, &middot;&middot;&middot;, <code>s[j]</code>.
6380 The default value for <code>i</code> is&nbsp;1;
6381 the default value for <code>j</code> is&nbsp;<code>i</code>.
6382
6383
6384 <p>
6385 Note that numerical codes are not necessarily portable across platforms.
6386
6387
6388
6389
6390 <p>
6391 <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
6392 Receives zero or more integers.
6393 Returns a string with length equal to the number of arguments,
6394 in which each character has the internal numerical code equal
6395 to its corresponding argument.
6396
6397
6398 <p>
6399 Note that numerical codes are not necessarily portable across platforms.
6400
6401
6402
6403
6404 <p>
6405 <hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
6406
6407
6408 <p>
6409 Returns a string containing a binary representation of the given function,
6410 so that a later <a href="#pdf-loadstring"><code>loadstring</code></a> on this string returns
6411 a copy of the function.
6412 <code>function</code> must be a Lua function without upvalues.
6413
6414
6415
6416
6417 <p>
6418 <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
6419 Looks for the first match of
6420 <code>pattern</code> in the string <code>s</code>.
6421 If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
6422 where this occurrence starts and ends;
6423 otherwise, it returns <b>nil</b>.
6424 A third, optional numerical argument <code>init</code> specifies
6425 where to start the search;
6426 its default value is&nbsp;1 and may be negative.
6427 A value of <b>true</b> as a fourth, optional argument <code>plain</code>
6428 turns off the pattern matching facilities,
6429 so the function does a plain "find substring" operation,
6430 with no characters in <code>pattern</code> being considered "magic".
6431 Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
6432
6433
6434 <p>
6435 If the pattern has captures,
6436 then in a successful match
6437 the captured values are also returned,
6438 after the two indices.
6439
6440
6441
6442
6443 <p>
6444 <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
6445 Returns a formatted version of its variable number of arguments
6446 following the description given in its first argument (which must be a string).
6447 The format string follows the same rules as the <code>printf</code> family of
6448 standard C&nbsp;functions.
6449 The only differences are that the options/modifiers
6450 <code>*</code>, <code>l</code>, <code>L</code>, <code>n</code>, <code>p</code>,
6451 and <code>h</code> are not supported
6452 and that there is an extra option, <code>q</code>.
6453 The <code>q</code> option formats a string in a form suitable to be safely read
6454 back by the Lua interpreter:
6455 the string is written between double quotes,
6456 and all double quotes, newlines, embedded zeros,
6457 and backslashes in the string
6458 are correctly escaped when written.
6459 For instance, the call
6460
6461 <pre>
6462      string.format('%q', 'a string with "quotes" and \n new line')
6463 </pre><p>
6464 will produce the string:
6465
6466 <pre>
6467      "a string with \"quotes\" and \
6468       new line"
6469 </pre>
6470
6471 <p>
6472 The options <code>c</code>, <code>d</code>, <code>E</code>, <code>e</code>, <code>f</code>,
6473 <code>g</code>, <code>G</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> all
6474 expect a number as argument,
6475 whereas <code>q</code> and <code>s</code> expect a string.
6476
6477
6478 <p>
6479 This function does not accept string values
6480 containing embedded zeros,
6481 except as arguments to the <code>q</code> option.
6482
6483
6484
6485
6486 <p>
6487 <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
6488 Returns an iterator function that,
6489 each time it is called,
6490 returns the next captures from <code>pattern</code> over string <code>s</code>.
6491 If <code>pattern</code> specifies no captures,
6492 then the whole match is produced in each call.
6493
6494
6495 <p>
6496 As an example, the following loop
6497
6498 <pre>
6499      s = "hello world from Lua"
6500      for w in string.gmatch(s, "%a+") do
6501        print(w)
6502      end
6503 </pre><p>
6504 will iterate over all the words from string <code>s</code>,
6505 printing one per line.
6506 The next example collects all pairs <code>key=value</code> from the
6507 given string into a table:
6508
6509 <pre>
6510      t = {}
6511      s = "from=world, to=Lua"
6512      for k, v in string.gmatch(s, "(%w+)=(%w+)") do
6513        t[k] = v
6514      end
6515 </pre>
6516
6517 <p>
6518 For this function, a '<code>^</code>' at the start of a pattern does not
6519 work as an anchor, as this would prevent the iteration.
6520
6521
6522
6523
6524 <p>
6525 <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
6526 Returns a copy of <code>s</code>
6527 in which all occurrences of the <code>pattern</code> have been
6528 replaced by a replacement string specified by <code>repl</code>,
6529 which may be a string, a table, or a function.
6530 <code>gsub</code> also returns, as its second value,
6531 the total number of substitutions made.
6532
6533
6534 <p>
6535 If <code>repl</code> is a string, then its value is used for replacement.
6536 The character&nbsp;<code>%</code> works as an escape character:
6537 any sequence in <code>repl</code> of the form <code>%<em>n</em></code>,
6538 with <em>n</em> between 1 and 9,
6539 stands for the value of the <em>n</em>-th captured substring (see below).
6540 The sequence <code>%0</code> stands for the whole match.
6541 The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
6542
6543
6544 <p>
6545 If <code>repl</code> is a table, then the table is queried for every match,
6546 using the first capture as the key;
6547 if the pattern specifies no captures,
6548 then the whole match is used as the key.
6549
6550
6551 <p>
6552 If <code>repl</code> is a function, then this function is called every time a
6553 match occurs, with all captured substrings passed as arguments,
6554 in order;
6555 if the pattern specifies no captures,
6556 then the whole match is passed as a sole argument.
6557
6558
6559 <p>
6560 If the value returned by the table query or by the function call
6561 is a string or a number,
6562 then it is used as the replacement string;
6563 otherwise, if it is <b>false</b> or <b>nil</b>,
6564 then there is no replacement
6565 (that is, the original match is kept in the string).
6566
6567
6568 <p>
6569 The optional last parameter <code>n</code> limits
6570 the maximum number of substitutions to occur.
6571 For instance, when <code>n</code> is 1 only the first occurrence of
6572 <code>pattern</code> is replaced.
6573
6574
6575 <p>
6576 Here are some examples:
6577
6578 <pre>
6579      x = string.gsub("hello world", "(%w+)", "%1 %1")
6580      --&gt; x="hello hello world world"
6581      
6582      x = string.gsub("hello world", "%w+", "%0 %0", 1)
6583      --&gt; x="hello hello world"
6584      
6585      x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
6586      --&gt; x="world hello Lua from"
6587      
6588      x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
6589      --&gt; x="home = /home/roberto, user = roberto"
6590      
6591      x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
6592            return loadstring(s)()
6593          end)
6594      --&gt; x="4+5 = 9"
6595      
6596      local t = {name="lua", version="5.1"}
6597      x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
6598      --&gt; x="lua-5.1.tar.gz"
6599 </pre>
6600
6601
6602
6603 <p>
6604 <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
6605 Receives a string and returns its length.
6606 The empty string <code>""</code> has length 0.
6607 Embedded zeros are counted,
6608 so <code>"a\000bc\000"</code> has length 5.
6609
6610
6611
6612
6613 <p>
6614 <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
6615 Receives a string and returns a copy of this string with all
6616 uppercase letters changed to lowercase.
6617 All other characters are left unchanged.
6618 The definition of what an uppercase letter is depends on the current locale.
6619
6620
6621
6622
6623 <p>
6624 <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
6625 Looks for the first <em>match</em> of
6626 <code>pattern</code> in the string <code>s</code>.
6627 If it finds one, then <code>match</code> returns
6628 the captures from the pattern;
6629 otherwise it returns <b>nil</b>.
6630 If <code>pattern</code> specifies no captures,
6631 then the whole match is returned.
6632 A third, optional numerical argument <code>init</code> specifies
6633 where to start the search;
6634 its default value is&nbsp;1 and may be negative.
6635
6636
6637
6638
6639 <p>
6640 <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n)</code></a></h3>
6641 Returns a string that is the concatenation of <code>n</code> copies of
6642 the string <code>s</code>.
6643
6644
6645
6646
6647 <p>
6648 <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
6649 Returns a string that is the string <code>s</code> reversed.
6650
6651
6652
6653
6654 <p>
6655 <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
6656 Returns the substring of <code>s</code> that
6657 starts at <code>i</code>  and continues until <code>j</code>;
6658 <code>i</code> and <code>j</code> may be negative.
6659 If <code>j</code> is absent, then it is assumed to be equal to -1
6660 (which is the same as the string length).
6661 In particular,
6662 the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
6663 with length <code>j</code>,
6664 and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
6665 with length <code>i</code>.
6666
6667
6668
6669
6670 <p>
6671 <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
6672 Receives a string and returns a copy of this string with all
6673 lowercase letters changed to uppercase.
6674 All other characters are left unchanged.
6675 The definition of what a lowercase letter is depends on the current locale.
6676
6677
6678
6679 <h3>5.4.1 - <a name="5.4.1">Patterns</a></h3>
6680
6681
6682 <h4>Character Class:</h4><p>
6683 A <em>character class</em> is used to represent a set of characters.
6684 The following combinations are allowed in describing a character class:
6685
6686 <ul>
6687
6688 <li><b><em>x</em>:</b>
6689 (where <em>x</em> is not one of the <em>magic characters</em>
6690 <code>^$()%.[]*+-?</code>)
6691 represents the character <em>x</em> itself.
6692 </li>
6693
6694 <li><b><code>.</code>:</b> (a dot) represents all characters.</li>
6695
6696 <li><b><code>%a</code>:</b> represents all letters.</li>
6697
6698 <li><b><code>%c</code>:</b> represents all control characters.</li>
6699
6700 <li><b><code>%d</code>:</b> represents all digits.</li>
6701
6702 <li><b><code>%l</code>:</b> represents all lowercase letters.</li>
6703
6704 <li><b><code>%p</code>:</b> represents all punctuation characters.</li>
6705
6706 <li><b><code>%s</code>:</b> represents all space characters.</li>
6707
6708 <li><b><code>%u</code>:</b> represents all uppercase letters.</li>
6709
6710 <li><b><code>%w</code>:</b> represents all alphanumeric characters.</li>
6711
6712 <li><b><code>%x</code>:</b> represents all hexadecimal digits.</li>
6713
6714 <li><b><code>%z</code>:</b> represents the character with representation 0.</li>
6715
6716 <li><b><code>%<em>x</em></code>:</b> (where <em>x</em> is any non-alphanumeric character)
6717 represents the character <em>x</em>.
6718 This is the standard way to escape the magic characters.
6719 Any punctuation character (even the non magic)
6720 can be preceded by a '<code>%</code>'
6721 when used to represent itself in a pattern.
6722 </li>
6723
6724 <li><b><code>[<em>set</em>]</code>:</b>
6725 represents the class which is the union of all
6726 characters in <em>set</em>.
6727 A range of characters may be specified by
6728 separating the end characters of the range with a '<code>-</code>'.
6729 All classes <code>%</code><em>x</em> described above may also be used as
6730 components in <em>set</em>.
6731 All other characters in <em>set</em> represent themselves.
6732 For example, <code>[%w_]</code> (or <code>[_%w]</code>)
6733 represents all alphanumeric characters plus the underscore,
6734 <code>[0-7]</code> represents the octal digits,
6735 and <code>[0-7%l%-]</code> represents the octal digits plus
6736 the lowercase letters plus the '<code>-</code>' character.
6737
6738
6739 <p>
6740 The interaction between ranges and classes is not defined.
6741 Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
6742 have no meaning.
6743 </li>
6744
6745 <li><b><code>[^<em>set</em>]</code>:</b>
6746 represents the complement of <em>set</em>,
6747 where <em>set</em> is interpreted as above.
6748 </li>
6749
6750 </ul><p>
6751 For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
6752 the corresponding uppercase letter represents the complement of the class.
6753 For instance, <code>%S</code> represents all non-space characters.
6754
6755
6756 <p>
6757 The definitions of letter, space, and other character groups
6758 depend on the current locale.
6759 In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
6760
6761
6762
6763
6764
6765 <h4>Pattern Item:</h4><p>
6766 A <em>pattern item</em> may be
6767
6768 <ul>
6769
6770 <li>
6771 a single character class,
6772 which matches any single character in the class;
6773 </li>
6774
6775 <li>
6776 a single character class followed by '<code>*</code>',
6777 which matches 0 or more repetitions of characters in the class.
6778 These repetition items will always match the longest possible sequence;
6779 </li>
6780
6781 <li>
6782 a single character class followed by '<code>+</code>',
6783 which matches 1 or more repetitions of characters in the class.
6784 These repetition items will always match the longest possible sequence;
6785 </li>
6786
6787 <li>
6788 a single character class followed by '<code>-</code>',
6789 which also matches 0 or more repetitions of characters in the class.
6790 Unlike '<code>*</code>',
6791 these repetition items will always match the <em>shortest</em> possible sequence;
6792 </li>
6793
6794 <li>
6795 a single character class followed by '<code>?</code>',
6796 which matches 0 or 1 occurrence of a character in the class;
6797 </li>
6798
6799 <li>
6800 <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
6801 such item matches a substring equal to the <em>n</em>-th captured string
6802 (see below);
6803 </li>
6804
6805 <li>
6806 <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
6807 such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
6808 and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
6809 This means that, if one reads the string from left to right,
6810 counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
6811 the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
6812 For instance, the item <code>%b()</code> matches expressions with
6813 balanced parentheses.
6814 </li>
6815
6816 </ul>
6817
6818
6819
6820
6821 <h4>Pattern:</h4><p>
6822 A <em>pattern</em> is a sequence of pattern items.
6823 A '<code>^</code>' at the beginning of a pattern anchors the match at the
6824 beginning of the subject string.
6825 A '<code>$</code>' at the end of a pattern anchors the match at the
6826 end of the subject string.
6827 At other positions,
6828 '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
6829
6830
6831
6832
6833
6834 <h4>Captures:</h4><p>
6835 A pattern may contain sub-patterns enclosed in parentheses;
6836 they describe <em>captures</em>.
6837 When a match succeeds, the substrings of the subject string
6838 that match captures are stored (<em>captured</em>) for future use.
6839 Captures are numbered according to their left parentheses.
6840 For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
6841 the part of the string matching <code>"a*(.)%w(%s*)"</code> is
6842 stored as the first capture (and therefore has number&nbsp;1);
6843 the character matching "<code>.</code>" is captured with number&nbsp;2,
6844 and the part matching "<code>%s*</code>" has number&nbsp;3.
6845
6846
6847 <p>
6848 As a special case, the empty capture <code>()</code> captures
6849 the current string position (a number).
6850 For instance, if we apply the pattern <code>"()aa()"</code> on the
6851 string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
6852
6853
6854 <p>
6855 A pattern cannot contain embedded zeros.  Use <code>%z</code> instead.
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867 <h2>5.5 - <a name="5.5">Table Manipulation</a></h2><p>
6868 This library provides generic functions for table manipulation.
6869 It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
6870
6871
6872 <p>
6873 Most functions in the table library assume that the table
6874 represents an array or a list.
6875 For these functions, when we talk about the "length" of a table
6876 we mean the result of the length operator.
6877
6878
6879 <p>
6880 <hr><h3><a name="pdf-table.concat"><code>table.concat (table [, sep [, i [, j]]])</code></a></h3>
6881 Given an array where all elements are strings or numbers,
6882 returns <code>table[i]..sep..table[i+1] &middot;&middot;&middot; sep..table[j]</code>.
6883 The default value for <code>sep</code> is the empty string,
6884 the default for <code>i</code> is 1,
6885 and the default for <code>j</code> is the length of the table.
6886 If <code>i</code> is greater than <code>j</code>, returns the empty string.
6887
6888
6889
6890
6891 <p>
6892 <hr><h3><a name="pdf-table.insert"><code>table.insert (table, [pos,] value)</code></a></h3>
6893
6894
6895 <p>
6896 Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>,
6897 shifting up other elements to open space, if necessary.
6898 The default value for <code>pos</code> is <code>n+1</code>,
6899 where <code>n</code> is the length of the table (see <a href="#2.5.5">&sect;2.5.5</a>),
6900 so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
6901 of table <code>t</code>.
6902
6903
6904
6905
6906 <p>
6907 <hr><h3><a name="pdf-table.maxn"><code>table.maxn (table)</code></a></h3>
6908
6909
6910 <p>
6911 Returns the largest positive numerical index of the given table,
6912 or zero if the table has no positive numerical indices.
6913 (To do its job this function does a linear traversal of
6914 the whole table.) 
6915
6916
6917
6918
6919 <p>
6920 <hr><h3><a name="pdf-table.remove"><code>table.remove (table [, pos])</code></a></h3>
6921
6922
6923 <p>
6924 Removes from <code>table</code> the element at position <code>pos</code>,
6925 shifting down other elements to close the space, if necessary.
6926 Returns the value of the removed element.
6927 The default value for <code>pos</code> is <code>n</code>,
6928 where <code>n</code> is the length of the table,
6929 so that a call <code>table.remove(t)</code> removes the last element
6930 of table <code>t</code>.
6931
6932
6933
6934
6935 <p>
6936 <hr><h3><a name="pdf-table.sort"><code>table.sort (table [, comp])</code></a></h3>
6937 Sorts table elements in a given order, <em>in-place</em>,
6938 from <code>table[1]</code> to <code>table[n]</code>,
6939 where <code>n</code> is the length of the table.
6940 If <code>comp</code> is given,
6941 then it must be a function that receives two table elements,
6942 and returns true
6943 when the first is less than the second
6944 (so that <code>not comp(a[i+1],a[i])</code> will be true after the sort).
6945 If <code>comp</code> is not given,
6946 then the standard Lua operator <code>&lt;</code> is used instead.
6947
6948
6949 <p>
6950 The sort algorithm is not stable;
6951 that is, elements considered equal by the given order
6952 may have their relative positions changed by the sort.
6953
6954
6955
6956
6957
6958
6959
6960 <h2>5.6 - <a name="5.6">Mathematical Functions</a></h2>
6961
6962 <p>
6963 This library is an interface to the standard C&nbsp;math library.
6964 It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
6965
6966
6967 <p>
6968 <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
6969
6970
6971 <p>
6972 Returns the absolute value of <code>x</code>.
6973
6974
6975
6976
6977 <p>
6978 <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
6979
6980
6981 <p>
6982 Returns the arc cosine of <code>x</code> (in radians).
6983
6984
6985
6986
6987 <p>
6988 <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
6989
6990
6991 <p>
6992 Returns the arc sine of <code>x</code> (in radians).
6993
6994
6995
6996
6997 <p>
6998 <hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
6999
7000
7001 <p>
7002 Returns the arc tangent of <code>x</code> (in radians).
7003
7004
7005
7006
7007 <p>
7008 <hr><h3><a name="pdf-math.atan2"><code>math.atan2 (x, y)</code></a></h3>
7009
7010
7011 <p>
7012 Returns the arc tangent of <code>x/y</code> (in radians),
7013 but uses the signs of both parameters to find the
7014 quadrant of the result.
7015 (It also handles correctly the case of <code>y</code> being zero.)
7016
7017
7018
7019
7020 <p>
7021 <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
7022
7023
7024 <p>
7025 Returns the smallest integer larger than or equal to <code>x</code>.
7026
7027
7028
7029
7030 <p>
7031 <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
7032
7033
7034 <p>
7035 Returns the cosine of <code>x</code> (assumed to be in radians).
7036
7037
7038
7039
7040 <p>
7041 <hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
7042
7043
7044 <p>
7045 Returns the hyperbolic cosine of <code>x</code>.
7046
7047
7048
7049
7050 <p>
7051 <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
7052
7053
7054 <p>
7055 Returns the angle <code>x</code> (given in radians) in degrees.
7056
7057
7058
7059
7060 <p>
7061 <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
7062
7063
7064 <p>
7065 Returns the the value <em>e<sup>x</sup></em>.
7066
7067
7068
7069
7070 <p>
7071 <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
7072
7073
7074 <p>
7075 Returns the largest integer smaller than or equal to <code>x</code>.
7076
7077
7078
7079
7080 <p>
7081 <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
7082
7083
7084 <p>
7085 Returns the remainder of the division of <code>x</code> by <code>y</code>.
7086
7087
7088
7089
7090 <p>
7091 <hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
7092
7093
7094 <p>
7095 Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
7096 <code>e</code> is an integer and the absolute value of <code>m</code> is
7097 in the range <em>[0.5, 1)</em>
7098 (or zero when <code>x</code> is zero).
7099
7100
7101
7102
7103 <p>
7104 <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
7105
7106
7107 <p>
7108 The value <code>HUGE_VAL</code>,
7109 a value larger than or equal to any other numerical value.
7110
7111
7112
7113
7114 <p>
7115 <hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
7116
7117
7118 <p>
7119 Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
7120
7121
7122
7123
7124 <p>
7125 <hr><h3><a name="pdf-math.log"><code>math.log (x)</code></a></h3>
7126
7127
7128 <p>
7129 Returns the natural logarithm of <code>x</code>.
7130
7131
7132
7133
7134 <p>
7135 <hr><h3><a name="pdf-math.log10"><code>math.log10 (x)</code></a></h3>
7136
7137
7138 <p>
7139 Returns the base-10 logarithm of <code>x</code>.
7140
7141
7142
7143
7144 <p>
7145 <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
7146
7147
7148 <p>
7149 Returns the maximum value among its arguments.
7150
7151
7152
7153
7154 <p>
7155 <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
7156
7157
7158 <p>
7159 Returns the minimum value among its arguments.
7160
7161
7162
7163
7164 <p>
7165 <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
7166
7167
7168 <p>
7169 Returns two numbers,
7170 the integral part of <code>x</code> and the fractional part of <code>x</code>.
7171
7172
7173
7174
7175 <p>
7176 <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
7177
7178
7179 <p>
7180 The value of <em>pi</em>.
7181
7182
7183
7184
7185 <p>
7186 <hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
7187
7188
7189 <p>
7190 Returns <em>x<sup>y</sup></em>.
7191 (You can also use the expression <code>x^y</code> to compute this value.)
7192
7193
7194
7195
7196 <p>
7197 <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
7198
7199
7200 <p>
7201 Returns the angle <code>x</code> (given in degrees) in radians.
7202
7203
7204
7205
7206 <p>
7207 <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
7208
7209
7210 <p>
7211 This function is an interface to the simple
7212 pseudo-random generator function <code>rand</code> provided by ANSI&nbsp;C.
7213 (No guarantees can be given for its statistical properties.)
7214
7215
7216 <p>
7217 When called without arguments,
7218 returns a pseudo-random real number
7219 in the range <em>[0,1)</em>.  
7220 When called with a number <code>m</code>,
7221 <code>math.random</code> returns
7222 a pseudo-random integer in the range <em>[1, m]</em>.
7223 When called with two numbers <code>m</code> and <code>n</code>,
7224 <code>math.random</code> returns a pseudo-random
7225 integer in the range <em>[m, n]</em>.
7226
7227
7228
7229
7230 <p>
7231 <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
7232
7233
7234 <p>
7235 Sets <code>x</code> as the "seed"
7236 for the pseudo-random generator:
7237 equal seeds produce equal sequences of numbers.
7238
7239
7240
7241
7242 <p>
7243 <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
7244
7245
7246 <p>
7247 Returns the sine of <code>x</code> (assumed to be in radians).
7248
7249
7250
7251
7252 <p>
7253 <hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
7254
7255
7256 <p>
7257 Returns the hyperbolic sine of <code>x</code>.
7258
7259
7260
7261
7262 <p>
7263 <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
7264
7265
7266 <p>
7267 Returns the square root of <code>x</code>.
7268 (You can also use the expression <code>x^0.5</code> to compute this value.)
7269
7270
7271
7272
7273 <p>
7274 <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
7275
7276
7277 <p>
7278 Returns the tangent of <code>x</code> (assumed to be in radians).
7279
7280
7281
7282
7283 <p>
7284 <hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
7285
7286
7287 <p>
7288 Returns the hyperbolic tangent of <code>x</code>.
7289
7290
7291
7292
7293
7294
7295
7296 <h2>5.7 - <a name="5.7">Input and Output Facilities</a></h2>
7297
7298 <p>
7299 The I/O library provides two different styles for file manipulation.
7300 The first one uses implicit file descriptors;
7301 that is, there are operations to set a default input file and a
7302 default output file,
7303 and all input/output operations are over these default files.
7304 The second style uses explicit file descriptors.
7305
7306
7307 <p>
7308 When using implicit file descriptors,
7309 all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
7310 When using explicit file descriptors,
7311 the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
7312 and then all operations are supplied as methods of the file descriptor.
7313
7314
7315 <p>
7316 The table <code>io</code> also provides
7317 three predefined file descriptors with their usual meanings from C:
7318 <a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>.
7319
7320
7321 <p>
7322 Unless otherwise stated,
7323 all I/O functions return <b>nil</b> on failure
7324 (plus an error message as a second result and
7325 a system-dependent error code as a third result)
7326 and some value different from <b>nil</b> on success.
7327
7328
7329 <p>
7330 <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
7331
7332
7333 <p>
7334 Equivalent to <code>file:close()</code>.
7335 Without a <code>file</code>, closes the default output file.
7336
7337
7338
7339
7340 <p>
7341 <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
7342
7343
7344 <p>
7345 Equivalent to <code>file:flush</code> over the default output file.
7346
7347
7348
7349
7350 <p>
7351 <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
7352
7353
7354 <p>
7355 When called with a file name, it opens the named file (in text mode),
7356 and sets its handle as the default input file.
7357 When called with a file handle,
7358 it simply sets this file handle as the default input file.
7359 When called without parameters,
7360 it returns the current default input file.
7361
7362
7363 <p>
7364 In case of errors this function raises the error,
7365 instead of returning an error code.
7366
7367
7368
7369
7370 <p>
7371 <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename])</code></a></h3>
7372
7373
7374 <p>
7375 Opens the given file name in read mode
7376 and returns an iterator function that,
7377 each time it is called,
7378 returns a new line from the file.
7379 Therefore, the construction
7380
7381 <pre>
7382      for line in io.lines(filename) do <em>body</em> end
7383 </pre><p>
7384 will iterate over all lines of the file.
7385 When the iterator function detects the end of file,
7386 it returns <b>nil</b> (to finish the loop) and automatically closes the file.
7387
7388
7389 <p>
7390 The call <code>io.lines()</code> (with no file name) is equivalent
7391 to <code>io.input():lines()</code>;
7392 that is, it iterates over the lines of the default input file.
7393 In this case it does not close the file when the loop ends.
7394
7395
7396
7397
7398 <p>
7399 <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
7400
7401
7402 <p>
7403 This function opens a file,
7404 in the mode specified in the string <code>mode</code>.
7405 It returns a new file handle,
7406 or, in case of errors, <b>nil</b> plus an error message.
7407
7408
7409 <p>
7410 The <code>mode</code> string can be any of the following:
7411
7412 <ul>
7413 <li><b>"r":</b> read mode (the default);</li>
7414 <li><b>"w":</b> write mode;</li>
7415 <li><b>"a":</b> append mode;</li>
7416 <li><b>"r+":</b> update mode, all previous data is preserved;</li>
7417 <li><b>"w+":</b> update mode, all previous data is erased;</li>
7418 <li><b>"a+":</b> append update mode, previous data is preserved,
7419   writing is only allowed at the end of file.</li>
7420 </ul><p>
7421 The <code>mode</code> string may also have a '<code>b</code>' at the end,
7422 which is needed in some systems to open the file in binary mode.
7423 This string is exactly what is used in the
7424 standard&nbsp;C function <code>fopen</code>.
7425
7426
7427
7428
7429 <p>
7430 <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
7431
7432
7433 <p>
7434 Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
7435
7436
7437
7438
7439 <p>
7440 <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
7441
7442
7443 <p>
7444 Starts program <code>prog</code> in a separated process and returns
7445 a file handle that you can use to read data from this program
7446 (if <code>mode</code> is <code>"r"</code>, the default)
7447 or to write data to this program
7448 (if <code>mode</code> is <code>"w"</code>).
7449
7450
7451 <p>
7452 This function is system dependent and is not available
7453 on all platforms.
7454
7455
7456
7457
7458 <p>
7459 <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
7460
7461
7462 <p>
7463 Equivalent to <code>io.input():read</code>.
7464
7465
7466
7467
7468 <p>
7469 <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
7470
7471
7472 <p>
7473 Returns a handle for a temporary file.
7474 This file is opened in update mode
7475 and it is automatically removed when the program ends.
7476
7477
7478
7479
7480 <p>
7481 <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
7482
7483
7484 <p>
7485 Checks whether <code>obj</code> is a valid file handle.
7486 Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
7487 <code>"closed file"</code> if <code>obj</code> is a closed file handle,
7488 or <b>nil</b> if <code>obj</code> is not a file handle.
7489
7490
7491
7492
7493 <p>
7494 <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
7495
7496
7497 <p>
7498 Equivalent to <code>io.output():write</code>.
7499
7500
7501
7502
7503 <p>
7504 <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
7505
7506
7507 <p>
7508 Closes <code>file</code>.
7509 Note that files are automatically closed when
7510 their handles are garbage collected,
7511 but that takes an unpredictable amount of time to happen.
7512
7513
7514
7515
7516 <p>
7517 <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
7518
7519
7520 <p>
7521 Saves any written data to <code>file</code>.
7522
7523
7524
7525
7526 <p>
7527 <hr><h3><a name="pdf-file:lines"><code>file:lines ()</code></a></h3>
7528
7529
7530 <p>
7531 Returns an iterator function that,
7532 each time it is called,
7533 returns a new line from the file.
7534 Therefore, the construction
7535
7536 <pre>
7537      for line in file:lines() do <em>body</em> end
7538 </pre><p>
7539 will iterate over all lines of the file.
7540 (Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
7541 when the loop ends.)
7542
7543
7544
7545
7546 <p>
7547 <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
7548
7549
7550 <p>
7551 Reads the file <code>file</code>,
7552 according to the given formats, which specify what to read.
7553 For each format,
7554 the function returns a string (or a number) with the characters read,
7555 or <b>nil</b> if it cannot read data with the specified format.
7556 When called without formats,
7557 it uses a default format that reads the entire next line
7558 (see below).
7559
7560
7561 <p>
7562 The available formats are
7563
7564 <ul>
7565
7566 <li><b>"*n":</b>
7567 reads a number;
7568 this is the only format that returns a number instead of a string.
7569 </li>
7570
7571 <li><b>"*a":</b>
7572 reads the whole file, starting at the current position.
7573 On end of file, it returns the empty string.
7574 </li>
7575
7576 <li><b>"*l":</b>
7577 reads the next line (skipping the end of line),
7578 returning <b>nil</b> on end of file.
7579 This is the default format.
7580 </li>
7581
7582 <li><b><em>number</em>:</b>
7583 reads a string with up to this number of characters,
7584 returning <b>nil</b> on end of file.
7585 If number is zero,
7586 it reads nothing and returns an empty string,
7587 or <b>nil</b> on end of file.
7588 </li>
7589
7590 </ul>
7591
7592
7593
7594 <p>
7595 <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence] [, offset])</code></a></h3>
7596
7597
7598 <p>
7599 Sets and gets the file position,
7600 measured from the beginning of the file,
7601 to the position given by <code>offset</code> plus a base
7602 specified by the string <code>whence</code>, as follows:
7603
7604 <ul>
7605 <li><b>"set":</b> base is position 0 (beginning of the file);</li>
7606 <li><b>"cur":</b> base is current position;</li>
7607 <li><b>"end":</b> base is end of file;</li>
7608 </ul><p>
7609 In case of success, function <code>seek</code> returns the final file position,
7610 measured in bytes from the beginning of the file.
7611 If this function fails, it returns <b>nil</b>,
7612 plus a string describing the error.
7613
7614
7615 <p>
7616 The default value for <code>whence</code> is <code>"cur"</code>,
7617 and for <code>offset</code> is 0.
7618 Therefore, the call <code>file:seek()</code> returns the current
7619 file position, without changing it;
7620 the call <code>file:seek("set")</code> sets the position to the
7621 beginning of the file (and returns 0);
7622 and the call <code>file:seek("end")</code> sets the position to the
7623 end of the file, and returns its size.
7624
7625
7626
7627
7628 <p>
7629 <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
7630
7631
7632 <p>
7633 Sets the buffering mode for an output file.
7634 There are three available modes:
7635
7636 <ul>
7637
7638 <li><b>"no":</b>
7639 no buffering; the result of any output operation appears immediately.
7640 </li>
7641
7642 <li><b>"full":</b>
7643 full buffering; output operation is performed only
7644 when the buffer is full (or when you explicitly <code>flush</code> the file
7645 (see <a href="#pdf-io.flush"><code>io.flush</code></a>)).
7646 </li>
7647
7648 <li><b>"line":</b>
7649 line buffering; output is buffered until a newline is output
7650 or there is any input from some special files
7651 (such as a terminal device).
7652 </li>
7653
7654 </ul><p>
7655 For the last two cases, <code>size</code>
7656 specifies the size of the buffer, in bytes.
7657 The default is an appropriate size.
7658
7659
7660
7661
7662 <p>
7663 <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
7664
7665
7666 <p>
7667 Writes the value of each of its arguments to
7668 the <code>file</code>.
7669 The arguments must be strings or numbers.
7670 To write other values,
7671 use <a href="#pdf-tostring"><code>tostring</code></a> or <a href="#pdf-string.format"><code>string.format</code></a> before <code>write</code>.
7672
7673
7674
7675
7676
7677
7678
7679 <h2>5.8 - <a name="5.8">Operating System Facilities</a></h2>
7680
7681 <p>
7682 This library is implemented through table <a name="pdf-os"><code>os</code></a>.
7683
7684
7685 <p>
7686 <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
7687
7688
7689 <p>
7690 Returns an approximation of the amount in seconds of CPU time
7691 used by the program.
7692
7693
7694
7695
7696 <p>
7697 <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
7698
7699
7700 <p>
7701 Returns a string or a table containing date and time,
7702 formatted according to the given string <code>format</code>.
7703
7704
7705 <p>
7706 If the <code>time</code> argument is present,
7707 this is the time to be formatted
7708 (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
7709 Otherwise, <code>date</code> formats the current time.
7710
7711
7712 <p>
7713 If <code>format</code> starts with '<code>!</code>',
7714 then the date is formatted in Coordinated Universal Time.
7715 After this optional character,
7716 if <code>format</code> is the string "<code>*t</code>",
7717 then <code>date</code> returns a table with the following fields:
7718 <code>year</code> (four digits), <code>month</code> (1--12), <code>day</code> (1--31),
7719 <code>hour</code> (0--23), <code>min</code> (0--59), <code>sec</code> (0--61),
7720 <code>wday</code> (weekday, Sunday is&nbsp;1),
7721 <code>yday</code> (day of the year),
7722 and <code>isdst</code> (daylight saving flag, a boolean).
7723
7724
7725 <p>
7726 If <code>format</code> is not "<code>*t</code>",
7727 then <code>date</code> returns the date as a string,
7728 formatted according to the same rules as the C&nbsp;function <code>strftime</code>.
7729
7730
7731 <p>
7732 When called without arguments,
7733 <code>date</code> returns a reasonable date and time representation that depends on
7734 the host system and on the current locale
7735 (that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
7736
7737
7738
7739
7740 <p>
7741 <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
7742
7743
7744 <p>
7745 Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
7746 In POSIX, Windows, and some other systems,
7747 this value is exactly <code>t2</code><em>-</em><code>t1</code>.
7748
7749
7750
7751
7752 <p>
7753 <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
7754
7755
7756 <p>
7757 This function is equivalent to the C&nbsp;function <code>system</code>.
7758 It passes <code>command</code> to be executed by an operating system shell.
7759 It returns a status code, which is system-dependent.
7760 If <code>command</code> is absent, then it returns nonzero if a shell is available
7761 and zero otherwise.
7762
7763
7764
7765
7766 <p>
7767 <hr><h3><a name="pdf-os.exit"><code>os.exit ([code])</code></a></h3>
7768
7769
7770 <p>
7771 Calls the C&nbsp;function <code>exit</code>,
7772 with an optional <code>code</code>,
7773 to terminate the host program.
7774 The default value for <code>code</code> is the success code.
7775
7776
7777
7778
7779 <p>
7780 <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
7781
7782
7783 <p>
7784 Returns the value of the process environment variable <code>varname</code>,
7785 or <b>nil</b> if the variable is not defined.
7786
7787
7788
7789
7790 <p>
7791 <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
7792
7793
7794 <p>
7795 Deletes the file or directory with the given name.
7796 Directories must be empty to be removed.
7797 If this function fails, it returns <b>nil</b>,
7798 plus a string describing the error.
7799
7800
7801
7802
7803 <p>
7804 <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
7805
7806
7807 <p>
7808 Renames file or directory named <code>oldname</code> to <code>newname</code>.
7809 If this function fails, it returns <b>nil</b>,
7810 plus a string describing the error.
7811
7812
7813
7814
7815 <p>
7816 <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
7817
7818
7819 <p>
7820 Sets the current locale of the program.
7821 <code>locale</code> is a string specifying a locale;
7822 <code>category</code> is an optional string describing which category to change:
7823 <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
7824 <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
7825 the default category is <code>"all"</code>.
7826 The function returns the name of the new locale,
7827 or <b>nil</b> if the request cannot be honored.
7828
7829
7830 <p>
7831 If <code>locale</code> is the empty string,
7832 the current locate is set to an implementation-defined native locale.
7833 If <code>locate</code> is the string "<code>C</code>",
7834 the current locate is set to the standard C locale.
7835
7836
7837 <p>
7838 When called with <b>nil</b> as the first argument,
7839 this function only returns the name of the current locale
7840 for the given category.
7841
7842
7843
7844
7845 <p>
7846 <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
7847
7848
7849 <p>
7850 Returns the current time when called without arguments,
7851 or a time representing the date and time specified by the given table.
7852 This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
7853 and may have fields <code>hour</code>, <code>min</code>, <code>sec</code>, and <code>isdst</code>
7854 (for a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function).
7855
7856
7857 <p>
7858 The returned value is a number, whose meaning depends on your system.
7859 In POSIX, Windows, and some other systems, this number counts the number
7860 of seconds since some given start time (the "epoch").
7861 In other systems, the meaning is not specified,
7862 and the number returned by <code>time</code> can be used only as an argument to
7863 <code>date</code> and <code>difftime</code>.
7864
7865
7866
7867
7868 <p>
7869 <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
7870
7871
7872 <p>
7873 Returns a string with a file name that can
7874 be used for a temporary file.
7875 The file must be explicitly opened before its use
7876 and explicitly removed when no longer needed.
7877
7878
7879
7880
7881
7882
7883
7884 <h2>5.9 - <a name="5.9">The Debug Library</a></h2>
7885
7886 <p>
7887 This library provides
7888 the functionality of the debug interface to Lua programs.
7889 You should exert care when using this library.
7890 The functions provided here should be used exclusively for debugging
7891 and similar tasks, such as profiling.
7892 Please resist the temptation to use them as a
7893 usual programming tool:
7894 they can be very slow.
7895 Moreover, several of its functions
7896 violate some assumptions about Lua code
7897 (e.g., that variables local to a function
7898 cannot be accessed from outside or
7899 that userdata metatables cannot be changed by Lua code)
7900 and therefore can compromise otherwise secure code.
7901
7902
7903 <p>
7904 All functions in this library are provided
7905 inside the <a name="pdf-debug"><code>debug</code></a> table.
7906 All functions that operate over a thread
7907 have an optional first argument which is the
7908 thread to operate over.
7909 The default is always the current thread.
7910
7911
7912 <p>
7913 <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
7914
7915
7916 <p>
7917 Enters an interactive mode with the user,
7918 running each string that the user enters.
7919 Using simple commands and other debug facilities,
7920 the user can inspect global and local variables,
7921 change their values, evaluate expressions, and so on.
7922 A line containing only the word <code>cont</code> finishes this function,
7923 so that the caller continues its execution.
7924
7925
7926 <p>
7927 Note that commands for <code>debug.debug</code> are not lexically nested
7928 within any function, and so have no direct access to local variables.
7929
7930
7931
7932
7933 <p>
7934 <hr><h3><a name="pdf-debug.getfenv"><code>debug.getfenv (o)</code></a></h3>
7935 Returns the environment of object <code>o</code>.
7936
7937
7938
7939
7940 <p>
7941 <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
7942
7943
7944 <p>
7945 Returns the current hook settings of the thread, as three values:
7946 the current hook function, the current hook mask,
7947 and the current hook count
7948 (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
7949
7950
7951
7952
7953 <p>
7954 <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] function [, what])</code></a></h3>
7955
7956
7957 <p>
7958 Returns a table with information about a function.
7959 You can give the function directly,
7960 or you can give a number as the value of <code>function</code>,
7961 which means the function running at level <code>function</code> of the call stack
7962 of the given thread:
7963 level&nbsp;0 is the current function (<code>getinfo</code> itself);
7964 level&nbsp;1 is the function that called <code>getinfo</code>;
7965 and so on.
7966 If <code>function</code> is a number larger than the number of active functions,
7967 then <code>getinfo</code> returns <b>nil</b>.
7968
7969
7970 <p>
7971 The returned table may contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
7972 with the string <code>what</code> describing which fields to fill in.
7973 The default for <code>what</code> is to get all information available,
7974 except the table of valid lines.
7975 If present,
7976 the option '<code>f</code>'
7977 adds a field named <code>func</code> with the function itself.
7978 If present,
7979 the option '<code>L</code>'
7980 adds a field named <code>activelines</code> with the table of
7981 valid lines.
7982
7983
7984 <p>
7985 For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
7986 a name of the current function, if a reasonable name can be found,
7987 and the expression <code>debug.getinfo(print)</code>
7988 returns a table with all available information
7989 about the <a href="#pdf-print"><code>print</code></a> function.
7990
7991
7992
7993
7994 <p>
7995 <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] level, local)</code></a></h3>
7996
7997
7998 <p>
7999 This function returns the name and the value of the local variable
8000 with index <code>local</code> of the function at level <code>level</code> of the stack.
8001 (The first parameter or local variable has index&nbsp;1, and so on,
8002 until the last active local variable.)
8003 The function returns <b>nil</b> if there is no local
8004 variable with the given index,
8005 and raises an error when called with a <code>level</code> out of range.
8006 (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
8007
8008
8009 <p>
8010 Variable names starting with '<code>(</code>' (open parentheses)
8011 represent internal variables
8012 (loop control variables, temporaries, and C&nbsp;function locals).
8013
8014
8015
8016
8017 <p>
8018 <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (object)</code></a></h3>
8019
8020
8021 <p>
8022 Returns the metatable of the given <code>object</code>
8023 or <b>nil</b> if it does not have a metatable.
8024
8025
8026
8027
8028 <p>
8029 <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
8030
8031
8032 <p>
8033 Returns the registry table (see <a href="#3.5">&sect;3.5</a>).
8034
8035
8036
8037
8038 <p>
8039 <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (func, up)</code></a></h3>
8040
8041
8042 <p>
8043 This function returns the name and the value of the upvalue
8044 with index <code>up</code> of the function <code>func</code>.
8045 The function returns <b>nil</b> if there is no upvalue with the given index.
8046
8047
8048
8049
8050 <p>
8051 <hr><h3><a name="pdf-debug.setfenv"><code>debug.setfenv (object, table)</code></a></h3>
8052
8053
8054 <p>
8055 Sets the environment of the given <code>object</code> to the given <code>table</code>.
8056 Returns <code>object</code>.
8057
8058
8059
8060
8061 <p>
8062 <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
8063
8064
8065 <p>
8066 Sets the given function as a hook.
8067 The string <code>mask</code> and the number <code>count</code> describe
8068 when the hook will be called.
8069 The string mask may have the following characters,
8070 with the given meaning:
8071
8072 <ul>
8073 <li><b><code>"c"</code>:</b> The hook is called every time Lua calls a function;</li>
8074 <li><b><code>"r"</code>:</b> The hook is called every time Lua returns from a function;</li>
8075 <li><b><code>"l"</code>:</b> The hook is called every time Lua enters a new line of code.</li>
8076 </ul><p>
8077 With a <code>count</code> different from zero,
8078 the hook is called after every <code>count</code> instructions.
8079
8080
8081 <p>
8082 When called without arguments,
8083 <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
8084
8085
8086 <p>
8087 When the hook is called, its first parameter is a string
8088 describing the event that has triggered its call:
8089 <code>"call"</code>, <code>"return"</code> (or <code>"tail return"</code>),
8090 <code>"line"</code>, and <code>"count"</code>.
8091 For line events,
8092 the hook also gets the new line number as its second parameter.
8093 Inside a hook,
8094 you can call <code>getinfo</code> with level&nbsp;2 to get more information about
8095 the running function
8096 (level&nbsp;0 is the <code>getinfo</code> function,
8097 and level&nbsp;1 is the hook function),
8098 unless the event is <code>"tail return"</code>.
8099 In this case, Lua is only simulating the return,
8100 and a call to <code>getinfo</code> will return invalid data.
8101
8102
8103
8104
8105 <p>
8106 <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
8107
8108
8109 <p>
8110 This function assigns the value <code>value</code> to the local variable
8111 with index <code>local</code> of the function at level <code>level</code> of the stack.
8112 The function returns <b>nil</b> if there is no local
8113 variable with the given index,
8114 and raises an error when called with a <code>level</code> out of range.
8115 (You can call <code>getinfo</code> to check whether the level is valid.)
8116 Otherwise, it returns the name of the local variable.
8117
8118
8119
8120
8121 <p>
8122 <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (object, table)</code></a></h3>
8123
8124
8125 <p>
8126 Sets the metatable for the given <code>object</code> to the given <code>table</code>
8127 (which can be <b>nil</b>).
8128
8129
8130
8131
8132 <p>
8133 <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (func, up, value)</code></a></h3>
8134
8135
8136 <p>
8137 This function assigns the value <code>value</code> to the upvalue
8138 with index <code>up</code> of the function <code>func</code>.
8139 The function returns <b>nil</b> if there is no upvalue
8140 with the given index.
8141 Otherwise, it returns the name of the upvalue.
8142
8143
8144
8145
8146 <p>
8147 <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message] [, level])</code></a></h3>
8148
8149
8150 <p>
8151 Returns a string with a traceback of the call stack.
8152 An optional <code>message</code> string is appended
8153 at the beginning of the traceback.
8154 An optional <code>level</code> number tells at which level
8155 to start the traceback
8156 (default is 1, the function calling <code>traceback</code>).
8157
8158
8159
8160
8161
8162
8163
8164 <h1>6 - <a name="6">Lua Stand-alone</a></h1>
8165
8166 <p>
8167 Although Lua has been designed as an extension language,
8168 to be embedded in a host C&nbsp;program,
8169 it is also frequently used as a stand-alone language.
8170 An interpreter for Lua as a stand-alone language,
8171 called simply <code>lua</code>,
8172 is provided with the standard distribution.
8173 The stand-alone interpreter includes
8174 all standard libraries, including the debug library.
8175 Its usage is:
8176
8177 <pre>
8178      lua [options] [script [args]]
8179 </pre><p>
8180 The options are:
8181
8182 <ul>
8183 <li><b><code>-e <em>stat</em></code>:</b> executes string <em>stat</em>;</li>
8184 <li><b><code>-l <em>mod</em></code>:</b> "requires" <em>mod</em>;</li>
8185 <li><b><code>-i</code>:</b> enters interactive mode after running <em>script</em>;</li>
8186 <li><b><code>-v</code>:</b> prints version information;</li>
8187 <li><b><code>--</code>:</b> stops handling options;</li>
8188 <li><b><code>-</code>:</b> executes <code>stdin</code> as a file and stops handling options.</li>
8189 </ul><p>
8190 After handling its options, <code>lua</code> runs the given <em>script</em>,
8191 passing to it the given <em>args</em> as string arguments.
8192 When called without arguments,
8193 <code>lua</code> behaves as <code>lua -v -i</code>
8194 when the standard input (<code>stdin</code>) is a terminal,
8195 and as <code>lua -</code> otherwise.
8196
8197
8198 <p>
8199 Before running any argument,
8200 the interpreter checks for an environment variable <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a>.
8201 If its format is <code>@<em>filename</em></code>,
8202 then <code>lua</code> executes the file.
8203 Otherwise, <code>lua</code> executes the string itself.
8204
8205
8206 <p>
8207 All options are handled in order, except <code>-i</code>.
8208 For instance, an invocation like
8209
8210 <pre>
8211      $ lua -e'a=1' -e 'print(a)' script.lua
8212 </pre><p>
8213 will first set <code>a</code> to 1, then print the value of <code>a</code> (which is '<code>1</code>'),
8214 and finally run the file <code>script.lua</code> with no arguments.
8215 (Here <code>$</code> is the shell prompt. Your prompt may be different.)
8216
8217
8218 <p>
8219 Before starting to run the script,
8220 <code>lua</code> collects all arguments in the command line
8221 in a global table called <code>arg</code>.
8222 The script name is stored at index 0,
8223 the first argument after the script name goes to index 1,
8224 and so on.
8225 Any arguments before the script name
8226 (that is, the interpreter name plus the options)
8227 go to negative indices.
8228 For instance, in the call
8229
8230 <pre>
8231      $ lua -la b.lua t1 t2
8232 </pre><p>
8233 the interpreter first runs the file <code>a.lua</code>,
8234 then creates a table
8235
8236 <pre>
8237      arg = { [-2] = "lua", [-1] = "-la",
8238              [0] = "b.lua",
8239              [1] = "t1", [2] = "t2" }
8240 </pre><p>
8241 and finally runs the file <code>b.lua</code>.
8242 The script is called with <code>arg[1]</code>, <code>arg[2]</code>, &middot;&middot;&middot;
8243 as arguments;
8244 it can also access these arguments with the vararg expression '<code>...</code>'.
8245
8246
8247 <p>
8248 In interactive mode,
8249 if you write an incomplete statement,
8250 the interpreter waits for its completion
8251 by issuing a different prompt.
8252
8253
8254 <p>
8255 If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
8256 then its value is used as the prompt.
8257 Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
8258 its value is used as the secondary prompt
8259 (issued during incomplete statements).
8260 Therefore, both prompts can be changed directly on the command line.
8261 For instance,
8262
8263 <pre>
8264      $ lua -e"_PROMPT='myprompt&gt; '" -i
8265 </pre><p>
8266 (the outer pair of quotes is for the shell,
8267 the inner pair is for Lua),
8268 or in any Lua programs by assigning to <code>_PROMPT</code>.
8269 Note the use of <code>-i</code> to enter interactive mode; otherwise,
8270 the program would just end silently right after the assignment to <code>_PROMPT</code>.
8271
8272
8273 <p>
8274 To allow the use of Lua as a
8275 script interpreter in Unix systems,
8276 the stand-alone interpreter skips
8277 the first line of a chunk if it starts with <code>#</code>.
8278 Therefore, Lua scripts can be made into executable programs
8279 by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
8280 as in
8281
8282 <pre>
8283      #!/usr/local/bin/lua
8284 </pre><p>
8285 (Of course,
8286 the location of the Lua interpreter may be different in your machine.
8287 If <code>lua</code> is in your <code>PATH</code>,
8288 then 
8289
8290 <pre>
8291      #!/usr/bin/env lua
8292 </pre><p>
8293 is a more portable solution.) 
8294
8295
8296
8297 <h1>7 - <a name="7">Incompatibilities with the Previous Version</a></h1>
8298
8299 <p>
8300 Here we list the incompatibilities that you may found when moving a program
8301 from Lua&nbsp;5.0 to Lua&nbsp;5.1.
8302 You can avoid most of the incompatibilities compiling Lua with
8303 appropriate options (see file <code>luaconf.h</code>).
8304 However,
8305 all these compatibility options will be removed in the next version of Lua.
8306
8307
8308
8309 <h2>7.1 - <a name="7.1">Changes in the Language</a></h2>
8310 <ul>
8311
8312 <li>
8313 The vararg system changed from the pseudo-argument <code>arg</code> with a
8314 table with the extra arguments to the vararg expression.
8315 (See compile-time option <code>LUA_COMPAT_VARARG</code> in <code>luaconf.h</code>.)
8316 </li>
8317
8318 <li>
8319 There was a subtle change in the scope of the implicit
8320 variables of the <b>for</b> statement and for the <b>repeat</b> statement.
8321 </li>
8322
8323 <li>
8324 The long string/long comment syntax (<code>[[<em>string</em>]]</code>)
8325 does not allow nesting.
8326 You can use the new syntax (<code>[=[<em>string</em>]=]</code>) in these cases.
8327 (See compile-time option <code>LUA_COMPAT_LSTR</code> in <code>luaconf.h</code>.)
8328 </li>
8329
8330 </ul>
8331
8332
8333
8334
8335 <h2>7.2 - <a name="7.2">Changes in the Libraries</a></h2>
8336 <ul>
8337
8338 <li>
8339 Function <code>string.gfind</code> was renamed <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>.
8340 (See compile-time option <code>LUA_COMPAT_GFIND</code> in <code>luaconf.h</code>.)
8341 </li>
8342
8343 <li>
8344 When <a href="#pdf-string.gsub"><code>string.gsub</code></a> is called with a function as its
8345 third argument,
8346 whenever this function returns <b>nil</b> or <b>false</b> the
8347 replacement string is the whole match,
8348 instead of the empty string.
8349 </li>
8350
8351 <li>
8352 Function <code>table.setn</code> was deprecated.
8353 Function <code>table.getn</code> corresponds
8354 to the new length operator (<code>#</code>);
8355 use the operator instead of the function.
8356 (See compile-time option <code>LUA_COMPAT_GETN</code> in <code>luaconf.h</code>.)
8357 </li>
8358
8359 <li>
8360 Function <code>loadlib</code> was renamed <a href="#pdf-package.loadlib"><code>package.loadlib</code></a>.
8361 (See compile-time option <code>LUA_COMPAT_LOADLIB</code> in <code>luaconf.h</code>.)
8362 </li>
8363
8364 <li>
8365 Function <code>math.mod</code> was renamed <a href="#pdf-math.fmod"><code>math.fmod</code></a>.
8366 (See compile-time option <code>LUA_COMPAT_MOD</code> in <code>luaconf.h</code>.)
8367 </li>
8368
8369 <li>
8370 Functions <code>table.foreach</code> and <code>table.foreachi</code> are deprecated.
8371 You can use a for loop with <code>pairs</code> or <code>ipairs</code> instead.
8372 </li>
8373
8374 <li>
8375 There were substantial changes in function <a href="#pdf-require"><code>require</code></a> due to
8376 the new module system.
8377 However, the new behavior is mostly compatible with the old,
8378 but <code>require</code> gets the path from <a href="#pdf-package.path"><code>package.path</code></a> instead
8379 of from <code>LUA_PATH</code>.
8380 </li>
8381
8382 <li>
8383 Function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> has different arguments.
8384 Function <code>gcinfo</code> is deprecated;
8385 use <code>collectgarbage("count")</code> instead.
8386 </li>
8387
8388 </ul>
8389
8390
8391
8392
8393 <h2>7.3 - <a name="7.3">Changes in the API</a></h2>
8394 <ul>
8395
8396 <li>
8397 The <code>luaopen_*</code> functions (to open libraries)
8398 cannot be called directly,
8399 like a regular C function.
8400 They must be called through Lua,
8401 like a Lua function.
8402 </li>
8403
8404 <li>
8405 Function <code>lua_open</code> was replaced by <a href="#lua_newstate"><code>lua_newstate</code></a> to
8406 allow the user to set a memory-allocation function.
8407 You can use <a href="#luaL_newstate"><code>luaL_newstate</code></a> from the standard library to
8408 create a state with a standard allocation function
8409 (based on <code>realloc</code>).
8410 </li>
8411
8412 <li>
8413 Functions <code>luaL_getn</code> and <code>luaL_setn</code>
8414 (from the auxiliary library) are deprecated.
8415 Use <a href="#lua_objlen"><code>lua_objlen</code></a> instead of <code>luaL_getn</code>
8416 and nothing instead of <code>luaL_setn</code>.
8417 </li>
8418
8419 <li>
8420 Function <code>luaL_openlib</code> was replaced by <a href="#luaL_register"><code>luaL_register</code></a>.
8421 </li>
8422
8423 <li>
8424 Function <code>luaL_checkudata</code> now throws an error when the given value
8425 is not a userdata of the expected type.
8426 (In Lua&nbsp;5.0 it returned <code>NULL</code>.)
8427 </li>
8428
8429 </ul>
8430
8431
8432
8433
8434 <h1>8 - <a name="8">The Complete Syntax of Lua</a></h1>
8435
8436 <p>
8437 Here is the complete syntax of Lua in extended BNF.
8438 (It does not describe operator precedences.)
8439
8440
8441
8442
8443 <pre>
8444
8445         chunk ::= {stat [`<b>;</b>&acute;]} [laststat [`<b>;</b>&acute;]]
8446
8447         block ::= chunk
8448
8449         stat ::=  varlist1 `<b>=</b>&acute; explist1 | 
8450                  functioncall | 
8451                  <b>do</b> block <b>end</b> | 
8452                  <b>while</b> exp <b>do</b> block <b>end</b> | 
8453                  <b>repeat</b> block <b>until</b> exp | 
8454                  <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | 
8455                  <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b> | 
8456                  <b>for</b> namelist <b>in</b> explist1 <b>do</b> block <b>end</b> | 
8457                  <b>function</b> funcname funcbody | 
8458                  <b>local</b> <b>function</b> Name funcbody | 
8459                  <b>local</b> namelist [`<b>=</b>&acute; explist1] 
8460
8461         laststat ::= <b>return</b> [explist1] | <b>break</b>
8462
8463         funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
8464
8465         varlist1 ::= var {`<b>,</b>&acute; var}
8466
8467         var ::=  Name | prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute; | prefixexp `<b>.</b>&acute; Name 
8468
8469         namelist ::= Name {`<b>,</b>&acute; Name}
8470
8471         explist1 ::= {exp `<b>,</b>&acute;} exp
8472
8473         exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | `<b>...</b>&acute; | function | 
8474                  prefixexp | tableconstructor | exp binop exp | unop exp 
8475
8476         prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
8477
8478         functioncall ::=  prefixexp args | prefixexp `<b>:</b>&acute; Name args 
8479
8480         args ::=  `<b>(</b>&acute; [explist1] `<b>)</b>&acute; | tableconstructor | String 
8481
8482         function ::= <b>function</b> funcbody
8483
8484         funcbody ::= `<b>(</b>&acute; [parlist1] `<b>)</b>&acute; block <b>end</b>
8485
8486         parlist1 ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
8487
8488         tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
8489
8490         fieldlist ::= field {fieldsep field} [fieldsep]
8491
8492         field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
8493
8494         fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
8495
8496         binop ::= `<b>+</b>&acute; | `<b>-</b>&acute; | `<b>*</b>&acute; | `<b>/</b>&acute; | `<b>^</b>&acute; | `<b>%</b>&acute; | `<b>..</b>&acute; | 
8497                  `<b>&lt;</b>&acute; | `<b>&lt;=</b>&acute; | `<b>&gt;</b>&acute; | `<b>&gt;=</b>&acute; | `<b>==</b>&acute; | `<b>~=</b>&acute; | 
8498                  <b>and</b> | <b>or</b>
8499
8500         unop ::= `<b>-</b>&acute; | <b>not</b> | `<b>#</b>&acute;
8501
8502 </pre>
8503
8504 <p>
8505
8506
8507
8508
8509
8510
8511 <HR>
8512 <SMALL>
8513 Last update:
8514 Mon Mar 26 12:59:26 BRT 2007
8515 </SMALL>
8516 <!--
8517 Last change: ready for Lua 5.1.2
8518 -->
8519
8520 </body></html>
8521