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