Release 5.1.3
[lua.git] / doc / manual.html
blobb125c13d881f56073fd81e8d24064e6f2972d5db
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
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 <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
9 </head>
11 <body>
13 <hr>
14 <h1>
15 <a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
16 Lua 5.1 Reference Manual
17 </h1>
19 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
20 <p>
21 <small>
22 Copyright &copy; 2006-2008 Lua.org, PUC-Rio.
23 Freely available under the terms of the
24 <a href="http://www.lua.org/license.html#5">Lua license</a>.
25 </small>
26 <hr>
27 <p>
29 <a href="contents.html#contents">contents</A>
30 &middot;
31 <a href="contents.html#index">index</A>
33 <!-- ====================================================================== -->
34 <p>
36 <!-- $Id: manual.of,v 1.45 2008/01/19 00:17:30 roberto Exp $ -->
41 <h1>1 - <a name="1">Introduction</a></h1>
43 <p>
44 Lua is an extension programming language designed to support
45 general procedural programming with data description
46 facilities.
47 It also offers good support for object-oriented programming,
48 functional programming, and data-driven programming.
49 Lua is intended to be used as a powerful, light-weight
50 scripting language for any program that needs one.
51 Lua is implemented as a library, written in <em>clean</em> C
52 (that is, in the common subset of ANSI&nbsp;C and C++).
55 <p>
56 Being an extension language, Lua has no notion of a "main" program:
57 it only works <em>embedded</em> in a host client,
58 called the <em>embedding program</em> or simply the <em>host</em>.
59 This host program can invoke functions to execute a piece of Lua code,
60 can write and read Lua variables,
61 and can register C&nbsp;functions to be called by Lua code.
62 Through the use of C&nbsp;functions, Lua can be augmented to cope with
63 a wide range of different domains,
64 thus creating customized programming languages sharing a syntactical framework.
65 The Lua distribution includes a sample host program called <code>lua</code>,
66 which uses the Lua library to offer a complete, stand-alone Lua interpreter.
69 <p>
70 Lua is free software,
71 and is provided as usual with no guarantees,
72 as stated in its license.
73 The implementation described in this manual is available
74 at Lua's official web site, <code>www.lua.org</code>.
77 <p>
78 Like any other reference manual,
79 this document is dry in places.
80 For a discussion of the decisions behind the design of Lua,
81 see the technical papers available at Lua's web site.
82 For a detailed introduction to programming in Lua,
83 see Roberto's book, <em>Programming in Lua (Second Edition)</em>.
87 <h1>2 - <a name="2">The Language</a></h1>
89 <p>
90 This section describes the lexis, the syntax, and the semantics of Lua.
91 In other words,
92 this section describes
93 which tokens are valid,
94 how they can be combined,
95 and what their combinations mean.
98 <p>
99 The language constructs will be explained using the usual extended BNF notation,
100 in which
101 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
102 [<em>a</em>]&nbsp;means an optional <em>a</em>.
103 Non-terminals are shown like non-terminal,
104 keywords are shown like <b>kword</b>,
105 and other terminal symbols are shown like `<b>=</b>&acute;.
106 The complete syntax of Lua can be found at the end of this manual.
110 <h2>2.1 - <a name="2.1">Lexical Conventions</a></h2>
113 <em>Names</em>
114 (also called <em>identifiers</em>)
115 in Lua can be any string of letters,
116 digits, and underscores,
117 not beginning with a digit.
118 This coincides with the definition of names in most languages.
119 (The definition of letter depends on the current locale:
120 any character considered alphabetic by the current locale
121 can be used in an identifier.)
122 Identifiers are used to name variables and table fields.
126 The following <em>keywords</em> are reserved
127 and cannot be used as names:
130 <pre>
131 and break do else elseif
132 end false for function if
133 in local nil not or
134 repeat return then true until while
135 </pre>
138 Lua is a case-sensitive language:
139 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
140 are two different, valid names.
141 As a convention, names starting with an underscore followed by
142 uppercase letters (such as <code>_VERSION</code>)
143 are reserved for internal global variables used by Lua.
147 The following strings denote other tokens:
149 <pre>
150 + - * / % ^ #
151 == ~= &lt;= &gt;= &lt; &gt; =
152 ( ) { } [ ]
153 ; : , . .. ...
154 </pre>
157 <em>Literal strings</em>
158 can be delimited by matching single or double quotes,
159 and can contain the following C-like escape sequences:
160 '<code>\a</code>' (bell),
161 '<code>\b</code>' (backspace),
162 '<code>\f</code>' (form feed),
163 '<code>\n</code>' (newline),
164 '<code>\r</code>' (carriage return),
165 '<code>\t</code>' (horizontal tab),
166 '<code>\v</code>' (vertical tab),
167 '<code>\\</code>' (backslash),
168 '<code>\"</code>' (quotation mark [double quote]),
169 and '<code>\'</code>' (apostrophe [single quote]).
170 Moreover, a backslash followed by a real newline
171 results in a newline in the string.
172 A character in a string may also be specified by its numerical value
173 using the escape sequence <code>\<em>ddd</em></code>,
174 where <em>ddd</em> is a sequence of up to three decimal digits.
175 (Note that if a numerical escape is to be followed by a digit,
176 it must be expressed using exactly three digits.)
177 Strings in Lua may contain any 8-bit value, including embedded zeros,
178 which can be specified as '<code>\0</code>'.
182 To put a double (single) quote, a newline, a backslash,
183 a carriage return,
184 or an embedded zero
185 inside a literal string enclosed by double (single) quotes
186 you must use an escape sequence.
187 Any other character may be directly inserted into the literal.
188 (Some control characters may cause problems for the file system,
189 but Lua has no problem with them.)
193 Literal strings can also be defined using a long format
194 enclosed by <em>long brackets</em>.
195 We define an <em>opening long bracket of level <em>n</em></em> as an opening
196 square bracket followed by <em>n</em> equal signs followed by another
197 opening square bracket.
198 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
199 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
200 and so on.
201 A <em>closing long bracket</em> is defined similarly;
202 for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
203 A long string starts with an opening long bracket of any level and
204 ends at the first closing long bracket of the same level.
205 Literals in this bracketed form may run for several lines,
206 do not interpret any escape sequences,
207 and ignore long brackets of any other level.
208 They may contain anything except a closing bracket of the proper level.
212 For convenience,
213 when the opening long bracket is immediately followed by a newline,
214 the newline is not included in the string.
215 As an example, in a system using ASCII
216 (in which '<code>a</code>' is coded as&nbsp;97,
217 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
218 the five literals below denote the same string:
220 <pre>
221 a = 'alo\n123"'
222 a = "alo\n123\""
223 a = '\97lo\10\04923"'
224 a = [[alo
225 123"]]
226 a = [==[
228 123"]==]
229 </pre>
232 A <em>numerical constant</em> may be written with an optional decimal part
233 and an optional decimal exponent.
234 Lua also accepts integer hexadecimal constants,
235 by prefixing them with <code>0x</code>.
236 Examples of valid numerical constants are
238 <pre>
239 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
240 </pre>
243 A <em>comment</em> starts with a double hyphen (<code>--</code>)
244 anywhere outside a string.
245 If the text immediately after <code>--</code> is not an opening long bracket,
246 the comment is a <em>short comment</em>,
247 which runs until the end of the line.
248 Otherwise, it is a <em>long comment</em>,
249 which runs until the corresponding closing long bracket.
250 Long comments are frequently used to disable code temporarily.
256 <h2>2.2 - <a name="2.2">Values and Types</a></h2>
259 Lua is a <em>dynamically typed language</em>.
260 This means that
261 variables do not have types; only values do.
262 There are no type definitions in the language.
263 All values carry their own type.
267 All values in Lua are <em>first-class values</em>.
268 This means that all values can be stored in variables,
269 passed as arguments to other functions, and returned as results.
273 There are eight basic types in Lua:
274 <em>nil</em>, <em>boolean</em>, <em>number</em>,
275 <em>string</em>, <em>function</em>, <em>userdata</em>,
276 <em>thread</em>, and <em>table</em>.
277 <em>Nil</em> is the type of the value <b>nil</b>,
278 whose main property is to be different from any other value;
279 it usually represents the absence of a useful value.
280 <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
281 Both <b>nil</b> and <b>false</b> make a condition false;
282 any other value makes it true.
283 <em>Number</em> represents real (double-precision floating-point) numbers.
284 (It is easy to build Lua interpreters that use other
285 internal representations for numbers,
286 such as single-precision float or long integers;
287 see file <code>luaconf.h</code>.)
288 <em>String</em> represents arrays of characters.
290 Lua is 8-bit clean:
291 strings may contain any 8-bit character,
292 including embedded zeros ('<code>\0</code>') (see <a href="#2.1">&sect;2.1</a>).
296 Lua can call (and manipulate) functions written in Lua and
297 functions written in C
298 (see <a href="#2.5.8">&sect;2.5.8</a>).
302 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
303 be stored in Lua variables.
304 This type corresponds to a block of raw memory
305 and has no pre-defined operations in Lua,
306 except assignment and identity test.
307 However, by using <em>metatables</em>,
308 the programmer can define operations for userdata values
309 (see <a href="#2.8">&sect;2.8</a>).
310 Userdata values cannot be created or modified in Lua,
311 only through the C&nbsp;API.
312 This guarantees the integrity of data owned by the host program.
316 The type <em>thread</em> represents independent threads of execution
317 and it is used to implement coroutines (see <a href="#2.11">&sect;2.11</a>).
318 Do not confuse Lua threads with operating-system threads.
319 Lua supports coroutines on all systems,
320 even those that do not support threads.
324 The type <em>table</em> implements associative arrays,
325 that is, arrays that can be indexed not only with numbers,
326 but with any value (except <b>nil</b>).
327 Tables can be <em>heterogeneous</em>;
328 that is, they can contain values of all types (except <b>nil</b>).
329 Tables are the sole data structuring mechanism in Lua;
330 they may be used to represent ordinary arrays,
331 symbol tables, sets, records, graphs, trees, etc.
332 To represent records, Lua uses the field name as an index.
333 The language supports this representation by
334 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
335 There are several convenient ways to create tables in Lua
336 (see <a href="#2.5.7">&sect;2.5.7</a>).
340 Like indices,
341 the value of a table field can be of any type (except <b>nil</b>).
342 In particular,
343 because functions are first-class values,
344 table fields may contain functions.
345 Thus tables may also carry <em>methods</em> (see <a href="#2.5.9">&sect;2.5.9</a>).
349 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
350 variables do not actually <em>contain</em> these values,
351 only <em>references</em> to them.
352 Assignment, parameter passing, and function returns
353 always manipulate references to such values;
354 these operations do not imply any kind of copy.
358 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
359 of a given value.
363 <h3>2.2.1 - <a name="2.2.1">Coercion</a></h3>
366 Lua provides automatic conversion between
367 string and number values at run time.
368 Any arithmetic operation applied to a string tries to convert
369 this string to a number, following the usual conversion rules.
370 Conversely, whenever a number is used where a string is expected,
371 the number is converted to a string, in a reasonable format.
372 For complete control over how numbers are converted to strings,
373 use the <code>format</code> function from the string library
374 (see <a href="#pdf-string.format"><code>string.format</code></a>).
382 <h2>2.3 - <a name="2.3">Variables</a></h2>
385 Variables are places that store values.
387 There are three kinds of variables in Lua:
388 global variables, local variables, and table fields.
392 A single name can denote a global variable or a local variable
393 (or a function's formal parameter,
394 which is a particular kind of local variable):
396 <pre>
397 var ::= Name
398 </pre><p>
399 Name denotes identifiers, as defined in <a href="#2.1">&sect;2.1</a>.
403 Any variable is assumed to be global unless explicitly declared
404 as a local (see <a href="#2.4.7">&sect;2.4.7</a>).
405 Local variables are <em>lexically scoped</em>:
406 local variables can be freely accessed by functions
407 defined inside their scope (see <a href="#2.6">&sect;2.6</a>).
411 Before the first assignment to a variable, its value is <b>nil</b>.
415 Square brackets are used to index a table:
417 <pre>
418 var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
419 </pre><p>
420 The meaning of accesses to global variables
421 and table fields can be changed via metatables.
422 An access to an indexed variable <code>t[i]</code> is equivalent to
423 a call <code>gettable_event(t,i)</code>.
424 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
425 <code>gettable_event</code> function.
426 This function is not defined or callable in Lua.
427 We use it here only for explanatory purposes.)
431 The syntax <code>var.Name</code> is just syntactic sugar for
432 <code>var["Name"]</code>:
434 <pre>
435 var ::= prefixexp `<b>.</b>&acute; Name
436 </pre>
439 All global variables live as fields in ordinary Lua tables,
440 called <em>environment tables</em> or simply
441 <em>environments</em> (see <a href="#2.9">&sect;2.9</a>).
442 Each function has its own reference to an environment,
443 so that all global variables in this function
444 will refer to this environment table.
445 When a function is created,
446 it inherits the environment from the function that created it.
447 To get the environment table of a Lua function,
448 you call <a href="#pdf-getfenv"><code>getfenv</code></a>.
449 To replace it,
450 you call <a href="#pdf-setfenv"><code>setfenv</code></a>.
451 (You can only manipulate the environment of C&nbsp;functions
452 through the debug library; (see <a href="#5.9">&sect;5.9</a>).)
456 An access to a global variable <code>x</code>
457 is equivalent to <code>_env.x</code>,
458 which in turn is equivalent to
460 <pre>
461 gettable_event(_env, "x")
462 </pre><p>
463 where <code>_env</code> is the environment of the running function.
464 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
465 <code>gettable_event</code> function.
466 This function is not defined or callable in Lua.
467 Similarly, the <code>_env</code> variable is not defined in Lua.
468 We use them here only for explanatory purposes.)
474 <h2>2.4 - <a name="2.4">Statements</a></h2>
477 Lua supports an almost conventional set of statements,
478 similar to those in Pascal or C.
479 This set includes
480 assignment, control structures, function calls,
481 and variable declarations.
485 <h3>2.4.1 - <a name="2.4.1">Chunks</a></h3>
488 The unit of execution of Lua is called a <em>chunk</em>.
489 A chunk is simply a sequence of statements,
490 which are executed sequentially.
491 Each statement can be optionally followed by a semicolon:
493 <pre>
494 chunk ::= {stat [`<b>;</b>&acute;]}
495 </pre><p>
496 There are no empty statements and thus '<code>;;</code>' is not legal.
500 Lua handles a chunk as the body of an anonymous function
501 with a variable number of arguments
502 (see <a href="#2.5.9">&sect;2.5.9</a>).
503 As such, chunks can define local variables,
504 receive arguments, and return values.
508 A chunk may be stored in a file or in a string inside the host program.
509 When a chunk is executed, first it is pre-compiled into instructions for
510 a virtual machine,
511 and then the compiled code is executed
512 by an interpreter for the virtual machine.
516 Chunks may also be pre-compiled into binary form;
517 see program <code>luac</code> for details.
518 Programs in source and compiled forms are interchangeable;
519 Lua automatically detects the file type and acts accordingly.
526 <h3>2.4.2 - <a name="2.4.2">Blocks</a></h3><p>
527 A block is a list of statements;
528 syntactically, a block is the same as a chunk:
530 <pre>
531 block ::= chunk
532 </pre>
535 A block may be explicitly delimited to produce a single statement:
537 <pre>
538 stat ::= <b>do</b> block <b>end</b>
539 </pre><p>
540 Explicit blocks are useful
541 to control the scope of variable declarations.
542 Explicit blocks are also sometimes used to
543 add a <b>return</b> or <b>break</b> statement in the middle
544 of another block (see <a href="#2.4.4">&sect;2.4.4</a>).
550 <h3>2.4.3 - <a name="2.4.3">Assignment</a></h3>
553 Lua allows multiple assignment.
554 Therefore, the syntax for assignment
555 defines a list of variables on the left side
556 and a list of expressions on the right side.
557 The elements in both lists are separated by commas:
559 <pre>
560 stat ::= varlist `<b>=</b>&acute; explist
561 varlist ::= var {`<b>,</b>&acute; var}
562 explist ::= exp {`<b>,</b>&acute; exp}
563 </pre><p>
564 Expressions are discussed in <a href="#2.5">&sect;2.5</a>.
568 Before the assignment,
569 the list of values is <em>adjusted</em> to the length of
570 the list of variables.
571 If there are more values than needed,
572 the excess values are thrown away.
573 If there are fewer values than needed,
574 the list is extended with as many <b>nil</b>'s as needed.
575 If the list of expressions ends with a function call,
576 then all values returned by this call enter in the list of values,
577 before the adjustment
578 (except when the call is enclosed in parentheses; see <a href="#2.5">&sect;2.5</a>).
582 The assignment statement first evaluates all its expressions
583 and only then are the assignments performed.
584 Thus the code
586 <pre>
587 i = 3
588 i, a[i] = i+1, 20
589 </pre><p>
590 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
591 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
592 before it is assigned&nbsp;4.
593 Similarly, the line
595 <pre>
596 x, y = y, x
597 </pre><p>
598 exchanges the values of <code>x</code> and <code>y</code>.
602 The meaning of assignments to global variables
603 and table fields can be changed via metatables.
604 An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
605 <code>settable_event(t,i,val)</code>.
606 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
607 <code>settable_event</code> function.
608 This function is not defined or callable in Lua.
609 We use it here only for explanatory purposes.)
613 An assignment to a global variable <code>x = val</code>
614 is equivalent to the assignment
615 <code>_env.x = val</code>,
616 which in turn is equivalent to
618 <pre>
619 settable_event(_env, "x", val)
620 </pre><p>
621 where <code>_env</code> is the environment of the running function.
622 (The <code>_env</code> variable is not defined in Lua.
623 We use it here only for explanatory purposes.)
629 <h3>2.4.4 - <a name="2.4.4">Control Structures</a></h3><p>
630 The control structures
631 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
632 familiar syntax:
637 <pre>
638 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
639 stat ::= <b>repeat</b> block <b>until</b> exp
640 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
641 </pre><p>
642 Lua also has a <b>for</b> statement, in two flavors (see <a href="#2.4.5">&sect;2.4.5</a>).
646 The condition expression of a
647 control structure may return any value.
648 Both <b>false</b> and <b>nil</b> are considered false.
649 All values different from <b>nil</b> and <b>false</b> are considered true
650 (in particular, the number 0 and the empty string are also true).
654 In the <b>repeat</b>&ndash;<b>until</b> loop,
655 the inner block does not end at the <b>until</b> keyword,
656 but only after the condition.
657 So, the condition can refer to local variables
658 declared inside the loop block.
662 The <b>return</b> statement is used to return values
663 from a function or a chunk (which is just a function).
665 Functions and chunks may return more than one value,
666 so the syntax for the <b>return</b> statement is
668 <pre>
669 stat ::= <b>return</b> [explist]
670 </pre>
673 The <b>break</b> statement is used to terminate the execution of a
674 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
675 skipping to the next statement after the loop:
678 <pre>
679 stat ::= <b>break</b>
680 </pre><p>
681 A <b>break</b> ends the innermost enclosing loop.
685 The <b>return</b> and <b>break</b>
686 statements can only be written as the <em>last</em> statement of a block.
687 If it is really necessary to <b>return</b> or <b>break</b> in the
688 middle of a block,
689 then an explicit inner block can be used,
690 as in the idioms
691 <code>do return end</code> and <code>do break end</code>,
692 because now <b>return</b> and <b>break</b> are the last statements in
693 their (inner) blocks.
699 <h3>2.4.5 - <a name="2.4.5">For Statement</a></h3>
703 The <b>for</b> statement has two forms:
704 one numeric and one generic.
708 The numeric <b>for</b> loop repeats a block of code while a
709 control variable runs through an arithmetic progression.
710 It has the following syntax:
712 <pre>
713 stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
714 </pre><p>
715 The <em>block</em> is repeated for <em>name</em> starting at the value of
716 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
717 third <em>exp</em>.
718 More precisely, a <b>for</b> statement like
720 <pre>
721 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
722 </pre><p>
723 is equivalent to the code:
725 <pre>
727 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
728 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
729 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
730 local v = <em>var</em>
731 <em>block</em>
732 <em>var</em> = <em>var</em> + <em>step</em>
735 </pre><p>
736 Note the following:
738 <ul>
740 <li>
741 All three control expressions are evaluated only once,
742 before the loop starts.
743 They must all result in numbers.
744 </li>
746 <li>
747 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
748 The names are here for explanatory purposes only.
749 </li>
751 <li>
752 If the third expression (the step) is absent,
753 then a step of&nbsp;1 is used.
754 </li>
756 <li>
757 You can use <b>break</b> to exit a <b>for</b> loop.
758 </li>
760 <li>
761 The loop variable <code>v</code> is local to the loop;
762 you cannot use its value after the <b>for</b> ends or is broken.
763 If you need this value,
764 assign it to another variable before breaking or exiting the loop.
765 </li>
767 </ul>
770 The generic <b>for</b> statement works over functions,
771 called <em>iterators</em>.
772 On each iteration, the iterator function is called to produce a new value,
773 stopping when this new value is <b>nil</b>.
774 The generic <b>for</b> loop has the following syntax:
776 <pre>
777 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
778 namelist ::= Name {`<b>,</b>&acute; Name}
779 </pre><p>
780 A <b>for</b> statement like
782 <pre>
783 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
784 </pre><p>
785 is equivalent to the code:
787 <pre>
789 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
790 while true do
791 local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
792 <em>var</em> = <em>var_1</em>
793 if <em>var</em> == nil then break end
794 <em>block</em>
797 </pre><p>
798 Note the following:
800 <ul>
802 <li>
803 <code><em>explist</em></code> is evaluated only once.
804 Its results are an <em>iterator</em> function,
805 a <em>state</em>,
806 and an initial value for the first <em>iterator variable</em>.
807 </li>
809 <li>
810 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
811 The names are here for explanatory purposes only.
812 </li>
814 <li>
815 You can use <b>break</b> to exit a <b>for</b> loop.
816 </li>
818 <li>
819 The loop variables <code><em>var_i</em></code> are local to the loop;
820 you cannot use their values after the <b>for</b> ends.
821 If you need these values,
822 then assign them to other variables before breaking or exiting the loop.
823 </li>
825 </ul>
830 <h3>2.4.6 - <a name="2.4.6">Function Calls as Statements</a></h3><p>
831 To allow possible side-effects,
832 function calls can be executed as statements:
834 <pre>
835 stat ::= functioncall
836 </pre><p>
837 In this case, all returned values are thrown away.
838 Function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>.
844 <h3>2.4.7 - <a name="2.4.7">Local Declarations</a></h3><p>
845 Local variables may be declared anywhere inside a block.
846 The declaration may include an initial assignment:
848 <pre>
849 stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist]
850 </pre><p>
851 If present, an initial assignment has the same semantics
852 of a multiple assignment (see <a href="#2.4.3">&sect;2.4.3</a>).
853 Otherwise, all variables are initialized with <b>nil</b>.
857 A chunk is also a block (see <a href="#2.4.1">&sect;2.4.1</a>),
858 and so local variables can be declared in a chunk outside any explicit block.
859 The scope of such local variables extends until the end of the chunk.
863 The visibility rules for local variables are explained in <a href="#2.6">&sect;2.6</a>.
871 <h2>2.5 - <a name="2.5">Expressions</a></h2>
874 The basic expressions in Lua are the following:
876 <pre>
877 exp ::= prefixexp
878 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
879 exp ::= Number
880 exp ::= String
881 exp ::= function
882 exp ::= tableconstructor
883 exp ::= `<b>...</b>&acute;
884 exp ::= exp binop exp
885 exp ::= unop exp
886 prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
887 </pre>
890 Numbers and literal strings are explained in <a href="#2.1">&sect;2.1</a>;
891 variables are explained in <a href="#2.3">&sect;2.3</a>;
892 function definitions are explained in <a href="#2.5.9">&sect;2.5.9</a>;
893 function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>;
894 table constructors are explained in <a href="#2.5.7">&sect;2.5.7</a>.
895 Vararg expressions,
896 denoted by three dots ('<code>...</code>'), can only be used when
897 directly inside a vararg function;
898 they are explained in <a href="#2.5.9">&sect;2.5.9</a>.
902 Binary operators comprise arithmetic operators (see <a href="#2.5.1">&sect;2.5.1</a>),
903 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>),
904 and the concatenation operator (see <a href="#2.5.4">&sect;2.5.4</a>).
905 Unary operators comprise the unary minus (see <a href="#2.5.1">&sect;2.5.1</a>),
906 the unary <b>not</b> (see <a href="#2.5.3">&sect;2.5.3</a>),
907 and the unary <em>length operator</em> (see <a href="#2.5.5">&sect;2.5.5</a>).
911 Both function calls and vararg expressions may result in multiple values.
912 If the expression is used as a statement (see <a href="#2.4.6">&sect;2.4.6</a>)
913 (only possible for function calls),
914 then its return list is adjusted to zero elements,
915 thus discarding all returned values.
916 If the expression is used as the last (or the only) element
917 of a list of expressions,
918 then no adjustment is made
919 (unless the call is enclosed in parentheses).
920 In all other contexts,
921 Lua adjusts the result list to one element,
922 discarding all values except the first one.
926 Here are some examples:
928 <pre>
929 f() -- adjusted to 0 results
930 g(f(), x) -- f() is adjusted to 1 result
931 g(x, f()) -- g gets x plus all results from f()
932 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
933 a,b = ... -- a gets the first vararg parameter, b gets
934 -- the second (both a and b may get nil if there
935 -- is no corresponding vararg parameter)
937 a,b,c = x, f() -- f() is adjusted to 2 results
938 a,b,c = f() -- f() is adjusted to 3 results
939 return f() -- returns all results from f()
940 return ... -- returns all received vararg parameters
941 return x,y,f() -- returns x, y, and all results from f()
942 {f()} -- creates a list with all results from f()
943 {...} -- creates a list with all vararg parameters
944 {f(), nil} -- f() is adjusted to 1 result
945 </pre>
948 An expression enclosed in parentheses always results in only one value.
949 Thus,
950 <code>(f(x,y,z))</code> is always a single value,
951 even if <code>f</code> returns several values.
952 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
953 or <b>nil</b> if <code>f</code> does not return any values.)
957 <h3>2.5.1 - <a name="2.5.1">Arithmetic Operators</a></h3><p>
958 Lua supports the usual arithmetic operators:
959 the binary <code>+</code> (addition),
960 <code>-</code> (subtraction), <code>*</code> (multiplication),
961 <code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
962 and unary <code>-</code> (negation).
963 If the operands are numbers, or strings that can be converted to
964 numbers (see <a href="#2.2.1">&sect;2.2.1</a>),
965 then all operations have the usual meaning.
966 Exponentiation works for any exponent.
967 For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
968 Modulo is defined as
970 <pre>
971 a % b == a - math.floor(a/b)*b
972 </pre><p>
973 That is, it is the remainder of a division that rounds
974 the quotient towards minus infinity.
980 <h3>2.5.2 - <a name="2.5.2">Relational Operators</a></h3><p>
981 The relational operators in Lua are
983 <pre>
984 == ~= &lt; &gt; &lt;= &gt;=
985 </pre><p>
986 These operators always result in <b>false</b> or <b>true</b>.
990 Equality (<code>==</code>) first compares the type of its operands.
991 If the types are different, then the result is <b>false</b>.
992 Otherwise, the values of the operands are compared.
993 Numbers and strings are compared in the usual way.
994 Objects (tables, userdata, threads, and functions)
995 are compared by <em>reference</em>:
996 two objects are considered equal only if they are the <em>same</em> object.
997 Every time you create a new object
998 (a table, userdata, thread, or function),
999 this new object is different from any previously existing object.
1003 You can change the way that Lua compares tables and userdata
1004 by using the "eq" metamethod (see <a href="#2.8">&sect;2.8</a>).
1008 The conversion rules of <a href="#2.2.1">&sect;2.2.1</a>
1009 <em>do not</em> apply to equality comparisons.
1010 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
1011 and <code>t[0]</code> and <code>t["0"]</code> denote different
1012 entries in a table.
1016 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
1020 The order operators work as follows.
1021 If both arguments are numbers, then they are compared as such.
1022 Otherwise, if both arguments are strings,
1023 then their values are compared according to the current locale.
1024 Otherwise, Lua tries to call the "lt" or the "le"
1025 metamethod (see <a href="#2.8">&sect;2.8</a>).
1031 <h3>2.5.3 - <a name="2.5.3">Logical Operators</a></h3><p>
1032 The logical operators in Lua are
1033 <b>and</b>, <b>or</b>, and <b>not</b>.
1034 Like the control structures (see <a href="#2.4.4">&sect;2.4.4</a>),
1035 all logical operators consider both <b>false</b> and <b>nil</b> as false
1036 and anything else as true.
1040 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
1041 The conjunction operator <b>and</b> returns its first argument
1042 if this value is <b>false</b> or <b>nil</b>;
1043 otherwise, <b>and</b> returns its second argument.
1044 The disjunction operator <b>or</b> returns its first argument
1045 if this value is different from <b>nil</b> and <b>false</b>;
1046 otherwise, <b>or</b> returns its second argument.
1047 Both <b>and</b> and <b>or</b> use short-cut evaluation;
1048 that is,
1049 the second operand is evaluated only if necessary.
1050 Here are some examples:
1052 <pre>
1053 10 or 20 --&gt; 10
1054 10 or error() --&gt; 10
1055 nil or "a" --&gt; "a"
1056 nil and 10 --&gt; nil
1057 false and error() --&gt; false
1058 false and nil --&gt; false
1059 false or nil --&gt; nil
1060 10 and 20 --&gt; 20
1061 </pre><p>
1062 (In this manual,
1063 --> indicates the result of the preceding expression.)
1069 <h3>2.5.4 - <a name="2.5.4">Concatenation</a></h3><p>
1070 The string concatenation operator in Lua is
1071 denoted by two dots ('<code>..</code>').
1072 If both operands are strings or numbers, then they are converted to
1073 strings according to the rules mentioned in <a href="#2.2.1">&sect;2.2.1</a>.
1074 Otherwise, the "concat" metamethod is called (see <a href="#2.8">&sect;2.8</a>).
1080 <h3>2.5.5 - <a name="2.5.5">The Length Operator</a></h3>
1083 The length operator is denoted by the unary operator <code>#</code>.
1084 The length of a string is its number of bytes
1085 (that is, the usual meaning of string length when each
1086 character is one byte).
1090 The length of a table <code>t</code> is defined to be any
1091 integer index <code>n</code>
1092 such that <code>t[n]</code> is not <b>nil</b> and <code>t[n+1]</code> is <b>nil</b>;
1093 moreover, if <code>t[1]</code> is <b>nil</b>, <code>n</code> may be zero.
1094 For a regular array, with non-nil values from 1 to a given <code>n</code>,
1095 its length is exactly that <code>n</code>,
1096 the index of its last value.
1097 If the array has "holes"
1098 (that is, <b>nil</b> values between other non-nil values),
1099 then <code>#t</code> may be any of the indices that
1100 directly precedes a <b>nil</b> value
1101 (that is, it may consider any such <b>nil</b> value as the end of
1102 the array).
1108 <h3>2.5.6 - <a name="2.5.6">Precedence</a></h3><p>
1109 Operator precedence in Lua follows the table below,
1110 from lower to higher priority:
1112 <pre>
1115 &lt; &gt; &lt;= &gt;= ~= ==
1118 * / %
1119 not # - (unary)
1121 </pre><p>
1122 As usual,
1123 you can use parentheses to change the precedences of an expression.
1124 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
1125 operators are right associative.
1126 All other binary operators are left associative.
1132 <h3>2.5.7 - <a name="2.5.7">Table Constructors</a></h3><p>
1133 Table constructors are expressions that create tables.
1134 Every time a constructor is evaluated, a new table is created.
1135 Constructors can be used to create empty tables,
1136 or to create a table and initialize some of its fields.
1137 The general syntax for constructors is
1139 <pre>
1140 tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
1141 fieldlist ::= field {fieldsep field} [fieldsep]
1142 field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
1143 fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
1144 </pre>
1147 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
1148 with key <code>exp1</code> and value <code>exp2</code>.
1149 A field of the form <code>name = exp</code> is equivalent to
1150 <code>["name"] = exp</code>.
1151 Finally, fields of the form <code>exp</code> are equivalent to
1152 <code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
1153 starting with 1.
1154 Fields in the other formats do not affect this counting.
1155 For example,
1157 <pre>
1158 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
1159 </pre><p>
1160 is equivalent to
1162 <pre>
1164 local t = {}
1165 t[f(1)] = g
1166 t[1] = "x" -- 1st exp
1167 t[2] = "y" -- 2nd exp
1168 t.x = 1 -- t["x"] = 1
1169 t[3] = f(x) -- 3rd exp
1170 t[30] = 23
1171 t[4] = 45 -- 4th exp
1172 a = t
1174 </pre>
1177 If the last field in the list has the form <code>exp</code>
1178 and the expression is a function call or a vararg expression,
1179 then all values returned by this expression enter the list consecutively
1180 (see <a href="#2.5.8">&sect;2.5.8</a>).
1181 To avoid this,
1182 enclose the function call (or the vararg expression)
1183 in parentheses (see <a href="#2.5">&sect;2.5</a>).
1187 The field list may have an optional trailing separator,
1188 as a convenience for machine-generated code.
1194 <h3>2.5.8 - <a name="2.5.8">Function Calls</a></h3><p>
1195 A function call in Lua has the following syntax:
1197 <pre>
1198 functioncall ::= prefixexp args
1199 </pre><p>
1200 In a function call,
1201 first prefixexp and args are evaluated.
1202 If the value of prefixexp has type <em>function</em>,
1203 then this function is called
1204 with the given arguments.
1205 Otherwise, the prefixexp "call" metamethod is called,
1206 having as first parameter the value of prefixexp,
1207 followed by the original call arguments
1208 (see <a href="#2.8">&sect;2.8</a>).
1212 The form
1214 <pre>
1215 functioncall ::= prefixexp `<b>:</b>&acute; Name args
1216 </pre><p>
1217 can be used to call "methods".
1218 A call <code>v:name(<em>args</em>)</code>
1219 is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
1220 except that <code>v</code> is evaluated only once.
1224 Arguments have the following syntax:
1226 <pre>
1227 args ::= `<b>(</b>&acute; [explist] `<b>)</b>&acute;
1228 args ::= tableconstructor
1229 args ::= String
1230 </pre><p>
1231 All argument expressions are evaluated before the call.
1232 A call of the form <code>f{<em>fields</em>}</code> is
1233 syntactic sugar for <code>f({<em>fields</em>})</code>;
1234 that is, the argument list is a single new table.
1235 A call of the form <code>f'<em>string</em>'</code>
1236 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
1237 is syntactic sugar for <code>f('<em>string</em>')</code>;
1238 that is, the argument list is a single literal string.
1242 As an exception to the free-format syntax of Lua,
1243 you cannot put a line break before the '<code>(</code>' in a function call.
1244 This restriction avoids some ambiguities in the language.
1245 If you write
1247 <pre>
1248 a = f
1249 (g).x(a)
1250 </pre><p>
1251 Lua would see that as a single statement, <code>a = f(g).x(a)</code>.
1252 So, if you want two statements, you must add a semi-colon between them.
1253 If you actually want to call <code>f</code>,
1254 you must remove the line break before <code>(g)</code>.
1258 A call of the form <code>return</code> <em>functioncall</em> is called
1259 a <em>tail call</em>.
1260 Lua implements <em>proper tail calls</em>
1261 (or <em>proper tail recursion</em>):
1262 in a tail call,
1263 the called function reuses the stack entry of the calling function.
1264 Therefore, there is no limit on the number of nested tail calls that
1265 a program can execute.
1266 However, a tail call erases any debug information about the
1267 calling function.
1268 Note that a tail call only happens with a particular syntax,
1269 where the <b>return</b> has one single function call as argument;
1270 this syntax makes the calling function return exactly
1271 the returns of the called function.
1272 So, none of the following examples are tail calls:
1274 <pre>
1275 return (f(x)) -- results adjusted to 1
1276 return 2 * f(x)
1277 return x, f(x) -- additional results
1278 f(x); return -- results discarded
1279 return x or f(x) -- results adjusted to 1
1280 </pre>
1285 <h3>2.5.9 - <a name="2.5.9">Function Definitions</a></h3>
1288 The syntax for function definition is
1290 <pre>
1291 function ::= <b>function</b> funcbody
1292 funcbody ::= `<b>(</b>&acute; [parlist] `<b>)</b>&acute; block <b>end</b>
1293 </pre>
1296 The following syntactic sugar simplifies function definitions:
1298 <pre>
1299 stat ::= <b>function</b> funcname funcbody
1300 stat ::= <b>local</b> <b>function</b> Name funcbody
1301 funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
1302 </pre><p>
1303 The statement
1305 <pre>
1306 function f () <em>body</em> end
1307 </pre><p>
1308 translates to
1310 <pre>
1311 f = function () <em>body</em> end
1312 </pre><p>
1313 The statement
1315 <pre>
1316 function t.a.b.c.f () <em>body</em> end
1317 </pre><p>
1318 translates to
1320 <pre>
1321 t.a.b.c.f = function () <em>body</em> end
1322 </pre><p>
1323 The statement
1325 <pre>
1326 local function f () <em>body</em> end
1327 </pre><p>
1328 translates to
1330 <pre>
1331 local f; f = function () <em>body</em> end
1332 </pre><p>
1333 <em>not</em> to
1335 <pre>
1336 local f = function () <em>body</em> end
1337 </pre><p>
1338 (This only makes a difference when the body of the function
1339 contains references to <code>f</code>.)
1343 A function definition is an executable expression,
1344 whose value has type <em>function</em>.
1345 When Lua pre-compiles a chunk,
1346 all its function bodies are pre-compiled too.
1347 Then, whenever Lua executes the function definition,
1348 the function is <em>instantiated</em> (or <em>closed</em>).
1349 This function instance (or <em>closure</em>)
1350 is the final value of the expression.
1351 Different instances of the same function
1352 may refer to different external local variables
1353 and may have different environment tables.
1357 Parameters act as local variables that are
1358 initialized with the argument values:
1360 <pre>
1361 parlist ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
1362 </pre><p>
1363 When a function is called,
1364 the list of arguments is adjusted to
1365 the length of the list of parameters,
1366 unless the function is a variadic or <em>vararg function</em>,
1367 which is
1368 indicated by three dots ('<code>...</code>') at the end of its parameter list.
1369 A vararg function does not adjust its argument list;
1370 instead, it collects all extra arguments and supplies them
1371 to the function through a <em>vararg expression</em>,
1372 which is also written as three dots.
1373 The value of this expression is a list of all actual extra arguments,
1374 similar to a function with multiple results.
1375 If a vararg expression is used inside another expression
1376 or in the middle of a list of expressions,
1377 then its return list is adjusted to one element.
1378 If the expression is used as the last element of a list of expressions,
1379 then no adjustment is made
1380 (unless the call is enclosed in parentheses).
1384 As an example, consider the following definitions:
1386 <pre>
1387 function f(a, b) end
1388 function g(a, b, ...) end
1389 function r() return 1,2,3 end
1390 </pre><p>
1391 Then, we have the following mapping from arguments to parameters and
1392 to the vararg expression:
1394 <pre>
1395 CALL PARAMETERS
1397 f(3) a=3, b=nil
1398 f(3, 4) a=3, b=4
1399 f(3, 4, 5) a=3, b=4
1400 f(r(), 10) a=1, b=10
1401 f(r()) a=1, b=2
1403 g(3) a=3, b=nil, ... --&gt; (nothing)
1404 g(3, 4) a=3, b=4, ... --&gt; (nothing)
1405 g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
1406 g(5, r()) a=5, b=1, ... --&gt; 2 3
1407 </pre>
1410 Results are returned using the <b>return</b> statement (see <a href="#2.4.4">&sect;2.4.4</a>).
1411 If control reaches the end of a function
1412 without encountering a <b>return</b> statement,
1413 then the function returns with no results.
1417 The <em>colon</em> syntax
1418 is used for defining <em>methods</em>,
1419 that is, functions that have an implicit extra parameter <code>self</code>.
1420 Thus, the statement
1422 <pre>
1423 function t.a.b.c:f (<em>params</em>) <em>body</em> end
1424 </pre><p>
1425 is syntactic sugar for
1427 <pre>
1428 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
1429 </pre>
1436 <h2>2.6 - <a name="2.6">Visibility Rules</a></h2>
1440 Lua is a lexically scoped language.
1441 The scope of variables begins at the first statement <em>after</em>
1442 their declaration and lasts until the end of the innermost block that
1443 includes the declaration.
1444 Consider the following example:
1446 <pre>
1447 x = 10 -- global variable
1448 do -- new block
1449 local x = x -- new 'x', with value 10
1450 print(x) --&gt; 10
1451 x = x+1
1452 do -- another block
1453 local x = x+1 -- another 'x'
1454 print(x) --&gt; 12
1456 print(x) --&gt; 11
1458 print(x) --&gt; 10 (the global one)
1459 </pre>
1462 Notice that, in a declaration like <code>local x = x</code>,
1463 the new <code>x</code> being declared is not in scope yet,
1464 and so the second <code>x</code> refers to the outside variable.
1468 Because of the lexical scoping rules,
1469 local variables can be freely accessed by functions
1470 defined inside their scope.
1471 A local variable used by an inner function is called
1472 an <em>upvalue</em>, or <em>external local variable</em>,
1473 inside the inner function.
1477 Notice that each execution of a <b>local</b> statement
1478 defines new local variables.
1479 Consider the following example:
1481 <pre>
1482 a = {}
1483 local x = 20
1484 for i=1,10 do
1485 local y = 0
1486 a[i] = function () y=y+1; return x+y end
1488 </pre><p>
1489 The loop creates ten closures
1490 (that is, ten instances of the anonymous function).
1491 Each of these closures uses a different <code>y</code> variable,
1492 while all of them share the same <code>x</code>.
1498 <h2>2.7 - <a name="2.7">Error Handling</a></h2>
1501 Because Lua is an embedded extension language,
1502 all Lua actions start from C&nbsp;code in the host program
1503 calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
1504 Whenever an error occurs during Lua compilation or execution,
1505 control returns to C,
1506 which can take appropriate measures
1507 (such as printing an error message).
1511 Lua code can explicitly generate an error by calling the
1512 <a href="#pdf-error"><code>error</code></a> function.
1513 If you need to catch errors in Lua,
1514 you can use the <a href="#pdf-pcall"><code>pcall</code></a> function.
1520 <h2>2.8 - <a name="2.8">Metatables</a></h2>
1523 Every value in Lua may have a <em>metatable</em>.
1524 This <em>metatable</em> is an ordinary Lua table
1525 that defines the behavior of the original value
1526 under certain special operations.
1527 You can change several aspects of the behavior
1528 of operations over a value by setting specific fields in its metatable.
1529 For instance, when a non-numeric value is the operand of an addition,
1530 Lua checks for a function in the field <code>"__add"</code> in its metatable.
1531 If it finds one,
1532 Lua calls this function to perform the addition.
1536 We call the keys in a metatable <em>events</em>
1537 and the values <em>metamethods</em>.
1538 In the previous example, the event is <code>"add"</code>
1539 and the metamethod is the function that performs the addition.
1543 You can query the metatable of any value
1544 through the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
1548 You can replace the metatable of tables
1549 through the <a href="#pdf-setmetatable"><code>setmetatable</code></a>
1550 function.
1551 You cannot change the metatable of other types from Lua
1552 (except using the debug library);
1553 you must use the C&nbsp;API for that.
1557 Tables and full userdata have individual metatables
1558 (although multiple tables and userdata can share their metatables);
1559 values of all other types share one single metatable per type.
1560 So, there is one single metatable for all numbers,
1561 one for all strings, etc.
1565 A metatable may control how an object behaves in arithmetic operations,
1566 order comparisons, concatenation, length operation, and indexing.
1567 A metatable can also define a function to be called when a userdata
1568 is garbage collected.
1569 For each of these operations Lua associates a specific key
1570 called an <em>event</em>.
1571 When Lua performs one of these operations over a value,
1572 it checks whether this value has a metatable with the corresponding event.
1573 If so, the value associated with that key (the metamethod)
1574 controls how Lua will perform the operation.
1578 Metatables control the operations listed next.
1579 Each operation is identified by its corresponding name.
1580 The key for each operation is a string with its name prefixed by
1581 two underscores, '<code>__</code>';
1582 for instance, the key for operation "add" is the
1583 string <code>"__add"</code>.
1584 The semantics of these operations is better explained by a Lua function
1585 describing how the interpreter executes the operation.
1589 The code shown here in Lua is only illustrative;
1590 the real behavior is hard coded in the interpreter
1591 and it is much more efficient than this simulation.
1592 All functions used in these descriptions
1593 (<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
1594 are described in <a href="#5.1">&sect;5.1</a>.
1595 In particular, to retrieve the metamethod of a given object,
1596 we use the expression
1598 <pre>
1599 metatable(obj)[event]
1600 </pre><p>
1601 This should be read as
1603 <pre>
1604 rawget(getmetatable(obj) or {}, event)
1605 </pre><p>
1607 That is, the access to a metamethod does not invoke other metamethods,
1608 and the access to objects with no metatables does not fail
1609 (it simply results in <b>nil</b>).
1613 <ul>
1615 <li><b>"add":</b>
1616 the <code>+</code> operation.
1621 The function <code>getbinhandler</code> below defines how Lua chooses a handler
1622 for a binary operation.
1623 First, Lua tries the first operand.
1624 If its type does not define a handler for the operation,
1625 then Lua tries the second operand.
1627 <pre>
1628 function getbinhandler (op1, op2, event)
1629 return metatable(op1)[event] or metatable(op2)[event]
1631 </pre><p>
1632 By using this function,
1633 the behavior of the <code>op1 + op2</code> is
1635 <pre>
1636 function add_event (op1, op2)
1637 local o1, o2 = tonumber(op1), tonumber(op2)
1638 if o1 and o2 then -- both operands are numeric?
1639 return o1 + o2 -- '+' here is the primitive 'add'
1640 else -- at least one of the operands is not numeric
1641 local h = getbinhandler(op1, op2, "__add")
1642 if h then
1643 -- call the handler with both operands
1644 return (h(op1, op2))
1645 else -- no handler available: default behavior
1646 error(&middot;&middot;&middot;)
1650 </pre><p>
1651 </li>
1653 <li><b>"sub":</b>
1654 the <code>-</code> operation.
1656 Behavior similar to the "add" operation.
1657 </li>
1659 <li><b>"mul":</b>
1660 the <code>*</code> operation.
1662 Behavior similar to the "add" operation.
1663 </li>
1665 <li><b>"div":</b>
1666 the <code>/</code> operation.
1668 Behavior similar to the "add" operation.
1669 </li>
1671 <li><b>"mod":</b>
1672 the <code>%</code> operation.
1674 Behavior similar to the "add" operation,
1675 with the operation
1676 <code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
1677 </li>
1679 <li><b>"pow":</b>
1680 the <code>^</code> (exponentiation) operation.
1682 Behavior similar to the "add" operation,
1683 with the function <code>pow</code> (from the C&nbsp;math library)
1684 as the primitive operation.
1685 </li>
1687 <li><b>"unm":</b>
1688 the unary <code>-</code> operation.
1691 <pre>
1692 function unm_event (op)
1693 local o = tonumber(op)
1694 if o then -- operand is numeric?
1695 return -o -- '-' here is the primitive 'unm'
1696 else -- the operand is not numeric.
1697 -- Try to get a handler from the operand
1698 local h = metatable(op).__unm
1699 if h then
1700 -- call the handler with the operand
1701 return (h(op))
1702 else -- no handler available: default behavior
1703 error(&middot;&middot;&middot;)
1707 </pre><p>
1708 </li>
1710 <li><b>"concat":</b>
1711 the <code>..</code> (concatenation) operation.
1714 <pre>
1715 function concat_event (op1, op2)
1716 if (type(op1) == "string" or type(op1) == "number") and
1717 (type(op2) == "string" or type(op2) == "number") then
1718 return op1 .. op2 -- primitive string concatenation
1719 else
1720 local h = getbinhandler(op1, op2, "__concat")
1721 if h then
1722 return (h(op1, op2))
1723 else
1724 error(&middot;&middot;&middot;)
1728 </pre><p>
1729 </li>
1731 <li><b>"len":</b>
1732 the <code>#</code> operation.
1735 <pre>
1736 function len_event (op)
1737 if type(op) == "string" then
1738 return strlen(op) -- primitive string length
1739 elseif type(op) == "table" then
1740 return #op -- primitive table length
1741 else
1742 local h = metatable(op).__len
1743 if h then
1744 -- call the handler with the operand
1745 return (h(op))
1746 else -- no handler available: default behavior
1747 error(&middot;&middot;&middot;)
1751 </pre><p>
1752 See <a href="#2.5.5">&sect;2.5.5</a> for a description of the length of a table.
1753 </li>
1755 <li><b>"eq":</b>
1756 the <code>==</code> operation.
1758 The function <code>getcomphandler</code> defines how Lua chooses a metamethod
1759 for comparison operators.
1760 A metamethod only is selected when both objects
1761 being compared have the same type
1762 and the same metamethod for the selected operation.
1764 <pre>
1765 function getcomphandler (op1, op2, event)
1766 if type(op1) ~= type(op2) then return nil end
1767 local mm1 = metatable(op1)[event]
1768 local mm2 = metatable(op2)[event]
1769 if mm1 == mm2 then return mm1 else return nil end
1771 </pre><p>
1772 The "eq" event is defined as follows:
1774 <pre>
1775 function eq_event (op1, op2)
1776 if type(op1) ~= type(op2) then -- different types?
1777 return false -- different objects
1779 if op1 == op2 then -- primitive equal?
1780 return true -- objects are equal
1782 -- try metamethod
1783 local h = getcomphandler(op1, op2, "__eq")
1784 if h then
1785 return (h(op1, op2))
1786 else
1787 return false
1790 </pre><p>
1791 <code>a ~= b</code> is equivalent to <code>not (a == b)</code>.
1792 </li>
1794 <li><b>"lt":</b>
1795 the <code>&lt;</code> operation.
1798 <pre>
1799 function lt_event (op1, op2)
1800 if type(op1) == "number" and type(op2) == "number" then
1801 return op1 &lt; op2 -- numeric comparison
1802 elseif type(op1) == "string" and type(op2) == "string" then
1803 return op1 &lt; op2 -- lexicographic comparison
1804 else
1805 local h = getcomphandler(op1, op2, "__lt")
1806 if h then
1807 return (h(op1, op2))
1808 else
1809 error(&middot;&middot;&middot;);
1813 </pre><p>
1814 <code>a &gt; b</code> is equivalent to <code>b &lt; a</code>.
1815 </li>
1817 <li><b>"le":</b>
1818 the <code>&lt;=</code> operation.
1821 <pre>
1822 function le_event (op1, op2)
1823 if type(op1) == "number" and type(op2) == "number" then
1824 return op1 &lt;= op2 -- numeric comparison
1825 elseif type(op1) == "string" and type(op2) == "string" then
1826 return op1 &lt;= op2 -- lexicographic comparison
1827 else
1828 local h = getcomphandler(op1, op2, "__le")
1829 if h then
1830 return (h(op1, op2))
1831 else
1832 h = getcomphandler(op1, op2, "__lt")
1833 if h then
1834 return not h(op2, op1)
1835 else
1836 error(&middot;&middot;&middot;);
1841 </pre><p>
1842 <code>a &gt;= b</code> is equivalent to <code>b &lt;= a</code>.
1843 Note that, in the absence of a "le" metamethod,
1844 Lua tries the "lt", assuming that <code>a &lt;= b</code> is
1845 equivalent to <code>not (b &lt; a)</code>.
1846 </li>
1848 <li><b>"index":</b>
1849 The indexing access <code>table[key]</code>.
1852 <pre>
1853 function gettable_event (table, key)
1854 local h
1855 if type(table) == "table" then
1856 local v = rawget(table, key)
1857 if v ~= nil then return v end
1858 h = metatable(table).__index
1859 if h == nil then return nil end
1860 else
1861 h = metatable(table).__index
1862 if h == nil then
1863 error(&middot;&middot;&middot;);
1866 if type(h) == "function" then
1867 return (h(table, key)) -- call the handler
1868 else return h[key] -- or repeat operation on it
1871 </pre><p>
1872 </li>
1874 <li><b>"newindex":</b>
1875 The indexing assignment <code>table[key] = value</code>.
1878 <pre>
1879 function settable_event (table, key, value)
1880 local h
1881 if type(table) == "table" then
1882 local v = rawget(table, key)
1883 if v ~= nil then rawset(table, key, value); return end
1884 h = metatable(table).__newindex
1885 if h == nil then rawset(table, key, value); return end
1886 else
1887 h = metatable(table).__newindex
1888 if h == nil then
1889 error(&middot;&middot;&middot;);
1892 if type(h) == "function" then
1893 h(table, key,value) -- call the handler
1894 else h[key] = value -- or repeat operation on it
1897 </pre><p>
1898 </li>
1900 <li><b>"call":</b>
1901 called when Lua calls a value.
1904 <pre>
1905 function function_event (func, ...)
1906 if type(func) == "function" then
1907 return func(...) -- primitive call
1908 else
1909 local h = metatable(func).__call
1910 if h then
1911 return h(func, ...)
1912 else
1913 error(&middot;&middot;&middot;)
1917 </pre><p>
1918 </li>
1920 </ul>
1925 <h2>2.9 - <a name="2.9">Environments</a></h2>
1928 Besides metatables,
1929 objects of types thread, function, and userdata
1930 have another table associated with them,
1931 called their <em>environment</em>.
1932 Like metatables, environments are regular tables and
1933 multiple objects can share the same environment.
1937 Environments associated with userdata have no meaning for Lua.
1938 It is only a convenience feature for programmers to associate a table to
1939 a userdata.
1943 Environments associated with threads are called
1944 <em>global environments</em>.
1945 They are used as the default environment for their threads and
1946 non-nested functions created by the thread
1947 (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>)
1948 and can be directly accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1952 Environments associated with C&nbsp;functions can be directly
1953 accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1954 They are used as the default environment for other C&nbsp;functions
1955 created by the function.
1959 Environments associated with Lua functions are used to resolve
1960 all accesses to global variables within the function (see <a href="#2.3">&sect;2.3</a>).
1961 They are used as the default environment for other Lua functions
1962 created by the function.
1966 You can change the environment of a Lua function or the
1967 running thread by calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
1968 You can get the environment of a Lua function or the running thread
1969 by calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
1970 To manipulate the environment of other objects
1971 (userdata, C&nbsp;functions, other threads) you must
1972 use the C&nbsp;API.
1978 <h2>2.10 - <a name="2.10">Garbage Collection</a></h2>
1981 Lua performs automatic memory management.
1982 This means that
1983 you have to worry neither about allocating memory for new objects
1984 nor about freeing it when the objects are no longer needed.
1985 Lua manages memory automatically by running
1986 a <em>garbage collector</em> from time to time
1987 to collect all <em>dead objects</em>
1988 (that is, these objects that are no longer accessible from Lua).
1989 All objects in Lua are subject to automatic management:
1990 tables, userdata, functions, threads, and strings.
1994 Lua implements an incremental mark-and-sweep collector.
1995 It uses two numbers to control its garbage-collection cycles:
1996 the <em>garbage-collector pause</em> and
1997 the <em>garbage-collector step multiplier</em>.
2001 The garbage-collector pause
2002 controls how long the collector waits before starting a new cycle.
2003 Larger values make the collector less aggressive.
2004 Values smaller than 1 mean the collector will not wait to
2005 start a new cycle.
2006 A value of 2 means that the collector waits for the total memory in use
2007 to double before starting a new cycle.
2011 The step multiplier
2012 controls the relative speed of the collector relative to
2013 memory allocation.
2014 Larger values make the collector more aggressive but also increase
2015 the size of each incremental step.
2016 Values smaller than 1 make the collector too slow and
2017 may result in the collector never finishing a cycle.
2018 The default, 2, means that the collector runs at "twice"
2019 the speed of memory allocation.
2023 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
2024 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
2025 Both get percentage points as arguments
2026 (so an argument of 100 means a real value of 1).
2027 With these functions you can also control
2028 the collector directly (e.g., stop and restart it).
2032 <h3>2.10.1 - <a name="2.10.1">Garbage-Collection Metamethods</a></h3>
2035 Using the C&nbsp;API,
2036 you can set garbage-collector metamethods for userdata (see <a href="#2.8">&sect;2.8</a>).
2037 These metamethods are also called <em>finalizers</em>.
2038 Finalizers allow you to coordinate Lua's garbage collection
2039 with external resource management
2040 (such as closing files, network or database connections,
2041 or freeing your own memory).
2045 Garbage userdata with a field <code>__gc</code> in their metatables are not
2046 collected immediately by the garbage collector.
2047 Instead, Lua puts them in a list.
2048 After the collection,
2049 Lua does the equivalent of the following function
2050 for each userdata in that list:
2052 <pre>
2053 function gc_event (udata)
2054 local h = metatable(udata).__gc
2055 if h then
2056 h(udata)
2059 </pre>
2062 At the end of each garbage-collection cycle,
2063 the finalizers for userdata are called in <em>reverse</em>
2064 order of their creation,
2065 among those collected in that cycle.
2066 That is, the first finalizer to be called is the one associated
2067 with the userdata created last in the program.
2068 The userdata itself is freed only in the next garbage-collection cycle.
2074 <h3>2.10.2 - <a name="2.10.2">Weak Tables</a></h3>
2077 A <em>weak table</em> is a table whose elements are
2078 <em>weak references</em>.
2079 A weak reference is ignored by the garbage collector.
2080 In other words,
2081 if the only references to an object are weak references,
2082 then the garbage collector will collect this object.
2086 A weak table can have weak keys, weak values, or both.
2087 A table with weak keys allows the collection of its keys,
2088 but prevents the collection of its values.
2089 A table with both weak keys and weak values allows the collection of
2090 both keys and values.
2091 In any case, if either the key or the value is collected,
2092 the whole pair is removed from the table.
2093 The weakness of a table is controlled by the
2094 <code>__mode</code> field of its metatable.
2095 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
2096 the keys in the table are weak.
2097 If <code>__mode</code> contains '<code>v</code>',
2098 the values in the table are weak.
2102 After you use a table as a metatable,
2103 you should not change the value of its field <code>__mode</code>.
2104 Otherwise, the weak behavior of the tables controlled by this
2105 metatable is undefined.
2113 <h2>2.11 - <a name="2.11">Coroutines</a></h2>
2116 Lua supports coroutines,
2117 also called <em>collaborative multithreading</em>.
2118 A coroutine in Lua represents an independent thread of execution.
2119 Unlike threads in multithread systems, however,
2120 a coroutine only suspends its execution by explicitly calling
2121 a yield function.
2125 You create a coroutine with a call to <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
2126 Its sole argument is a function
2127 that is the main function of the coroutine.
2128 The <code>create</code> function only creates a new coroutine and
2129 returns a handle to it (an object of type <em>thread</em>);
2130 it does not start the coroutine execution.
2134 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2135 passing as its first argument
2136 the thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2137 the coroutine starts its execution,
2138 at the first line of its main function.
2139 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
2140 to the coroutine main function.
2141 After the coroutine starts running,
2142 it runs until it terminates or <em>yields</em>.
2146 A coroutine can terminate its execution in two ways:
2147 normally, when its main function returns
2148 (explicitly or implicitly, after the last instruction);
2149 and abnormally, if there is an unprotected error.
2150 In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
2151 plus any values returned by the coroutine main function.
2152 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
2153 plus an error message.
2157 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2158 When a coroutine yields,
2159 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
2160 even if the yield happens inside nested function calls
2161 (that is, not in the main function,
2162 but in a function directly or indirectly called by the main function).
2163 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
2164 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2165 The next time you resume the same coroutine,
2166 it continues its execution from the point where it yielded,
2167 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
2168 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2172 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2173 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
2174 but instead of returning the coroutine itself,
2175 it returns a function that, when called, resumes the coroutine.
2176 Any arguments passed to this function
2177 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2178 <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>,
2179 except the first one (the boolean error code).
2180 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2181 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
2182 any error is propagated to the caller.
2186 As an example,
2187 consider the following code:
2189 <pre>
2190 function foo (a)
2191 print("foo", a)
2192 return coroutine.yield(2*a)
2195 co = coroutine.create(function (a,b)
2196 print("co-body", a, b)
2197 local r = foo(a+1)
2198 print("co-body", r)
2199 local r, s = coroutine.yield(a+b, a-b)
2200 print("co-body", r, s)
2201 return b, "end"
2202 end)
2204 print("main", coroutine.resume(co, 1, 10))
2205 print("main", coroutine.resume(co, "r"))
2206 print("main", coroutine.resume(co, "x", "y"))
2207 print("main", coroutine.resume(co, "x", "y"))
2208 </pre><p>
2209 When you run it, it produces the following output:
2211 <pre>
2212 co-body 1 10
2213 foo 2
2215 main true 4
2216 co-body r
2217 main true 11 -9
2218 co-body x y
2219 main true 10 end
2220 main false cannot resume dead coroutine
2221 </pre>
2226 <h1>3 - <a name="3">The Application Program Interface</a></h1>
2230 This section describes the C&nbsp;API for Lua, that is,
2231 the set of C&nbsp;functions available to the host program to communicate
2232 with Lua.
2233 All API functions and related types and constants
2234 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2238 Even when we use the term "function",
2239 any facility in the API may be provided as a macro instead.
2240 All such macros use each of their arguments exactly once
2241 (except for the first argument, which is always a Lua state),
2242 and so do not generate any hidden side-effects.
2246 As in most C&nbsp;libraries,
2247 the Lua API functions do not check their arguments for validity or consistency.
2248 However, you can change this behavior by compiling Lua
2249 with a proper definition for the macro <a name="pdf-luai_apicheck"><code>luai_apicheck</code></a>,
2250 in file <code>luaconf.h</code>.
2254 <h2>3.1 - <a name="3.1">The Stack</a></h2>
2257 Lua uses a <em>virtual stack</em> to pass values to and from C.
2258 Each element in this stack represents a Lua value
2259 (<b>nil</b>, number, string, etc.).
2263 Whenever Lua calls C, the called function gets a new stack,
2264 which is independent of previous stacks and of stacks of
2265 C&nbsp;functions that are still active.
2266 This stack initially contains any arguments to the C&nbsp;function
2267 and it is where the C&nbsp;function pushes its results
2268 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2272 For convenience,
2273 most query operations in the API do not follow a strict stack discipline.
2274 Instead, they can refer to any element in the stack
2275 by using an <em>index</em>:
2276 A positive index represents an <em>absolute</em> stack position
2277 (starting at&nbsp;1);
2278 a negative index represents an <em>offset</em> relative to the top of the stack.
2279 More specifically, if the stack has <em>n</em> elements,
2280 then index&nbsp;1 represents the first element
2281 (that is, the element that was pushed onto the stack first)
2283 index&nbsp;<em>n</em> represents the last element;
2284 index&nbsp;-1 also represents the last element
2285 (that is, the element at the&nbsp;top)
2286 and index <em>-n</em> represents the first element.
2287 We say that an index is <em>valid</em>
2288 if it lies between&nbsp;1 and the stack top
2289 (that is, if <code>1 &le; abs(index) &le; top</code>).
2296 <h2>3.2 - <a name="3.2">Stack Size</a></h2>
2299 When you interact with Lua API,
2300 you are responsible for ensuring consistency.
2301 In particular,
2302 <em>you are responsible for controlling stack overflow</em>.
2303 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2304 to grow the stack size.
2308 Whenever Lua calls C,
2309 it ensures that at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> stack positions are available.
2310 <code>LUA_MINSTACK</code> is defined as 20,
2311 so that usually you do not have to worry about stack space
2312 unless your code has loops pushing elements onto the stack.
2316 Most query functions accept as indices any value inside the
2317 available stack space, that is, indices up to the maximum stack size
2318 you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2319 Such indices are called <em>acceptable indices</em>.
2320 More formally, we define an <em>acceptable index</em>
2321 as follows:
2323 <pre>
2324 (index &lt; 0 &amp;&amp; abs(index) &lt;= top) ||
2325 (index &gt; 0 &amp;&amp; index &lt;= stackspace)
2326 </pre><p>
2327 Note that 0 is never an acceptable index.
2333 <h2>3.3 - <a name="3.3">Pseudo-Indices</a></h2>
2336 Unless otherwise noted,
2337 any function that accepts valid indices can also be called with
2338 <em>pseudo-indices</em>,
2339 which represent some Lua values that are accessible to C&nbsp;code
2340 but which are not in the stack.
2341 Pseudo-indices are used to access the thread environment,
2342 the function environment,
2343 the registry,
2344 and the upvalues of a C&nbsp;function (see <a href="#3.4">&sect;3.4</a>).
2348 The thread environment (where global variables live) is
2349 always at pseudo-index <a name="pdf-LUA_GLOBALSINDEX"><code>LUA_GLOBALSINDEX</code></a>.
2350 The environment of the running C&nbsp;function is always
2351 at pseudo-index <a name="pdf-LUA_ENVIRONINDEX"><code>LUA_ENVIRONINDEX</code></a>.
2355 To access and change the value of global variables,
2356 you can use regular table operations over an environment table.
2357 For instance, to access the value of a global variable, do
2359 <pre>
2360 lua_getfield(L, LUA_GLOBALSINDEX, varname);
2361 </pre>
2366 <h2>3.4 - <a name="3.4">C Closures</a></h2>
2369 When a C&nbsp;function is created,
2370 it is possible to associate some values with it,
2371 thus creating a <em>C&nbsp;closure</em>;
2372 these values are called <em>upvalues</em> and are
2373 accessible to the function whenever it is called
2374 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
2378 Whenever a C&nbsp;function is called,
2379 its upvalues are located at specific pseudo-indices.
2380 These pseudo-indices are produced by the macro
2381 <a name="lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2382 The first value associated with a function is at position
2383 <code>lua_upvalueindex(1)</code>, and so on.
2384 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2385 where <em>n</em> is greater than the number of upvalues of the
2386 current function,
2387 produces an acceptable (but invalid) index.
2393 <h2>3.5 - <a name="3.5">Registry</a></h2>
2396 Lua provides a <em>registry</em>,
2397 a pre-defined table that can be used by any C&nbsp;code to
2398 store whatever Lua value it needs to store.
2399 This table is always located at pseudo-index
2400 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
2401 Any C&nbsp;library can store data into this table,
2402 but it should take care to choose keys different from those used
2403 by other libraries, to avoid collisions.
2404 Typically, you should use as key a string containing your library name
2405 or a light userdata with the address of a C&nbsp;object in your code.
2409 The integer keys in the registry are used by the reference mechanism,
2410 implemented by the auxiliary library,
2411 and therefore should not be used for other purposes.
2417 <h2>3.6 - <a name="3.6">Error Handling in C</a></h2>
2420 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2421 (You can also choose to use exceptions if you use C++;
2422 see file <code>luaconf.h</code>.)
2423 When Lua faces any error
2424 (such as memory allocation errors, type errors, syntax errors,
2425 and runtime errors)
2426 it <em>raises</em> an error;
2427 that is, it does a long jump.
2428 A <em>protected environment</em> uses <code>setjmp</code>
2429 to set a recover point;
2430 any error jumps to the most recent active recover point.
2434 Most functions in the API may throw an error,
2435 for instance due to a memory allocation error.
2436 The documentation for each function indicates whether
2437 it can throw errors.
2441 Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2447 <h2>3.7 - <a name="3.7">Functions and Types</a></h2>
2450 Here we list all functions and types from the C&nbsp;API in
2451 alphabetical order.
2452 Each function has an indicator like this:
2453 <span class="apii">[-o, +p, <em>x</em>]</span>
2457 The first field, <code>o</code>,
2458 is how many elements the function pops from the stack.
2459 The second field, <code>p</code>,
2460 is how many elements the function pushes onto the stack.
2461 (Any function always pushes its results after popping its arguments.)
2462 A field in the form <code>x|y</code> means the function may push (or pop)
2463 <code>x</code> or <code>y</code> elements,
2464 depending on the situation;
2465 an interrogation mark '<code>?</code>' means that
2466 we cannot know how many elements the function pops/pushes
2467 by looking only at its arguments
2468 (e.g., they may depend on what is on the stack).
2469 The third field, <code>x</code>,
2470 tells whether the function may throw errors:
2471 '<code>-</code>' means the function never throws any error;
2472 '<code>m</code>' means the function may throw an error
2473 only due to not enough memory;
2474 '<code>e</code>' means the function may throw other kinds of errors;
2475 '<code>v</code>' means the function may throw an error on purpose.
2479 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2480 <pre>typedef void * (*lua_Alloc) (void *ud,
2481 void *ptr,
2482 size_t osize,
2483 size_t nsize);</pre>
2486 The type of the memory-allocation function used by Lua states.
2487 The allocator function must provide a
2488 functionality similar to <code>realloc</code>,
2489 but not exactly the same.
2490 Its arguments are
2491 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2492 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2493 <code>osize</code>, the original size of the block;
2494 <code>nsize</code>, the new size of the block.
2495 <code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
2496 When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
2497 if <code>osize</code> is not zero,
2498 it should free the block pointed to by <code>ptr</code>.
2499 When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
2500 if and only if it cannot fill the request.
2501 When <code>nsize</code> is not zero and <code>osize</code> is zero,
2502 the allocator should behave like <code>malloc</code>.
2503 When <code>nsize</code> and <code>osize</code> are not zero,
2504 the allocator behaves like <code>realloc</code>.
2505 Lua assumes that the allocator never fails when
2506 <code>osize &gt;= nsize</code>.
2510 Here is a simple implementation for the allocator function.
2511 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2513 <pre>
2514 static void *l_alloc (void *ud, void *ptr, size_t osize,
2515 size_t nsize) {
2516 (void)ud; (void)osize; /* not used */
2517 if (nsize == 0) {
2518 free(ptr);
2519 return NULL;
2521 else
2522 return realloc(ptr, nsize);
2524 </pre><p>
2525 This code assumes
2526 that <code>free(NULL)</code> has no effect and that
2527 <code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2528 ANSI&nbsp;C ensures both behaviors.
2534 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
2535 <span class="apii">[-0, +0, <em>-</em>]</span>
2536 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2539 Sets a new panic function and returns the old one.
2543 If an error happens outside any protected environment,
2544 Lua calls a <em>panic function</em>
2545 and then calls <code>exit(EXIT_FAILURE)</code>,
2546 thus exiting the host application.
2547 Your panic function may avoid this exit by
2548 never returning (e.g., doing a long jump).
2552 The panic function can access the error message at the top of the stack.
2558 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
2559 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
2560 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
2563 Calls a function.
2567 To call a function you must use the following protocol:
2568 first, the function to be called is pushed onto the stack;
2569 then, the arguments to the function are pushed
2570 in direct order;
2571 that is, the first argument is pushed first.
2572 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
2573 <code>nargs</code> is the number of arguments that you pushed onto the stack.
2574 All arguments and the function value are popped from the stack
2575 when the function is called.
2576 The function results are pushed onto the stack when the function returns.
2577 The number of results is adjusted to <code>nresults</code>,
2578 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
2579 In this case, <em>all</em> results from the function are pushed.
2580 Lua takes care that the returned values fit into the stack space.
2581 The function results are pushed onto the stack in direct order
2582 (the first result is pushed first),
2583 so that after the call the last result is on the top of the stack.
2587 Any error inside the called function is propagated upwards
2588 (with a <code>longjmp</code>).
2592 The following example shows how the host program may do the
2593 equivalent to this Lua code:
2595 <pre>
2596 a = f("how", t.x, 14)
2597 </pre><p>
2598 Here it is in&nbsp;C:
2600 <pre>
2601 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
2602 lua_pushstring(L, "how"); /* 1st argument */
2603 lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */
2604 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
2605 lua_remove(L, -2); /* remove 't' from the stack */
2606 lua_pushinteger(L, 14); /* 3rd argument */
2607 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
2608 lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global 'a' */
2609 </pre><p>
2610 Note that the code above is "balanced":
2611 at its end, the stack is back to its original configuration.
2612 This is considered good programming practice.
2618 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
2619 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
2622 Type for C&nbsp;functions.
2626 In order to communicate properly with Lua,
2627 a C&nbsp;function must use the following protocol,
2628 which defines the way parameters and results are passed:
2629 a C&nbsp;function receives its arguments from Lua in its stack
2630 in direct order (the first argument is pushed first).
2631 So, when the function starts,
2632 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
2633 The first argument (if any) is at index 1
2634 and its last argument is at index <code>lua_gettop(L)</code>.
2635 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
2636 in direct order (the first result is pushed first),
2637 and returns the number of results.
2638 Any other value in the stack below the results will be properly
2639 discarded by Lua.
2640 Like a Lua function, a C&nbsp;function called by Lua can also return
2641 many results.
2645 As an example, the following function receives a variable number
2646 of numerical arguments and returns their average and sum:
2648 <pre>
2649 static int foo (lua_State *L) {
2650 int n = lua_gettop(L); /* number of arguments */
2651 lua_Number sum = 0;
2652 int i;
2653 for (i = 1; i &lt;= n; i++) {
2654 if (!lua_isnumber(L, i)) {
2655 lua_pushstring(L, "incorrect argument");
2656 lua_error(L);
2658 sum += lua_tonumber(L, i);
2660 lua_pushnumber(L, sum/n); /* first result */
2661 lua_pushnumber(L, sum); /* second result */
2662 return 2; /* number of results */
2664 </pre>
2669 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
2670 <span class="apii">[-0, +0, <em>m</em>]</span>
2671 <pre>int lua_checkstack (lua_State *L, int extra);</pre>
2674 Ensures that there are at least <code>extra</code> free stack slots in the stack.
2675 It returns false if it cannot grow the stack to that size.
2676 This function never shrinks the stack;
2677 if the stack is already larger than the new size,
2678 it is left unchanged.
2684 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
2685 <span class="apii">[-0, +0, <em>-</em>]</span>
2686 <pre>void lua_close (lua_State *L);</pre>
2689 Destroys all objects in the given Lua state
2690 (calling the corresponding garbage-collection metamethods, if any)
2691 and frees all dynamic memory used by this state.
2692 On several platforms, you may not need to call this function,
2693 because all resources are naturally released when the host program ends.
2694 On the other hand, long-running programs,
2695 such as a daemon or a web server,
2696 might need to release states as soon as they are not needed,
2697 to avoid growing too large.
2703 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
2704 <span class="apii">[-n, +1, <em>e</em>]</span>
2705 <pre>void lua_concat (lua_State *L, int n);</pre>
2708 Concatenates the <code>n</code> values at the top of the stack,
2709 pops them, and leaves the result at the top.
2710 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
2711 (that is, the function does nothing);
2712 if <code>n</code> is 0, the result is the empty string.
2713 Concatenation is performed following the usual semantics of Lua
2714 (see <a href="#2.5.4">&sect;2.5.4</a>).
2720 <hr><h3><a name="lua_cpcall"><code>lua_cpcall</code></a></h3><p>
2721 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
2722 <pre>int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);</pre>
2725 Calls the C&nbsp;function <code>func</code> in protected mode.
2726 <code>func</code> starts with only one element in its stack,
2727 a light userdata containing <code>ud</code>.
2728 In case of errors,
2729 <a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
2730 plus the error object on the top of the stack;
2731 otherwise, it returns zero, and does not change the stack.
2732 All values returned by <code>func</code> are discarded.
2738 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
2739 <span class="apii">[-0, +1, <em>m</em>]</span>
2740 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
2743 Creates a new empty table and pushes it onto the stack.
2744 The new table has space pre-allocated
2745 for <code>narr</code> array elements and <code>nrec</code> non-array elements.
2746 This pre-allocation is useful when you know exactly how many elements
2747 the table will have.
2748 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
2754 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
2755 <span class="apii">[-0, +0, <em>m</em>]</span>
2756 <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
2759 Dumps a function as a binary chunk.
2760 Receives a Lua function on the top of the stack
2761 and produces a binary chunk that,
2762 if loaded again,
2763 results in a function equivalent to the one dumped.
2764 As it produces parts of the chunk,
2765 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
2766 with the given <code>data</code>
2767 to write them.
2771 The value returned is the error code returned by the last
2772 call to the writer;
2773 0&nbsp;means no errors.
2777 This function does not pop the Lua function from the stack.
2783 <hr><h3><a name="lua_equal"><code>lua_equal</code></a></h3><p>
2784 <span class="apii">[-0, +0, <em>e</em>]</span>
2785 <pre>int lua_equal (lua_State *L, int index1, int index2);</pre>
2788 Returns 1 if the two values in acceptable indices <code>index1</code> and
2789 <code>index2</code> are equal,
2790 following the semantics of the Lua <code>==</code> operator
2791 (that is, may call metamethods).
2792 Otherwise returns&nbsp;0.
2793 Also returns&nbsp;0 if any of the indices is non valid.
2799 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
2800 <span class="apii">[-1, +0, <em>v</em>]</span>
2801 <pre>int lua_error (lua_State *L);</pre>
2804 Generates a Lua error.
2805 The error message (which can actually be a Lua value of any type)
2806 must be on the stack top.
2807 This function does a long jump,
2808 and therefore never returns.
2809 (see <a href="#luaL_error"><code>luaL_error</code></a>).
2815 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
2816 <span class="apii">[-0, +0, <em>e</em>]</span>
2817 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
2820 Controls the garbage collector.
2824 This function performs several tasks,
2825 according to the value of the parameter <code>what</code>:
2827 <ul>
2829 <li><b><code>LUA_GCSTOP</code>:</b>
2830 stops the garbage collector.
2831 </li>
2833 <li><b><code>LUA_GCRESTART</code>:</b>
2834 restarts the garbage collector.
2835 </li>
2837 <li><b><code>LUA_GCCOLLECT</code>:</b>
2838 performs a full garbage-collection cycle.
2839 </li>
2841 <li><b><code>LUA_GCCOUNT</code>:</b>
2842 returns the current amount of memory (in Kbytes) in use by Lua.
2843 </li>
2845 <li><b><code>LUA_GCCOUNTB</code>:</b>
2846 returns the remainder of dividing the current amount of bytes of
2847 memory in use by Lua by 1024.
2848 </li>
2850 <li><b><code>LUA_GCSTEP</code>:</b>
2851 performs an incremental step of garbage collection.
2852 The step "size" is controlled by <code>data</code>
2853 (larger values mean more steps) in a non-specified way.
2854 If you want to control the step size
2855 you must experimentally tune the value of <code>data</code>.
2856 The function returns 1 if the step finished a
2857 garbage-collection cycle.
2858 </li>
2860 <li><b><code>LUA_GCSETPAUSE</code>:</b>
2861 sets <code>data</code>/100 as the new value
2862 for the <em>pause</em> of the collector (see <a href="#2.10">&sect;2.10</a>).
2863 The function returns the previous value of the pause.
2864 </li>
2866 <li><b><code>LUA_GCSETSTEPMUL</code>:</b>
2867 sets <code>data</code>/100 as the new value for the <em>step multiplier</em> of
2868 the collector (see <a href="#2.10">&sect;2.10</a>).
2869 The function returns the previous value of the step multiplier.
2870 </li>
2872 </ul>
2877 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
2878 <span class="apii">[-0, +0, <em>-</em>]</span>
2879 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
2882 Returns the memory-allocation function of a given state.
2883 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
2884 opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
2890 <hr><h3><a name="lua_getfenv"><code>lua_getfenv</code></a></h3><p>
2891 <span class="apii">[-0, +1, <em>-</em>]</span>
2892 <pre>void lua_getfenv (lua_State *L, int index);</pre>
2895 Pushes onto the stack the environment table of
2896 the value at the given index.
2902 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
2903 <span class="apii">[-0, +1, <em>e</em>]</span>
2904 <pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
2907 Pushes onto the stack the value <code>t[k]</code>,
2908 where <code>t</code> is the value at the given valid index.
2909 As in Lua, this function may trigger a metamethod
2910 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2916 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
2917 <span class="apii">[-0, +1, <em>e</em>]</span>
2918 <pre>void lua_getglobal (lua_State *L, const char *name);</pre>
2921 Pushes onto the stack the value of the global <code>name</code>.
2922 It is defined as a macro:
2924 <pre>
2925 #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
2926 </pre>
2931 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
2932 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
2933 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
2936 Pushes onto the stack the metatable of the value at the given
2937 acceptable index.
2938 If the index is not valid,
2939 or if the value does not have a metatable,
2940 the function returns&nbsp;0 and pushes nothing on the stack.
2946 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
2947 <span class="apii">[-1, +1, <em>e</em>]</span>
2948 <pre>void lua_gettable (lua_State *L, int index);</pre>
2951 Pushes onto the stack the value <code>t[k]</code>,
2952 where <code>t</code> is the value at the given valid index
2953 and <code>k</code> is the value at the top of the stack.
2957 This function pops the key from the stack
2958 (putting the resulting value in its place).
2959 As in Lua, this function may trigger a metamethod
2960 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2966 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
2967 <span class="apii">[-0, +0, <em>-</em>]</span>
2968 <pre>int lua_gettop (lua_State *L);</pre>
2971 Returns the index of the top element in the stack.
2972 Because indices start at&nbsp;1,
2973 this result is equal to the number of elements in the stack
2974 (and so 0&nbsp;means an empty stack).
2980 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
2981 <span class="apii">[-1, +1, <em>-</em>]</span>
2982 <pre>void lua_insert (lua_State *L, int index);</pre>
2985 Moves the top element into the given valid index,
2986 shifting up the elements above this index to open space.
2987 Cannot be called with a pseudo-index,
2988 because a pseudo-index is not an actual stack position.
2994 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
2995 <pre>typedef ptrdiff_t lua_Integer;</pre>
2998 The type used by the Lua API to represent integral values.
3002 By default it is a <code>ptrdiff_t</code>,
3003 which is usually the largest signed integral type the machine handles
3004 "comfortably".
3010 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3011 <span class="apii">[-0, +0, <em>-</em>]</span>
3012 <pre>int lua_isboolean (lua_State *L, int index);</pre>
3015 Returns 1 if the value at the given acceptable index has type boolean,
3016 and 0&nbsp;otherwise.
3022 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3023 <span class="apii">[-0, +0, <em>-</em>]</span>
3024 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
3027 Returns 1 if the value at the given acceptable index is a C&nbsp;function,
3028 and 0&nbsp;otherwise.
3034 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3035 <span class="apii">[-0, +0, <em>-</em>]</span>
3036 <pre>int lua_isfunction (lua_State *L, int index);</pre>
3039 Returns 1 if the value at the given acceptable index is a function
3040 (either C or Lua), and 0&nbsp;otherwise.
3046 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3047 <span class="apii">[-0, +0, <em>-</em>]</span>
3048 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3051 Returns 1 if the value at the given acceptable index is a light userdata,
3052 and 0&nbsp;otherwise.
3058 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3059 <span class="apii">[-0, +0, <em>-</em>]</span>
3060 <pre>int lua_isnil (lua_State *L, int index);</pre>
3063 Returns 1 if the value at the given acceptable index is <b>nil</b>,
3064 and 0&nbsp;otherwise.
3070 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3071 <span class="apii">[-0, +0, <em>-</em>]</span>
3072 <pre>int lua_isnone (lua_State *L, int index);</pre>
3075 Returns 1 if the given acceptable index is not valid
3076 (that is, it refers to an element outside the current stack),
3077 and 0&nbsp;otherwise.
3083 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3084 <span class="apii">[-0, +0, <em>-</em>]</span>
3085 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3088 Returns 1 if the given acceptable index is not valid
3089 (that is, it refers to an element outside the current stack)
3090 or if the value at this index is <b>nil</b>,
3091 and 0&nbsp;otherwise.
3097 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3098 <span class="apii">[-0, +0, <em>-</em>]</span>
3099 <pre>int lua_isnumber (lua_State *L, int index);</pre>
3102 Returns 1 if the value at the given acceptable index is a number
3103 or a string convertible to a number,
3104 and 0&nbsp;otherwise.
3110 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3111 <span class="apii">[-0, +0, <em>-</em>]</span>
3112 <pre>int lua_isstring (lua_State *L, int index);</pre>
3115 Returns 1 if the value at the given acceptable index is a string
3116 or a number (which is always convertible to a string),
3117 and 0&nbsp;otherwise.
3123 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3124 <span class="apii">[-0, +0, <em>-</em>]</span>
3125 <pre>int lua_istable (lua_State *L, int index);</pre>
3128 Returns 1 if the value at the given acceptable index is a table,
3129 and 0&nbsp;otherwise.
3135 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3136 <span class="apii">[-0, +0, <em>-</em>]</span>
3137 <pre>int lua_isthread (lua_State *L, int index);</pre>
3140 Returns 1 if the value at the given acceptable index is a thread,
3141 and 0&nbsp;otherwise.
3147 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3148 <span class="apii">[-0, +0, <em>-</em>]</span>
3149 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
3152 Returns 1 if the value at the given acceptable index is a userdata
3153 (either full or light), and 0&nbsp;otherwise.
3159 <hr><h3><a name="lua_lessthan"><code>lua_lessthan</code></a></h3><p>
3160 <span class="apii">[-0, +0, <em>e</em>]</span>
3161 <pre>int lua_lessthan (lua_State *L, int index1, int index2);</pre>
3164 Returns 1 if the value at acceptable index <code>index1</code> is smaller
3165 than the value at acceptable index <code>index2</code>,
3166 following the semantics of the Lua <code>&lt;</code> operator
3167 (that is, may call metamethods).
3168 Otherwise returns&nbsp;0.
3169 Also returns&nbsp;0 if any of the indices is non valid.
3175 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3176 <span class="apii">[-0, +1, <em>-</em>]</span>
3177 <pre>int lua_load (lua_State *L,
3178 lua_Reader reader,
3179 void *data,
3180 const char *chunkname);</pre>
3183 Loads a Lua chunk.
3184 If there are no errors,
3185 <a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
3186 function on top of the stack.
3187 Otherwise, it pushes an error message.
3188 The return values of <a href="#lua_load"><code>lua_load</code></a> are:
3190 <ul>
3192 <li><b>0:</b> no errors;</li>
3194 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
3195 syntax error during pre-compilation;</li>
3197 <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3198 memory allocation error.</li>
3200 </ul>
3203 This function only loads a chunk;
3204 it does not run it.
3208 <a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
3209 and loads it accordingly (see program <code>luac</code>).
3213 The <a href="#lua_load"><code>lua_load</code></a> function uses a user-supplied <code>reader</code> function
3214 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3215 The <code>data</code> argument is an opaque value passed to the reader function.
3219 The <code>chunkname</code> argument gives a name to the chunk,
3220 which is used for error messages and in debug information (see <a href="#3.8">&sect;3.8</a>).
3226 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3227 <span class="apii">[-0, +0, <em>-</em>]</span>
3228 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3231 Creates a new, independent state.
3232 Returns <code>NULL</code> if cannot create the state
3233 (due to lack of memory).
3234 The argument <code>f</code> is the allocator function;
3235 Lua does all memory allocation for this state through this function.
3236 The second argument, <code>ud</code>, is an opaque pointer that Lua
3237 simply passes to the allocator in every call.
3243 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
3244 <span class="apii">[-0, +1, <em>m</em>]</span>
3245 <pre>void lua_newtable (lua_State *L);</pre>
3248 Creates a new empty table and pushes it onto the stack.
3249 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3255 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
3256 <span class="apii">[-0, +1, <em>m</em>]</span>
3257 <pre>lua_State *lua_newthread (lua_State *L);</pre>
3260 Creates a new thread, pushes it on the stack,
3261 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3262 The new state returned by this function shares with the original state
3263 all global objects (such as tables),
3264 but has an independent execution stack.
3268 There is no explicit function to close or to destroy a thread.
3269 Threads are subject to garbage collection,
3270 like any Lua object.
3276 <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
3277 <span class="apii">[-0, +1, <em>m</em>]</span>
3278 <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3281 This function allocates a new block of memory with the given size,
3282 pushes onto the stack a new full userdata with the block address,
3283 and returns this address.
3287 Userdata represent C&nbsp;values in Lua.
3288 A <em>full userdata</em> represents a block of memory.
3289 It is an object (like a table):
3290 you must create it, it can have its own metatable,
3291 and you can detect when it is being collected.
3292 A full userdata is only equal to itself (under raw equality).
3296 When Lua collects a full userdata with a <code>gc</code> metamethod,
3297 Lua calls the metamethod and marks the userdata as finalized.
3298 When this userdata is collected again then
3299 Lua frees its corresponding memory.
3305 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
3306 <span class="apii">[-1, +(2|0), <em>e</em>]</span>
3307 <pre>int lua_next (lua_State *L, int index);</pre>
3310 Pops a key from the stack,
3311 and pushes a key-value pair from the table at the given index
3312 (the "next" pair after the given key).
3313 If there are no more elements in the table,
3314 then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3318 A typical traversal looks like this:
3320 <pre>
3321 /* table is in the stack at index 't' */
3322 lua_pushnil(L); /* first key */
3323 while (lua_next(L, t) != 0) {
3324 /* uses 'key' (at index -2) and 'value' (at index -1) */
3325 printf("%s - %s\n",
3326 lua_typename(L, lua_type(L, -2)),
3327 lua_typename(L, lua_type(L, -1)));
3328 /* removes 'value'; keeps 'key' for next iteration */
3329 lua_pop(L, 1);
3331 </pre>
3334 While traversing a table,
3335 do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3336 unless you know that the key is actually a string.
3337 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
3338 the value at the given index;
3339 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3345 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3346 <pre>typedef double lua_Number;</pre>
3349 The type of numbers in Lua.
3350 By default, it is double, but that can be changed in <code>luaconf.h</code>.
3354 Through the configuration file you can change
3355 Lua to operate with another type for numbers (e.g., float or long).
3361 <hr><h3><a name="lua_objlen"><code>lua_objlen</code></a></h3><p>
3362 <span class="apii">[-0, +0, <em>-</em>]</span>
3363 <pre>size_t lua_objlen (lua_State *L, int index);</pre>
3366 Returns the "length" of the value at the given acceptable index:
3367 for strings, this is the string length;
3368 for tables, this is the result of the length operator ('<code>#</code>');
3369 for userdata, this is the size of the block of memory allocated
3370 for the userdata;
3371 for other values, it is&nbsp;0.
3377 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
3378 <span class="apii">[-(nargs + 1), +(nresults|1), <em>-</em>]</span>
3379 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);</pre>
3382 Calls a function in protected mode.
3386 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3387 in <a href="#lua_call"><code>lua_call</code></a>.
3388 If there are no errors during the call,
3389 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
3390 However, if there is any error,
3391 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3392 pushes a single value on the stack (the error message),
3393 and returns an error code.
3394 Like <a href="#lua_call"><code>lua_call</code></a>,
3395 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3396 and its arguments from the stack.
3400 If <code>errfunc</code> is 0,
3401 then the error message returned on the stack
3402 is exactly the original error message.
3403 Otherwise, <code>errfunc</code> is the stack index of an
3404 <em>error handler function</em>.
3405 (In the current implementation, this index cannot be a pseudo-index.)
3406 In case of runtime errors,
3407 this function will be called with the error message
3408 and its return value will be the message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3412 Typically, the error handler function is used to add more debug
3413 information to the error message, such as a stack traceback.
3414 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3415 since by then the stack has unwound.
3419 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
3420 or one of the following error codes
3421 (defined in <code>lua.h</code>):
3423 <ul>
3425 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b>
3426 a runtime error.
3427 </li>
3429 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3430 memory allocation error.
3431 For such errors, Lua does not call the error handler function.
3432 </li>
3434 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
3435 error while running the error handler function.
3436 </li>
3438 </ul>
3443 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
3444 <span class="apii">[-n, +0, <em>-</em>]</span>
3445 <pre>void lua_pop (lua_State *L, int n);</pre>
3448 Pops <code>n</code> elements from the stack.
3454 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
3455 <span class="apii">[-0, +1, <em>-</em>]</span>
3456 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
3459 Pushes a boolean value with value <code>b</code> onto the stack.
3465 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
3466 <span class="apii">[-n, +1, <em>m</em>]</span>
3467 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
3470 Pushes a new C&nbsp;closure onto the stack.
3474 When a C&nbsp;function is created,
3475 it is possible to associate some values with it,
3476 thus creating a C&nbsp;closure (see <a href="#3.4">&sect;3.4</a>);
3477 these values are then accessible to the function whenever it is called.
3478 To associate values with a C&nbsp;function,
3479 first these values should be pushed onto the stack
3480 (when there are multiple values, the first value is pushed first).
3481 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
3482 is called to create and push the C&nbsp;function onto the stack,
3483 with the argument <code>n</code> telling how many values should be
3484 associated with the function.
3485 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
3491 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
3492 <span class="apii">[-0, +1, <em>m</em>]</span>
3493 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
3496 Pushes a C&nbsp;function onto the stack.
3497 This function receives a pointer to a C function
3498 and pushes onto the stack a Lua value of type <code>function</code> that,
3499 when called, invokes the corresponding C&nbsp;function.
3503 Any function to be registered in Lua must
3504 follow the correct protocol to receive its parameters
3505 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
3509 <code>lua_pushcfunction</code> is defined as a macro:
3511 <pre>
3512 #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
3513 </pre>
3518 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
3519 <span class="apii">[-0, +1, <em>m</em>]</span>
3520 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
3523 Pushes onto the stack a formatted string
3524 and returns a pointer to this string.
3525 It is similar to the C&nbsp;function <code>sprintf</code>,
3526 but has some important differences:
3528 <ul>
3530 <li>
3531 You do not have to allocate space for the result:
3532 the result is a Lua string and Lua takes care of memory allocation
3533 (and deallocation, through garbage collection).
3534 </li>
3536 <li>
3537 The conversion specifiers are quite restricted.
3538 There are no flags, widths, or precisions.
3539 The conversion specifiers can only be
3540 '<code>%%</code>' (inserts a '<code>%</code>' in the string),
3541 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
3542 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
3543 '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
3544 '<code>%d</code>' (inserts an <code>int</code>), and
3545 '<code>%c</code>' (inserts an <code>int</code> as a character).
3546 </li>
3548 </ul>
3553 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
3554 <span class="apii">[-0, +1, <em>-</em>]</span>
3555 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
3558 Pushes a number with value <code>n</code> onto the stack.
3564 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
3565 <span class="apii">[-0, +1, <em>-</em>]</span>
3566 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
3569 Pushes a light userdata onto the stack.
3573 Userdata represent C&nbsp;values in Lua.
3574 A <em>light userdata</em> represents a pointer.
3575 It is a value (like a number):
3576 you do not create it, it has no individual metatable,
3577 and it is not collected (as it was never created).
3578 A light userdata is equal to "any"
3579 light userdata with the same C&nbsp;address.
3585 <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
3586 <span class="apii">[-0, +1, <em>m</em>]</span>
3587 <pre>void lua_pushliteral (lua_State *L, const char *s);</pre>
3590 This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3591 but can be used only when <code>s</code> is a literal string.
3592 In these cases, it automatically provides the string length.
3598 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
3599 <span class="apii">[-0, +1, <em>m</em>]</span>
3600 <pre>void lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
3603 Pushes the string pointed to by <code>s</code> with size <code>len</code>
3604 onto the stack.
3605 Lua makes (or reuses) an internal copy of the given string,
3606 so the memory at <code>s</code> can be freed or reused immediately after
3607 the function returns.
3608 The string can contain embedded zeros.
3614 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
3615 <span class="apii">[-0, +1, <em>-</em>]</span>
3616 <pre>void lua_pushnil (lua_State *L);</pre>
3619 Pushes a nil value onto the stack.
3625 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
3626 <span class="apii">[-0, +1, <em>-</em>]</span>
3627 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
3630 Pushes a number with value <code>n</code> onto the stack.
3636 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
3637 <span class="apii">[-0, +1, <em>m</em>]</span>
3638 <pre>void lua_pushstring (lua_State *L, const char *s);</pre>
3641 Pushes the zero-terminated string pointed to by <code>s</code>
3642 onto the stack.
3643 Lua makes (or reuses) an internal copy of the given string,
3644 so the memory at <code>s</code> can be freed or reused immediately after
3645 the function returns.
3646 The string cannot contain embedded zeros;
3647 it is assumed to end at the first zero.
3653 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
3654 <span class="apii">[-0, +1, <em>-</em>]</span>
3655 <pre>int lua_pushthread (lua_State *L);</pre>
3658 Pushes the thread represented by <code>L</code> onto the stack.
3659 Returns 1 if this thread is the main thread of its state.
3665 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
3666 <span class="apii">[-0, +1, <em>-</em>]</span>
3667 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
3670 Pushes a copy of the element at the given valid index
3671 onto the stack.
3677 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
3678 <span class="apii">[-0, +1, <em>m</em>]</span>
3679 <pre>const char *lua_pushvfstring (lua_State *L,
3680 const char *fmt,
3681 va_list argp);</pre>
3684 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
3685 instead of a variable number of arguments.
3691 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
3692 <span class="apii">[-0, +0, <em>-</em>]</span>
3693 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
3696 Returns 1 if the two values in acceptable indices <code>index1</code> and
3697 <code>index2</code> are primitively equal
3698 (that is, without calling metamethods).
3699 Otherwise returns&nbsp;0.
3700 Also returns&nbsp;0 if any of the indices are non valid.
3706 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
3707 <span class="apii">[-1, +1, <em>-</em>]</span>
3708 <pre>void lua_rawget (lua_State *L, int index);</pre>
3711 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
3712 (i.e., without metamethods).
3718 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
3719 <span class="apii">[-0, +1, <em>-</em>]</span>
3720 <pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
3723 Pushes onto the stack the value <code>t[n]</code>,
3724 where <code>t</code> is the value at the given valid index.
3725 The access is raw;
3726 that is, it does not invoke metamethods.
3732 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
3733 <span class="apii">[-2, +0, <em>m</em>]</span>
3734 <pre>void lua_rawset (lua_State *L, int index);</pre>
3737 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
3738 (i.e., without metamethods).
3744 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
3745 <span class="apii">[-1, +0, <em>m</em>]</span>
3746 <pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
3749 Does the equivalent of <code>t[n] = v</code>,
3750 where <code>t</code> is the value at the given valid index
3751 and <code>v</code> is the value at the top of the stack.
3755 This function pops the value from the stack.
3756 The assignment is raw;
3757 that is, it does not invoke metamethods.
3763 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
3764 <pre>typedef const char * (*lua_Reader) (lua_State *L,
3765 void *data,
3766 size_t *size);</pre>
3769 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
3770 Every time it needs another piece of the chunk,
3771 <a href="#lua_load"><code>lua_load</code></a> calls the reader,
3772 passing along its <code>data</code> parameter.
3773 The reader must return a pointer to a block of memory
3774 with a new piece of the chunk
3775 and set <code>size</code> to the block size.
3776 The block must exist until the reader function is called again.
3777 To signal the end of the chunk, the reader must return <code>NULL</code>.
3778 The reader function may return pieces of any size greater than zero.
3784 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
3785 <span class="apii">[-0, +0, <em>e</em>]</span>
3786 <pre>void lua_register (lua_State *L,
3787 const char *name,
3788 lua_CFunction f);</pre>
3791 Sets the C function <code>f</code> as the new value of global <code>name</code>.
3792 It is defined as a macro:
3794 <pre>
3795 #define lua_register(L,n,f) \
3796 (lua_pushcfunction(L, f), lua_setglobal(L, n))
3797 </pre>
3802 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
3803 <span class="apii">[-1, +0, <em>-</em>]</span>
3804 <pre>void lua_remove (lua_State *L, int index);</pre>
3807 Removes the element at the given valid index,
3808 shifting down the elements above this index to fill the gap.
3809 Cannot be called with a pseudo-index,
3810 because a pseudo-index is not an actual stack position.
3816 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
3817 <span class="apii">[-1, +0, <em>-</em>]</span>
3818 <pre>void lua_replace (lua_State *L, int index);</pre>
3821 Moves the top element into the given position (and pops it),
3822 without shifting any element
3823 (therefore replacing the value at the given position).
3829 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
3830 <span class="apii">[-?, +?, <em>-</em>]</span>
3831 <pre>int lua_resume (lua_State *L, int narg);</pre>
3834 Starts and resumes a coroutine in a given thread.
3838 To start a coroutine, you first create a new thread
3839 (see <a href="#lua_newthread"><code>lua_newthread</code></a>);
3840 then you push onto its stack the main function plus any arguments;
3841 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
3842 with <code>narg</code> being the number of arguments.
3843 This call returns when the coroutine suspends or finishes its execution.
3844 When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
3845 or all values returned by the body function.
3846 <a href="#lua_resume"><code>lua_resume</code></a> returns
3847 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
3848 0 if the coroutine finishes its execution
3849 without errors,
3850 or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
3851 In case of errors,
3852 the stack is not unwound,
3853 so you can use the debug API over it.
3854 The error message is on the top of the stack.
3855 To restart a coroutine, you put on its stack only the values to
3856 be passed as results from <code>yield</code>,
3857 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
3863 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
3864 <span class="apii">[-0, +0, <em>-</em>]</span>
3865 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
3868 Changes the allocator function of a given state to <code>f</code>
3869 with user data <code>ud</code>.
3875 <hr><h3><a name="lua_setfenv"><code>lua_setfenv</code></a></h3><p>
3876 <span class="apii">[-1, +0, <em>-</em>]</span>
3877 <pre>int lua_setfenv (lua_State *L, int index);</pre>
3880 Pops a table from the stack and sets it as
3881 the new environment for the value at the given index.
3882 If the value at the given index is
3883 neither a function nor a thread nor a userdata,
3884 <a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0.
3885 Otherwise it returns 1.
3891 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
3892 <span class="apii">[-1, +0, <em>e</em>]</span>
3893 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
3896 Does the equivalent to <code>t[k] = v</code>,
3897 where <code>t</code> is the value at the given valid index
3898 and <code>v</code> is the value at the top of the stack.
3902 This function pops the value from the stack.
3903 As in Lua, this function may trigger a metamethod
3904 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3910 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
3911 <span class="apii">[-1, +0, <em>e</em>]</span>
3912 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
3915 Pops a value from the stack and
3916 sets it as the new value of global <code>name</code>.
3917 It is defined as a macro:
3919 <pre>
3920 #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
3921 </pre>
3926 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
3927 <span class="apii">[-1, +0, <em>-</em>]</span>
3928 <pre>int lua_setmetatable (lua_State *L, int index);</pre>
3931 Pops a table from the stack and
3932 sets it as the new metatable for the value at the given
3933 acceptable index.
3939 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
3940 <span class="apii">[-2, +0, <em>e</em>]</span>
3941 <pre>void lua_settable (lua_State *L, int index);</pre>
3944 Does the equivalent to <code>t[k] = v</code>,
3945 where <code>t</code> is the value at the given valid index,
3946 <code>v</code> is the value at the top of the stack,
3947 and <code>k</code> is the value just below the top.
3951 This function pops both the key and the value from the stack.
3952 As in Lua, this function may trigger a metamethod
3953 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3959 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
3960 <span class="apii">[-?, +?, <em>-</em>]</span>
3961 <pre>void lua_settop (lua_State *L, int index);</pre>
3964 Accepts any acceptable index, or&nbsp;0,
3965 and sets the stack top to this index.
3966 If the new top is larger than the old one,
3967 then the new elements are filled with <b>nil</b>.
3968 If <code>index</code> is&nbsp;0, then all stack elements are removed.
3974 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
3975 <pre>typedef struct lua_State lua_State;</pre>
3978 Opaque structure that keeps the whole state of a Lua interpreter.
3979 The Lua library is fully reentrant:
3980 it has no global variables.
3981 All information about a state is kept in this structure.
3985 A pointer to this state must be passed as the first argument to
3986 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
3987 which creates a Lua state from scratch.
3993 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
3994 <span class="apii">[-0, +0, <em>-</em>]</span>
3995 <pre>int lua_status (lua_State *L);</pre>
3998 Returns the status of the thread <code>L</code>.
4002 The status can be 0 for a normal thread,
4003 an error code if the thread finished its execution with an error,
4004 or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4010 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4011 <span class="apii">[-0, +0, <em>-</em>]</span>
4012 <pre>int lua_toboolean (lua_State *L, int index);</pre>
4015 Converts the Lua value at the given acceptable index to a C&nbsp;boolean
4016 value (0&nbsp;or&nbsp;1).
4017 Like all tests in Lua,
4018 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
4019 different from <b>false</b> and <b>nil</b>;
4020 otherwise it returns 0.
4021 It also returns 0 when called with a non-valid index.
4022 (If you want to accept only actual boolean values,
4023 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4029 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4030 <span class="apii">[-0, +0, <em>-</em>]</span>
4031 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4034 Converts a value at the given acceptable index to a C&nbsp;function.
4035 That value must be a C&nbsp;function;
4036 otherwise, returns <code>NULL</code>.
4042 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4043 <span class="apii">[-0, +0, <em>-</em>]</span>
4044 <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4047 Converts the Lua value at the given acceptable index
4048 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4049 The Lua value must be a number or a string convertible to a number
4050 (see <a href="#2.2.1">&sect;2.2.1</a>);
4051 otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns&nbsp;0.
4055 If the number is not an integer,
4056 it is truncated in some non-specified way.
4062 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
4063 <span class="apii">[-0, +0, <em>m</em>]</span>
4064 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
4067 Converts the Lua value at the given acceptable index to a C&nbsp;string.
4068 If <code>len</code> is not <code>NULL</code>,
4069 it also sets <code>*len</code> with the string length.
4070 The Lua value must be a string or a number;
4071 otherwise, the function returns <code>NULL</code>.
4072 If the value is a number,
4073 then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
4074 <em>changes the actual value in the stack to a string</em>.
4075 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
4076 when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys during a table traversal.)
4080 <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
4081 to a string inside the Lua state.
4082 This string always has a zero ('<code>\0</code>')
4083 after its last character (as in&nbsp;C),
4084 but may contain other zeros in its body.
4085 Because Lua has garbage collection,
4086 there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
4087 will be valid after the corresponding value is removed from the stack.
4093 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
4094 <span class="apii">[-0, +0, <em>-</em>]</span>
4095 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
4098 Converts the Lua value at the given acceptable index
4099 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
4100 The Lua value must be a number or a string convertible to a number
4101 (see <a href="#2.2.1">&sect;2.2.1</a>);
4102 otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns&nbsp;0.
4108 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
4109 <span class="apii">[-0, +0, <em>-</em>]</span>
4110 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
4113 Converts the value at the given acceptable index to a generic
4114 C&nbsp;pointer (<code>void*</code>).
4115 The value may be a userdata, a table, a thread, or a function;
4116 otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
4117 Different objects will give different pointers.
4118 There is no way to convert the pointer back to its original value.
4122 Typically this function is used only for debug information.
4128 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
4129 <span class="apii">[-0, +0, <em>m</em>]</span>
4130 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
4133 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4139 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
4140 <span class="apii">[-0, +0, <em>-</em>]</span>
4141 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4144 Converts the value at the given acceptable index to a Lua thread
4145 (represented as <code>lua_State*</code>).
4146 This value must be a thread;
4147 otherwise, the function returns <code>NULL</code>.
4153 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
4154 <span class="apii">[-0, +0, <em>-</em>]</span>
4155 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
4158 If the value at the given acceptable index is a full userdata,
4159 returns its block address.
4160 If the value is a light userdata,
4161 returns its pointer.
4162 Otherwise, returns <code>NULL</code>.
4168 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
4169 <span class="apii">[-0, +0, <em>-</em>]</span>
4170 <pre>int lua_type (lua_State *L, int index);</pre>
4173 Returns the type of the value in the given acceptable index,
4174 or <code>LUA_TNONE</code> for a non-valid index
4175 (that is, an index to an "empty" stack position).
4176 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4177 defined in <code>lua.h</code>:
4178 <code>LUA_TNIL</code>,
4179 <code>LUA_TNUMBER</code>,
4180 <code>LUA_TBOOLEAN</code>,
4181 <code>LUA_TSTRING</code>,
4182 <code>LUA_TTABLE</code>,
4183 <code>LUA_TFUNCTION</code>,
4184 <code>LUA_TUSERDATA</code>,
4185 <code>LUA_TTHREAD</code>,
4187 <code>LUA_TLIGHTUSERDATA</code>.
4193 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
4194 <span class="apii">[-0, +0, <em>-</em>]</span>
4195 <pre>const char *lua_typename (lua_State *L, int tp);</pre>
4198 Returns the name of the type encoded by the value <code>tp</code>,
4199 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4205 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4206 <pre>typedef int (*lua_Writer) (lua_State *L,
4207 const void* p,
4208 size_t sz,
4209 void* ud);</pre>
4212 The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4213 Every time it produces another piece of chunk,
4214 <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4215 passing along the buffer to be written (<code>p</code>),
4216 its size (<code>sz</code>),
4217 and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4221 The writer returns an error code:
4222 0&nbsp;means no errors;
4223 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4224 calling the writer again.
4230 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
4231 <span class="apii">[-?, +?, <em>-</em>]</span>
4232 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4235 Exchange values between different threads of the <em>same</em> global state.
4239 This function pops <code>n</code> values from the stack <code>from</code>,
4240 and pushes them onto the stack <code>to</code>.
4246 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
4247 <span class="apii">[-?, +?, <em>-</em>]</span>
4248 <pre>int lua_yield (lua_State *L, int nresults);</pre>
4251 Yields a coroutine.
4255 This function should only be called as the
4256 return expression of a C&nbsp;function, as follows:
4258 <pre>
4259 return lua_yield (L, nresults);
4260 </pre><p>
4261 When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
4262 the running coroutine suspends its execution,
4263 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
4264 The parameter <code>nresults</code> is the number of values from the stack
4265 that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
4273 <h2>3.8 - <a name="3.8">The Debug Interface</a></h2>
4276 Lua has no built-in debugging facilities.
4277 Instead, it offers a special interface
4278 by means of functions and <em>hooks</em>.
4279 This interface allows the construction of different
4280 kinds of debuggers, profilers, and other tools
4281 that need "inside information" from the interpreter.
4285 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
4286 <pre>typedef struct lua_Debug {
4287 int event;
4288 const char *name; /* (n) */
4289 const char *namewhat; /* (n) */
4290 const char *what; /* (S) */
4291 const char *source; /* (S) */
4292 int currentline; /* (l) */
4293 int nups; /* (u) number of upvalues */
4294 int linedefined; /* (S) */
4295 int lastlinedefined; /* (S) */
4296 char short_src[LUA_IDSIZE]; /* (S) */
4297 /* private part */
4298 <em>other fields</em>
4299 } lua_Debug;</pre>
4302 A structure used to carry different pieces of
4303 information about an active function.
4304 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
4305 of this structure, for later use.
4306 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
4307 call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4311 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
4313 <ul>
4315 <li><b><code>source</code>:</b>
4316 If the function was defined in a string,
4317 then <code>source</code> is that string.
4318 If the function was defined in a file,
4319 then <code>source</code> starts with a '<code>@</code>' followed by the file name.
4320 </li>
4322 <li><b><code>short_src</code>:</b>
4323 a "printable" version of <code>source</code>, to be used in error messages.
4324 </li>
4326 <li><b><code>linedefined</code>:</b>
4327 the line number where the definition of the function starts.
4328 </li>
4330 <li><b><code>lastlinedefined</code>:</b>
4331 the line number where the definition of the function ends.
4332 </li>
4334 <li><b><code>what</code>:</b>
4335 the string <code>"Lua"</code> if the function is a Lua function,
4336 <code>"C"</code> if it is a C&nbsp;function,
4337 <code>"main"</code> if it is the main part of a chunk,
4338 and <code>"tail"</code> if it was a function that did a tail call.
4339 In the latter case,
4340 Lua has no other information about the function.
4341 </li>
4343 <li><b><code>currentline</code>:</b>
4344 the current line where the given function is executing.
4345 When no line information is available,
4346 <code>currentline</code> is set to -1.
4347 </li>
4349 <li><b><code>name</code>:</b>
4350 a reasonable name for the given function.
4351 Because functions in Lua are first-class values,
4352 they do not have a fixed name:
4353 some functions may be the value of multiple global variables,
4354 while others may be stored only in a table field.
4355 The <code>lua_getinfo</code> function checks how the function was
4356 called to find a suitable name.
4357 If it cannot find a name,
4358 then <code>name</code> is set to <code>NULL</code>.
4359 </li>
4361 <li><b><code>namewhat</code>:</b>
4362 explains the <code>name</code> field.
4363 The value of <code>namewhat</code> can be
4364 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
4365 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
4366 according to how the function was called.
4367 (Lua uses the empty string when no other option seems to apply.)
4368 </li>
4370 <li><b><code>nups</code>:</b>
4371 the number of upvalues of the function.
4372 </li>
4374 </ul>
4379 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
4380 <span class="apii">[-0, +0, <em>-</em>]</span>
4381 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
4384 Returns the current hook function.
4390 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
4391 <span class="apii">[-0, +0, <em>-</em>]</span>
4392 <pre>int lua_gethookcount (lua_State *L);</pre>
4395 Returns the current hook count.
4401 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
4402 <span class="apii">[-0, +0, <em>-</em>]</span>
4403 <pre>int lua_gethookmask (lua_State *L);</pre>
4406 Returns the current hook mask.
4412 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
4413 <span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
4414 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
4417 Returns information about a specific function or function invocation.
4421 To get information about a function invocation,
4422 the parameter <code>ar</code> must be a valid activation record that was
4423 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4424 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4428 To get information about a function you push it onto the stack
4429 and start the <code>what</code> string with the character '<code>&gt;</code>'.
4430 (In that case,
4431 <code>lua_getinfo</code> pops the function in the top of the stack.)
4432 For instance, to know in which line a function <code>f</code> was defined,
4433 you can write the following code:
4435 <pre>
4436 lua_Debug ar;
4437 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
4438 lua_getinfo(L, "&gt;S", &amp;ar);
4439 printf("%d\n", ar.linedefined);
4440 </pre>
4443 Each character in the string <code>what</code>
4444 selects some fields of the structure <code>ar</code> to be filled or
4445 a value to be pushed on the stack:
4447 <ul>
4449 <li><b>'<code>n</code>':</b> fills in the field <code>name</code> and <code>namewhat</code>;
4450 </li>
4452 <li><b>'<code>S</code>':</b>
4453 fills in the fields <code>source</code>, <code>short_src</code>,
4454 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
4455 </li>
4457 <li><b>'<code>l</code>':</b> fills in the field <code>currentline</code>;
4458 </li>
4460 <li><b>'<code>u</code>':</b> fills in the field <code>nups</code>;
4461 </li>
4463 <li><b>'<code>f</code>':</b>
4464 pushes onto the stack the function that is
4465 running at the given level;
4466 </li>
4468 <li><b>'<code>L</code>':</b>
4469 pushes onto the stack a table whose indices are the
4470 numbers of the lines that are valid on the function.
4471 (A <em>valid line</em> is a line with some associated code,
4472 that is, a line where you can put a break point.
4473 Non-valid lines include empty lines and comments.)
4474 </li>
4476 </ul>
4479 This function returns 0 on error
4480 (for instance, an invalid option in <code>what</code>).
4486 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
4487 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
4488 <pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4491 Gets information about a local variable of a given activation record.
4492 The parameter <code>ar</code> must be a valid activation record that was
4493 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4494 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4495 The index <code>n</code> selects which local variable to inspect
4496 (1 is the first parameter or active local variable, and so on,
4497 until the last active local variable).
4498 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
4499 and returns its name.
4503 Variable names starting with '<code>(</code>' (open parentheses)
4504 represent internal variables
4505 (loop control variables, temporaries, and C&nbsp;function locals).
4509 Returns <code>NULL</code> (and pushes nothing)
4510 when the index is greater than
4511 the number of active local variables.
4517 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
4518 <span class="apii">[-0, +0, <em>-</em>]</span>
4519 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
4522 Get information about the interpreter runtime stack.
4526 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
4527 an identification of the <em>activation record</em>
4528 of the function executing at a given level.
4529 Level&nbsp;0 is the current running function,
4530 whereas level <em>n+1</em> is the function that has called level <em>n</em>.
4531 When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
4532 when called with a level greater than the stack depth,
4533 it returns 0.
4539 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
4540 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
4541 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
4544 Gets information about a closure's upvalue.
4545 (For Lua functions,
4546 upvalues are the external local variables that the function uses,
4547 and that are consequently included in its closure.)
4548 <a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
4549 pushes the upvalue's value onto the stack,
4550 and returns its name.
4551 <code>funcindex</code> points to the closure in the stack.
4552 (Upvalues have no particular order,
4553 as they are active through the whole function.
4554 So, they are numbered in an arbitrary order.)
4558 Returns <code>NULL</code> (and pushes nothing)
4559 when the index is greater than the number of upvalues.
4560 For C&nbsp;functions, this function uses the empty string <code>""</code>
4561 as a name for all upvalues.
4567 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
4568 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
4571 Type for debugging hook functions.
4575 Whenever a hook is called, its <code>ar</code> argument has its field
4576 <code>event</code> set to the specific event that triggered the hook.
4577 Lua identifies these events with the following constants:
4578 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
4579 <a name="pdf-LUA_HOOKTAILRET"><code>LUA_HOOKTAILRET</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
4580 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
4581 Moreover, for line events, the field <code>currentline</code> is also set.
4582 To get the value of any other field in <code>ar</code>,
4583 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4584 For return events, <code>event</code> may be <code>LUA_HOOKRET</code>,
4585 the normal value, or <code>LUA_HOOKTAILRET</code>.
4586 In the latter case, Lua is simulating a return from
4587 a function that did a tail call;
4588 in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4592 While Lua is running a hook, it disables other calls to hooks.
4593 Therefore, if a hook calls back Lua to execute a function or a chunk,
4594 this execution occurs without any calls to hooks.
4600 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
4601 <span class="apii">[-0, +0, <em>-</em>]</span>
4602 <pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
4605 Sets the debugging hook function.
4609 Argument <code>f</code> is the hook function.
4610 <code>mask</code> specifies on which events the hook will be called:
4611 it is formed by a bitwise or of the constants
4612 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
4613 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
4614 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
4615 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
4616 The <code>count</code> argument is only meaningful when the mask
4617 includes <code>LUA_MASKCOUNT</code>.
4618 For each event, the hook is called as explained below:
4620 <ul>
4622 <li><b>The call hook:</b> is called when the interpreter calls a function.
4623 The hook is called just after Lua enters the new function,
4624 before the function gets its arguments.
4625 </li>
4627 <li><b>The return hook:</b> is called when the interpreter returns from a function.
4628 The hook is called just before Lua leaves the function.
4629 You have no access to the values to be returned by the function.
4630 </li>
4632 <li><b>The line hook:</b> is called when the interpreter is about to
4633 start the execution of a new line of code,
4634 or when it jumps back in the code (even to the same line).
4635 (This event only happens while Lua is executing a Lua function.)
4636 </li>
4638 <li><b>The count hook:</b> is called after the interpreter executes every
4639 <code>count</code> instructions.
4640 (This event only happens while Lua is executing a Lua function.)
4641 </li>
4643 </ul>
4646 A hook is disabled by setting <code>mask</code> to zero.
4652 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
4653 <span class="apii">[-(0|1), +0, <em>-</em>]</span>
4654 <pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4657 Sets the value of a local variable of a given activation record.
4658 Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
4659 (see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
4660 <a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
4661 to the variable and returns its name.
4662 It also pops the value from the stack.
4666 Returns <code>NULL</code> (and pops nothing)
4667 when the index is greater than
4668 the number of active local variables.
4674 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
4675 <span class="apii">[-(0|1), +0, <em>-</em>]</span>
4676 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
4679 Sets the value of a closure's upvalue.
4680 It assigns the value at the top of the stack
4681 to the upvalue and returns its name.
4682 It also pops the value from the stack.
4683 Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
4684 (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
4688 Returns <code>NULL</code> (and pops nothing)
4689 when the index is greater than the number of upvalues.
4697 <h1>4 - <a name="4">The Auxiliary Library</a></h1>
4701 The <em>auxiliary library</em> provides several convenient functions
4702 to interface C with Lua.
4703 While the basic API provides the primitive functions for all
4704 interactions between C and Lua,
4705 the auxiliary library provides higher-level functions for some
4706 common tasks.
4710 All functions from the auxiliary library
4711 are defined in header file <code>lauxlib.h</code> and
4712 have a prefix <code>luaL_</code>.
4716 All functions in the auxiliary library are built on
4717 top of the basic API,
4718 and so they provide nothing that cannot be done with this API.
4722 Several functions in the auxiliary library are used to
4723 check C&nbsp;function arguments.
4724 Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
4725 All of these functions throw an error if the check is not satisfied.
4726 Because the error message is formatted for arguments
4727 (e.g., "<code>bad argument #1</code>"),
4728 you should not use these functions for other stack values.
4732 <h2>4.1 - <a name="4.1">Functions and Types</a></h2>
4735 Here we list all functions and types from the auxiliary library
4736 in alphabetical order.
4740 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
4741 <span class="apii">[-0, +0, <em>m</em>]</span>
4742 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
4745 Adds the character <code>c</code> to the buffer <code>B</code>
4746 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4752 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
4753 <span class="apii">[-0, +0, <em>m</em>]</span>
4754 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
4757 Adds the string pointed to by <code>s</code> with length <code>l</code> to
4758 the buffer <code>B</code>
4759 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4760 The string may contain embedded zeros.
4766 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
4767 <span class="apii">[-0, +0, <em>m</em>]</span>
4768 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
4771 Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
4772 a string of length <code>n</code> previously copied to the
4773 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
4779 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
4780 <span class="apii">[-0, +0, <em>m</em>]</span>
4781 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
4784 Adds the zero-terminated string pointed to by <code>s</code>
4785 to the buffer <code>B</code>
4786 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4787 The string may not contain embedded zeros.
4793 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
4794 <span class="apii">[-1, +0, <em>m</em>]</span>
4795 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
4798 Adds the value at the top of the stack
4799 to the buffer <code>B</code>
4800 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4801 Pops the value.
4805 This is the only function on string buffers that can (and must)
4806 be called with an extra element on the stack,
4807 which is the value to be added to the buffer.
4813 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
4814 <span class="apii">[-0, +0, <em>v</em>]</span>
4815 <pre>void luaL_argcheck (lua_State *L,
4816 int cond,
4817 int narg,
4818 const char *extramsg);</pre>
4821 Checks whether <code>cond</code> is true.
4822 If not, raises an error with the following message,
4823 where <code>func</code> is retrieved from the call stack:
4825 <pre>
4826 bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4827 </pre>
4832 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
4833 <span class="apii">[-0, +0, <em>v</em>]</span>
4834 <pre>int luaL_argerror (lua_State *L, int narg, const char *extramsg);</pre>
4837 Raises an error with the following message,
4838 where <code>func</code> is retrieved from the call stack:
4840 <pre>
4841 bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4842 </pre>
4845 This function never returns,
4846 but it is an idiom to use it in C&nbsp;functions
4847 as <code>return luaL_argerror(<em>args</em>)</code>.
4853 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
4854 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
4857 Type for a <em>string buffer</em>.
4861 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
4862 Its pattern of use is as follows:
4864 <ul>
4866 <li>First you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
4868 <li>Then you initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
4870 <li>
4871 Then you add string pieces to the buffer calling any of
4872 the <code>luaL_add*</code> functions.
4873 </li>
4875 <li>
4876 You finish by calling <code>luaL_pushresult(&amp;b)</code>.
4877 This call leaves the final string on the top of the stack.
4878 </li>
4880 </ul>
4883 During its normal operation,
4884 a string buffer uses a variable number of stack slots.
4885 So, while using a buffer, you cannot assume that you know where
4886 the top of the stack is.
4887 You can use the stack between successive calls to buffer operations
4888 as long as that use is balanced;
4889 that is,
4890 when you call a buffer operation,
4891 the stack is at the same level
4892 it was immediately after the previous buffer operation.
4893 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
4894 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
4895 level when the buffer was initialized,
4896 plus the final string on its top.
4902 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
4903 <span class="apii">[-0, +0, <em>-</em>]</span>
4904 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
4907 Initializes a buffer <code>B</code>.
4908 This function does not allocate any space;
4909 the buffer must be declared as a variable
4910 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4916 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
4917 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
4918 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
4921 Calls a metamethod.
4925 If the object at index <code>obj</code> has a metatable and this
4926 metatable has a field <code>e</code>,
4927 this function calls this field and passes the object as its only argument.
4928 In this case this function returns 1 and pushes onto the
4929 stack the value returned by the call.
4930 If there is no metatable or no metamethod,
4931 this function returns 0 (without pushing any value on the stack).
4937 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
4938 <span class="apii">[-0, +0, <em>v</em>]</span>
4939 <pre>void luaL_checkany (lua_State *L, int narg);</pre>
4942 Checks whether the function has an argument
4943 of any type (including <b>nil</b>) at position <code>narg</code>.
4949 <hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
4950 <span class="apii">[-0, +0, <em>v</em>]</span>
4951 <pre>int luaL_checkint (lua_State *L, int narg);</pre>
4954 Checks whether the function argument <code>narg</code> is a number
4955 and returns this number cast to an <code>int</code>.
4961 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
4962 <span class="apii">[-0, +0, <em>v</em>]</span>
4963 <pre>lua_Integer luaL_checkinteger (lua_State *L, int narg);</pre>
4966 Checks whether the function argument <code>narg</code> is a number
4967 and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
4973 <hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
4974 <span class="apii">[-0, +0, <em>v</em>]</span>
4975 <pre>long luaL_checklong (lua_State *L, int narg);</pre>
4978 Checks whether the function argument <code>narg</code> is a number
4979 and returns this number cast to a <code>long</code>.
4985 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
4986 <span class="apii">[-0, +0, <em>v</em>]</span>
4987 <pre>const char *luaL_checklstring (lua_State *L, int narg, size_t *l);</pre>
4990 Checks whether the function argument <code>narg</code> is a string
4991 and returns this string;
4992 if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
4993 with the string's length.
4997 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
4998 so all conversions and caveats of that function apply here.
5004 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
5005 <span class="apii">[-0, +0, <em>v</em>]</span>
5006 <pre>lua_Number luaL_checknumber (lua_State *L, int narg);</pre>
5009 Checks whether the function argument <code>narg</code> is a number
5010 and returns this number.
5016 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
5017 <span class="apii">[-0, +0, <em>v</em>]</span>
5018 <pre>int luaL_checkoption (lua_State *L,
5019 int narg,
5020 const char *def,
5021 const char *const lst[]);</pre>
5024 Checks whether the function argument <code>narg</code> is a string and
5025 searches for this string in the array <code>lst</code>
5026 (which must be NULL-terminated).
5027 Returns the index in the array where the string was found.
5028 Raises an error if the argument is not a string or
5029 if the string cannot be found.
5033 If <code>def</code> is not <code>NULL</code>,
5034 the function uses <code>def</code> as a default value when
5035 there is no argument <code>narg</code> or if this argument is <b>nil</b>.
5039 This is a useful function for mapping strings to C&nbsp;enums.
5040 (The usual convention in Lua libraries is
5041 to use strings instead of numbers to select options.)
5047 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
5048 <span class="apii">[-0, +0, <em>v</em>]</span>
5049 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
5052 Grows the stack size to <code>top + sz</code> elements,
5053 raising an error if the stack cannot grow to that size.
5054 <code>msg</code> is an additional text to go into the error message.
5060 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
5061 <span class="apii">[-0, +0, <em>v</em>]</span>
5062 <pre>const char *luaL_checkstring (lua_State *L, int narg);</pre>
5065 Checks whether the function argument <code>narg</code> is a string
5066 and returns this string.
5070 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5071 so all conversions and caveats of that function apply here.
5077 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
5078 <span class="apii">[-0, +0, <em>v</em>]</span>
5079 <pre>void luaL_checktype (lua_State *L, int narg, int t);</pre>
5082 Checks whether the function argument <code>narg</code> has type <code>t</code>.
5083 See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
5089 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
5090 <span class="apii">[-0, +0, <em>v</em>]</span>
5091 <pre>void *luaL_checkudata (lua_State *L, int narg, const char *tname);</pre>
5094 Checks whether the function argument <code>narg</code> is a userdata
5095 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5101 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
5102 <span class="apii">[-0, +?, <em>m</em>]</span>
5103 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
5106 Loads and runs the given file.
5107 It is defined as the following macro:
5109 <pre>
5110 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
5111 </pre><p>
5112 It returns 0 if there are no errors
5113 or 1 in case of errors.
5119 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
5120 <span class="apii">[-0, +?, <em>m</em>]</span>
5121 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
5124 Loads and runs the given string.
5125 It is defined as the following macro:
5127 <pre>
5128 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
5129 </pre><p>
5130 It returns 0 if there are no errors
5131 or 1 in case of errors.
5137 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
5138 <span class="apii">[-0, +0, <em>v</em>]</span>
5139 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
5142 Raises an error.
5143 The error message format is given by <code>fmt</code>
5144 plus any extra arguments,
5145 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
5146 It also adds at the beginning of the message the file name and
5147 the line number where the error occurred,
5148 if this information is available.
5152 This function never returns,
5153 but it is an idiom to use it in C&nbsp;functions
5154 as <code>return luaL_error(<em>args</em>)</code>.
5160 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
5161 <span class="apii">[-0, +(0|1), <em>m</em>]</span>
5162 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
5165 Pushes onto the stack the field <code>e</code> from the metatable
5166 of the object at index <code>obj</code>.
5167 If the object does not have a metatable,
5168 or if the metatable does not have this field,
5169 returns 0 and pushes nothing.
5175 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
5176 <span class="apii">[-0, +1, <em>-</em>]</span>
5177 <pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
5180 Pushes onto the stack the metatable associated with name <code>tname</code>
5181 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5187 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
5188 <span class="apii">[-0, +1, <em>m</em>]</span>
5189 <pre>const char *luaL_gsub (lua_State *L,
5190 const char *s,
5191 const char *p,
5192 const char *r);</pre>
5195 Creates a copy of string <code>s</code> by replacing
5196 any occurrence of the string <code>p</code>
5197 with the string <code>r</code>.
5198 Pushes the resulting string on the stack and returns it.
5204 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
5205 <span class="apii">[-0, +1, <em>m</em>]</span>
5206 <pre>int luaL_loadbuffer (lua_State *L,
5207 const char *buff,
5208 size_t sz,
5209 const char *name);</pre>
5212 Loads a buffer as a Lua chunk.
5213 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
5214 buffer pointed to by <code>buff</code> with size <code>sz</code>.
5218 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5219 <code>name</code> is the chunk name,
5220 used for debug information and error messages.
5226 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
5227 <span class="apii">[-0, +1, <em>m</em>]</span>
5228 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
5231 Loads a file as a Lua chunk.
5232 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
5233 named <code>filename</code>.
5234 If <code>filename</code> is <code>NULL</code>,
5235 then it loads from the standard input.
5236 The first line in the file is ignored if it starts with a <code>#</code>.
5240 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
5241 but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
5242 if it cannot open/read the file.
5246 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5247 it does not run it.
5253 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
5254 <span class="apii">[-0, +1, <em>m</em>]</span>
5255 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
5258 Loads a string as a Lua chunk.
5259 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
5260 the zero-terminated string <code>s</code>.
5264 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5268 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5269 it does not run it.
5275 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
5276 <span class="apii">[-0, +1, <em>m</em>]</span>
5277 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
5280 If the registry already has the key <code>tname</code>,
5281 returns 0.
5282 Otherwise,
5283 creates a new table to be used as a metatable for userdata,
5284 adds it to the registry with key <code>tname</code>,
5285 and returns 1.
5289 In both cases pushes onto the stack the final value associated
5290 with <code>tname</code> in the registry.
5296 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
5297 <span class="apii">[-0, +0, <em>-</em>]</span>
5298 <pre>lua_State *luaL_newstate (void);</pre>
5301 Creates a new Lua state.
5302 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
5303 allocator based on the standard&nbsp;C <code>realloc</code> function
5304 and then sets a panic function (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) that prints
5305 an error message to the standard error output in case of fatal
5306 errors.
5310 Returns the new state,
5311 or <code>NULL</code> if there is a memory allocation error.
5317 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
5318 <span class="apii">[-0, +0, <em>m</em>]</span>
5319 <pre>void luaL_openlibs (lua_State *L);</pre>
5322 Opens all standard Lua libraries into the given state.
5328 <hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
5329 <span class="apii">[-0, +0, <em>v</em>]</span>
5330 <pre>int luaL_optint (lua_State *L, int narg, int d);</pre>
5333 If the function argument <code>narg</code> is a number,
5334 returns this number cast to an <code>int</code>.
5335 If this argument is absent or is <b>nil</b>,
5336 returns <code>d</code>.
5337 Otherwise, raises an error.
5343 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
5344 <span class="apii">[-0, +0, <em>v</em>]</span>
5345 <pre>lua_Integer luaL_optinteger (lua_State *L,
5346 int narg,
5347 lua_Integer d);</pre>
5350 If the function argument <code>narg</code> is a number,
5351 returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
5352 If this argument is absent or is <b>nil</b>,
5353 returns <code>d</code>.
5354 Otherwise, raises an error.
5360 <hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3><p>
5361 <span class="apii">[-0, +0, <em>v</em>]</span>
5362 <pre>long luaL_optlong (lua_State *L, int narg, long d);</pre>
5365 If the function argument <code>narg</code> is a number,
5366 returns this number cast to a <code>long</code>.
5367 If this argument is absent or is <b>nil</b>,
5368 returns <code>d</code>.
5369 Otherwise, raises an error.
5375 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
5376 <span class="apii">[-0, +0, <em>v</em>]</span>
5377 <pre>const char *luaL_optlstring (lua_State *L,
5378 int narg,
5379 const char *d,
5380 size_t *l);</pre>
5383 If the function argument <code>narg</code> is a string,
5384 returns this string.
5385 If this argument is absent or is <b>nil</b>,
5386 returns <code>d</code>.
5387 Otherwise, raises an error.
5391 If <code>l</code> is not <code>NULL</code>,
5392 fills the position <code>*l</code> with the results's length.
5398 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
5399 <span class="apii">[-0, +0, <em>v</em>]</span>
5400 <pre>lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);</pre>
5403 If the function argument <code>narg</code> is a number,
5404 returns this number.
5405 If this argument is absent or is <b>nil</b>,
5406 returns <code>d</code>.
5407 Otherwise, raises an error.
5413 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
5414 <span class="apii">[-0, +0, <em>v</em>]</span>
5415 <pre>const char *luaL_optstring (lua_State *L,
5416 int narg,
5417 const char *d);</pre>
5420 If the function argument <code>narg</code> is a string,
5421 returns this string.
5422 If this argument is absent or is <b>nil</b>,
5423 returns <code>d</code>.
5424 Otherwise, raises an error.
5430 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
5431 <span class="apii">[-0, +0, <em>-</em>]</span>
5432 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
5435 Returns an address to a space of size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>
5436 where you can copy a string to be added to buffer <code>B</code>
5437 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5438 After copying the string into this space you must call
5439 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
5440 it to the buffer.
5446 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
5447 <span class="apii">[-?, +1, <em>m</em>]</span>
5448 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
5451 Finishes the use of buffer <code>B</code> leaving the final string on
5452 the top of the stack.
5458 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
5459 <span class="apii">[-1, +0, <em>m</em>]</span>
5460 <pre>int luaL_ref (lua_State *L, int t);</pre>
5463 Creates and returns a <em>reference</em>,
5464 in the table at index <code>t</code>,
5465 for the object at the top of the stack (and pops the object).
5469 A reference is a unique integer key.
5470 As long as you do not manually add integer keys into table <code>t</code>,
5471 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
5472 You can retrieve an object referred by reference <code>r</code>
5473 by calling <code>lua_rawgeti(L, t, r)</code>.
5474 Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
5478 If the object at the top of the stack is <b>nil</b>,
5479 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
5480 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
5481 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
5487 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
5488 <pre>typedef struct luaL_Reg {
5489 const char *name;
5490 lua_CFunction func;
5491 } luaL_Reg;</pre>
5494 Type for arrays of functions to be registered by
5495 <a href="#luaL_register"><code>luaL_register</code></a>.
5496 <code>name</code> is the function name and <code>func</code> is a pointer to
5497 the function.
5498 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
5499 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
5505 <hr><h3><a name="luaL_register"><code>luaL_register</code></a></h3><p>
5506 <span class="apii">[-(0|1), +1, <em>m</em>]</span>
5507 <pre>void luaL_register (lua_State *L,
5508 const char *libname,
5509 const luaL_Reg *l);</pre>
5512 Opens a library.
5516 When called with <code>libname</code> equal to <code>NULL</code>,
5517 it simply registers all functions in the list <code>l</code>
5518 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
5522 When called with a non-null <code>libname</code>,
5523 <code>luaL_register</code> creates a new table <code>t</code>,
5524 sets it as the value of the global variable <code>libname</code>,
5525 sets it as the value of <code>package.loaded[libname]</code>,
5526 and registers on it all functions in the list <code>l</code>.
5527 If there is a table in <code>package.loaded[libname]</code> or in
5528 variable <code>libname</code>,
5529 reuses this table instead of creating a new one.
5533 In any case the function leaves the table
5534 on the top of the stack.
5540 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
5541 <span class="apii">[-0, +0, <em>-</em>]</span>
5542 <pre>const char *luaL_typename (lua_State *L, int index);</pre>
5545 Returns the name of the type of the value at the given index.
5551 <hr><h3><a name="luaL_typerror"><code>luaL_typerror</code></a></h3><p>
5552 <span class="apii">[-0, +0, <em>v</em>]</span>
5553 <pre>int luaL_typerror (lua_State *L, int narg, const char *tname);</pre>
5556 Generates an error with a message like the following:
5558 <pre>
5559 <em>location</em>: bad argument <em>narg</em> to '<em>func</em>' (<em>tname</em> expected, got <em>rt</em>)
5560 </pre><p>
5561 where <code><em>location</em></code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
5562 <code><em>func</em></code> is the name of the current function,
5563 and <code><em>rt</em></code> is the type name of the actual argument.
5569 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
5570 <span class="apii">[-0, +0, <em>-</em>]</span>
5571 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
5574 Releases reference <code>ref</code> from the table at index <code>t</code>
5575 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
5576 The entry is removed from the table,
5577 so that the referred object can be collected.
5578 The reference <code>ref</code> is also freed to be used again.
5582 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>,
5583 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
5589 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
5590 <span class="apii">[-0, +1, <em>m</em>]</span>
5591 <pre>void luaL_where (lua_State *L, int lvl);</pre>
5594 Pushes onto the stack a string identifying the current position
5595 of the control at level <code>lvl</code> in the call stack.
5596 Typically this string has the following format:
5598 <pre>
5599 <em>chunkname</em>:<em>currentline</em>:
5600 </pre><p>
5601 Level&nbsp;0 is the running function,
5602 level&nbsp;1 is the function that called the running function,
5603 etc.
5607 This function is used to build a prefix for error messages.
5615 <h1>5 - <a name="5">Standard Libraries</a></h1>
5618 The standard Lua libraries provide useful functions
5619 that are implemented directly through the C&nbsp;API.
5620 Some of these functions provide essential services to the language
5621 (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
5622 others provide access to "outside" services (e.g., I/O);
5623 and others could be implemented in Lua itself,
5624 but are quite useful or have critical performance requirements that
5625 deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
5629 All libraries are implemented through the official C&nbsp;API
5630 and are provided as separate C&nbsp;modules.
5631 Currently, Lua has the following standard libraries:
5633 <ul>
5635 <li>basic library;</li>
5637 <li>package library;</li>
5639 <li>string manipulation;</li>
5641 <li>table manipulation;</li>
5643 <li>mathematical functions (sin, log, etc.);</li>
5645 <li>input and output;</li>
5647 <li>operating system facilities;</li>
5649 <li>debug facilities.</li>
5651 </ul><p>
5652 Except for the basic and package libraries,
5653 each library provides all its functions as fields of a global table
5654 or as methods of its objects.
5658 To have access to these libraries,
5659 the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
5660 which opens all standard libraries.
5661 Alternatively,
5662 it can open them individually by calling
5663 <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
5664 <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
5665 <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
5666 <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
5667 <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
5668 <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
5669 <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
5670 and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
5671 These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>
5672 and should not be called directly:
5673 you must call them like any other Lua C&nbsp;function,
5674 e.g., by using <a href="#lua_call"><code>lua_call</code></a>.
5678 <h2>5.1 - <a name="5.1">Basic Functions</a></h2>
5681 The basic library provides some core functions to Lua.
5682 If you do not include this library in your application,
5683 you should check carefully whether you need to provide
5684 implementations for some of its facilities.
5688 <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
5689 Issues an error when
5690 the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
5691 otherwise, returns all its arguments.
5692 <code>message</code> is an error message;
5693 when absent, it defaults to "assertion failed!"
5699 <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage (opt [, arg])</code></a></h3>
5703 This function is a generic interface to the garbage collector.
5704 It performs different functions according to its first argument, <code>opt</code>:
5706 <ul>
5708 <li><b>"stop":</b>
5709 stops the garbage collector.
5710 </li>
5712 <li><b>"restart":</b>
5713 restarts the garbage collector.
5714 </li>
5716 <li><b>"collect":</b>
5717 performs a full garbage-collection cycle.
5718 </li>
5720 <li><b>"count":</b>
5721 returns the total memory in use by Lua (in Kbytes).
5722 </li>
5724 <li><b>"step":</b>
5725 performs a garbage-collection step.
5726 The step "size" is controlled by <code>arg</code>
5727 (larger values mean more steps) in a non-specified way.
5728 If you want to control the step size
5729 you must experimentally tune the value of <code>arg</code>.
5730 Returns <b>true</b> if the step finished a collection cycle.
5731 </li>
5733 <li><b>"setpause":</b>
5734 sets <code>arg</code>/100 as the new value for the <em>pause</em> of
5735 the collector (see <a href="#2.10">&sect;2.10</a>).
5736 </li>
5738 <li><b>"setstepmul":</b>
5739 sets <code>arg</code>/100 as the new value for the <em>step multiplier</em> of
5740 the collector (see <a href="#2.10">&sect;2.10</a>).
5741 </li>
5743 </ul>
5748 <hr><h3><a name="pdf-dofile"><code>dofile (filename)</code></a></h3>
5749 Opens the named file and executes its contents as a Lua chunk.
5750 When called without arguments,
5751 <code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
5752 Returns all values returned by the chunk.
5753 In case of errors, <code>dofile</code> propagates the error
5754 to its caller (that is, <code>dofile</code> does not run in protected mode).
5760 <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
5761 Terminates the last protected function called
5762 and returns <code>message</code> as the error message.
5763 Function <code>error</code> never returns.
5767 Usually, <code>error</code> adds some information about the error position
5768 at the beginning of the message.
5769 The <code>level</code> argument specifies how to get the error position.
5770 With level&nbsp;1 (the default), the error position is where the
5771 <code>error</code> function was called.
5772 Level&nbsp;2 points the error to where the function
5773 that called <code>error</code> was called; and so on.
5774 Passing a level&nbsp;0 avoids the addition of error position information
5775 to the message.
5781 <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
5782 A global variable (not a function) that
5783 holds the global environment (that is, <code>_G._G = _G</code>).
5784 Lua itself does not use this variable;
5785 changing its value does not affect any environment,
5786 nor vice-versa.
5787 (Use <a href="#pdf-setfenv"><code>setfenv</code></a> to change environments.)
5793 <hr><h3><a name="pdf-getfenv"><code>getfenv ([f])</code></a></h3>
5794 Returns the current environment in use by the function.
5795 <code>f</code> can be a Lua function or a number
5796 that specifies the function at that stack level:
5797 Level&nbsp;1 is the function calling <code>getfenv</code>.
5798 If the given function is not a Lua function,
5799 or if <code>f</code> is 0,
5800 <code>getfenv</code> returns the global environment.
5801 The default for <code>f</code> is 1.
5807 <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
5811 If <code>object</code> does not have a metatable, returns <b>nil</b>.
5812 Otherwise,
5813 if the object's metatable has a <code>"__metatable"</code> field,
5814 returns the associated value.
5815 Otherwise, returns the metatable of the given object.
5821 <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
5825 Returns three values: an iterator function, the table <code>t</code>, and 0,
5826 so that the construction
5828 <pre>
5829 for i,v in ipairs(t) do <em>body</em> end
5830 </pre><p>
5831 will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), &middot;&middot;&middot;,
5832 up to the first integer key absent from the table.
5838 <hr><h3><a name="pdf-load"><code>load (func [, chunkname])</code></a></h3>
5842 Loads a chunk using function <code>func</code> to get its pieces.
5843 Each call to <code>func</code> must return a string that concatenates
5844 with previous results.
5845 A return of <b>nil</b> (or no value) signals the end of the chunk.
5849 If there are no errors,
5850 returns the compiled chunk as a function;
5851 otherwise, returns <b>nil</b> plus the error message.
5852 The environment of the returned function is the global environment.
5856 <code>chunkname</code> is used as the chunk name for error messages
5857 and debug information.
5858 When absent,
5859 it defaults to "<code>=(load)</code>".
5865 <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename])</code></a></h3>
5869 Similar to <a href="#pdf-load"><code>load</code></a>,
5870 but gets the chunk from file <code>filename</code>
5871 or from the standard input,
5872 if no file name is given.
5878 <hr><h3><a name="pdf-loadstring"><code>loadstring (string [, chunkname])</code></a></h3>
5882 Similar to <a href="#pdf-load"><code>load</code></a>,
5883 but gets the chunk from the given string.
5887 To load and run a given string, use the idiom
5889 <pre>
5890 assert(loadstring(s))()
5891 </pre>
5894 When absent,
5895 <code>chunkname</code> defaults to the given string.
5901 <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
5905 Allows a program to traverse all fields of a table.
5906 Its first argument is a table and its second argument
5907 is an index in this table.
5908 <code>next</code> returns the next index of the table
5909 and its associated value.
5910 When called with <b>nil</b> as its second argument,
5911 <code>next</code> returns an initial index
5912 and its associated value.
5913 When called with the last index,
5914 or with <b>nil</b> in an empty table,
5915 <code>next</code> returns <b>nil</b>.
5916 If the second argument is absent, then it is interpreted as <b>nil</b>.
5917 In particular,
5918 you can use <code>next(t)</code> to check whether a table is empty.
5922 The order in which the indices are enumerated is not specified,
5923 <em>even for numeric indices</em>.
5924 (To traverse a table in numeric order,
5925 use a numerical <b>for</b> or the <a href="#pdf-ipairs"><code>ipairs</code></a> function.)
5929 The behavior of <code>next</code> is <em>undefined</em> if,
5930 during the traversal,
5931 you assign any value to a non-existent field in the table.
5932 You may however modify existing fields.
5933 In particular, you may clear existing fields.
5939 <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
5943 Returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
5944 so that the construction
5946 <pre>
5947 for k,v in pairs(t) do <em>body</em> end
5948 </pre><p>
5949 will iterate over all key&ndash;value pairs of table <code>t</code>.
5953 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
5954 the table during its traversal.
5960 <hr><h3><a name="pdf-pcall"><code>pcall (f, arg1, &middot;&middot;&middot;)</code></a></h3>
5964 Calls function <code>f</code> with
5965 the given arguments in <em>protected mode</em>.
5966 This means that any error inside&nbsp;<code>f</code> is not propagated;
5967 instead, <code>pcall</code> catches the error
5968 and returns a status code.
5969 Its first result is the status code (a boolean),
5970 which is true if the call succeeds without errors.
5971 In such case, <code>pcall</code> also returns all results from the call,
5972 after this first result.
5973 In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
5979 <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
5980 Receives any number of arguments,
5981 and prints their values to <code>stdout</code>,
5982 using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert them to strings.
5983 <code>print</code> is not intended for formatted output,
5984 but only as a quick way to show a value,
5985 typically for debugging.
5986 For formatted output, use <a href="#pdf-string.format"><code>string.format</code></a>.
5992 <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
5993 Checks whether <code>v1</code> is equal to <code>v2</code>,
5994 without invoking any metamethod.
5995 Returns a boolean.
6001 <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
6002 Gets the real value of <code>table[index]</code>,
6003 without invoking any metamethod.
6004 <code>table</code> must be a table;
6005 <code>index</code> may be any value.
6011 <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
6012 Sets the real value of <code>table[index]</code> to <code>value</code>,
6013 without invoking any metamethod.
6014 <code>table</code> must be a table,
6015 <code>index</code> any value different from <b>nil</b>,
6016 and <code>value</code> any Lua value.
6020 This function returns <code>table</code>.
6026 <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
6030 If <code>index</code> is a number,
6031 returns all arguments after argument number <code>index</code>.
6032 Otherwise, <code>index</code> must be the string <code>"#"</code>,
6033 and <code>select</code> returns the total number of extra arguments it received.
6039 <hr><h3><a name="pdf-setfenv"><code>setfenv (f, table)</code></a></h3>
6043 Sets the environment to be used by the given function.
6044 <code>f</code> can be a Lua function or a number
6045 that specifies the function at that stack level:
6046 Level&nbsp;1 is the function calling <code>setfenv</code>.
6047 <code>setfenv</code> returns the given function.
6051 As a special case, when <code>f</code> is 0 <code>setfenv</code> changes
6052 the environment of the running thread.
6053 In this case, <code>setfenv</code> returns no values.
6059 <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
6063 Sets the metatable for the given table.
6064 (You cannot change the metatable of other types from Lua, only from&nbsp;C.)
6065 If <code>metatable</code> is <b>nil</b>,
6066 removes the metatable of the given table.
6067 If the original metatable has a <code>"__metatable"</code> field,
6068 raises an error.
6072 This function returns <code>table</code>.
6078 <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
6079 Tries to convert its argument to a number.
6080 If the argument is already a number or a string convertible
6081 to a number, then <code>tonumber</code> returns this number;
6082 otherwise, it returns <b>nil</b>.
6086 An optional argument specifies the base to interpret the numeral.
6087 The base may be any integer between 2 and 36, inclusive.
6088 In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
6089 represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
6090 with '<code>Z</code>' representing 35.
6091 In base 10 (the default), the number may have a decimal part,
6092 as well as an optional exponent part (see <a href="#2.1">&sect;2.1</a>).
6093 In other bases, only unsigned integers are accepted.
6099 <hr><h3><a name="pdf-tostring"><code>tostring (e)</code></a></h3>
6100 Receives an argument of any type and
6101 converts it to a string in a reasonable format.
6102 For complete control of how numbers are converted,
6103 use <a href="#pdf-string.format"><code>string.format</code></a>.
6107 If the metatable of <code>e</code> has a <code>"__tostring"</code> field,
6108 then <code>tostring</code> calls the corresponding value
6109 with <code>e</code> as argument,
6110 and uses the result of the call as its result.
6116 <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
6117 Returns the type of its only argument, coded as a string.
6118 The possible results of this function are
6119 "<code>nil</code>" (a string, not the value <b>nil</b>),
6120 "<code>number</code>",
6121 "<code>string</code>",
6122 "<code>boolean</code>",
6123 "<code>table</code>",
6124 "<code>function</code>",
6125 "<code>thread</code>",
6126 and "<code>userdata</code>".
6132 <hr><h3><a name="pdf-unpack"><code>unpack (list [, i [, j]])</code></a></h3>
6133 Returns the elements from the given table.
6134 This function is equivalent to
6136 <pre>
6137 return list[i], list[i+1], &middot;&middot;&middot;, list[j]
6138 </pre><p>
6139 except that the above code can be written only for a fixed number
6140 of elements.
6141 By default, <code>i</code> is&nbsp;1 and <code>j</code> is the length of the list,
6142 as defined by the length operator (see <a href="#2.5.5">&sect;2.5.5</a>).
6148 <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
6149 A global variable (not a function) that
6150 holds a string containing the current interpreter version.
6151 The current contents of this variable is "<code>Lua 5.1</code>".
6157 <hr><h3><a name="pdf-xpcall"><code>xpcall (f, err)</code></a></h3>
6161 This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
6162 except that you can set a new error handler.
6166 <code>xpcall</code> calls function <code>f</code> in protected mode,
6167 using <code>err</code> as the error handler.
6168 Any error inside <code>f</code> is not propagated;
6169 instead, <code>xpcall</code> catches the error,
6170 calls the <code>err</code> function with the original error object,
6171 and returns a status code.
6172 Its first result is the status code (a boolean),
6173 which is true if the call succeeds without errors.
6174 In this case, <code>xpcall</code> also returns all results from the call,
6175 after this first result.
6176 In case of any error,
6177 <code>xpcall</code> returns <b>false</b> plus the result from <code>err</code>.
6185 <h2>5.2 - <a name="5.2">Coroutine Manipulation</a></h2>
6188 The operations related to coroutines comprise a sub-library of
6189 the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
6190 See <a href="#2.11">&sect;2.11</a> for a general description of coroutines.
6194 <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
6198 Creates a new coroutine, with body <code>f</code>.
6199 <code>f</code> must be a Lua function.
6200 Returns this new coroutine,
6201 an object with type <code>"thread"</code>.
6207 <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
6211 Starts or continues the execution of coroutine <code>co</code>.
6212 The first time you resume a coroutine,
6213 it starts running its body.
6214 The values <code>val1</code>, &middot;&middot;&middot; are passed
6215 as the arguments to the body function.
6216 If the coroutine has yielded,
6217 <code>resume</code> restarts it;
6218 the values <code>val1</code>, &middot;&middot;&middot; are passed
6219 as the results from the yield.
6223 If the coroutine runs without any errors,
6224 <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
6225 (if the coroutine yields) or any values returned by the body function
6226 (if the coroutine terminates).
6227 If there is any error,
6228 <code>resume</code> returns <b>false</b> plus the error message.
6234 <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
6238 Returns the running coroutine,
6239 or <b>nil</b> when called by the main thread.
6245 <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
6249 Returns the status of coroutine <code>co</code>, as a string:
6250 <code>"running"</code>,
6251 if the coroutine is running (that is, it called <code>status</code>);
6252 <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
6253 or if it has not started running yet;
6254 <code>"normal"</code> if the coroutine is active but not running
6255 (that is, it has resumed another coroutine);
6256 and <code>"dead"</code> if the coroutine has finished its body function,
6257 or if it has stopped with an error.
6263 <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
6267 Creates a new coroutine, with body <code>f</code>.
6268 <code>f</code> must be a Lua function.
6269 Returns a function that resumes the coroutine each time it is called.
6270 Any arguments passed to the function behave as the
6271 extra arguments to <code>resume</code>.
6272 Returns the same values returned by <code>resume</code>,
6273 except the first boolean.
6274 In case of error, propagates the error.
6280 <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
6284 Suspends the execution of the calling coroutine.
6285 The coroutine cannot be running a C&nbsp;function,
6286 a metamethod, or an iterator.
6287 Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
6295 <h2>5.3 - <a name="5.3">Modules</a></h2>
6298 The package library provides basic
6299 facilities for loading and building modules in Lua.
6300 It exports two of its functions directly in the global environment:
6301 <a href="#pdf-require"><code>require</code></a> and <a href="#pdf-module"><code>module</code></a>.
6302 Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
6306 <hr><h3><a name="pdf-module"><code>module (name [, &middot;&middot;&middot;])</code></a></h3>
6310 Creates a module.
6311 If there is a table in <code>package.loaded[name]</code>,
6312 this table is the module.
6313 Otherwise, if there is a global table <code>t</code> with the given name,
6314 this table is the module.
6315 Otherwise creates a new table <code>t</code> and
6316 sets it as the value of the global <code>name</code> and
6317 the value of <code>package.loaded[name]</code>.
6318 This function also initializes <code>t._NAME</code> with the given name,
6319 <code>t._M</code> with the module (<code>t</code> itself),
6320 and <code>t._PACKAGE</code> with the package name
6321 (the full module name minus last component; see below).
6322 Finally, <code>module</code> sets <code>t</code> as the new environment
6323 of the current function and the new value of <code>package.loaded[name]</code>,
6324 so that <a href="#pdf-require"><code>require</code></a> returns <code>t</code>.
6328 If <code>name</code> is a compound name
6329 (that is, one with components separated by dots),
6330 <code>module</code> creates (or reuses, if they already exist)
6331 tables for each component.
6332 For instance, if <code>name</code> is <code>a.b.c</code>,
6333 then <code>module</code> stores the module table in field <code>c</code> of
6334 field <code>b</code> of global <code>a</code>.
6338 This function may receive optional <em>options</em> after
6339 the module name,
6340 where each option is a function to be applied over the module.
6346 <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
6350 Loads the given module.
6351 The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
6352 to determine whether <code>modname</code> is already loaded.
6353 If it is, then <code>require</code> returns the value stored
6354 at <code>package.loaded[modname]</code>.
6355 Otherwise, it tries to find a <em>loader</em> for the module.
6359 To find a loader,
6360 <code>require</code> is guided by the <a href="#pdf-package.loaders"><code>package.loaders</code></a> array.
6361 By changing this array,
6362 we can change how <code>require</code> looks for a module.
6363 The following explanation is based on the default configuration
6364 for <a href="#pdf-package.loaders"><code>package.loaders</code></a>.
6368 First <code>require</code> queries <code>package.preload[modname]</code>.
6369 If it has a value,
6370 this value (which should be a function) is the loader.
6371 Otherwise <code>require</code> searches for a Lua loader using the
6372 path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
6373 If that also fails, it searches for a C&nbsp;loader using the
6374 path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
6375 If that also fails,
6376 it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.loaders"><code>package.loaders</code></a>).
6380 Once a loader is found,
6381 <code>require</code> calls the loader with a single argument, <code>modname</code>.
6382 If the loader returns any value,
6383 <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
6384 If the loader returns no value and
6385 has not assigned any value to <code>package.loaded[modname]</code>,
6386 then <code>require</code> assigns <b>true</b> to this entry.
6387 In any case, <code>require</code> returns the
6388 final value of <code>package.loaded[modname]</code>.
6392 If there is any error loading or running the module,
6393 or if it cannot find any loader for the module,
6394 then <code>require</code> signals an error.
6400 <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
6404 The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
6408 Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
6409 it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
6410 using the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
6411 or a default path defined in <code>luaconf.h</code>.
6418 <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
6422 A table used by <a href="#pdf-require"><code>require</code></a> to control which
6423 modules are already loaded.
6424 When you require a module <code>modname</code> and
6425 <code>package.loaded[modname]</code> is not false,
6426 <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
6432 <hr><h3><a name="pdf-package.loaders"><code>package.loaders</code></a></h3>
6436 A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
6440 Each entry in this table is a <em>searcher function</em>.
6441 When looking for a module,
6442 <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
6443 with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
6444 sole parameter.
6445 The function may return another function (the module <em>loader</em>)
6446 or a string explaining why it did not find that module
6447 (or <b>nil</b> if it has nothing to say).
6448 Lua initializes this table with four functions.
6452 The first searcher simply looks for a loader in the
6453 <a href="#pdf-package.preload"><code>package.preload</code></a> table.
6457 The second searcher looks for a loader as a Lua library,
6458 using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
6459 A path is a sequence of <em>templates</em> separated by semicolons.
6460 For each template,
6461 the searcher will change each interrogation
6462 mark in the template by <code>filename</code>,
6463 which is the module name with each dot replaced by a
6464 "directory separator" (such as "<code>/</code>" in Unix);
6465 then it will try to open the resulting file name.
6466 So, for instance, if the Lua path is the string
6468 <pre>
6469 "./?.lua;./?.lc;/usr/local/?/init.lua"
6470 </pre><p>
6471 the search for a Lua file for module <code>foo</code>
6472 will try to open the files
6473 <code>./foo.lua</code>, <code>./foo.lc</code>, and
6474 <code>/usr/local/foo/init.lua</code>, in that order.
6478 The third searcher looks for a loader as a C&nbsp;library,
6479 using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
6480 For instance,
6481 if the C&nbsp;path is the string
6483 <pre>
6484 "./?.so;./?.dll;/usr/local/?/init.so"
6485 </pre><p>
6486 the searcher for module <code>foo</code>
6487 will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
6488 and <code>/usr/local/foo/init.so</code>, in that order.
6489 Once it finds a C&nbsp;library,
6490 this searcher first uses a dynamic link facility to link the
6491 application with the library.
6492 Then it tries to find a C&nbsp;function inside the library to
6493 be used as the loader.
6494 The name of this C&nbsp;function is the string "<code>luaopen_</code>"
6495 concatenated with a copy of the module name where each dot
6496 is replaced by an underscore.
6497 Moreover, if the module name has a hyphen,
6498 its prefix up to (and including) the first hyphen is removed.
6499 For instance, if the module name is <code>a.v1-b.c</code>,
6500 the function name will be <code>luaopen_b_c</code>.
6504 The fourth searcher tries an <em>all-in-one loader</em>.
6505 It searches the C&nbsp;path for a library for
6506 the root name of the given module.
6507 For instance, when requiring <code>a.b.c</code>,
6508 it will search for a C&nbsp;library for <code>a</code>.
6509 If found, it looks into it for an open function for
6510 the submodule;
6511 in our example, that would be <code>luaopen_a_b_c</code>.
6512 With this facility, a package can pack several C&nbsp;submodules
6513 into one single library,
6514 with each submodule keeping its original open function.
6520 <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
6524 Dynamically links the host program with the C&nbsp;library <code>libname</code>.
6525 Inside this library, looks for a function <code>funcname</code>
6526 and returns this function as a C&nbsp;function.
6527 (So, <code>funcname</code> must follow the protocol (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>)).
6531 This is a low-level function.
6532 It completely bypasses the package and module system.
6533 Unlike <a href="#pdf-require"><code>require</code></a>,
6534 it does not perform any path searching and
6535 does not automatically adds extensions.
6536 <code>libname</code> must be the complete file name of the C&nbsp;library,
6537 including if necessary a path and extension.
6538 <code>funcname</code> must be the exact name exported by the C&nbsp;library
6539 (which may depend on the C&nbsp;compiler and linker used).
6543 This function is not supported by ANSI C.
6544 As such, it is only available on some platforms
6545 (Windows, Linux, Mac OS X, Solaris, BSD,
6546 plus other Unix systems that support the <code>dlfcn</code> standard).
6552 <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
6556 The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
6560 At start-up, Lua initializes this variable with
6561 the value of the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
6562 with a default path defined in <code>luaconf.h</code>,
6563 if the environment variable is not defined.
6564 Any "<code>;;</code>" in the value of the environment variable
6565 is replaced by the default path.
6571 <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
6575 A table to store loaders for specific modules
6576 (see <a href="#pdf-require"><code>require</code></a>).
6582 <hr><h3><a name="pdf-package.seeall"><code>package.seeall (module)</code></a></h3>
6586 Sets a metatable for <code>module</code> with
6587 its <code>__index</code> field referring to the global environment,
6588 so that this module inherits values
6589 from the global environment.
6590 To be used as an option to function <a href="#pdf-module"><code>module</code></a>.
6598 <h2>5.4 - <a name="5.4">String Manipulation</a></h2>
6601 This library provides generic functions for string manipulation,
6602 such as finding and extracting substrings, and pattern matching.
6603 When indexing a string in Lua, the first character is at position&nbsp;1
6604 (not at&nbsp;0, as in C).
6605 Indices are allowed to be negative and are interpreted as indexing backwards,
6606 from the end of the string.
6607 Thus, the last character is at position -1, and so on.
6611 The string library provides all its functions inside the table
6612 <a name="pdf-string"><code>string</code></a>.
6613 It also sets a metatable for strings
6614 where the <code>__index</code> field points to the <code>string</code> table.
6615 Therefore, you can use the string functions in object-oriented style.
6616 For instance, <code>string.byte(s, i)</code>
6617 can be written as <code>s:byte(i)</code>.
6621 <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
6622 Returns the internal numerical codes of the characters <code>s[i]</code>,
6623 <code>s[i+1]</code>, &middot;&middot;&middot;, <code>s[j]</code>.
6624 The default value for <code>i</code> is&nbsp;1;
6625 the default value for <code>j</code> is&nbsp;<code>i</code>.
6629 Note that numerical codes are not necessarily portable across platforms.
6635 <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
6636 Receives zero or more integers.
6637 Returns a string with length equal to the number of arguments,
6638 in which each character has the internal numerical code equal
6639 to its corresponding argument.
6643 Note that numerical codes are not necessarily portable across platforms.
6649 <hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
6653 Returns a string containing a binary representation of the given function,
6654 so that a later <a href="#pdf-loadstring"><code>loadstring</code></a> on this string returns
6655 a copy of the function.
6656 <code>function</code> must be a Lua function without upvalues.
6662 <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
6663 Looks for the first match of
6664 <code>pattern</code> in the string <code>s</code>.
6665 If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
6666 where this occurrence starts and ends;
6667 otherwise, it returns <b>nil</b>.
6668 A third, optional numerical argument <code>init</code> specifies
6669 where to start the search;
6670 its default value is&nbsp;1 and may be negative.
6671 A value of <b>true</b> as a fourth, optional argument <code>plain</code>
6672 turns off the pattern matching facilities,
6673 so the function does a plain "find substring" operation,
6674 with no characters in <code>pattern</code> being considered "magic".
6675 Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
6679 If the pattern has captures,
6680 then in a successful match
6681 the captured values are also returned,
6682 after the two indices.
6688 <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
6689 Returns a formatted version of its variable number of arguments
6690 following the description given in its first argument (which must be a string).
6691 The format string follows the same rules as the <code>printf</code> family of
6692 standard C&nbsp;functions.
6693 The only differences are that the options/modifiers
6694 <code>*</code>, <code>l</code>, <code>L</code>, <code>n</code>, <code>p</code>,
6695 and <code>h</code> are not supported
6696 and that there is an extra option, <code>q</code>.
6697 The <code>q</code> option formats a string in a form suitable to be safely read
6698 back by the Lua interpreter:
6699 the string is written between double quotes,
6700 and all double quotes, newlines, embedded zeros,
6701 and backslashes in the string
6702 are correctly escaped when written.
6703 For instance, the call
6705 <pre>
6706 string.format('%q', 'a string with "quotes" and \n new line')
6707 </pre><p>
6708 will produce the string:
6710 <pre>
6711 "a string with \"quotes\" and \
6712 new line"
6713 </pre>
6716 The options <code>c</code>, <code>d</code>, <code>E</code>, <code>e</code>, <code>f</code>,
6717 <code>g</code>, <code>G</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> all
6718 expect a number as argument,
6719 whereas <code>q</code> and <code>s</code> expect a string.
6723 This function does not accept string values
6724 containing embedded zeros,
6725 except as arguments to the <code>q</code> option.
6731 <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
6732 Returns an iterator function that,
6733 each time it is called,
6734 returns the next captures from <code>pattern</code> over string <code>s</code>.
6735 If <code>pattern</code> specifies no captures,
6736 then the whole match is produced in each call.
6740 As an example, the following loop
6742 <pre>
6743 s = "hello world from Lua"
6744 for w in string.gmatch(s, "%a+") do
6745 print(w)
6747 </pre><p>
6748 will iterate over all the words from string <code>s</code>,
6749 printing one per line.
6750 The next example collects all pairs <code>key=value</code> from the
6751 given string into a table:
6753 <pre>
6754 t = {}
6755 s = "from=world, to=Lua"
6756 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
6757 t[k] = v
6759 </pre>
6762 For this function, a '<code>^</code>' at the start of a pattern does not
6763 work as an anchor, as this would prevent the iteration.
6769 <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
6770 Returns a copy of <code>s</code>
6771 in which all (or the first <code>n</code>, if given)
6772 occurrences of the <code>pattern</code> have been
6773 replaced by a replacement string specified by <code>repl</code>,
6774 which may be a string, a table, or a function.
6775 <code>gsub</code> also returns, as its second value,
6776 the total number of matches that occurred.
6780 If <code>repl</code> is a string, then its value is used for replacement.
6781 The character&nbsp;<code>%</code> works as an escape character:
6782 any sequence in <code>repl</code> of the form <code>%<em>n</em></code>,
6783 with <em>n</em> between 1 and 9,
6784 stands for the value of the <em>n</em>-th captured substring (see below).
6785 The sequence <code>%0</code> stands for the whole match.
6786 The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
6790 If <code>repl</code> is a table, then the table is queried for every match,
6791 using the first capture as the key;
6792 if the pattern specifies no captures,
6793 then the whole match is used as the key.
6797 If <code>repl</code> is a function, then this function is called every time a
6798 match occurs, with all captured substrings passed as arguments,
6799 in order;
6800 if the pattern specifies no captures,
6801 then the whole match is passed as a sole argument.
6805 If the value returned by the table query or by the function call
6806 is a string or a number,
6807 then it is used as the replacement string;
6808 otherwise, if it is <b>false</b> or <b>nil</b>,
6809 then there is no replacement
6810 (that is, the original match is kept in the string).
6814 Here are some examples:
6816 <pre>
6817 x = string.gsub("hello world", "(%w+)", "%1 %1")
6818 --&gt; x="hello hello world world"
6820 x = string.gsub("hello world", "%w+", "%0 %0", 1)
6821 --&gt; x="hello hello world"
6823 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
6824 --&gt; x="world hello Lua from"
6826 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
6827 --&gt; x="home = /home/roberto, user = roberto"
6829 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
6830 return loadstring(s)()
6831 end)
6832 --&gt; x="4+5 = 9"
6834 local t = {name="lua", version="5.1"}
6835 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
6836 --&gt; x="lua-5.1.tar.gz"
6837 </pre>
6842 <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
6843 Receives a string and returns its length.
6844 The empty string <code>""</code> has length 0.
6845 Embedded zeros are counted,
6846 so <code>"a\000bc\000"</code> has length 5.
6852 <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
6853 Receives a string and returns a copy of this string with all
6854 uppercase letters changed to lowercase.
6855 All other characters are left unchanged.
6856 The definition of what an uppercase letter is depends on the current locale.
6862 <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
6863 Looks for the first <em>match</em> of
6864 <code>pattern</code> in the string <code>s</code>.
6865 If it finds one, then <code>match</code> returns
6866 the captures from the pattern;
6867 otherwise it returns <b>nil</b>.
6868 If <code>pattern</code> specifies no captures,
6869 then the whole match is returned.
6870 A third, optional numerical argument <code>init</code> specifies
6871 where to start the search;
6872 its default value is&nbsp;1 and may be negative.
6878 <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n)</code></a></h3>
6879 Returns a string that is the concatenation of <code>n</code> copies of
6880 the string <code>s</code>.
6886 <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
6887 Returns a string that is the string <code>s</code> reversed.
6893 <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
6894 Returns the substring of <code>s</code> that
6895 starts at <code>i</code> and continues until <code>j</code>;
6896 <code>i</code> and <code>j</code> may be negative.
6897 If <code>j</code> is absent, then it is assumed to be equal to -1
6898 (which is the same as the string length).
6899 In particular,
6900 the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
6901 with length <code>j</code>,
6902 and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
6903 with length <code>i</code>.
6909 <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
6910 Receives a string and returns a copy of this string with all
6911 lowercase letters changed to uppercase.
6912 All other characters are left unchanged.
6913 The definition of what a lowercase letter is depends on the current locale.
6917 <h3>5.4.1 - <a name="5.4.1">Patterns</a></h3>
6920 <h4>Character Class:</h4><p>
6921 A <em>character class</em> is used to represent a set of characters.
6922 The following combinations are allowed in describing a character class:
6924 <ul>
6926 <li><b><em>x</em>:</b>
6927 (where <em>x</em> is not one of the <em>magic characters</em>
6928 <code>^$()%.[]*+-?</code>)
6929 represents the character <em>x</em> itself.
6930 </li>
6932 <li><b><code>.</code>:</b> (a dot) represents all characters.</li>
6934 <li><b><code>%a</code>:</b> represents all letters.</li>
6936 <li><b><code>%c</code>:</b> represents all control characters.</li>
6938 <li><b><code>%d</code>:</b> represents all digits.</li>
6940 <li><b><code>%l</code>:</b> represents all lowercase letters.</li>
6942 <li><b><code>%p</code>:</b> represents all punctuation characters.</li>
6944 <li><b><code>%s</code>:</b> represents all space characters.</li>
6946 <li><b><code>%u</code>:</b> represents all uppercase letters.</li>
6948 <li><b><code>%w</code>:</b> represents all alphanumeric characters.</li>
6950 <li><b><code>%x</code>:</b> represents all hexadecimal digits.</li>
6952 <li><b><code>%z</code>:</b> represents the character with representation 0.</li>
6954 <li><b><code>%<em>x</em></code>:</b> (where <em>x</em> is any non-alphanumeric character)
6955 represents the character <em>x</em>.
6956 This is the standard way to escape the magic characters.
6957 Any punctuation character (even the non magic)
6958 can be preceded by a '<code>%</code>'
6959 when used to represent itself in a pattern.
6960 </li>
6962 <li><b><code>[<em>set</em>]</code>:</b>
6963 represents the class which is the union of all
6964 characters in <em>set</em>.
6965 A range of characters may be specified by
6966 separating the end characters of the range with a '<code>-</code>'.
6967 All classes <code>%</code><em>x</em> described above may also be used as
6968 components in <em>set</em>.
6969 All other characters in <em>set</em> represent themselves.
6970 For example, <code>[%w_]</code> (or <code>[_%w]</code>)
6971 represents all alphanumeric characters plus the underscore,
6972 <code>[0-7]</code> represents the octal digits,
6973 and <code>[0-7%l%-]</code> represents the octal digits plus
6974 the lowercase letters plus the '<code>-</code>' character.
6978 The interaction between ranges and classes is not defined.
6979 Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
6980 have no meaning.
6981 </li>
6983 <li><b><code>[^<em>set</em>]</code>:</b>
6984 represents the complement of <em>set</em>,
6985 where <em>set</em> is interpreted as above.
6986 </li>
6988 </ul><p>
6989 For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
6990 the corresponding uppercase letter represents the complement of the class.
6991 For instance, <code>%S</code> represents all non-space characters.
6995 The definitions of letter, space, and other character groups
6996 depend on the current locale.
6997 In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
7003 <h4>Pattern Item:</h4><p>
7004 A <em>pattern item</em> may be
7006 <ul>
7008 <li>
7009 a single character class,
7010 which matches any single character in the class;
7011 </li>
7013 <li>
7014 a single character class followed by '<code>*</code>',
7015 which matches 0 or more repetitions of characters in the class.
7016 These repetition items will always match the longest possible sequence;
7017 </li>
7019 <li>
7020 a single character class followed by '<code>+</code>',
7021 which matches 1 or more repetitions of characters in the class.
7022 These repetition items will always match the longest possible sequence;
7023 </li>
7025 <li>
7026 a single character class followed by '<code>-</code>',
7027 which also matches 0 or more repetitions of characters in the class.
7028 Unlike '<code>*</code>',
7029 these repetition items will always match the <em>shortest</em> possible sequence;
7030 </li>
7032 <li>
7033 a single character class followed by '<code>?</code>',
7034 which matches 0 or 1 occurrence of a character in the class;
7035 </li>
7037 <li>
7038 <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
7039 such item matches a substring equal to the <em>n</em>-th captured string
7040 (see below);
7041 </li>
7043 <li>
7044 <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
7045 such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
7046 and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
7047 This means that, if one reads the string from left to right,
7048 counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
7049 the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
7050 For instance, the item <code>%b()</code> matches expressions with
7051 balanced parentheses.
7052 </li>
7054 </ul>
7059 <h4>Pattern:</h4><p>
7060 A <em>pattern</em> is a sequence of pattern items.
7061 A '<code>^</code>' at the beginning of a pattern anchors the match at the
7062 beginning of the subject string.
7063 A '<code>$</code>' at the end of a pattern anchors the match at the
7064 end of the subject string.
7065 At other positions,
7066 '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
7072 <h4>Captures:</h4><p>
7073 A pattern may contain sub-patterns enclosed in parentheses;
7074 they describe <em>captures</em>.
7075 When a match succeeds, the substrings of the subject string
7076 that match captures are stored (<em>captured</em>) for future use.
7077 Captures are numbered according to their left parentheses.
7078 For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
7079 the part of the string matching <code>"a*(.)%w(%s*)"</code> is
7080 stored as the first capture (and therefore has number&nbsp;1);
7081 the character matching "<code>.</code>" is captured with number&nbsp;2,
7082 and the part matching "<code>%s*</code>" has number&nbsp;3.
7086 As a special case, the empty capture <code>()</code> captures
7087 the current string position (a number).
7088 For instance, if we apply the pattern <code>"()aa()"</code> on the
7089 string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
7093 A pattern cannot contain embedded zeros. Use <code>%z</code> instead.
7105 <h2>5.5 - <a name="5.5">Table Manipulation</a></h2><p>
7106 This library provides generic functions for table manipulation.
7107 It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
7111 Most functions in the table library assume that the table
7112 represents an array or a list.
7113 For these functions, when we talk about the "length" of a table
7114 we mean the result of the length operator.
7118 <hr><h3><a name="pdf-table.concat"><code>table.concat (table [, sep [, i [, j]]])</code></a></h3>
7119 Given an array where all elements are strings or numbers,
7120 returns <code>table[i]..sep..table[i+1] &middot;&middot;&middot; sep..table[j]</code>.
7121 The default value for <code>sep</code> is the empty string,
7122 the default for <code>i</code> is 1,
7123 and the default for <code>j</code> is the length of the table.
7124 If <code>i</code> is greater than <code>j</code>, returns the empty string.
7130 <hr><h3><a name="pdf-table.insert"><code>table.insert (table, [pos,] value)</code></a></h3>
7134 Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>,
7135 shifting up other elements to open space, if necessary.
7136 The default value for <code>pos</code> is <code>n+1</code>,
7137 where <code>n</code> is the length of the table (see <a href="#2.5.5">&sect;2.5.5</a>),
7138 so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
7139 of table <code>t</code>.
7145 <hr><h3><a name="pdf-table.maxn"><code>table.maxn (table)</code></a></h3>
7149 Returns the largest positive numerical index of the given table,
7150 or zero if the table has no positive numerical indices.
7151 (To do its job this function does a linear traversal of
7152 the whole table.)
7158 <hr><h3><a name="pdf-table.remove"><code>table.remove (table [, pos])</code></a></h3>
7162 Removes from <code>table</code> the element at position <code>pos</code>,
7163 shifting down other elements to close the space, if necessary.
7164 Returns the value of the removed element.
7165 The default value for <code>pos</code> is <code>n</code>,
7166 where <code>n</code> is the length of the table,
7167 so that a call <code>table.remove(t)</code> removes the last element
7168 of table <code>t</code>.
7174 <hr><h3><a name="pdf-table.sort"><code>table.sort (table [, comp])</code></a></h3>
7175 Sorts table elements in a given order, <em>in-place</em>,
7176 from <code>table[1]</code> to <code>table[n]</code>,
7177 where <code>n</code> is the length of the table.
7178 If <code>comp</code> is given,
7179 then it must be a function that receives two table elements,
7180 and returns true
7181 when the first is less than the second
7182 (so that <code>not comp(a[i+1],a[i])</code> will be true after the sort).
7183 If <code>comp</code> is not given,
7184 then the standard Lua operator <code>&lt;</code> is used instead.
7188 The sort algorithm is not stable;
7189 that is, elements considered equal by the given order
7190 may have their relative positions changed by the sort.
7198 <h2>5.6 - <a name="5.6">Mathematical Functions</a></h2>
7201 This library is an interface to the standard C&nbsp;math library.
7202 It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
7206 <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
7210 Returns the absolute value of <code>x</code>.
7216 <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
7220 Returns the arc cosine of <code>x</code> (in radians).
7226 <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
7230 Returns the arc sine of <code>x</code> (in radians).
7236 <hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
7240 Returns the arc tangent of <code>x</code> (in radians).
7246 <hr><h3><a name="pdf-math.atan2"><code>math.atan2 (y, x)</code></a></h3>
7250 Returns the arc tangent of <code>y/x</code> (in radians),
7251 but uses the signs of both parameters to find the
7252 quadrant of the result.
7253 (It also handles correctly the case of <code>x</code> being zero.)
7259 <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
7263 Returns the smallest integer larger than or equal to <code>x</code>.
7269 <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
7273 Returns the cosine of <code>x</code> (assumed to be in radians).
7279 <hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
7283 Returns the hyperbolic cosine of <code>x</code>.
7289 <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
7293 Returns the angle <code>x</code> (given in radians) in degrees.
7299 <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
7303 Returns the value <em>e<sup>x</sup></em>.
7309 <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
7313 Returns the largest integer smaller than or equal to <code>x</code>.
7319 <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
7323 Returns the remainder of the division of <code>x</code> by <code>y</code>.
7329 <hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
7333 Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
7334 <code>e</code> is an integer and the absolute value of <code>m</code> is
7335 in the range <em>[0.5, 1)</em>
7336 (or zero when <code>x</code> is zero).
7342 <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
7346 The value <code>HUGE_VAL</code>,
7347 a value larger than or equal to any other numerical value.
7353 <hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
7357 Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
7363 <hr><h3><a name="pdf-math.log"><code>math.log (x)</code></a></h3>
7367 Returns the natural logarithm of <code>x</code>.
7373 <hr><h3><a name="pdf-math.log10"><code>math.log10 (x)</code></a></h3>
7377 Returns the base-10 logarithm of <code>x</code>.
7383 <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
7387 Returns the maximum value among its arguments.
7393 <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
7397 Returns the minimum value among its arguments.
7403 <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
7407 Returns two numbers,
7408 the integral part of <code>x</code> and the fractional part of <code>x</code>.
7414 <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
7418 The value of <em>pi</em>.
7424 <hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
7428 Returns <em>x<sup>y</sup></em>.
7429 (You can also use the expression <code>x^y</code> to compute this value.)
7435 <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
7439 Returns the angle <code>x</code> (given in degrees) in radians.
7445 <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
7449 This function is an interface to the simple
7450 pseudo-random generator function <code>rand</code> provided by ANSI&nbsp;C.
7451 (No guarantees can be given for its statistical properties.)
7455 When called without arguments,
7456 returns a uniform pseudo-random real number
7457 in the range <em>[0,1)</em>.
7458 When called with an integer number <code>m</code>,
7459 <code>math.random</code> returns
7460 a uniform pseudo-random integer in the range <em>[1, m]</em>.
7461 When called with two integer numbers <code>m</code> and <code>n</code>,
7462 <code>math.random</code> returns a uniform pseudo-random
7463 integer in the range <em>[m, n]</em>.
7469 <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
7473 Sets <code>x</code> as the "seed"
7474 for the pseudo-random generator:
7475 equal seeds produce equal sequences of numbers.
7481 <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
7485 Returns the sine of <code>x</code> (assumed to be in radians).
7491 <hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
7495 Returns the hyperbolic sine of <code>x</code>.
7501 <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
7505 Returns the square root of <code>x</code>.
7506 (You can also use the expression <code>x^0.5</code> to compute this value.)
7512 <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
7516 Returns the tangent of <code>x</code> (assumed to be in radians).
7522 <hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
7526 Returns the hyperbolic tangent of <code>x</code>.
7534 <h2>5.7 - <a name="5.7">Input and Output Facilities</a></h2>
7537 The I/O library provides two different styles for file manipulation.
7538 The first one uses implicit file descriptors;
7539 that is, there are operations to set a default input file and a
7540 default output file,
7541 and all input/output operations are over these default files.
7542 The second style uses explicit file descriptors.
7546 When using implicit file descriptors,
7547 all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
7548 When using explicit file descriptors,
7549 the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
7550 and then all operations are supplied as methods of the file descriptor.
7554 The table <code>io</code> also provides
7555 three predefined file descriptors with their usual meanings from C:
7556 <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>.
7557 The I/O library never closes these files.
7561 Unless otherwise stated,
7562 all I/O functions return <b>nil</b> on failure
7563 (plus an error message as a second result and
7564 a system-dependent error code as a third result)
7565 and some value different from <b>nil</b> on success.
7569 <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
7573 Equivalent to <code>file:close()</code>.
7574 Without a <code>file</code>, closes the default output file.
7580 <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
7584 Equivalent to <code>file:flush</code> over the default output file.
7590 <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
7594 When called with a file name, it opens the named file (in text mode),
7595 and sets its handle as the default input file.
7596 When called with a file handle,
7597 it simply sets this file handle as the default input file.
7598 When called without parameters,
7599 it returns the current default input file.
7603 In case of errors this function raises the error,
7604 instead of returning an error code.
7610 <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename])</code></a></h3>
7614 Opens the given file name in read mode
7615 and returns an iterator function that,
7616 each time it is called,
7617 returns a new line from the file.
7618 Therefore, the construction
7620 <pre>
7621 for line in io.lines(filename) do <em>body</em> end
7622 </pre><p>
7623 will iterate over all lines of the file.
7624 When the iterator function detects the end of file,
7625 it returns <b>nil</b> (to finish the loop) and automatically closes the file.
7629 The call <code>io.lines()</code> (with no file name) is equivalent
7630 to <code>io.input():lines()</code>;
7631 that is, it iterates over the lines of the default input file.
7632 In this case it does not close the file when the loop ends.
7638 <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
7642 This function opens a file,
7643 in the mode specified in the string <code>mode</code>.
7644 It returns a new file handle,
7645 or, in case of errors, <b>nil</b> plus an error message.
7649 The <code>mode</code> string can be any of the following:
7651 <ul>
7652 <li><b>"r":</b> read mode (the default);</li>
7653 <li><b>"w":</b> write mode;</li>
7654 <li><b>"a":</b> append mode;</li>
7655 <li><b>"r+":</b> update mode, all previous data is preserved;</li>
7656 <li><b>"w+":</b> update mode, all previous data is erased;</li>
7657 <li><b>"a+":</b> append update mode, previous data is preserved,
7658 writing is only allowed at the end of file.</li>
7659 </ul><p>
7660 The <code>mode</code> string may also have a '<code>b</code>' at the end,
7661 which is needed in some systems to open the file in binary mode.
7662 This string is exactly what is used in the
7663 standard&nbsp;C function <code>fopen</code>.
7669 <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
7673 Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
7679 <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
7683 Starts program <code>prog</code> in a separated process and returns
7684 a file handle that you can use to read data from this program
7685 (if <code>mode</code> is <code>"r"</code>, the default)
7686 or to write data to this program
7687 (if <code>mode</code> is <code>"w"</code>).
7691 This function is system dependent and is not available
7692 on all platforms.
7698 <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
7702 Equivalent to <code>io.input():read</code>.
7708 <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
7712 Returns a handle for a temporary file.
7713 This file is opened in update mode
7714 and it is automatically removed when the program ends.
7720 <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
7724 Checks whether <code>obj</code> is a valid file handle.
7725 Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
7726 <code>"closed file"</code> if <code>obj</code> is a closed file handle,
7727 or <b>nil</b> if <code>obj</code> is not a file handle.
7733 <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
7737 Equivalent to <code>io.output():write</code>.
7743 <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
7747 Closes <code>file</code>.
7748 Note that files are automatically closed when
7749 their handles are garbage collected,
7750 but that takes an unpredictable amount of time to happen.
7756 <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
7760 Saves any written data to <code>file</code>.
7766 <hr><h3><a name="pdf-file:lines"><code>file:lines ()</code></a></h3>
7770 Returns an iterator function that,
7771 each time it is called,
7772 returns a new line from the file.
7773 Therefore, the construction
7775 <pre>
7776 for line in file:lines() do <em>body</em> end
7777 </pre><p>
7778 will iterate over all lines of the file.
7779 (Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
7780 when the loop ends.)
7786 <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
7790 Reads the file <code>file</code>,
7791 according to the given formats, which specify what to read.
7792 For each format,
7793 the function returns a string (or a number) with the characters read,
7794 or <b>nil</b> if it cannot read data with the specified format.
7795 When called without formats,
7796 it uses a default format that reads the entire next line
7797 (see below).
7801 The available formats are
7803 <ul>
7805 <li><b>"*n":</b>
7806 reads a number;
7807 this is the only format that returns a number instead of a string.
7808 </li>
7810 <li><b>"*a":</b>
7811 reads the whole file, starting at the current position.
7812 On end of file, it returns the empty string.
7813 </li>
7815 <li><b>"*l":</b>
7816 reads the next line (skipping the end of line),
7817 returning <b>nil</b> on end of file.
7818 This is the default format.
7819 </li>
7821 <li><b><em>number</em>:</b>
7822 reads a string with up to this number of characters,
7823 returning <b>nil</b> on end of file.
7824 If number is zero,
7825 it reads nothing and returns an empty string,
7826 or <b>nil</b> on end of file.
7827 </li>
7829 </ul>
7834 <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence] [, offset])</code></a></h3>
7838 Sets and gets the file position,
7839 measured from the beginning of the file,
7840 to the position given by <code>offset</code> plus a base
7841 specified by the string <code>whence</code>, as follows:
7843 <ul>
7844 <li><b>"set":</b> base is position 0 (beginning of the file);</li>
7845 <li><b>"cur":</b> base is current position;</li>
7846 <li><b>"end":</b> base is end of file;</li>
7847 </ul><p>
7848 In case of success, function <code>seek</code> returns the final file position,
7849 measured in bytes from the beginning of the file.
7850 If this function fails, it returns <b>nil</b>,
7851 plus a string describing the error.
7855 The default value for <code>whence</code> is <code>"cur"</code>,
7856 and for <code>offset</code> is 0.
7857 Therefore, the call <code>file:seek()</code> returns the current
7858 file position, without changing it;
7859 the call <code>file:seek("set")</code> sets the position to the
7860 beginning of the file (and returns 0);
7861 and the call <code>file:seek("end")</code> sets the position to the
7862 end of the file, and returns its size.
7868 <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
7872 Sets the buffering mode for an output file.
7873 There are three available modes:
7875 <ul>
7877 <li><b>"no":</b>
7878 no buffering; the result of any output operation appears immediately.
7879 </li>
7881 <li><b>"full":</b>
7882 full buffering; output operation is performed only
7883 when the buffer is full (or when you explicitly <code>flush</code> the file
7884 (see <a href="#pdf-io.flush"><code>io.flush</code></a>)).
7885 </li>
7887 <li><b>"line":</b>
7888 line buffering; output is buffered until a newline is output
7889 or there is any input from some special files
7890 (such as a terminal device).
7891 </li>
7893 </ul><p>
7894 For the last two cases, <code>size</code>
7895 specifies the size of the buffer, in bytes.
7896 The default is an appropriate size.
7902 <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
7906 Writes the value of each of its arguments to
7907 the <code>file</code>.
7908 The arguments must be strings or numbers.
7909 To write other values,
7910 use <a href="#pdf-tostring"><code>tostring</code></a> or <a href="#pdf-string.format"><code>string.format</code></a> before <code>write</code>.
7918 <h2>5.8 - <a name="5.8">Operating System Facilities</a></h2>
7921 This library is implemented through table <a name="pdf-os"><code>os</code></a>.
7925 <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
7929 Returns an approximation of the amount in seconds of CPU time
7930 used by the program.
7936 <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
7940 Returns a string or a table containing date and time,
7941 formatted according to the given string <code>format</code>.
7945 If the <code>time</code> argument is present,
7946 this is the time to be formatted
7947 (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
7948 Otherwise, <code>date</code> formats the current time.
7952 If <code>format</code> starts with '<code>!</code>',
7953 then the date is formatted in Coordinated Universal Time.
7954 After this optional character,
7955 if <code>format</code> is the string "<code>*t</code>",
7956 then <code>date</code> returns a table with the following fields:
7957 <code>year</code> (four digits), <code>month</code> (1--12), <code>day</code> (1--31),
7958 <code>hour</code> (0--23), <code>min</code> (0--59), <code>sec</code> (0--61),
7959 <code>wday</code> (weekday, Sunday is&nbsp;1),
7960 <code>yday</code> (day of the year),
7961 and <code>isdst</code> (daylight saving flag, a boolean).
7965 If <code>format</code> is not "<code>*t</code>",
7966 then <code>date</code> returns the date as a string,
7967 formatted according to the same rules as the C&nbsp;function <code>strftime</code>.
7971 When called without arguments,
7972 <code>date</code> returns a reasonable date and time representation that depends on
7973 the host system and on the current locale
7974 (that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
7980 <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
7984 Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
7985 In POSIX, Windows, and some other systems,
7986 this value is exactly <code>t2</code><em>-</em><code>t1</code>.
7992 <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
7996 This function is equivalent to the C&nbsp;function <code>system</code>.
7997 It passes <code>command</code> to be executed by an operating system shell.
7998 It returns a status code, which is system-dependent.
7999 If <code>command</code> is absent, then it returns nonzero if a shell is available
8000 and zero otherwise.
8006 <hr><h3><a name="pdf-os.exit"><code>os.exit ([code])</code></a></h3>
8010 Calls the C&nbsp;function <code>exit</code>,
8011 with an optional <code>code</code>,
8012 to terminate the host program.
8013 The default value for <code>code</code> is the success code.
8019 <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
8023 Returns the value of the process environment variable <code>varname</code>,
8024 or <b>nil</b> if the variable is not defined.
8030 <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
8034 Deletes the file or directory with the given name.
8035 Directories must be empty to be removed.
8036 If this function fails, it returns <b>nil</b>,
8037 plus a string describing the error.
8043 <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
8047 Renames file or directory named <code>oldname</code> to <code>newname</code>.
8048 If this function fails, it returns <b>nil</b>,
8049 plus a string describing the error.
8055 <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
8059 Sets the current locale of the program.
8060 <code>locale</code> is a string specifying a locale;
8061 <code>category</code> is an optional string describing which category to change:
8062 <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
8063 <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
8064 the default category is <code>"all"</code>.
8065 The function returns the name of the new locale,
8066 or <b>nil</b> if the request cannot be honored.
8070 If <code>locale</code> is the empty string,
8071 the current locale is set to an implementation-defined native locale.
8072 If <code>locale</code> is the string "<code>C</code>",
8073 the current locale is set to the standard C locale.
8077 When called with <b>nil</b> as the first argument,
8078 this function only returns the name of the current locale
8079 for the given category.
8085 <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
8089 Returns the current time when called without arguments,
8090 or a time representing the date and time specified by the given table.
8091 This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
8092 and may have fields <code>hour</code>, <code>min</code>, <code>sec</code>, and <code>isdst</code>
8093 (for a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function).
8097 The returned value is a number, whose meaning depends on your system.
8098 In POSIX, Windows, and some other systems, this number counts the number
8099 of seconds since some given start time (the "epoch").
8100 In other systems, the meaning is not specified,
8101 and the number returned by <code>time</code> can be used only as an argument to
8102 <code>date</code> and <code>difftime</code>.
8108 <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
8112 Returns a string with a file name that can
8113 be used for a temporary file.
8114 The file must be explicitly opened before its use
8115 and explicitly removed when no longer needed.
8123 <h2>5.9 - <a name="5.9">The Debug Library</a></h2>
8126 This library provides
8127 the functionality of the debug interface to Lua programs.
8128 You should exert care when using this library.
8129 The functions provided here should be used exclusively for debugging
8130 and similar tasks, such as profiling.
8131 Please resist the temptation to use them as a
8132 usual programming tool:
8133 they can be very slow.
8134 Moreover, several of these functions
8135 violate some assumptions about Lua code
8136 (e.g., that variables local to a function
8137 cannot be accessed from outside or
8138 that userdata metatables cannot be changed by Lua code)
8139 and therefore can compromise otherwise secure code.
8143 All functions in this library are provided
8144 inside the <a name="pdf-debug"><code>debug</code></a> table.
8145 All functions that operate over a thread
8146 have an optional first argument which is the
8147 thread to operate over.
8148 The default is always the current thread.
8152 <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
8156 Enters an interactive mode with the user,
8157 running each string that the user enters.
8158 Using simple commands and other debug facilities,
8159 the user can inspect global and local variables,
8160 change their values, evaluate expressions, and so on.
8161 A line containing only the word <code>cont</code> finishes this function,
8162 so that the caller continues its execution.
8166 Note that commands for <code>debug.debug</code> are not lexically nested
8167 within any function, and so have no direct access to local variables.
8173 <hr><h3><a name="pdf-debug.getfenv"><code>debug.getfenv (o)</code></a></h3>
8174 Returns the environment of object <code>o</code>.
8180 <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
8184 Returns the current hook settings of the thread, as three values:
8185 the current hook function, the current hook mask,
8186 and the current hook count
8187 (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
8193 <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] function [, what])</code></a></h3>
8197 Returns a table with information about a function.
8198 You can give the function directly,
8199 or you can give a number as the value of <code>function</code>,
8200 which means the function running at level <code>function</code> of the call stack
8201 of the given thread:
8202 level&nbsp;0 is the current function (<code>getinfo</code> itself);
8203 level&nbsp;1 is the function that called <code>getinfo</code>;
8204 and so on.
8205 If <code>function</code> is a number larger than the number of active functions,
8206 then <code>getinfo</code> returns <b>nil</b>.
8210 The returned table may contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
8211 with the string <code>what</code> describing which fields to fill in.
8212 The default for <code>what</code> is to get all information available,
8213 except the table of valid lines.
8214 If present,
8215 the option '<code>f</code>'
8216 adds a field named <code>func</code> with the function itself.
8217 If present,
8218 the option '<code>L</code>'
8219 adds a field named <code>activelines</code> with the table of
8220 valid lines.
8224 For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
8225 a table with a name for the current function,
8226 if a reasonable name can be found,
8227 and the expression <code>debug.getinfo(print)</code>
8228 returns a table with all available information
8229 about the <a href="#pdf-print"><code>print</code></a> function.
8235 <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] level, local)</code></a></h3>
8239 This function returns the name and the value of the local variable
8240 with index <code>local</code> of the function at level <code>level</code> of the stack.
8241 (The first parameter or local variable has index&nbsp;1, and so on,
8242 until the last active local variable.)
8243 The function returns <b>nil</b> if there is no local
8244 variable with the given index,
8245 and raises an error when called with a <code>level</code> out of range.
8246 (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
8250 Variable names starting with '<code>(</code>' (open parentheses)
8251 represent internal variables
8252 (loop control variables, temporaries, and C&nbsp;function locals).
8258 <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (object)</code></a></h3>
8262 Returns the metatable of the given <code>object</code>
8263 or <b>nil</b> if it does not have a metatable.
8269 <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
8273 Returns the registry table (see <a href="#3.5">&sect;3.5</a>).
8279 <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (func, up)</code></a></h3>
8283 This function returns the name and the value of the upvalue
8284 with index <code>up</code> of the function <code>func</code>.
8285 The function returns <b>nil</b> if there is no upvalue with the given index.
8291 <hr><h3><a name="pdf-debug.setfenv"><code>debug.setfenv (object, table)</code></a></h3>
8295 Sets the environment of the given <code>object</code> to the given <code>table</code>.
8296 Returns <code>object</code>.
8302 <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
8306 Sets the given function as a hook.
8307 The string <code>mask</code> and the number <code>count</code> describe
8308 when the hook will be called.
8309 The string mask may have the following characters,
8310 with the given meaning:
8312 <ul>
8313 <li><b><code>"c"</code>:</b> the hook is called every time Lua calls a function;</li>
8314 <li><b><code>"r"</code>:</b> the hook is called every time Lua returns from a function;</li>
8315 <li><b><code>"l"</code>:</b> the hook is called every time Lua enters a new line of code.</li>
8316 </ul><p>
8317 With a <code>count</code> different from zero,
8318 the hook is called after every <code>count</code> instructions.
8322 When called without arguments,
8323 <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
8327 When the hook is called, its first parameter is a string
8328 describing the event that has triggered its call:
8329 <code>"call"</code>, <code>"return"</code> (or <code>"tail return"</code>),
8330 <code>"line"</code>, and <code>"count"</code>.
8331 For line events,
8332 the hook also gets the new line number as its second parameter.
8333 Inside a hook,
8334 you can call <code>getinfo</code> with level&nbsp;2 to get more information about
8335 the running function
8336 (level&nbsp;0 is the <code>getinfo</code> function,
8337 and level&nbsp;1 is the hook function),
8338 unless the event is <code>"tail return"</code>.
8339 In this case, Lua is only simulating the return,
8340 and a call to <code>getinfo</code> will return invalid data.
8346 <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
8350 This function assigns the value <code>value</code> to the local variable
8351 with index <code>local</code> of the function at level <code>level</code> of the stack.
8352 The function returns <b>nil</b> if there is no local
8353 variable with the given index,
8354 and raises an error when called with a <code>level</code> out of range.
8355 (You can call <code>getinfo</code> to check whether the level is valid.)
8356 Otherwise, it returns the name of the local variable.
8362 <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (object, table)</code></a></h3>
8366 Sets the metatable for the given <code>object</code> to the given <code>table</code>
8367 (which can be <b>nil</b>).
8373 <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (func, up, value)</code></a></h3>
8377 This function assigns the value <code>value</code> to the upvalue
8378 with index <code>up</code> of the function <code>func</code>.
8379 The function returns <b>nil</b> if there is no upvalue
8380 with the given index.
8381 Otherwise, it returns the name of the upvalue.
8387 <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message] [, level])</code></a></h3>
8391 Returns a string with a traceback of the call stack.
8392 An optional <code>message</code> string is appended
8393 at the beginning of the traceback.
8394 An optional <code>level</code> number tells at which level
8395 to start the traceback
8396 (default is 1, the function calling <code>traceback</code>).
8404 <h1>6 - <a name="6">Lua Stand-alone</a></h1>
8407 Although Lua has been designed as an extension language,
8408 to be embedded in a host C&nbsp;program,
8409 it is also frequently used as a stand-alone language.
8410 An interpreter for Lua as a stand-alone language,
8411 called simply <code>lua</code>,
8412 is provided with the standard distribution.
8413 The stand-alone interpreter includes
8414 all standard libraries, including the debug library.
8415 Its usage is:
8417 <pre>
8418 lua [options] [script [args]]
8419 </pre><p>
8420 The options are:
8422 <ul>
8423 <li><b><code>-e <em>stat</em></code>:</b> executes string <em>stat</em>;</li>
8424 <li><b><code>-l <em>mod</em></code>:</b> "requires" <em>mod</em>;</li>
8425 <li><b><code>-i</code>:</b> enters interactive mode after running <em>script</em>;</li>
8426 <li><b><code>-v</code>:</b> prints version information;</li>
8427 <li><b><code>--</code>:</b> stops handling options;</li>
8428 <li><b><code>-</code>:</b> executes <code>stdin</code> as a file and stops handling options.</li>
8429 </ul><p>
8430 After handling its options, <code>lua</code> runs the given <em>script</em>,
8431 passing to it the given <em>args</em> as string arguments.
8432 When called without arguments,
8433 <code>lua</code> behaves as <code>lua -v -i</code>
8434 when the standard input (<code>stdin</code>) is a terminal,
8435 and as <code>lua -</code> otherwise.
8439 Before running any argument,
8440 the interpreter checks for an environment variable <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a>.
8441 If its format is <code>@<em>filename</em></code>,
8442 then <code>lua</code> executes the file.
8443 Otherwise, <code>lua</code> executes the string itself.
8447 All options are handled in order, except <code>-i</code>.
8448 For instance, an invocation like
8450 <pre>
8451 $ lua -e'a=1' -e 'print(a)' script.lua
8452 </pre><p>
8453 will first set <code>a</code> to 1, then print the value of <code>a</code> (which is '<code>1</code>'),
8454 and finally run the file <code>script.lua</code> with no arguments.
8455 (Here <code>$</code> is the shell prompt. Your prompt may be different.)
8459 Before starting to run the script,
8460 <code>lua</code> collects all arguments in the command line
8461 in a global table called <code>arg</code>.
8462 The script name is stored at index 0,
8463 the first argument after the script name goes to index 1,
8464 and so on.
8465 Any arguments before the script name
8466 (that is, the interpreter name plus the options)
8467 go to negative indices.
8468 For instance, in the call
8470 <pre>
8471 $ lua -la b.lua t1 t2
8472 </pre><p>
8473 the interpreter first runs the file <code>a.lua</code>,
8474 then creates a table
8476 <pre>
8477 arg = { [-2] = "lua", [-1] = "-la",
8478 [0] = "b.lua",
8479 [1] = "t1", [2] = "t2" }
8480 </pre><p>
8481 and finally runs the file <code>b.lua</code>.
8482 The script is called with <code>arg[1]</code>, <code>arg[2]</code>, &middot;&middot;&middot;
8483 as arguments;
8484 it can also access these arguments with the vararg expression '<code>...</code>'.
8488 In interactive mode,
8489 if you write an incomplete statement,
8490 the interpreter waits for its completion
8491 by issuing a different prompt.
8495 If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
8496 then its value is used as the prompt.
8497 Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
8498 its value is used as the secondary prompt
8499 (issued during incomplete statements).
8500 Therefore, both prompts can be changed directly on the command line
8501 or in any Lua programs by assigning to <code>_PROMPT</code>.
8502 See the next example:
8504 <pre>
8505 $ lua -e"_PROMPT='myprompt&gt; '" -i
8506 </pre><p>
8507 (The outer pair of quotes is for the shell,
8508 the inner pair is for Lua.)
8509 Note the use of <code>-i</code> to enter interactive mode;
8510 otherwise,
8511 the program would just end silently
8512 right after the assignment to <code>_PROMPT</code>.
8516 To allow the use of Lua as a
8517 script interpreter in Unix systems,
8518 the stand-alone interpreter skips
8519 the first line of a chunk if it starts with <code>#</code>.
8520 Therefore, Lua scripts can be made into executable programs
8521 by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
8522 as in
8524 <pre>
8525 #!/usr/local/bin/lua
8526 </pre><p>
8527 (Of course,
8528 the location of the Lua interpreter may be different in your machine.
8529 If <code>lua</code> is in your <code>PATH</code>,
8530 then
8532 <pre>
8533 #!/usr/bin/env lua
8534 </pre><p>
8535 is a more portable solution.)
8539 <h1>7 - <a name="7">Incompatibilities with the Previous Version</a></h1>
8542 Here we list the incompatibilities that you may find when moving a program
8543 from Lua&nbsp;5.0 to Lua&nbsp;5.1.
8544 You can avoid most of the incompatibilities compiling Lua with
8545 appropriate options (see file <code>luaconf.h</code>).
8546 However,
8547 all these compatibility options will be removed in the next version of Lua.
8551 <h2>7.1 - <a name="7.1">Changes in the Language</a></h2>
8552 <ul>
8554 <li>
8555 The vararg system changed from the pseudo-argument <code>arg</code> with a
8556 table with the extra arguments to the vararg expression.
8557 (See compile-time option <code>LUA_COMPAT_VARARG</code> in <code>luaconf.h</code>.)
8558 </li>
8560 <li>
8561 There was a subtle change in the scope of the implicit
8562 variables of the <b>for</b> statement and for the <b>repeat</b> statement.
8563 </li>
8565 <li>
8566 The long string/long comment syntax (<code>[[<em>string</em>]]</code>)
8567 does not allow nesting.
8568 You can use the new syntax (<code>[=[<em>string</em>]=]</code>) in these cases.
8569 (See compile-time option <code>LUA_COMPAT_LSTR</code> in <code>luaconf.h</code>.)
8570 </li>
8572 </ul>
8577 <h2>7.2 - <a name="7.2">Changes in the Libraries</a></h2>
8578 <ul>
8580 <li>
8581 Function <code>string.gfind</code> was renamed <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>.
8582 (See compile-time option <code>LUA_COMPAT_GFIND</code> in <code>luaconf.h</code>.)
8583 </li>
8585 <li>
8586 When <a href="#pdf-string.gsub"><code>string.gsub</code></a> is called with a function as its
8587 third argument,
8588 whenever this function returns <b>nil</b> or <b>false</b> the
8589 replacement string is the whole match,
8590 instead of the empty string.
8591 </li>
8593 <li>
8594 Function <code>table.setn</code> was deprecated.
8595 Function <code>table.getn</code> corresponds
8596 to the new length operator (<code>#</code>);
8597 use the operator instead of the function.
8598 (See compile-time option <code>LUA_COMPAT_GETN</code> in <code>luaconf.h</code>.)
8599 </li>
8601 <li>
8602 Function <code>loadlib</code> was renamed <a href="#pdf-package.loadlib"><code>package.loadlib</code></a>.
8603 (See compile-time option <code>LUA_COMPAT_LOADLIB</code> in <code>luaconf.h</code>.)
8604 </li>
8606 <li>
8607 Function <code>math.mod</code> was renamed <a href="#pdf-math.fmod"><code>math.fmod</code></a>.
8608 (See compile-time option <code>LUA_COMPAT_MOD</code> in <code>luaconf.h</code>.)
8609 </li>
8611 <li>
8612 Functions <code>table.foreach</code> and <code>table.foreachi</code> are deprecated.
8613 You can use a for loop with <code>pairs</code> or <code>ipairs</code> instead.
8614 </li>
8616 <li>
8617 There were substantial changes in function <a href="#pdf-require"><code>require</code></a> due to
8618 the new module system.
8619 However, the new behavior is mostly compatible with the old,
8620 but <code>require</code> gets the path from <a href="#pdf-package.path"><code>package.path</code></a> instead
8621 of from <code>LUA_PATH</code>.
8622 </li>
8624 <li>
8625 Function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> has different arguments.
8626 Function <code>gcinfo</code> is deprecated;
8627 use <code>collectgarbage("count")</code> instead.
8628 </li>
8630 </ul>
8635 <h2>7.3 - <a name="7.3">Changes in the API</a></h2>
8636 <ul>
8638 <li>
8639 The <code>luaopen_*</code> functions (to open libraries)
8640 cannot be called directly,
8641 like a regular C function.
8642 They must be called through Lua,
8643 like a Lua function.
8644 </li>
8646 <li>
8647 Function <code>lua_open</code> was replaced by <a href="#lua_newstate"><code>lua_newstate</code></a> to
8648 allow the user to set a memory-allocation function.
8649 You can use <a href="#luaL_newstate"><code>luaL_newstate</code></a> from the standard library to
8650 create a state with a standard allocation function
8651 (based on <code>realloc</code>).
8652 </li>
8654 <li>
8655 Functions <code>luaL_getn</code> and <code>luaL_setn</code>
8656 (from the auxiliary library) are deprecated.
8657 Use <a href="#lua_objlen"><code>lua_objlen</code></a> instead of <code>luaL_getn</code>
8658 and nothing instead of <code>luaL_setn</code>.
8659 </li>
8661 <li>
8662 Function <code>luaL_openlib</code> was replaced by <a href="#luaL_register"><code>luaL_register</code></a>.
8663 </li>
8665 <li>
8666 Function <code>luaL_checkudata</code> now throws an error when the given value
8667 is not a userdata of the expected type.
8668 (In Lua&nbsp;5.0 it returned <code>NULL</code>.)
8669 </li>
8671 </ul>
8676 <h1>8 - <a name="8">The Complete Syntax of Lua</a></h1>
8679 Here is the complete syntax of Lua in extended BNF.
8680 (It does not describe operator precedences.)
8685 <pre>
8687 chunk ::= {stat [`<b>;</b>&acute;]} [laststat [`<b>;</b>&acute;]]
8689 block ::= chunk
8691 stat ::= varlist `<b>=</b>&acute; explist |
8692 functioncall |
8693 <b>do</b> block <b>end</b> |
8694 <b>while</b> exp <b>do</b> block <b>end</b> |
8695 <b>repeat</b> block <b>until</b> exp |
8696 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
8697 <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b> |
8698 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
8699 <b>function</b> funcname funcbody |
8700 <b>local</b> <b>function</b> Name funcbody |
8701 <b>local</b> namelist [`<b>=</b>&acute; explist]
8703 laststat ::= <b>return</b> [explist] | <b>break</b>
8705 funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
8707 varlist ::= var {`<b>,</b>&acute; var}
8709 var ::= Name | prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute; | prefixexp `<b>.</b>&acute; Name
8711 namelist ::= Name {`<b>,</b>&acute; Name}
8713 explist ::= {exp `<b>,</b>&acute;} exp
8715 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | `<b>...</b>&acute; | function |
8716 prefixexp | tableconstructor | exp binop exp | unop exp
8718 prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
8720 functioncall ::= prefixexp args | prefixexp `<b>:</b>&acute; Name args
8722 args ::= `<b>(</b>&acute; [explist] `<b>)</b>&acute; | tableconstructor | String
8724 function ::= <b>function</b> funcbody
8726 funcbody ::= `<b>(</b>&acute; [parlist] `<b>)</b>&acute; block <b>end</b>
8728 parlist ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
8730 tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
8732 fieldlist ::= field {fieldsep field} [fieldsep]
8734 field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
8736 fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
8738 binop ::= `<b>+</b>&acute; | `<b>-</b>&acute; | `<b>*</b>&acute; | `<b>/</b>&acute; | `<b>^</b>&acute; | `<b>%</b>&acute; | `<b>..</b>&acute; |
8739 `<b>&lt;</b>&acute; | `<b>&lt;=</b>&acute; | `<b>&gt;</b>&acute; | `<b>&gt;=</b>&acute; | `<b>==</b>&acute; | `<b>~=</b>&acute; |
8740 <b>and</b> | <b>or</b>
8742 unop ::= `<b>-</b>&acute; | <b>not</b> | `<b>#</b>&acute;
8744 </pre>
8754 <HR>
8755 <SMALL>
8756 Last update:
8757 Fri Jan 18 22:32:24 BRST 2008
8758 </SMALL>
8759 <!--
8760 Last change: revised for Lua 5.1.3
8763 </body></html>