release.sh changes & fixes
[minix3.git] / external / mit / lua / dist / doc / manual.html
bloba8c88c412dcf9eba11ba85c76cdd726a74f46cf3
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" type="text/css" href="lua.css">
7 <link rel="stylesheet" type="text/css" 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&ndash;2012 Lua.org, PUC-Rio.
23 Freely available under the terms of the
24 <a href="http://www.lua.org/license.html">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>
32 &middot;
33 <A HREF="http://www.lua.org/manual/">other versions</A>
35 <!-- ====================================================================== -->
36 <p>
38 <!-- $Id: manual.html,v 1.1.1.2 2012/03/15 00:08:20 alnsn Exp $ -->
43 <h1>1 - <a name="1">Introduction</a></h1>
45 <p>
46 Lua is an extension programming language designed to support
47 general procedural programming with data description
48 facilities.
49 It also offers good support for object-oriented programming,
50 functional programming, and data-driven programming.
51 Lua is intended to be used as a powerful, light-weight
52 scripting language for any program that needs one.
53 Lua is implemented as a library, written in <em>clean</em> C
54 (that is, in the common subset of ANSI&nbsp;C and C++).
57 <p>
58 Being an extension language, Lua has no notion of a "main" program:
59 it only works <em>embedded</em> in a host client,
60 called the <em>embedding program</em> or simply the <em>host</em>.
61 This host program can invoke functions to execute a piece of Lua code,
62 can write and read Lua variables,
63 and can register C&nbsp;functions to be called by Lua code.
64 Through the use of C&nbsp;functions, Lua can be augmented to cope with
65 a wide range of different domains,
66 thus creating customized programming languages sharing a syntactical framework.
67 The Lua distribution includes a sample host program called <code>lua</code>,
68 which uses the Lua library to offer a complete, stand-alone Lua interpreter.
71 <p>
72 Lua is free software,
73 and is provided as usual with no guarantees,
74 as stated in its license.
75 The implementation described in this manual is available
76 at Lua's official web site, <code>www.lua.org</code>.
79 <p>
80 Like any other reference manual,
81 this document is dry in places.
82 For a discussion of the decisions behind the design of Lua,
83 see the technical papers available at Lua's web site.
84 For a detailed introduction to programming in Lua,
85 see Roberto's book, <em>Programming in Lua (Second Edition)</em>.
89 <h1>2 - <a name="2">The Language</a></h1>
91 <p>
92 This section describes the lexis, the syntax, and the semantics of Lua.
93 In other words,
94 this section describes
95 which tokens are valid,
96 how they can be combined,
97 and what their combinations mean.
101 The language constructs will be explained using the usual extended BNF notation,
102 in which
103 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
104 [<em>a</em>]&nbsp;means an optional <em>a</em>.
105 Non-terminals are shown like non-terminal,
106 keywords are shown like <b>kword</b>,
107 and other terminal symbols are shown like `<b>=</b>&acute;.
108 The complete syntax of Lua can be found in <a href="#8">&sect;8</a>
109 at the end of this manual.
113 <h2>2.1 - <a name="2.1">Lexical Conventions</a></h2>
116 <em>Names</em>
117 (also called <em>identifiers</em>)
118 in Lua can be any string of letters,
119 digits, and underscores,
120 not beginning with a digit.
121 This coincides with the definition of names in most languages.
122 (The definition of letter depends on the current locale:
123 any character considered alphabetic by the current locale
124 can be used in an identifier.)
125 Identifiers are used to name variables and table fields.
129 The following <em>keywords</em> are reserved
130 and cannot be used as names:
133 <pre>
134 and break do else elseif
135 end false for function if
136 in local nil not or
137 repeat return then true until while
138 </pre>
141 Lua is a case-sensitive language:
142 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
143 are two different, valid names.
144 As a convention, names starting with an underscore followed by
145 uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
146 are reserved for internal global variables used by Lua.
150 The following strings denote other tokens:
152 <pre>
153 + - * / % ^ #
154 == ~= &lt;= &gt;= &lt; &gt; =
155 ( ) { } [ ]
156 ; : , . .. ...
157 </pre>
160 <em>Literal strings</em>
161 can be delimited by matching single or double quotes,
162 and can contain the following C-like escape sequences:
163 '<code>\a</code>' (bell),
164 '<code>\b</code>' (backspace),
165 '<code>\f</code>' (form feed),
166 '<code>\n</code>' (newline),
167 '<code>\r</code>' (carriage return),
168 '<code>\t</code>' (horizontal tab),
169 '<code>\v</code>' (vertical tab),
170 '<code>\\</code>' (backslash),
171 '<code>\"</code>' (quotation mark [double quote]),
172 and '<code>\'</code>' (apostrophe [single quote]).
173 Moreover, a backslash followed by a real newline
174 results in a newline in the string.
175 A character in a string can also be specified by its numerical value
176 using the escape sequence <code>\<em>ddd</em></code>,
177 where <em>ddd</em> is a sequence of up to three decimal digits.
178 (Note that if a numerical escape is to be followed by a digit,
179 it must be expressed using exactly three digits.)
180 Strings in Lua can contain any 8-bit value, including embedded zeros,
181 which can be specified as '<code>\0</code>'.
185 Literal strings can also be defined using a long format
186 enclosed by <em>long brackets</em>.
187 We define an <em>opening long bracket of level <em>n</em></em> as an opening
188 square bracket followed by <em>n</em> equal signs followed by another
189 opening square bracket.
190 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
191 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
192 and so on.
193 A <em>closing long bracket</em> is defined similarly;
194 for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
195 A long string starts with an opening long bracket of any level and
196 ends at the first closing long bracket of the same level.
197 Literals in this bracketed form can run for several lines,
198 do not interpret any escape sequences,
199 and ignore long brackets of any other level.
200 They can contain anything except a closing bracket of the proper level.
204 For convenience,
205 when the opening long bracket is immediately followed by a newline,
206 the newline is not included in the string.
207 As an example, in a system using ASCII
208 (in which '<code>a</code>' is coded as&nbsp;97,
209 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
210 the five literal strings below denote the same string:
212 <pre>
213 a = 'alo\n123"'
214 a = "alo\n123\""
215 a = '\97lo\10\04923"'
216 a = [[alo
217 123"]]
218 a = [==[
220 123"]==]
221 </pre>
224 A <em>numerical constant</em> can be written with an optional decimal part
225 and an optional decimal exponent.
226 Lua also accepts integer hexadecimal constants,
227 by prefixing them with <code>0x</code>.
228 Examples of valid numerical constants are
230 <pre>
231 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
232 </pre>
235 A <em>comment</em> starts with a double hyphen (<code>--</code>)
236 anywhere outside a string.
237 If the text immediately after <code>--</code> is not an opening long bracket,
238 the comment is a <em>short comment</em>,
239 which runs until the end of the line.
240 Otherwise, it is a <em>long comment</em>,
241 which runs until the corresponding closing long bracket.
242 Long comments are frequently used to disable code temporarily.
248 <h2>2.2 - <a name="2.2">Values and Types</a></h2>
251 Lua is a <em>dynamically typed language</em>.
252 This means that
253 variables do not have types; only values do.
254 There are no type definitions in the language.
255 All values carry their own type.
259 All values in Lua are <em>first-class values</em>.
260 This means that all values can be stored in variables,
261 passed as arguments to other functions, and returned as results.
265 There are eight basic types in Lua:
266 <em>nil</em>, <em>boolean</em>, <em>number</em>,
267 <em>string</em>, <em>function</em>, <em>userdata</em>,
268 <em>thread</em>, and <em>table</em>.
269 <em>Nil</em> is the type of the value <b>nil</b>,
270 whose main property is to be different from any other value;
271 it usually represents the absence of a useful value.
272 <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
273 Both <b>nil</b> and <b>false</b> make a condition false;
274 any other value makes it true.
275 <em>Number</em> represents real (double-precision floating-point) numbers.
276 (It is easy to build Lua interpreters that use other
277 internal representations for numbers,
278 such as single-precision float or long integers;
279 see file <code>luaconf.h</code>.)
280 <em>String</em> represents arrays of characters.
282 Lua is 8-bit clean:
283 strings can contain any 8-bit character,
284 including embedded zeros ('<code>\0</code>') (see <a href="#2.1">&sect;2.1</a>).
288 Lua can call (and manipulate) functions written in Lua and
289 functions written in C
290 (see <a href="#2.5.8">&sect;2.5.8</a>).
294 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
295 be stored in Lua variables.
296 This type corresponds to a block of raw memory
297 and has no pre-defined operations in Lua,
298 except assignment and identity test.
299 However, by using <em>metatables</em>,
300 the programmer can define operations for userdata values
301 (see <a href="#2.8">&sect;2.8</a>).
302 Userdata values cannot be created or modified in Lua,
303 only through the C&nbsp;API.
304 This guarantees the integrity of data owned by the host program.
308 The type <em>thread</em> represents independent threads of execution
309 and it is used to implement coroutines (see <a href="#2.11">&sect;2.11</a>).
310 Do not confuse Lua threads with operating-system threads.
311 Lua supports coroutines on all systems,
312 even those that do not support threads.
316 The type <em>table</em> implements associative arrays,
317 that is, arrays that can be indexed not only with numbers,
318 but with any value (except <b>nil</b>).
319 Tables can be <em>heterogeneous</em>;
320 that is, they can contain values of all types (except <b>nil</b>).
321 Tables are the sole data structuring mechanism in Lua;
322 they can be used to represent ordinary arrays,
323 symbol tables, sets, records, graphs, trees, etc.
324 To represent records, Lua uses the field name as an index.
325 The language supports this representation by
326 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
327 There are several convenient ways to create tables in Lua
328 (see <a href="#2.5.7">&sect;2.5.7</a>).
332 Like indices,
333 the value of a table field can be of any type (except <b>nil</b>).
334 In particular,
335 because functions are first-class values,
336 table fields can contain functions.
337 Thus tables can also carry <em>methods</em> (see <a href="#2.5.9">&sect;2.5.9</a>).
341 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
342 variables do not actually <em>contain</em> these values,
343 only <em>references</em> to them.
344 Assignment, parameter passing, and function returns
345 always manipulate references to such values;
346 these operations do not imply any kind of copy.
350 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
351 of a given value.
355 <h3>2.2.1 - <a name="2.2.1">Coercion</a></h3>
358 Lua provides automatic conversion between
359 string and number values at run time.
360 Any arithmetic operation applied to a string tries to convert
361 this string to a number, following the usual conversion rules.
362 Conversely, whenever a number is used where a string is expected,
363 the number is converted to a string, in a reasonable format.
364 For complete control over how numbers are converted to strings,
365 use the <code>format</code> function from the string library
366 (see <a href="#pdf-string.format"><code>string.format</code></a>).
374 <h2>2.3 - <a name="2.3">Variables</a></h2>
377 Variables are places that store values.
379 There are three kinds of variables in Lua:
380 global variables, local variables, and table fields.
384 A single name can denote a global variable or a local variable
385 (or a function's formal parameter,
386 which is a particular kind of local variable):
388 <pre>
389 var ::= Name
390 </pre><p>
391 Name denotes identifiers, as defined in <a href="#2.1">&sect;2.1</a>.
395 Any variable is assumed to be global unless explicitly declared
396 as a local (see <a href="#2.4.7">&sect;2.4.7</a>).
397 Local variables are <em>lexically scoped</em>:
398 local variables can be freely accessed by functions
399 defined inside their scope (see <a href="#2.6">&sect;2.6</a>).
403 Before the first assignment to a variable, its value is <b>nil</b>.
407 Square brackets are used to index a table:
409 <pre>
410 var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
411 </pre><p>
412 The meaning of accesses to global variables
413 and table fields can be changed via metatables.
414 An access to an indexed variable <code>t[i]</code> is equivalent to
415 a call <code>gettable_event(t,i)</code>.
416 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
417 <code>gettable_event</code> function.
418 This function is not defined or callable in Lua.
419 We use it here only for explanatory purposes.)
423 The syntax <code>var.Name</code> is just syntactic sugar for
424 <code>var["Name"]</code>:
426 <pre>
427 var ::= prefixexp `<b>.</b>&acute; Name
428 </pre>
431 All global variables live as fields in ordinary Lua tables,
432 called <em>environment tables</em> or simply
433 <em>environments</em> (see <a href="#2.9">&sect;2.9</a>).
434 Each function has its own reference to an environment,
435 so that all global variables in this function
436 will refer to this environment table.
437 When a function is created,
438 it inherits the environment from the function that created it.
439 To get the environment table of a Lua function,
440 you call <a href="#pdf-getfenv"><code>getfenv</code></a>.
441 To replace it,
442 you call <a href="#pdf-setfenv"><code>setfenv</code></a>.
443 (You can only manipulate the environment of C&nbsp;functions
444 through the debug library; (see <a href="#5.9">&sect;5.9</a>).)
448 An access to a global variable <code>x</code>
449 is equivalent to <code>_env.x</code>,
450 which in turn is equivalent to
452 <pre>
453 gettable_event(_env, "x")
454 </pre><p>
455 where <code>_env</code> is the environment of the running function.
456 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
457 <code>gettable_event</code> function.
458 This function is not defined or callable in Lua.
459 Similarly, the <code>_env</code> variable is not defined in Lua.
460 We use them here only for explanatory purposes.)
466 <h2>2.4 - <a name="2.4">Statements</a></h2>
469 Lua supports an almost conventional set of statements,
470 similar to those in Pascal or C.
471 This set includes
472 assignments, control structures, function calls,
473 and variable declarations.
477 <h3>2.4.1 - <a name="2.4.1">Chunks</a></h3>
480 The unit of execution of Lua is called a <em>chunk</em>.
481 A chunk is simply a sequence of statements,
482 which are executed sequentially.
483 Each statement can be optionally followed by a semicolon:
485 <pre>
486 chunk ::= {stat [`<b>;</b>&acute;]}
487 </pre><p>
488 There are no empty statements and thus '<code>;;</code>' is not legal.
492 Lua handles a chunk as the body of an anonymous function
493 with a variable number of arguments
494 (see <a href="#2.5.9">&sect;2.5.9</a>).
495 As such, chunks can define local variables,
496 receive arguments, and return values.
500 A chunk can be stored in a file or in a string inside the host program.
501 To execute a chunk,
502 Lua first pre-compiles the chunk into instructions for a virtual machine,
503 and then it executes the compiled code
504 with an interpreter for the virtual machine.
508 Chunks can also be pre-compiled into binary form;
509 see program <code>luac</code> for details.
510 Programs in source and compiled forms are interchangeable;
511 Lua automatically detects the file type and acts accordingly.
518 <h3>2.4.2 - <a name="2.4.2">Blocks</a></h3><p>
519 A block is a list of statements;
520 syntactically, a block is the same as a chunk:
522 <pre>
523 block ::= chunk
524 </pre>
527 A block can be explicitly delimited to produce a single statement:
529 <pre>
530 stat ::= <b>do</b> block <b>end</b>
531 </pre><p>
532 Explicit blocks are useful
533 to control the scope of variable declarations.
534 Explicit blocks are also sometimes used to
535 add a <b>return</b> or <b>break</b> statement in the middle
536 of another block (see <a href="#2.4.4">&sect;2.4.4</a>).
542 <h3>2.4.3 - <a name="2.4.3">Assignment</a></h3>
545 Lua allows multiple assignments.
546 Therefore, the syntax for assignment
547 defines a list of variables on the left side
548 and a list of expressions on the right side.
549 The elements in both lists are separated by commas:
551 <pre>
552 stat ::= varlist `<b>=</b>&acute; explist
553 varlist ::= var {`<b>,</b>&acute; var}
554 explist ::= exp {`<b>,</b>&acute; exp}
555 </pre><p>
556 Expressions are discussed in <a href="#2.5">&sect;2.5</a>.
560 Before the assignment,
561 the list of values is <em>adjusted</em> to the length of
562 the list of variables.
563 If there are more values than needed,
564 the excess values are thrown away.
565 If there are fewer values than needed,
566 the list is extended with as many <b>nil</b>'s as needed.
567 If the list of expressions ends with a function call,
568 then all values returned by that call enter the list of values,
569 before the adjustment
570 (except when the call is enclosed in parentheses; see <a href="#2.5">&sect;2.5</a>).
574 The assignment statement first evaluates all its expressions
575 and only then are the assignments performed.
576 Thus the code
578 <pre>
579 i = 3
580 i, a[i] = i+1, 20
581 </pre><p>
582 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
583 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
584 before it is assigned&nbsp;4.
585 Similarly, the line
587 <pre>
588 x, y = y, x
589 </pre><p>
590 exchanges the values of <code>x</code> and <code>y</code>,
593 <pre>
594 x, y, z = y, z, x
595 </pre><p>
596 cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
600 The meaning of assignments to global variables
601 and table fields can be changed via metatables.
602 An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
603 <code>settable_event(t,i,val)</code>.
604 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
605 <code>settable_event</code> function.
606 This function is not defined or callable in Lua.
607 We use it here only for explanatory purposes.)
611 An assignment to a global variable <code>x = val</code>
612 is equivalent to the assignment
613 <code>_env.x = val</code>,
614 which in turn is equivalent to
616 <pre>
617 settable_event(_env, "x", val)
618 </pre><p>
619 where <code>_env</code> is the environment of the running function.
620 (The <code>_env</code> variable is not defined in Lua.
621 We use it here only for explanatory purposes.)
627 <h3>2.4.4 - <a name="2.4.4">Control Structures</a></h3><p>
628 The control structures
629 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
630 familiar syntax:
635 <pre>
636 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
637 stat ::= <b>repeat</b> block <b>until</b> exp
638 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
639 </pre><p>
640 Lua also has a <b>for</b> statement, in two flavors (see <a href="#2.4.5">&sect;2.4.5</a>).
644 The condition expression of a
645 control structure can return any value.
646 Both <b>false</b> and <b>nil</b> are considered false.
647 All values different from <b>nil</b> and <b>false</b> are considered true
648 (in particular, the number 0 and the empty string are also true).
652 In the <b>repeat</b>&ndash;<b>until</b> loop,
653 the inner block does not end at the <b>until</b> keyword,
654 but only after the condition.
655 So, the condition can refer to local variables
656 declared inside the loop block.
660 The <b>return</b> statement is used to return values
661 from a function or a chunk (which is just a function).
663 Functions and chunks can return more than one value,
664 and so the syntax for the <b>return</b> statement is
666 <pre>
667 stat ::= <b>return</b> [explist]
668 </pre>
671 The <b>break</b> statement is used to terminate the execution of a
672 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
673 skipping to the next statement after the loop:
676 <pre>
677 stat ::= <b>break</b>
678 </pre><p>
679 A <b>break</b> ends the innermost enclosing loop.
683 The <b>return</b> and <b>break</b>
684 statements can only be written as the <em>last</em> statement of a block.
685 If it is really necessary to <b>return</b> or <b>break</b> in the
686 middle of a block,
687 then an explicit inner block can be used,
688 as in the idioms
689 <code>do return end</code> and <code>do break end</code>,
690 because now <b>return</b> and <b>break</b> are the last statements in
691 their (inner) blocks.
697 <h3>2.4.5 - <a name="2.4.5">For Statement</a></h3>
701 The <b>for</b> statement has two forms:
702 one numeric and one generic.
706 The numeric <b>for</b> loop repeats a block of code while a
707 control variable runs through an arithmetic progression.
708 It has the following syntax:
710 <pre>
711 stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
712 </pre><p>
713 The <em>block</em> is repeated for <em>name</em> starting at the value of
714 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
715 third <em>exp</em>.
716 More precisely, a <b>for</b> statement like
718 <pre>
719 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
720 </pre><p>
721 is equivalent to the code:
723 <pre>
725 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
726 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
727 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
728 local v = <em>var</em>
729 <em>block</em>
730 <em>var</em> = <em>var</em> + <em>step</em>
733 </pre><p>
734 Note the following:
736 <ul>
738 <li>
739 All three control expressions are evaluated only once,
740 before the loop starts.
741 They must all result in numbers.
742 </li>
744 <li>
745 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
746 The names shown here are for explanatory purposes only.
747 </li>
749 <li>
750 If the third expression (the step) is absent,
751 then a step of&nbsp;1 is used.
752 </li>
754 <li>
755 You can use <b>break</b> to exit a <b>for</b> loop.
756 </li>
758 <li>
759 The loop variable <code>v</code> is local to the loop;
760 you cannot use its value after the <b>for</b> ends or is broken.
761 If you need this value,
762 assign it to another variable before breaking or exiting the loop.
763 </li>
765 </ul>
768 The generic <b>for</b> statement works over functions,
769 called <em>iterators</em>.
770 On each iteration, the iterator function is called to produce a new value,
771 stopping when this new value is <b>nil</b>.
772 The generic <b>for</b> loop has the following syntax:
774 <pre>
775 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
776 namelist ::= Name {`<b>,</b>&acute; Name}
777 </pre><p>
778 A <b>for</b> statement like
780 <pre>
781 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
782 </pre><p>
783 is equivalent to the code:
785 <pre>
787 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
788 while true do
789 local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
790 <em>var</em> = <em>var_1</em>
791 if <em>var</em> == nil then break end
792 <em>block</em>
795 </pre><p>
796 Note the following:
798 <ul>
800 <li>
801 <code><em>explist</em></code> is evaluated only once.
802 Its results are an <em>iterator</em> function,
803 a <em>state</em>,
804 and an initial value for the first <em>iterator variable</em>.
805 </li>
807 <li>
808 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
809 The names are here for explanatory purposes only.
810 </li>
812 <li>
813 You can use <b>break</b> to exit a <b>for</b> loop.
814 </li>
816 <li>
817 The loop variables <code><em>var_i</em></code> are local to the loop;
818 you cannot use their values after the <b>for</b> ends.
819 If you need these values,
820 then assign them to other variables before breaking or exiting the loop.
821 </li>
823 </ul>
828 <h3>2.4.6 - <a name="2.4.6">Function Calls as Statements</a></h3><p>
829 To allow possible side-effects,
830 function calls can be executed as statements:
832 <pre>
833 stat ::= functioncall
834 </pre><p>
835 In this case, all returned values are thrown away.
836 Function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>.
842 <h3>2.4.7 - <a name="2.4.7">Local Declarations</a></h3><p>
843 Local variables can be declared anywhere inside a block.
844 The declaration can include an initial assignment:
846 <pre>
847 stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist]
848 </pre><p>
849 If present, an initial assignment has the same semantics
850 of a multiple assignment (see <a href="#2.4.3">&sect;2.4.3</a>).
851 Otherwise, all variables are initialized with <b>nil</b>.
855 A chunk is also a block (see <a href="#2.4.1">&sect;2.4.1</a>),
856 and so local variables can be declared in a chunk outside any explicit block.
857 The scope of such local variables extends until the end of the chunk.
861 The visibility rules for local variables are explained in <a href="#2.6">&sect;2.6</a>.
869 <h2>2.5 - <a name="2.5">Expressions</a></h2>
872 The basic expressions in Lua are the following:
874 <pre>
875 exp ::= prefixexp
876 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
877 exp ::= Number
878 exp ::= String
879 exp ::= function
880 exp ::= tableconstructor
881 exp ::= `<b>...</b>&acute;
882 exp ::= exp binop exp
883 exp ::= unop exp
884 prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
885 </pre>
888 Numbers and literal strings are explained in <a href="#2.1">&sect;2.1</a>;
889 variables are explained in <a href="#2.3">&sect;2.3</a>;
890 function definitions are explained in <a href="#2.5.9">&sect;2.5.9</a>;
891 function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>;
892 table constructors are explained in <a href="#2.5.7">&sect;2.5.7</a>.
893 Vararg expressions,
894 denoted by three dots ('<code>...</code>'), can only be used when
895 directly inside a vararg function;
896 they are explained in <a href="#2.5.9">&sect;2.5.9</a>.
900 Binary operators comprise arithmetic operators (see <a href="#2.5.1">&sect;2.5.1</a>),
901 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>),
902 and the concatenation operator (see <a href="#2.5.4">&sect;2.5.4</a>).
903 Unary operators comprise the unary minus (see <a href="#2.5.1">&sect;2.5.1</a>),
904 the unary <b>not</b> (see <a href="#2.5.3">&sect;2.5.3</a>),
905 and the unary <em>length operator</em> (see <a href="#2.5.5">&sect;2.5.5</a>).
909 Both function calls and vararg expressions can result in multiple values.
910 If an expression is used as a statement
911 (only possible for function calls (see <a href="#2.4.6">&sect;2.4.6</a>)),
912 then its return list is adjusted to zero elements,
913 thus discarding all returned values.
914 If an expression is used as the last (or the only) element
915 of a list of expressions,
916 then no adjustment is made
917 (unless the call is enclosed in parentheses).
918 In all other contexts,
919 Lua adjusts the result list to one element,
920 discarding all values except the first one.
924 Here are some examples:
926 <pre>
927 f() -- adjusted to 0 results
928 g(f(), x) -- f() is adjusted to 1 result
929 g(x, f()) -- g gets x plus all results from f()
930 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
931 a,b = ... -- a gets the first vararg parameter, b gets
932 -- the second (both a and b can get nil if there
933 -- is no corresponding vararg parameter)
935 a,b,c = x, f() -- f() is adjusted to 2 results
936 a,b,c = f() -- f() is adjusted to 3 results
937 return f() -- returns all results from f()
938 return ... -- returns all received vararg parameters
939 return x,y,f() -- returns x, y, and all results from f()
940 {f()} -- creates a list with all results from f()
941 {...} -- creates a list with all vararg parameters
942 {f(), nil} -- f() is adjusted to 1 result
943 </pre>
946 Any expression enclosed in parentheses always results in only one value.
947 Thus,
948 <code>(f(x,y,z))</code> is always a single value,
949 even if <code>f</code> returns several values.
950 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
951 or <b>nil</b> if <code>f</code> does not return any values.)
955 <h3>2.5.1 - <a name="2.5.1">Arithmetic Operators</a></h3><p>
956 Lua supports the usual arithmetic operators:
957 the binary <code>+</code> (addition),
958 <code>-</code> (subtraction), <code>*</code> (multiplication),
959 <code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
960 and unary <code>-</code> (negation).
961 If the operands are numbers, or strings that can be converted to
962 numbers (see <a href="#2.2.1">&sect;2.2.1</a>),
963 then all operations have the usual meaning.
964 Exponentiation works for any exponent.
965 For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
966 Modulo is defined as
968 <pre>
969 a % b == a - math.floor(a/b)*b
970 </pre><p>
971 That is, it is the remainder of a division that rounds
972 the quotient towards minus infinity.
978 <h3>2.5.2 - <a name="2.5.2">Relational Operators</a></h3><p>
979 The relational operators in Lua are
981 <pre>
982 == ~= &lt; &gt; &lt;= &gt;=
983 </pre><p>
984 These operators always result in <b>false</b> or <b>true</b>.
988 Equality (<code>==</code>) first compares the type of its operands.
989 If the types are different, then the result is <b>false</b>.
990 Otherwise, the values of the operands are compared.
991 Numbers and strings are compared in the usual way.
992 Objects (tables, userdata, threads, and functions)
993 are compared by <em>reference</em>:
994 two objects are considered equal only if they are the <em>same</em> object.
995 Every time you create a new object
996 (a table, userdata, thread, or function),
997 this new object is different from any previously existing object.
1001 You can change the way that Lua compares tables and userdata
1002 by using the "eq" metamethod (see <a href="#2.8">&sect;2.8</a>).
1006 The conversion rules of <a href="#2.2.1">&sect;2.2.1</a>
1007 <em>do not</em> apply to equality comparisons.
1008 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
1009 and <code>t[0]</code> and <code>t["0"]</code> denote different
1010 entries in a table.
1014 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
1018 The order operators work as follows.
1019 If both arguments are numbers, then they are compared as such.
1020 Otherwise, if both arguments are strings,
1021 then their values are compared according to the current locale.
1022 Otherwise, Lua tries to call the "lt" or the "le"
1023 metamethod (see <a href="#2.8">&sect;2.8</a>).
1024 A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
1025 and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
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 <code>--&gt;</code> 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> can 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> can 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 A constructor can be used to create an empty table
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 can 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 can refer to different external local variables
1353 and can 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 that last expression 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 can 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 by 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 that is, there is one single metatable for all numbers,
1561 one for all strings, etc.
1565 A metatable controls how an object behaves in arithmetic operations,
1566 order comparisons, concatenation, length operation, and indexing.
1567 A metatable also can 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 Threads are created sharing the environment of the creating thread.
1938 Userdata and C&nbsp;functions are created sharing the environment
1939 of the creating C&nbsp;function.
1940 Non-nested Lua functions
1941 (created by <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>)
1942 are created sharing the environment of the creating thread.
1943 Nested Lua functions are created sharing the environment of
1944 the creating Lua function.
1948 Environments associated with userdata have no meaning for Lua.
1949 It is only a convenience feature for programmers to associate a table to
1950 a userdata.
1954 Environments associated with threads are called
1955 <em>global environments</em>.
1956 They are used as the default environment for threads and
1957 non-nested Lua functions created by the thread
1958 and can be directly accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1962 The environment associated with a C&nbsp;function can be directly
1963 accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1964 It is used as the default environment for other C&nbsp;functions
1965 and userdata created by the function.
1969 Environments associated with Lua functions are used to resolve
1970 all accesses to global variables within the function (see <a href="#2.3">&sect;2.3</a>).
1971 They are used as the default environment for nested Lua functions
1972 created by the function.
1976 You can change the environment of a Lua function or the
1977 running thread by calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
1978 You can get the environment of a Lua function or the running thread
1979 by calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
1980 To manipulate the environment of other objects
1981 (userdata, C&nbsp;functions, other threads) you must
1982 use the C&nbsp;API.
1988 <h2>2.10 - <a name="2.10">Garbage Collection</a></h2>
1991 Lua performs automatic memory management.
1992 This means that
1993 you have to worry neither about allocating memory for new objects
1994 nor about freeing it when the objects are no longer needed.
1995 Lua manages memory automatically by running
1996 a <em>garbage collector</em> from time to time
1997 to collect all <em>dead objects</em>
1998 (that is, objects that are no longer accessible from Lua).
1999 All memory used by Lua is subject to automatic management:
2000 tables, userdata, functions, threads, strings, etc.
2004 Lua implements an incremental mark-and-sweep collector.
2005 It uses two numbers to control its garbage-collection cycles:
2006 the <em>garbage-collector pause</em> and
2007 the <em>garbage-collector step multiplier</em>.
2008 Both use percentage points as units
2009 (so that a value of 100 means an internal value of 1).
2013 The garbage-collector pause
2014 controls how long the collector waits before starting a new cycle.
2015 Larger values make the collector less aggressive.
2016 Values smaller than 100 mean the collector will not wait to
2017 start a new cycle.
2018 A value of 200 means that the collector waits for the total memory in use
2019 to double before starting a new cycle.
2023 The step multiplier
2024 controls the relative speed of the collector relative to
2025 memory allocation.
2026 Larger values make the collector more aggressive but also increase
2027 the size of each incremental step.
2028 Values smaller than 100 make the collector too slow and
2029 can result in the collector never finishing a cycle.
2030 The default, 200, means that the collector runs at "twice"
2031 the speed of memory allocation.
2035 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
2036 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
2037 With these functions you can also control
2038 the collector directly (e.g., stop and restart it).
2042 <h3>2.10.1 - <a name="2.10.1">Garbage-Collection Metamethods</a></h3>
2045 Using the C&nbsp;API,
2046 you can set garbage-collector metamethods for userdata (see <a href="#2.8">&sect;2.8</a>).
2047 These metamethods are also called <em>finalizers</em>.
2048 Finalizers allow you to coordinate Lua's garbage collection
2049 with external resource management
2050 (such as closing files, network or database connections,
2051 or freeing your own memory).
2055 Garbage userdata with a field <code>__gc</code> in their metatables are not
2056 collected immediately by the garbage collector.
2057 Instead, Lua puts them in a list.
2058 After the collection,
2059 Lua does the equivalent of the following function
2060 for each userdata in that list:
2062 <pre>
2063 function gc_event (udata)
2064 local h = metatable(udata).__gc
2065 if h then
2066 h(udata)
2069 </pre>
2072 At the end of each garbage-collection cycle,
2073 the finalizers for userdata are called in <em>reverse</em>
2074 order of their creation,
2075 among those collected in that cycle.
2076 That is, the first finalizer to be called is the one associated
2077 with the userdata created last in the program.
2078 The userdata itself is freed only in the next garbage-collection cycle.
2084 <h3>2.10.2 - <a name="2.10.2">Weak Tables</a></h3>
2087 A <em>weak table</em> is a table whose elements are
2088 <em>weak references</em>.
2089 A weak reference is ignored by the garbage collector.
2090 In other words,
2091 if the only references to an object are weak references,
2092 then the garbage collector will collect this object.
2096 A weak table can have weak keys, weak values, or both.
2097 A table with weak keys allows the collection of its keys,
2098 but prevents the collection of its values.
2099 A table with both weak keys and weak values allows the collection of
2100 both keys and values.
2101 In any case, if either the key or the value is collected,
2102 the whole pair is removed from the table.
2103 The weakness of a table is controlled by the
2104 <code>__mode</code> field of its metatable.
2105 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
2106 the keys in the table are weak.
2107 If <code>__mode</code> contains '<code>v</code>',
2108 the values in the table are weak.
2112 After you use a table as a metatable,
2113 you should not change the value of its <code>__mode</code> field.
2114 Otherwise, the weak behavior of the tables controlled by this
2115 metatable is undefined.
2123 <h2>2.11 - <a name="2.11">Coroutines</a></h2>
2126 Lua supports coroutines,
2127 also called <em>collaborative multithreading</em>.
2128 A coroutine in Lua represents an independent thread of execution.
2129 Unlike threads in multithread systems, however,
2130 a coroutine only suspends its execution by explicitly calling
2131 a yield function.
2135 You create a coroutine with a call to <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
2136 Its sole argument is a function
2137 that is the main function of the coroutine.
2138 The <code>create</code> function only creates a new coroutine and
2139 returns a handle to it (an object of type <em>thread</em>);
2140 it does not start the coroutine execution.
2144 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2145 passing as its first argument
2146 a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2147 the coroutine starts its execution,
2148 at the first line of its main function.
2149 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
2150 to the coroutine main function.
2151 After the coroutine starts running,
2152 it runs until it terminates or <em>yields</em>.
2156 A coroutine can terminate its execution in two ways:
2157 normally, when its main function returns
2158 (explicitly or implicitly, after the last instruction);
2159 and abnormally, if there is an unprotected error.
2160 In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
2161 plus any values returned by the coroutine main function.
2162 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
2163 plus an error message.
2167 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2168 When a coroutine yields,
2169 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
2170 even if the yield happens inside nested function calls
2171 (that is, not in the main function,
2172 but in a function directly or indirectly called by the main function).
2173 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
2174 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2175 The next time you resume the same coroutine,
2176 it continues its execution from the point where it yielded,
2177 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
2178 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2182 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2183 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
2184 but instead of returning the coroutine itself,
2185 it returns a function that, when called, resumes the coroutine.
2186 Any arguments passed to this function
2187 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2188 <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>,
2189 except the first one (the boolean error code).
2190 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2191 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
2192 any error is propagated to the caller.
2196 As an example,
2197 consider the following code:
2199 <pre>
2200 function foo (a)
2201 print("foo", a)
2202 return coroutine.yield(2*a)
2205 co = coroutine.create(function (a,b)
2206 print("co-body", a, b)
2207 local r = foo(a+1)
2208 print("co-body", r)
2209 local r, s = coroutine.yield(a+b, a-b)
2210 print("co-body", r, s)
2211 return b, "end"
2212 end)
2214 print("main", coroutine.resume(co, 1, 10))
2215 print("main", coroutine.resume(co, "r"))
2216 print("main", coroutine.resume(co, "x", "y"))
2217 print("main", coroutine.resume(co, "x", "y"))
2218 </pre><p>
2219 When you run it, it produces the following output:
2221 <pre>
2222 co-body 1 10
2223 foo 2
2225 main true 4
2226 co-body r
2227 main true 11 -9
2228 co-body x y
2229 main true 10 end
2230 main false cannot resume dead coroutine
2231 </pre>
2236 <h1>3 - <a name="3">The Application Program Interface</a></h1>
2240 This section describes the C&nbsp;API for Lua, that is,
2241 the set of C&nbsp;functions available to the host program to communicate
2242 with Lua.
2243 All API functions and related types and constants
2244 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2248 Even when we use the term "function",
2249 any facility in the API may be provided as a macro instead.
2250 All such macros use each of their arguments exactly once
2251 (except for the first argument, which is always a Lua state),
2252 and so do not generate any hidden side-effects.
2256 As in most C&nbsp;libraries,
2257 the Lua API functions do not check their arguments for validity or consistency.
2258 However, you can change this behavior by compiling Lua
2259 with a proper definition for the macro <a name="pdf-luai_apicheck"><code>luai_apicheck</code></a>,
2260 in file <code>luaconf.h</code>.
2264 <h2>3.1 - <a name="3.1">The Stack</a></h2>
2267 Lua uses a <em>virtual stack</em> to pass values to and from C.
2268 Each element in this stack represents a Lua value
2269 (<b>nil</b>, number, string, etc.).
2273 Whenever Lua calls C, the called function gets a new stack,
2274 which is independent of previous stacks and of stacks of
2275 C&nbsp;functions that are still active.
2276 This stack initially contains any arguments to the C&nbsp;function
2277 and it is where the C&nbsp;function pushes its results
2278 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2282 For convenience,
2283 most query operations in the API do not follow a strict stack discipline.
2284 Instead, they can refer to any element in the stack
2285 by using an <em>index</em>:
2286 A positive index represents an <em>absolute</em> stack position
2287 (starting at&nbsp;1);
2288 a negative index represents an <em>offset</em> relative to the top of the stack.
2289 More specifically, if the stack has <em>n</em> elements,
2290 then index&nbsp;1 represents the first element
2291 (that is, the element that was pushed onto the stack first)
2293 index&nbsp;<em>n</em> represents the last element;
2294 index&nbsp;-1 also represents the last element
2295 (that is, the element at the&nbsp;top)
2296 and index <em>-n</em> represents the first element.
2297 We say that an index is <em>valid</em>
2298 if it lies between&nbsp;1 and the stack top
2299 (that is, if <code>1 &le; abs(index) &le; top</code>).
2306 <h2>3.2 - <a name="3.2">Stack Size</a></h2>
2309 When you interact with Lua API,
2310 you are responsible for ensuring consistency.
2311 In particular,
2312 <em>you are responsible for controlling stack overflow</em>.
2313 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2314 to grow the stack size.
2318 Whenever Lua calls C,
2319 it ensures that at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> stack positions are available.
2320 <code>LUA_MINSTACK</code> is defined as 20,
2321 so that usually you do not have to worry about stack space
2322 unless your code has loops pushing elements onto the stack.
2326 Most query functions accept as indices any value inside the
2327 available stack space, that is, indices up to the maximum stack size
2328 you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2329 Such indices are called <em>acceptable indices</em>.
2330 More formally, we define an <em>acceptable index</em>
2331 as follows:
2333 <pre>
2334 (index &lt; 0 &amp;&amp; abs(index) &lt;= top) ||
2335 (index &gt; 0 &amp;&amp; index &lt;= stackspace)
2336 </pre><p>
2337 Note that 0 is never an acceptable index.
2343 <h2>3.3 - <a name="3.3">Pseudo-Indices</a></h2>
2346 Unless otherwise noted,
2347 any function that accepts valid indices can also be called with
2348 <em>pseudo-indices</em>,
2349 which represent some Lua values that are accessible to C&nbsp;code
2350 but which are not in the stack.
2351 Pseudo-indices are used to access the thread environment,
2352 the function environment,
2353 the registry,
2354 and the upvalues of a C&nbsp;function (see <a href="#3.4">&sect;3.4</a>).
2358 The thread environment (where global variables live) is
2359 always at pseudo-index <a name="pdf-LUA_GLOBALSINDEX"><code>LUA_GLOBALSINDEX</code></a>.
2360 The environment of the running C&nbsp;function is always
2361 at pseudo-index <a name="pdf-LUA_ENVIRONINDEX"><code>LUA_ENVIRONINDEX</code></a>.
2365 To access and change the value of global variables,
2366 you can use regular table operations over an environment table.
2367 For instance, to access the value of a global variable, do
2369 <pre>
2370 lua_getfield(L, LUA_GLOBALSINDEX, varname);
2371 </pre>
2376 <h2>3.4 - <a name="3.4">C Closures</a></h2>
2379 When a C&nbsp;function is created,
2380 it is possible to associate some values with it,
2381 thus creating a <em>C&nbsp;closure</em>;
2382 these values are called <em>upvalues</em> and are
2383 accessible to the function whenever it is called
2384 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
2388 Whenever a C&nbsp;function is called,
2389 its upvalues are located at specific pseudo-indices.
2390 These pseudo-indices are produced by the macro
2391 <a name="lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2392 The first value associated with a function is at position
2393 <code>lua_upvalueindex(1)</code>, and so on.
2394 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2395 where <em>n</em> is greater than the number of upvalues of the
2396 current function (but not greater than 256),
2397 produces an acceptable (but invalid) index.
2403 <h2>3.5 - <a name="3.5">Registry</a></h2>
2406 Lua provides a <em>registry</em>,
2407 a pre-defined table that can be used by any C&nbsp;code to
2408 store whatever Lua value it needs to store.
2409 This table is always located at pseudo-index
2410 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
2411 Any C&nbsp;library can store data into this table,
2412 but it should take care to choose keys different from those used
2413 by other libraries, to avoid collisions.
2414 Typically, you should use as key a string containing your library name
2415 or a light userdata with the address of a C&nbsp;object in your code.
2419 The integer keys in the registry are used by the reference mechanism,
2420 implemented by the auxiliary library,
2421 and therefore should not be used for other purposes.
2427 <h2>3.6 - <a name="3.6">Error Handling in C</a></h2>
2430 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2431 (You can also choose to use exceptions if you use C++;
2432 see file <code>luaconf.h</code>.)
2433 When Lua faces any error
2434 (such as memory allocation errors, type errors, syntax errors,
2435 and runtime errors)
2436 it <em>raises</em> an error;
2437 that is, it does a long jump.
2438 A <em>protected environment</em> uses <code>setjmp</code>
2439 to set a recover point;
2440 any error jumps to the most recent active recover point.
2444 Most functions in the API can throw an error,
2445 for instance due to a memory allocation error.
2446 The documentation for each function indicates whether
2447 it can throw errors.
2451 Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2457 <h2>3.7 - <a name="3.7">Functions and Types</a></h2>
2460 Here we list all functions and types from the C&nbsp;API in
2461 alphabetical order.
2462 Each function has an indicator like this:
2463 <span class="apii">[-o, +p, <em>x</em>]</span>
2467 The first field, <code>o</code>,
2468 is how many elements the function pops from the stack.
2469 The second field, <code>p</code>,
2470 is how many elements the function pushes onto the stack.
2471 (Any function always pushes its results after popping its arguments.)
2472 A field in the form <code>x|y</code> means the function can push (or pop)
2473 <code>x</code> or <code>y</code> elements,
2474 depending on the situation;
2475 an interrogation mark '<code>?</code>' means that
2476 we cannot know how many elements the function pops/pushes
2477 by looking only at its arguments
2478 (e.g., they may depend on what is on the stack).
2479 The third field, <code>x</code>,
2480 tells whether the function may throw errors:
2481 '<code>-</code>' means the function never throws any error;
2482 '<code>m</code>' means the function may throw an error
2483 only due to not enough memory;
2484 '<code>e</code>' means the function may throw other kinds of errors;
2485 '<code>v</code>' means the function may throw an error on purpose.
2489 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2490 <pre>typedef void * (*lua_Alloc) (void *ud,
2491 void *ptr,
2492 size_t osize,
2493 size_t nsize);</pre>
2496 The type of the memory-allocation function used by Lua states.
2497 The allocator function must provide a
2498 functionality similar to <code>realloc</code>,
2499 but not exactly the same.
2500 Its arguments are
2501 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2502 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2503 <code>osize</code>, the original size of the block;
2504 <code>nsize</code>, the new size of the block.
2505 <code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
2506 When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
2507 if <code>osize</code> is not zero,
2508 it should free the block pointed to by <code>ptr</code>.
2509 When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
2510 if and only if it cannot fill the request.
2511 When <code>nsize</code> is not zero and <code>osize</code> is zero,
2512 the allocator should behave like <code>malloc</code>.
2513 When <code>nsize</code> and <code>osize</code> are not zero,
2514 the allocator behaves like <code>realloc</code>.
2515 Lua assumes that the allocator never fails when
2516 <code>osize &gt;= nsize</code>.
2520 Here is a simple implementation for the allocator function.
2521 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2523 <pre>
2524 static void *l_alloc (void *ud, void *ptr, size_t osize,
2525 size_t nsize) {
2526 (void)ud; (void)osize; /* not used */
2527 if (nsize == 0) {
2528 free(ptr);
2529 return NULL;
2531 else
2532 return realloc(ptr, nsize);
2534 </pre><p>
2535 This code assumes
2536 that <code>free(NULL)</code> has no effect and that
2537 <code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2538 ANSI&nbsp;C ensures both behaviors.
2544 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
2545 <span class="apii">[-0, +0, <em>-</em>]</span>
2546 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2549 Sets a new panic function and returns the old one.
2553 If an error happens outside any protected environment,
2554 Lua calls a <em>panic function</em>
2555 and then calls <code>exit(EXIT_FAILURE)</code>,
2556 thus exiting the host application.
2557 Your panic function can avoid this exit by
2558 never returning (e.g., doing a long jump).
2562 The panic function can access the error message at the top of the stack.
2568 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
2569 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
2570 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
2573 Calls a function.
2577 To call a function you must use the following protocol:
2578 first, the function to be called is pushed onto the stack;
2579 then, the arguments to the function are pushed
2580 in direct order;
2581 that is, the first argument is pushed first.
2582 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
2583 <code>nargs</code> is the number of arguments that you pushed onto the stack.
2584 All arguments and the function value are popped from the stack
2585 when the function is called.
2586 The function results are pushed onto the stack when the function returns.
2587 The number of results is adjusted to <code>nresults</code>,
2588 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
2589 In this case, <em>all</em> results from the function are pushed.
2590 Lua takes care that the returned values fit into the stack space.
2591 The function results are pushed onto the stack in direct order
2592 (the first result is pushed first),
2593 so that after the call the last result is on the top of the stack.
2597 Any error inside the called function is propagated upwards
2598 (with a <code>longjmp</code>).
2602 The following example shows how the host program can do the
2603 equivalent to this Lua code:
2605 <pre>
2606 a = f("how", t.x, 14)
2607 </pre><p>
2608 Here it is in&nbsp;C:
2610 <pre>
2611 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
2612 lua_pushstring(L, "how"); /* 1st argument */
2613 lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */
2614 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
2615 lua_remove(L, -2); /* remove 't' from the stack */
2616 lua_pushinteger(L, 14); /* 3rd argument */
2617 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
2618 lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global 'a' */
2619 </pre><p>
2620 Note that the code above is "balanced":
2621 at its end, the stack is back to its original configuration.
2622 This is considered good programming practice.
2628 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
2629 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
2632 Type for C&nbsp;functions.
2636 In order to communicate properly with Lua,
2637 a C&nbsp;function must use the following protocol,
2638 which defines the way parameters and results are passed:
2639 a C&nbsp;function receives its arguments from Lua in its stack
2640 in direct order (the first argument is pushed first).
2641 So, when the function starts,
2642 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
2643 The first argument (if any) is at index 1
2644 and its last argument is at index <code>lua_gettop(L)</code>.
2645 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
2646 in direct order (the first result is pushed first),
2647 and returns the number of results.
2648 Any other value in the stack below the results will be properly
2649 discarded by Lua.
2650 Like a Lua function, a C&nbsp;function called by Lua can also return
2651 many results.
2655 As an example, the following function receives a variable number
2656 of numerical arguments and returns their average and sum:
2658 <pre>
2659 static int foo (lua_State *L) {
2660 int n = lua_gettop(L); /* number of arguments */
2661 lua_Number sum = 0;
2662 int i;
2663 for (i = 1; i &lt;= n; i++) {
2664 if (!lua_isnumber(L, i)) {
2665 lua_pushstring(L, "incorrect argument");
2666 lua_error(L);
2668 sum += lua_tonumber(L, i);
2670 lua_pushnumber(L, sum/n); /* first result */
2671 lua_pushnumber(L, sum); /* second result */
2672 return 2; /* number of results */
2674 </pre>
2679 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
2680 <span class="apii">[-0, +0, <em>m</em>]</span>
2681 <pre>int lua_checkstack (lua_State *L, int extra);</pre>
2684 Ensures that there are at least <code>extra</code> free stack slots in the stack.
2685 It returns false if it cannot grow the stack to that size.
2686 This function never shrinks the stack;
2687 if the stack is already larger than the new size,
2688 it is left unchanged.
2694 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
2695 <span class="apii">[-0, +0, <em>-</em>]</span>
2696 <pre>void lua_close (lua_State *L);</pre>
2699 Destroys all objects in the given Lua state
2700 (calling the corresponding garbage-collection metamethods, if any)
2701 and frees all dynamic memory used by this state.
2702 On several platforms, you may not need to call this function,
2703 because all resources are naturally released when the host program ends.
2704 On the other hand, long-running programs,
2705 such as a daemon or a web server,
2706 might need to release states as soon as they are not needed,
2707 to avoid growing too large.
2713 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
2714 <span class="apii">[-n, +1, <em>e</em>]</span>
2715 <pre>void lua_concat (lua_State *L, int n);</pre>
2718 Concatenates the <code>n</code> values at the top of the stack,
2719 pops them, and leaves the result at the top.
2720 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
2721 (that is, the function does nothing);
2722 if <code>n</code> is 0, the result is the empty string.
2723 Concatenation is performed following the usual semantics of Lua
2724 (see <a href="#2.5.4">&sect;2.5.4</a>).
2730 <hr><h3><a name="lua_cpcall"><code>lua_cpcall</code></a></h3><p>
2731 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
2732 <pre>int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);</pre>
2735 Calls the C&nbsp;function <code>func</code> in protected mode.
2736 <code>func</code> starts with only one element in its stack,
2737 a light userdata containing <code>ud</code>.
2738 In case of errors,
2739 <a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
2740 plus the error object on the top of the stack;
2741 otherwise, it returns zero, and does not change the stack.
2742 All values returned by <code>func</code> are discarded.
2748 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
2749 <span class="apii">[-0, +1, <em>m</em>]</span>
2750 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
2753 Creates a new empty table and pushes it onto the stack.
2754 The new table has space pre-allocated
2755 for <code>narr</code> array elements and <code>nrec</code> non-array elements.
2756 This pre-allocation is useful when you know exactly how many elements
2757 the table will have.
2758 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
2764 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
2765 <span class="apii">[-0, +0, <em>m</em>]</span>
2766 <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
2769 Dumps a function as a binary chunk.
2770 Receives a Lua function on the top of the stack
2771 and produces a binary chunk that,
2772 if loaded again,
2773 results in a function equivalent to the one dumped.
2774 As it produces parts of the chunk,
2775 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
2776 with the given <code>data</code>
2777 to write them.
2781 The value returned is the error code returned by the last
2782 call to the writer;
2783 0&nbsp;means no errors.
2787 This function does not pop the Lua function from the stack.
2793 <hr><h3><a name="lua_equal"><code>lua_equal</code></a></h3><p>
2794 <span class="apii">[-0, +0, <em>e</em>]</span>
2795 <pre>int lua_equal (lua_State *L, int index1, int index2);</pre>
2798 Returns 1 if the two values in acceptable indices <code>index1</code> and
2799 <code>index2</code> are equal,
2800 following the semantics of the Lua <code>==</code> operator
2801 (that is, may call metamethods).
2802 Otherwise returns&nbsp;0.
2803 Also returns&nbsp;0 if any of the indices is non valid.
2809 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
2810 <span class="apii">[-1, +0, <em>v</em>]</span>
2811 <pre>int lua_error (lua_State *L);</pre>
2814 Generates a Lua error.
2815 The error message (which can actually be a Lua value of any type)
2816 must be on the stack top.
2817 This function does a long jump,
2818 and therefore never returns.
2819 (see <a href="#luaL_error"><code>luaL_error</code></a>).
2825 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
2826 <span class="apii">[-0, +0, <em>e</em>]</span>
2827 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
2830 Controls the garbage collector.
2834 This function performs several tasks,
2835 according to the value of the parameter <code>what</code>:
2837 <ul>
2839 <li><b><code>LUA_GCSTOP</code>:</b>
2840 stops the garbage collector.
2841 </li>
2843 <li><b><code>LUA_GCRESTART</code>:</b>
2844 restarts the garbage collector.
2845 </li>
2847 <li><b><code>LUA_GCCOLLECT</code>:</b>
2848 performs a full garbage-collection cycle.
2849 </li>
2851 <li><b><code>LUA_GCCOUNT</code>:</b>
2852 returns the current amount of memory (in Kbytes) in use by Lua.
2853 </li>
2855 <li><b><code>LUA_GCCOUNTB</code>:</b>
2856 returns the remainder of dividing the current amount of bytes of
2857 memory in use by Lua by 1024.
2858 </li>
2860 <li><b><code>LUA_GCSTEP</code>:</b>
2861 performs an incremental step of garbage collection.
2862 The step "size" is controlled by <code>data</code>
2863 (larger values mean more steps) in a non-specified way.
2864 If you want to control the step size
2865 you must experimentally tune the value of <code>data</code>.
2866 The function returns 1 if the step finished a
2867 garbage-collection cycle.
2868 </li>
2870 <li><b><code>LUA_GCSETPAUSE</code>:</b>
2871 sets <code>data</code> as the new value
2872 for the <em>pause</em> of the collector (see <a href="#2.10">&sect;2.10</a>).
2873 The function returns the previous value of the pause.
2874 </li>
2876 <li><b><code>LUA_GCSETSTEPMUL</code>:</b>
2877 sets <code>data</code> as the new value for the <em>step multiplier</em> of
2878 the collector (see <a href="#2.10">&sect;2.10</a>).
2879 The function returns the previous value of the step multiplier.
2880 </li>
2882 </ul>
2887 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
2888 <span class="apii">[-0, +0, <em>-</em>]</span>
2889 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
2892 Returns the memory-allocation function of a given state.
2893 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
2894 opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
2900 <hr><h3><a name="lua_getfenv"><code>lua_getfenv</code></a></h3><p>
2901 <span class="apii">[-0, +1, <em>-</em>]</span>
2902 <pre>void lua_getfenv (lua_State *L, int index);</pre>
2905 Pushes onto the stack the environment table of
2906 the value at the given index.
2912 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
2913 <span class="apii">[-0, +1, <em>e</em>]</span>
2914 <pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
2917 Pushes onto the stack the value <code>t[k]</code>,
2918 where <code>t</code> is the value at the given valid index.
2919 As in Lua, this function may trigger a metamethod
2920 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2926 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
2927 <span class="apii">[-0, +1, <em>e</em>]</span>
2928 <pre>void lua_getglobal (lua_State *L, const char *name);</pre>
2931 Pushes onto the stack the value of the global <code>name</code>.
2932 It is defined as a macro:
2934 <pre>
2935 #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
2936 </pre>
2941 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
2942 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
2943 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
2946 Pushes onto the stack the metatable of the value at the given
2947 acceptable index.
2948 If the index is not valid,
2949 or if the value does not have a metatable,
2950 the function returns&nbsp;0 and pushes nothing on the stack.
2956 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
2957 <span class="apii">[-1, +1, <em>e</em>]</span>
2958 <pre>void lua_gettable (lua_State *L, int index);</pre>
2961 Pushes onto the stack the value <code>t[k]</code>,
2962 where <code>t</code> is the value at the given valid index
2963 and <code>k</code> is the value at the top of the stack.
2967 This function pops the key from the stack
2968 (putting the resulting value in its place).
2969 As in Lua, this function may trigger a metamethod
2970 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2976 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
2977 <span class="apii">[-0, +0, <em>-</em>]</span>
2978 <pre>int lua_gettop (lua_State *L);</pre>
2981 Returns the index of the top element in the stack.
2982 Because indices start at&nbsp;1,
2983 this result is equal to the number of elements in the stack
2984 (and so 0&nbsp;means an empty stack).
2990 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
2991 <span class="apii">[-1, +1, <em>-</em>]</span>
2992 <pre>void lua_insert (lua_State *L, int index);</pre>
2995 Moves the top element into the given valid index,
2996 shifting up the elements above this index to open space.
2997 Cannot be called with a pseudo-index,
2998 because a pseudo-index is not an actual stack position.
3004 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3005 <pre>typedef ptrdiff_t lua_Integer;</pre>
3008 The type used by the Lua API to represent integral values.
3012 By default it is a <code>ptrdiff_t</code>,
3013 which is usually the largest signed integral type the machine handles
3014 "comfortably".
3020 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3021 <span class="apii">[-0, +0, <em>-</em>]</span>
3022 <pre>int lua_isboolean (lua_State *L, int index);</pre>
3025 Returns 1 if the value at the given acceptable index has type boolean,
3026 and 0&nbsp;otherwise.
3032 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3033 <span class="apii">[-0, +0, <em>-</em>]</span>
3034 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
3037 Returns 1 if the value at the given acceptable index is a C&nbsp;function,
3038 and 0&nbsp;otherwise.
3044 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3045 <span class="apii">[-0, +0, <em>-</em>]</span>
3046 <pre>int lua_isfunction (lua_State *L, int index);</pre>
3049 Returns 1 if the value at the given acceptable index is a function
3050 (either C or Lua), and 0&nbsp;otherwise.
3056 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3057 <span class="apii">[-0, +0, <em>-</em>]</span>
3058 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3061 Returns 1 if the value at the given acceptable index is a light userdata,
3062 and 0&nbsp;otherwise.
3068 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3069 <span class="apii">[-0, +0, <em>-</em>]</span>
3070 <pre>int lua_isnil (lua_State *L, int index);</pre>
3073 Returns 1 if the value at the given acceptable index is <b>nil</b>,
3074 and 0&nbsp;otherwise.
3080 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3081 <span class="apii">[-0, +0, <em>-</em>]</span>
3082 <pre>int lua_isnone (lua_State *L, int index);</pre>
3085 Returns 1 if the given acceptable index is not valid
3086 (that is, it refers to an element outside the current stack),
3087 and 0&nbsp;otherwise.
3093 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3094 <span class="apii">[-0, +0, <em>-</em>]</span>
3095 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3098 Returns 1 if the given acceptable index is not valid
3099 (that is, it refers to an element outside the current stack)
3100 or if the value at this index is <b>nil</b>,
3101 and 0&nbsp;otherwise.
3107 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3108 <span class="apii">[-0, +0, <em>-</em>]</span>
3109 <pre>int lua_isnumber (lua_State *L, int index);</pre>
3112 Returns 1 if the value at the given acceptable index is a number
3113 or a string convertible to a number,
3114 and 0&nbsp;otherwise.
3120 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3121 <span class="apii">[-0, +0, <em>-</em>]</span>
3122 <pre>int lua_isstring (lua_State *L, int index);</pre>
3125 Returns 1 if the value at the given acceptable index is a string
3126 or a number (which is always convertible to a string),
3127 and 0&nbsp;otherwise.
3133 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3134 <span class="apii">[-0, +0, <em>-</em>]</span>
3135 <pre>int lua_istable (lua_State *L, int index);</pre>
3138 Returns 1 if the value at the given acceptable index is a table,
3139 and 0&nbsp;otherwise.
3145 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3146 <span class="apii">[-0, +0, <em>-</em>]</span>
3147 <pre>int lua_isthread (lua_State *L, int index);</pre>
3150 Returns 1 if the value at the given acceptable index is a thread,
3151 and 0&nbsp;otherwise.
3157 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3158 <span class="apii">[-0, +0, <em>-</em>]</span>
3159 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
3162 Returns 1 if the value at the given acceptable index is a userdata
3163 (either full or light), and 0&nbsp;otherwise.
3169 <hr><h3><a name="lua_lessthan"><code>lua_lessthan</code></a></h3><p>
3170 <span class="apii">[-0, +0, <em>e</em>]</span>
3171 <pre>int lua_lessthan (lua_State *L, int index1, int index2);</pre>
3174 Returns 1 if the value at acceptable index <code>index1</code> is smaller
3175 than the value at acceptable index <code>index2</code>,
3176 following the semantics of the Lua <code>&lt;</code> operator
3177 (that is, may call metamethods).
3178 Otherwise returns&nbsp;0.
3179 Also returns&nbsp;0 if any of the indices is non valid.
3185 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3186 <span class="apii">[-0, +1, <em>-</em>]</span>
3187 <pre>int lua_load (lua_State *L,
3188 lua_Reader reader,
3189 void *data,
3190 const char *chunkname);</pre>
3193 Loads a Lua chunk.
3194 If there are no errors,
3195 <a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
3196 function on top of the stack.
3197 Otherwise, it pushes an error message.
3198 The return values of <a href="#lua_load"><code>lua_load</code></a> are:
3200 <ul>
3202 <li><b>0:</b> no errors;</li>
3204 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
3205 syntax error during pre-compilation;</li>
3207 <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3208 memory allocation error.</li>
3210 </ul>
3213 This function only loads a chunk;
3214 it does not run it.
3218 <a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
3219 and loads it accordingly (see program <code>luac</code>).
3223 The <a href="#lua_load"><code>lua_load</code></a> function uses a user-supplied <code>reader</code> function
3224 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3225 The <code>data</code> argument is an opaque value passed to the reader function.
3229 The <code>chunkname</code> argument gives a name to the chunk,
3230 which is used for error messages and in debug information (see <a href="#3.8">&sect;3.8</a>).
3236 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3237 <span class="apii">[-0, +0, <em>-</em>]</span>
3238 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3241 Creates a new, independent state.
3242 Returns <code>NULL</code> if cannot create the state
3243 (due to lack of memory).
3244 The argument <code>f</code> is the allocator function;
3245 Lua does all memory allocation for this state through this function.
3246 The second argument, <code>ud</code>, is an opaque pointer that Lua
3247 simply passes to the allocator in every call.
3253 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
3254 <span class="apii">[-0, +1, <em>m</em>]</span>
3255 <pre>void lua_newtable (lua_State *L);</pre>
3258 Creates a new empty table and pushes it onto the stack.
3259 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3265 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
3266 <span class="apii">[-0, +1, <em>m</em>]</span>
3267 <pre>lua_State *lua_newthread (lua_State *L);</pre>
3270 Creates a new thread, pushes it on the stack,
3271 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3272 The new state returned by this function shares with the original state
3273 all global objects (such as tables),
3274 but has an independent execution stack.
3278 There is no explicit function to close or to destroy a thread.
3279 Threads are subject to garbage collection,
3280 like any Lua object.
3286 <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
3287 <span class="apii">[-0, +1, <em>m</em>]</span>
3288 <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3291 This function allocates a new block of memory with the given size,
3292 pushes onto the stack a new full userdata with the block address,
3293 and returns this address.
3297 Userdata represent C&nbsp;values in Lua.
3298 A <em>full userdata</em> represents a block of memory.
3299 It is an object (like a table):
3300 you must create it, it can have its own metatable,
3301 and you can detect when it is being collected.
3302 A full userdata is only equal to itself (under raw equality).
3306 When Lua collects a full userdata with a <code>gc</code> metamethod,
3307 Lua calls the metamethod and marks the userdata as finalized.
3308 When this userdata is collected again then
3309 Lua frees its corresponding memory.
3315 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
3316 <span class="apii">[-1, +(2|0), <em>e</em>]</span>
3317 <pre>int lua_next (lua_State *L, int index);</pre>
3320 Pops a key from the stack,
3321 and pushes a key-value pair from the table at the given index
3322 (the "next" pair after the given key).
3323 If there are no more elements in the table,
3324 then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3328 A typical traversal looks like this:
3330 <pre>
3331 /* table is in the stack at index 't' */
3332 lua_pushnil(L); /* first key */
3333 while (lua_next(L, t) != 0) {
3334 /* uses 'key' (at index -2) and 'value' (at index -1) */
3335 printf("%s - %s\n",
3336 lua_typename(L, lua_type(L, -2)),
3337 lua_typename(L, lua_type(L, -1)));
3338 /* removes 'value'; keeps 'key' for next iteration */
3339 lua_pop(L, 1);
3341 </pre>
3344 While traversing a table,
3345 do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3346 unless you know that the key is actually a string.
3347 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
3348 the value at the given index;
3349 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3355 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3356 <pre>typedef double lua_Number;</pre>
3359 The type of numbers in Lua.
3360 By default, it is double, but that can be changed in <code>luaconf.h</code>.
3364 Through the configuration file you can change
3365 Lua to operate with another type for numbers (e.g., float or long).
3371 <hr><h3><a name="lua_objlen"><code>lua_objlen</code></a></h3><p>
3372 <span class="apii">[-0, +0, <em>-</em>]</span>
3373 <pre>size_t lua_objlen (lua_State *L, int index);</pre>
3376 Returns the "length" of the value at the given acceptable index:
3377 for strings, this is the string length;
3378 for tables, this is the result of the length operator ('<code>#</code>');
3379 for userdata, this is the size of the block of memory allocated
3380 for the userdata;
3381 for other values, it is&nbsp;0.
3387 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
3388 <span class="apii">[-(nargs + 1), +(nresults|1), <em>-</em>]</span>
3389 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);</pre>
3392 Calls a function in protected mode.
3396 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3397 in <a href="#lua_call"><code>lua_call</code></a>.
3398 If there are no errors during the call,
3399 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
3400 However, if there is any error,
3401 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3402 pushes a single value on the stack (the error message),
3403 and returns an error code.
3404 Like <a href="#lua_call"><code>lua_call</code></a>,
3405 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3406 and its arguments from the stack.
3410 If <code>errfunc</code> is 0,
3411 then the error message returned on the stack
3412 is exactly the original error message.
3413 Otherwise, <code>errfunc</code> is the stack index of an
3414 <em>error handler function</em>.
3415 (In the current implementation, this index cannot be a pseudo-index.)
3416 In case of runtime errors,
3417 this function will be called with the error message
3418 and its return value will be the message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3422 Typically, the error handler function is used to add more debug
3423 information to the error message, such as a stack traceback.
3424 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3425 since by then the stack has unwound.
3429 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
3430 or one of the following error codes
3431 (defined in <code>lua.h</code>):
3433 <ul>
3435 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b>
3436 a runtime error.
3437 </li>
3439 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3440 memory allocation error.
3441 For such errors, Lua does not call the error handler function.
3442 </li>
3444 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
3445 error while running the error handler function.
3446 </li>
3448 </ul>
3453 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
3454 <span class="apii">[-n, +0, <em>-</em>]</span>
3455 <pre>void lua_pop (lua_State *L, int n);</pre>
3458 Pops <code>n</code> elements from the stack.
3464 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
3465 <span class="apii">[-0, +1, <em>-</em>]</span>
3466 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
3469 Pushes a boolean value with value <code>b</code> onto the stack.
3475 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
3476 <span class="apii">[-n, +1, <em>m</em>]</span>
3477 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
3480 Pushes a new C&nbsp;closure onto the stack.
3484 When a C&nbsp;function is created,
3485 it is possible to associate some values with it,
3486 thus creating a C&nbsp;closure (see <a href="#3.4">&sect;3.4</a>);
3487 these values are then accessible to the function whenever it is called.
3488 To associate values with a C&nbsp;function,
3489 first these values should be pushed onto the stack
3490 (when there are multiple values, the first value is pushed first).
3491 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
3492 is called to create and push the C&nbsp;function onto the stack,
3493 with the argument <code>n</code> telling how many values should be
3494 associated with the function.
3495 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
3499 The maximum value for <code>n</code> is 255.
3505 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
3506 <span class="apii">[-0, +1, <em>m</em>]</span>
3507 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
3510 Pushes a C&nbsp;function onto the stack.
3511 This function receives a pointer to a C function
3512 and pushes onto the stack a Lua value of type <code>function</code> that,
3513 when called, invokes the corresponding C&nbsp;function.
3517 Any function to be registered in Lua must
3518 follow the correct protocol to receive its parameters
3519 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
3523 <code>lua_pushcfunction</code> is defined as a macro:
3525 <pre>
3526 #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
3527 </pre>
3532 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
3533 <span class="apii">[-0, +1, <em>m</em>]</span>
3534 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
3537 Pushes onto the stack a formatted string
3538 and returns a pointer to this string.
3539 It is similar to the C&nbsp;function <code>sprintf</code>,
3540 but has some important differences:
3542 <ul>
3544 <li>
3545 You do not have to allocate space for the result:
3546 the result is a Lua string and Lua takes care of memory allocation
3547 (and deallocation, through garbage collection).
3548 </li>
3550 <li>
3551 The conversion specifiers are quite restricted.
3552 There are no flags, widths, or precisions.
3553 The conversion specifiers can only be
3554 '<code>%%</code>' (inserts a '<code>%</code>' in the string),
3555 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
3556 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
3557 '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
3558 '<code>%d</code>' (inserts an <code>int</code>), and
3559 '<code>%c</code>' (inserts an <code>int</code> as a character).
3560 </li>
3562 </ul>
3567 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
3568 <span class="apii">[-0, +1, <em>-</em>]</span>
3569 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
3572 Pushes a number with value <code>n</code> onto the stack.
3578 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
3579 <span class="apii">[-0, +1, <em>-</em>]</span>
3580 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
3583 Pushes a light userdata onto the stack.
3587 Userdata represent C&nbsp;values in Lua.
3588 A <em>light userdata</em> represents a pointer.
3589 It is a value (like a number):
3590 you do not create it, it has no individual metatable,
3591 and it is not collected (as it was never created).
3592 A light userdata is equal to "any"
3593 light userdata with the same C&nbsp;address.
3599 <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
3600 <span class="apii">[-0, +1, <em>m</em>]</span>
3601 <pre>void lua_pushliteral (lua_State *L, const char *s);</pre>
3604 This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3605 but can be used only when <code>s</code> is a literal string.
3606 In these cases, it automatically provides the string length.
3612 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
3613 <span class="apii">[-0, +1, <em>m</em>]</span>
3614 <pre>void lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
3617 Pushes the string pointed to by <code>s</code> with size <code>len</code>
3618 onto the stack.
3619 Lua makes (or reuses) an internal copy of the given string,
3620 so the memory at <code>s</code> can be freed or reused immediately after
3621 the function returns.
3622 The string can contain embedded zeros.
3628 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
3629 <span class="apii">[-0, +1, <em>-</em>]</span>
3630 <pre>void lua_pushnil (lua_State *L);</pre>
3633 Pushes a nil value onto the stack.
3639 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
3640 <span class="apii">[-0, +1, <em>-</em>]</span>
3641 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
3644 Pushes a number with value <code>n</code> onto the stack.
3650 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
3651 <span class="apii">[-0, +1, <em>m</em>]</span>
3652 <pre>void lua_pushstring (lua_State *L, const char *s);</pre>
3655 Pushes the zero-terminated string pointed to by <code>s</code>
3656 onto the stack.
3657 Lua makes (or reuses) an internal copy of the given string,
3658 so the memory at <code>s</code> can be freed or reused immediately after
3659 the function returns.
3660 The string cannot contain embedded zeros;
3661 it is assumed to end at the first zero.
3667 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
3668 <span class="apii">[-0, +1, <em>-</em>]</span>
3669 <pre>int lua_pushthread (lua_State *L);</pre>
3672 Pushes the thread represented by <code>L</code> onto the stack.
3673 Returns 1 if this thread is the main thread of its state.
3679 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
3680 <span class="apii">[-0, +1, <em>-</em>]</span>
3681 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
3684 Pushes a copy of the element at the given valid index
3685 onto the stack.
3691 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
3692 <span class="apii">[-0, +1, <em>m</em>]</span>
3693 <pre>const char *lua_pushvfstring (lua_State *L,
3694 const char *fmt,
3695 va_list argp);</pre>
3698 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
3699 instead of a variable number of arguments.
3705 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
3706 <span class="apii">[-0, +0, <em>-</em>]</span>
3707 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
3710 Returns 1 if the two values in acceptable indices <code>index1</code> and
3711 <code>index2</code> are primitively equal
3712 (that is, without calling metamethods).
3713 Otherwise returns&nbsp;0.
3714 Also returns&nbsp;0 if any of the indices are non valid.
3720 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
3721 <span class="apii">[-1, +1, <em>-</em>]</span>
3722 <pre>void lua_rawget (lua_State *L, int index);</pre>
3725 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
3726 (i.e., without metamethods).
3732 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
3733 <span class="apii">[-0, +1, <em>-</em>]</span>
3734 <pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
3737 Pushes onto the stack the value <code>t[n]</code>,
3738 where <code>t</code> is the value at the given valid index.
3739 The access is raw;
3740 that is, it does not invoke metamethods.
3746 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
3747 <span class="apii">[-2, +0, <em>m</em>]</span>
3748 <pre>void lua_rawset (lua_State *L, int index);</pre>
3751 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
3752 (i.e., without metamethods).
3758 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
3759 <span class="apii">[-1, +0, <em>m</em>]</span>
3760 <pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
3763 Does the equivalent of <code>t[n] = v</code>,
3764 where <code>t</code> is the value at the given valid index
3765 and <code>v</code> is the value at the top of the stack.
3769 This function pops the value from the stack.
3770 The assignment is raw;
3771 that is, it does not invoke metamethods.
3777 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
3778 <pre>typedef const char * (*lua_Reader) (lua_State *L,
3779 void *data,
3780 size_t *size);</pre>
3783 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
3784 Every time it needs another piece of the chunk,
3785 <a href="#lua_load"><code>lua_load</code></a> calls the reader,
3786 passing along its <code>data</code> parameter.
3787 The reader must return a pointer to a block of memory
3788 with a new piece of the chunk
3789 and set <code>size</code> to the block size.
3790 The block must exist until the reader function is called again.
3791 To signal the end of the chunk,
3792 the reader must return <code>NULL</code> or set <code>size</code> to zero.
3793 The reader function may return pieces of any size greater than zero.
3799 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
3800 <span class="apii">[-0, +0, <em>e</em>]</span>
3801 <pre>void lua_register (lua_State *L,
3802 const char *name,
3803 lua_CFunction f);</pre>
3806 Sets the C function <code>f</code> as the new value of global <code>name</code>.
3807 It is defined as a macro:
3809 <pre>
3810 #define lua_register(L,n,f) \
3811 (lua_pushcfunction(L, f), lua_setglobal(L, n))
3812 </pre>
3817 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
3818 <span class="apii">[-1, +0, <em>-</em>]</span>
3819 <pre>void lua_remove (lua_State *L, int index);</pre>
3822 Removes the element at the given valid index,
3823 shifting down the elements above this index to fill the gap.
3824 Cannot be called with a pseudo-index,
3825 because a pseudo-index is not an actual stack position.
3831 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
3832 <span class="apii">[-1, +0, <em>-</em>]</span>
3833 <pre>void lua_replace (lua_State *L, int index);</pre>
3836 Moves the top element into the given position (and pops it),
3837 without shifting any element
3838 (therefore replacing the value at the given position).
3844 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
3845 <span class="apii">[-?, +?, <em>-</em>]</span>
3846 <pre>int lua_resume (lua_State *L, int narg);</pre>
3849 Starts and resumes a coroutine in a given thread.
3853 To start a coroutine, you first create a new thread
3854 (see <a href="#lua_newthread"><code>lua_newthread</code></a>);
3855 then you push onto its stack the main function plus any arguments;
3856 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
3857 with <code>narg</code> being the number of arguments.
3858 This call returns when the coroutine suspends or finishes its execution.
3859 When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
3860 or all values returned by the body function.
3861 <a href="#lua_resume"><code>lua_resume</code></a> returns
3862 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
3863 0 if the coroutine finishes its execution
3864 without errors,
3865 or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
3866 In case of errors,
3867 the stack is not unwound,
3868 so you can use the debug API over it.
3869 The error message is on the top of the stack.
3870 To restart a coroutine, you put on its stack only the values to
3871 be passed as results from <code>yield</code>,
3872 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
3878 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
3879 <span class="apii">[-0, +0, <em>-</em>]</span>
3880 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
3883 Changes the allocator function of a given state to <code>f</code>
3884 with user data <code>ud</code>.
3890 <hr><h3><a name="lua_setfenv"><code>lua_setfenv</code></a></h3><p>
3891 <span class="apii">[-1, +0, <em>-</em>]</span>
3892 <pre>int lua_setfenv (lua_State *L, int index);</pre>
3895 Pops a table from the stack and sets it as
3896 the new environment for the value at the given index.
3897 If the value at the given index is
3898 neither a function nor a thread nor a userdata,
3899 <a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0.
3900 Otherwise it returns 1.
3906 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
3907 <span class="apii">[-1, +0, <em>e</em>]</span>
3908 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
3911 Does the equivalent to <code>t[k] = v</code>,
3912 where <code>t</code> is the value at the given valid index
3913 and <code>v</code> is the value at the top of the stack.
3917 This function pops the value from the stack.
3918 As in Lua, this function may trigger a metamethod
3919 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3925 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
3926 <span class="apii">[-1, +0, <em>e</em>]</span>
3927 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
3930 Pops a value from the stack and
3931 sets it as the new value of global <code>name</code>.
3932 It is defined as a macro:
3934 <pre>
3935 #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
3936 </pre>
3941 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
3942 <span class="apii">[-1, +0, <em>-</em>]</span>
3943 <pre>int lua_setmetatable (lua_State *L, int index);</pre>
3946 Pops a table from the stack and
3947 sets it as the new metatable for the value at the given
3948 acceptable index.
3954 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
3955 <span class="apii">[-2, +0, <em>e</em>]</span>
3956 <pre>void lua_settable (lua_State *L, int index);</pre>
3959 Does the equivalent to <code>t[k] = v</code>,
3960 where <code>t</code> is the value at the given valid index,
3961 <code>v</code> is the value at the top of the stack,
3962 and <code>k</code> is the value just below the top.
3966 This function pops both the key and the value from the stack.
3967 As in Lua, this function may trigger a metamethod
3968 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3974 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
3975 <span class="apii">[-?, +?, <em>-</em>]</span>
3976 <pre>void lua_settop (lua_State *L, int index);</pre>
3979 Accepts any acceptable index, or&nbsp;0,
3980 and sets the stack top to this index.
3981 If the new top is larger than the old one,
3982 then the new elements are filled with <b>nil</b>.
3983 If <code>index</code> is&nbsp;0, then all stack elements are removed.
3989 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
3990 <pre>typedef struct lua_State lua_State;</pre>
3993 Opaque structure that keeps the whole state of a Lua interpreter.
3994 The Lua library is fully reentrant:
3995 it has no global variables.
3996 All information about a state is kept in this structure.
4000 A pointer to this state must be passed as the first argument to
4001 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4002 which creates a Lua state from scratch.
4008 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4009 <span class="apii">[-0, +0, <em>-</em>]</span>
4010 <pre>int lua_status (lua_State *L);</pre>
4013 Returns the status of the thread <code>L</code>.
4017 The status can be 0 for a normal thread,
4018 an error code if the thread finished its execution with an error,
4019 or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4025 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4026 <span class="apii">[-0, +0, <em>-</em>]</span>
4027 <pre>int lua_toboolean (lua_State *L, int index);</pre>
4030 Converts the Lua value at the given acceptable index to a C&nbsp;boolean
4031 value (0&nbsp;or&nbsp;1).
4032 Like all tests in Lua,
4033 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
4034 different from <b>false</b> and <b>nil</b>;
4035 otherwise it returns 0.
4036 It also returns 0 when called with a non-valid index.
4037 (If you want to accept only actual boolean values,
4038 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4044 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4045 <span class="apii">[-0, +0, <em>-</em>]</span>
4046 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4049 Converts a value at the given acceptable index to a C&nbsp;function.
4050 That value must be a C&nbsp;function;
4051 otherwise, returns <code>NULL</code>.
4057 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4058 <span class="apii">[-0, +0, <em>-</em>]</span>
4059 <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4062 Converts the Lua value at the given acceptable index
4063 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4064 The Lua value must be a number or a string convertible to a number
4065 (see <a href="#2.2.1">&sect;2.2.1</a>);
4066 otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns&nbsp;0.
4070 If the number is not an integer,
4071 it is truncated in some non-specified way.
4077 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
4078 <span class="apii">[-0, +0, <em>m</em>]</span>
4079 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
4082 Converts the Lua value at the given acceptable index to a C&nbsp;string.
4083 If <code>len</code> is not <code>NULL</code>,
4084 it also sets <code>*len</code> with the string length.
4085 The Lua value must be a string or a number;
4086 otherwise, the function returns <code>NULL</code>.
4087 If the value is a number,
4088 then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
4089 <em>changes the actual value in the stack to a string</em>.
4090 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
4091 when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys during a table traversal.)
4095 <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
4096 to a string inside the Lua state.
4097 This string always has a zero ('<code>\0</code>')
4098 after its last character (as in&nbsp;C),
4099 but can contain other zeros in its body.
4100 Because Lua has garbage collection,
4101 there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
4102 will be valid after the corresponding value is removed from the stack.
4108 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
4109 <span class="apii">[-0, +0, <em>-</em>]</span>
4110 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
4113 Converts the Lua value at the given acceptable index
4114 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
4115 The Lua value must be a number or a string convertible to a number
4116 (see <a href="#2.2.1">&sect;2.2.1</a>);
4117 otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns&nbsp;0.
4123 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
4124 <span class="apii">[-0, +0, <em>-</em>]</span>
4125 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
4128 Converts the value at the given acceptable index to a generic
4129 C&nbsp;pointer (<code>void*</code>).
4130 The value can be a userdata, a table, a thread, or a function;
4131 otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
4132 Different objects will give different pointers.
4133 There is no way to convert the pointer back to its original value.
4137 Typically this function is used only for debug information.
4143 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
4144 <span class="apii">[-0, +0, <em>m</em>]</span>
4145 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
4148 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4154 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
4155 <span class="apii">[-0, +0, <em>-</em>]</span>
4156 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4159 Converts the value at the given acceptable index to a Lua thread
4160 (represented as <code>lua_State*</code>).
4161 This value must be a thread;
4162 otherwise, the function returns <code>NULL</code>.
4168 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
4169 <span class="apii">[-0, +0, <em>-</em>]</span>
4170 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
4173 If the value at the given acceptable index is a full userdata,
4174 returns its block address.
4175 If the value is a light userdata,
4176 returns its pointer.
4177 Otherwise, returns <code>NULL</code>.
4183 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
4184 <span class="apii">[-0, +0, <em>-</em>]</span>
4185 <pre>int lua_type (lua_State *L, int index);</pre>
4188 Returns the type of the value in the given acceptable index,
4189 or <code>LUA_TNONE</code> for a non-valid index
4190 (that is, an index to an "empty" stack position).
4191 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4192 defined in <code>lua.h</code>:
4193 <code>LUA_TNIL</code>,
4194 <code>LUA_TNUMBER</code>,
4195 <code>LUA_TBOOLEAN</code>,
4196 <code>LUA_TSTRING</code>,
4197 <code>LUA_TTABLE</code>,
4198 <code>LUA_TFUNCTION</code>,
4199 <code>LUA_TUSERDATA</code>,
4200 <code>LUA_TTHREAD</code>,
4202 <code>LUA_TLIGHTUSERDATA</code>.
4208 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
4209 <span class="apii">[-0, +0, <em>-</em>]</span>
4210 <pre>const char *lua_typename (lua_State *L, int tp);</pre>
4213 Returns the name of the type encoded by the value <code>tp</code>,
4214 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4220 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4221 <pre>typedef int (*lua_Writer) (lua_State *L,
4222 const void* p,
4223 size_t sz,
4224 void* ud);</pre>
4227 The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4228 Every time it produces another piece of chunk,
4229 <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4230 passing along the buffer to be written (<code>p</code>),
4231 its size (<code>sz</code>),
4232 and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4236 The writer returns an error code:
4237 0&nbsp;means no errors;
4238 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4239 calling the writer again.
4245 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
4246 <span class="apii">[-?, +?, <em>-</em>]</span>
4247 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4250 Exchange values between different threads of the <em>same</em> global state.
4254 This function pops <code>n</code> values from the stack <code>from</code>,
4255 and pushes them onto the stack <code>to</code>.
4261 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
4262 <span class="apii">[-?, +?, <em>-</em>]</span>
4263 <pre>int lua_yield (lua_State *L, int nresults);</pre>
4266 Yields a coroutine.
4270 This function should only be called as the
4271 return expression of a C&nbsp;function, as follows:
4273 <pre>
4274 return lua_yield (L, nresults);
4275 </pre><p>
4276 When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
4277 the running coroutine suspends its execution,
4278 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
4279 The parameter <code>nresults</code> is the number of values from the stack
4280 that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
4288 <h2>3.8 - <a name="3.8">The Debug Interface</a></h2>
4291 Lua has no built-in debugging facilities.
4292 Instead, it offers a special interface
4293 by means of functions and <em>hooks</em>.
4294 This interface allows the construction of different
4295 kinds of debuggers, profilers, and other tools
4296 that need "inside information" from the interpreter.
4300 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
4301 <pre>typedef struct lua_Debug {
4302 int event;
4303 const char *name; /* (n) */
4304 const char *namewhat; /* (n) */
4305 const char *what; /* (S) */
4306 const char *source; /* (S) */
4307 int currentline; /* (l) */
4308 int nups; /* (u) number of upvalues */
4309 int linedefined; /* (S) */
4310 int lastlinedefined; /* (S) */
4311 char short_src[LUA_IDSIZE]; /* (S) */
4312 /* private part */
4313 <em>other fields</em>
4314 } lua_Debug;</pre>
4317 A structure used to carry different pieces of
4318 information about an active function.
4319 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
4320 of this structure, for later use.
4321 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
4322 call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4326 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
4328 <ul>
4330 <li><b><code>source</code>:</b>
4331 If the function was defined in a string,
4332 then <code>source</code> is that string.
4333 If the function was defined in a file,
4334 then <code>source</code> starts with a '<code>@</code>' followed by the file name.
4335 </li>
4337 <li><b><code>short_src</code>:</b>
4338 a "printable" version of <code>source</code>, to be used in error messages.
4339 </li>
4341 <li><b><code>linedefined</code>:</b>
4342 the line number where the definition of the function starts.
4343 </li>
4345 <li><b><code>lastlinedefined</code>:</b>
4346 the line number where the definition of the function ends.
4347 </li>
4349 <li><b><code>what</code>:</b>
4350 the string <code>"Lua"</code> if the function is a Lua function,
4351 <code>"C"</code> if it is a C&nbsp;function,
4352 <code>"main"</code> if it is the main part of a chunk,
4353 and <code>"tail"</code> if it was a function that did a tail call.
4354 In the latter case,
4355 Lua has no other information about the function.
4356 </li>
4358 <li><b><code>currentline</code>:</b>
4359 the current line where the given function is executing.
4360 When no line information is available,
4361 <code>currentline</code> is set to -1.
4362 </li>
4364 <li><b><code>name</code>:</b>
4365 a reasonable name for the given function.
4366 Because functions in Lua are first-class values,
4367 they do not have a fixed name:
4368 some functions can be the value of multiple global variables,
4369 while others can be stored only in a table field.
4370 The <code>lua_getinfo</code> function checks how the function was
4371 called to find a suitable name.
4372 If it cannot find a name,
4373 then <code>name</code> is set to <code>NULL</code>.
4374 </li>
4376 <li><b><code>namewhat</code>:</b>
4377 explains the <code>name</code> field.
4378 The value of <code>namewhat</code> can be
4379 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
4380 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
4381 according to how the function was called.
4382 (Lua uses the empty string when no other option seems to apply.)
4383 </li>
4385 <li><b><code>nups</code>:</b>
4386 the number of upvalues of the function.
4387 </li>
4389 </ul>
4394 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
4395 <span class="apii">[-0, +0, <em>-</em>]</span>
4396 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
4399 Returns the current hook function.
4405 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
4406 <span class="apii">[-0, +0, <em>-</em>]</span>
4407 <pre>int lua_gethookcount (lua_State *L);</pre>
4410 Returns the current hook count.
4416 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
4417 <span class="apii">[-0, +0, <em>-</em>]</span>
4418 <pre>int lua_gethookmask (lua_State *L);</pre>
4421 Returns the current hook mask.
4427 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
4428 <span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
4429 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
4432 Returns information about a specific function or function invocation.
4436 To get information about a function invocation,
4437 the parameter <code>ar</code> must be a valid activation record that was
4438 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4439 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4443 To get information about a function you push it onto the stack
4444 and start the <code>what</code> string with the character '<code>&gt;</code>'.
4445 (In that case,
4446 <code>lua_getinfo</code> pops the function in the top of the stack.)
4447 For instance, to know in which line a function <code>f</code> was defined,
4448 you can write the following code:
4450 <pre>
4451 lua_Debug ar;
4452 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
4453 lua_getinfo(L, "&gt;S", &amp;ar);
4454 printf("%d\n", ar.linedefined);
4455 </pre>
4458 Each character in the string <code>what</code>
4459 selects some fields of the structure <code>ar</code> to be filled or
4460 a value to be pushed on the stack:
4462 <ul>
4464 <li><b>'<code>n</code>':</b> fills in the field <code>name</code> and <code>namewhat</code>;
4465 </li>
4467 <li><b>'<code>S</code>':</b>
4468 fills in the fields <code>source</code>, <code>short_src</code>,
4469 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
4470 </li>
4472 <li><b>'<code>l</code>':</b> fills in the field <code>currentline</code>;
4473 </li>
4475 <li><b>'<code>u</code>':</b> fills in the field <code>nups</code>;
4476 </li>
4478 <li><b>'<code>f</code>':</b>
4479 pushes onto the stack the function that is
4480 running at the given level;
4481 </li>
4483 <li><b>'<code>L</code>':</b>
4484 pushes onto the stack a table whose indices are the
4485 numbers of the lines that are valid on the function.
4486 (A <em>valid line</em> is a line with some associated code,
4487 that is, a line where you can put a break point.
4488 Non-valid lines include empty lines and comments.)
4489 </li>
4491 </ul>
4494 This function returns 0 on error
4495 (for instance, an invalid option in <code>what</code>).
4501 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
4502 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
4503 <pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4506 Gets information about a local variable of a given activation record.
4507 The parameter <code>ar</code> must be a valid activation record that was
4508 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4509 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4510 The index <code>n</code> selects which local variable to inspect
4511 (1 is the first parameter or active local variable, and so on,
4512 until the last active local variable).
4513 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
4514 and returns its name.
4518 Variable names starting with '<code>(</code>' (open parentheses)
4519 represent internal variables
4520 (loop control variables, temporaries, and C&nbsp;function locals).
4524 Returns <code>NULL</code> (and pushes nothing)
4525 when the index is greater than
4526 the number of active local variables.
4532 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
4533 <span class="apii">[-0, +0, <em>-</em>]</span>
4534 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
4537 Get information about the interpreter runtime stack.
4541 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
4542 an identification of the <em>activation record</em>
4543 of the function executing at a given level.
4544 Level&nbsp;0 is the current running function,
4545 whereas level <em>n+1</em> is the function that has called level <em>n</em>.
4546 When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
4547 when called with a level greater than the stack depth,
4548 it returns 0.
4554 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
4555 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
4556 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
4559 Gets information about a closure's upvalue.
4560 (For Lua functions,
4561 upvalues are the external local variables that the function uses,
4562 and that are consequently included in its closure.)
4563 <a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
4564 pushes the upvalue's value onto the stack,
4565 and returns its name.
4566 <code>funcindex</code> points to the closure in the stack.
4567 (Upvalues have no particular order,
4568 as they are active through the whole function.
4569 So, they are numbered in an arbitrary order.)
4573 Returns <code>NULL</code> (and pushes nothing)
4574 when the index is greater than the number of upvalues.
4575 For C&nbsp;functions, this function uses the empty string <code>""</code>
4576 as a name for all upvalues.
4582 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
4583 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
4586 Type for debugging hook functions.
4590 Whenever a hook is called, its <code>ar</code> argument has its field
4591 <code>event</code> set to the specific event that triggered the hook.
4592 Lua identifies these events with the following constants:
4593 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
4594 <a name="pdf-LUA_HOOKTAILRET"><code>LUA_HOOKTAILRET</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
4595 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
4596 Moreover, for line events, the field <code>currentline</code> is also set.
4597 To get the value of any other field in <code>ar</code>,
4598 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4599 For return events, <code>event</code> can be <code>LUA_HOOKRET</code>,
4600 the normal value, or <code>LUA_HOOKTAILRET</code>.
4601 In the latter case, Lua is simulating a return from
4602 a function that did a tail call;
4603 in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4607 While Lua is running a hook, it disables other calls to hooks.
4608 Therefore, if a hook calls back Lua to execute a function or a chunk,
4609 this execution occurs without any calls to hooks.
4615 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
4616 <span class="apii">[-0, +0, <em>-</em>]</span>
4617 <pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
4620 Sets the debugging hook function.
4624 Argument <code>f</code> is the hook function.
4625 <code>mask</code> specifies on which events the hook will be called:
4626 it is formed by a bitwise or of the constants
4627 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
4628 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
4629 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
4630 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
4631 The <code>count</code> argument is only meaningful when the mask
4632 includes <code>LUA_MASKCOUNT</code>.
4633 For each event, the hook is called as explained below:
4635 <ul>
4637 <li><b>The call hook:</b> is called when the interpreter calls a function.
4638 The hook is called just after Lua enters the new function,
4639 before the function gets its arguments.
4640 </li>
4642 <li><b>The return hook:</b> is called when the interpreter returns from a function.
4643 The hook is called just before Lua leaves the function.
4644 You have no access to the values to be returned by the function.
4645 </li>
4647 <li><b>The line hook:</b> is called when the interpreter is about to
4648 start the execution of a new line of code,
4649 or when it jumps back in the code (even to the same line).
4650 (This event only happens while Lua is executing a Lua function.)
4651 </li>
4653 <li><b>The count hook:</b> is called after the interpreter executes every
4654 <code>count</code> instructions.
4655 (This event only happens while Lua is executing a Lua function.)
4656 </li>
4658 </ul>
4661 A hook is disabled by setting <code>mask</code> to zero.
4667 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
4668 <span class="apii">[-(0|1), +0, <em>-</em>]</span>
4669 <pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4672 Sets the value of a local variable of a given activation record.
4673 Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
4674 (see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
4675 <a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
4676 to the variable and returns its name.
4677 It also pops the value from the stack.
4681 Returns <code>NULL</code> (and pops nothing)
4682 when the index is greater than
4683 the number of active local variables.
4689 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
4690 <span class="apii">[-(0|1), +0, <em>-</em>]</span>
4691 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
4694 Sets the value of a closure's upvalue.
4695 It assigns the value at the top of the stack
4696 to the upvalue and returns its name.
4697 It also pops the value from the stack.
4698 Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
4699 (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
4703 Returns <code>NULL</code> (and pops nothing)
4704 when the index is greater than the number of upvalues.
4712 <h1>4 - <a name="4">The Auxiliary Library</a></h1>
4716 The <em>auxiliary library</em> provides several convenient functions
4717 to interface C with Lua.
4718 While the basic API provides the primitive functions for all
4719 interactions between C and Lua,
4720 the auxiliary library provides higher-level functions for some
4721 common tasks.
4725 All functions from the auxiliary library
4726 are defined in header file <code>lauxlib.h</code> and
4727 have a prefix <code>luaL_</code>.
4731 All functions in the auxiliary library are built on
4732 top of the basic API,
4733 and so they provide nothing that cannot be done with this API.
4737 Several functions in the auxiliary library are used to
4738 check C&nbsp;function arguments.
4739 Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
4740 All of these functions throw an error if the check is not satisfied.
4741 Because the error message is formatted for arguments
4742 (e.g., "<code>bad argument #1</code>"),
4743 you should not use these functions for other stack values.
4747 <h2>4.1 - <a name="4.1">Functions and Types</a></h2>
4750 Here we list all functions and types from the auxiliary library
4751 in alphabetical order.
4755 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
4756 <span class="apii">[-0, +0, <em>m</em>]</span>
4757 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
4760 Adds the character <code>c</code> to the buffer <code>B</code>
4761 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4767 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
4768 <span class="apii">[-0, +0, <em>m</em>]</span>
4769 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
4772 Adds the string pointed to by <code>s</code> with length <code>l</code> to
4773 the buffer <code>B</code>
4774 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4775 The string may contain embedded zeros.
4781 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
4782 <span class="apii">[-0, +0, <em>m</em>]</span>
4783 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
4786 Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
4787 a string of length <code>n</code> previously copied to the
4788 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
4794 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
4795 <span class="apii">[-0, +0, <em>m</em>]</span>
4796 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
4799 Adds the zero-terminated string pointed to by <code>s</code>
4800 to the buffer <code>B</code>
4801 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4802 The string may not contain embedded zeros.
4808 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
4809 <span class="apii">[-1, +0, <em>m</em>]</span>
4810 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
4813 Adds the value at the top of the stack
4814 to the buffer <code>B</code>
4815 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4816 Pops the value.
4820 This is the only function on string buffers that can (and must)
4821 be called with an extra element on the stack,
4822 which is the value to be added to the buffer.
4828 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
4829 <span class="apii">[-0, +0, <em>v</em>]</span>
4830 <pre>void luaL_argcheck (lua_State *L,
4831 int cond,
4832 int narg,
4833 const char *extramsg);</pre>
4836 Checks whether <code>cond</code> is true.
4837 If not, 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>
4847 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
4848 <span class="apii">[-0, +0, <em>v</em>]</span>
4849 <pre>int luaL_argerror (lua_State *L, int narg, const char *extramsg);</pre>
4852 Raises an error with the following message,
4853 where <code>func</code> is retrieved from the call stack:
4855 <pre>
4856 bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4857 </pre>
4860 This function never returns,
4861 but it is an idiom to use it in C&nbsp;functions
4862 as <code>return luaL_argerror(<em>args</em>)</code>.
4868 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
4869 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
4872 Type for a <em>string buffer</em>.
4876 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
4877 Its pattern of use is as follows:
4879 <ul>
4881 <li>First you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
4883 <li>Then you initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
4885 <li>
4886 Then you add string pieces to the buffer calling any of
4887 the <code>luaL_add*</code> functions.
4888 </li>
4890 <li>
4891 You finish by calling <code>luaL_pushresult(&amp;b)</code>.
4892 This call leaves the final string on the top of the stack.
4893 </li>
4895 </ul>
4898 During its normal operation,
4899 a string buffer uses a variable number of stack slots.
4900 So, while using a buffer, you cannot assume that you know where
4901 the top of the stack is.
4902 You can use the stack between successive calls to buffer operations
4903 as long as that use is balanced;
4904 that is,
4905 when you call a buffer operation,
4906 the stack is at the same level
4907 it was immediately after the previous buffer operation.
4908 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
4909 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
4910 level when the buffer was initialized,
4911 plus the final string on its top.
4917 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
4918 <span class="apii">[-0, +0, <em>-</em>]</span>
4919 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
4922 Initializes a buffer <code>B</code>.
4923 This function does not allocate any space;
4924 the buffer must be declared as a variable
4925 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4931 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
4932 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
4933 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
4936 Calls a metamethod.
4940 If the object at index <code>obj</code> has a metatable and this
4941 metatable has a field <code>e</code>,
4942 this function calls this field and passes the object as its only argument.
4943 In this case this function returns 1 and pushes onto the
4944 stack the value returned by the call.
4945 If there is no metatable or no metamethod,
4946 this function returns 0 (without pushing any value on the stack).
4952 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
4953 <span class="apii">[-0, +0, <em>v</em>]</span>
4954 <pre>void luaL_checkany (lua_State *L, int narg);</pre>
4957 Checks whether the function has an argument
4958 of any type (including <b>nil</b>) at position <code>narg</code>.
4964 <hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
4965 <span class="apii">[-0, +0, <em>v</em>]</span>
4966 <pre>int luaL_checkint (lua_State *L, int narg);</pre>
4969 Checks whether the function argument <code>narg</code> is a number
4970 and returns this number cast to an <code>int</code>.
4976 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
4977 <span class="apii">[-0, +0, <em>v</em>]</span>
4978 <pre>lua_Integer luaL_checkinteger (lua_State *L, int narg);</pre>
4981 Checks whether the function argument <code>narg</code> is a number
4982 and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
4988 <hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
4989 <span class="apii">[-0, +0, <em>v</em>]</span>
4990 <pre>long luaL_checklong (lua_State *L, int narg);</pre>
4993 Checks whether the function argument <code>narg</code> is a number
4994 and returns this number cast to a <code>long</code>.
5000 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
5001 <span class="apii">[-0, +0, <em>v</em>]</span>
5002 <pre>const char *luaL_checklstring (lua_State *L, int narg, size_t *l);</pre>
5005 Checks whether the function argument <code>narg</code> is a string
5006 and returns this string;
5007 if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
5008 with the string's length.
5012 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5013 so all conversions and caveats of that function apply here.
5019 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
5020 <span class="apii">[-0, +0, <em>v</em>]</span>
5021 <pre>lua_Number luaL_checknumber (lua_State *L, int narg);</pre>
5024 Checks whether the function argument <code>narg</code> is a number
5025 and returns this number.
5031 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
5032 <span class="apii">[-0, +0, <em>v</em>]</span>
5033 <pre>int luaL_checkoption (lua_State *L,
5034 int narg,
5035 const char *def,
5036 const char *const lst[]);</pre>
5039 Checks whether the function argument <code>narg</code> is a string and
5040 searches for this string in the array <code>lst</code>
5041 (which must be NULL-terminated).
5042 Returns the index in the array where the string was found.
5043 Raises an error if the argument is not a string or
5044 if the string cannot be found.
5048 If <code>def</code> is not <code>NULL</code>,
5049 the function uses <code>def</code> as a default value when
5050 there is no argument <code>narg</code> or if this argument is <b>nil</b>.
5054 This is a useful function for mapping strings to C&nbsp;enums.
5055 (The usual convention in Lua libraries is
5056 to use strings instead of numbers to select options.)
5062 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
5063 <span class="apii">[-0, +0, <em>v</em>]</span>
5064 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
5067 Grows the stack size to <code>top + sz</code> elements,
5068 raising an error if the stack cannot grow to that size.
5069 <code>msg</code> is an additional text to go into the error message.
5075 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
5076 <span class="apii">[-0, +0, <em>v</em>]</span>
5077 <pre>const char *luaL_checkstring (lua_State *L, int narg);</pre>
5080 Checks whether the function argument <code>narg</code> is a string
5081 and returns this string.
5085 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5086 so all conversions and caveats of that function apply here.
5092 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
5093 <span class="apii">[-0, +0, <em>v</em>]</span>
5094 <pre>void luaL_checktype (lua_State *L, int narg, int t);</pre>
5097 Checks whether the function argument <code>narg</code> has type <code>t</code>.
5098 See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
5104 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
5105 <span class="apii">[-0, +0, <em>v</em>]</span>
5106 <pre>void *luaL_checkudata (lua_State *L, int narg, const char *tname);</pre>
5109 Checks whether the function argument <code>narg</code> is a userdata
5110 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5116 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
5117 <span class="apii">[-0, +?, <em>m</em>]</span>
5118 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
5121 Loads and runs the given file.
5122 It is defined as the following macro:
5124 <pre>
5125 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
5126 </pre><p>
5127 It returns 0 if there are no errors
5128 or 1 in case of errors.
5134 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
5135 <span class="apii">[-0, +?, <em>m</em>]</span>
5136 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
5139 Loads and runs the given string.
5140 It is defined as the following macro:
5142 <pre>
5143 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
5144 </pre><p>
5145 It returns 0 if there are no errors
5146 or 1 in case of errors.
5152 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
5153 <span class="apii">[-0, +0, <em>v</em>]</span>
5154 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
5157 Raises an error.
5158 The error message format is given by <code>fmt</code>
5159 plus any extra arguments,
5160 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
5161 It also adds at the beginning of the message the file name and
5162 the line number where the error occurred,
5163 if this information is available.
5167 This function never returns,
5168 but it is an idiom to use it in C&nbsp;functions
5169 as <code>return luaL_error(<em>args</em>)</code>.
5175 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
5176 <span class="apii">[-0, +(0|1), <em>m</em>]</span>
5177 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
5180 Pushes onto the stack the field <code>e</code> from the metatable
5181 of the object at index <code>obj</code>.
5182 If the object does not have a metatable,
5183 or if the metatable does not have this field,
5184 returns 0 and pushes nothing.
5190 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
5191 <span class="apii">[-0, +1, <em>-</em>]</span>
5192 <pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
5195 Pushes onto the stack the metatable associated with name <code>tname</code>
5196 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5202 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
5203 <span class="apii">[-0, +1, <em>m</em>]</span>
5204 <pre>const char *luaL_gsub (lua_State *L,
5205 const char *s,
5206 const char *p,
5207 const char *r);</pre>
5210 Creates a copy of string <code>s</code> by replacing
5211 any occurrence of the string <code>p</code>
5212 with the string <code>r</code>.
5213 Pushes the resulting string on the stack and returns it.
5219 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
5220 <span class="apii">[-0, +1, <em>m</em>]</span>
5221 <pre>int luaL_loadbuffer (lua_State *L,
5222 const char *buff,
5223 size_t sz,
5224 const char *name);</pre>
5227 Loads a buffer as a Lua chunk.
5228 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
5229 buffer pointed to by <code>buff</code> with size <code>sz</code>.
5233 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5234 <code>name</code> is the chunk name,
5235 used for debug information and error messages.
5241 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
5242 <span class="apii">[-0, +1, <em>m</em>]</span>
5243 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
5246 Loads a file as a Lua chunk.
5247 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
5248 named <code>filename</code>.
5249 If <code>filename</code> is <code>NULL</code>,
5250 then it loads from the standard input.
5251 The first line in the file is ignored if it starts with a <code>#</code>.
5255 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
5256 but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
5257 if it cannot open/read the file.
5261 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5262 it does not run it.
5268 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
5269 <span class="apii">[-0, +1, <em>m</em>]</span>
5270 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
5273 Loads a string as a Lua chunk.
5274 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
5275 the zero-terminated string <code>s</code>.
5279 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5283 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5284 it does not run it.
5290 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
5291 <span class="apii">[-0, +1, <em>m</em>]</span>
5292 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
5295 If the registry already has the key <code>tname</code>,
5296 returns 0.
5297 Otherwise,
5298 creates a new table to be used as a metatable for userdata,
5299 adds it to the registry with key <code>tname</code>,
5300 and returns 1.
5304 In both cases pushes onto the stack the final value associated
5305 with <code>tname</code> in the registry.
5311 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
5312 <span class="apii">[-0, +0, <em>-</em>]</span>
5313 <pre>lua_State *luaL_newstate (void);</pre>
5316 Creates a new Lua state.
5317 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
5318 allocator based on the standard&nbsp;C <code>realloc</code> function
5319 and then sets a panic function (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) that prints
5320 an error message to the standard error output in case of fatal
5321 errors.
5325 Returns the new state,
5326 or <code>NULL</code> if there is a memory allocation error.
5332 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
5333 <span class="apii">[-0, +0, <em>m</em>]</span>
5334 <pre>void luaL_openlibs (lua_State *L);</pre>
5337 Opens all standard Lua libraries into the given state.
5343 <hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
5344 <span class="apii">[-0, +0, <em>v</em>]</span>
5345 <pre>int luaL_optint (lua_State *L, int narg, int d);</pre>
5348 If the function argument <code>narg</code> is a number,
5349 returns this number cast to an <code>int</code>.
5350 If this argument is absent or is <b>nil</b>,
5351 returns <code>d</code>.
5352 Otherwise, raises an error.
5358 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
5359 <span class="apii">[-0, +0, <em>v</em>]</span>
5360 <pre>lua_Integer luaL_optinteger (lua_State *L,
5361 int narg,
5362 lua_Integer d);</pre>
5365 If the function argument <code>narg</code> is a number,
5366 returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
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_optlong"><code>luaL_optlong</code></a></h3><p>
5376 <span class="apii">[-0, +0, <em>v</em>]</span>
5377 <pre>long luaL_optlong (lua_State *L, int narg, long d);</pre>
5380 If the function argument <code>narg</code> is a number,
5381 returns this number cast to a <code>long</code>.
5382 If this argument is absent or is <b>nil</b>,
5383 returns <code>d</code>.
5384 Otherwise, raises an error.
5390 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
5391 <span class="apii">[-0, +0, <em>v</em>]</span>
5392 <pre>const char *luaL_optlstring (lua_State *L,
5393 int narg,
5394 const char *d,
5395 size_t *l);</pre>
5398 If the function argument <code>narg</code> is a string,
5399 returns this string.
5400 If this argument is absent or is <b>nil</b>,
5401 returns <code>d</code>.
5402 Otherwise, raises an error.
5406 If <code>l</code> is not <code>NULL</code>,
5407 fills the position <code>*l</code> with the results's length.
5413 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
5414 <span class="apii">[-0, +0, <em>v</em>]</span>
5415 <pre>lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);</pre>
5418 If the function argument <code>narg</code> is a number,
5419 returns this number.
5420 If this argument is absent or is <b>nil</b>,
5421 returns <code>d</code>.
5422 Otherwise, raises an error.
5428 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
5429 <span class="apii">[-0, +0, <em>v</em>]</span>
5430 <pre>const char *luaL_optstring (lua_State *L,
5431 int narg,
5432 const char *d);</pre>
5435 If the function argument <code>narg</code> is a string,
5436 returns this string.
5437 If this argument is absent or is <b>nil</b>,
5438 returns <code>d</code>.
5439 Otherwise, raises an error.
5445 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
5446 <span class="apii">[-0, +0, <em>-</em>]</span>
5447 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
5450 Returns an address to a space of size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>
5451 where you can copy a string to be added to buffer <code>B</code>
5452 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5453 After copying the string into this space you must call
5454 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
5455 it to the buffer.
5461 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
5462 <span class="apii">[-?, +1, <em>m</em>]</span>
5463 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
5466 Finishes the use of buffer <code>B</code> leaving the final string on
5467 the top of the stack.
5473 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
5474 <span class="apii">[-1, +0, <em>m</em>]</span>
5475 <pre>int luaL_ref (lua_State *L, int t);</pre>
5478 Creates and returns a <em>reference</em>,
5479 in the table at index <code>t</code>,
5480 for the object at the top of the stack (and pops the object).
5484 A reference is a unique integer key.
5485 As long as you do not manually add integer keys into table <code>t</code>,
5486 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
5487 You can retrieve an object referred by reference <code>r</code>
5488 by calling <code>lua_rawgeti(L, t, r)</code>.
5489 Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
5493 If the object at the top of the stack is <b>nil</b>,
5494 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
5495 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
5496 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
5502 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
5503 <pre>typedef struct luaL_Reg {
5504 const char *name;
5505 lua_CFunction func;
5506 } luaL_Reg;</pre>
5509 Type for arrays of functions to be registered by
5510 <a href="#luaL_register"><code>luaL_register</code></a>.
5511 <code>name</code> is the function name and <code>func</code> is a pointer to
5512 the function.
5513 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
5514 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
5520 <hr><h3><a name="luaL_register"><code>luaL_register</code></a></h3><p>
5521 <span class="apii">[-(0|1), +1, <em>m</em>]</span>
5522 <pre>void luaL_register (lua_State *L,
5523 const char *libname,
5524 const luaL_Reg *l);</pre>
5527 Opens a library.
5531 When called with <code>libname</code> equal to <code>NULL</code>,
5532 it simply registers all functions in the list <code>l</code>
5533 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
5537 When called with a non-null <code>libname</code>,
5538 <code>luaL_register</code> creates a new table <code>t</code>,
5539 sets it as the value of the global variable <code>libname</code>,
5540 sets it as the value of <code>package.loaded[libname]</code>,
5541 and registers on it all functions in the list <code>l</code>.
5542 If there is a table in <code>package.loaded[libname]</code> or in
5543 variable <code>libname</code>,
5544 reuses this table instead of creating a new one.
5548 In any case the function leaves the table
5549 on the top of the stack.
5555 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
5556 <span class="apii">[-0, +0, <em>-</em>]</span>
5557 <pre>const char *luaL_typename (lua_State *L, int index);</pre>
5560 Returns the name of the type of the value at the given index.
5566 <hr><h3><a name="luaL_typerror"><code>luaL_typerror</code></a></h3><p>
5567 <span class="apii">[-0, +0, <em>v</em>]</span>
5568 <pre>int luaL_typerror (lua_State *L, int narg, const char *tname);</pre>
5571 Generates an error with a message like the following:
5573 <pre>
5574 <em>location</em>: bad argument <em>narg</em> to '<em>func</em>' (<em>tname</em> expected, got <em>rt</em>)
5575 </pre><p>
5576 where <code><em>location</em></code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
5577 <code><em>func</em></code> is the name of the current function,
5578 and <code><em>rt</em></code> is the type name of the actual argument.
5584 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
5585 <span class="apii">[-0, +0, <em>-</em>]</span>
5586 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
5589 Releases reference <code>ref</code> from the table at index <code>t</code>
5590 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
5591 The entry is removed from the table,
5592 so that the referred object can be collected.
5593 The reference <code>ref</code> is also freed to be used again.
5597 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>,
5598 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
5604 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
5605 <span class="apii">[-0, +1, <em>m</em>]</span>
5606 <pre>void luaL_where (lua_State *L, int lvl);</pre>
5609 Pushes onto the stack a string identifying the current position
5610 of the control at level <code>lvl</code> in the call stack.
5611 Typically this string has the following format:
5613 <pre>
5614 <em>chunkname</em>:<em>currentline</em>:
5615 </pre><p>
5616 Level&nbsp;0 is the running function,
5617 level&nbsp;1 is the function that called the running function,
5618 etc.
5622 This function is used to build a prefix for error messages.
5630 <h1>5 - <a name="5">Standard Libraries</a></h1>
5633 The standard Lua libraries provide useful functions
5634 that are implemented directly through the C&nbsp;API.
5635 Some of these functions provide essential services to the language
5636 (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
5637 others provide access to "outside" services (e.g., I/O);
5638 and others could be implemented in Lua itself,
5639 but are quite useful or have critical performance requirements that
5640 deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
5644 All libraries are implemented through the official C&nbsp;API
5645 and are provided as separate C&nbsp;modules.
5646 Currently, Lua has the following standard libraries:
5648 <ul>
5650 <li>basic library, which includes the coroutine sub-library;</li>
5652 <li>package library;</li>
5654 <li>string manipulation;</li>
5656 <li>table manipulation;</li>
5658 <li>mathematical functions (sin, log, etc.);</li>
5660 <li>input and output;</li>
5662 <li>operating system facilities;</li>
5664 <li>debug facilities.</li>
5666 </ul><p>
5667 Except for the basic and package libraries,
5668 each library provides all its functions as fields of a global table
5669 or as methods of its objects.
5673 To have access to these libraries,
5674 the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
5675 which opens all standard libraries.
5676 Alternatively,
5677 it can open them individually by calling
5678 <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
5679 <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
5680 <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
5681 <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
5682 <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
5683 <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
5684 <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
5685 and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
5686 These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>
5687 and should not be called directly:
5688 you must call them like any other Lua C&nbsp;function,
5689 e.g., by using <a href="#lua_call"><code>lua_call</code></a>.
5693 <h2>5.1 - <a name="5.1">Basic Functions</a></h2>
5696 The basic library provides some core functions to Lua.
5697 If you do not include this library in your application,
5698 you should check carefully whether you need to provide
5699 implementations for some of its facilities.
5703 <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
5704 Issues an error when
5705 the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
5706 otherwise, returns all its arguments.
5707 <code>message</code> is an error message;
5708 when absent, it defaults to "assertion failed!"
5714 <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
5718 This function is a generic interface to the garbage collector.
5719 It performs different functions according to its first argument, <code>opt</code>:
5721 <ul>
5723 <li><b>"collect":</b>
5724 performs a full garbage-collection cycle.
5725 This is the default option.
5726 </li>
5728 <li><b>"stop":</b>
5729 stops the garbage collector.
5730 </li>
5732 <li><b>"restart":</b>
5733 restarts the garbage collector.
5734 </li>
5736 <li><b>"count":</b>
5737 returns the total memory in use by Lua (in Kbytes).
5738 </li>
5740 <li><b>"step":</b>
5741 performs a garbage-collection step.
5742 The step "size" is controlled by <code>arg</code>
5743 (larger values mean more steps) in a non-specified way.
5744 If you want to control the step size
5745 you must experimentally tune the value of <code>arg</code>.
5746 Returns <b>true</b> if the step finished a collection cycle.
5747 </li>
5749 <li><b>"setpause":</b>
5750 sets <code>arg</code> as the new value for the <em>pause</em> of
5751 the collector (see <a href="#2.10">&sect;2.10</a>).
5752 Returns the previous value for <em>pause</em>.
5753 </li>
5755 <li><b>"setstepmul":</b>
5756 sets <code>arg</code> as the new value for the <em>step multiplier</em> of
5757 the collector (see <a href="#2.10">&sect;2.10</a>).
5758 Returns the previous value for <em>step</em>.
5759 </li>
5761 </ul>
5766 <hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
5767 Opens the named file and executes its contents as a Lua chunk.
5768 When called without arguments,
5769 <code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
5770 Returns all values returned by the chunk.
5771 In case of errors, <code>dofile</code> propagates the error
5772 to its caller (that is, <code>dofile</code> does not run in protected mode).
5778 <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
5779 Terminates the last protected function called
5780 and returns <code>message</code> as the error message.
5781 Function <code>error</code> never returns.
5785 Usually, <code>error</code> adds some information about the error position
5786 at the beginning of the message.
5787 The <code>level</code> argument specifies how to get the error position.
5788 With level&nbsp;1 (the default), the error position is where the
5789 <code>error</code> function was called.
5790 Level&nbsp;2 points the error to where the function
5791 that called <code>error</code> was called; and so on.
5792 Passing a level&nbsp;0 avoids the addition of error position information
5793 to the message.
5799 <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
5800 A global variable (not a function) that
5801 holds the global environment (that is, <code>_G._G = _G</code>).
5802 Lua itself does not use this variable;
5803 changing its value does not affect any environment,
5804 nor vice-versa.
5805 (Use <a href="#pdf-setfenv"><code>setfenv</code></a> to change environments.)
5811 <hr><h3><a name="pdf-getfenv"><code>getfenv ([f])</code></a></h3>
5812 Returns the current environment in use by the function.
5813 <code>f</code> can be a Lua function or a number
5814 that specifies the function at that stack level:
5815 Level&nbsp;1 is the function calling <code>getfenv</code>.
5816 If the given function is not a Lua function,
5817 or if <code>f</code> is 0,
5818 <code>getfenv</code> returns the global environment.
5819 The default for <code>f</code> is 1.
5825 <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
5829 If <code>object</code> does not have a metatable, returns <b>nil</b>.
5830 Otherwise,
5831 if the object's metatable has a <code>"__metatable"</code> field,
5832 returns the associated value.
5833 Otherwise, returns the metatable of the given object.
5839 <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
5843 Returns three values: an iterator function, the table <code>t</code>, and 0,
5844 so that the construction
5846 <pre>
5847 for i,v in ipairs(t) do <em>body</em> end
5848 </pre><p>
5849 will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), &middot;&middot;&middot;,
5850 up to the first integer key absent from the table.
5856 <hr><h3><a name="pdf-load"><code>load (func [, chunkname])</code></a></h3>
5860 Loads a chunk using function <code>func</code> to get its pieces.
5861 Each call to <code>func</code> must return a string that concatenates
5862 with previous results.
5863 A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
5867 If there are no errors,
5868 returns the compiled chunk as a function;
5869 otherwise, returns <b>nil</b> plus the error message.
5870 The environment of the returned function is the global environment.
5874 <code>chunkname</code> is used as the chunk name for error messages
5875 and debug information.
5876 When absent,
5877 it defaults to "<code>=(load)</code>".
5883 <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename])</code></a></h3>
5887 Similar to <a href="#pdf-load"><code>load</code></a>,
5888 but gets the chunk from file <code>filename</code>
5889 or from the standard input,
5890 if no file name is given.
5896 <hr><h3><a name="pdf-loadstring"><code>loadstring (string [, chunkname])</code></a></h3>
5900 Similar to <a href="#pdf-load"><code>load</code></a>,
5901 but gets the chunk from the given string.
5905 To load and run a given string, use the idiom
5907 <pre>
5908 assert(loadstring(s))()
5909 </pre>
5912 When absent,
5913 <code>chunkname</code> defaults to the given string.
5919 <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
5923 Allows a program to traverse all fields of a table.
5924 Its first argument is a table and its second argument
5925 is an index in this table.
5926 <code>next</code> returns the next index of the table
5927 and its associated value.
5928 When called with <b>nil</b> as its second argument,
5929 <code>next</code> returns an initial index
5930 and its associated value.
5931 When called with the last index,
5932 or with <b>nil</b> in an empty table,
5933 <code>next</code> returns <b>nil</b>.
5934 If the second argument is absent, then it is interpreted as <b>nil</b>.
5935 In particular,
5936 you can use <code>next(t)</code> to check whether a table is empty.
5940 The order in which the indices are enumerated is not specified,
5941 <em>even for numeric indices</em>.
5942 (To traverse a table in numeric order,
5943 use a numerical <b>for</b> or the <a href="#pdf-ipairs"><code>ipairs</code></a> function.)
5947 The behavior of <code>next</code> is <em>undefined</em> if,
5948 during the traversal,
5949 you assign any value to a non-existent field in the table.
5950 You may however modify existing fields.
5951 In particular, you may clear existing fields.
5957 <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
5961 Returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
5962 so that the construction
5964 <pre>
5965 for k,v in pairs(t) do <em>body</em> end
5966 </pre><p>
5967 will iterate over all key&ndash;value pairs of table <code>t</code>.
5971 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
5972 the table during its traversal.
5978 <hr><h3><a name="pdf-pcall"><code>pcall (f, arg1, &middot;&middot;&middot;)</code></a></h3>
5982 Calls function <code>f</code> with
5983 the given arguments in <em>protected mode</em>.
5984 This means that any error inside&nbsp;<code>f</code> is not propagated;
5985 instead, <code>pcall</code> catches the error
5986 and returns a status code.
5987 Its first result is the status code (a boolean),
5988 which is true if the call succeeds without errors.
5989 In such case, <code>pcall</code> also returns all results from the call,
5990 after this first result.
5991 In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
5997 <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
5998 Receives any number of arguments,
5999 and prints their values to <code>stdout</code>,
6000 using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert them to strings.
6001 <code>print</code> is not intended for formatted output,
6002 but only as a quick way to show a value,
6003 typically for debugging.
6004 For formatted output, use <a href="#pdf-string.format"><code>string.format</code></a>.
6010 <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
6011 Checks whether <code>v1</code> is equal to <code>v2</code>,
6012 without invoking any metamethod.
6013 Returns a boolean.
6019 <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
6020 Gets the real value of <code>table[index]</code>,
6021 without invoking any metamethod.
6022 <code>table</code> must be a table;
6023 <code>index</code> may be any value.
6029 <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
6030 Sets the real value of <code>table[index]</code> to <code>value</code>,
6031 without invoking any metamethod.
6032 <code>table</code> must be a table,
6033 <code>index</code> any value different from <b>nil</b>,
6034 and <code>value</code> any Lua value.
6038 This function returns <code>table</code>.
6044 <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
6048 If <code>index</code> is a number,
6049 returns all arguments after argument number <code>index</code>.
6050 Otherwise, <code>index</code> must be the string <code>"#"</code>,
6051 and <code>select</code> returns the total number of extra arguments it received.
6057 <hr><h3><a name="pdf-setfenv"><code>setfenv (f, table)</code></a></h3>
6061 Sets the environment to be used by the given function.
6062 <code>f</code> can be a Lua function or a number
6063 that specifies the function at that stack level:
6064 Level&nbsp;1 is the function calling <code>setfenv</code>.
6065 <code>setfenv</code> returns the given function.
6069 As a special case, when <code>f</code> is 0 <code>setfenv</code> changes
6070 the environment of the running thread.
6071 In this case, <code>setfenv</code> returns no values.
6077 <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
6081 Sets the metatable for the given table.
6082 (You cannot change the metatable of other types from Lua, only from&nbsp;C.)
6083 If <code>metatable</code> is <b>nil</b>,
6084 removes the metatable of the given table.
6085 If the original metatable has a <code>"__metatable"</code> field,
6086 raises an error.
6090 This function returns <code>table</code>.
6096 <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
6097 Tries to convert its argument to a number.
6098 If the argument is already a number or a string convertible
6099 to a number, then <code>tonumber</code> returns this number;
6100 otherwise, it returns <b>nil</b>.
6104 An optional argument specifies the base to interpret the numeral.
6105 The base may be any integer between 2 and 36, inclusive.
6106 In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
6107 represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
6108 with '<code>Z</code>' representing 35.
6109 In base 10 (the default), the number can have a decimal part,
6110 as well as an optional exponent part (see <a href="#2.1">&sect;2.1</a>).
6111 In other bases, only unsigned integers are accepted.
6117 <hr><h3><a name="pdf-tostring"><code>tostring (e)</code></a></h3>
6118 Receives an argument of any type and
6119 converts it to a string in a reasonable format.
6120 For complete control of how numbers are converted,
6121 use <a href="#pdf-string.format"><code>string.format</code></a>.
6125 If the metatable of <code>e</code> has a <code>"__tostring"</code> field,
6126 then <code>tostring</code> calls the corresponding value
6127 with <code>e</code> as argument,
6128 and uses the result of the call as its result.
6134 <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
6135 Returns the type of its only argument, coded as a string.
6136 The possible results of this function are
6137 "<code>nil</code>" (a string, not the value <b>nil</b>),
6138 "<code>number</code>",
6139 "<code>string</code>",
6140 "<code>boolean</code>",
6141 "<code>table</code>",
6142 "<code>function</code>",
6143 "<code>thread</code>",
6144 and "<code>userdata</code>".
6150 <hr><h3><a name="pdf-unpack"><code>unpack (list [, i [, j]])</code></a></h3>
6151 Returns the elements from the given table.
6152 This function is equivalent to
6154 <pre>
6155 return list[i], list[i+1], &middot;&middot;&middot;, list[j]
6156 </pre><p>
6157 except that the above code can be written only for a fixed number
6158 of elements.
6159 By default, <code>i</code> is&nbsp;1 and <code>j</code> is the length of the list,
6160 as defined by the length operator (see <a href="#2.5.5">&sect;2.5.5</a>).
6166 <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
6167 A global variable (not a function) that
6168 holds a string containing the current interpreter version.
6169 The current contents of this variable is "<code>Lua 5.1</code>".
6175 <hr><h3><a name="pdf-xpcall"><code>xpcall (f, err)</code></a></h3>
6179 This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
6180 except that you can set a new error handler.
6184 <code>xpcall</code> calls function <code>f</code> in protected mode,
6185 using <code>err</code> as the error handler.
6186 Any error inside <code>f</code> is not propagated;
6187 instead, <code>xpcall</code> catches the error,
6188 calls the <code>err</code> function with the original error object,
6189 and returns a status code.
6190 Its first result is the status code (a boolean),
6191 which is true if the call succeeds without errors.
6192 In this case, <code>xpcall</code> also returns all results from the call,
6193 after this first result.
6194 In case of any error,
6195 <code>xpcall</code> returns <b>false</b> plus the result from <code>err</code>.
6203 <h2>5.2 - <a name="5.2">Coroutine Manipulation</a></h2>
6206 The operations related to coroutines comprise a sub-library of
6207 the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
6208 See <a href="#2.11">&sect;2.11</a> for a general description of coroutines.
6212 <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
6216 Creates a new coroutine, with body <code>f</code>.
6217 <code>f</code> must be a Lua function.
6218 Returns this new coroutine,
6219 an object with type <code>"thread"</code>.
6225 <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
6229 Starts or continues the execution of coroutine <code>co</code>.
6230 The first time you resume a coroutine,
6231 it starts running its body.
6232 The values <code>val1</code>, &middot;&middot;&middot; are passed
6233 as the arguments to the body function.
6234 If the coroutine has yielded,
6235 <code>resume</code> restarts it;
6236 the values <code>val1</code>, &middot;&middot;&middot; are passed
6237 as the results from the yield.
6241 If the coroutine runs without any errors,
6242 <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
6243 (if the coroutine yields) or any values returned by the body function
6244 (if the coroutine terminates).
6245 If there is any error,
6246 <code>resume</code> returns <b>false</b> plus the error message.
6252 <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
6256 Returns the running coroutine,
6257 or <b>nil</b> when called by the main thread.
6263 <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
6267 Returns the status of coroutine <code>co</code>, as a string:
6268 <code>"running"</code>,
6269 if the coroutine is running (that is, it called <code>status</code>);
6270 <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
6271 or if it has not started running yet;
6272 <code>"normal"</code> if the coroutine is active but not running
6273 (that is, it has resumed another coroutine);
6274 and <code>"dead"</code> if the coroutine has finished its body function,
6275 or if it has stopped with an error.
6281 <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
6285 Creates a new coroutine, with body <code>f</code>.
6286 <code>f</code> must be a Lua function.
6287 Returns a function that resumes the coroutine each time it is called.
6288 Any arguments passed to the function behave as the
6289 extra arguments to <code>resume</code>.
6290 Returns the same values returned by <code>resume</code>,
6291 except the first boolean.
6292 In case of error, propagates the error.
6298 <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
6302 Suspends the execution of the calling coroutine.
6303 The coroutine cannot be running a C&nbsp;function,
6304 a metamethod, or an iterator.
6305 Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
6313 <h2>5.3 - <a name="5.3">Modules</a></h2>
6316 The package library provides basic
6317 facilities for loading and building modules in Lua.
6318 It exports two of its functions directly in the global environment:
6319 <a href="#pdf-require"><code>require</code></a> and <a href="#pdf-module"><code>module</code></a>.
6320 Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
6324 <hr><h3><a name="pdf-module"><code>module (name [, &middot;&middot;&middot;])</code></a></h3>
6328 Creates a module.
6329 If there is a table in <code>package.loaded[name]</code>,
6330 this table is the module.
6331 Otherwise, if there is a global table <code>t</code> with the given name,
6332 this table is the module.
6333 Otherwise creates a new table <code>t</code> and
6334 sets it as the value of the global <code>name</code> and
6335 the value of <code>package.loaded[name]</code>.
6336 This function also initializes <code>t._NAME</code> with the given name,
6337 <code>t._M</code> with the module (<code>t</code> itself),
6338 and <code>t._PACKAGE</code> with the package name
6339 (the full module name minus last component; see below).
6340 Finally, <code>module</code> sets <code>t</code> as the new environment
6341 of the current function and the new value of <code>package.loaded[name]</code>,
6342 so that <a href="#pdf-require"><code>require</code></a> returns <code>t</code>.
6346 If <code>name</code> is a compound name
6347 (that is, one with components separated by dots),
6348 <code>module</code> creates (or reuses, if they already exist)
6349 tables for each component.
6350 For instance, if <code>name</code> is <code>a.b.c</code>,
6351 then <code>module</code> stores the module table in field <code>c</code> of
6352 field <code>b</code> of global <code>a</code>.
6356 This function can receive optional <em>options</em> after
6357 the module name,
6358 where each option is a function to be applied over the module.
6364 <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
6368 Loads the given module.
6369 The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
6370 to determine whether <code>modname</code> is already loaded.
6371 If it is, then <code>require</code> returns the value stored
6372 at <code>package.loaded[modname]</code>.
6373 Otherwise, it tries to find a <em>loader</em> for the module.
6377 To find a loader,
6378 <code>require</code> is guided by the <a href="#pdf-package.loaders"><code>package.loaders</code></a> array.
6379 By changing this array,
6380 we can change how <code>require</code> looks for a module.
6381 The following explanation is based on the default configuration
6382 for <a href="#pdf-package.loaders"><code>package.loaders</code></a>.
6386 First <code>require</code> queries <code>package.preload[modname]</code>.
6387 If it has a value,
6388 this value (which should be a function) is the loader.
6389 Otherwise <code>require</code> searches for a Lua loader using the
6390 path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
6391 If that also fails, it searches for a C&nbsp;loader using the
6392 path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
6393 If that also fails,
6394 it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.loaders"><code>package.loaders</code></a>).
6398 Once a loader is found,
6399 <code>require</code> calls the loader with a single argument, <code>modname</code>.
6400 If the loader returns any value,
6401 <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
6402 If the loader returns no value and
6403 has not assigned any value to <code>package.loaded[modname]</code>,
6404 then <code>require</code> assigns <b>true</b> to this entry.
6405 In any case, <code>require</code> returns the
6406 final value of <code>package.loaded[modname]</code>.
6410 If there is any error loading or running the module,
6411 or if it cannot find any loader for the module,
6412 then <code>require</code> signals an error.
6418 <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
6422 The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
6426 Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
6427 it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
6428 using the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
6429 or a default path defined in <code>luaconf.h</code>.
6436 <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
6440 A table used by <a href="#pdf-require"><code>require</code></a> to control which
6441 modules are already loaded.
6442 When you require a module <code>modname</code> and
6443 <code>package.loaded[modname]</code> is not false,
6444 <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
6450 <hr><h3><a name="pdf-package.loaders"><code>package.loaders</code></a></h3>
6454 A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
6458 Each entry in this table is a <em>searcher function</em>.
6459 When looking for a module,
6460 <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
6461 with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
6462 sole parameter.
6463 The function can return another function (the module <em>loader</em>)
6464 or a string explaining why it did not find that module
6465 (or <b>nil</b> if it has nothing to say).
6466 Lua initializes this table with four functions.
6470 The first searcher simply looks for a loader in the
6471 <a href="#pdf-package.preload"><code>package.preload</code></a> table.
6475 The second searcher looks for a loader as a Lua library,
6476 using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
6477 A path is a sequence of <em>templates</em> separated by semicolons.
6478 For each template,
6479 the searcher will change each interrogation
6480 mark in the template by <code>filename</code>,
6481 which is the module name with each dot replaced by a
6482 "directory separator" (such as "<code>/</code>" in Unix);
6483 then it will try to open the resulting file name.
6484 So, for instance, if the Lua path is the string
6486 <pre>
6487 "./?.lua;./?.lc;/usr/local/?/init.lua"
6488 </pre><p>
6489 the search for a Lua file for module <code>foo</code>
6490 will try to open the files
6491 <code>./foo.lua</code>, <code>./foo.lc</code>, and
6492 <code>/usr/local/foo/init.lua</code>, in that order.
6496 The third searcher looks for a loader as a C&nbsp;library,
6497 using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
6498 For instance,
6499 if the C&nbsp;path is the string
6501 <pre>
6502 "./?.so;./?.dll;/usr/local/?/init.so"
6503 </pre><p>
6504 the searcher for module <code>foo</code>
6505 will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
6506 and <code>/usr/local/foo/init.so</code>, in that order.
6507 Once it finds a C&nbsp;library,
6508 this searcher first uses a dynamic link facility to link the
6509 application with the library.
6510 Then it tries to find a C&nbsp;function inside the library to
6511 be used as the loader.
6512 The name of this C&nbsp;function is the string "<code>luaopen_</code>"
6513 concatenated with a copy of the module name where each dot
6514 is replaced by an underscore.
6515 Moreover, if the module name has a hyphen,
6516 its prefix up to (and including) the first hyphen is removed.
6517 For instance, if the module name is <code>a.v1-b.c</code>,
6518 the function name will be <code>luaopen_b_c</code>.
6522 The fourth searcher tries an <em>all-in-one loader</em>.
6523 It searches the C&nbsp;path for a library for
6524 the root name of the given module.
6525 For instance, when requiring <code>a.b.c</code>,
6526 it will search for a C&nbsp;library for <code>a</code>.
6527 If found, it looks into it for an open function for
6528 the submodule;
6529 in our example, that would be <code>luaopen_a_b_c</code>.
6530 With this facility, a package can pack several C&nbsp;submodules
6531 into one single library,
6532 with each submodule keeping its original open function.
6538 <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
6542 Dynamically links the host program with the C&nbsp;library <code>libname</code>.
6543 Inside this library, looks for a function <code>funcname</code>
6544 and returns this function as a C&nbsp;function.
6545 (So, <code>funcname</code> must follow the protocol (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>)).
6549 This is a low-level function.
6550 It completely bypasses the package and module system.
6551 Unlike <a href="#pdf-require"><code>require</code></a>,
6552 it does not perform any path searching and
6553 does not automatically adds extensions.
6554 <code>libname</code> must be the complete file name of the C&nbsp;library,
6555 including if necessary a path and extension.
6556 <code>funcname</code> must be the exact name exported by the C&nbsp;library
6557 (which may depend on the C&nbsp;compiler and linker used).
6561 This function is not supported by ANSI C.
6562 As such, it is only available on some platforms
6563 (Windows, Linux, Mac OS X, Solaris, BSD,
6564 plus other Unix systems that support the <code>dlfcn</code> standard).
6570 <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
6574 The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
6578 At start-up, Lua initializes this variable with
6579 the value of the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
6580 with a default path defined in <code>luaconf.h</code>,
6581 if the environment variable is not defined.
6582 Any "<code>;;</code>" in the value of the environment variable
6583 is replaced by the default path.
6589 <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
6593 A table to store loaders for specific modules
6594 (see <a href="#pdf-require"><code>require</code></a>).
6600 <hr><h3><a name="pdf-package.seeall"><code>package.seeall (module)</code></a></h3>
6604 Sets a metatable for <code>module</code> with
6605 its <code>__index</code> field referring to the global environment,
6606 so that this module inherits values
6607 from the global environment.
6608 To be used as an option to function <a href="#pdf-module"><code>module</code></a>.
6616 <h2>5.4 - <a name="5.4">String Manipulation</a></h2>
6619 This library provides generic functions for string manipulation,
6620 such as finding and extracting substrings, and pattern matching.
6621 When indexing a string in Lua, the first character is at position&nbsp;1
6622 (not at&nbsp;0, as in C).
6623 Indices are allowed to be negative and are interpreted as indexing backwards,
6624 from the end of the string.
6625 Thus, the last character is at position -1, and so on.
6629 The string library provides all its functions inside the table
6630 <a name="pdf-string"><code>string</code></a>.
6631 It also sets a metatable for strings
6632 where the <code>__index</code> field points to the <code>string</code> table.
6633 Therefore, you can use the string functions in object-oriented style.
6634 For instance, <code>string.byte(s, i)</code>
6635 can be written as <code>s:byte(i)</code>.
6639 The string library assumes one-byte character encodings.
6643 <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
6644 Returns the internal numerical codes of the characters <code>s[i]</code>,
6645 <code>s[i+1]</code>, &middot;&middot;&middot;, <code>s[j]</code>.
6646 The default value for <code>i</code> is&nbsp;1;
6647 the default value for <code>j</code> is&nbsp;<code>i</code>.
6651 Note that numerical codes are not necessarily portable across platforms.
6657 <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
6658 Receives zero or more integers.
6659 Returns a string with length equal to the number of arguments,
6660 in which each character has the internal numerical code equal
6661 to its corresponding argument.
6665 Note that numerical codes are not necessarily portable across platforms.
6671 <hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
6675 Returns a string containing a binary representation of the given function,
6676 so that a later <a href="#pdf-loadstring"><code>loadstring</code></a> on this string returns
6677 a copy of the function.
6678 <code>function</code> must be a Lua function without upvalues.
6684 <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
6685 Looks for the first match of
6686 <code>pattern</code> in the string <code>s</code>.
6687 If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
6688 where this occurrence starts and ends;
6689 otherwise, it returns <b>nil</b>.
6690 A third, optional numerical argument <code>init</code> specifies
6691 where to start the search;
6692 its default value is&nbsp;1 and can be negative.
6693 A value of <b>true</b> as a fourth, optional argument <code>plain</code>
6694 turns off the pattern matching facilities,
6695 so the function does a plain "find substring" operation,
6696 with no characters in <code>pattern</code> being considered "magic".
6697 Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
6701 If the pattern has captures,
6702 then in a successful match
6703 the captured values are also returned,
6704 after the two indices.
6710 <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
6711 Returns a formatted version of its variable number of arguments
6712 following the description given in its first argument (which must be a string).
6713 The format string follows the same rules as the <code>printf</code> family of
6714 standard C&nbsp;functions.
6715 The only differences are that the options/modifiers
6716 <code>*</code>, <code>l</code>, <code>L</code>, <code>n</code>, <code>p</code>,
6717 and <code>h</code> are not supported
6718 and that there is an extra option, <code>q</code>.
6719 The <code>q</code> option formats a string in a form suitable to be safely read
6720 back by the Lua interpreter:
6721 the string is written between double quotes,
6722 and all double quotes, newlines, embedded zeros,
6723 and backslashes in the string
6724 are correctly escaped when written.
6725 For instance, the call
6727 <pre>
6728 string.format('%q', 'a string with "quotes" and \n new line')
6729 </pre><p>
6730 will produce the string:
6732 <pre>
6733 "a string with \"quotes\" and \
6734 new line"
6735 </pre>
6738 The options <code>c</code>, <code>d</code>, <code>E</code>, <code>e</code>, <code>f</code>,
6739 <code>g</code>, <code>G</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> all
6740 expect a number as argument,
6741 whereas <code>q</code> and <code>s</code> expect a string.
6745 This function does not accept string values
6746 containing embedded zeros,
6747 except as arguments to the <code>q</code> option.
6753 <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
6754 Returns an iterator function that,
6755 each time it is called,
6756 returns the next captures from <code>pattern</code> over string <code>s</code>.
6757 If <code>pattern</code> specifies no captures,
6758 then the whole match is produced in each call.
6762 As an example, the following loop
6764 <pre>
6765 s = "hello world from Lua"
6766 for w in string.gmatch(s, "%a+") do
6767 print(w)
6769 </pre><p>
6770 will iterate over all the words from string <code>s</code>,
6771 printing one per line.
6772 The next example collects all pairs <code>key=value</code> from the
6773 given string into a table:
6775 <pre>
6776 t = {}
6777 s = "from=world, to=Lua"
6778 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
6779 t[k] = v
6781 </pre>
6784 For this function, a '<code>^</code>' at the start of a pattern does not
6785 work as an anchor, as this would prevent the iteration.
6791 <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
6792 Returns a copy of <code>s</code>
6793 in which all (or the first <code>n</code>, if given)
6794 occurrences of the <code>pattern</code> have been
6795 replaced by a replacement string specified by <code>repl</code>,
6796 which can be a string, a table, or a function.
6797 <code>gsub</code> also returns, as its second value,
6798 the total number of matches that occurred.
6802 If <code>repl</code> is a string, then its value is used for replacement.
6803 The character&nbsp;<code>%</code> works as an escape character:
6804 any sequence in <code>repl</code> of the form <code>%<em>n</em></code>,
6805 with <em>n</em> between 1 and 9,
6806 stands for the value of the <em>n</em>-th captured substring (see below).
6807 The sequence <code>%0</code> stands for the whole match.
6808 The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
6812 If <code>repl</code> is a table, then the table is queried for every match,
6813 using the first capture as the key;
6814 if the pattern specifies no captures,
6815 then the whole match is used as the key.
6819 If <code>repl</code> is a function, then this function is called every time a
6820 match occurs, with all captured substrings passed as arguments,
6821 in order;
6822 if the pattern specifies no captures,
6823 then the whole match is passed as a sole argument.
6827 If the value returned by the table query or by the function call
6828 is a string or a number,
6829 then it is used as the replacement string;
6830 otherwise, if it is <b>false</b> or <b>nil</b>,
6831 then there is no replacement
6832 (that is, the original match is kept in the string).
6836 Here are some examples:
6838 <pre>
6839 x = string.gsub("hello world", "(%w+)", "%1 %1")
6840 --&gt; x="hello hello world world"
6842 x = string.gsub("hello world", "%w+", "%0 %0", 1)
6843 --&gt; x="hello hello world"
6845 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
6846 --&gt; x="world hello Lua from"
6848 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
6849 --&gt; x="home = /home/roberto, user = roberto"
6851 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
6852 return loadstring(s)()
6853 end)
6854 --&gt; x="4+5 = 9"
6856 local t = {name="lua", version="5.1"}
6857 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
6858 --&gt; x="lua-5.1.tar.gz"
6859 </pre>
6864 <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
6865 Receives a string and returns its length.
6866 The empty string <code>""</code> has length 0.
6867 Embedded zeros are counted,
6868 so <code>"a\000bc\000"</code> has length 5.
6874 <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
6875 Receives a string and returns a copy of this string with all
6876 uppercase letters changed to lowercase.
6877 All other characters are left unchanged.
6878 The definition of what an uppercase letter is depends on the current locale.
6884 <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
6885 Looks for the first <em>match</em> of
6886 <code>pattern</code> in the string <code>s</code>.
6887 If it finds one, then <code>match</code> returns
6888 the captures from the pattern;
6889 otherwise it returns <b>nil</b>.
6890 If <code>pattern</code> specifies no captures,
6891 then the whole match is returned.
6892 A third, optional numerical argument <code>init</code> specifies
6893 where to start the search;
6894 its default value is&nbsp;1 and can be negative.
6900 <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n)</code></a></h3>
6901 Returns a string that is the concatenation of <code>n</code> copies of
6902 the string <code>s</code>.
6908 <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
6909 Returns a string that is the string <code>s</code> reversed.
6915 <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
6916 Returns the substring of <code>s</code> that
6917 starts at <code>i</code> and continues until <code>j</code>;
6918 <code>i</code> and <code>j</code> can be negative.
6919 If <code>j</code> is absent, then it is assumed to be equal to -1
6920 (which is the same as the string length).
6921 In particular,
6922 the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
6923 with length <code>j</code>,
6924 and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
6925 with length <code>i</code>.
6931 <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
6932 Receives a string and returns a copy of this string with all
6933 lowercase letters changed to uppercase.
6934 All other characters are left unchanged.
6935 The definition of what a lowercase letter is depends on the current locale.
6939 <h3>5.4.1 - <a name="5.4.1">Patterns</a></h3>
6942 <h4>Character Class:</h4><p>
6943 A <em>character class</em> is used to represent a set of characters.
6944 The following combinations are allowed in describing a character class:
6946 <ul>
6948 <li><b><em>x</em>:</b>
6949 (where <em>x</em> is not one of the <em>magic characters</em>
6950 <code>^$()%.[]*+-?</code>)
6951 represents the character <em>x</em> itself.
6952 </li>
6954 <li><b><code>.</code>:</b> (a dot) represents all characters.</li>
6956 <li><b><code>%a</code>:</b> represents all letters.</li>
6958 <li><b><code>%c</code>:</b> represents all control characters.</li>
6960 <li><b><code>%d</code>:</b> represents all digits.</li>
6962 <li><b><code>%l</code>:</b> represents all lowercase letters.</li>
6964 <li><b><code>%p</code>:</b> represents all punctuation characters.</li>
6966 <li><b><code>%s</code>:</b> represents all space characters.</li>
6968 <li><b><code>%u</code>:</b> represents all uppercase letters.</li>
6970 <li><b><code>%w</code>:</b> represents all alphanumeric characters.</li>
6972 <li><b><code>%x</code>:</b> represents all hexadecimal digits.</li>
6974 <li><b><code>%z</code>:</b> represents the character with representation 0.</li>
6976 <li><b><code>%<em>x</em></code>:</b> (where <em>x</em> is any non-alphanumeric character)
6977 represents the character <em>x</em>.
6978 This is the standard way to escape the magic characters.
6979 Any punctuation character (even the non magic)
6980 can be preceded by a '<code>%</code>'
6981 when used to represent itself in a pattern.
6982 </li>
6984 <li><b><code>[<em>set</em>]</code>:</b>
6985 represents the class which is the union of all
6986 characters in <em>set</em>.
6987 A range of characters can be specified by
6988 separating the end characters of the range with a '<code>-</code>'.
6989 All classes <code>%</code><em>x</em> described above can also be used as
6990 components in <em>set</em>.
6991 All other characters in <em>set</em> represent themselves.
6992 For example, <code>[%w_]</code> (or <code>[_%w]</code>)
6993 represents all alphanumeric characters plus the underscore,
6994 <code>[0-7]</code> represents the octal digits,
6995 and <code>[0-7%l%-]</code> represents the octal digits plus
6996 the lowercase letters plus the '<code>-</code>' character.
7000 The interaction between ranges and classes is not defined.
7001 Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
7002 have no meaning.
7003 </li>
7005 <li><b><code>[^<em>set</em>]</code>:</b>
7006 represents the complement of <em>set</em>,
7007 where <em>set</em> is interpreted as above.
7008 </li>
7010 </ul><p>
7011 For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
7012 the corresponding uppercase letter represents the complement of the class.
7013 For instance, <code>%S</code> represents all non-space characters.
7017 The definitions of letter, space, and other character groups
7018 depend on the current locale.
7019 In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
7025 <h4>Pattern Item:</h4><p>
7026 A <em>pattern item</em> can be
7028 <ul>
7030 <li>
7031 a single character class,
7032 which matches any single character in the class;
7033 </li>
7035 <li>
7036 a single character class followed by '<code>*</code>',
7037 which matches 0 or more repetitions of characters in the class.
7038 These repetition items will always match the longest possible sequence;
7039 </li>
7041 <li>
7042 a single character class followed by '<code>+</code>',
7043 which matches 1 or more repetitions of characters in the class.
7044 These repetition items will always match the longest possible sequence;
7045 </li>
7047 <li>
7048 a single character class followed by '<code>-</code>',
7049 which also matches 0 or more repetitions of characters in the class.
7050 Unlike '<code>*</code>',
7051 these repetition items will always match the <em>shortest</em> possible sequence;
7052 </li>
7054 <li>
7055 a single character class followed by '<code>?</code>',
7056 which matches 0 or 1 occurrence of a character in the class;
7057 </li>
7059 <li>
7060 <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
7061 such item matches a substring equal to the <em>n</em>-th captured string
7062 (see below);
7063 </li>
7065 <li>
7066 <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
7067 such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
7068 and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
7069 This means that, if one reads the string from left to right,
7070 counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
7071 the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
7072 For instance, the item <code>%b()</code> matches expressions with
7073 balanced parentheses.
7074 </li>
7076 </ul>
7081 <h4>Pattern:</h4><p>
7082 A <em>pattern</em> is a sequence of pattern items.
7083 A '<code>^</code>' at the beginning of a pattern anchors the match at the
7084 beginning of the subject string.
7085 A '<code>$</code>' at the end of a pattern anchors the match at the
7086 end of the subject string.
7087 At other positions,
7088 '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
7094 <h4>Captures:</h4><p>
7095 A pattern can contain sub-patterns enclosed in parentheses;
7096 they describe <em>captures</em>.
7097 When a match succeeds, the substrings of the subject string
7098 that match captures are stored (<em>captured</em>) for future use.
7099 Captures are numbered according to their left parentheses.
7100 For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
7101 the part of the string matching <code>"a*(.)%w(%s*)"</code> is
7102 stored as the first capture (and therefore has number&nbsp;1);
7103 the character matching "<code>.</code>" is captured with number&nbsp;2,
7104 and the part matching "<code>%s*</code>" has number&nbsp;3.
7108 As a special case, the empty capture <code>()</code> captures
7109 the current string position (a number).
7110 For instance, if we apply the pattern <code>"()aa()"</code> on the
7111 string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
7115 A pattern cannot contain embedded zeros. Use <code>%z</code> instead.
7127 <h2>5.5 - <a name="5.5">Table Manipulation</a></h2><p>
7128 This library provides generic functions for table manipulation.
7129 It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
7133 Most functions in the table library assume that the table
7134 represents an array or a list.
7135 For these functions, when we talk about the "length" of a table
7136 we mean the result of the length operator.
7140 <hr><h3><a name="pdf-table.concat"><code>table.concat (table [, sep [, i [, j]]])</code></a></h3>
7141 Given an array where all elements are strings or numbers,
7142 returns <code>table[i]..sep..table[i+1] &middot;&middot;&middot; sep..table[j]</code>.
7143 The default value for <code>sep</code> is the empty string,
7144 the default for <code>i</code> is 1,
7145 and the default for <code>j</code> is the length of the table.
7146 If <code>i</code> is greater than <code>j</code>, returns the empty string.
7152 <hr><h3><a name="pdf-table.insert"><code>table.insert (table, [pos,] value)</code></a></h3>
7156 Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>,
7157 shifting up other elements to open space, if necessary.
7158 The default value for <code>pos</code> is <code>n+1</code>,
7159 where <code>n</code> is the length of the table (see <a href="#2.5.5">&sect;2.5.5</a>),
7160 so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
7161 of table <code>t</code>.
7167 <hr><h3><a name="pdf-table.maxn"><code>table.maxn (table)</code></a></h3>
7171 Returns the largest positive numerical index of the given table,
7172 or zero if the table has no positive numerical indices.
7173 (To do its job this function does a linear traversal of
7174 the whole table.)
7180 <hr><h3><a name="pdf-table.remove"><code>table.remove (table [, pos])</code></a></h3>
7184 Removes from <code>table</code> the element at position <code>pos</code>,
7185 shifting down other elements to close the space, if necessary.
7186 Returns the value of the removed element.
7187 The default value for <code>pos</code> is <code>n</code>,
7188 where <code>n</code> is the length of the table,
7189 so that a call <code>table.remove(t)</code> removes the last element
7190 of table <code>t</code>.
7196 <hr><h3><a name="pdf-table.sort"><code>table.sort (table [, comp])</code></a></h3>
7197 Sorts table elements in a given order, <em>in-place</em>,
7198 from <code>table[1]</code> to <code>table[n]</code>,
7199 where <code>n</code> is the length of the table.
7200 If <code>comp</code> is given,
7201 then it must be a function that receives two table elements,
7202 and returns true
7203 when the first is less than the second
7204 (so that <code>not comp(a[i+1],a[i])</code> will be true after the sort).
7205 If <code>comp</code> is not given,
7206 then the standard Lua operator <code>&lt;</code> is used instead.
7210 The sort algorithm is not stable;
7211 that is, elements considered equal by the given order
7212 may have their relative positions changed by the sort.
7220 <h2>5.6 - <a name="5.6">Mathematical Functions</a></h2>
7223 This library is an interface to the standard C&nbsp;math library.
7224 It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
7228 <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
7232 Returns the absolute value of <code>x</code>.
7238 <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
7242 Returns the arc cosine of <code>x</code> (in radians).
7248 <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
7252 Returns the arc sine of <code>x</code> (in radians).
7258 <hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
7262 Returns the arc tangent of <code>x</code> (in radians).
7268 <hr><h3><a name="pdf-math.atan2"><code>math.atan2 (y, x)</code></a></h3>
7272 Returns the arc tangent of <code>y/x</code> (in radians),
7273 but uses the signs of both parameters to find the
7274 quadrant of the result.
7275 (It also handles correctly the case of <code>x</code> being zero.)
7281 <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
7285 Returns the smallest integer larger than or equal to <code>x</code>.
7291 <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
7295 Returns the cosine of <code>x</code> (assumed to be in radians).
7301 <hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
7305 Returns the hyperbolic cosine of <code>x</code>.
7311 <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
7315 Returns the angle <code>x</code> (given in radians) in degrees.
7321 <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
7325 Returns the value <em>e<sup>x</sup></em>.
7331 <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
7335 Returns the largest integer smaller than or equal to <code>x</code>.
7341 <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
7345 Returns the remainder of the division of <code>x</code> by <code>y</code>
7346 that rounds the quotient towards zero.
7352 <hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
7356 Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
7357 <code>e</code> is an integer and the absolute value of <code>m</code> is
7358 in the range <em>[0.5, 1)</em>
7359 (or zero when <code>x</code> is zero).
7365 <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
7369 The value <code>HUGE_VAL</code>,
7370 a value larger than or equal to any other numerical value.
7376 <hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
7380 Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
7386 <hr><h3><a name="pdf-math.log"><code>math.log (x)</code></a></h3>
7390 Returns the natural logarithm of <code>x</code>.
7396 <hr><h3><a name="pdf-math.log10"><code>math.log10 (x)</code></a></h3>
7400 Returns the base-10 logarithm of <code>x</code>.
7406 <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
7410 Returns the maximum value among its arguments.
7416 <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
7420 Returns the minimum value among its arguments.
7426 <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
7430 Returns two numbers,
7431 the integral part of <code>x</code> and the fractional part of <code>x</code>.
7437 <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
7441 The value of <em>pi</em>.
7447 <hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
7451 Returns <em>x<sup>y</sup></em>.
7452 (You can also use the expression <code>x^y</code> to compute this value.)
7458 <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
7462 Returns the angle <code>x</code> (given in degrees) in radians.
7468 <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
7472 This function is an interface to the simple
7473 pseudo-random generator function <code>rand</code> provided by ANSI&nbsp;C.
7474 (No guarantees can be given for its statistical properties.)
7478 When called without arguments,
7479 returns a uniform pseudo-random real number
7480 in the range <em>[0,1)</em>.
7481 When called with an integer number <code>m</code>,
7482 <code>math.random</code> returns
7483 a uniform pseudo-random integer in the range <em>[1, m]</em>.
7484 When called with two integer numbers <code>m</code> and <code>n</code>,
7485 <code>math.random</code> returns a uniform pseudo-random
7486 integer in the range <em>[m, n]</em>.
7492 <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
7496 Sets <code>x</code> as the "seed"
7497 for the pseudo-random generator:
7498 equal seeds produce equal sequences of numbers.
7504 <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
7508 Returns the sine of <code>x</code> (assumed to be in radians).
7514 <hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
7518 Returns the hyperbolic sine of <code>x</code>.
7524 <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
7528 Returns the square root of <code>x</code>.
7529 (You can also use the expression <code>x^0.5</code> to compute this value.)
7535 <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
7539 Returns the tangent of <code>x</code> (assumed to be in radians).
7545 <hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
7549 Returns the hyperbolic tangent of <code>x</code>.
7557 <h2>5.7 - <a name="5.7">Input and Output Facilities</a></h2>
7560 The I/O library provides two different styles for file manipulation.
7561 The first one uses implicit file descriptors;
7562 that is, there are operations to set a default input file and a
7563 default output file,
7564 and all input/output operations are over these default files.
7565 The second style uses explicit file descriptors.
7569 When using implicit file descriptors,
7570 all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
7571 When using explicit file descriptors,
7572 the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
7573 and then all operations are supplied as methods of the file descriptor.
7577 The table <code>io</code> also provides
7578 three predefined file descriptors with their usual meanings from C:
7579 <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>.
7580 The I/O library never closes these files.
7584 Unless otherwise stated,
7585 all I/O functions return <b>nil</b> on failure
7586 (plus an error message as a second result and
7587 a system-dependent error code as a third result)
7588 and some value different from <b>nil</b> on success.
7592 <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
7596 Equivalent to <code>file:close()</code>.
7597 Without a <code>file</code>, closes the default output file.
7603 <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
7607 Equivalent to <code>file:flush</code> over the default output file.
7613 <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
7617 When called with a file name, it opens the named file (in text mode),
7618 and sets its handle as the default input file.
7619 When called with a file handle,
7620 it simply sets this file handle as the default input file.
7621 When called without parameters,
7622 it returns the current default input file.
7626 In case of errors this function raises the error,
7627 instead of returning an error code.
7633 <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename])</code></a></h3>
7637 Opens the given file name in read mode
7638 and returns an iterator function that,
7639 each time it is called,
7640 returns a new line from the file.
7641 Therefore, the construction
7643 <pre>
7644 for line in io.lines(filename) do <em>body</em> end
7645 </pre><p>
7646 will iterate over all lines of the file.
7647 When the iterator function detects the end of file,
7648 it returns <b>nil</b> (to finish the loop) and automatically closes the file.
7652 The call <code>io.lines()</code> (with no file name) is equivalent
7653 to <code>io.input():lines()</code>;
7654 that is, it iterates over the lines of the default input file.
7655 In this case it does not close the file when the loop ends.
7661 <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
7665 This function opens a file,
7666 in the mode specified in the string <code>mode</code>.
7667 It returns a new file handle,
7668 or, in case of errors, <b>nil</b> plus an error message.
7672 The <code>mode</code> string can be any of the following:
7674 <ul>
7675 <li><b>"r":</b> read mode (the default);</li>
7676 <li><b>"w":</b> write mode;</li>
7677 <li><b>"a":</b> append mode;</li>
7678 <li><b>"r+":</b> update mode, all previous data is preserved;</li>
7679 <li><b>"w+":</b> update mode, all previous data is erased;</li>
7680 <li><b>"a+":</b> append update mode, previous data is preserved,
7681 writing is only allowed at the end of file.</li>
7682 </ul><p>
7683 The <code>mode</code> string can also have a '<code>b</code>' at the end,
7684 which is needed in some systems to open the file in binary mode.
7685 This string is exactly what is used in the
7686 standard&nbsp;C function <code>fopen</code>.
7692 <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
7696 Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
7702 <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
7706 Starts program <code>prog</code> in a separated process and returns
7707 a file handle that you can use to read data from this program
7708 (if <code>mode</code> is <code>"r"</code>, the default)
7709 or to write data to this program
7710 (if <code>mode</code> is <code>"w"</code>).
7714 This function is system dependent and is not available
7715 on all platforms.
7721 <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
7725 Equivalent to <code>io.input():read</code>.
7731 <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
7735 Returns a handle for a temporary file.
7736 This file is opened in update mode
7737 and it is automatically removed when the program ends.
7743 <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
7747 Checks whether <code>obj</code> is a valid file handle.
7748 Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
7749 <code>"closed file"</code> if <code>obj</code> is a closed file handle,
7750 or <b>nil</b> if <code>obj</code> is not a file handle.
7756 <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
7760 Equivalent to <code>io.output():write</code>.
7766 <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
7770 Closes <code>file</code>.
7771 Note that files are automatically closed when
7772 their handles are garbage collected,
7773 but that takes an unpredictable amount of time to happen.
7779 <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
7783 Saves any written data to <code>file</code>.
7789 <hr><h3><a name="pdf-file:lines"><code>file:lines ()</code></a></h3>
7793 Returns an iterator function that,
7794 each time it is called,
7795 returns a new line from the file.
7796 Therefore, the construction
7798 <pre>
7799 for line in file:lines() do <em>body</em> end
7800 </pre><p>
7801 will iterate over all lines of the file.
7802 (Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
7803 when the loop ends.)
7809 <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
7813 Reads the file <code>file</code>,
7814 according to the given formats, which specify what to read.
7815 For each format,
7816 the function returns a string (or a number) with the characters read,
7817 or <b>nil</b> if it cannot read data with the specified format.
7818 When called without formats,
7819 it uses a default format that reads the entire next line
7820 (see below).
7824 The available formats are
7826 <ul>
7828 <li><b>"*n":</b>
7829 reads a number;
7830 this is the only format that returns a number instead of a string.
7831 </li>
7833 <li><b>"*a":</b>
7834 reads the whole file, starting at the current position.
7835 On end of file, it returns the empty string.
7836 </li>
7838 <li><b>"*l":</b>
7839 reads the next line (skipping the end of line),
7840 returning <b>nil</b> on end of file.
7841 This is the default format.
7842 </li>
7844 <li><b><em>number</em>:</b>
7845 reads a string with up to this number of characters,
7846 returning <b>nil</b> on end of file.
7847 If number is zero,
7848 it reads nothing and returns an empty string,
7849 or <b>nil</b> on end of file.
7850 </li>
7852 </ul>
7857 <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence] [, offset])</code></a></h3>
7861 Sets and gets the file position,
7862 measured from the beginning of the file,
7863 to the position given by <code>offset</code> plus a base
7864 specified by the string <code>whence</code>, as follows:
7866 <ul>
7867 <li><b>"set":</b> base is position 0 (beginning of the file);</li>
7868 <li><b>"cur":</b> base is current position;</li>
7869 <li><b>"end":</b> base is end of file;</li>
7870 </ul><p>
7871 In case of success, function <code>seek</code> returns the final file position,
7872 measured in bytes from the beginning of the file.
7873 If this function fails, it returns <b>nil</b>,
7874 plus a string describing the error.
7878 The default value for <code>whence</code> is <code>"cur"</code>,
7879 and for <code>offset</code> is 0.
7880 Therefore, the call <code>file:seek()</code> returns the current
7881 file position, without changing it;
7882 the call <code>file:seek("set")</code> sets the position to the
7883 beginning of the file (and returns 0);
7884 and the call <code>file:seek("end")</code> sets the position to the
7885 end of the file, and returns its size.
7891 <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
7895 Sets the buffering mode for an output file.
7896 There are three available modes:
7898 <ul>
7900 <li><b>"no":</b>
7901 no buffering; the result of any output operation appears immediately.
7902 </li>
7904 <li><b>"full":</b>
7905 full buffering; output operation is performed only
7906 when the buffer is full (or when you explicitly <code>flush</code> the file
7907 (see <a href="#pdf-io.flush"><code>io.flush</code></a>)).
7908 </li>
7910 <li><b>"line":</b>
7911 line buffering; output is buffered until a newline is output
7912 or there is any input from some special files
7913 (such as a terminal device).
7914 </li>
7916 </ul><p>
7917 For the last two cases, <code>size</code>
7918 specifies the size of the buffer, in bytes.
7919 The default is an appropriate size.
7925 <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
7929 Writes the value of each of its arguments to
7930 the <code>file</code>.
7931 The arguments must be strings or numbers.
7932 To write other values,
7933 use <a href="#pdf-tostring"><code>tostring</code></a> or <a href="#pdf-string.format"><code>string.format</code></a> before <code>write</code>.
7941 <h2>5.8 - <a name="5.8">Operating System Facilities</a></h2>
7944 This library is implemented through table <a name="pdf-os"><code>os</code></a>.
7948 <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
7952 Returns an approximation of the amount in seconds of CPU time
7953 used by the program.
7959 <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
7963 Returns a string or a table containing date and time,
7964 formatted according to the given string <code>format</code>.
7968 If the <code>time</code> argument is present,
7969 this is the time to be formatted
7970 (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
7971 Otherwise, <code>date</code> formats the current time.
7975 If <code>format</code> starts with '<code>!</code>',
7976 then the date is formatted in Coordinated Universal Time.
7977 After this optional character,
7978 if <code>format</code> is the string "<code>*t</code>",
7979 then <code>date</code> returns a table with the following fields:
7980 <code>year</code> (four digits), <code>month</code> (1--12), <code>day</code> (1--31),
7981 <code>hour</code> (0--23), <code>min</code> (0--59), <code>sec</code> (0--61),
7982 <code>wday</code> (weekday, Sunday is&nbsp;1),
7983 <code>yday</code> (day of the year),
7984 and <code>isdst</code> (daylight saving flag, a boolean).
7988 If <code>format</code> is not "<code>*t</code>",
7989 then <code>date</code> returns the date as a string,
7990 formatted according to the same rules as the C&nbsp;function <code>strftime</code>.
7994 When called without arguments,
7995 <code>date</code> returns a reasonable date and time representation that depends on
7996 the host system and on the current locale
7997 (that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
8003 <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
8007 Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
8008 In POSIX, Windows, and some other systems,
8009 this value is exactly <code>t2</code><em>-</em><code>t1</code>.
8015 <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
8019 This function is equivalent to the C&nbsp;function <code>system</code>.
8020 It passes <code>command</code> to be executed by an operating system shell.
8021 It returns a status code, which is system-dependent.
8022 If <code>command</code> is absent, then it returns nonzero if a shell is available
8023 and zero otherwise.
8029 <hr><h3><a name="pdf-os.exit"><code>os.exit ([code])</code></a></h3>
8033 Calls the C&nbsp;function <code>exit</code>,
8034 with an optional <code>code</code>,
8035 to terminate the host program.
8036 The default value for <code>code</code> is the success code.
8042 <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
8046 Returns the value of the process environment variable <code>varname</code>,
8047 or <b>nil</b> if the variable is not defined.
8053 <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
8057 Deletes the file or directory with the given name.
8058 Directories must be empty to be removed.
8059 If this function fails, it returns <b>nil</b>,
8060 plus a string describing the error.
8066 <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
8070 Renames file or directory named <code>oldname</code> to <code>newname</code>.
8071 If this function fails, it returns <b>nil</b>,
8072 plus a string describing the error.
8078 <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
8082 Sets the current locale of the program.
8083 <code>locale</code> is a string specifying a locale;
8084 <code>category</code> is an optional string describing which category to change:
8085 <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
8086 <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
8087 the default category is <code>"all"</code>.
8088 The function returns the name of the new locale,
8089 or <b>nil</b> if the request cannot be honored.
8093 If <code>locale</code> is the empty string,
8094 the current locale is set to an implementation-defined native locale.
8095 If <code>locale</code> is the string "<code>C</code>",
8096 the current locale is set to the standard C locale.
8100 When called with <b>nil</b> as the first argument,
8101 this function only returns the name of the current locale
8102 for the given category.
8108 <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
8112 Returns the current time when called without arguments,
8113 or a time representing the date and time specified by the given table.
8114 This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
8115 and may have fields <code>hour</code>, <code>min</code>, <code>sec</code>, and <code>isdst</code>
8116 (for a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function).
8120 The returned value is a number, whose meaning depends on your system.
8121 In POSIX, Windows, and some other systems, this number counts the number
8122 of seconds since some given start time (the "epoch").
8123 In other systems, the meaning is not specified,
8124 and the number returned by <code>time</code> can be used only as an argument to
8125 <code>date</code> and <code>difftime</code>.
8131 <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
8135 Returns a string with a file name that can
8136 be used for a temporary file.
8137 The file must be explicitly opened before its use
8138 and explicitly removed when no longer needed.
8142 On some systems (POSIX),
8143 this function also creates a file with that name,
8144 to avoid security risks.
8145 (Someone else might create the file with wrong permissions
8146 in the time between getting the name and creating the file.)
8147 You still have to open the file to use it
8148 and to remove it (even if you do not use it).
8152 When possible,
8153 you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
8154 which automatically removes the file when the program ends.
8162 <h2>5.9 - <a name="5.9">The Debug Library</a></h2>
8165 This library provides
8166 the functionality of the debug interface to Lua programs.
8167 You should exert care when using this library.
8168 The functions provided here should be used exclusively for debugging
8169 and similar tasks, such as profiling.
8170 Please resist the temptation to use them as a
8171 usual programming tool:
8172 they can be very slow.
8173 Moreover, several of these functions
8174 violate some assumptions about Lua code
8175 (e.g., that variables local to a function
8176 cannot be accessed from outside or
8177 that userdata metatables cannot be changed by Lua code)
8178 and therefore can compromise otherwise secure code.
8182 All functions in this library are provided
8183 inside the <a name="pdf-debug"><code>debug</code></a> table.
8184 All functions that operate over a thread
8185 have an optional first argument which is the
8186 thread to operate over.
8187 The default is always the current thread.
8191 <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
8195 Enters an interactive mode with the user,
8196 running each string that the user enters.
8197 Using simple commands and other debug facilities,
8198 the user can inspect global and local variables,
8199 change their values, evaluate expressions, and so on.
8200 A line containing only the word <code>cont</code> finishes this function,
8201 so that the caller continues its execution.
8205 Note that commands for <code>debug.debug</code> are not lexically nested
8206 within any function, and so have no direct access to local variables.
8212 <hr><h3><a name="pdf-debug.getfenv"><code>debug.getfenv (o)</code></a></h3>
8213 Returns the environment of object <code>o</code>.
8219 <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
8223 Returns the current hook settings of the thread, as three values:
8224 the current hook function, the current hook mask,
8225 and the current hook count
8226 (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
8232 <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] function [, what])</code></a></h3>
8236 Returns a table with information about a function.
8237 You can give the function directly,
8238 or you can give a number as the value of <code>function</code>,
8239 which means the function running at level <code>function</code> of the call stack
8240 of the given thread:
8241 level&nbsp;0 is the current function (<code>getinfo</code> itself);
8242 level&nbsp;1 is the function that called <code>getinfo</code>;
8243 and so on.
8244 If <code>function</code> is a number larger than the number of active functions,
8245 then <code>getinfo</code> returns <b>nil</b>.
8249 The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
8250 with the string <code>what</code> describing which fields to fill in.
8251 The default for <code>what</code> is to get all information available,
8252 except the table of valid lines.
8253 If present,
8254 the option '<code>f</code>'
8255 adds a field named <code>func</code> with the function itself.
8256 If present,
8257 the option '<code>L</code>'
8258 adds a field named <code>activelines</code> with the table of
8259 valid lines.
8263 For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
8264 a table with a name for the current function,
8265 if a reasonable name can be found,
8266 and the expression <code>debug.getinfo(print)</code>
8267 returns a table with all available information
8268 about the <a href="#pdf-print"><code>print</code></a> function.
8274 <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] level, local)</code></a></h3>
8278 This function returns the name and the value of the local variable
8279 with index <code>local</code> of the function at level <code>level</code> of the stack.
8280 (The first parameter or local variable has index&nbsp;1, and so on,
8281 until the last active local variable.)
8282 The function returns <b>nil</b> if there is no local
8283 variable with the given index,
8284 and raises an error when called with a <code>level</code> out of range.
8285 (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
8289 Variable names starting with '<code>(</code>' (open parentheses)
8290 represent internal variables
8291 (loop control variables, temporaries, and C&nbsp;function locals).
8297 <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (object)</code></a></h3>
8301 Returns the metatable of the given <code>object</code>
8302 or <b>nil</b> if it does not have a metatable.
8308 <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
8312 Returns the registry table (see <a href="#3.5">&sect;3.5</a>).
8318 <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (func, up)</code></a></h3>
8322 This function returns the name and the value of the upvalue
8323 with index <code>up</code> of the function <code>func</code>.
8324 The function returns <b>nil</b> if there is no upvalue with the given index.
8330 <hr><h3><a name="pdf-debug.setfenv"><code>debug.setfenv (object, table)</code></a></h3>
8334 Sets the environment of the given <code>object</code> to the given <code>table</code>.
8335 Returns <code>object</code>.
8341 <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
8345 Sets the given function as a hook.
8346 The string <code>mask</code> and the number <code>count</code> describe
8347 when the hook will be called.
8348 The string mask may have the following characters,
8349 with the given meaning:
8351 <ul>
8352 <li><b><code>"c"</code>:</b> the hook is called every time Lua calls a function;</li>
8353 <li><b><code>"r"</code>:</b> the hook is called every time Lua returns from a function;</li>
8354 <li><b><code>"l"</code>:</b> the hook is called every time Lua enters a new line of code.</li>
8355 </ul><p>
8356 With a <code>count</code> different from zero,
8357 the hook is called after every <code>count</code> instructions.
8361 When called without arguments,
8362 <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
8366 When the hook is called, its first parameter is a string
8367 describing the event that has triggered its call:
8368 <code>"call"</code>, <code>"return"</code> (or <code>"tail return"</code>,
8369 when simulating a return from a tail call),
8370 <code>"line"</code>, and <code>"count"</code>.
8371 For line events,
8372 the hook also gets the new line number as its second parameter.
8373 Inside a hook,
8374 you can call <code>getinfo</code> with level&nbsp;2 to get more information about
8375 the running function
8376 (level&nbsp;0 is the <code>getinfo</code> function,
8377 and level&nbsp;1 is the hook function),
8378 unless the event is <code>"tail return"</code>.
8379 In this case, Lua is only simulating the return,
8380 and a call to <code>getinfo</code> will return invalid data.
8386 <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
8390 This function assigns the value <code>value</code> to the local variable
8391 with index <code>local</code> of the function at level <code>level</code> of the stack.
8392 The function returns <b>nil</b> if there is no local
8393 variable with the given index,
8394 and raises an error when called with a <code>level</code> out of range.
8395 (You can call <code>getinfo</code> to check whether the level is valid.)
8396 Otherwise, it returns the name of the local variable.
8402 <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (object, table)</code></a></h3>
8406 Sets the metatable for the given <code>object</code> to the given <code>table</code>
8407 (which can be <b>nil</b>).
8413 <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (func, up, value)</code></a></h3>
8417 This function assigns the value <code>value</code> to the upvalue
8418 with index <code>up</code> of the function <code>func</code>.
8419 The function returns <b>nil</b> if there is no upvalue
8420 with the given index.
8421 Otherwise, it returns the name of the upvalue.
8427 <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
8431 Returns a string with a traceback of the call stack.
8432 An optional <code>message</code> string is appended
8433 at the beginning of the traceback.
8434 An optional <code>level</code> number tells at which level
8435 to start the traceback
8436 (default is 1, the function calling <code>traceback</code>).
8444 <h1>6 - <a name="6">Lua Stand-alone</a></h1>
8447 Although Lua has been designed as an extension language,
8448 to be embedded in a host C&nbsp;program,
8449 it is also frequently used as a stand-alone language.
8450 An interpreter for Lua as a stand-alone language,
8451 called simply <code>lua</code>,
8452 is provided with the standard distribution.
8453 The stand-alone interpreter includes
8454 all standard libraries, including the debug library.
8455 Its usage is:
8457 <pre>
8458 lua [options] [script [args]]
8459 </pre><p>
8460 The options are:
8462 <ul>
8463 <li><b><code>-e <em>stat</em></code>:</b> executes string <em>stat</em>;</li>
8464 <li><b><code>-l <em>mod</em></code>:</b> "requires" <em>mod</em>;</li>
8465 <li><b><code>-i</code>:</b> enters interactive mode after running <em>script</em>;</li>
8466 <li><b><code>-v</code>:</b> prints version information;</li>
8467 <li><b><code>--</code>:</b> stops handling options;</li>
8468 <li><b><code>-</code>:</b> executes <code>stdin</code> as a file and stops handling options.</li>
8469 </ul><p>
8470 After handling its options, <code>lua</code> runs the given <em>script</em>,
8471 passing to it the given <em>args</em> as string arguments.
8472 When called without arguments,
8473 <code>lua</code> behaves as <code>lua -v -i</code>
8474 when the standard input (<code>stdin</code>) is a terminal,
8475 and as <code>lua -</code> otherwise.
8479 Before running any argument,
8480 the interpreter checks for an environment variable <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a>.
8481 If its format is <code>@<em>filename</em></code>,
8482 then <code>lua</code> executes the file.
8483 Otherwise, <code>lua</code> executes the string itself.
8487 All options are handled in order, except <code>-i</code>.
8488 For instance, an invocation like
8490 <pre>
8491 $ lua -e'a=1' -e 'print(a)' script.lua
8492 </pre><p>
8493 will first set <code>a</code> to 1, then print the value of <code>a</code> (which is '<code>1</code>'),
8494 and finally run the file <code>script.lua</code> with no arguments.
8495 (Here <code>$</code> is the shell prompt. Your prompt may be different.)
8499 Before starting to run the script,
8500 <code>lua</code> collects all arguments in the command line
8501 in a global table called <code>arg</code>.
8502 The script name is stored at index 0,
8503 the first argument after the script name goes to index 1,
8504 and so on.
8505 Any arguments before the script name
8506 (that is, the interpreter name plus the options)
8507 go to negative indices.
8508 For instance, in the call
8510 <pre>
8511 $ lua -la b.lua t1 t2
8512 </pre><p>
8513 the interpreter first runs the file <code>a.lua</code>,
8514 then creates a table
8516 <pre>
8517 arg = { [-2] = "lua", [-1] = "-la",
8518 [0] = "b.lua",
8519 [1] = "t1", [2] = "t2" }
8520 </pre><p>
8521 and finally runs the file <code>b.lua</code>.
8522 The script is called with <code>arg[1]</code>, <code>arg[2]</code>, &middot;&middot;&middot;
8523 as arguments;
8524 it can also access these arguments with the vararg expression '<code>...</code>'.
8528 In interactive mode,
8529 if you write an incomplete statement,
8530 the interpreter waits for its completion
8531 by issuing a different prompt.
8535 If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
8536 then its value is used as the prompt.
8537 Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
8538 its value is used as the secondary prompt
8539 (issued during incomplete statements).
8540 Therefore, both prompts can be changed directly on the command line
8541 or in any Lua programs by assigning to <code>_PROMPT</code>.
8542 See the next example:
8544 <pre>
8545 $ lua -e"_PROMPT='myprompt&gt; '" -i
8546 </pre><p>
8547 (The outer pair of quotes is for the shell,
8548 the inner pair is for Lua.)
8549 Note the use of <code>-i</code> to enter interactive mode;
8550 otherwise,
8551 the program would just end silently
8552 right after the assignment to <code>_PROMPT</code>.
8556 To allow the use of Lua as a
8557 script interpreter in Unix systems,
8558 the stand-alone interpreter skips
8559 the first line of a chunk if it starts with <code>#</code>.
8560 Therefore, Lua scripts can be made into executable programs
8561 by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
8562 as in
8564 <pre>
8565 #!/usr/local/bin/lua
8566 </pre><p>
8567 (Of course,
8568 the location of the Lua interpreter may be different in your machine.
8569 If <code>lua</code> is in your <code>PATH</code>,
8570 then
8572 <pre>
8573 #!/usr/bin/env lua
8574 </pre><p>
8575 is a more portable solution.)
8579 <h1>7 - <a name="7">Incompatibilities with the Previous Version</a></h1>
8582 Here we list the incompatibilities that you may find when moving a program
8583 from Lua&nbsp;5.0 to Lua&nbsp;5.1.
8584 You can avoid most of the incompatibilities compiling Lua with
8585 appropriate options (see file <code>luaconf.h</code>).
8586 However,
8587 all these compatibility options will be removed in the next version of Lua.
8591 <h2>7.1 - <a name="7.1">Changes in the Language</a></h2>
8592 <ul>
8594 <li>
8595 The vararg system changed from the pseudo-argument <code>arg</code> with a
8596 table with the extra arguments to the vararg expression.
8597 (See compile-time option <code>LUA_COMPAT_VARARG</code> in <code>luaconf.h</code>.)
8598 </li>
8600 <li>
8601 There was a subtle change in the scope of the implicit
8602 variables of the <b>for</b> statement and for the <b>repeat</b> statement.
8603 </li>
8605 <li>
8606 The long string/long comment syntax (<code>[[<em>string</em>]]</code>)
8607 does not allow nesting.
8608 You can use the new syntax (<code>[=[<em>string</em>]=]</code>) in these cases.
8609 (See compile-time option <code>LUA_COMPAT_LSTR</code> in <code>luaconf.h</code>.)
8610 </li>
8612 </ul>
8617 <h2>7.2 - <a name="7.2">Changes in the Libraries</a></h2>
8618 <ul>
8620 <li>
8621 Function <code>string.gfind</code> was renamed <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>.
8622 (See compile-time option <code>LUA_COMPAT_GFIND</code> in <code>luaconf.h</code>.)
8623 </li>
8625 <li>
8626 When <a href="#pdf-string.gsub"><code>string.gsub</code></a> is called with a function as its
8627 third argument,
8628 whenever this function returns <b>nil</b> or <b>false</b> the
8629 replacement string is the whole match,
8630 instead of the empty string.
8631 </li>
8633 <li>
8634 Function <code>table.setn</code> was deprecated.
8635 Function <code>table.getn</code> corresponds
8636 to the new length operator (<code>#</code>);
8637 use the operator instead of the function.
8638 (See compile-time option <code>LUA_COMPAT_GETN</code> in <code>luaconf.h</code>.)
8639 </li>
8641 <li>
8642 Function <code>loadlib</code> was renamed <a href="#pdf-package.loadlib"><code>package.loadlib</code></a>.
8643 (See compile-time option <code>LUA_COMPAT_LOADLIB</code> in <code>luaconf.h</code>.)
8644 </li>
8646 <li>
8647 Function <code>math.mod</code> was renamed <a href="#pdf-math.fmod"><code>math.fmod</code></a>.
8648 (See compile-time option <code>LUA_COMPAT_MOD</code> in <code>luaconf.h</code>.)
8649 </li>
8651 <li>
8652 Functions <code>table.foreach</code> and <code>table.foreachi</code> are deprecated.
8653 You can use a for loop with <code>pairs</code> or <code>ipairs</code> instead.
8654 </li>
8656 <li>
8657 There were substantial changes in function <a href="#pdf-require"><code>require</code></a> due to
8658 the new module system.
8659 However, the new behavior is mostly compatible with the old,
8660 but <code>require</code> gets the path from <a href="#pdf-package.path"><code>package.path</code></a> instead
8661 of from <code>LUA_PATH</code>.
8662 </li>
8664 <li>
8665 Function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> has different arguments.
8666 Function <code>gcinfo</code> is deprecated;
8667 use <code>collectgarbage("count")</code> instead.
8668 </li>
8670 </ul>
8675 <h2>7.3 - <a name="7.3">Changes in the API</a></h2>
8676 <ul>
8678 <li>
8679 The <code>luaopen_*</code> functions (to open libraries)
8680 cannot be called directly,
8681 like a regular C function.
8682 They must be called through Lua,
8683 like a Lua function.
8684 </li>
8686 <li>
8687 Function <code>lua_open</code> was replaced by <a href="#lua_newstate"><code>lua_newstate</code></a> to
8688 allow the user to set a memory-allocation function.
8689 You can use <a href="#luaL_newstate"><code>luaL_newstate</code></a> from the standard library to
8690 create a state with a standard allocation function
8691 (based on <code>realloc</code>).
8692 </li>
8694 <li>
8695 Functions <code>luaL_getn</code> and <code>luaL_setn</code>
8696 (from the auxiliary library) are deprecated.
8697 Use <a href="#lua_objlen"><code>lua_objlen</code></a> instead of <code>luaL_getn</code>
8698 and nothing instead of <code>luaL_setn</code>.
8699 </li>
8701 <li>
8702 Function <code>luaL_openlib</code> was replaced by <a href="#luaL_register"><code>luaL_register</code></a>.
8703 </li>
8705 <li>
8706 Function <code>luaL_checkudata</code> now throws an error when the given value
8707 is not a userdata of the expected type.
8708 (In Lua&nbsp;5.0 it returned <code>NULL</code>.)
8709 </li>
8711 </ul>
8716 <h1>8 - <a name="8">The Complete Syntax of Lua</a></h1>
8719 Here is the complete syntax of Lua in extended BNF.
8720 (It does not describe operator precedences.)
8725 <pre>
8727 chunk ::= {stat [`<b>;</b>&acute;]} [laststat [`<b>;</b>&acute;]]
8729 block ::= chunk
8731 stat ::= varlist `<b>=</b>&acute; explist |
8732 functioncall |
8733 <b>do</b> block <b>end</b> |
8734 <b>while</b> exp <b>do</b> block <b>end</b> |
8735 <b>repeat</b> block <b>until</b> exp |
8736 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
8737 <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b> |
8738 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
8739 <b>function</b> funcname funcbody |
8740 <b>local</b> <b>function</b> Name funcbody |
8741 <b>local</b> namelist [`<b>=</b>&acute; explist]
8743 laststat ::= <b>return</b> [explist] | <b>break</b>
8745 funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
8747 varlist ::= var {`<b>,</b>&acute; var}
8749 var ::= Name | prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute; | prefixexp `<b>.</b>&acute; Name
8751 namelist ::= Name {`<b>,</b>&acute; Name}
8753 explist ::= {exp `<b>,</b>&acute;} exp
8755 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | `<b>...</b>&acute; | function |
8756 prefixexp | tableconstructor | exp binop exp | unop exp
8758 prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
8760 functioncall ::= prefixexp args | prefixexp `<b>:</b>&acute; Name args
8762 args ::= `<b>(</b>&acute; [explist] `<b>)</b>&acute; | tableconstructor | String
8764 function ::= <b>function</b> funcbody
8766 funcbody ::= `<b>(</b>&acute; [parlist] `<b>)</b>&acute; block <b>end</b>
8768 parlist ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
8770 tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
8772 fieldlist ::= field {fieldsep field} [fieldsep]
8774 field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
8776 fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
8778 binop ::= `<b>+</b>&acute; | `<b>-</b>&acute; | `<b>*</b>&acute; | `<b>/</b>&acute; | `<b>^</b>&acute; | `<b>%</b>&acute; | `<b>..</b>&acute; |
8779 `<b>&lt;</b>&acute; | `<b>&lt;=</b>&acute; | `<b>&gt;</b>&acute; | `<b>&gt;=</b>&acute; | `<b>==</b>&acute; | `<b>~=</b>&acute; |
8780 <b>and</b> | <b>or</b>
8782 unop ::= `<b>-</b>&acute; | <b>not</b> | `<b>#</b>&acute;
8784 </pre>
8794 <HR>
8795 <SMALL CLASS="footer">
8796 Last update:
8797 Mon Feb 13 18:54:19 BRST 2012
8798 </SMALL>
8799 <!--
8800 Last change: revised for Lua 5.1.5
8803 </body></html>