use lua_mem(L, +-size) to track your additional userdata sizes. keep it balanced...
[blua.git] / doc / manual.html
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=""><img src="logo.gif" alt="" border="0"></a>
16 Lua 5.1 Reference Manual
17 </h1>
19 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
20 <p>
21 <small>
22 Copyright &copy; 2006-2008, PUC-Rio.
23 Freely available under the terms of the
24 <a href="">Lua license</a>.
25 </small>
26 <hr>
27 <p>
29 <a href="contents.html#contents">contents</A>
30 &middot;
31 <a href="contents.html#index">index</A>
33 <!-- ====================================================================== -->
34 <p>
36 <!-- $Id: manual.of,v 1.48 2008/08/18 15:24:20 roberto Exp $ -->
41 <h1>1 - <a name="1">Introduction</a></h1>
43 <p>
44 Lua is an extension programming language designed to support
45 general procedural programming with data description
46 facilities.
47 It also offers good support for object-oriented programming,
48 functional programming, and data-driven programming.
49 Lua is intended to be used as a powerful, light-weight
50 scripting language for any program that needs one.
51 Lua is implemented as a library, written in <em>clean</em> C
52 (that is, in the common subset of ANSI&nbsp;C and C++).
55 <p>
56 Being an extension language, Lua has no notion of a "main" program:
57 it only works <em>embedded</em> in a host client,
58 called the <em>embedding program</em> or simply the <em>host</em>.
59 This host program can invoke functions to execute a piece of Lua code,
60 can write and read Lua variables,
61 and can register C&nbsp;functions to be called by Lua code.
62 Through the use of C&nbsp;functions, Lua can be augmented to cope with
63 a wide range of different domains,
64 thus creating customized programming languages sharing a syntactical framework.
65 The Lua distribution includes a sample host program called <code>lua</code>,
66 which uses the Lua library to offer a complete, stand-alone Lua interpreter.
69 <p>
70 Lua is free software,
71 and is provided as usual with no guarantees,
72 as stated in its license.
73 The implementation described in this manual is available
74 at Lua's official web site, <code></code>.
77 <p>
78 Like any other reference manual,
79 this document is dry in places.
80 For a discussion of the decisions behind the design of Lua,
81 see the technical papers available at Lua's web site.
82 For a detailed introduction to programming in Lua,
83 see Roberto's book, <em>Programming in Lua (Second Edition)</em>.
87 <h1>2 - <a name="2">The Language</a></h1>
89 <p>
90 This section describes the lexis, the syntax, and the semantics of Lua.
91 In other words,
92 this section describes
93 which tokens are valid,
94 how they can be combined,
95 and what their combinations mean.
98 <p>
99 The language constructs will be explained using the usual extended BNF notation,
100 in which
101 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
102 [<em>a</em>]&nbsp;means an optional <em>a</em>.
103 Non-terminals are shown like non-terminal,
104 keywords are shown like <b>kword</b>,
105 and other terminal symbols are shown like `<b>=</b>&acute;.
106 The complete syntax of Lua can be found in <a href="#8">&sect;8</a>
107 at the end of this manual.
111 <h2>2.1 - <a name="2.1">Lexical Conventions</a></h2>
114 <em>Names</em>
115 (also called <em>identifiers</em>)
116 in Lua can be any string of letters,
117 digits, and underscores,
118 not beginning with a digit.
119 This coincides with the definition of names in most languages.
120 (The definition of letter depends on the current locale:
121 any character considered alphabetic by the current locale
122 can be used in an identifier.)
123 Identifiers are used to name variables and table fields.
127 The following <em>keywords</em> are reserved
128 and cannot be used as names:
131 <pre>
132 and break do else elseif
133 end false for function if
134 in local nil not or
135 repeat return then true until while
136 </pre>
139 Lua is a case-sensitive language:
140 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
141 are two different, valid names.
142 As a convention, names starting with an underscore followed by
143 uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
144 are reserved for internal global variables used by Lua.
148 The following strings denote other tokens:
150 <pre>
151 + - * / % ^ #
152 == ~= &lt;= &gt;= &lt; &gt; =
153 ( ) { } [ ]
154 ; : , . .. ...
155 </pre>
158 <em>Literal strings</em>
159 can be delimited by matching single or double quotes,
160 and can contain the following C-like escape sequences:
161 '<code>\a</code>' (bell),
162 '<code>\b</code>' (backspace),
163 '<code>\f</code>' (form feed),
164 '<code>\n</code>' (newline),
165 '<code>\r</code>' (carriage return),
166 '<code>\t</code>' (horizontal tab),
167 '<code>\v</code>' (vertical tab),
168 '<code>\\</code>' (backslash),
169 '<code>\"</code>' (quotation mark [double quote]),
170 and '<code>\'</code>' (apostrophe [single quote]).
171 Moreover, a backslash followed by a real newline
172 results in a newline in the string.
173 A character in a string can also be specified by its numerical value
174 using the escape sequence <code>\<em>ddd</em></code>,
175 where <em>ddd</em> is a sequence of up to three decimal digits.
176 (Note that if a numerical escape is to be followed by a digit,
177 it must be expressed using exactly three digits.)
178 Strings in Lua can contain any 8-bit value, including embedded zeros,
179 which can be specified as '<code>\0</code>'.
183 Literal strings can also be defined using a long format
184 enclosed by <em>long brackets</em>.
185 We define an <em>opening long bracket of level <em>n</em></em> as an opening
186 square bracket followed by <em>n</em> equal signs followed by another
187 opening square bracket.
188 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
189 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
190 and so on.
191 A <em>closing long bracket</em> is defined similarly;
192 for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
193 A long string starts with an opening long bracket of any level and
194 ends at the first closing long bracket of the same level.
195 Literals in this bracketed form can run for several lines,
196 do not interpret any escape sequences,
197 and ignore long brackets of any other level.
198 They can contain anything except a closing bracket of the proper level.
202 For convenience,
203 when the opening long bracket is immediately followed by a newline,
204 the newline is not included in the string.
205 As an example, in a system using ASCII
206 (in which '<code>a</code>' is coded as&nbsp;97,
207 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
208 the five literal strings below denote the same string:
210 <pre>
211 a = 'alo\n123"'
212 a = "alo\n123\""
213 a = '\97lo\10\04923"'
214 a = [[alo
215 123"]]
216 a = [==[
218 123"]==]
219 </pre>
222 A <em>numerical constant</em> can be written with an optional decimal part
223 and an optional decimal exponent.
224 Lua also accepts integer hexadecimal constants,
225 by prefixing them with <code>0x</code>.
226 Examples of valid numerical constants are
228 <pre>
229 3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
230 </pre>
233 A <em>comment</em> starts with a double hyphen (<code>--</code>)
234 anywhere outside a string.
235 If the text immediately after <code>--</code> is not an opening long bracket,
236 the comment is a <em>short comment</em>,
237 which runs until the end of the line.
238 Otherwise, it is a <em>long comment</em>,
239 which runs until the corresponding closing long bracket.
240 Long comments are frequently used to disable code temporarily.
246 <h2>2.2 - <a name="2.2">Values and Types</a></h2>
249 Lua is a <em>dynamically typed language</em>.
250 This means that
251 variables do not have types; only values do.
252 There are no type definitions in the language.
253 All values carry their own type.
257 All values in Lua are <em>first-class values</em>.
258 This means that all values can be stored in variables,
259 passed as arguments to other functions, and returned as results.
263 There are eight basic types in Lua:
264 <em>nil</em>, <em>boolean</em>, <em>number</em>,
265 <em>string</em>, <em>function</em>, <em>userdata</em>,
266 <em>thread</em>, and <em>table</em>.
267 <em>Nil</em> is the type of the value <b>nil</b>,
268 whose main property is to be different from any other value;
269 it usually represents the absence of a useful value.
270 <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
271 Both <b>nil</b> and <b>false</b> make a condition false;
272 any other value makes it true.
273 <em>Number</em> represents real (double-precision floating-point) numbers.
274 (It is easy to build Lua interpreters that use other
275 internal representations for numbers,
276 such as single-precision float or long integers;
277 see file <code>luaconf.h</code>.)
278 <em>String</em> represents arrays of characters.
280 Lua is 8-bit clean:
281 strings can contain any 8-bit character,
282 including embedded zeros ('<code>\0</code>') (see <a href="#2.1">&sect;2.1</a>).
286 Lua can call (and manipulate) functions written in Lua and
287 functions written in C
288 (see <a href="#2.5.8">&sect;2.5.8</a>).
292 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
293 be stored in Lua variables.
294 This type corresponds to a block of raw memory
295 and has no pre-defined operations in Lua,
296 except assignment and identity test.
297 However, by using <em>metatables</em>,
298 the programmer can define operations for userdata values
299 (see <a href="#2.8">&sect;2.8</a>).
300 Userdata values cannot be created or modified in Lua,
301 only through the C&nbsp;API.
302 This guarantees the integrity of data owned by the host program.
306 The type <em>thread</em> represents independent threads of execution
307 and it is used to implement coroutines (see <a href="#2.11">&sect;2.11</a>).
308 Do not confuse Lua threads with operating-system threads.
309 Lua supports coroutines on all systems,
310 even those that do not support threads.
314 The type <em>table</em> implements associative arrays,
315 that is, arrays that can be indexed not only with numbers,
316 but with any value (except <b>nil</b>).
317 Tables can be <em>heterogeneous</em>;
318 that is, they can contain values of all types (except <b>nil</b>).
319 Tables are the sole data structuring mechanism in Lua;
320 they can be used to represent ordinary arrays,
321 symbol tables, sets, records, graphs, trees, etc.
322 To represent records, Lua uses the field name as an index.
323 The language supports this representation by
324 providing <code></code> as syntactic sugar for <code>a["name"]</code>.
325 There are several convenient ways to create tables in Lua
326 (see <a href="#2.5.7">&sect;2.5.7</a>).
330 Like indices,
331 the value of a table field can be of any type (except <b>nil</b>).
332 In particular,
333 because functions are first-class values,
334 table fields can contain functions.
335 Thus tables can also carry <em>methods</em> (see <a href="#2.5.9">&sect;2.5.9</a>).
339 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
340 variables do not actually <em>contain</em> these values,
341 only <em>references</em> to them.
342 Assignment, parameter passing, and function returns
343 always manipulate references to such values;
344 these operations do not imply any kind of copy.
348 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
349 of a given value.
353 <h3>2.2.1 - <a name="2.2.1">Coercion</a></h3>
356 Lua provides automatic conversion between
357 string and number values at run time.
358 Any arithmetic operation applied to a string tries to convert
359 this string to a number, following the usual conversion rules.
360 Conversely, whenever a number is used where a string is expected,
361 the number is converted to a string, in a reasonable format.
362 For complete control over how numbers are converted to strings,
363 use the <code>format</code> function from the string library
364 (see <a href="#pdf-string.format"><code>string.format</code></a>).
372 <h2>2.3 - <a name="2.3">Variables</a></h2>
375 Variables are places that store values.
377 There are three kinds of variables in Lua:
378 global variables, local variables, and table fields.
382 A single name can denote a global variable or a local variable
383 (or a function's formal parameter,
384 which is a particular kind of local variable):
386 <pre>
387 var ::= Name
388 </pre><p>
389 Name denotes identifiers, as defined in <a href="#2.1">&sect;2.1</a>.
393 Any variable is assumed to be global unless explicitly declared
394 as a local (see <a href="#2.4.7">&sect;2.4.7</a>).
395 Local variables are <em>lexically scoped</em>:
396 local variables can be freely accessed by functions
397 defined inside their scope (see <a href="#2.6">&sect;2.6</a>).
401 Before the first assignment to a variable, its value is <b>nil</b>.
405 Square brackets are used to index a table:
407 <pre>
408 var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
409 </pre><p>
410 The meaning of accesses to global variables
411 and table fields can be changed via metatables.
412 An access to an indexed variable <code>t[i]</code> is equivalent to
413 a call <code>gettable_event(t,i)</code>.
414 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
415 <code>gettable_event</code> function.
416 This function is not defined or callable in Lua.
417 We use it here only for explanatory purposes.)
421 The syntax <code>var.Name</code> is just syntactic sugar for
422 <code>var["Name"]</code>:
424 <pre>
425 var ::= prefixexp `<b>.</b>&acute; Name
426 </pre>
429 All global variables live as fields in ordinary Lua tables,
430 called <em>environment tables</em> or simply
431 <em>environments</em> (see <a href="#2.9">&sect;2.9</a>).
432 Each function has its own reference to an environment,
433 so that all global variables in this function
434 will refer to this environment table.
435 When a function is created,
436 it inherits the environment from the function that created it.
437 To get the environment table of a Lua function,
438 you call <a href="#pdf-getfenv"><code>getfenv</code></a>.
439 To replace it,
440 you call <a href="#pdf-setfenv"><code>setfenv</code></a>.
441 (You can only manipulate the environment of C&nbsp;functions
442 through the debug library; (see <a href="#5.9">&sect;5.9</a>).)
446 An access to a global variable <code>x</code>
447 is equivalent to <code>_env.x</code>,
448 which in turn is equivalent to
450 <pre>
451 gettable_event(_env, "x")
452 </pre><p>
453 where <code>_env</code> is the environment of the running function.
454 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
455 <code>gettable_event</code> function.
456 This function is not defined or callable in Lua.
457 Similarly, the <code>_env</code> variable is not defined in Lua.
458 We use them here only for explanatory purposes.)
464 <h2>2.4 - <a name="2.4">Statements</a></h2>
467 Lua supports an almost conventional set of statements,
468 similar to those in Pascal or C.
469 This set includes
470 assignments, control structures, function calls,
471 and variable declarations.
475 <h3>2.4.1 - <a name="2.4.1">Chunks</a></h3>
478 The unit of execution of Lua is called a <em>chunk</em>.
479 A chunk is simply a sequence of statements,
480 which are executed sequentially.
481 Each statement can be optionally followed by a semicolon:
483 <pre>
484 chunk ::= {stat [`<b>;</b>&acute;]}
485 </pre><p>
486 There are no empty statements and thus '<code>;;</code>' is not legal.
490 Lua handles a chunk as the body of an anonymous function
491 with a variable number of arguments
492 (see <a href="#2.5.9">&sect;2.5.9</a>).
493 As such, chunks can define local variables,
494 receive arguments, and return values.
498 A chunk can be stored in a file or in a string inside the host program.
499 To execute a chunk,
500 Lua first pre-compiles the chunk into instructions for a virtual machine,
501 and then it executes the compiled code
502 with an interpreter for the virtual machine.
506 Chunks can also be pre-compiled into binary form;
507 see program <code>luac</code> for details.
508 Programs in source and compiled forms are interchangeable;
509 Lua automatically detects the file type and acts accordingly.
516 <h3>2.4.2 - <a name="2.4.2">Blocks</a></h3><p>
517 A block is a list of statements;
518 syntactically, a block is the same as a chunk:
520 <pre>
521 block ::= chunk
522 </pre>
525 A block can be explicitly delimited to produce a single statement:
527 <pre>
528 stat ::= <b>do</b> block <b>end</b>
529 </pre><p>
530 Explicit blocks are useful
531 to control the scope of variable declarations.
532 Explicit blocks are also sometimes used to
533 add a <b>return</b> or <b>break</b> statement in the middle
534 of another block (see <a href="#2.4.4">&sect;2.4.4</a>).
540 <h3>2.4.3 - <a name="2.4.3">Assignment</a></h3>
543 Lua allows multiple assignments.
544 Therefore, the syntax for assignment
545 defines a list of variables on the left side
546 and a list of expressions on the right side.
547 The elements in both lists are separated by commas:
549 <pre>
550 stat ::= varlist `<b>=</b>&acute; explist
551 varlist ::= var {`<b>,</b>&acute; var}
552 explist ::= exp {`<b>,</b>&acute; exp}
553 </pre><p>
554 Expressions are discussed in <a href="#2.5">&sect;2.5</a>.
558 Before the assignment,
559 the list of values is <em>adjusted</em> to the length of
560 the list of variables.
561 If there are more values than needed,
562 the excess values are thrown away.
563 If there are fewer values than needed,
564 the list is extended with as many <b>nil</b>'s as needed.
565 If the list of expressions ends with a function call,
566 then all values returned by that call enter the list of values,
567 before the adjustment
568 (except when the call is enclosed in parentheses; see <a href="#2.5">&sect;2.5</a>).
572 The assignment statement first evaluates all its expressions
573 and only then are the assignments performed.
574 Thus the code
576 <pre>
577 i = 3
578 i, a[i] = i+1, 20
579 </pre><p>
580 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
581 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
582 before it is assigned&nbsp;4.
583 Similarly, the line
585 <pre>
586 x, y = y, x
587 </pre><p>
588 exchanges the values of <code>x</code> and <code>y</code>,
591 <pre>
592 x, y, z = y, z, x
593 </pre><p>
594 cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
598 The meaning of assignments to global variables
599 and table fields can be changed via metatables.
600 An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
601 <code>settable_event(t,i,val)</code>.
602 (See <a href="#2.8">&sect;2.8</a> for a complete description of the
603 <code>settable_event</code> function.
604 This function is not defined or callable in Lua.
605 We use it here only for explanatory purposes.)
609 An assignment to a global variable <code>x = val</code>
610 is equivalent to the assignment
611 <code>_env.x = val</code>,
612 which in turn is equivalent to
614 <pre>
615 settable_event(_env, "x", val)
616 </pre><p>
617 where <code>_env</code> is the environment of the running function.
618 (The <code>_env</code> variable is not defined in Lua.
619 We use it here only for explanatory purposes.)
625 <h3>2.4.4 - <a name="2.4.4">Control Structures</a></h3><p>
626 The control structures
627 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
628 familiar syntax:
633 <pre>
634 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
635 stat ::= <b>repeat</b> block <b>until</b> exp
636 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
637 </pre><p>
638 Lua also has a <b>for</b> statement, in two flavors (see <a href="#2.4.5">&sect;2.4.5</a>).
642 The condition expression of a
643 control structure can return any value.
644 Both <b>false</b> and <b>nil</b> are considered false.
645 All values different from <b>nil</b> and <b>false</b> are considered true
646 (in particular, the number 0 and the empty string are also true).
650 In the <b>repeat</b>&ndash;<b>until</b> loop,
651 the inner block does not end at the <b>until</b> keyword,
652 but only after the condition.
653 So, the condition can refer to local variables
654 declared inside the loop block.
658 The <b>return</b> statement is used to return values
659 from a function or a chunk (which is just a function).
661 Functions and chunks can return more than one value,
662 and so the syntax for the <b>return</b> statement is
664 <pre>
665 stat ::= <b>return</b> [explist]
666 </pre>
669 The <b>break</b> statement is used to terminate the execution of a
670 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
671 skipping to the next statement after the loop:
674 <pre>
675 stat ::= <b>break</b>
676 </pre><p>
677 A <b>break</b> ends the innermost enclosing loop.
681 The <b>return</b> and <b>break</b>
682 statements can only be written as the <em>last</em> statement of a block.
683 If it is really necessary to <b>return</b> or <b>break</b> in the
684 middle of a block,
685 then an explicit inner block can be used,
686 as in the idioms
687 <code>do return end</code> and <code>do break end</code>,
688 because now <b>return</b> and <b>break</b> are the last statements in
689 their (inner) blocks.
695 <h3>2.4.5 - <a name="2.4.5">For Statement</a></h3>
699 The <b>for</b> statement has two forms:
700 one numeric and one generic.
704 The numeric <b>for</b> loop repeats a block of code while a
705 control variable runs through an arithmetic progression.
706 It has the following syntax:
708 <pre>
709 stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
710 </pre><p>
711 The <em>block</em> is repeated for <em>name</em> starting at the value of
712 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
713 third <em>exp</em>.
714 More precisely, a <b>for</b> statement like
716 <pre>
717 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
718 </pre><p>
719 is equivalent to the code:
721 <pre>
723 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
724 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
725 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
726 local v = <em>var</em>
727 <em>block</em>
728 <em>var</em> = <em>var</em> + <em>step</em>
731 </pre><p>
732 Note the following:
734 <ul>
736 <li>
737 All three control expressions are evaluated only once,
738 before the loop starts.
739 They must all result in numbers.
740 </li>
742 <li>
743 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
744 The names shown here are for explanatory purposes only.
745 </li>
747 <li>
748 If the third expression (the step) is absent,
749 then a step of&nbsp;1 is used.
750 </li>
752 <li>
753 You can use <b>break</b> to exit a <b>for</b> loop.
754 </li>
756 <li>
757 The loop variable <code>v</code> is local to the loop;
758 you cannot use its value after the <b>for</b> ends or is broken.
759 If you need this value,
760 assign it to another variable before breaking or exiting the loop.
761 </li>
763 </ul>
766 The generic <b>for</b> statement works over functions,
767 called <em>iterators</em>.
768 On each iteration, the iterator function is called to produce a new value,
769 stopping when this new value is <b>nil</b>.
770 The generic <b>for</b> loop has the following syntax:
772 <pre>
773 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
774 namelist ::= Name {`<b>,</b>&acute; Name}
775 </pre><p>
776 A <b>for</b> statement like
778 <pre>
779 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
780 </pre><p>
781 is equivalent to the code:
783 <pre>
785 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
786 while true do
787 local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
788 <em>var</em> = <em>var_1</em>
789 if <em>var</em> == nil then break end
790 <em>block</em>
793 </pre><p>
794 Note the following:
796 <ul>
798 <li>
799 <code><em>explist</em></code> is evaluated only once.
800 Its results are an <em>iterator</em> function,
801 a <em>state</em>,
802 and an initial value for the first <em>iterator variable</em>.
803 </li>
805 <li>
806 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
807 The names are here for explanatory purposes only.
808 </li>
810 <li>
811 You can use <b>break</b> to exit a <b>for</b> loop.
812 </li>
814 <li>
815 The loop variables <code><em>var_i</em></code> are local to the loop;
816 you cannot use their values after the <b>for</b> ends.
817 If you need these values,
818 then assign them to other variables before breaking or exiting the loop.
819 </li>
821 </ul>
826 <h3>2.4.6 - <a name="2.4.6">Function Calls as Statements</a></h3><p>
827 To allow possible side-effects,
828 function calls can be executed as statements:
830 <pre>
831 stat ::= functioncall
832 </pre><p>
833 In this case, all returned values are thrown away.
834 Function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>.
840 <h3>2.4.7 - <a name="2.4.7">Local Declarations</a></h3><p>
841 Local variables can be declared anywhere inside a block.
842 The declaration can include an initial assignment:
844 <pre>
845 stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist]
846 </pre><p>
847 If present, an initial assignment has the same semantics
848 of a multiple assignment (see <a href="#2.4.3">&sect;2.4.3</a>).
849 Otherwise, all variables are initialized with <b>nil</b>.
853 A chunk is also a block (see <a href="#2.4.1">&sect;2.4.1</a>),
854 and so local variables can be declared in a chunk outside any explicit block.
855 The scope of such local variables extends until the end of the chunk.
859 The visibility rules for local variables are explained in <a href="#2.6">&sect;2.6</a>.
867 <h2>2.5 - <a name="2.5">Expressions</a></h2>
870 The basic expressions in Lua are the following:
872 <pre>
873 exp ::= prefixexp
874 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
875 exp ::= Number
876 exp ::= String
877 exp ::= function
878 exp ::= tableconstructor
879 exp ::= `<b>...</b>&acute;
880 exp ::= exp binop exp
881 exp ::= unop exp
882 prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
883 </pre>
886 Numbers and literal strings are explained in <a href="#2.1">&sect;2.1</a>;
887 variables are explained in <a href="#2.3">&sect;2.3</a>;
888 function definitions are explained in <a href="#2.5.9">&sect;2.5.9</a>;
889 function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>;
890 table constructors are explained in <a href="#2.5.7">&sect;2.5.7</a>.
891 Vararg expressions,
892 denoted by three dots ('<code>...</code>'), can only be used when
893 directly inside a vararg function;
894 they are explained in <a href="#2.5.9">&sect;2.5.9</a>.
898 Binary operators comprise arithmetic operators (see <a href="#2.5.1">&sect;2.5.1</a>),
899 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>),
900 and the concatenation operator (see <a href="#2.5.4">&sect;2.5.4</a>).
901 Unary operators comprise the unary minus (see <a href="#2.5.1">&sect;2.5.1</a>),
902 the unary <b>not</b> (see <a href="#2.5.3">&sect;2.5.3</a>),
903 and the unary <em>length operator</em> (see <a href="#2.5.5">&sect;2.5.5</a>).
907 Both function calls and vararg expressions can result in multiple values.
908 If an expression is used as a statement
909 (only possible for function calls (see <a href="#2.4.6">&sect;2.4.6</a>)),
910 then its return list is adjusted to zero elements,
911 thus discarding all returned values.
912 If an expression is used as the last (or the only) element
913 of a list of expressions,
914 then no adjustment is made
915 (unless the call is enclosed in parentheses).
916 In all other contexts,
917 Lua adjusts the result list to one element,
918 discarding all values except the first one.
922 Here are some examples:
924 <pre>
925 f() -- adjusted to 0 results
926 g(f(), x) -- f() is adjusted to 1 result
927 g(x, f()) -- g gets x plus all results from f()
928 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
929 a,b = ... -- a gets the first vararg parameter, b gets
930 -- the second (both a and b can get nil if there
931 -- is no corresponding vararg parameter)
933 a,b,c = x, f() -- f() is adjusted to 2 results
934 a,b,c = f() -- f() is adjusted to 3 results
935 return f() -- returns all results from f()
936 return ... -- returns all received vararg parameters
937 return x,y,f() -- returns x, y, and all results from f()
938 {f()} -- creates a list with all results from f()
939 {...} -- creates a list with all vararg parameters
940 {f(), nil} -- f() is adjusted to 1 result
941 </pre>
944 Any expression enclosed in parentheses always results in only one value.
945 Thus,
946 <code>(f(x,y,z))</code> is always a single value,
947 even if <code>f</code> returns several values.
948 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
949 or <b>nil</b> if <code>f</code> does not return any values.)
953 <h3>2.5.1 - <a name="2.5.1">Arithmetic Operators</a></h3><p>
954 Lua supports the usual arithmetic operators:
955 the binary <code>+</code> (addition),
956 <code>-</code> (subtraction), <code>*</code> (multiplication),
957 <code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
958 and unary <code>-</code> (negation).
959 If the operands are numbers, or strings that can be converted to
960 numbers (see <a href="#2.2.1">&sect;2.2.1</a>),
961 then all operations have the usual meaning.
962 Exponentiation works for any exponent.
963 For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
964 Modulo is defined as
966 <pre>
967 a % b == a - math.floor(a/b)*b
968 </pre><p>
969 That is, it is the remainder of a division that rounds
970 the quotient towards minus infinity.
976 <h3>2.5.2 - <a name="2.5.2">Relational Operators</a></h3><p>
977 The relational operators in Lua are
979 <pre>
980 == ~= &lt; &gt; &lt;= &gt;=
981 </pre><p>
982 These operators always result in <b>false</b> or <b>true</b>.
986 Equality (<code>==</code>) first compares the type of its operands.
987 If the types are different, then the result is <b>false</b>.
988 Otherwise, the values of the operands are compared.
989 Numbers and strings are compared in the usual way.
990 Objects (tables, userdata, threads, and functions)
991 are compared by <em>reference</em>:
992 two objects are considered equal only if they are the <em>same</em> object.
993 Every time you create a new object
994 (a table, userdata, thread, or function),
995 this new object is different from any previously existing object.
999 You can change the way that Lua compares tables and userdata
1000 by using the "eq" metamethod (see <a href="#2.8">&sect;2.8</a>).
1004 The conversion rules of <a href="#2.2.1">&sect;2.2.1</a>
1005 <em>do not</em> apply to equality comparisons.
1006 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
1007 and <code>t[0]</code> and <code>t["0"]</code> denote different
1008 entries in a table.
1012 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
1016 The order operators work as follows.
1017 If both arguments are numbers, then they are compared as such.
1018 Otherwise, if both arguments are strings,
1019 then their values are compared according to the current locale.
1020 Otherwise, Lua tries to call the "lt" or the "le"
1021 metamethod (see <a href="#2.8">&sect;2.8</a>).
1022 A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
1023 and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
1029 <h3>2.5.3 - <a name="2.5.3">Logical Operators</a></h3><p>
1030 The logical operators in Lua are
1031 <b>and</b>, <b>or</b>, and <b>not</b>.
1032 Like the control structures (see <a href="#2.4.4">&sect;2.4.4</a>),
1033 all logical operators consider both <b>false</b> and <b>nil</b> as false
1034 and anything else as true.
1038 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
1039 The conjunction operator <b>and</b> returns its first argument
1040 if this value is <b>false</b> or <b>nil</b>;
1041 otherwise, <b>and</b> returns its second argument.
1042 The disjunction operator <b>or</b> returns its first argument
1043 if this value is different from <b>nil</b> and <b>false</b>;
1044 otherwise, <b>or</b> returns its second argument.
1045 Both <b>and</b> and <b>or</b> use short-cut evaluation;
1046 that is,
1047 the second operand is evaluated only if necessary.
1048 Here are some examples:
1050 <pre>
1051 10 or 20 --&gt; 10
1052 10 or error() --&gt; 10
1053 nil or "a" --&gt; "a"
1054 nil and 10 --&gt; nil
1055 false and error() --&gt; false
1056 false and nil --&gt; false
1057 false or nil --&gt; nil
1058 10 and 20 --&gt; 20
1059 </pre><p>
1060 (In this manual,
1061 <code>--&gt;</code> indicates the result of the preceding expression.)
1067 <h3>2.5.4 - <a name="2.5.4">Concatenation</a></h3><p>
1068 The string concatenation operator in Lua is
1069 denoted by two dots ('<code>..</code>').
1070 If both operands are strings or numbers, then they are converted to
1071 strings according to the rules mentioned in <a href="#2.2.1">&sect;2.2.1</a>.
1072 Otherwise, the "concat" metamethod is called (see <a href="#2.8">&sect;2.8</a>).
1078 <h3>2.5.5 - <a name="2.5.5">The Length Operator</a></h3>
1081 The length operator is denoted by the unary operator <code>#</code>.
1082 The length of a string is its number of bytes
1083 (that is, the usual meaning of string length when each
1084 character is one byte).
1088 The length of a table <code>t</code> is defined to be any
1089 integer index <code>n</code>
1090 such that <code>t[n]</code> is not <b>nil</b> and <code>t[n+1]</code> is <b>nil</b>;
1091 moreover, if <code>t[1]</code> is <b>nil</b>, <code>n</code> can be zero.
1092 For a regular array, with non-nil values from 1 to a given <code>n</code>,
1093 its length is exactly that <code>n</code>,
1094 the index of its last value.
1095 If the array has "holes"
1096 (that is, <b>nil</b> values between other non-nil values),
1097 then <code>#t</code> can be any of the indices that
1098 directly precedes a <b>nil</b> value
1099 (that is, it may consider any such <b>nil</b> value as the end of
1100 the array).
1106 <h3>2.5.6 - <a name="2.5.6">Precedence</a></h3><p>
1107 Operator precedence in Lua follows the table below,
1108 from lower to higher priority:
1110 <pre>
1113 &lt; &gt; &lt;= &gt;= ~= ==
1116 * / %
1117 not # - (unary)
1119 </pre><p>
1120 As usual,
1121 you can use parentheses to change the precedences of an expression.
1122 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
1123 operators are right associative.
1124 All other binary operators are left associative.
1130 <h3>2.5.7 - <a name="2.5.7">Table Constructors</a></h3><p>
1131 Table constructors are expressions that create tables.
1132 Every time a constructor is evaluated, a new table is created.
1133 A constructor can be used to create an empty table
1134 or to create a table and initialize some of its fields.
1135 The general syntax for constructors is
1137 <pre>
1138 tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
1139 fieldlist ::= field {fieldsep field} [fieldsep]
1140 field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
1141 fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
1142 </pre>
1145 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
1146 with key <code>exp1</code> and value <code>exp2</code>.
1147 A field of the form <code>name = exp</code> is equivalent to
1148 <code>["name"] = exp</code>.
1149 Finally, fields of the form <code>exp</code> are equivalent to
1150 <code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
1151 starting with 1.
1152 Fields in the other formats do not affect this counting.
1153 For example,
1155 <pre>
1156 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
1157 </pre><p>
1158 is equivalent to
1160 <pre>
1162 local t = {}
1163 t[f(1)] = g
1164 t[1] = "x" -- 1st exp
1165 t[2] = "y" -- 2nd exp
1166 t.x = 1 -- t["x"] = 1
1167 t[3] = f(x) -- 3rd exp
1168 t[30] = 23
1169 t[4] = 45 -- 4th exp
1170 a = t
1172 </pre>
1175 If the last field in the list has the form <code>exp</code>
1176 and the expression is a function call or a vararg expression,
1177 then all values returned by this expression enter the list consecutively
1178 (see <a href="#2.5.8">&sect;2.5.8</a>).
1179 To avoid this,
1180 enclose the function call or the vararg expression
1181 in parentheses (see <a href="#2.5">&sect;2.5</a>).
1185 The field list can have an optional trailing separator,
1186 as a convenience for machine-generated code.
1192 <h3>2.5.8 - <a name="2.5.8">Function Calls</a></h3><p>
1193 A function call in Lua has the following syntax:
1195 <pre>
1196 functioncall ::= prefixexp args
1197 </pre><p>
1198 In a function call,
1199 first prefixexp and args are evaluated.
1200 If the value of prefixexp has type <em>function</em>,
1201 then this function is called
1202 with the given arguments.
1203 Otherwise, the prefixexp "call" metamethod is called,
1204 having as first parameter the value of prefixexp,
1205 followed by the original call arguments
1206 (see <a href="#2.8">&sect;2.8</a>).
1210 The form
1212 <pre>
1213 functioncall ::= prefixexp `<b>:</b>&acute; Name args
1214 </pre><p>
1215 can be used to call "methods".
1216 A call <code>v:name(<em>args</em>)</code>
1217 is syntactic sugar for <code>,<em>args</em>)</code>,
1218 except that <code>v</code> is evaluated only once.
1222 Arguments have the following syntax:
1224 <pre>
1225 args ::= `<b>(</b>&acute; [explist] `<b>)</b>&acute;
1226 args ::= tableconstructor
1227 args ::= String
1228 </pre><p>
1229 All argument expressions are evaluated before the call.
1230 A call of the form <code>f{<em>fields</em>}</code> is
1231 syntactic sugar for <code>f({<em>fields</em>})</code>;
1232 that is, the argument list is a single new table.
1233 A call of the form <code>f'<em>string</em>'</code>
1234 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
1235 is syntactic sugar for <code>f('<em>string</em>')</code>;
1236 that is, the argument list is a single literal string.
1240 As an exception to the free-format syntax of Lua,
1241 you cannot put a line break before the '<code>(</code>' in a function call.
1242 This restriction avoids some ambiguities in the language.
1243 If you write
1245 <pre>
1246 a = f
1247 (g).x(a)
1248 </pre><p>
1249 Lua would see that as a single statement, <code>a = f(g).x(a)</code>.
1250 So, if you want two statements, you must add a semi-colon between them.
1251 If you actually want to call <code>f</code>,
1252 you must remove the line break before <code>(g)</code>.
1256 A call of the form <code>return</code> <em>functioncall</em> is called
1257 a <em>tail call</em>.
1258 Lua implements <em>proper tail calls</em>
1259 (or <em>proper tail recursion</em>):
1260 in a tail call,
1261 the called function reuses the stack entry of the calling function.
1262 Therefore, there is no limit on the number of nested tail calls that
1263 a program can execute.
1264 However, a tail call erases any debug information about the
1265 calling function.
1266 Note that a tail call only happens with a particular syntax,
1267 where the <b>return</b> has one single function call as argument;
1268 this syntax makes the calling function return exactly
1269 the returns of the called function.
1270 So, none of the following examples are tail calls:
1272 <pre>
1273 return (f(x)) -- results adjusted to 1
1274 return 2 * f(x)
1275 return x, f(x) -- additional results
1276 f(x); return -- results discarded
1277 return x or f(x) -- results adjusted to 1
1278 </pre>
1283 <h3>2.5.9 - <a name="2.5.9">Function Definitions</a></h3>
1286 The syntax for function definition is
1288 <pre>
1289 function ::= <b>function</b> funcbody
1290 funcbody ::= `<b>(</b>&acute; [parlist] `<b>)</b>&acute; block <b>end</b>
1291 </pre>
1294 The following syntactic sugar simplifies function definitions:
1296 <pre>
1297 stat ::= <b>function</b> funcname funcbody
1298 stat ::= <b>local</b> <b>function</b> Name funcbody
1299 funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
1300 </pre><p>
1301 The statement
1303 <pre>
1304 function f () <em>body</em> end
1305 </pre><p>
1306 translates to
1308 <pre>
1309 f = function () <em>body</em> end
1310 </pre><p>
1311 The statement
1313 <pre>
1314 function t.a.b.c.f () <em>body</em> end
1315 </pre><p>
1316 translates to
1318 <pre>
1319 t.a.b.c.f = function () <em>body</em> end
1320 </pre><p>
1321 The statement
1323 <pre>
1324 local function f () <em>body</em> end
1325 </pre><p>
1326 translates to
1328 <pre>
1329 local f; f = function () <em>body</em> end
1330 </pre><p>
1331 <em>not</em> to
1333 <pre>
1334 local f = function () <em>body</em> end
1335 </pre><p>
1336 (This only makes a difference when the body of the function
1337 contains references to <code>f</code>.)
1341 A function definition is an executable expression,
1342 whose value has type <em>function</em>.
1343 When Lua pre-compiles a chunk,
1344 all its function bodies are pre-compiled too.
1345 Then, whenever Lua executes the function definition,
1346 the function is <em>instantiated</em> (or <em>closed</em>).
1347 This function instance (or <em>closure</em>)
1348 is the final value of the expression.
1349 Different instances of the same function
1350 can refer to different external local variables
1351 and can have different environment tables.
1355 Parameters act as local variables that are
1356 initialized with the argument values:
1358 <pre>
1359 parlist ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
1360 </pre><p>
1361 When a function is called,
1362 the list of arguments is adjusted to
1363 the length of the list of parameters,
1364 unless the function is a variadic or <em>vararg function</em>,
1365 which is
1366 indicated by three dots ('<code>...</code>') at the end of its parameter list.
1367 A vararg function does not adjust its argument list;
1368 instead, it collects all extra arguments and supplies them
1369 to the function through a <em>vararg expression</em>,
1370 which is also written as three dots.
1371 The value of this expression is a list of all actual extra arguments,
1372 similar to a function with multiple results.
1373 If a vararg expression is used inside another expression
1374 or in the middle of a list of expressions,
1375 then its return list is adjusted to one element.
1376 If the expression is used as the last element of a list of expressions,
1377 then no adjustment is made
1378 (unless that last expression is enclosed in parentheses).
1382 As an example, consider the following definitions:
1384 <pre>
1385 function f(a, b) end
1386 function g(a, b, ...) end
1387 function r() return 1,2,3 end
1388 </pre><p>
1389 Then, we have the following mapping from arguments to parameters and
1390 to the vararg expression:
1392 <pre>
1395 f(3) a=3, b=nil
1396 f(3, 4) a=3, b=4
1397 f(3, 4, 5) a=3, b=4
1398 f(r(), 10) a=1, b=10
1399 f(r()) a=1, b=2
1401 g(3) a=3, b=nil, ... --&gt; (nothing)
1402 g(3, 4) a=3, b=4, ... --&gt; (nothing)
1403 g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
1404 g(5, r()) a=5, b=1, ... --&gt; 2 3
1405 </pre>
1408 Results are returned using the <b>return</b> statement (see <a href="#2.4.4">&sect;2.4.4</a>).
1409 If control reaches the end of a function
1410 without encountering a <b>return</b> statement,
1411 then the function returns with no results.
1415 The <em>colon</em> syntax
1416 is used for defining <em>methods</em>,
1417 that is, functions that have an implicit extra parameter <code>self</code>.
1418 Thus, the statement
1420 <pre>
1421 function t.a.b.c:f (<em>params</em>) <em>body</em> end
1422 </pre><p>
1423 is syntactic sugar for
1425 <pre>
1426 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
1427 </pre>
1434 <h2>2.6 - <a name="2.6">Visibility Rules</a></h2>
1438 Lua is a lexically scoped language.
1439 The scope of variables begins at the first statement <em>after</em>
1440 their declaration and lasts until the end of the innermost block that
1441 includes the declaration.
1442 Consider the following example:
1444 <pre>
1445 x = 10 -- global variable
1446 do -- new block
1447 local x = x -- new 'x', with value 10
1448 print(x) --&gt; 10
1449 x = x+1
1450 do -- another block
1451 local x = x+1 -- another 'x'
1452 print(x) --&gt; 12
1454 print(x) --&gt; 11
1456 print(x) --&gt; 10 (the global one)
1457 </pre>
1460 Notice that, in a declaration like <code>local x = x</code>,
1461 the new <code>x</code> being declared is not in scope yet,
1462 and so the second <code>x</code> refers to the outside variable.
1466 Because of the lexical scoping rules,
1467 local variables can be freely accessed by functions
1468 defined inside their scope.
1469 A local variable used by an inner function is called
1470 an <em>upvalue</em>, or <em>external local variable</em>,
1471 inside the inner function.
1475 Notice that each execution of a <b>local</b> statement
1476 defines new local variables.
1477 Consider the following example:
1479 <pre>
1480 a = {}
1481 local x = 20
1482 for i=1,10 do
1483 local y = 0
1484 a[i] = function () y=y+1; return x+y end
1486 </pre><p>
1487 The loop creates ten closures
1488 (that is, ten instances of the anonymous function).
1489 Each of these closures uses a different <code>y</code> variable,
1490 while all of them share the same <code>x</code>.
1496 <h2>2.7 - <a name="2.7">Error Handling</a></h2>
1499 Because Lua is an embedded extension language,
1500 all Lua actions start from C&nbsp;code in the host program
1501 calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
1502 Whenever an error occurs during Lua compilation or execution,
1503 control returns to C,
1504 which can take appropriate measures
1505 (such as printing an error message).
1509 Lua code can explicitly generate an error by calling the
1510 <a href="#pdf-error"><code>error</code></a> function.
1511 If you need to catch errors in Lua,
1512 you can use the <a href="#pdf-pcall"><code>pcall</code></a> function.
1518 <h2>2.8 - <a name="2.8">Metatables</a></h2>
1521 Every value in Lua can have a <em>metatable</em>.
1522 This <em>metatable</em> is an ordinary Lua table
1523 that defines the behavior of the original value
1524 under certain special operations.
1525 You can change several aspects of the behavior
1526 of operations over a value by setting specific fields in its metatable.
1527 For instance, when a non-numeric value is the operand of an addition,
1528 Lua checks for a function in the field <code>"__add"</code> in its metatable.
1529 If it finds one,
1530 Lua calls this function to perform the addition.
1534 We call the keys in a metatable <em>events</em>
1535 and the values <em>metamethods</em>.
1536 In the previous example, the event is <code>"add"</code>
1537 and the metamethod is the function that performs the addition.
1541 You can query the metatable of any value
1542 through the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
1546 You can replace the metatable of tables
1547 through the <a href="#pdf-setmetatable"><code>setmetatable</code></a>
1548 function.
1549 You cannot change the metatable of other types from Lua
1550 (except by using the debug library);
1551 you must use the C&nbsp;API for that.
1555 Tables and full userdata have individual metatables
1556 (although multiple tables and userdata can share their metatables).
1557 Values of all other types share one single metatable per type;
1558 that is, there is one single metatable for all numbers,
1559 one for all strings, etc.
1563 A metatable controls how an object behaves in arithmetic operations,
1564 order comparisons, concatenation, length operation, and indexing.
1565 A metatable also can define a function to be called when a userdata
1566 is garbage collected.
1567 For each of these operations Lua associates a specific key
1568 called an <em>event</em>.
1569 When Lua performs one of these operations over a value,
1570 it checks whether this value has a metatable with the corresponding event.
1571 If so, the value associated with that key (the metamethod)
1572 controls how Lua will perform the operation.
1576 Metatables control the operations listed next.
1577 Each operation is identified by its corresponding name.
1578 The key for each operation is a string with its name prefixed by
1579 two underscores, '<code>__</code>';
1580 for instance, the key for operation "add" is the
1581 string <code>"__add"</code>.
1582 The semantics of these operations is better explained by a Lua function
1583 describing how the interpreter executes the operation.
1587 The code shown here in Lua is only illustrative;
1588 the real behavior is hard coded in the interpreter
1589 and it is much more efficient than this simulation.
1590 All functions used in these descriptions
1591 (<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
1592 are described in <a href="#5.1">&sect;5.1</a>.
1593 In particular, to retrieve the metamethod of a given object,
1594 we use the expression
1596 <pre>
1597 metatable(obj)[event]
1598 </pre><p>
1599 This should be read as
1601 <pre>
1602 rawget(getmetatable(obj) or {}, event)
1603 </pre><p>
1605 That is, the access to a metamethod does not invoke other metamethods,
1606 and the access to objects with no metatables does not fail
1607 (it simply results in <b>nil</b>).
1611 <ul>
1613 <li><b>"add":</b>
1614 the <code>+</code> operation.
1619 The function <code>getbinhandler</code> below defines how Lua chooses a handler
1620 for a binary operation.
1621 First, Lua tries the first operand.
1622 If its type does not define a handler for the operation,
1623 then Lua tries the second operand.
1625 <pre>
1626 function getbinhandler (op1, op2, event)
1627 return metatable(op1)[event] or metatable(op2)[event]
1629 </pre><p>
1630 By using this function,
1631 the behavior of the <code>op1 + op2</code> is
1633 <pre>
1634 function add_event (op1, op2)
1635 local o1, o2 = tonumber(op1), tonumber(op2)
1636 if o1 and o2 then -- both operands are numeric?
1637 return o1 + o2 -- '+' here is the primitive 'add'
1638 else -- at least one of the operands is not numeric
1639 local h = getbinhandler(op1, op2, "__add")
1640 if h then
1641 -- call the handler with both operands
1642 return (h(op1, op2))
1643 else -- no handler available: default behavior
1644 error(&middot;&middot;&middot;)
1648 </pre><p>
1649 </li>
1651 <li><b>"sub":</b>
1652 the <code>-</code> operation.
1654 Behavior similar to the "add" operation.
1655 </li>
1657 <li><b>"mul":</b>
1658 the <code>*</code> operation.
1660 Behavior similar to the "add" operation.
1661 </li>
1663 <li><b>"div":</b>
1664 the <code>/</code> operation.
1666 Behavior similar to the "add" operation.
1667 </li>
1669 <li><b>"mod":</b>
1670 the <code>%</code> operation.
1672 Behavior similar to the "add" operation,
1673 with the operation
1674 <code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
1675 </li>
1677 <li><b>"pow":</b>
1678 the <code>^</code> (exponentiation) operation.
1680 Behavior similar to the "add" operation,
1681 with the function <code>pow</code> (from the C&nbsp;math library)
1682 as the primitive operation.
1683 </li>
1685 <li><b>"unm":</b>
1686 the unary <code>-</code> operation.
1689 <pre>
1690 function unm_event (op)
1691 local o = tonumber(op)
1692 if o then -- operand is numeric?
1693 return -o -- '-' here is the primitive 'unm'
1694 else -- the operand is not numeric.
1695 -- Try to get a handler from the operand
1696 local h = metatable(op).__unm
1697 if h then
1698 -- call the handler with the operand
1699 return (h(op))
1700 else -- no handler available: default behavior
1701 error(&middot;&middot;&middot;)
1705 </pre><p>
1706 </li>
1708 <li><b>"concat":</b>
1709 the <code>..</code> (concatenation) operation.
1712 <pre>
1713 function concat_event (op1, op2)
1714 if (type(op1) == "string" or type(op1) == "number") and
1715 (type(op2) == "string" or type(op2) == "number") then
1716 return op1 .. op2 -- primitive string concatenation
1717 else
1718 local h = getbinhandler(op1, op2, "__concat")
1719 if h then
1720 return (h(op1, op2))
1721 else
1722 error(&middot;&middot;&middot;)
1726 </pre><p>
1727 </li>
1729 <li><b>"len":</b>
1730 the <code>#</code> operation.
1733 <pre>
1734 function len_event (op)
1735 if type(op) == "string" then
1736 return strlen(op) -- primitive string length
1737 elseif type(op) == "table" then
1738 return #op -- primitive table length
1739 else
1740 local h = metatable(op).__len
1741 if h then
1742 -- call the handler with the operand
1743 return (h(op))
1744 else -- no handler available: default behavior
1745 error(&middot;&middot;&middot;)
1749 </pre><p>
1750 See <a href="#2.5.5">&sect;2.5.5</a> for a description of the length of a table.
1751 </li>
1753 <li><b>"eq":</b>
1754 the <code>==</code> operation.
1756 The function <code>getcomphandler</code> defines how Lua chooses a metamethod
1757 for comparison operators.
1758 A metamethod only is selected when both objects
1759 being compared have the same type
1760 and the same metamethod for the selected operation.
1762 <pre>
1763 function getcomphandler (op1, op2, event)
1764 if type(op1) ~= type(op2) then return nil end
1765 local mm1 = metatable(op1)[event]
1766 local mm2 = metatable(op2)[event]
1767 if mm1 == mm2 then return mm1 else return nil end
1769 </pre><p>
1770 The "eq" event is defined as follows:
1772 <pre>
1773 function eq_event (op1, op2)
1774 if type(op1) ~= type(op2) then -- different types?
1775 return false -- different objects
1777 if op1 == op2 then -- primitive equal?
1778 return true -- objects are equal
1780 -- try metamethod
1781 local h = getcomphandler(op1, op2, "__eq")
1782 if h then
1783 return (h(op1, op2))
1784 else
1785 return false
1788 </pre><p>
1789 <code>a ~= b</code> is equivalent to <code>not (a == b)</code>.
1790 </li>
1792 <li><b>"lt":</b>
1793 the <code>&lt;</code> operation.
1796 <pre>
1797 function lt_event (op1, op2)
1798 if type(op1) == "number" and type(op2) == "number" then
1799 return op1 &lt; op2 -- numeric comparison
1800 elseif type(op1) == "string" and type(op2) == "string" then
1801 return op1 &lt; op2 -- lexicographic comparison
1802 else
1803 local h = getcomphandler(op1, op2, "__lt")
1804 if h then
1805 return (h(op1, op2))
1806 else
1807 error(&middot;&middot;&middot;)
1811 </pre><p>
1812 <code>a &gt; b</code> is equivalent to <code>b &lt; a</code>.
1813 </li>
1815 <li><b>"le":</b>
1816 the <code>&lt;=</code> operation.
1819 <pre>
1820 function le_event (op1, op2)
1821 if type(op1) == "number" and type(op2) == "number" then
1822 return op1 &lt;= op2 -- numeric comparison
1823 elseif type(op1) == "string" and type(op2) == "string" then
1824 return op1 &lt;= op2 -- lexicographic comparison
1825 else
1826 local h = getcomphandler(op1, op2, "__le")
1827 if h then
1828 return (h(op1, op2))
1829 else
1830 h = getcomphandler(op1, op2, "__lt")
1831 if h then
1832 return not h(op2, op1)
1833 else
1834 error(&middot;&middot;&middot;)
1839 </pre><p>
1840 <code>a &gt;= b</code> is equivalent to <code>b &lt;= a</code>.
1841 Note that, in the absence of a "le" metamethod,
1842 Lua tries the "lt", assuming that <code>a &lt;= b</code> is
1843 equivalent to <code>not (b &lt; a)</code>.
1844 </li>
1846 <li><b>"index":</b>
1847 The indexing access <code>table[key]</code>.
1850 <pre>
1851 function gettable_event (table, key)
1852 local h
1853 if type(table) == "table" then
1854 local v = rawget(table, key)
1855 if v ~= nil then return v end
1856 h = metatable(table).__index
1857 if h == nil then return nil end
1858 else
1859 h = metatable(table).__index
1860 if h == nil then
1861 error(&middot;&middot;&middot;)
1864 if type(h) == "function" then
1865 return (h(table, key)) -- call the handler
1866 else return h[key] -- or repeat operation on it
1869 </pre><p>
1870 </li>
1872 <li><b>"newindex":</b>
1873 The indexing assignment <code>table[key] = value</code>.
1876 <pre>
1877 function settable_event (table, key, value)
1878 local h
1879 if type(table) == "table" then
1880 local v = rawget(table, key)
1881 if v ~= nil then rawset(table, key, value); return end
1882 h = metatable(table).__newindex
1883 if h == nil then rawset(table, key, value); return end
1884 else
1885 h = metatable(table).__newindex
1886 if h == nil then
1887 error(&middot;&middot;&middot;)
1890 if type(h) == "function" then
1891 h(table, key,value) -- call the handler
1892 else h[key] = value -- or repeat operation on it
1895 </pre><p>
1896 </li>
1898 <li><b>"call":</b>
1899 called when Lua calls a value.
1902 <pre>
1903 function function_event (func, ...)
1904 if type(func) == "function" then
1905 return func(...) -- primitive call
1906 else
1907 local h = metatable(func).__call
1908 if h then
1909 return h(func, ...)
1910 else
1911 error(&middot;&middot;&middot;)
1915 </pre><p>
1916 </li>
1918 </ul>
1923 <h2>2.9 - <a name="2.9">Environments</a></h2>
1926 Besides metatables,
1927 objects of types thread, function, and userdata
1928 have another table associated with them,
1929 called their <em>environment</em>.
1930 Like metatables, environments are regular tables and
1931 multiple objects can share the same environment.
1935 Threads are created sharing the environment of the creating thread.
1936 Userdata and C&nbsp;functions are created sharing the environment
1937 of the creating C&nbsp;function.
1938 Non-nested Lua functions
1939 (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>)
1940 are created sharing the environment of the creating thread.
1941 Nested Lua functions are created sharing the environment of
1942 the creating Lua function.
1946 Environments associated with userdata have no meaning for Lua.
1947 It is only a convenience feature for programmers to associate a table to
1948 a userdata.
1952 Environments associated with threads are called
1953 <em>global environments</em>.
1954 They are used as the default environment for threads and
1955 non-nested Lua functions created by the thread
1956 and can be directly accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1960 The environment associated with a C&nbsp;function can be directly
1961 accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1962 It is used as the default environment for other C&nbsp;functions
1963 and userdata created by the function.
1967 Environments associated with Lua functions are used to resolve
1968 all accesses to global variables within the function (see <a href="#2.3">&sect;2.3</a>).
1969 They are used as the default environment for nested Lua functions
1970 created by the function.
1974 You can change the environment of a Lua function or the
1975 running thread by calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
1976 You can get the environment of a Lua function or the running thread
1977 by calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
1978 To manipulate the environment of other objects
1979 (userdata, C&nbsp;functions, other threads) you must
1980 use the C&nbsp;API.
1986 <h2>2.10 - <a name="2.10">Garbage Collection</a></h2>
1989 Lua performs automatic memory management.
1990 This means that
1991 you have to worry neither about allocating memory for new objects
1992 nor about freeing it when the objects are no longer needed.
1993 Lua manages memory automatically by running
1994 a <em>garbage collector</em> from time to time
1995 to collect all <em>dead objects</em>
1996 (that is, objects that are no longer accessible from Lua).
1997 All memory used by Lua is subject to automatic management:
1998 tables, userdata, functions, threads, strings, etc.
2002 Lua implements an incremental mark-and-sweep collector.
2003 It uses two numbers to control its garbage-collection cycles:
2004 the <em>garbage-collector pause</em> and
2005 the <em>garbage-collector step multiplier</em>.
2006 Both use percentage points as units
2007 (so that a value of 100 means an internal value of 1).
2011 The garbage-collector pause
2012 controls how long the collector waits before starting a new cycle.
2013 Larger values make the collector less aggressive.
2014 Values smaller than 100 mean the collector will not wait to
2015 start a new cycle.
2016 A value of 200 means that the collector waits for the total memory in use
2017 to double before starting a new cycle.
2021 The step multiplier
2022 controls the relative speed of the collector relative to
2023 memory allocation.
2024 Larger values make the collector more aggressive but also increase
2025 the size of each incremental step.
2026 Values smaller than 100 make the collector too slow and
2027 can result in the collector never finishing a cycle.
2028 The default, 200, means that the collector runs at "twice"
2029 the speed of memory allocation.
2033 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
2034 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
2035 With these functions you can also control
2036 the collector directly (e.g., stop and restart it).
2040 <h3>2.10.1 - <a name="2.10.1">Garbage-Collection Metamethods</a></h3>
2043 Using the C&nbsp;API,
2044 you can set garbage-collector metamethods for userdata (see <a href="#2.8">&sect;2.8</a>).
2045 These metamethods are also called <em>finalizers</em>.
2046 Finalizers allow you to coordinate Lua's garbage collection
2047 with external resource management
2048 (such as closing files, network or database connections,
2049 or freeing your own memory).
2053 Garbage userdata with a field <code>__gc</code> in their metatables are not
2054 collected immediately by the garbage collector.
2055 Instead, Lua puts them in a list.
2056 After the collection,
2057 Lua does the equivalent of the following function
2058 for each userdata in that list:
2060 <pre>
2061 function gc_event (udata)
2062 local h = metatable(udata).__gc
2063 if h then
2064 h(udata)
2067 </pre>
2070 At the end of each garbage-collection cycle,
2071 the finalizers for userdata are called in <em>reverse</em>
2072 order of their creation,
2073 among those collected in that cycle.
2074 That is, the first finalizer to be called is the one associated
2075 with the userdata created last in the program.
2076 The userdata itself is freed only in the next garbage-collection cycle.
2082 <h3>2.10.2 - <a name="2.10.2">Weak Tables</a></h3>
2085 A <em>weak table</em> is a table whose elements are
2086 <em>weak references</em>.
2087 A weak reference is ignored by the garbage collector.
2088 In other words,
2089 if the only references to an object are weak references,
2090 then the garbage collector will collect this object.
2094 A weak table can have weak keys, weak values, or both.
2095 A table with weak keys allows the collection of its keys,
2096 but prevents the collection of its values.
2097 A table with both weak keys and weak values allows the collection of
2098 both keys and values.
2099 In any case, if either the key or the value is collected,
2100 the whole pair is removed from the table.
2101 The weakness of a table is controlled by the
2102 <code>__mode</code> field of its metatable.
2103 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
2104 the keys in the table are weak.
2105 If <code>__mode</code> contains '<code>v</code>',
2106 the values in the table are weak.
2110 After you use a table as a metatable,
2111 you should not change the value of its <code>__mode</code> field.
2112 Otherwise, the weak behavior of the tables controlled by this
2113 metatable is undefined.
2121 <h2>2.11 - <a name="2.11">Coroutines</a></h2>
2124 Lua supports coroutines,
2125 also called <em>collaborative multithreading</em>.
2126 A coroutine in Lua represents an independent thread of execution.
2127 Unlike threads in multithread systems, however,
2128 a coroutine only suspends its execution by explicitly calling
2129 a yield function.
2133 You create a coroutine with a call to <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
2134 Its sole argument is a function
2135 that is the main function of the coroutine.
2136 The <code>create</code> function only creates a new coroutine and
2137 returns a handle to it (an object of type <em>thread</em>);
2138 it does not start the coroutine execution.
2142 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2143 passing as its first argument
2144 a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2145 the coroutine starts its execution,
2146 at the first line of its main function.
2147 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
2148 to the coroutine main function.
2149 After the coroutine starts running,
2150 it runs until it terminates or <em>yields</em>.
2154 A coroutine can terminate its execution in two ways:
2155 normally, when its main function returns
2156 (explicitly or implicitly, after the last instruction);
2157 and abnormally, if there is an unprotected error.
2158 In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
2159 plus any values returned by the coroutine main function.
2160 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
2161 plus an error message.
2165 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2166 When a coroutine yields,
2167 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
2168 even if the yield happens inside nested function calls
2169 (that is, not in the main function,
2170 but in a function directly or indirectly called by the main function).
2171 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
2172 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2173 The next time you resume the same coroutine,
2174 it continues its execution from the point where it yielded,
2175 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
2176 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2180 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2181 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
2182 but instead of returning the coroutine itself,
2183 it returns a function that, when called, resumes the coroutine.
2184 Any arguments passed to this function
2185 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2186 <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>,
2187 except the first one (the boolean error code).
2188 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2189 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
2190 any error is propagated to the caller.
2194 As an example,
2195 consider the following code:
2197 <pre>
2198 function foo (a)
2199 print("foo", a)
2200 return coroutine.yield(2*a)
2203 co = coroutine.create(function (a,b)
2204 print("co-body", a, b)
2205 local r = foo(a+1)
2206 print("co-body", r)
2207 local r, s = coroutine.yield(a+b, a-b)
2208 print("co-body", r, s)
2209 return b, "end"
2210 end)
2212 print("main", coroutine.resume(co, 1, 10))
2213 print("main", coroutine.resume(co, "r"))
2214 print("main", coroutine.resume(co, "x", "y"))
2215 print("main", coroutine.resume(co, "x", "y"))
2216 </pre><p>
2217 When you run it, it produces the following output:
2219 <pre>
2220 co-body 1 10
2221 foo 2
2223 main true 4
2224 co-body r
2225 main true 11 -9
2226 co-body x y
2227 main true 10 end
2228 main false cannot resume dead coroutine
2229 </pre>
2234 <h1>3 - <a name="3">The Application Program Interface</a></h1>
2238 This section describes the C&nbsp;API for Lua, that is,
2239 the set of C&nbsp;functions available to the host program to communicate
2240 with Lua.
2241 All API functions and related types and constants
2242 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2246 Even when we use the term "function",
2247 any facility in the API may be provided as a macro instead.
2248 All such macros use each of their arguments exactly once
2249 (except for the first argument, which is always a Lua state),
2250 and so do not generate any hidden side-effects.
2254 As in most C&nbsp;libraries,
2255 the Lua API functions do not check their arguments for validity or consistency.
2256 However, you can change this behavior by compiling Lua
2257 with a proper definition for the macro <a name="pdf-luai_apicheck"><code>luai_apicheck</code></a>,
2258 in file <code>luaconf.h</code>.
2262 <h2>3.1 - <a name="3.1">The Stack</a></h2>
2265 Lua uses a <em>virtual stack</em> to pass values to and from C.
2266 Each element in this stack represents a Lua value
2267 (<b>nil</b>, number, string, etc.).
2271 Whenever Lua calls C, the called function gets a new stack,
2272 which is independent of previous stacks and of stacks of
2273 C&nbsp;functions that are still active.
2274 This stack initially contains any arguments to the C&nbsp;function
2275 and it is where the C&nbsp;function pushes its results
2276 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2280 For convenience,
2281 most query operations in the API do not follow a strict stack discipline.
2282 Instead, they can refer to any element in the stack
2283 by using an <em>index</em>:
2284 A positive index represents an <em>absolute</em> stack position
2285 (starting at&nbsp;1);
2286 a negative index represents an <em>offset</em> relative to the top of the stack.
2287 More specifically, if the stack has <em>n</em> elements,
2288 then index&nbsp;1 represents the first element
2289 (that is, the element that was pushed onto the stack first)
2291 index&nbsp;<em>n</em> represents the last element;
2292 index&nbsp;-1 also represents the last element
2293 (that is, the element at the&nbsp;top)
2294 and index <em>-n</em> represents the first element.
2295 We say that an index is <em>valid</em>
2296 if it lies between&nbsp;1 and the stack top
2297 (that is, if <code>1 &le; abs(index) &le; top</code>).
2304 <h2>3.2 - <a name="3.2">Stack Size</a></h2>
2307 When you interact with Lua API,
2308 you are responsible for ensuring consistency.
2309 In particular,
2310 <em>you are responsible for controlling stack overflow</em>.
2311 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2312 to grow the stack size.
2316 Whenever Lua calls C,
2317 it ensures that at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> stack positions are available.
2318 <code>LUA_MINSTACK</code> is defined as 20,
2319 so that usually you do not have to worry about stack space
2320 unless your code has loops pushing elements onto the stack.
2324 Most query functions accept as indices any value inside the
2325 available stack space, that is, indices up to the maximum stack size
2326 you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2327 Such indices are called <em>acceptable indices</em>.
2328 More formally, we define an <em>acceptable index</em>
2329 as follows:
2331 <pre>
2332 (index &lt; 0 &amp;&amp; abs(index) &lt;= top) ||
2333 (index &gt; 0 &amp;&amp; index &lt;= stackspace)
2334 </pre><p>
2335 Note that 0 is never an acceptable index.
2341 <h2>3.3 - <a name="3.3">Pseudo-Indices</a></h2>
2344 Unless otherwise noted,
2345 any function that accepts valid indices can also be called with
2346 <em>pseudo-indices</em>,
2347 which represent some Lua values that are accessible to C&nbsp;code
2348 but which are not in the stack.
2349 Pseudo-indices are used to access the thread environment,
2350 the function environment,
2351 the registry,
2352 and the upvalues of a C&nbsp;function (see <a href="#3.4">&sect;3.4</a>).
2356 The thread environment (where global variables live) is
2357 always at pseudo-index <a name="pdf-LUA_GLOBALSINDEX"><code>LUA_GLOBALSINDEX</code></a>.
2358 The environment of the running C&nbsp;function is always
2359 at pseudo-index <a name="pdf-LUA_ENVIRONINDEX"><code>LUA_ENVIRONINDEX</code></a>.
2363 To access and change the value of global variables,
2364 you can use regular table operations over an environment table.
2365 For instance, to access the value of a global variable, do
2367 <pre>
2368 lua_getfield(L, LUA_GLOBALSINDEX, varname);
2369 </pre>
2374 <h2>3.4 - <a name="3.4">C Closures</a></h2>
2377 When a C&nbsp;function is created,
2378 it is possible to associate some values with it,
2379 thus creating a <em>C&nbsp;closure</em>;
2380 these values are called <em>upvalues</em> and are
2381 accessible to the function whenever it is called
2382 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
2386 Whenever a C&nbsp;function is called,
2387 its upvalues are located at specific pseudo-indices.
2388 These pseudo-indices are produced by the macro
2389 <a name="lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2390 The first value associated with a function is at position
2391 <code>lua_upvalueindex(1)</code>, and so on.
2392 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2393 where <em>n</em> is greater than the number of upvalues of the
2394 current function (but not greater than 256),
2395 produces an acceptable (but invalid) index.
2401 <h2>3.5 - <a name="3.5">Registry</a></h2>
2404 Lua provides a <em>registry</em>,
2405 a pre-defined table that can be used by any C&nbsp;code to
2406 store whatever Lua value it needs to store.
2407 This table is always located at pseudo-index
2408 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
2409 Any C&nbsp;library can store data into this table,
2410 but it should take care to choose keys different from those used
2411 by other libraries, to avoid collisions.
2412 Typically, you should use as key a string containing your library name
2413 or a light userdata with the address of a C&nbsp;object in your code.
2417 The integer keys in the registry are used by the reference mechanism,
2418 implemented by the auxiliary library,
2419 and therefore should not be used for other purposes.
2425 <h2>3.6 - <a name="3.6">Error Handling in C</a></h2>
2428 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2429 (You can also choose to use exceptions if you use C++;
2430 see file <code>luaconf.h</code>.)
2431 When Lua faces any error
2432 (such as memory allocation errors, type errors, syntax errors,
2433 and runtime errors)
2434 it <em>raises</em> an error;
2435 that is, it does a long jump.
2436 A <em>protected environment</em> uses <code>setjmp</code>
2437 to set a recover point;
2438 any error jumps to the most recent active recover point.
2442 Most functions in the API can throw an error,
2443 for instance due to a memory allocation error.
2444 The documentation for each function indicates whether
2445 it can throw errors.
2449 Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2455 <h2>3.7 - <a name="3.7">Functions and Types</a></h2>
2458 Here we list all functions and types from the C&nbsp;API in
2459 alphabetical order.
2460 Each function has an indicator like this:
2461 <span class="apii">[-o, +p, <em>x</em>]</span>
2465 The first field, <code>o</code>,
2466 is how many elements the function pops from the stack.
2467 The second field, <code>p</code>,
2468 is how many elements the function pushes onto the stack.
2469 (Any function always pushes its results after popping its arguments.)
2470 A field in the form <code>x|y</code> means the function can push (or pop)
2471 <code>x</code> or <code>y</code> elements,
2472 depending on the situation;
2473 an interrogation mark '<code>?</code>' means that
2474 we cannot know how many elements the function pops/pushes
2475 by looking only at its arguments
2476 (e.g., they may depend on what is on the stack).
2477 The third field, <code>x</code>,
2478 tells whether the function may throw errors:
2479 '<code>-</code>' means the function never throws any error;
2480 '<code>m</code>' means the function may throw an error
2481 only due to not enough memory;
2482 '<code>e</code>' means the function may throw other kinds of errors;
2483 '<code>v</code>' means the function may throw an error on purpose.
2487 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2488 <pre>typedef void * (*lua_Alloc) (void *ud,
2489 void *ptr,
2490 size_t osize,
2491 size_t nsize);</pre>
2494 The type of the memory-allocation function used by Lua states.
2495 The allocator function must provide a
2496 functionality similar to <code>realloc</code>,
2497 but not exactly the same.
2498 Its arguments are
2499 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2500 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2501 <code>osize</code>, the original size of the block;
2502 <code>nsize</code>, the new size of the block.
2503 <code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
2504 When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
2505 if <code>osize</code> is not zero,
2506 it should free the block pointed to by <code>ptr</code>.
2507 When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
2508 if and only if it cannot fill the request.
2509 When <code>nsize</code> is not zero and <code>osize</code> is zero,
2510 the allocator should behave like <code>malloc</code>.
2511 When <code>nsize</code> and <code>osize</code> are not zero,
2512 the allocator behaves like <code>realloc</code>.
2513 Lua assumes that the allocator never fails when
2514 <code>osize &gt;= nsize</code>.
2518 Here is a simple implementation for the allocator function.
2519 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2521 <pre>
2522 static void *l_alloc (void *ud, void *ptr, size_t osize,
2523 size_t nsize) {
2524 (void)ud; (void)osize; /* not used */
2525 if (nsize == 0) {
2526 free(ptr);
2527 return NULL;
2529 else
2530 return realloc(ptr, nsize);
2532 </pre><p>
2533 This code assumes
2534 that <code>free(NULL)</code> has no effect and that
2535 <code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2536 ANSI&nbsp;C ensures both behaviors.
2542 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
2543 <span class="apii">[-0, +0, <em>-</em>]</span>
2544 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2547 Sets a new panic function and returns the old one.
2551 If an error happens outside any protected environment,
2552 Lua calls a <em>panic function</em>
2553 and then calls <code>exit(EXIT_FAILURE)</code>,
2554 thus exiting the host application.
2555 Your panic function can avoid this exit by
2556 never returning (e.g., doing a long jump).
2560 The panic function can access the error message at the top of the stack.
2566 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
2567 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
2568 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
2571 Calls a function.
2575 To call a function you must use the following protocol:
2576 first, the function to be called is pushed onto the stack;
2577 then, the arguments to the function are pushed
2578 in direct order;
2579 that is, the first argument is pushed first.
2580 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
2581 <code>nargs</code> is the number of arguments that you pushed onto the stack.
2582 All arguments and the function value are popped from the stack
2583 when the function is called.
2584 The function results are pushed onto the stack when the function returns.
2585 The number of results is adjusted to <code>nresults</code>,
2586 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
2587 In this case, <em>all</em> results from the function are pushed.
2588 Lua takes care that the returned values fit into the stack space.
2589 The function results are pushed onto the stack in direct order
2590 (the first result is pushed first),
2591 so that after the call the last result is on the top of the stack.
2595 Any error inside the called function is propagated upwards
2596 (with a <code>longjmp</code>).
2600 The following example shows how the host program can do the
2601 equivalent to this Lua code:
2603 <pre>
2604 a = f("how", t.x, 14)
2605 </pre><p>
2606 Here it is in&nbsp;C:
2608 <pre>
2609 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
2610 lua_pushstring(L, "how"); /* 1st argument */
2611 lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */
2612 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
2613 lua_remove(L, -2); /* remove 't' from the stack */
2614 lua_pushinteger(L, 14); /* 3rd argument */
2615 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
2616 lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global 'a' */
2617 </pre><p>
2618 Note that the code above is "balanced":
2619 at its end, the stack is back to its original configuration.
2620 This is considered good programming practice.
2626 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
2627 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
2630 Type for C&nbsp;functions.
2634 In order to communicate properly with Lua,
2635 a C&nbsp;function must use the following protocol,
2636 which defines the way parameters and results are passed:
2637 a C&nbsp;function receives its arguments from Lua in its stack
2638 in direct order (the first argument is pushed first).
2639 So, when the function starts,
2640 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
2641 The first argument (if any) is at index 1
2642 and its last argument is at index <code>lua_gettop(L)</code>.
2643 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
2644 in direct order (the first result is pushed first),
2645 and returns the number of results.
2646 Any other value in the stack below the results will be properly
2647 discarded by Lua.
2648 Like a Lua function, a C&nbsp;function called by Lua can also return
2649 many results.
2653 As an example, the following function receives a variable number
2654 of numerical arguments and returns their average and sum:
2656 <pre>
2657 static int foo (lua_State *L) {
2658 int n = lua_gettop(L); /* number of arguments */
2659 lua_Number sum = 0;
2660 int i;
2661 for (i = 1; i &lt;= n; i++) {
2662 if (!lua_isnumber(L, i)) {
2663 lua_pushstring(L, "incorrect argument");
2664 lua_error(L);
2666 sum += lua_tonumber(L, i);
2668 lua_pushnumber(L, sum/n); /* first result */
2669 lua_pushnumber(L, sum); /* second result */
2670 return 2; /* number of results */
2672 </pre>
2677 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
2678 <span class="apii">[-0, +0, <em>m</em>]</span>
2679 <pre>int lua_checkstack (lua_State *L, int extra);</pre>
2682 Ensures that there are at least <code>extra</code> free stack slots in the stack.
2683 It returns false if it cannot grow the stack to that size.
2684 This function never shrinks the stack;
2685 if the stack is already larger than the new size,
2686 it is left unchanged.
2692 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
2693 <span class="apii">[-0, +0, <em>-</em>]</span>
2694 <pre>void lua_close (lua_State *L);</pre>
2697 Destroys all objects in the given Lua state
2698 (calling the corresponding garbage-collection metamethods, if any)
2699 and frees all dynamic memory used by this state.
2700 On several platforms, you may not need to call this function,
2701 because all resources are naturally released when the host program ends.
2702 On the other hand, long-running programs,
2703 such as a daemon or a web server,
2704 might need to release states as soon as they are not needed,
2705 to avoid growing too large.
2711 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
2712 <span class="apii">[-n, +1, <em>e</em>]</span>
2713 <pre>void lua_concat (lua_State *L, int n);</pre>
2716 Concatenates the <code>n</code> values at the top of the stack,
2717 pops them, and leaves the result at the top.
2718 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
2719 (that is, the function does nothing);
2720 if <code>n</code> is 0, the result is the empty string.
2721 Concatenation is performed following the usual semantics of Lua
2722 (see <a href="#2.5.4">&sect;2.5.4</a>).
2728 <hr><h3><a name="lua_cpcall"><code>lua_cpcall</code></a></h3><p>
2729 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
2730 <pre>int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);</pre>
2733 Calls the C&nbsp;function <code>func</code> in protected mode.
2734 <code>func</code> starts with only one element in its stack,
2735 a light userdata containing <code>ud</code>.
2736 In case of errors,
2737 <a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
2738 plus the error object on the top of the stack;
2739 otherwise, it returns zero, and does not change the stack.
2740 All values returned by <code>func</code> are discarded.
2746 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
2747 <span class="apii">[-0, +1, <em>m</em>]</span>
2748 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
2751 Creates a new empty table and pushes it onto the stack.
2752 The new table has space pre-allocated
2753 for <code>narr</code> array elements and <code>nrec</code> non-array elements.
2754 This pre-allocation is useful when you know exactly how many elements
2755 the table will have.
2756 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
2762 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
2763 <span class="apii">[-0, +0, <em>m</em>]</span>
2764 <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
2767 Dumps a function as a binary chunk.
2768 Receives a Lua function on the top of the stack
2769 and produces a binary chunk that,
2770 if loaded again,
2771 results in a function equivalent to the one dumped.
2772 As it produces parts of the chunk,
2773 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
2774 with the given <code>data</code>
2775 to write them.
2779 The value returned is the error code returned by the last
2780 call to the writer;
2781 0&nbsp;means no errors.
2785 This function does not pop the Lua function from the stack.
2791 <hr><h3><a name="lua_equal"><code>lua_equal</code></a></h3><p>
2792 <span class="apii">[-0, +0, <em>e</em>]</span>
2793 <pre>int lua_equal (lua_State *L, int index1, int index2);</pre>
2796 Returns 1 if the two values in acceptable indices <code>index1</code> and
2797 <code>index2</code> are equal,
2798 following the semantics of the Lua <code>==</code> operator
2799 (that is, may call metamethods).
2800 Otherwise returns&nbsp;0.
2801 Also returns&nbsp;0 if any of the indices is non valid.
2807 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
2808 <span class="apii">[-1, +0, <em>v</em>]</span>
2809 <pre>int lua_error (lua_State *L);</pre>
2812 Generates a Lua error.
2813 The error message (which can actually be a Lua value of any type)
2814 must be on the stack top.
2815 This function does a long jump,
2816 and therefore never returns.
2817 (see <a href="#luaL_error"><code>luaL_error</code></a>).
2823 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
2824 <span class="apii">[-0, +0, <em>e</em>]</span>
2825 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
2828 Controls the garbage collector.
2832 This function performs several tasks,
2833 according to the value of the parameter <code>what</code>:
2835 <ul>
2837 <li><b><code>LUA_GCSTOP</code>:</b>
2838 stops the garbage collector.
2839 </li>
2841 <li><b><code>LUA_GCRESTART</code>:</b>
2842 restarts the garbage collector.
2843 </li>
2845 <li><b><code>LUA_GCCOLLECT</code>:</b>
2846 performs a full garbage-collection cycle.
2847 </li>
2849 <li><b><code>LUA_GCCOUNT</code>:</b>
2850 returns the current amount of memory (in Kbytes) in use by Lua.
2851 </li>
2853 <li><b><code>LUA_GCCOUNTB</code>:</b>
2854 returns the remainder of dividing the current amount of bytes of
2855 memory in use by Lua by 1024.
2856 </li>
2858 <li><b><code>LUA_GCSTEP</code>:</b>
2859 performs an incremental step of garbage collection.
2860 The step "size" is controlled by <code>data</code>
2861 (larger values mean more steps) in a non-specified way.
2862 If you want to control the step size
2863 you must experimentally tune the value of <code>data</code>.
2864 The function returns 1 if the step finished a
2865 garbage-collection cycle.
2866 </li>
2868 <li><b><code>LUA_GCSETPAUSE</code>:</b>
2869 sets <code>data</code> as the new value
2870 for the <em>pause</em> of the collector (see <a href="#2.10">&sect;2.10</a>).
2871 The function returns the previous value of the pause.
2872 </li>
2874 <li><b><code>LUA_GCSETSTEPMUL</code>:</b>
2875 sets <code>data</code> as the new value for the <em>step multiplier</em> of
2876 the collector (see <a href="#2.10">&sect;2.10</a>).
2877 The function returns the previous value of the step multiplier.
2878 </li>
2880 </ul>
2885 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
2886 <span class="apii">[-0, +0, <em>-</em>]</span>
2887 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
2890 Returns the memory-allocation function of a given state.
2891 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
2892 opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
2898 <hr><h3><a name="lua_getfenv"><code>lua_getfenv</code></a></h3><p>
2899 <span class="apii">[-0, +1, <em>-</em>]</span>
2900 <pre>void lua_getfenv (lua_State *L, int index);</pre>
2903 Pushes onto the stack the environment table of
2904 the value at the given index.
2910 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
2911 <span class="apii">[-0, +1, <em>e</em>]</span>
2912 <pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
2915 Pushes onto the stack the value <code>t[k]</code>,
2916 where <code>t</code> is the value at the given valid index.
2917 As in Lua, this function may trigger a metamethod
2918 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2924 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
2925 <span class="apii">[-0, +1, <em>e</em>]</span>
2926 <pre>void lua_getglobal (lua_State *L, const char *name);</pre>
2929 Pushes onto the stack the value of the global <code>name</code>.
2930 It is defined as a macro:
2932 <pre>
2933 #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
2934 </pre>
2939 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
2940 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
2941 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
2944 Pushes onto the stack the metatable of the value at the given
2945 acceptable index.
2946 If the index is not valid,
2947 or if the value does not have a metatable,
2948 the function returns&nbsp;0 and pushes nothing on the stack.
2954 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
2955 <span class="apii">[-1, +1, <em>e</em>]</span>
2956 <pre>void lua_gettable (lua_State *L, int index);</pre>
2959 Pushes onto the stack the value <code>t[k]</code>,
2960 where <code>t</code> is the value at the given valid index
2961 and <code>k</code> is the value at the top of the stack.
2965 This function pops the key from the stack
2966 (putting the resulting value in its place).
2967 As in Lua, this function may trigger a metamethod
2968 for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2974 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
2975 <span class="apii">[-0, +0, <em>-</em>]</span>
2976 <pre>int lua_gettop (lua_State *L);</pre>
2979 Returns the index of the top element in the stack.
2980 Because indices start at&nbsp;1,
2981 this result is equal to the number of elements in the stack
2982 (and so 0&nbsp;means an empty stack).
2988 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
2989 <span class="apii">[-1, +1, <em>-</em>]</span>
2990 <pre>void lua_insert (lua_State *L, int index);</pre>
2993 Moves the top element into the given valid index,
2994 shifting up the elements above this index to open space.
2995 Cannot be called with a pseudo-index,
2996 because a pseudo-index is not an actual stack position.
3002 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3003 <pre>typedef ptrdiff_t lua_Integer;</pre>
3006 The type used by the Lua API to represent integral values.
3010 By default it is a <code>ptrdiff_t</code>,
3011 which is usually the largest signed integral type the machine handles
3012 "comfortably".
3018 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3019 <span class="apii">[-0, +0, <em>-</em>]</span>
3020 <pre>int lua_isboolean (lua_State *L, int index);</pre>
3023 Returns 1 if the value at the given acceptable index has type boolean,
3024 and 0&nbsp;otherwise.
3030 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3031 <span class="apii">[-0, +0, <em>-</em>]</span>
3032 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
3035 Returns 1 if the value at the given acceptable index is a C&nbsp;function,
3036 and 0&nbsp;otherwise.
3042 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3043 <span class="apii">[-0, +0, <em>-</em>]</span>
3044 <pre>int lua_isfunction (lua_State *L, int index);</pre>
3047 Returns 1 if the value at the given acceptable index is a function
3048 (either C or Lua), and 0&nbsp;otherwise.
3054 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3055 <span class="apii">[-0, +0, <em>-</em>]</span>
3056 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3059 Returns 1 if the value at the given acceptable index is a light userdata,
3060 and 0&nbsp;otherwise.
3066 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3067 <span class="apii">[-0, +0, <em>-</em>]</span>
3068 <pre>int lua_isnil (lua_State *L, int index);</pre>
3071 Returns 1 if the value at the given acceptable index is <b>nil</b>,
3072 and 0&nbsp;otherwise.
3078 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3079 <span class="apii">[-0, +0, <em>-</em>]</span>
3080 <pre>int lua_isnone (lua_State *L, int index);</pre>
3083 Returns 1 if the given acceptable index is not valid
3084 (that is, it refers to an element outside the current stack),
3085 and 0&nbsp;otherwise.
3091 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3092 <span class="apii">[-0, +0, <em>-</em>]</span>
3093 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3096 Returns 1 if the given acceptable index is not valid
3097 (that is, it refers to an element outside the current stack)
3098 or if the value at this index is <b>nil</b>,
3099 and 0&nbsp;otherwise.
3105 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3106 <span class="apii">[-0, +0, <em>-</em>]</span>
3107 <pre>int lua_isnumber (lua_State *L, int index);</pre>
3110 Returns 1 if the value at the given acceptable index is a number
3111 or a string convertible to a number,
3112 and 0&nbsp;otherwise.
3118 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3119 <span class="apii">[-0, +0, <em>-</em>]</span>
3120 <pre>int lua_isstring (lua_State *L, int index);</pre>
3123 Returns 1 if the value at the given acceptable index is a string
3124 or a number (which is always convertible to a string),
3125 and 0&nbsp;otherwise.
3131 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3132 <span class="apii">[-0, +0, <em>-</em>]</span>
3133 <pre>int lua_istable (lua_State *L, int index);</pre>
3136 Returns 1 if the value at the given acceptable index is a table,
3137 and 0&nbsp;otherwise.
3143 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3144 <span class="apii">[-0, +0, <em>-</em>]</span>
3145 <pre>int lua_isthread (lua_State *L, int index);</pre>
3148 Returns 1 if the value at the given acceptable index is a thread,
3149 and 0&nbsp;otherwise.
3155 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3156 <span class="apii">[-0, +0, <em>-</em>]</span>
3157 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
3160 Returns 1 if the value at the given acceptable index is a userdata
3161 (either full or light), and 0&nbsp;otherwise.
3167 <hr><h3><a name="lua_lessthan"><code>lua_lessthan</code></a></h3><p>
3168 <span class="apii">[-0, +0, <em>e</em>]</span>
3169 <pre>int lua_lessthan (lua_State *L, int index1, int index2);</pre>
3172 Returns 1 if the value at acceptable index <code>index1</code> is smaller
3173 than the value at acceptable index <code>index2</code>,
3174 following the semantics of the Lua <code>&lt;</code> operator
3175 (that is, may call metamethods).
3176 Otherwise returns&nbsp;0.
3177 Also returns&nbsp;0 if any of the indices is non valid.
3183 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3184 <span class="apii">[-0, +1, <em>-</em>]</span>
3185 <pre>int lua_load (lua_State *L,
3186 lua_Reader reader,
3187 void *data,
3188 const char *chunkname);</pre>
3191 Loads a Lua chunk.
3192 If there are no errors,
3193 <a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
3194 function on top of the stack.
3195 Otherwise, it pushes an error message.
3196 The return values of <a href="#lua_load"><code>lua_load</code></a> are:
3198 <ul>
3200 <li><b>0:</b> no errors;</li>
3202 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
3203 syntax error during pre-compilation;</li>
3205 <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3206 memory allocation error.</li>
3208 </ul>
3211 This function only loads a chunk;
3212 it does not run it.
3216 <a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
3217 and loads it accordingly (see program <code>luac</code>).
3221 The <a href="#lua_load"><code>lua_load</code></a> function uses a user-supplied <code>reader</code> function
3222 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3223 The <code>data</code> argument is an opaque value passed to the reader function.
3227 The <code>chunkname</code> argument gives a name to the chunk,
3228 which is used for error messages and in debug information (see <a href="#3.8">&sect;3.8</a>).
3234 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3235 <span class="apii">[-0, +0, <em>-</em>]</span>
3236 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3239 Creates a new, independent state.
3240 Returns <code>NULL</code> if cannot create the state
3241 (due to lack of memory).
3242 The argument <code>f</code> is the allocator function;
3243 Lua does all memory allocation for this state through this function.
3244 The second argument, <code>ud</code>, is an opaque pointer that Lua
3245 simply passes to the allocator in every call.
3251 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
3252 <span class="apii">[-0, +1, <em>m</em>]</span>
3253 <pre>void lua_newtable (lua_State *L);</pre>
3256 Creates a new empty table and pushes it onto the stack.
3257 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3263 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
3264 <span class="apii">[-0, +1, <em>m</em>]</span>
3265 <pre>lua_State *lua_newthread (lua_State *L);</pre>
3268 Creates a new thread, pushes it on the stack,
3269 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3270 The new state returned by this function shares with the original state
3271 all global objects (such as tables),
3272 but has an independent execution stack.
3276 There is no explicit function to close or to destroy a thread.
3277 Threads are subject to garbage collection,
3278 like any Lua object.
3284 <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
3285 <span class="apii">[-0, +1, <em>m</em>]</span>
3286 <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3289 This function allocates a new block of memory with the given size,
3290 pushes onto the stack a new full userdata with the block address,
3291 and returns this address.
3295 Userdata represent C&nbsp;values in Lua.
3296 A <em>full userdata</em> represents a block of memory.
3297 It is an object (like a table):
3298 you must create it, it can have its own metatable,
3299 and you can detect when it is being collected.
3300 A full userdata is only equal to itself (under raw equality).
3304 When Lua collects a full userdata with a <code>gc</code> metamethod,
3305 Lua calls the metamethod and marks the userdata as finalized.
3306 When this userdata is collected again then
3307 Lua frees its corresponding memory.
3313 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
3314 <span class="apii">[-1, +(2|0), <em>e</em>]</span>
3315 <pre>int lua_next (lua_State *L, int index);</pre>
3318 Pops a key from the stack,
3319 and pushes a key-value pair from the table at the given index
3320 (the "next" pair after the given key).
3321 If there are no more elements in the table,
3322 then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3326 A typical traversal looks like this:
3328 <pre>
3329 /* table is in the stack at index 't' */
3330 lua_pushnil(L); /* first key */
3331 while (lua_next(L, t) != 0) {
3332 /* uses 'key' (at index -2) and 'value' (at index -1) */
3333 printf("%s - %s\n",
3334 lua_typename(L, lua_type(L, -2)),
3335 lua_typename(L, lua_type(L, -1)));
3336 /* removes 'value'; keeps 'key' for next iteration */
3337 lua_pop(L, 1);
3339 </pre>
3342 While traversing a table,
3343 do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3344 unless you know that the key is actually a string.
3345 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
3346 the value at the given index;
3347 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3353 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3354 <pre>typedef double lua_Number;</pre>
3357 The type of numbers in Lua.
3358 By default, it is double, but that can be changed in <code>luaconf.h</code>.
3362 Through the configuration file you can change
3363 Lua to operate with another type for numbers (e.g., float or long).
3369 <hr><h3><a name="lua_objlen"><code>lua_objlen</code></a></h3><p>
3370 <span class="apii">[-0, +0, <em>-</em>]</span>
3371 <pre>size_t lua_objlen (lua_State *L, int index);</pre>
3374 Returns the "length" of the value at the given acceptable index:
3375 for strings, this is the string length;
3376 for tables, this is the result of the length operator ('<code>#</code>');
3377 for userdata, this is the size of the block of memory allocated
3378 for the userdata;
3379 for other values, it is&nbsp;0.
3385 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
3386 <span class="apii">[-(nargs + 1), +(nresults|1), <em>-</em>]</span>
3387 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);</pre>
3390 Calls a function in protected mode.
3394 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3395 in <a href="#lua_call"><code>lua_call</code></a>.
3396 If there are no errors during the call,
3397 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
3398 However, if there is any error,
3399 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3400 pushes a single value on the stack (the error message),
3401 and returns an error code.
3402 Like <a href="#lua_call"><code>lua_call</code></a>,
3403 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3404 and its arguments from the stack.
3408 If <code>errfunc</code> is 0,
3409 then the error message returned on the stack
3410 is exactly the original error message.
3411 Otherwise, <code>errfunc</code> is the stack index of an
3412 <em>error handler function</em>.
3413 (In the current implementation, this index cannot be a pseudo-index.)
3414 In case of runtime errors,
3415 this function will be called with the error message
3416 and its return value will be the message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3420 Typically, the error handler function is used to add more debug
3421 information to the error message, such as a stack traceback.
3422 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3423 since by then the stack has unwound.
3427 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
3428 or one of the following error codes
3429 (defined in <code>lua.h</code>):
3431 <ul>
3433 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b>
3434 a runtime error.
3435 </li>
3437 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3438 memory allocation error.
3439 For such errors, Lua does not call the error handler function.
3440 </li>
3442 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
3443 error while running the error handler function.
3444 </li>
3446 </ul>
3451 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
3452 <span class="apii">[-n, +0, <em>-</em>]</span>
3453 <pre>void lua_pop (lua_State *L, int n);</pre>
3456 Pops <code>n</code> elements from the stack.
3462 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
3463 <span class="apii">[-0, +1, <em>-</em>]</span>
3464 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
3467 Pushes a boolean value with value <code>b</code> onto the stack.
3473 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
3474 <span class="apii">[-n, +1, <em>m</em>]</span>
3475 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
3478 Pushes a new C&nbsp;closure onto the stack.
3482 When a C&nbsp;function is created,
3483 it is possible to associate some values with it,
3484 thus creating a C&nbsp;closure (see <a href="#3.4">&sect;3.4</a>);
3485 these values are then accessible to the function whenever it is called.
3486 To associate values with a C&nbsp;function,
3487 first these values should be pushed onto the stack
3488 (when there are multiple values, the first value is pushed first).
3489 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
3490 is called to create and push the C&nbsp;function onto the stack,
3491 with the argument <code>n</code> telling how many values should be
3492 associated with the function.
3493 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
3497 The maximum value for <code>n</code> is 255.
3503 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
3504 <span class="apii">[-0, +1, <em>m</em>]</span>
3505 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
3508 Pushes a C&nbsp;function onto the stack.
3509 This function receives a pointer to a C function
3510 and pushes onto the stack a Lua value of type <code>function</code> that,
3511 when called, invokes the corresponding C&nbsp;function.
3515 Any function to be registered in Lua must
3516 follow the correct protocol to receive its parameters
3517 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
3521 <code>lua_pushcfunction</code> is defined as a macro:
3523 <pre>
3524 #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
3525 </pre>
3530 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
3531 <span class="apii">[-0, +1, <em>m</em>]</span>
3532 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
3535 Pushes onto the stack a formatted string
3536 and returns a pointer to this string.
3537 It is similar to the C&nbsp;function <code>sprintf</code>,
3538 but has some important differences:
3540 <ul>
3542 <li>
3543 You do not have to allocate space for the result:
3544 the result is a Lua string and Lua takes care of memory allocation
3545 (and deallocation, through garbage collection).
3546 </li>
3548 <li>
3549 The conversion specifiers are quite restricted.
3550 There are no flags, widths, or precisions.
3551 The conversion specifiers can only be
3552 '<code>%%</code>' (inserts a '<code>%</code>' in the string),
3553 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
3554 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
3555 '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
3556 '<code>%d</code>' (inserts an <code>int</code>), and
3557 '<code>%c</code>' (inserts an <code>int</code> as a character).
3558 </li>
3560 </ul>
3565 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
3566 <span class="apii">[-0, +1, <em>-</em>]</span>
3567 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
3570 Pushes a number with value <code>n</code> onto the stack.
3576 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
3577 <span class="apii">[-0, +1, <em>-</em>]</span>
3578 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
3581 Pushes a light userdata onto the stack.
3585 Userdata represent C&nbsp;values in Lua.
3586 A <em>light userdata</em> represents a pointer.
3587 It is a value (like a number):
3588 you do not create it, it has no individual metatable,
3589 and it is not collected (as it was never created).
3590 A light userdata is equal to "any"
3591 light userdata with the same C&nbsp;address.
3597 <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
3598 <span class="apii">[-0, +1, <em>m</em>]</span>
3599 <pre>void lua_pushliteral (lua_State *L, const char *s);</pre>
3602 This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3603 but can be used only when <code>s</code> is a literal string.
3604 In these cases, it automatically provides the string length.
3610 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
3611 <span class="apii">[-0, +1, <em>m</em>]</span>
3612 <pre>void lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
3615 Pushes the string pointed to by <code>s</code> with size <code>len</code>
3616 onto the stack.
3617 Lua makes (or reuses) an internal copy of the given string,
3618 so the memory at <code>s</code> can be freed or reused immediately after
3619 the function returns.
3620 The string can contain embedded zeros.
3626 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
3627 <span class="apii">[-0, +1, <em>-</em>]</span>
3628 <pre>void lua_pushnil (lua_State *L);</pre>
3631 Pushes a nil value onto the stack.
3637 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
3638 <span class="apii">[-0, +1, <em>-</em>]</span>
3639 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
3642 Pushes a number with value <code>n</code> onto the stack.
3648 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
3649 <span class="apii">[-0, +1, <em>m</em>]</span>
3650 <pre>void lua_pushstring (lua_State *L, const char *s);</pre>
3653 Pushes the zero-terminated string pointed to by <code>s</code>
3654 onto the stack.
3655 Lua makes (or reuses) an internal copy of the given string,
3656 so the memory at <code>s</code> can be freed or reused immediately after
3657 the function returns.
3658 The string cannot contain embedded zeros;
3659 it is assumed to end at the first zero.
3665 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
3666 <span class="apii">[-0, +1, <em>-</em>]</span>
3667 <pre>int lua_pushthread (lua_State *L);</pre>
3670 Pushes the thread represented by <code>L</code> onto the stack.
3671 Returns 1 if this thread is the main thread of its state.
3677 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
3678 <span class="apii">[-0, +1, <em>-</em>]</span>
3679 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
3682 Pushes a copy of the element at the given valid index
3683 onto the stack.
3689 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
3690 <span class="apii">[-0, +1, <em>m</em>]</span>
3691 <pre>const char *lua_pushvfstring (lua_State *L,
3692 const char *fmt,
3693 va_list argp);</pre>
3696 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
3697 instead of a variable number of arguments.
3703 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
3704 <span class="apii">[-0, +0, <em>-</em>]</span>
3705 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
3708 Returns 1 if the two values in acceptable indices <code>index1</code> and
3709 <code>index2</code> are primitively equal
3710 (that is, without calling metamethods).
3711 Otherwise returns&nbsp;0.
3712 Also returns&nbsp;0 if any of the indices are non valid.
3718 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
3719 <span class="apii">[-1, +1, <em>-</em>]</span>
3720 <pre>void lua_rawget (lua_State *L, int index);</pre>
3723 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
3724 (i.e., without metamethods).
3730 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
3731 <span class="apii">[-0, +1, <em>-</em>]</span>
3732 <pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
3735 Pushes onto the stack the value <code>t[n]</code>,
3736 where <code>t</code> is the value at the given valid index.
3737 The access is raw;
3738 that is, it does not invoke metamethods.
3744 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
3745 <span class="apii">[-2, +0, <em>m</em>]</span>
3746 <pre>void lua_rawset (lua_State *L, int index);</pre>
3749 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
3750 (i.e., without metamethods).
3756 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
3757 <span class="apii">[-1, +0, <em>m</em>]</span>
3758 <pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
3761 Does the equivalent of <code>t[n] = v</code>,
3762 where <code>t</code> is the value at the given valid index
3763 and <code>v</code> is the value at the top of the stack.
3767 This function pops the value from the stack.
3768 The assignment is raw;
3769 that is, it does not invoke metamethods.
3775 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
3776 <pre>typedef const char * (*lua_Reader) (lua_State *L,
3777 void *data,
3778 size_t *size);</pre>
3781 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
3782 Every time it needs another piece of the chunk,
3783 <a href="#lua_load"><code>lua_load</code></a> calls the reader,
3784 passing along its <code>data</code> parameter.
3785 The reader must return a pointer to a block of memory
3786 with a new piece of the chunk
3787 and set <code>size</code> to the block size.
3788 The block must exist until the reader function is called again.
3789 To signal the end of the chunk,
3790 the reader must return <code>NULL</code> or set <code>size</code> to zero.
3791 The reader function may return pieces of any size greater than zero.
3797 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
3798 <span class="apii">[-0, +0, <em>e</em>]</span>
3799 <pre>void lua_register (lua_State *L,
3800 const char *name,
3801 lua_CFunction f);</pre>
3804 Sets the C function <code>f</code> as the new value of global <code>name</code>.
3805 It is defined as a macro:
3807 <pre>
3808 #define lua_register(L,n,f) \
3809 (lua_pushcfunction(L, f), lua_setglobal(L, n))
3810 </pre>
3815 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
3816 <span class="apii">[-1, +0, <em>-</em>]</span>
3817 <pre>void lua_remove (lua_State *L, int index);</pre>
3820 Removes the element at the given valid index,
3821 shifting down the elements above this index to fill the gap.
3822 Cannot be called with a pseudo-index,
3823 because a pseudo-index is not an actual stack position.
3829 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
3830 <span class="apii">[-1, +0, <em>-</em>]</span>
3831 <pre>void lua_replace (lua_State *L, int index);</pre>
3834 Moves the top element into the given position (and pops it),
3835 without shifting any element
3836 (therefore replacing the value at the given position).
3842 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
3843 <span class="apii">[-?, +?, <em>-</em>]</span>
3844 <pre>int lua_resume (lua_State *L, int narg);</pre>
3847 Starts and resumes a coroutine in a given thread.
3851 To start a coroutine, you first create a new thread
3852 (see <a href="#lua_newthread"><code>lua_newthread</code></a>);
3853 then you push onto its stack the main function plus any arguments;
3854 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
3855 with <code>narg</code> being the number of arguments.
3856 This call returns when the coroutine suspends or finishes its execution.
3857 When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
3858 or all values returned by the body function.
3859 <a href="#lua_resume"><code>lua_resume</code></a> returns
3860 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
3861 0 if the coroutine finishes its execution
3862 without errors,
3863 or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
3864 In case of errors,
3865 the stack is not unwound,
3866 so you can use the debug API over it.
3867 The error message is on the top of the stack.
3868 To restart a coroutine, you put on its stack only the values to
3869 be passed as results from <code>yield</code>,
3870 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
3876 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
3877 <span class="apii">[-0, +0, <em>-</em>]</span>
3878 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
3881 Changes the allocator function of a given state to <code>f</code>
3882 with user data <code>ud</code>.
3888 <hr><h3><a name="lua_setfenv"><code>lua_setfenv</code></a></h3><p>
3889 <span class="apii">[-1, +0, <em>-</em>]</span>
3890 <pre>int lua_setfenv (lua_State *L, int index);</pre>
3893 Pops a table from the stack and sets it as
3894 the new environment for the value at the given index.
3895 If the value at the given index is
3896 neither a function nor a thread nor a userdata,
3897 <a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0.
3898 Otherwise it returns 1.
3904 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
3905 <span class="apii">[-1, +0, <em>e</em>]</span>
3906 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
3909 Does the equivalent to <code>t[k] = v</code>,
3910 where <code>t</code> is the value at the given valid index
3911 and <code>v</code> is the value at the top of the stack.
3915 This function pops the value from the stack.
3916 As in Lua, this function may trigger a metamethod
3917 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3923 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
3924 <span class="apii">[-1, +0, <em>e</em>]</span>
3925 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
3928 Pops a value from the stack and
3929 sets it as the new value of global <code>name</code>.
3930 It is defined as a macro:
3932 <pre>
3933 #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
3934 </pre>
3939 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
3940 <span class="apii">[-1, +0, <em>-</em>]</span>
3941 <pre>int lua_setmetatable (lua_State *L, int index);</pre>
3944 Pops a table from the stack and
3945 sets it as the new metatable for the value at the given
3946 acceptable index.
3952 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
3953 <span class="apii">[-2, +0, <em>e</em>]</span>
3954 <pre>void lua_settable (lua_State *L, int index);</pre>
3957 Does the equivalent to <code>t[k] = v</code>,
3958 where <code>t</code> is the value at the given valid index,
3959 <code>v</code> is the value at the top of the stack,
3960 and <code>k</code> is the value just below the top.
3964 This function pops both the key and the value from the stack.
3965 As in Lua, this function may trigger a metamethod
3966 for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3972 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
3973 <span class="apii">[-?, +?, <em>-</em>]</span>
3974 <pre>void lua_settop (lua_State *L, int index);</pre>
3977 Accepts any acceptable index, or&nbsp;0,
3978 and sets the stack top to this index.
3979 If the new top is larger than the old one,
3980 then the new elements are filled with <b>nil</b>.
3981 If <code>index</code> is&nbsp;0, then all stack elements are removed.
3987 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
3988 <pre>typedef struct lua_State lua_State;</pre>
3991 Opaque structure that keeps the whole state of a Lua interpreter.
3992 The Lua library is fully reentrant:
3993 it has no global variables.
3994 All information about a state is kept in this structure.
3998 A pointer to this state must be passed as the first argument to
3999 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4000 which creates a Lua state from scratch.
4006 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4007 <span class="apii">[-0, +0, <em>-</em>]</span>
4008 <pre>int lua_status (lua_State *L);</pre>
4011 Returns the status of the thread <code>L</code>.
4015 The status can be 0 for a normal thread,
4016 an error code if the thread finished its execution with an error,
4017 or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4023 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4024 <span class="apii">[-0, +0, <em>-</em>]</span>
4025 <pre>int lua_toboolean (lua_State *L, int index);</pre>
4028 Converts the Lua value at the given acceptable index to a C&nbsp;boolean
4029 value (0&nbsp;or&nbsp;1).
4030 Like all tests in Lua,
4031 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
4032 different from <b>false</b> and <b>nil</b>;
4033 otherwise it returns 0.
4034 It also returns 0 when called with a non-valid index.
4035 (If you want to accept only actual boolean values,
4036 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4042 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4043 <span class="apii">[-0, +0, <em>-</em>]</span>
4044 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4047 Converts a value at the given acceptable index to a C&nbsp;function.
4048 That value must be a C&nbsp;function;
4049 otherwise, returns <code>NULL</code>.
4055 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4056 <span class="apii">[-0, +0, <em>-</em>]</span>
4057 <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4060 Converts the Lua value at the given acceptable index
4061 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4062 The Lua value must be a number or a string convertible to a number
4063 (see <a href="#2.2.1">&sect;2.2.1</a>);
4064 otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns&nbsp;0.
4068 If the number is not an integer,
4069 it is truncated in some non-specified way.
4075 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
4076 <span class="apii">[-0, +0, <em>m</em>]</span>
4077 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
4080 Converts the Lua value at the given acceptable index to a C&nbsp;string.
4081 If <code>len</code> is not <code>NULL</code>,
4082 it also sets <code>*len</code> with the string length.
4083 The Lua value must be a string or a number;
4084 otherwise, the function returns <code>NULL</code>.
4085 If the value is a number,
4086 then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
4087 <em>changes the actual value in the stack to a string</em>.
4088 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
4089 when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys during a table traversal.)
4093 <a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
4094 to a string inside the Lua state.
4095 This string always has a zero ('<code>\0</code>')
4096 after its last character (as in&nbsp;C),
4097 but can contain other zeros in its body.
4098 Because Lua has garbage collection,
4099 there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
4100 will be valid after the corresponding value is removed from the stack.
4106 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
4107 <span class="apii">[-0, +0, <em>-</em>]</span>
4108 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
4111 Converts the Lua value at the given acceptable index
4112 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
4113 The Lua value must be a number or a string convertible to a number
4114 (see <a href="#2.2.1">&sect;2.2.1</a>);
4115 otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns&nbsp;0.
4121 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
4122 <span class="apii">[-0, +0, <em>-</em>]</span>
4123 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
4126 Converts the value at the given acceptable index to a generic
4127 C&nbsp;pointer (<code>void*</code>).
4128 The value can be a userdata, a table, a thread, or a function;
4129 otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
4130 Different objects will give different pointers.
4131 There is no way to convert the pointer back to its original value.
4135 Typically this function is used only for debug information.
4141 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
4142 <span class="apii">[-0, +0, <em>m</em>]</span>
4143 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
4146 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4152 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
4153 <span class="apii">[-0, +0, <em>-</em>]</span>
4154 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4157 Converts the value at the given acceptable index to a Lua thread
4158 (represented as <code>lua_State*</code>).
4159 This value must be a thread;
4160 otherwise, the function returns <code>NULL</code>.
4166 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
4167 <span class="apii">[-0, +0, <em>-</em>]</span>
4168 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
4171 If the value at the given acceptable index is a full userdata,
4172 returns its block address.
4173 If the value is a light userdata,
4174 returns its pointer.
4175 Otherwise, returns <code>NULL</code>.
4181 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
4182 <span class="apii">[-0, +0, <em>-</em>]</span>
4183 <pre>int lua_type (lua_State *L, int index);</pre>
4186 Returns the type of the value in the given acceptable index,
4187 or <code>LUA_TNONE</code> for a non-valid index
4188 (that is, an index to an "empty" stack position).
4189 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4190 defined in <code>lua.h</code>:
4191 <code>LUA_TNIL</code>,
4192 <code>LUA_TNUMBER</code>,
4193 <code>LUA_TBOOLEAN</code>,
4194 <code>LUA_TSTRING</code>,
4195 <code>LUA_TTABLE</code>,
4196 <code>LUA_TFUNCTION</code>,
4197 <code>LUA_TUSERDATA</code>,
4198 <code>LUA_TTHREAD</code>,
4200 <code>LUA_TLIGHTUSERDATA</code>.
4206 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
4207 <span class="apii">[-0, +0, <em>-</em>]</span>
4208 <pre>const char *lua_typename (lua_State *L, int tp);</pre>
4211 Returns the name of the type encoded by the value <code>tp</code>,
4212 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4218 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4219 <pre>typedef int (*lua_Writer) (lua_State *L,
4220 const void* p,
4221 size_t sz,
4222 void* ud);</pre>
4225 The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4226 Every time it produces another piece of chunk,
4227 <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4228 passing along the buffer to be written (<code>p</code>),
4229 its size (<code>sz</code>),
4230 and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4234 The writer returns an error code:
4235 0&nbsp;means no errors;
4236 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4237 calling the writer again.
4243 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
4244 <span class="apii">[-?, +?, <em>-</em>]</span>
4245 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4248 Exchange values between different threads of the <em>same</em> global state.
4252 This function pops <code>n</code> values from the stack <code>from</code>,
4253 and pushes them onto the stack <code>to</code>.
4259 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
4260 <span class="apii">[-?, +?, <em>-</em>]</span>
4261 <pre>int lua_yield (lua_State *L, int nresults);</pre>
4264 Yields a coroutine.
4268 This function should only be called as the
4269 return expression of a C&nbsp;function, as follows:
4271 <pre>
4272 return lua_yield (L, nresults);
4273 </pre><p>
4274 When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
4275 the running coroutine suspends its execution,
4276 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
4277 The parameter <code>nresults</code> is the number of values from the stack
4278 that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
4286 <h2>3.8 - <a name="3.8">The Debug Interface</a></h2>
4289 Lua has no built-in debugging facilities.
4290 Instead, it offers a special interface
4291 by means of functions and <em>hooks</em>.
4292 This interface allows the construction of different
4293 kinds of debuggers, profilers, and other tools
4294 that need "inside information" from the interpreter.
4298 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
4299 <pre>typedef struct lua_Debug {
4300 int event;
4301 const char *name; /* (n) */
4302 const char *namewhat; /* (n) */
4303 const char *what; /* (S) */
4304 const char *source; /* (S) */
4305 int currentline; /* (l) */
4306 int nups; /* (u) number of upvalues */
4307 int linedefined; /* (S) */
4308 int lastlinedefined; /* (S) */
4309 char short_src[LUA_IDSIZE]; /* (S) */
4310 /* private part */
4311 <em>other fields</em>
4312 } lua_Debug;</pre>
4315 A structure used to carry different pieces of
4316 information about an active function.
4317 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
4318 of this structure, for later use.
4319 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
4320 call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4324 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
4326 <ul>
4328 <li><b><code>source</code>:</b>
4329 If the function was defined in a string,
4330 then <code>source</code> is that string.
4331 If the function was defined in a file,
4332 then <code>source</code> starts with a '<code>@</code>' followed by the file name.
4333 </li>
4335 <li><b><code>short_src</code>:</b>
4336 a "printable" version of <code>source</code>, to be used in error messages.
4337 </li>
4339 <li><b><code>linedefined</code>:</b>
4340 the line number where the definition of the function starts.
4341 </li>
4343 <li><b><code>lastlinedefined</code>:</b>
4344 the line number where the definition of the function ends.
4345 </li>
4347 <li><b><code>what</code>:</b>
4348 the string <code>"Lua"</code> if the function is a Lua function,
4349 <code>"C"</code> if it is a C&nbsp;function,
4350 <code>"main"</code> if it is the main part of a chunk,
4351 and <code>"tail"</code> if it was a function that did a tail call.
4352 In the latter case,
4353 Lua has no other information about the function.
4354 </li>
4356 <li><b><code>currentline</code>:</b>
4357 the current line where the given function is executing.
4358 When no line information is available,
4359 <code>currentline</code> is set to -1.
4360 </li>
4362 <li><b><code>name</code>:</b>
4363 a reasonable name for the given function.
4364 Because functions in Lua are first-class values,
4365 they do not have a fixed name:
4366 some functions can be the value of multiple global variables,
4367 while others can be stored only in a table field.
4368 The <code>lua_getinfo</code> function checks how the function was
4369 called to find a suitable name.
4370 If it cannot find a name,
4371 then <code>name</code> is set to <code>NULL</code>.
4372 </li>
4374 <li><b><code>namewhat</code>:</b>
4375 explains the <code>name</code> field.
4376 The value of <code>namewhat</code> can be
4377 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
4378 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
4379 according to how the function was called.
4380 (Lua uses the empty string when no other option seems to apply.)
4381 </li>
4383 <li><b><code>nups</code>:</b>
4384 the number of upvalues of the function.
4385 </li>
4387 </ul>
4392 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
4393 <span class="apii">[-0, +0, <em>-</em>]</span>
4394 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
4397 Returns the current hook function.
4403 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
4404 <span class="apii">[-0, +0, <em>-</em>]</span>
4405 <pre>int lua_gethookcount (lua_State *L);</pre>
4408 Returns the current hook count.
4414 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
4415 <span class="apii">[-0, +0, <em>-</em>]</span>
4416 <pre>int lua_gethookmask (lua_State *L);</pre>
4419 Returns the current hook mask.
4425 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
4426 <span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
4427 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
4430 Returns information about a specific function or function invocation.
4434 To get information about a function invocation,
4435 the parameter <code>ar</code> must be a valid activation record that was
4436 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4437 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4441 To get information about a function you push it onto the stack
4442 and start the <code>what</code> string with the character '<code>&gt;</code>'.
4443 (In that case,
4444 <code>lua_getinfo</code> pops the function in the top of the stack.)
4445 For instance, to know in which line a function <code>f</code> was defined,
4446 you can write the following code:
4448 <pre>
4449 lua_Debug ar;
4450 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
4451 lua_getinfo(L, "&gt;S", &amp;ar);
4452 printf("%d\n", ar.linedefined);
4453 </pre>
4456 Each character in the string <code>what</code>
4457 selects some fields of the structure <code>ar</code> to be filled or
4458 a value to be pushed on the stack:
4460 <ul>
4462 <li><b>'<code>n</code>':</b> fills in the field <code>name</code> and <code>namewhat</code>;
4463 </li>
4465 <li><b>'<code>S</code>':</b>
4466 fills in the fields <code>source</code>, <code>short_src</code>,
4467 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
4468 </li>
4470 <li><b>'<code>l</code>':</b> fills in the field <code>currentline</code>;
4471 </li>
4473 <li><b>'<code>u</code>':</b> fills in the field <code>nups</code>;
4474 </li>
4476 <li><b>'<code>f</code>':</b>
4477 pushes onto the stack the function that is
4478 running at the given level;
4479 </li>
4481 <li><b>'<code>L</code>':</b>
4482 pushes onto the stack a table whose indices are the
4483 numbers of the lines that are valid on the function.
4484 (A <em>valid line</em> is a line with some associated code,
4485 that is, a line where you can put a break point.
4486 Non-valid lines include empty lines and comments.)
4487 </li>
4489 </ul>
4492 This function returns 0 on error
4493 (for instance, an invalid option in <code>what</code>).
4499 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
4500 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
4501 <pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4504 Gets information about a local variable of a given activation record.
4505 The parameter <code>ar</code> must be a valid activation record that was
4506 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4507 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4508 The index <code>n</code> selects which local variable to inspect
4509 (1 is the first parameter or active local variable, and so on,
4510 until the last active local variable).
4511 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
4512 and returns its name.
4516 Variable names starting with '<code>(</code>' (open parentheses)
4517 represent internal variables
4518 (loop control variables, temporaries, and C&nbsp;function locals).
4522 Returns <code>NULL</code> (and pushes nothing)
4523 when the index is greater than
4524 the number of active local variables.
4530 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
4531 <span class="apii">[-0, +0, <em>-</em>]</span>
4532 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
4535 Get information about the interpreter runtime stack.
4539 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
4540 an identification of the <em>activation record</em>
4541 of the function executing at a given level.
4542 Level&nbsp;0 is the current running function,
4543 whereas level <em>n+1</em> is the function that has called level <em>n</em>.
4544 When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
4545 when called with a level greater than the stack depth,
4546 it returns 0.
4552 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
4553 <span class="apii">[-0, +(0|1), <em>-</em>]</span>
4554 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
4557 Gets information about a closure's upvalue.
4558 (For Lua functions,
4559 upvalues are the external local variables that the function uses,
4560 and that are consequently included in its closure.)
4561 <a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
4562 pushes the upvalue's value onto the stack,
4563 and returns its name.
4564 <code>funcindex</code> points to the closure in the stack.
4565 (Upvalues have no particular order,
4566 as they are active through the whole function.
4567 So, they are numbered in an arbitrary order.)
4571 Returns <code>NULL</code> (and pushes nothing)
4572 when the index is greater than the number of upvalues.
4573 For C&nbsp;functions, this function uses the empty string <code>""</code>
4574 as a name for all upvalues.
4580 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
4581 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
4584 Type for debugging hook functions.
4588 Whenever a hook is called, its <code>ar</code> argument has its field
4589 <code>event</code> set to the specific event that triggered the hook.
4590 Lua identifies these events with the following constants:
4591 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
4592 <a name="pdf-LUA_HOOKTAILRET"><code>LUA_HOOKTAILRET</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
4593 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
4594 Moreover, for line events, the field <code>currentline</code> is also set.
4595 To get the value of any other field in <code>ar</code>,
4596 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4597 For return events, <code>event</code> can be <code>LUA_HOOKRET</code>,
4598 the normal value, or <code>LUA_HOOKTAILRET</code>.
4599 In the latter case, Lua is simulating a return from
4600 a function that did a tail call;
4601 in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4605 While Lua is running a hook, it disables other calls to hooks.
4606 Therefore, if a hook calls back Lua to execute a function or a chunk,
4607 this execution occurs without any calls to hooks.
4613 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
4614 <span class="apii">[-0, +0, <em>-</em>]</span>
4615 <pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
4618 Sets the debugging hook function.
4622 Argument <code>f</code> is the hook function.
4623 <code>mask</code> specifies on which events the hook will be called:
4624 it is formed by a bitwise or of the constants
4625 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
4626 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
4627 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
4628 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
4629 The <code>count</code> argument is only meaningful when the mask
4630 includes <code>LUA_MASKCOUNT</code>.
4631 For each event, the hook is called as explained below:
4633 <ul>
4635 <li><b>The call hook:</b> is called when the interpreter calls a function.
4636 The hook is called just after Lua enters the new function,
4637 before the function gets its arguments.
4638 </li>
4640 <li><b>The return hook:</b> is called when the interpreter returns from a function.
4641 The hook is called just before Lua leaves the function.
4642 You have no access to the values to be returned by the function.
4643 </li>
4645 <li><b>The line hook:</b> is called when the interpreter is about to
4646 start the execution of a new line of code,
4647 or when it jumps back in the code (even to the same line).
4648 (This event only happens while Lua is executing a Lua function.)
4649 </li>
4651 <li><b>The count hook:</b> is called after the interpreter executes every
4652 <code>count</code> instructions.
4653 (This event only happens while Lua is executing a Lua function.)
4654 </li>
4656 </ul>
4659 A hook is disabled by setting <code>mask</code> to zero.
4665 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
4666 <span class="apii">[-(0|1), +0, <em>-</em>]</span>
4667 <pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
4670 Sets the value of a local variable of a given activation record.
4671 Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
4672 (see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
4673 <a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
4674 to the variable and returns its name.
4675 It also pops the value from the stack.
4679 Returns <code>NULL</code> (and pops nothing)
4680 when the index is greater than
4681 the number of active local variables.
4687 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
4688 <span class="apii">[-(0|1), +0, <em>-</em>]</span>
4689 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
4692 Sets the value of a closure's upvalue.
4693 It assigns the value at the top of the stack
4694 to the upvalue and returns its name.
4695 It also pops the value from the stack.
4696 Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
4697 (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
4701 Returns <code>NULL</code> (and pops nothing)
4702 when the index is greater than the number of upvalues.
4710 <h1>4 - <a name="4">The Auxiliary Library</a></h1>
4714 The <em>auxiliary library</em> provides several convenient functions
4715 to interface C with Lua.
4716 While the basic API provides the primitive functions for all
4717 interactions between C and Lua,
4718 the auxiliary library provides higher-level functions for some
4719 common tasks.
4723 All functions from the auxiliary library
4724 are defined in header file <code>lauxlib.h</code> and
4725 have a prefix <code>luaL_</code>.
4729 All functions in the auxiliary library are built on
4730 top of the basic API,
4731 and so they provide nothing that cannot be done with this API.
4735 Several functions in the auxiliary library are used to
4736 check C&nbsp;function arguments.
4737 Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
4738 All of these functions throw an error if the check is not satisfied.
4739 Because the error message is formatted for arguments
4740 (e.g., "<code>bad argument #1</code>"),
4741 you should not use these functions for other stack values.
4745 <h2>4.1 - <a name="4.1">Functions and Types</a></h2>
4748 Here we list all functions and types from the auxiliary library
4749 in alphabetical order.
4753 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
4754 <span class="apii">[-0, +0, <em>m</em>]</span>
4755 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
4758 Adds the character <code>c</code> to the buffer <code>B</code>
4759 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4765 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
4766 <span class="apii">[-0, +0, <em>m</em>]</span>
4767 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
4770 Adds the string pointed to by <code>s</code> with length <code>l</code> to
4771 the buffer <code>B</code>
4772 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4773 The string may contain embedded zeros.
4779 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
4780 <span class="apii">[-0, +0, <em>m</em>]</span>
4781 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
4784 Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
4785 a string of length <code>n</code> previously copied to the
4786 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
4792 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
4793 <span class="apii">[-0, +0, <em>m</em>]</span>
4794 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
4797 Adds the zero-terminated string pointed to by <code>s</code>
4798 to the buffer <code>B</code>
4799 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4800 The string may not contain embedded zeros.
4806 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
4807 <span class="apii">[-1, +0, <em>m</em>]</span>
4808 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
4811 Adds the value at the top of the stack
4812 to the buffer <code>B</code>
4813 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4814 Pops the value.
4818 This is the only function on string buffers that can (and must)
4819 be called with an extra element on the stack,
4820 which is the value to be added to the buffer.
4826 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
4827 <span class="apii">[-0, +0, <em>v</em>]</span>
4828 <pre>void luaL_argcheck (lua_State *L,
4829 int cond,
4830 int narg,
4831 const char *extramsg);</pre>
4834 Checks whether <code>cond</code> is true.
4835 If not, raises an error with the following message,
4836 where <code>func</code> is retrieved from the call stack:
4838 <pre>
4839 bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4840 </pre>
4845 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
4846 <span class="apii">[-0, +0, <em>v</em>]</span>
4847 <pre>int luaL_argerror (lua_State *L, int narg, const char *extramsg);</pre>
4850 Raises an error with the following message,
4851 where <code>func</code> is retrieved from the call stack:
4853 <pre>
4854 bad argument #&lt;narg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4855 </pre>
4858 This function never returns,
4859 but it is an idiom to use it in C&nbsp;functions
4860 as <code>return luaL_argerror(<em>args</em>)</code>.
4866 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
4867 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
4870 Type for a <em>string buffer</em>.
4874 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
4875 Its pattern of use is as follows:
4877 <ul>
4879 <li>First you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
4881 <li>Then you initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
4883 <li>
4884 Then you add string pieces to the buffer calling any of
4885 the <code>luaL_add*</code> functions.
4886 </li>
4888 <li>
4889 You finish by calling <code>luaL_pushresult(&amp;b)</code>.
4890 This call leaves the final string on the top of the stack.
4891 </li>
4893 </ul>
4896 During its normal operation,
4897 a string buffer uses a variable number of stack slots.
4898 So, while using a buffer, you cannot assume that you know where
4899 the top of the stack is.
4900 You can use the stack between successive calls to buffer operations
4901 as long as that use is balanced;
4902 that is,
4903 when you call a buffer operation,
4904 the stack is at the same level
4905 it was immediately after the previous buffer operation.
4906 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
4907 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
4908 level when the buffer was initialized,
4909 plus the final string on its top.
4915 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
4916 <span class="apii">[-0, +0, <em>-</em>]</span>
4917 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
4920 Initializes a buffer <code>B</code>.
4921 This function does not allocate any space;
4922 the buffer must be declared as a variable
4923 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4929 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
4930 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
4931 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
4934 Calls a metamethod.
4938 If the object at index <code>obj</code> has a metatable and this
4939 metatable has a field <code>e</code>,
4940 this function calls this field and passes the object as its only argument.
4941 In this case this function returns 1 and pushes onto the
4942 stack the value returned by the call.
4943 If there is no metatable or no metamethod,
4944 this function returns 0 (without pushing any value on the stack).
4950 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
4951 <span class="apii">[-0, +0, <em>v</em>]</span>
4952 <pre>void luaL_checkany (lua_State *L, int narg);</pre>
4955 Checks whether the function has an argument
4956 of any type (including <b>nil</b>) at position <code>narg</code>.
4962 <hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
4963 <span class="apii">[-0, +0, <em>v</em>]</span>
4964 <pre>int luaL_checkint (lua_State *L, int narg);</pre>
4967 Checks whether the function argument <code>narg</code> is a number
4968 and returns this number cast to an <code>int</code>.
4974 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
4975 <span class="apii">[-0, +0, <em>v</em>]</span>
4976 <pre>lua_Integer luaL_checkinteger (lua_State *L, int narg);</pre>
4979 Checks whether the function argument <code>narg</code> is a number
4980 and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
4986 <hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
4987 <span class="apii">[-0, +0, <em>v</em>]</span>
4988 <pre>long luaL_checklong (lua_State *L, int narg);</pre>
4991 Checks whether the function argument <code>narg</code> is a number
4992 and returns this number cast to a <code>long</code>.
4998 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
4999 <span class="apii">[-0, +0, <em>v</em>]</span>
5000 <pre>const char *luaL_checklstring (lua_State *L, int narg, size_t *l);</pre>
5003 Checks whether the function argument <code>narg</code> is a string
5004 and returns this string;
5005 if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
5006 with the string's length.
5010 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5011 so all conversions and caveats of that function apply here.
5017 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
5018 <span class="apii">[-0, +0, <em>v</em>]</span>
5019 <pre>lua_Number luaL_checknumber (lua_State *L, int narg);</pre>
5022 Checks whether the function argument <code>narg</code> is a number
5023 and returns this number.
5029 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
5030 <span class="apii">[-0, +0, <em>v</em>]</span>
5031 <pre>int luaL_checkoption (lua_State *L,
5032 int narg,
5033 const char *def,
5034 const char *const lst[]);</pre>
5037 Checks whether the function argument <code>narg</code> is a string and
5038 searches for this string in the array <code>lst</code>
5039 (which must be NULL-terminated).
5040 Returns the index in the array where the string was found.
5041 Raises an error if the argument is not a string or
5042 if the string cannot be found.
5046 If <code>def</code> is not <code>NULL</code>,
5047 the function uses <code>def</code> as a default value when
5048 there is no argument <code>narg</code> or if this argument is <b>nil</b>.
5052 This is a useful function for mapping strings to C&nbsp;enums.
5053 (The usual convention in Lua libraries is
5054 to use strings instead of numbers to select options.)
5060 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
5061 <span class="apii">[-0, +0, <em>v</em>]</span>
5062 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
5065 Grows the stack size to <code>top + sz</code> elements,
5066 raising an error if the stack cannot grow to that size.
5067 <code>msg</code> is an additional text to go into the error message.
5073 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
5074 <span class="apii">[-0, +0, <em>v</em>]</span>
5075 <pre>const char *luaL_checkstring (lua_State *L, int narg);</pre>
5078 Checks whether the function argument <code>narg</code> is a string
5079 and returns this string.
5083 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5084 so all conversions and caveats of that function apply here.
5090 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
5091 <span class="apii">[-0, +0, <em>v</em>]</span>
5092 <pre>void luaL_checktype (lua_State *L, int narg, int t);</pre>
5095 Checks whether the function argument <code>narg</code> has type <code>t</code>.
5096 See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
5102 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
5103 <span class="apii">[-0, +0, <em>v</em>]</span>
5104 <pre>void *luaL_checkudata (lua_State *L, int narg, const char *tname);</pre>
5107 Checks whether the function argument <code>narg</code> is a userdata
5108 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5114 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
5115 <span class="apii">[-0, +?, <em>m</em>]</span>
5116 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
5119 Loads and runs the given file.
5120 It is defined as the following macro:
5122 <pre>
5123 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
5124 </pre><p>
5125 It returns 0 if there are no errors
5126 or 1 in case of errors.
5132 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
5133 <span class="apii">[-0, +?, <em>m</em>]</span>
5134 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
5137 Loads and runs the given string.
5138 It is defined as the following macro:
5140 <pre>
5141 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
5142 </pre><p>
5143 It returns 0 if there are no errors
5144 or 1 in case of errors.
5150 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
5151 <span class="apii">[-0, +0, <em>v</em>]</span>
5152 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
5155 Raises an error.
5156 The error message format is given by <code>fmt</code>
5157 plus any extra arguments,
5158 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
5159 It also adds at the beginning of the message the file name and
5160 the line number where the error occurred,
5161 if this information is available.
5165 This function never returns,
5166 but it is an idiom to use it in C&nbsp;functions
5167 as <code>return luaL_error(<em>args</em>)</code>.
5173 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
5174 <span class="apii">[-0, +(0|1), <em>m</em>]</span>
5175 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
5178 Pushes onto the stack the field <code>e</code> from the metatable
5179 of the object at index <code>obj</code>.
5180 If the object does not have a metatable,
5181 or if the metatable does not have this field,
5182 returns 0 and pushes nothing.
5188 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
5189 <span class="apii">[-0, +1, <em>-</em>]</span>
5190 <pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
5193 Pushes onto the stack the metatable associated with name <code>tname</code>
5194 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
5200 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
5201 <span class="apii">[-0, +1, <em>m</em>]</span>
5202 <pre>const char *luaL_gsub (lua_State *L,
5203 const char *s,
5204 const char *p,
5205 const char *r);</pre>
5208 Creates a copy of string <code>s</code> by replacing
5209 any occurrence of the string <code>p</code>
5210 with the string <code>r</code>.
5211 Pushes the resulting string on the stack and returns it.
5217 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
5218 <span class="apii">[-0, +1, <em>m</em>]</span>
5219 <pre>int luaL_loadbuffer (lua_State *L,
5220 const char *buff,
5221 size_t sz,
5222 const char *name);</pre>
5225 Loads a buffer as a Lua chunk.
5226 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
5227 buffer pointed to by <code>buff</code> with size <code>sz</code>.
5231 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5232 <code>name</code> is the chunk name,
5233 used for debug information and error messages.
5239 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
5240 <span class="apii">[-0, +1, <em>m</em>]</span>
5241 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
5244 Loads a file as a Lua chunk.
5245 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
5246 named <code>filename</code>.
5247 If <code>filename</code> is <code>NULL</code>,
5248 then it loads from the standard input.
5249 The first line in the file is ignored if it starts with a <code>#</code>.
5253 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
5254 but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
5255 if it cannot open/read the file.
5259 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5260 it does not run it.
5266 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
5267 <span class="apii">[-0, +1, <em>m</em>]</span>
5268 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
5271 Loads a string as a Lua chunk.
5272 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
5273 the zero-terminated string <code>s</code>.
5277 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5281 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5282 it does not run it.
5288 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
5289 <span class="apii">[-0, +1, <em>m</em>]</span>
5290 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
5293 If the registry already has the key <code>tname</code>,
5294 returns 0.
5295 Otherwise,
5296 creates a new table to be used as a metatable for userdata,
5297 adds it to the registry with key <code>tname</code>,
5298 and returns 1.
5302 In both cases pushes onto the stack the final value associated
5303 with <code>tname</code> in the registry.
5309 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
5310 <span class="apii">[-0, +0, <em>-</em>]</span>
5311 <pre>lua_State *luaL_newstate (void);</pre>
5314 Creates a new Lua state.
5315 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
5316 allocator based on the standard&nbsp;C <code>realloc</code> function
5317 and then sets a panic function (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) that prints
5318 an error message to the standard error output in case of fatal
5319 errors.
5323 Returns the new state,
5324 or <code>NULL</code> if there is a memory allocation error.
5330 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
5331 <span class="apii">[-0, +0, <em>m</em>]</span>
5332 <pre>void luaL_openlibs (lua_State *L);</pre>
5335 Opens all standard Lua libraries into the given state.
5341 <hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
5342 <span class="apii">[-0, +0, <em>v</em>]</span>
5343 <pre>int luaL_optint (lua_State *L, int narg, int d);</pre>
5346 If the function argument <code>narg</code> is a number,
5347 returns this number cast to an <code>int</code>.
5348 If this argument is absent or is <b>nil</b>,
5349 returns <code>d</code>.
5350 Otherwise, raises an error.
5356 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
5357 <span class="apii">[-0, +0, <em>v</em>]</span>
5358 <pre>lua_Integer luaL_optinteger (lua_State *L,
5359 int narg,
5360 lua_Integer d);</pre>
5363 If the function argument <code>narg</code> is a number,
5364 returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
5365 If this argument is absent or is <b>nil</b>,
5366 returns <code>d</code>.
5367 Otherwise, raises an error.
5373 <hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3><p>
5374 <span class="apii">[-0, +0, <em>v</em>]</span>
5375 <pre>long luaL_optlong (lua_State *L, int narg, long d);</pre>
5378 If the function argument <code>narg</code> is a number,
5379 returns this number cast to a <code>long</code>.
5380 If this argument is absent or is <b>nil</b>,
5381 returns <code>d</code>.
5382 Otherwise, raises an error.
5388 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
5389 <span class="apii">[-0, +0, <em>v</em>]</span>
5390 <pre>const char *luaL_optlstring (lua_State *L,
5391 int narg,
5392 const char *d,
5393 size_t *l);</pre>
5396 If the function argument <code>narg</code> is a string,
5397 returns this string.
5398 If this argument is absent or is <b>nil</b>,
5399 returns <code>d</code>.
5400 Otherwise, raises an error.
5404 If <code>l</code> is not <code>NULL</code>,
5405 fills the position <code>*l</code> with the results's length.
5411 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
5412 <span class="apii">[-0, +0, <em>v</em>]</span>
5413 <pre>lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);</pre>
5416 If the function argument <code>narg</code> is a number,
5417 returns this number.
5418 If this argument is absent or is <b>nil</b>,
5419 returns <code>d</code>.
5420 Otherwise, raises an error.
5426 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
5427 <span class="apii">[-0, +0, <em>v</em>]</span>
5428 <pre>const char *luaL_optstring (lua_State *L,
5429 int narg,
5430 const char *d);</pre>
5433 If the function argument <code>narg</code> is a string,
5434 returns this string.
5435 If this argument is absent or is <b>nil</b>,
5436 returns <code>d</code>.
5437 Otherwise, raises an error.
5443 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
5444 <span class="apii">[-0, +0, <em>-</em>]</span>
5445 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
5448 Returns an address to a space of size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>
5449 where you can copy a string to be added to buffer <code>B</code>
5450 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5451 After copying the string into this space you must call
5452 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
5453 it to the buffer.
5459 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
5460 <span class="apii">[-?, +1, <em>m</em>]</span>
5461 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
5464 Finishes the use of buffer <code>B</code> leaving the final string on
5465 the top of the stack.
5471 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
5472 <span class="apii">[-1, +0, <em>m</em>]</span>
5473 <pre>int luaL_ref (lua_State *L, int t);</pre>
5476 Creates and returns a <em>reference</em>,
5477 in the table at index <code>t</code>,
5478 for the object at the top of the stack (and pops the object).
5482 A reference is a unique integer key.
5483 As long as you do not manually add integer keys into table <code>t</code>,
5484 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
5485 You can retrieve an object referred by reference <code>r</code>
5486 by calling <code>lua_rawgeti(L, t, r)</code>.
5487 Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
5491 If the object at the top of the stack is <b>nil</b>,
5492 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
5493 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
5494 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
5500 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
5501 <pre>typedef struct luaL_Reg {
5502 const char *name;
5503 lua_CFunction func;
5504 } luaL_Reg;</pre>
5507 Type for arrays of functions to be registered by
5508 <a href="#luaL_register"><code>luaL_register</code></a>.
5509 <code>name</code> is the function name and <code>func</code> is a pointer to
5510 the function.
5511 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
5512 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
5518 <hr><h3><a name="luaL_register"><code>luaL_register</code></a></h3><p>
5519 <span class="apii">[-(0|1), +1, <em>m</em>]</span>
5520 <pre>void luaL_register (lua_State *L,
5521 const char *libname,
5522 const luaL_Reg *l);</pre>
5525 Opens a library.
5529 When called with <code>libname</code> equal to <code>NULL</code>,
5530 it simply registers all functions in the list <code>l</code>
5531 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
5535 When called with a non-null <code>libname</code>,
5536 <code>luaL_register</code> creates a new table <code>t</code>,
5537 sets it as the value of the global variable <code>libname</code>,
5538 sets it as the value of <code>package.loaded[libname]</code>,
5539 and registers on it all functions in the list <code>l</code>.
5540 If there is a table in <code>package.loaded[libname]</code> or in
5541 variable <code>libname</code>,
5542 reuses this table instead of creating a new one.
5546 In any case the function leaves the table
5547 on the top of the stack.
5553 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
5554 <span class="apii">[-0, +0, <em>-</em>]</span>
5555 <pre>const char *luaL_typename (lua_State *L, int index);</pre>
5558 Returns the name of the type of the value at the given index.
5564 <hr><h3><a name="luaL_typerror"><code>luaL_typerror</code></a></h3><p>
5565 <span class="apii">[-0, +0, <em>v</em>]</span>
5566 <pre>int luaL_typerror (lua_State *L, int narg, const char *tname);</pre>
5569 Generates an error with a message like the following:
5571 <pre>
5572 <em>location</em>: bad argument <em>narg</em> to '<em>func</em>' (<em>tname</em> expected, got <em>rt</em>)
5573 </pre><p>
5574 where <code><em>location</em></code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
5575 <code><em>func</em></code> is the name of the current function,
5576 and <code><em>rt</em></code> is the type name of the actual argument.
5582 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
5583 <span class="apii">[-0, +0, <em>-</em>]</span>
5584 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
5587 Releases reference <code>ref</code> from the table at index <code>t</code>
5588 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
5589 The entry is removed from the table,
5590 so that the referred object can be collected.
5591 The reference <code>ref</code> is also freed to be used again.
5595 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>,
5596 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
5602 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
5603 <span class="apii">[-0, +1, <em>m</em>]</span>
5604 <pre>void luaL_where (lua_State *L, int lvl);</pre>
5607 Pushes onto the stack a string identifying the current position
5608 of the control at level <code>lvl</code> in the call stack.
5609 Typically this string has the following format:
5611 <pre>
5612 <em>chunkname</em>:<em>currentline</em>:
5613 </pre><p>
5614 Level&nbsp;0 is the running function,
5615 level&nbsp;1 is the function that called the running function,
5616 etc.
5620 This function is used to build a prefix for error messages.