xref: /freebsd/contrib/lua/doc/manual.html (revision 1719886f6d08408b834d270c59ffcfd821c8f63a)
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<HTML>
3<HEAD>
4<TITLE>Lua 5.4 Reference Manual</TITLE>
5<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
6<LINK REL="stylesheet" TYPE="text/css" HREF="manual.css">
7<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
8</HEAD>
9
10<BODY>
11
12<H1>
13<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A>
14Lua 5.4 Reference Manual
15</H1>
16
17<P>
18by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
19
20<P>
21<SMALL>
22Copyright &copy; 2020&ndash;2023 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
27<DIV CLASS="menubar">
28<A HREF="contents.html#contents">contents</A>
29&middot;
30<A HREF="contents.html#index">index</A>
31&middot;
32<A HREF="http://www.lua.org/manual/">other versions</A>
33</DIV>
34
35<!-- ====================================================================== -->
36<p>
37
38<!-- $Id: manual.of $ -->
39
40
41
42
43<h1>1 &ndash; <a name="1">Introduction</a></h1>
44
45<p>
46Lua is a powerful, efficient, lightweight, embeddable scripting language.
47It supports procedural programming,
48object-oriented programming, functional programming,
49data-driven programming, and data description.
50
51
52<p>
53Lua combines simple procedural syntax with powerful data description
54constructs based on associative arrays and extensible semantics.
55Lua is dynamically typed,
56runs by interpreting bytecode with a register-based
57virtual machine,
58and has automatic memory management with
59a generational garbage collection,
60making it ideal for configuration, scripting,
61and rapid prototyping.
62
63
64<p>
65Lua is implemented as a library, written in <em>clean C</em>,
66the common subset of standard&nbsp;C and C++.
67The Lua distribution includes a host program called <code>lua</code>,
68which uses the Lua library to offer a complete,
69standalone Lua interpreter,
70for interactive or batch use.
71Lua is intended to be used both as a powerful, lightweight,
72embeddable scripting language for any program that needs one,
73and as a powerful but lightweight and efficient stand-alone language.
74
75
76<p>
77As an extension language, Lua has no notion of a "main" program:
78it works <em>embedded</em> in a host client,
79called the <em>embedding program</em> or simply the <em>host</em>.
80(Frequently, this host is the stand-alone <code>lua</code> program.)
81The host program can invoke functions to execute a piece of Lua code,
82can write and read Lua variables,
83and can register C&nbsp;functions to be called by Lua code.
84Through the use of C&nbsp;functions, Lua can be augmented to cope with
85a wide range of different domains,
86thus creating customized programming languages sharing a syntactical framework.
87
88
89<p>
90Lua is free software,
91and is provided as usual with no guarantees,
92as stated in its license.
93The implementation described in this manual is available
94at Lua's official web site, <code>www.lua.org</code>.
95
96
97<p>
98Like any other reference manual,
99this document is dry in places.
100For a discussion of the decisions behind the design of Lua,
101see the technical papers available at Lua's web site.
102For a detailed introduction to programming in Lua,
103see Roberto's book, <em>Programming in Lua</em>.
104
105
106
107<h1>2 &ndash; <a name="2">Basic Concepts</a></h1>
108
109
110
111<p>
112This section describes the basic concepts of the language.
113
114
115
116
117
118<h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
119
120<p>
121Lua is a dynamically typed language.
122This means that
123variables do not have types; only values do.
124There are no type definitions in the language.
125All values carry their own type.
126
127
128<p>
129All values in Lua are first-class values.
130This means that all values can be stored in variables,
131passed as arguments to other functions, and returned as results.
132
133
134<p>
135There are eight basic types in Lua:
136<em>nil</em>, <em>boolean</em>, <em>number</em>,
137<em>string</em>, <em>function</em>, <em>userdata</em>,
138<em>thread</em>, and <em>table</em>.
139The type <em>nil</em> has one single value, <b>nil</b>,
140whose main property is to be different from any other value;
141it often represents the absence of a useful value.
142The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>.
143Both <b>nil</b> and <b>false</b> make a condition false;
144they are collectively called <em>false values</em>.
145Any other value makes a condition true.
146Despite its name,
147<b>false</b> is frequently used as an alternative to <b>nil</b>,
148with the key difference that <b>false</b> behaves
149like a regular value in a table,
150while a <b>nil</b> in a table represents an absent key.
151
152
153<p>
154The type <em>number</em> represents both
155integer numbers and real (floating-point) numbers,
156using two subtypes: <em>integer</em> and <em>float</em>.
157Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
158but you can also compile Lua so that it
159uses 32-bit integers and/or single-precision (32-bit) floats.
160The option with 32 bits for both integers and floats
161is particularly attractive
162for small machines and embedded systems.
163(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
164
165
166<p>
167Unless stated otherwise,
168any overflow when manipulating integer values <em>wrap around</em>,
169according to the usual rules of two-complement arithmetic.
170(In other words,
171the actual result is the unique representable integer
172that is equal modulo <em>2<sup>n</sup></em> to the mathematical result,
173where <em>n</em> is the number of bits of the integer type.)
174
175
176<p>
177Lua has explicit rules about when each subtype is used,
178but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
179Therefore,
180the programmer may choose to mostly ignore the difference
181between integers and floats
182or to assume complete control over the representation of each number.
183
184
185<p>
186The type <em>string</em> represents immutable sequences of bytes.
187
188Lua is 8-bit clean:
189strings can contain any 8-bit value,
190including embedded zeros ('<code>\0</code>').
191Lua is also encoding-agnostic;
192it makes no assumptions about the contents of a string.
193The length of any string in Lua must fit in a Lua integer.
194
195
196<p>
197Lua can call (and manipulate) functions written in Lua and
198functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
199Both are represented by the type <em>function</em>.
200
201
202<p>
203The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
204be stored in Lua variables.
205A userdata value represents a block of raw memory.
206There are two kinds of userdata:
207<em>full userdata</em>,
208which is an object with a block of memory managed by Lua,
209and <em>light userdata</em>,
210which is simply a C&nbsp;pointer value.
211Userdata has no predefined operations in Lua,
212except assignment and identity test.
213By using <em>metatables</em>,
214the programmer can define operations for full userdata values
215(see <a href="#2.4">&sect;2.4</a>).
216Userdata values cannot be created or modified in Lua,
217only through the C&nbsp;API.
218This guarantees the integrity of data owned by
219the host program and C&nbsp;libraries.
220
221
222<p>
223The type <em>thread</em> represents independent threads of execution
224and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
225Lua threads are not related to operating-system threads.
226Lua supports coroutines on all systems,
227even those that do not support threads natively.
228
229
230<p>
231The type <em>table</em> implements associative arrays,
232that is, arrays that can have as indices not only numbers,
233but any Lua value except <b>nil</b> and NaN.
234(<em>Not a Number</em> is a special floating-point value
235used by the IEEE 754 standard to represent
236undefined numerical results, such as <code>0/0</code>.)
237Tables can be <em>heterogeneous</em>;
238that is, they can contain values of all types (except <b>nil</b>).
239Any key associated to the value <b>nil</b> is not considered part of the table.
240Conversely, any key that is not part of a table has
241an associated value <b>nil</b>.
242
243
244<p>
245Tables are the sole data-structuring mechanism in Lua;
246they can be used to represent ordinary arrays, lists,
247symbol tables, sets, records, graphs, trees, etc.
248To represent records, Lua uses the field name as an index.
249The language supports this representation by
250providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
251There are several convenient ways to create tables in Lua
252(see <a href="#3.4.9">&sect;3.4.9</a>).
253
254
255<p>
256Like indices,
257the values of table fields can be of any type.
258In particular,
259because functions are first-class values,
260table fields can contain functions.
261Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
262
263
264<p>
265The indexing of tables follows
266the definition of raw equality in the language.
267The expressions <code>a[i]</code> and <code>a[j]</code>
268denote the same table element
269if and only if <code>i</code> and <code>j</code> are raw equal
270(that is, equal without metamethods).
271In particular, floats with integral values
272are equal to their respective integers
273(e.g., <code>1.0 == 1</code>).
274To avoid ambiguities,
275any float used as a key that is equal to an integer
276is converted to that integer.
277For instance, if you write <code>a[2.0] = true</code>,
278the actual key inserted into the table will be the integer <code>2</code>.
279
280
281<p>
282Tables, functions, threads, and (full) userdata values are <em>objects</em>:
283variables do not actually <em>contain</em> these values,
284only <em>references</em> to them.
285Assignment, parameter passing, and function returns
286always manipulate references to such values;
287these operations do not imply any kind of copy.
288
289
290<p>
291The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
292of a given value (see <a href="#pdf-type"><code>type</code></a>).
293
294
295
296
297
298<h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
299
300<p>
301As we will discuss further in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
302any reference to a free name
303(that is, a name not bound to any declaration) <code>var</code>
304is syntactically translated to <code>_ENV.var</code>.
305Moreover, every chunk is compiled in the scope of
306an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
307so <code>_ENV</code> itself is never a free name in a chunk.
308
309
310<p>
311Despite the existence of this external <code>_ENV</code> variable and
312the translation of free names,
313<code>_ENV</code> is a completely regular name.
314In particular,
315you can define new variables and parameters with that name.
316Each reference to a free name uses the <code>_ENV</code> that is
317visible at that point in the program,
318following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
319
320
321<p>
322Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
323
324
325<p>
326Lua keeps a distinguished environment called the <em>global environment</em>.
327This value is kept at a special index in the C registry (see <a href="#4.3">&sect;4.3</a>).
328In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
329(<a href="#pdf-_G"><code>_G</code></a> is never used internally,
330so changing its value will affect only your own code.)
331
332
333<p>
334When Lua loads a chunk,
335the default value for its <code>_ENV</code> variable
336is the global environment (see <a href="#pdf-load"><code>load</code></a>).
337Therefore, by default,
338free names in Lua code refer to entries in the global environment
339and, therefore, they are also called <em>global variables</em>.
340Moreover, all standard libraries are loaded in the global environment
341and some functions there operate on that environment.
342You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
343to load a chunk with a different environment.
344(In C, you have to load the chunk and then change the value
345of its first upvalue; see <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.)
346
347
348
349
350
351<h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
352
353<p>
354Several operations in Lua can <em>raise</em> an error.
355An error interrupts the normal flow of the program,
356which can continue by <em>catching</em> the error.
357
358
359<p>
360Lua code can explicitly raise an error by calling the
361<a href="#pdf-error"><code>error</code></a> function.
362(This function never returns.)
363
364
365<p>
366To catch errors in Lua,
367you can do a <em>protected call</em>,
368using <a href="#pdf-pcall"><code>pcall</code></a> (or <a href="#pdf-xpcall"><code>xpcall</code></a>).
369The function <a href="#pdf-pcall"><code>pcall</code></a> calls a given function in <em>protected mode</em>.
370Any error while running the function stops its execution,
371and control returns immediately to <code>pcall</code>,
372which returns a status code.
373
374
375<p>
376Because Lua is an embedded extension language,
377Lua code starts running by a call
378from C&nbsp;code in the host program.
379(When you use Lua standalone,
380the <code>lua</code> application is the host program.)
381Usually, this call is protected;
382so, when an otherwise unprotected error occurs during
383the compilation or execution of a Lua chunk,
384control returns to the host,
385which can take appropriate measures,
386such as printing an error message.
387
388
389<p>
390Whenever there is an error,
391an <em>error object</em>
392is propagated with information about the error.
393Lua itself only generates errors whose error object is a string,
394but programs may generate errors with
395any value as the error object.
396It is up to the Lua program or its host to handle such error objects.
397For historical reasons,
398an error object is often called an <em>error message</em>,
399even though it does not have to be a string.
400
401
402<p>
403When you use <a href="#pdf-xpcall"><code>xpcall</code></a> (or <a href="#lua_pcall"><code>lua_pcall</code></a>, in C)
404you may give a <em>message handler</em>
405to be called in case of errors.
406This function is called with the original error object
407and returns a new error object.
408It is called before the error unwinds the stack,
409so that it can gather more information about the error,
410for instance by inspecting the stack and creating a stack traceback.
411This message handler is still protected by the protected call;
412so, an error inside the message handler
413will call the message handler again.
414If this loop goes on for too long,
415Lua breaks it and returns an appropriate message.
416The message handler is called only for regular runtime errors.
417It is not called for memory-allocation errors
418nor for errors while running finalizers or other message handlers.
419
420
421<p>
422Lua also offers a system of <em>warnings</em> (see <a href="#pdf-warn"><code>warn</code></a>).
423Unlike errors, warnings do not interfere
424in any way with program execution.
425They typically only generate a message to the user,
426although this behavior can be adapted from C (see <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>).
427
428
429
430
431
432<h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
433
434<p>
435Every value in Lua can have a <em>metatable</em>.
436This <em>metatable</em> is an ordinary Lua table
437that defines the behavior of the original value
438under certain events.
439You can change several aspects of the behavior
440of a value by setting specific fields in its metatable.
441For instance, when a non-numeric value is the operand of an addition,
442Lua checks for a function in the field <code>__add</code> of the value's metatable.
443If it finds one,
444Lua calls this function to perform the addition.
445
446
447<p>
448The key for each event in a metatable is a string
449with the event name prefixed by two underscores;
450the corresponding value is called a <em>metavalue</em>.
451For most events, the metavalue must be a function,
452which is then called a <em>metamethod</em>.
453In the previous example, the key is the string "<code>__add</code>"
454and the metamethod is the function that performs the addition.
455Unless stated otherwise,
456a metamethod may in fact be any callable value,
457which is either a function or a value with a <code>__call</code> metamethod.
458
459
460<p>
461You can query the metatable of any value
462using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
463Lua queries metamethods in metatables using a raw access (see <a href="#pdf-rawget"><code>rawget</code></a>).
464
465
466<p>
467You can replace the metatable of tables
468using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
469You cannot change the metatable of other types from Lua code,
470except by using the debug library (<a href="#6.10">&sect;6.10</a>).
471
472
473<p>
474Tables and full userdata have individual metatables,
475although multiple tables and userdata can share their metatables.
476Values of all other types share one single metatable per type;
477that is, there is one single metatable for all numbers,
478one for all strings, etc.
479By default, a value has no metatable,
480but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
481
482
483<p>
484A detailed list of operations controlled by metatables is given next.
485Each event is identified by its corresponding key.
486By convention, all metatable keys used by Lua are composed by
487two underscores followed by lowercase Latin letters.
488
489
490
491<ul>
492
493<li><b><code>__add</code>: </b>
494the addition (<code>+</code>) operation.
495If any operand for an addition is not a number,
496Lua will try to call a metamethod.
497It starts by checking the first operand (even if it is a number);
498if that operand does not define a metamethod for <code>__add</code>,
499then Lua will check the second operand.
500If Lua can find a metamethod,
501it calls the metamethod with the two operands as arguments,
502and the result of the call
503(adjusted to one value)
504is the result of the operation.
505Otherwise, if no metamethod is found,
506Lua raises an error.
507</li>
508
509<li><b><code>__sub</code>: </b>
510the subtraction (<code>-</code>) operation.
511Behavior similar to the addition operation.
512</li>
513
514<li><b><code>__mul</code>: </b>
515the multiplication (<code>*</code>) operation.
516Behavior similar to the addition operation.
517</li>
518
519<li><b><code>__div</code>: </b>
520the division (<code>/</code>) operation.
521Behavior similar to the addition operation.
522</li>
523
524<li><b><code>__mod</code>: </b>
525the modulo (<code>%</code>) operation.
526Behavior similar to the addition operation.
527</li>
528
529<li><b><code>__pow</code>: </b>
530the exponentiation (<code>^</code>) operation.
531Behavior similar to the addition operation.
532</li>
533
534<li><b><code>__unm</code>: </b>
535the negation (unary <code>-</code>) operation.
536Behavior similar to the addition operation.
537</li>
538
539<li><b><code>__idiv</code>: </b>
540the floor division (<code>//</code>) operation.
541Behavior similar to the addition operation.
542</li>
543
544<li><b><code>__band</code>: </b>
545the bitwise AND (<code>&amp;</code>) operation.
546Behavior similar to the addition operation,
547except that Lua will try a metamethod
548if any operand is neither an integer
549nor a float coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
550</li>
551
552<li><b><code>__bor</code>: </b>
553the bitwise OR (<code>|</code>) operation.
554Behavior similar to the bitwise AND operation.
555</li>
556
557<li><b><code>__bxor</code>: </b>
558the bitwise exclusive OR (binary <code>~</code>) operation.
559Behavior similar to the bitwise AND operation.
560</li>
561
562<li><b><code>__bnot</code>: </b>
563the bitwise NOT (unary <code>~</code>) operation.
564Behavior similar to the bitwise AND operation.
565</li>
566
567<li><b><code>__shl</code>: </b>
568the bitwise left shift (<code>&lt;&lt;</code>) operation.
569Behavior similar to the bitwise AND operation.
570</li>
571
572<li><b><code>__shr</code>: </b>
573the bitwise right shift (<code>&gt;&gt;</code>) operation.
574Behavior similar to the bitwise AND operation.
575</li>
576
577<li><b><code>__concat</code>: </b>
578the concatenation (<code>..</code>) operation.
579Behavior similar to the addition operation,
580except that Lua will try a metamethod
581if any operand is neither a string nor a number
582(which is always coercible to a string).
583</li>
584
585<li><b><code>__len</code>: </b>
586the length (<code>#</code>) operation.
587If the object is not a string,
588Lua will try its metamethod.
589If there is a metamethod,
590Lua calls it with the object as argument,
591and the result of the call
592(always adjusted to one value)
593is the result of the operation.
594If there is no metamethod but the object is a table,
595then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
596Otherwise, Lua raises an error.
597</li>
598
599<li><b><code>__eq</code>: </b>
600the equal (<code>==</code>) operation.
601Behavior similar to the addition operation,
602except that Lua will try a metamethod only when the values
603being compared are either both tables or both full userdata
604and they are not primitively equal.
605The result of the call is always converted to a boolean.
606</li>
607
608<li><b><code>__lt</code>: </b>
609the less than (<code>&lt;</code>) operation.
610Behavior similar to the addition operation,
611except that Lua will try a metamethod only when the values
612being compared are neither both numbers nor both strings.
613Moreover, the result of the call is always converted to a boolean.
614</li>
615
616<li><b><code>__le</code>: </b>
617the less equal (<code>&lt;=</code>) operation.
618Behavior similar to the less than operation.
619</li>
620
621<li><b><code>__index</code>: </b>
622The indexing access operation <code>table[key]</code>.
623This event happens when <code>table</code> is not a table or
624when <code>key</code> is not present in <code>table</code>.
625The metavalue is looked up in the metatable of <code>table</code>.
626
627
628<p>
629The metavalue for this event can be either a function, a table,
630or any value with an <code>__index</code> metavalue.
631If it is a function,
632it is called with <code>table</code> and <code>key</code> as arguments,
633and the result of the call
634(adjusted to one value)
635is the result of the operation.
636Otherwise,
637the final result is the result of indexing this metavalue with <code>key</code>.
638This indexing is regular, not raw,
639and therefore can trigger another <code>__index</code> metavalue.
640</li>
641
642<li><b><code>__newindex</code>: </b>
643The indexing assignment <code>table[key] = value</code>.
644Like the index event,
645this event happens when <code>table</code> is not a table or
646when <code>key</code> is not present in <code>table</code>.
647The metavalue is looked up in the metatable of <code>table</code>.
648
649
650<p>
651Like with indexing,
652the metavalue for this event can be either a function, a table,
653or any value with an <code>__newindex</code> metavalue.
654If it is a function,
655it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
656Otherwise,
657Lua repeats the indexing assignment over this metavalue
658with the same key and value.
659This assignment is regular, not raw,
660and therefore can trigger another <code>__newindex</code> metavalue.
661
662
663<p>
664Whenever a <code>__newindex</code> metavalue is invoked,
665Lua does not perform the primitive assignment.
666If needed,
667the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
668to do the assignment.
669</li>
670
671<li><b><code>__call</code>: </b>
672The call operation <code>func(args)</code>.
673This event happens when Lua tries to call a non-function value
674(that is, <code>func</code> is not a function).
675The metamethod is looked up in <code>func</code>.
676If present,
677the metamethod is called with <code>func</code> as its first argument,
678followed by the arguments of the original call (<code>args</code>).
679All results of the call
680are the results of the operation.
681This is the only metamethod that allows multiple results.
682</li>
683
684</ul>
685
686<p>
687In addition to the previous list,
688the interpreter also respects the following keys in metatables:
689<code>__gc</code> (see <a href="#2.5.3">&sect;2.5.3</a>),
690<code>__close</code> (see <a href="#3.3.8">&sect;3.3.8</a>),
691<code>__mode</code> (see <a href="#2.5.4">&sect;2.5.4</a>),
692and <code>__name</code>.
693(The entry <code>__name</code>,
694when it contains a string,
695may be used by <a href="#pdf-tostring"><code>tostring</code></a> and in error messages.)
696
697
698<p>
699For the unary operators (negation, length, and bitwise NOT),
700the metamethod is computed and called with a dummy second operand,
701equal to the first one.
702This extra operand is only to simplify Lua's internals
703(by making these operators behave like a binary operation)
704and may be removed in future versions.
705For most uses this extra operand is irrelevant.
706
707
708<p>
709Because metatables are regular tables,
710they can contain arbitrary fields,
711not only the event names defined above.
712Some functions in the standard library
713(e.g., <a href="#pdf-tostring"><code>tostring</code></a>)
714use other fields in metatables for their own purposes.
715
716
717<p>
718It is a good practice to add all needed metamethods to a table
719before setting it as a metatable of some object.
720In particular, the <code>__gc</code> metamethod works only when this order
721is followed (see <a href="#2.5.3">&sect;2.5.3</a>).
722It is also a good practice to set the metatable of an object
723right after its creation.
724
725
726
727
728
729<h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
730
731
732
733<p>
734Lua performs automatic memory management.
735This means that
736you do not have to worry about allocating memory for new objects
737or freeing it when the objects are no longer needed.
738Lua manages memory automatically by running
739a <em>garbage collector</em> to collect all <em>dead</em> objects.
740All memory used by Lua is subject to automatic management:
741strings, tables, userdata, functions, threads, internal structures, etc.
742
743
744<p>
745An object is considered <em>dead</em>
746as soon as the collector can be sure the object
747will not be accessed again in the normal execution of the program.
748("Normal execution" here excludes finalizers,
749which can resurrect dead objects (see <a href="#2.5.3">&sect;2.5.3</a>),
750and excludes also operations using the debug library.)
751Note that the time when the collector can be sure that an object
752is dead may not coincide with the programmer's expectations.
753The only guarantees are that Lua will not collect an object
754that may still be accessed in the normal execution of the program,
755and it will eventually collect an object
756that is inaccessible from Lua.
757(Here,
758<em>inaccessible from Lua</em> means that neither a variable nor
759another live object refer to the object.)
760Because Lua has no knowledge about C&nbsp;code,
761it never collects objects accessible through the registry (see <a href="#4.3">&sect;4.3</a>),
762which includes the global environment (see <a href="#2.2">&sect;2.2</a>).
763
764
765<p>
766The garbage collector (GC) in Lua can work in two modes:
767incremental and generational.
768
769
770<p>
771The default GC mode with the default parameters
772are adequate for most uses.
773However, programs that waste a large proportion of their time
774allocating and freeing memory can benefit from other settings.
775Keep in mind that the GC behavior is non-portable
776both across platforms and across different Lua releases;
777therefore, optimal settings are also non-portable.
778
779
780<p>
781You can change the GC mode and parameters by calling
782<a href="#lua_gc"><code>lua_gc</code></a> in&nbsp;C
783or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
784You can also use these functions to control
785the collector directly (e.g., to stop and restart it).
786
787
788
789
790
791<h3>2.5.1 &ndash; <a name="2.5.1">Incremental Garbage Collection</a></h3>
792
793<p>
794In incremental mode,
795each GC cycle performs a mark-and-sweep collection in small steps
796interleaved with the program's execution.
797In this mode,
798the collector uses three numbers to control its garbage-collection cycles:
799the <em>garbage-collector pause</em>,
800the <em>garbage-collector step multiplier</em>,
801and the <em>garbage-collector step size</em>.
802
803
804<p>
805The garbage-collector pause
806controls how long the collector waits before starting a new cycle.
807The collector starts a new cycle when the use of memory
808hits <em>n%</em> of the use after the previous collection.
809Larger values make the collector less aggressive.
810Values equal to or less than 100 mean the collector will not wait to
811start a new cycle.
812A value of 200 means that the collector waits for the total memory in use
813to double before starting a new cycle.
814The default value is 200; the maximum value is 1000.
815
816
817<p>
818The garbage-collector step multiplier
819controls the speed of the collector relative to
820memory allocation,
821that is,
822how many elements it marks or sweeps for each
823kilobyte of memory allocated.
824Larger values make the collector more aggressive but also increase
825the size of each incremental step.
826You should not use values less than 100,
827because they make the collector too slow and
828can result in the collector never finishing a cycle.
829The default value is 100;  the maximum value is 1000.
830
831
832<p>
833The garbage-collector step size controls the
834size of each incremental step,
835specifically how many bytes the interpreter allocates
836before performing a step.
837This parameter is logarithmic:
838A value of <em>n</em> means the interpreter will allocate <em>2<sup>n</sup></em>
839bytes between steps and perform equivalent work during the step.
840A large value (e.g., 60) makes the collector a stop-the-world
841(non-incremental) collector.
842The default value is 13,
843which means steps of approximately 8&nbsp;Kbytes.
844
845
846
847
848
849<h3>2.5.2 &ndash; <a name="2.5.2">Generational Garbage Collection</a></h3>
850
851<p>
852In generational mode,
853the collector does frequent <em>minor</em> collections,
854which traverses only objects recently created.
855If after a minor collection the use of memory is still above a limit,
856the collector does a stop-the-world <em>major</em> collection,
857which traverses all objects.
858The generational mode uses two parameters:
859the <em>minor multiplier</em> and the <em>the major multiplier</em>.
860
861
862<p>
863The minor multiplier controls the frequency of minor collections.
864For a minor multiplier <em>x</em>,
865a new minor collection will be done when memory
866grows <em>x%</em> larger than the memory in use after the previous major
867collection.
868For instance, for a multiplier of 20,
869the collector will do a minor collection when the use of memory
870gets 20% larger than the use after the previous major collection.
871The default value is 20; the maximum value is 200.
872
873
874<p>
875The major multiplier controls the frequency of major collections.
876For a major multiplier <em>x</em>,
877a new major collection will be done when memory
878grows <em>x%</em> larger than the memory in use after the previous major
879collection.
880For instance, for a multiplier of 100,
881the collector will do a major collection when the use of memory
882gets larger than twice the use after the previous collection.
883The default value is 100; the maximum value is 1000.
884
885
886
887
888
889<h3>2.5.3 &ndash; <a name="2.5.3">Garbage-Collection Metamethods</a></h3>
890
891<p>
892You can set garbage-collector metamethods for tables
893and, using the C&nbsp;API,
894for full userdata (see <a href="#2.4">&sect;2.4</a>).
895These metamethods, called <em>finalizers</em>,
896are called when the garbage collector detects that the
897corresponding table or userdata is dead.
898Finalizers allow you to coordinate Lua's garbage collection
899with external resource management such as closing files,
900network or database connections,
901or freeing your own memory.
902
903
904<p>
905For an object (table or userdata) to be finalized when collected,
906you must <em>mark</em> it for finalization.
907
908You mark an object for finalization when you set its metatable
909and the metatable has a <code>__gc</code> metamethod.
910Note that if you set a metatable without a <code>__gc</code> field
911and later create that field in the metatable,
912the object will not be marked for finalization.
913
914
915<p>
916When a marked object becomes dead,
917it is not collected immediately by the garbage collector.
918Instead, Lua puts it in a list.
919After the collection,
920Lua goes through that list.
921For each object in the list,
922it checks the object's <code>__gc</code> metamethod:
923If it is present,
924Lua calls it with the object as its single argument.
925
926
927<p>
928At the end of each garbage-collection cycle,
929the finalizers are called in
930the reverse order that the objects were marked for finalization,
931among those collected in that cycle;
932that is, the first finalizer to be called is the one associated
933with the object marked last in the program.
934The execution of each finalizer may occur at any point during
935the execution of the regular code.
936
937
938<p>
939Because the object being collected must still be used by the finalizer,
940that object (and other objects accessible only through it)
941must be <em>resurrected</em> by Lua.
942Usually, this resurrection is transient,
943and the object memory is freed in the next garbage-collection cycle.
944However, if the finalizer stores the object in some global place
945(e.g., a global variable),
946then the resurrection is permanent.
947Moreover, if the finalizer marks a finalizing object for finalization again,
948its finalizer will be called again in the next cycle where the
949object is dead.
950In any case,
951the object memory is freed only in a GC cycle where
952the object is dead and not marked for finalization.
953
954
955<p>
956When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
957Lua calls the finalizers of all objects marked for finalization,
958following the reverse order that they were marked.
959If any finalizer marks objects for collection during that phase,
960these marks have no effect.
961
962
963<p>
964Finalizers cannot yield nor run the garbage collector.
965Because they can run in unpredictable times,
966it is good practice to restrict each finalizer
967to the minimum necessary to properly release
968its associated resource.
969
970
971<p>
972Any error while running a finalizer generates a warning;
973the error is not propagated.
974
975
976
977
978
979<h3>2.5.4 &ndash; <a name="2.5.4">Weak Tables</a></h3>
980
981<p>
982A <em>weak table</em> is a table whose elements are
983<em>weak references</em>.
984A weak reference is ignored by the garbage collector.
985In other words,
986if the only references to an object are weak references,
987then the garbage collector will collect that object.
988
989
990<p>
991A weak table can have weak keys, weak values, or both.
992A table with weak values allows the collection of its values,
993but prevents the collection of its keys.
994A table with both weak keys and weak values allows the collection of
995both keys and values.
996In any case, if either the key or the value is collected,
997the whole pair is removed from the table.
998The weakness of a table is controlled by the
999<code>__mode</code> field of its metatable.
1000This metavalue, if present, must be one of the following strings:
1001"<code>k</code>", for a table with weak keys;
1002"<code>v</code>", for a table with weak values;
1003or "<code>kv</code>", for a table with both weak keys and values.
1004
1005
1006<p>
1007A table with weak keys and strong values
1008is also called an <em>ephemeron table</em>.
1009In an ephemeron table,
1010a value is considered reachable only if its key is reachable.
1011In particular,
1012if the only reference to a key comes through its value,
1013the pair is removed.
1014
1015
1016<p>
1017Any change in the weakness of a table may take effect only
1018at the next collect cycle.
1019In particular, if you change the weakness to a stronger mode,
1020Lua may still collect some items from that table
1021before the change takes effect.
1022
1023
1024<p>
1025Only objects that have an explicit construction
1026are removed from weak tables.
1027Values, such as numbers and light C&nbsp;functions,
1028are not subject to garbage collection,
1029and therefore are not removed from weak tables
1030(unless their associated values are collected).
1031Although strings are subject to garbage collection,
1032they do not have an explicit construction and
1033their equality is by value;
1034they behave more like values than like objects.
1035Therefore, they are not removed from weak tables.
1036
1037
1038<p>
1039Resurrected objects
1040(that is, objects being finalized
1041and objects accessible only through objects being finalized)
1042have a special behavior in weak tables.
1043They are removed from weak values before running their finalizers,
1044but are removed from weak keys only in the next collection
1045after running their finalizers, when such objects are actually freed.
1046This behavior allows the finalizer to access properties
1047associated with the object through weak tables.
1048
1049
1050<p>
1051If a weak table is among the resurrected objects in a collection cycle,
1052it may not be properly cleared until the next cycle.
1053
1054
1055
1056
1057
1058
1059
1060<h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
1061
1062<p>
1063Lua supports coroutines,
1064also called <em>collaborative multithreading</em>.
1065A coroutine in Lua represents an independent thread of execution.
1066Unlike threads in multithread systems, however,
1067a coroutine only suspends its execution by explicitly calling
1068a yield function.
1069
1070
1071<p>
1072You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1073Its sole argument is a function
1074that is the main function of the coroutine.
1075The <code>create</code> function only creates a new coroutine and
1076returns a handle to it (an object of type <em>thread</em>);
1077it does not start the coroutine.
1078
1079
1080<p>
1081You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1082When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1083passing as its first argument
1084a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1085the coroutine starts its execution by
1086calling its main function.
1087Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
1088as arguments to that function.
1089After the coroutine starts running,
1090it runs until it terminates or <em>yields</em>.
1091
1092
1093<p>
1094A coroutine can terminate its execution in two ways:
1095normally, when its main function returns
1096(explicitly or implicitly, after the last instruction);
1097and abnormally, if there is an unprotected error.
1098In case of normal termination,
1099<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1100plus any values returned by the coroutine main function.
1101In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1102plus the error object.
1103In this case, the coroutine does not unwind its stack,
1104so that it is possible to inspect it after the error
1105with the debug API.
1106
1107
1108<p>
1109A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1110When a coroutine yields,
1111the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1112even if the yield happens inside nested function calls
1113(that is, not in the main function,
1114but in a function directly or indirectly called by the main function).
1115In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1116plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1117The next time you resume the same coroutine,
1118it continues its execution from the point where it yielded,
1119with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1120arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1121
1122
1123<p>
1124Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1125the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1126but instead of returning the coroutine itself,
1127it returns a function that, when called, resumes the coroutine.
1128Any arguments passed to this function
1129go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1130<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>,
1131except the first one (the boolean error code).
1132Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1133the function created by <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>
1134propagates any error to the caller.
1135In this case,
1136the function also closes the coroutine (see <a href="#pdf-coroutine.close"><code>coroutine.close</code></a>).
1137
1138
1139<p>
1140As an example of how coroutines work,
1141consider the following code:
1142
1143<pre>
1144     function foo (a)
1145       print("foo", a)
1146       return coroutine.yield(2*a)
1147     end
1148
1149     co = coroutine.create(function (a,b)
1150           print("co-body", a, b)
1151           local r = foo(a+1)
1152           print("co-body", r)
1153           local r, s = coroutine.yield(a+b, a-b)
1154           print("co-body", r, s)
1155           return b, "end"
1156     end)
1157
1158     print("main", coroutine.resume(co, 1, 10))
1159     print("main", coroutine.resume(co, "r"))
1160     print("main", coroutine.resume(co, "x", "y"))
1161     print("main", coroutine.resume(co, "x", "y"))
1162</pre><p>
1163When you run it, it produces the following output:
1164
1165<pre>
1166     co-body 1       10
1167     foo     2
1168     main    true    4
1169     co-body r
1170     main    true    11      -9
1171     co-body x       y
1172     main    true    10      end
1173     main    false   cannot resume dead coroutine
1174</pre>
1175
1176<p>
1177You can also create and manipulate coroutines through the C API:
1178see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1179and <a href="#lua_yield"><code>lua_yield</code></a>.
1180
1181
1182
1183
1184
1185<h1>3 &ndash; <a name="3">The Language</a></h1>
1186
1187
1188
1189<p>
1190This section describes the lexis, the syntax, and the semantics of Lua.
1191In other words,
1192this section describes
1193which tokens are valid,
1194how they can be combined,
1195and what their combinations mean.
1196
1197
1198<p>
1199Language constructs will be explained using the usual extended BNF notation,
1200in which
1201{<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1202[<em>a</em>]&nbsp;means an optional <em>a</em>.
1203Non-terminals are shown like non-terminal,
1204keywords are shown like <b>kword</b>,
1205and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1206The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1207at the end of this manual.
1208
1209
1210
1211
1212
1213<h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1214
1215<p>
1216Lua is a free-form language.
1217It ignores spaces and comments between lexical elements (tokens),
1218except as delimiters between two tokens.
1219In source code,
1220Lua recognizes as spaces the standard ASCII whitespace
1221characters space, form feed, newline,
1222carriage return, horizontal tab, and vertical tab.
1223
1224
1225<p>
1226<em>Names</em>
1227(also called <em>identifiers</em>)
1228in Lua can be any string of Latin letters,
1229Arabic-Indic digits, and underscores,
1230not beginning with a digit and
1231not being a reserved word.
1232Identifiers are used to name variables, table fields, and labels.
1233
1234
1235<p>
1236The following <em>keywords</em> are reserved
1237and cannot be used as names:
1238
1239
1240<pre>
1241     and       break     do        else      elseif    end
1242     false     for       function  goto      if        in
1243     local     nil       not       or        repeat    return
1244     then      true      until     while
1245</pre>
1246
1247<p>
1248Lua is a case-sensitive language:
1249<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1250are two different, valid names.
1251As a convention,
1252programs should avoid creating
1253names that start with an underscore followed by
1254one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1255
1256
1257<p>
1258The following strings denote other tokens:
1259
1260<pre>
1261     +     -     *     /     %     ^     #
1262     &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
1263     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
1264     (     )     {     }     [     ]     ::
1265     ;     :     ,     .     ..    ...
1266</pre>
1267
1268<p>
1269A <em>short literal string</em>
1270can be delimited by matching single or double quotes,
1271and can contain the following C-like escape sequences:
1272'<code>\a</code>' (bell),
1273'<code>\b</code>' (backspace),
1274'<code>\f</code>' (form feed),
1275'<code>\n</code>' (newline),
1276'<code>\r</code>' (carriage return),
1277'<code>\t</code>' (horizontal tab),
1278'<code>\v</code>' (vertical tab),
1279'<code>\\</code>' (backslash),
1280'<code>\"</code>' (quotation mark [double quote]),
1281and '<code>\'</code>' (apostrophe [single quote]).
1282A backslash followed by a line break
1283results in a newline in the string.
1284The escape sequence '<code>\z</code>' skips the following span
1285of whitespace characters,
1286including line breaks;
1287it is particularly useful to break and indent a long literal string
1288into multiple lines without adding the newlines and spaces
1289into the string contents.
1290A short literal string cannot contain unescaped line breaks
1291nor escapes not forming a valid escape sequence.
1292
1293
1294<p>
1295We can specify any byte in a short literal string,
1296including embedded zeros,
1297by its numeric value.
1298This can be done
1299with the escape sequence <code>\x<em>XX</em></code>,
1300where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1301or with the escape sequence <code>\<em>ddd</em></code>,
1302where <em>ddd</em> is a sequence of up to three decimal digits.
1303(Note that if a decimal escape sequence is to be followed by a digit,
1304it must be expressed using exactly three digits.)
1305
1306
1307<p>
1308The UTF-8 encoding of a Unicode character
1309can be inserted in a literal string with
1310the escape sequence <code>\u{<em>XXX</em>}</code>
1311(with mandatory enclosing braces),
1312where <em>XXX</em> is a sequence of one or more hexadecimal digits
1313representing the character code point.
1314This code point can be any value less than <em>2<sup>31</sup></em>.
1315(Lua uses the original UTF-8 specification here,
1316which is not restricted to valid Unicode code points.)
1317
1318
1319<p>
1320Literal strings can also be defined using a long format
1321enclosed by <em>long brackets</em>.
1322We define an <em>opening long bracket of level <em>n</em></em> as an opening
1323square bracket followed by <em>n</em> equal signs followed by another
1324opening square bracket.
1325So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1326an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1327and so on.
1328A <em>closing long bracket</em> is defined similarly;
1329for instance,
1330a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
1331A <em>long literal</em> starts with an opening long bracket of any level and
1332ends at the first closing long bracket of the same level.
1333It can contain any text except a closing bracket of the same level.
1334Literals in this bracketed form can run for several lines,
1335do not interpret any escape sequences,
1336and ignore long brackets of any other level.
1337Any kind of end-of-line sequence
1338(carriage return, newline, carriage return followed by newline,
1339or newline followed by carriage return)
1340is converted to a simple newline.
1341When the opening long bracket is immediately followed by a newline,
1342the newline is not included in the string.
1343
1344
1345<p>
1346As an example, in a system using ASCII
1347(in which '<code>a</code>' is coded as&nbsp;97,
1348newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1349the five literal strings below denote the same string:
1350
1351<pre>
1352     a = 'alo\n123"'
1353     a = "alo\n123\""
1354     a = '\97lo\10\04923"'
1355     a = [[alo
1356     123"]]
1357     a = [==[
1358     alo
1359     123"]==]
1360</pre>
1361
1362<p>
1363Any byte in a literal string not
1364explicitly affected by the previous rules represents itself.
1365However, Lua opens files for parsing in text mode,
1366and the system's file functions may have problems with
1367some control characters.
1368So, it is safer to represent
1369binary data as a quoted literal with
1370explicit escape sequences for the non-text characters.
1371
1372
1373<p>
1374A <em>numeric constant</em> (or <em>numeral</em>)
1375can be written with an optional fractional part
1376and an optional decimal exponent,
1377marked by a letter '<code>e</code>' or '<code>E</code>'.
1378Lua also accepts hexadecimal constants,
1379which start with <code>0x</code> or <code>0X</code>.
1380Hexadecimal constants also accept an optional fractional part
1381plus an optional binary exponent,
1382marked by a letter '<code>p</code>' or '<code>P</code>' and written in decimal.
1383(For instance, <code>0x1.fp10</code> denotes 1984,
1384which is <em>0x1f / 16</em> multiplied by <em>2<sup>10</sup></em>.)
1385
1386
1387<p>
1388A numeric constant with a radix point or an exponent
1389denotes a float;
1390otherwise,
1391if its value fits in an integer or it is a hexadecimal constant,
1392it denotes an integer;
1393otherwise (that is, a decimal integer numeral that overflows),
1394it denotes a float.
1395Hexadecimal numerals with neither a radix point nor an exponent
1396always denote an integer value;
1397if the value overflows, it <em>wraps around</em>
1398to fit into a valid integer.
1399
1400
1401<p>
1402Examples of valid integer constants are
1403
1404<pre>
1405     3   345   0xff   0xBEBADA
1406</pre><p>
1407Examples of valid float constants are
1408
1409<pre>
1410     3.0     3.1416     314.16e-2     0.31416E1     34e1
1411     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
1412</pre>
1413
1414<p>
1415A <em>comment</em> starts with a double hyphen (<code>--</code>)
1416anywhere outside a string.
1417If the text immediately after <code>--</code> is not an opening long bracket,
1418the comment is a <em>short comment</em>,
1419which runs until the end of the line.
1420Otherwise, it is a <em>long comment</em>,
1421which runs until the corresponding closing long bracket.
1422
1423
1424
1425
1426
1427<h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1428
1429<p>
1430Variables are places that store values.
1431There are three kinds of variables in Lua:
1432global variables, local variables, and table fields.
1433
1434
1435<p>
1436A single name can denote a global variable or a local variable
1437(or a function's formal parameter,
1438which is a particular kind of local variable):
1439
1440<pre>
1441	var ::= Name
1442</pre><p>
1443Name denotes identifiers (see <a href="#3.1">&sect;3.1</a>).
1444
1445
1446<p>
1447Any variable name is assumed to be global unless explicitly declared
1448as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1449Local variables are <em>lexically scoped</em>:
1450local variables can be freely accessed by functions
1451defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1452
1453
1454<p>
1455Before the first assignment to a variable, its value is <b>nil</b>.
1456
1457
1458<p>
1459Square brackets are used to index a table:
1460
1461<pre>
1462	var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1463</pre><p>
1464The meaning of accesses to table fields can be changed via metatables
1465(see <a href="#2.4">&sect;2.4</a>).
1466
1467
1468<p>
1469The syntax <code>var.Name</code> is just syntactic sugar for
1470<code>var["Name"]</code>:
1471
1472<pre>
1473	var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1474</pre>
1475
1476<p>
1477An access to a global variable <code>x</code>
1478is equivalent to <code>_ENV.x</code>.
1479Due to the way that chunks are compiled,
1480the variable <code>_ENV</code> itself is never global (see <a href="#2.2">&sect;2.2</a>).
1481
1482
1483
1484
1485
1486<h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1487
1488
1489
1490<p>
1491Lua supports an almost conventional set of statements,
1492similar to those in other conventional languages.
1493This set includes
1494blocks, assignments, control structures, function calls,
1495and variable declarations.
1496
1497
1498
1499
1500
1501<h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1502
1503<p>
1504A block is a list of statements,
1505which are executed sequentially:
1506
1507<pre>
1508	block ::= {stat}
1509</pre><p>
1510Lua has <em>empty statements</em>
1511that allow you to separate statements with semicolons,
1512start a block with a semicolon
1513or write two semicolons in sequence:
1514
1515<pre>
1516	stat ::= &lsquo;<b>;</b>&rsquo;
1517</pre>
1518
1519<p>
1520Both function calls and assignments
1521can start with an open parenthesis.
1522This possibility leads to an ambiguity in Lua's grammar.
1523Consider the following fragment:
1524
1525<pre>
1526     a = b + c
1527     (print or io.write)('done')
1528</pre><p>
1529The grammar could see this fragment in two ways:
1530
1531<pre>
1532     a = b + c(print or io.write)('done')
1533
1534     a = b + c; (print or io.write)('done')
1535</pre><p>
1536The current parser always sees such constructions
1537in the first way,
1538interpreting the open parenthesis
1539as the start of the arguments to a call.
1540To avoid this ambiguity,
1541it is a good practice to always precede with a semicolon
1542statements that start with a parenthesis:
1543
1544<pre>
1545     ;(print or io.write)('done')
1546</pre>
1547
1548<p>
1549A block can be explicitly delimited to produce a single statement:
1550
1551<pre>
1552	stat ::= <b>do</b> block <b>end</b>
1553</pre><p>
1554Explicit blocks are useful
1555to control the scope of variable declarations.
1556Explicit blocks are also sometimes used to
1557add a <b>return</b> statement in the middle
1558of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1559
1560
1561
1562
1563
1564<h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1565
1566<p>
1567The unit of compilation of Lua is called a <em>chunk</em>.
1568Syntactically,
1569a chunk is simply a block:
1570
1571<pre>
1572	chunk ::= block
1573</pre>
1574
1575<p>
1576Lua handles a chunk as the body of an anonymous function
1577with a variable number of arguments
1578(see <a href="#3.4.11">&sect;3.4.11</a>).
1579As such, chunks can define local variables,
1580receive arguments, and return values.
1581Moreover, such anonymous function is compiled as in the
1582scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1583The resulting function always has <code>_ENV</code> as its only external variable,
1584even if it does not use that variable.
1585
1586
1587<p>
1588A chunk can be stored in a file or in a string inside the host program.
1589To execute a chunk,
1590Lua first <em>loads</em> it,
1591precompiling the chunk's code into instructions for a virtual machine,
1592and then Lua executes the compiled code
1593with an interpreter for the virtual machine.
1594
1595
1596<p>
1597Chunks can also be precompiled into binary form;
1598see the program <code>luac</code> and the function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1599Programs in source and compiled forms are interchangeable;
1600Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1601
1602
1603
1604
1605
1606<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1607
1608<p>
1609Lua allows multiple assignments.
1610Therefore, the syntax for assignment
1611defines a list of variables on the left side
1612and a list of expressions on the right side.
1613The elements in both lists are separated by commas:
1614
1615<pre>
1616	stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1617	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1618	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1619</pre><p>
1620Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1621
1622
1623<p>
1624Before the assignment,
1625the list of values is <em>adjusted</em> to the length of
1626the list of variables (see <a href="#3.4.12">&sect;3.4.12</a>).
1627
1628
1629<p>
1630If a variable is both assigned and read
1631inside a multiple assignment,
1632Lua ensures that all reads get the value of the variable
1633before the assignment.
1634Thus the code
1635
1636<pre>
1637     i = 3
1638     i, a[i] = i+1, 20
1639</pre><p>
1640sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1641because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1642before it is assigned&nbsp;4.
1643Similarly, the line
1644
1645<pre>
1646     x, y = y, x
1647</pre><p>
1648exchanges the values of <code>x</code> and <code>y</code>,
1649and
1650
1651<pre>
1652     x, y, z = y, z, x
1653</pre><p>
1654cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1655
1656
1657<p>
1658Note that this guarantee covers only accesses
1659syntactically inside the assignment statement.
1660If a function or a metamethod called during the assignment
1661changes the value of a variable,
1662Lua gives no guarantees about the order of that access.
1663
1664
1665<p>
1666An assignment to a global name <code>x = val</code>
1667is equivalent to the assignment
1668<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1669
1670
1671<p>
1672The meaning of assignments to table fields and
1673global variables (which are actually table fields, too)
1674can be changed via metatables (see <a href="#2.4">&sect;2.4</a>).
1675
1676
1677
1678
1679
1680<h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1681The control structures
1682<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1683familiar syntax:
1684
1685
1686
1687
1688<pre>
1689	stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1690	stat ::= <b>repeat</b> block <b>until</b> exp
1691	stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1692</pre><p>
1693Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1694
1695
1696<p>
1697The condition expression of a
1698control structure can return any value.
1699Both <b>false</b> and <b>nil</b> test false.
1700All values different from <b>nil</b> and <b>false</b> test true.
1701In particular, the number 0 and the empty string also test true.
1702
1703
1704<p>
1705In the <b>repeat</b>&ndash;<b>until</b> loop,
1706the inner block does not end at the <b>until</b> keyword,
1707but only after the condition.
1708So, the condition can refer to local variables
1709declared inside the loop block.
1710
1711
1712<p>
1713The <b>goto</b> statement transfers the program control to a label.
1714For syntactical reasons,
1715labels in Lua are considered statements too:
1716
1717
1718
1719<pre>
1720	stat ::= <b>goto</b> Name
1721	stat ::= label
1722	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1723</pre>
1724
1725<p>
1726A label is visible in the entire block where it is defined,
1727except inside nested functions.
1728A goto may jump to any visible label as long as it does not
1729enter into the scope of a local variable.
1730A label should not be declared
1731where a label with the same name is visible,
1732even if this other label has been declared in an enclosing block.
1733
1734
1735<p>
1736The <b>break</b> statement terminates the execution of a
1737<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1738skipping to the next statement after the loop:
1739
1740
1741<pre>
1742	stat ::= <b>break</b>
1743</pre><p>
1744A <b>break</b> ends the innermost enclosing loop.
1745
1746
1747<p>
1748The <b>return</b> statement is used to return values
1749from a function or a chunk
1750(which is handled as an anonymous function).
1751
1752Functions can return more than one value,
1753so the syntax for the <b>return</b> statement is
1754
1755<pre>
1756	stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1757</pre>
1758
1759<p>
1760The <b>return</b> statement can only be written
1761as the last statement of a block.
1762If it is necessary to <b>return</b> in the middle of a block,
1763then an explicit inner block can be used,
1764as in the idiom <code>do return end</code>,
1765because now <b>return</b> is the last statement in its (inner) block.
1766
1767
1768
1769
1770
1771<h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1772
1773<p>
1774
1775The <b>for</b> statement has two forms:
1776one numerical and one generic.
1777
1778
1779
1780<h4>The numerical <b>for</b> loop</h4>
1781
1782<p>
1783The numerical <b>for</b> loop repeats a block of code while a
1784control variable goes through an arithmetic progression.
1785It has the following syntax:
1786
1787<pre>
1788	stat ::= <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b>
1789</pre><p>
1790The given identifier (Name) defines the control variable,
1791which is a new variable local to the loop body (<em>block</em>).
1792
1793
1794<p>
1795The loop starts by evaluating once the three control expressions.
1796Their values are called respectively
1797the <em>initial value</em>, the <em>limit</em>, and the <em>step</em>.
1798If the step is absent, it defaults to&nbsp;1.
1799
1800
1801<p>
1802If both the initial value and the step are integers,
1803the loop is done with integers;
1804note that the limit may not be an integer.
1805Otherwise, the three values are converted to
1806floats and the loop is done with floats.
1807Beware of floating-point accuracy in this case.
1808
1809
1810<p>
1811After that initialization,
1812the loop body is repeated with the value of the control variable
1813going through an arithmetic progression,
1814starting at the initial value,
1815with a common difference given by the step.
1816A negative step makes a decreasing sequence;
1817a step equal to zero raises an error.
1818The loop continues while the value is less than
1819or equal to the limit
1820(greater than or equal to for a negative step).
1821If the initial value is already greater than the limit
1822(or less than, if the step is negative),
1823the body is not executed.
1824
1825
1826<p>
1827For integer loops,
1828the control variable never wraps around;
1829instead, the loop ends in case of an overflow.
1830
1831
1832<p>
1833You should not change the value of the control variable
1834during the loop.
1835If you need its value after the loop,
1836assign it to another variable before exiting the loop.
1837
1838
1839
1840
1841
1842<h4>The generic <b>for</b> loop</h4>
1843
1844<p>
1845The generic <b>for</b> statement works over functions,
1846called <em>iterators</em>.
1847On each iteration, the iterator function is called to produce a new value,
1848stopping when this new value is <b>nil</b>.
1849The generic <b>for</b> loop has the following syntax:
1850
1851<pre>
1852	stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1853	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1854</pre><p>
1855A <b>for</b> statement like
1856
1857<pre>
1858     for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>body</em> end
1859</pre><p>
1860works as follows.
1861
1862
1863<p>
1864The names <em>var_i</em> declare loop variables local to the loop body.
1865The first of these variables is the <em>control variable</em>.
1866
1867
1868<p>
1869The loop starts by evaluating <em>explist</em>
1870to produce four values:
1871an <em>iterator function</em>,
1872a <em>state</em>,
1873an initial value for the control variable,
1874and a <em>closing value</em>.
1875
1876
1877<p>
1878Then, at each iteration,
1879Lua calls the iterator function with two arguments:
1880the state and the control variable.
1881The results from this call are then assigned to the loop variables,
1882following the rules of multiple assignments (see <a href="#3.3.3">&sect;3.3.3</a>).
1883If the control variable becomes <b>nil</b>,
1884the loop terminates.
1885Otherwise, the body is executed and the loop goes
1886to the next iteration.
1887
1888
1889<p>
1890The closing value behaves like a
1891to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>),
1892which can be used to release resources when the loop ends.
1893Otherwise, it does not interfere with the loop.
1894
1895
1896<p>
1897You should not change the value of the control variable
1898during the loop.
1899
1900
1901
1902
1903
1904
1905
1906<h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1907To allow possible side-effects,
1908function calls can be executed as statements:
1909
1910<pre>
1911	stat ::= functioncall
1912</pre><p>
1913In this case, all returned values are thrown away.
1914Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1915
1916
1917
1918
1919
1920<h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1921Local variables can be declared anywhere inside a block.
1922The declaration can include an initialization:
1923
1924<pre>
1925	stat ::= <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
1926	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
1927</pre><p>
1928If present, an initial assignment has the same semantics
1929of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1930Otherwise, all variables are initialized with <b>nil</b>.
1931
1932
1933<p>
1934Each variable name may be postfixed by an attribute
1935(a name between angle brackets):
1936
1937<pre>
1938	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
1939</pre><p>
1940There are two possible attributes:
1941<code>const</code>, which declares a constant variable,
1942that is, a variable that cannot be assigned to
1943after its initialization;
1944and <code>close</code>, which declares a to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>).
1945A list of variables can contain at most one to-be-closed variable.
1946
1947
1948<p>
1949A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1950and so local variables can be declared in a chunk outside any explicit block.
1951
1952
1953<p>
1954The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1955
1956
1957
1958
1959
1960<h3>3.3.8 &ndash; <a name="3.3.8">To-be-closed Variables</a></h3>
1961
1962<p>
1963A to-be-closed variable behaves like a constant local variable,
1964except that its value is <em>closed</em> whenever the variable
1965goes out of scope, including normal block termination,
1966exiting its block by <b>break</b>/<b>goto</b>/<b>return</b>,
1967or exiting by an error.
1968
1969
1970<p>
1971Here, to <em>close</em> a value means
1972to call its <code>__close</code> metamethod.
1973When calling the metamethod,
1974the value itself is passed as the first argument
1975and the error object that caused the exit (if any)
1976is passed as a second argument;
1977if there was no error, the second argument is <b>nil</b>.
1978
1979
1980<p>
1981The value assigned to a to-be-closed variable
1982must have a <code>__close</code> metamethod
1983or be a false value.
1984(<b>nil</b> and <b>false</b> are ignored as to-be-closed values.)
1985
1986
1987<p>
1988If several to-be-closed variables go out of scope at the same event,
1989they are closed in the reverse order that they were declared.
1990
1991
1992<p>
1993If there is any error while running a closing method,
1994that error is handled like an error in the regular code
1995where the variable was defined.
1996After an error,
1997the other pending closing methods will still be called.
1998
1999
2000<p>
2001If a coroutine yields and is never resumed again,
2002some variables may never go out of scope,
2003and therefore they will never be closed.
2004(These variables are the ones created inside the coroutine
2005and in scope at the point where the coroutine yielded.)
2006Similarly, if a coroutine ends with an error,
2007it does not unwind its stack,
2008so it does not close any variable.
2009In both cases,
2010you can either use finalizers
2011or call <a href="#pdf-coroutine.close"><code>coroutine.close</code></a> to close the variables.
2012However, if the coroutine was created
2013through <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>,
2014then its corresponding function will close the coroutine
2015in case of errors.
2016
2017
2018
2019
2020
2021
2022
2023<h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
2024
2025
2026
2027<p>
2028The basic expressions in Lua are the following:
2029
2030<pre>
2031	exp ::= prefixexp
2032	exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
2033	exp ::= Numeral
2034	exp ::= LiteralString
2035	exp ::= functiondef
2036	exp ::= tableconstructor
2037	exp ::= &lsquo;<b>...</b>&rsquo;
2038	exp ::= exp binop exp
2039	exp ::= unop exp
2040	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
2041</pre>
2042
2043<p>
2044Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
2045variables are explained in <a href="#3.2">&sect;3.2</a>;
2046function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
2047function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
2048table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
2049Vararg expressions,
2050denoted by three dots ('<code>...</code>'), can only be used when
2051directly inside a variadic function;
2052they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
2053
2054
2055<p>
2056Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
2057bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
2058relational operators (see <a href="#3.4.4">&sect;3.4.4</a>), logical operators (see <a href="#3.4.5">&sect;3.4.5</a>),
2059and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
2060Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
2061the unary bitwise NOT (see <a href="#3.4.2">&sect;3.4.2</a>),
2062the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
2063and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
2064
2065
2066
2067
2068
2069<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
2070Lua supports the following arithmetic operators:
2071
2072<ul>
2073<li><b><code>+</code>: </b>addition</li>
2074<li><b><code>-</code>: </b>subtraction</li>
2075<li><b><code>*</code>: </b>multiplication</li>
2076<li><b><code>/</code>: </b>float division</li>
2077<li><b><code>//</code>: </b>floor division</li>
2078<li><b><code>%</code>: </b>modulo</li>
2079<li><b><code>^</code>: </b>exponentiation</li>
2080<li><b><code>-</code>: </b>unary minus</li>
2081</ul>
2082
2083<p>
2084With the exception of exponentiation and float division,
2085the arithmetic operators work as follows:
2086If both operands are integers,
2087the operation is performed over integers and the result is an integer.
2088Otherwise, if both operands are numbers,
2089then they are converted to floats,
2090the operation is performed following the machine's rules
2091for floating-point arithmetic
2092(usually the IEEE 754 standard),
2093and the result is a float.
2094(The string library coerces strings to numbers in
2095arithmetic operations; see <a href="#3.4.3">&sect;3.4.3</a> for details.)
2096
2097
2098<p>
2099Exponentiation and float division (<code>/</code>)
2100always convert their operands to floats
2101and the result is always a float.
2102Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
2103so that it works for non-integer exponents too.
2104
2105
2106<p>
2107Floor division (<code>//</code>) is a division
2108that rounds the quotient towards minus infinity,
2109resulting in the floor of the division of its operands.
2110
2111
2112<p>
2113Modulo is defined as the remainder of a division
2114that rounds the quotient towards minus infinity (floor division).
2115
2116
2117<p>
2118In case of overflows in integer arithmetic,
2119all operations <em>wrap around</em>.
2120
2121
2122
2123<h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
2124Lua supports the following bitwise operators:
2125
2126<ul>
2127<li><b><code>&amp;</code>: </b>bitwise AND</li>
2128<li><b><code>&#124;</code>: </b>bitwise OR</li>
2129<li><b><code>~</code>: </b>bitwise exclusive OR</li>
2130<li><b><code>&gt;&gt;</code>: </b>right shift</li>
2131<li><b><code>&lt;&lt;</code>: </b>left shift</li>
2132<li><b><code>~</code>: </b>unary bitwise NOT</li>
2133</ul>
2134
2135<p>
2136All bitwise operations convert its operands to integers
2137(see <a href="#3.4.3">&sect;3.4.3</a>),
2138operate on all bits of those integers,
2139and result in an integer.
2140
2141
2142<p>
2143Both right and left shifts fill the vacant bits with zeros.
2144Negative displacements shift to the other direction;
2145displacements with absolute values equal to or higher than
2146the number of bits in an integer
2147result in zero (as all bits are shifted out).
2148
2149
2150
2151
2152
2153<h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
2154Lua provides some automatic conversions between some
2155types and representations at run time.
2156Bitwise operators always convert float operands to integers.
2157Exponentiation and float division
2158always convert integer operands to floats.
2159All other arithmetic operations applied to mixed numbers
2160(integers and floats) convert the integer operand to a float.
2161The C API also converts both integers to floats and
2162floats to integers, as needed.
2163Moreover, string concatenation accepts numbers as arguments,
2164besides strings.
2165
2166
2167<p>
2168In a conversion from integer to float,
2169if the integer value has an exact representation as a float,
2170that is the result.
2171Otherwise,
2172the conversion gets the nearest higher or
2173the nearest lower representable value.
2174This kind of conversion never fails.
2175
2176
2177<p>
2178The conversion from float to integer
2179checks whether the float has an exact representation as an integer
2180(that is, the float has an integral value and
2181it is in the range of integer representation).
2182If it does, that representation is the result.
2183Otherwise, the conversion fails.
2184
2185
2186<p>
2187Several places in Lua coerce strings to numbers when necessary.
2188In particular,
2189the string library sets metamethods that try to coerce
2190strings to numbers in all arithmetic operations.
2191If the conversion fails,
2192the library calls the metamethod of the other operand
2193(if present) or it raises an error.
2194Note that bitwise operators do not do this coercion.
2195
2196
2197<p>
2198It is always a good practice not to rely on the
2199implicit coercions from strings to numbers,
2200as they are not always applied;
2201in particular, <code>"1"==1</code> is false and <code>"1"&lt;1</code> raises an error
2202(see <a href="#3.4.4">&sect;3.4.4</a>).
2203These coercions exist mainly for compatibility and may be removed
2204in future versions of the language.
2205
2206
2207<p>
2208A string is converted to an integer or a float
2209following its syntax and the rules of the Lua lexer.
2210The string may have also leading and trailing whitespaces and a sign.
2211All conversions from strings to numbers
2212accept both a dot and the current locale mark
2213as the radix character.
2214(The Lua lexer, however, accepts only a dot.)
2215If the string is not a valid numeral,
2216the conversion fails.
2217If necessary, the result of this first step is then converted
2218to a specific number subtype following the previous rules
2219for conversions between floats and integers.
2220
2221
2222<p>
2223The conversion from numbers to strings uses a
2224non-specified human-readable format.
2225To convert numbers to strings in any specific way,
2226use the function <a href="#pdf-string.format"><code>string.format</code></a>.
2227
2228
2229
2230
2231
2232<h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
2233Lua supports the following relational operators:
2234
2235<ul>
2236<li><b><code>==</code>: </b>equality</li>
2237<li><b><code>~=</code>: </b>inequality</li>
2238<li><b><code>&lt;</code>: </b>less than</li>
2239<li><b><code>&gt;</code>: </b>greater than</li>
2240<li><b><code>&lt;=</code>: </b>less or equal</li>
2241<li><b><code>&gt;=</code>: </b>greater or equal</li>
2242</ul><p>
2243These operators always result in <b>false</b> or <b>true</b>.
2244
2245
2246<p>
2247Equality (<code>==</code>) first compares the type of its operands.
2248If the types are different, then the result is <b>false</b>.
2249Otherwise, the values of the operands are compared.
2250Strings are equal if they have the same byte content.
2251Numbers are equal if they denote the same mathematical value.
2252
2253
2254<p>
2255Tables, userdata, and threads
2256are compared by reference:
2257two objects are considered equal only if they are the same object.
2258Every time you create a new object
2259(a table, a userdata, or a thread),
2260this new object is different from any previously existing object.
2261A function is always equal to itself.
2262Functions with any detectable difference
2263(different behavior, different definition) are always different.
2264Functions created at different times but with no detectable differences
2265may be classified as equal or not
2266(depending on internal caching details).
2267
2268
2269<p>
2270You can change the way that Lua compares tables and userdata
2271by using the <code>__eq</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2272
2273
2274<p>
2275Equality comparisons do not convert strings to numbers
2276or vice versa.
2277Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2278and <code>t[0]</code> and <code>t["0"]</code> denote different
2279entries in a table.
2280
2281
2282<p>
2283The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2284
2285
2286<p>
2287The order operators work as follows.
2288If both arguments are numbers,
2289then they are compared according to their mathematical values,
2290regardless of their subtypes.
2291Otherwise, if both arguments are strings,
2292then their values are compared according to the current locale.
2293Otherwise, Lua tries to call the <code>__lt</code> or the <code>__le</code>
2294metamethod (see <a href="#2.4">&sect;2.4</a>).
2295A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2296and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2297
2298
2299<p>
2300Following the IEEE 754 standard,
2301the special value NaN is considered neither less than,
2302nor equal to, nor greater than any value, including itself.
2303
2304
2305
2306
2307
2308<h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2309The logical operators in Lua are
2310<b>and</b>, <b>or</b>, and <b>not</b>.
2311Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2312all logical operators consider both <b>false</b> and <b>nil</b> as false
2313and anything else as true.
2314
2315
2316<p>
2317The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2318The conjunction operator <b>and</b> returns its first argument
2319if this value is <b>false</b> or <b>nil</b>;
2320otherwise, <b>and</b> returns its second argument.
2321The disjunction operator <b>or</b> returns its first argument
2322if this value is different from <b>nil</b> and <b>false</b>;
2323otherwise, <b>or</b> returns its second argument.
2324Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2325that is,
2326the second operand is evaluated only if necessary.
2327Here are some examples:
2328
2329<pre>
2330     10 or 20            --&gt; 10
2331     10 or error()       --&gt; 10
2332     nil or "a"          --&gt; "a"
2333     nil and 10          --&gt; nil
2334     false and error()   --&gt; false
2335     false and nil       --&gt; false
2336     false or nil        --&gt; nil
2337     10 and 20           --&gt; 20
2338</pre>
2339
2340
2341
2342
2343<h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2344The string concatenation operator in Lua is
2345denoted by two dots ('<code>..</code>').
2346If both operands are strings or numbers,
2347then the numbers are converted to strings
2348in a non-specified format (see <a href="#3.4.3">&sect;3.4.3</a>).
2349Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2350
2351
2352
2353
2354
2355<h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2356
2357<p>
2358The length operator is denoted by the unary prefix operator <code>#</code>.
2359
2360
2361<p>
2362The length of a string is its number of bytes.
2363(That is the usual meaning of string length when each
2364character is one byte.)
2365
2366
2367<p>
2368The length operator applied on a table
2369returns a border in that table.
2370A <em>border</em> in a table <code>t</code> is any non-negative integer
2371that satisfies the following condition:
2372
2373<pre>
2374     (border == 0 or t[border] ~= nil) and
2375     (t[border + 1] == nil or border == math.maxinteger)
2376</pre><p>
2377In words,
2378a border is any positive integer index present in the table
2379that is followed by an absent index,
2380plus two limit cases:
2381zero, when index 1 is absent;
2382and the maximum value for an integer, when that index is present.
2383Note that keys that are not positive integers
2384do not interfere with borders.
2385
2386
2387<p>
2388A table with exactly one border is called a <em>sequence</em>.
2389For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence,
2390as it has only one border (5).
2391The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5),
2392and therefore it is not a sequence.
2393(The <b>nil</b> at index 4 is called a <em>hole</em>.)
2394The table <code>{nil, 20, 30, nil, nil, 60, nil}</code>
2395has three borders (0, 3, and 6),
2396so it is not a sequence, too.
2397The table <code>{}</code> is a sequence with border 0.
2398
2399
2400<p>
2401When <code>t</code> is a sequence,
2402<code>#t</code> returns its only border,
2403which corresponds to the intuitive notion of the length of the sequence.
2404When <code>t</code> is not a sequence,
2405<code>#t</code> can return any of its borders.
2406(The exact one depends on details of
2407the internal representation of the table,
2408which in turn can depend on how the table was populated and
2409the memory addresses of its non-numeric keys.)
2410
2411
2412<p>
2413The computation of the length of a table
2414has a guaranteed worst time of <em>O(log n)</em>,
2415where <em>n</em> is the largest integer key in the table.
2416
2417
2418<p>
2419A program can modify the behavior of the length operator for
2420any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2421
2422
2423
2424
2425
2426<h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2427Operator precedence in Lua follows the table below,
2428from lower to higher priority:
2429
2430<pre>
2431     or
2432     and
2433     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2434     |
2435     ~
2436     &amp;
2437     &lt;&lt;    &gt;&gt;
2438     ..
2439     +     -
2440     *     /     //    %
2441     unary operators (not   #     -     ~)
2442     ^
2443</pre><p>
2444As usual,
2445you can use parentheses to change the precedences of an expression.
2446The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2447operators are right associative.
2448All other binary operators are left associative.
2449
2450
2451
2452
2453
2454<h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2455Table constructors are expressions that create tables.
2456Every time a constructor is evaluated, a new table is created.
2457A constructor can be used to create an empty table
2458or to create a table and initialize some of its fields.
2459The general syntax for constructors is
2460
2461<pre>
2462	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2463	fieldlist ::= field {fieldsep field} [fieldsep]
2464	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2465	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2466</pre>
2467
2468<p>
2469Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2470with key <code>exp1</code> and value <code>exp2</code>.
2471A field of the form <code>name = exp</code> is equivalent to
2472<code>["name"] = exp</code>.
2473Fields of the form <code>exp</code> are equivalent to
2474<code>[i] = exp</code>, where <code>i</code> are consecutive integers
2475starting with 1;
2476fields in the other formats do not affect this counting.
2477For example,
2478
2479<pre>
2480     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2481</pre><p>
2482is equivalent to
2483
2484<pre>
2485     do
2486       local t = {}
2487       t[f(1)] = g
2488       t[1] = "x"         -- 1st exp
2489       t[2] = "y"         -- 2nd exp
2490       t.x = 1            -- t["x"] = 1
2491       t[3] = f(x)        -- 3rd exp
2492       t[30] = 23
2493       t[4] = 45          -- 4th exp
2494       a = t
2495     end
2496</pre>
2497
2498<p>
2499The order of the assignments in a constructor is undefined.
2500(This order would be relevant only when there are repeated keys.)
2501
2502
2503<p>
2504If the last field in the list has the form <code>exp</code>
2505and the expression is a multires expression,
2506then all values returned by this expression enter the list consecutively
2507(see <a href="#3.4.12">&sect;3.4.12</a>).
2508
2509
2510<p>
2511The field list can have an optional trailing separator,
2512as a convenience for machine-generated code.
2513
2514
2515
2516
2517
2518<h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2519A function call in Lua has the following syntax:
2520
2521<pre>
2522	functioncall ::= prefixexp args
2523</pre><p>
2524In a function call,
2525first prefixexp and args are evaluated.
2526If the value of prefixexp has type <em>function</em>,
2527then this function is called
2528with the given arguments.
2529Otherwise, if present,
2530the prefixexp <code>__call</code> metamethod is called:
2531its first argument is the value of prefixexp,
2532followed by the original call arguments
2533(see <a href="#2.4">&sect;2.4</a>).
2534
2535
2536<p>
2537The form
2538
2539<pre>
2540	functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2541</pre><p>
2542can be used to emulate methods.
2543A call <code>v:name(<em>args</em>)</code>
2544is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2545except that <code>v</code> is evaluated only once.
2546
2547
2548<p>
2549Arguments have the following syntax:
2550
2551<pre>
2552	args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2553	args ::= tableconstructor
2554	args ::= LiteralString
2555</pre><p>
2556All argument expressions are evaluated before the call.
2557A call of the form <code>f{<em>fields</em>}</code> is
2558syntactic sugar for <code>f({<em>fields</em>})</code>;
2559that is, the argument list is a single new table.
2560A call of the form <code>f'<em>string</em>'</code>
2561(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2562is syntactic sugar for <code>f('<em>string</em>')</code>;
2563that is, the argument list is a single literal string.
2564
2565
2566<p>
2567A call of the form <code>return <em>functioncall</em></code> not in the
2568scope of a to-be-closed variable is called a <em>tail call</em>.
2569Lua implements <em>proper tail calls</em>
2570(or <em>proper tail recursion</em>):
2571In a tail call,
2572the called function reuses the stack entry of the calling function.
2573Therefore, there is no limit on the number of nested tail calls that
2574a program can execute.
2575However, a tail call erases any debug information about the
2576calling function.
2577Note that a tail call only happens with a particular syntax,
2578where the <b>return</b> has one single function call as argument,
2579and it is outside the scope of any to-be-closed variable.
2580This syntax makes the calling function return exactly
2581the returns of the called function,
2582without any intervening action.
2583So, none of the following examples are tail calls:
2584
2585<pre>
2586     return (f(x))        -- results adjusted to 1
2587     return 2 * f(x)      -- result multiplied by 2
2588     return x, f(x)       -- additional results
2589     f(x); return         -- results discarded
2590     return x or f(x)     -- results adjusted to 1
2591</pre>
2592
2593
2594
2595
2596<h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2597
2598<p>
2599The syntax for function definition is
2600
2601<pre>
2602	functiondef ::= <b>function</b> funcbody
2603	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2604</pre>
2605
2606<p>
2607The following syntactic sugar simplifies function definitions:
2608
2609<pre>
2610	stat ::= <b>function</b> funcname funcbody
2611	stat ::= <b>local</b> <b>function</b> Name funcbody
2612	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2613</pre><p>
2614The statement
2615
2616<pre>
2617     function f () <em>body</em> end
2618</pre><p>
2619translates to
2620
2621<pre>
2622     f = function () <em>body</em> end
2623</pre><p>
2624The statement
2625
2626<pre>
2627     function t.a.b.c.f () <em>body</em> end
2628</pre><p>
2629translates to
2630
2631<pre>
2632     t.a.b.c.f = function () <em>body</em> end
2633</pre><p>
2634The statement
2635
2636<pre>
2637     local function f () <em>body</em> end
2638</pre><p>
2639translates to
2640
2641<pre>
2642     local f; f = function () <em>body</em> end
2643</pre><p>
2644not to
2645
2646<pre>
2647     local f = function () <em>body</em> end
2648</pre><p>
2649(This only makes a difference when the body of the function
2650contains references to <code>f</code>.)
2651
2652
2653<p>
2654A function definition is an executable expression,
2655whose value has type <em>function</em>.
2656When Lua precompiles a chunk,
2657all its function bodies are precompiled too,
2658but they are not created yet.
2659Then, whenever Lua executes the function definition,
2660the function is <em>instantiated</em> (or <em>closed</em>).
2661This function instance, or <em>closure</em>,
2662is the final value of the expression.
2663
2664
2665<p>
2666Parameters act as local variables that are
2667initialized with the argument values:
2668
2669<pre>
2670	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2671</pre><p>
2672When a Lua function is called,
2673it adjusts its list of arguments to
2674the length of its list of parameters (see <a href="#3.4.12">&sect;3.4.12</a>),
2675unless the function is a <em>variadic function</em>,
2676which is indicated by three dots ('<code>...</code>')
2677at the end of its parameter list.
2678A variadic function does not adjust its argument list;
2679instead, it collects all extra arguments and supplies them
2680to the function through a <em>vararg expression</em>,
2681which is also written as three dots.
2682The value of this expression is a list of all actual extra arguments,
2683similar to a function with multiple results (see <a href="#3.4.12">&sect;3.4.12</a>).
2684
2685
2686<p>
2687As an example, consider the following definitions:
2688
2689<pre>
2690     function f(a, b) end
2691     function g(a, b, ...) end
2692     function r() return 1,2,3 end
2693</pre><p>
2694Then, we have the following mapping from arguments to parameters and
2695to the vararg expression:
2696
2697<pre>
2698     CALL             PARAMETERS
2699
2700     f(3)             a=3, b=nil
2701     f(3, 4)          a=3, b=4
2702     f(3, 4, 5)       a=3, b=4
2703     f(r(), 10)       a=1, b=10
2704     f(r())           a=1, b=2
2705
2706     g(3)             a=3, b=nil, ... --&gt;  (nothing)
2707     g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
2708     g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
2709     g(5, r())        a=5, b=1,   ... --&gt;  2  3
2710</pre>
2711
2712<p>
2713Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2714If control reaches the end of a function
2715without encountering a <b>return</b> statement,
2716then the function returns with no results.
2717
2718
2719<p>
2720
2721There is a system-dependent limit on the number of values
2722that a function may return.
2723This limit is guaranteed to be greater than 1000.
2724
2725
2726<p>
2727The <em>colon</em> syntax
2728is used to emulate <em>methods</em>,
2729adding an implicit extra parameter <code>self</code> to the function.
2730Thus, the statement
2731
2732<pre>
2733     function t.a.b.c:f (<em>params</em>) <em>body</em> end
2734</pre><p>
2735is syntactic sugar for
2736
2737<pre>
2738     t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2739</pre>
2740
2741
2742
2743
2744<h3>3.4.12 &ndash; <a name="3.4.12">Lists of expressions, multiple results,
2745and adjustment</a></h3>
2746
2747<p>
2748Both function calls and vararg expressions can result in multiple values.
2749These expressions are called <em>multires expressions</em>.
2750
2751
2752<p>
2753When a multires expression is used as the last element
2754of a list of expressions,
2755all results from the expression are added to the
2756list of values produced by the list of expressions.
2757Note that a single expression
2758in a place that expects a list of expressions
2759is the last expression in that (singleton) list.
2760
2761
2762<p>
2763These are the places where Lua expects a list of expressions:
2764
2765<ul>
2766
2767<li>A <b>return</b> statement,
2768for instance <code>return e1, e2, e3</code> (see <a href="#3.3.4">&sect;3.3.4</a>).</li>
2769
2770<li>A table constructor,
2771for instance <code>{e1, e2, e3}</code> (see <a href="#3.4.9">&sect;3.4.9</a>).</li>
2772
2773<li>The arguments of a function call,
2774for instance <code>foo(e1, e2, e3)</code> (see <a href="#3.4.10">&sect;3.4.10</a>).</li>
2775
2776<li>A multiple assignment,
2777for instance <code>a , b, c = e1, e2, e3</code> (see <a href="#3.3.3">&sect;3.3.3</a>).</li>
2778
2779<li>A local declaration,
2780for instance <code>local a , b, c = e1, e2, e3</code> (see <a href="#3.3.7">&sect;3.3.7</a>).</li>
2781
2782<li>The initial values in a generic <b>for</b> loop,
2783for instance <code>for k in e1, e2, e3 do ... end</code> (see <a href="#3.3.5">&sect;3.3.5</a>).</li>
2784
2785</ul><p>
2786In the last four cases,
2787the list of values from the list of expressions
2788must be <em>adjusted</em> to a specific length:
2789the number of parameters in a call to a non-variadic function
2790(see <a href="#3.4.11">&sect;3.4.11</a>),
2791the number of variables in a multiple assignment or
2792a local declaration,
2793and exactly four values for a generic <b>for</b> loop.
2794The <em>adjustment</em> follows these rules:
2795If there are more values than needed,
2796the extra values are thrown away;
2797if there are fewer values than needed,
2798the list is extended with <b>nil</b>'s.
2799When the list of expressions ends with a multires expression,
2800all results from that expression enter the list of values
2801before the adjustment.
2802
2803
2804<p>
2805When a multires expression is used
2806in a list of expressions without being the last element,
2807or in a place where the syntax expects a single expression,
2808Lua adjusts the result list of that expression to one element.
2809As a particular case,
2810the syntax expects a single expression inside a parenthesized expression;
2811therefore, adding parentheses around a multires expression
2812forces it to produce exactly one result.
2813
2814
2815<p>
2816We seldom need to use a vararg expression in a place
2817where the syntax expects a single expression.
2818(Usually it is simpler to add a regular parameter before
2819the variadic part and use that parameter.)
2820When there is such a need,
2821we recommend assigning the vararg expression
2822to a single variable and using that variable
2823in its place.
2824
2825
2826<p>
2827Here are some examples of uses of mutlres expressions.
2828In all cases, when the construction needs
2829"the n-th result" and there is no such result,
2830it uses a <b>nil</b>.
2831
2832<pre>
2833     print(x, f())      -- prints x and all results from f().
2834     print(x, (f()))    -- prints x and the first result from f().
2835     print(f(), x)      -- prints the first result from f() and x.
2836     print(1 + f())     -- prints 1 added to the first result from f().
2837     local x = ...      -- x gets the first vararg argument.
2838     x,y = ...          -- x gets the first vararg argument,
2839                        -- y gets the second vararg argument.
2840     x,y,z = w, f()     -- x gets w, y gets the first result from f(),
2841                        -- z gets the second result from f().
2842     x,y,z = f()        -- x gets the first result from f(),
2843                        -- y gets the second result from f(),
2844                        -- z gets the third result from f().
2845     x,y,z = f(), g()   -- x gets the first result from f(),
2846                        -- y gets the first result from g(),
2847                        -- z gets the second result from g().
2848     x,y,z = (f())      -- x gets the first result from f(), y and z get nil.
2849     return f()         -- returns all results from f().
2850     return x, ...      -- returns x and all received vararg arguments.
2851     return x,y,f()     -- returns x, y, and all results from f().
2852     {f()}              -- creates a list with all results from f().
2853     {...}              -- creates a list with all vararg arguments.
2854     {f(), 5}           -- creates a list with the first result from f() and 5.
2855</pre>
2856
2857
2858
2859
2860
2861
2862<h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2863
2864<p>
2865
2866Lua is a lexically scoped language.
2867The scope of a local variable begins at the first statement after
2868its declaration and lasts until the last non-void statement
2869of the innermost block that includes the declaration.
2870(<em>Void statements</em> are labels and empty statements.)
2871Consider the following example:
2872
2873<pre>
2874     x = 10                -- global variable
2875     do                    -- new block
2876       local x = x         -- new 'x', with value 10
2877       print(x)            --&gt; 10
2878       x = x+1
2879       do                  -- another block
2880         local x = x+1     -- another 'x'
2881         print(x)          --&gt; 12
2882       end
2883       print(x)            --&gt; 11
2884     end
2885     print(x)              --&gt; 10  (the global one)
2886</pre>
2887
2888<p>
2889Notice that, in a declaration like <code>local x = x</code>,
2890the new <code>x</code> being declared is not in scope yet,
2891and so the second <code>x</code> refers to the outside variable.
2892
2893
2894<p>
2895Because of the lexical scoping rules,
2896local variables can be freely accessed by functions
2897defined inside their scope.
2898A local variable used by an inner function is called an <em>upvalue</em>
2899(or <em>external local variable</em>, or simply <em>external variable</em>)
2900inside the inner function.
2901
2902
2903<p>
2904Notice that each execution of a <b>local</b> statement
2905defines new local variables.
2906Consider the following example:
2907
2908<pre>
2909     a = {}
2910     local x = 20
2911     for i = 1, 10 do
2912       local y = 0
2913       a[i] = function () y = y + 1; return x + y end
2914     end
2915</pre><p>
2916The loop creates ten closures
2917(that is, ten instances of the anonymous function).
2918Each of these closures uses a different <code>y</code> variable,
2919while all of them share the same <code>x</code>.
2920
2921
2922
2923
2924
2925<h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2926
2927
2928
2929<p>
2930
2931This section describes the C&nbsp;API for Lua, that is,
2932the set of C&nbsp;functions available to the host program to communicate
2933with Lua.
2934All API functions and related types and constants
2935are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2936
2937
2938<p>
2939Even when we use the term "function",
2940any facility in the API may be provided as a macro instead.
2941Except where stated otherwise,
2942all such macros use each of their arguments exactly once
2943(except for the first argument, which is always a Lua state),
2944and so do not generate any hidden side-effects.
2945
2946
2947<p>
2948As in most C&nbsp;libraries,
2949the Lua API functions do not check their arguments
2950for validity or consistency.
2951However, you can change this behavior by compiling Lua
2952with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2953
2954
2955<p>
2956The Lua library is fully reentrant:
2957it has no global variables.
2958It keeps all information it needs in a dynamic structure,
2959called the <em>Lua state</em>.
2960
2961
2962<p>
2963Each Lua state has one or more threads,
2964which correspond to independent, cooperative lines of execution.
2965The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread.
2966(Indirectly, through the thread, it also refers to the
2967Lua state associated to the thread.)
2968
2969
2970<p>
2971A pointer to a thread must be passed as the first argument to
2972every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
2973which creates a Lua state from scratch and returns a pointer
2974to the <em>main thread</em> in the new state.
2975
2976
2977
2978
2979
2980<h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2981
2982
2983
2984<p>
2985Lua uses a <em>virtual stack</em> to pass values to and from C.
2986Each element in this stack represents a Lua value
2987(<b>nil</b>, number, string, etc.).
2988Functions in the API can access this stack through the
2989Lua state parameter that they receive.
2990
2991
2992<p>
2993Whenever Lua calls C, the called function gets a new stack,
2994which is independent of previous stacks and of stacks of
2995C&nbsp;functions that are still active.
2996This stack initially contains any arguments to the C&nbsp;function
2997and it is where the C&nbsp;function can store temporary
2998Lua values and must push its results
2999to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
3000
3001
3002<p>
3003For convenience,
3004most query operations in the API do not follow a strict stack discipline.
3005Instead, they can refer to any element in the stack
3006by using an <em>index</em>:
3007A positive index represents an absolute stack position,
3008starting at&nbsp;1 as the bottom of the stack;
3009a negative index represents an offset relative to the top of the stack.
3010More specifically, if the stack has <em>n</em> elements,
3011then index&nbsp;1 represents the first element
3012(that is, the element that was pushed onto the stack first)
3013and
3014index&nbsp;<em>n</em> represents the last element;
3015index&nbsp;-1 also represents the last element
3016(that is, the element at the&nbsp;top)
3017and index <em>-n</em> represents the first element.
3018
3019
3020
3021
3022
3023<h3>4.1.1 &ndash; <a name="4.1.1">Stack Size</a></h3>
3024
3025<p>
3026When you interact with the Lua API,
3027you are responsible for ensuring consistency.
3028In particular,
3029<em>you are responsible for controlling stack overflow</em>.
3030When you call any API function,
3031you must ensure the stack has enough room to accommodate the results.
3032
3033
3034<p>
3035There is one exception to the above rule:
3036When you call a Lua function
3037without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
3038Lua ensures that the stack has enough space for all results.
3039However, it does not ensure any extra space.
3040So, before pushing anything on the stack after such a call
3041you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
3042
3043
3044<p>
3045Whenever Lua calls C,
3046it ensures that the stack has space for
3047at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra elements;
3048that is, you can safely push up to <code>LUA_MINSTACK</code> values into it.
3049<code>LUA_MINSTACK</code> is defined as 20,
3050so that usually you do not have to worry about stack space
3051unless your code has loops pushing elements onto the stack.
3052Whenever necessary,
3053you can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
3054to ensure that the stack has enough space for pushing new elements.
3055
3056
3057
3058
3059
3060<h3>4.1.2 &ndash; <a name="4.1.2">Valid and Acceptable Indices</a></h3>
3061
3062<p>
3063Any function in the API that receives stack indices
3064works only with <em>valid indices</em> or <em>acceptable indices</em>.
3065
3066
3067<p>
3068A <em>valid index</em> is an index that refers to a
3069position that stores a modifiable Lua value.
3070It comprises stack indices between&nbsp;1 and the stack top
3071(<code>1 &le; abs(index) &le; top</code>)
3072
3073plus <em>pseudo-indices</em>,
3074which represent some positions that are accessible to C&nbsp;code
3075but that are not in the stack.
3076Pseudo-indices are used to access the registry (see <a href="#4.3">&sect;4.3</a>)
3077and the upvalues of a C&nbsp;function (see <a href="#4.2">&sect;4.2</a>).
3078
3079
3080<p>
3081Functions that do not need a specific mutable position,
3082but only a value (e.g., query functions),
3083can be called with acceptable indices.
3084An <em>acceptable index</em> can be any valid index,
3085but it also can be any positive index after the stack top
3086within the space allocated for the stack,
3087that is, indices up to the stack size.
3088(Note that 0 is never an acceptable index.)
3089Indices to upvalues (see <a href="#4.2">&sect;4.2</a>) greater than the real number
3090of upvalues in the current C&nbsp;function are also acceptable (but invalid).
3091Except when noted otherwise,
3092functions in the API work with acceptable indices.
3093
3094
3095<p>
3096Acceptable indices serve to avoid extra tests
3097against the stack top when querying the stack.
3098For instance, a C&nbsp;function can query its third argument
3099without the need to check whether there is a third argument,
3100that is, without the need to check whether 3 is a valid index.
3101
3102
3103<p>
3104For functions that can be called with acceptable indices,
3105any non-valid index is treated as if it
3106contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
3107which behaves like a nil value.
3108
3109
3110
3111
3112
3113<h3>4.1.3 &ndash; <a name="4.1.3">Pointers to strings</a></h3>
3114
3115<p>
3116Several functions in the API return pointers (<code>const char*</code>)
3117to Lua strings in the stack.
3118(See <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3119<a href="#lua_pushstring"><code>lua_pushstring</code></a>, and <a href="#lua_tolstring"><code>lua_tolstring</code></a>.
3120See also <a href="#luaL_checklstring"><code>luaL_checklstring</code></a>, <a href="#luaL_checkstring"><code>luaL_checkstring</code></a>,
3121and <a href="#luaL_tolstring"><code>luaL_tolstring</code></a> in the auxiliary library.)
3122
3123
3124<p>
3125In general,
3126Lua's garbage collection can free or move internal memory
3127and then invalidate pointers to internal strings.
3128To allow a safe use of these pointers,
3129the API guarantees that any pointer to a string in a stack index
3130is valid while the string value at that index is not removed from the stack.
3131(It can be moved to another index, though.)
3132When the index is a pseudo-index (referring to an upvalue),
3133the pointer is valid while the corresponding call is active and
3134the corresponding upvalue is not modified.
3135
3136
3137<p>
3138Some functions in the debug interface
3139also return pointers to strings,
3140namely <a href="#lua_getlocal"><code>lua_getlocal</code></a>, <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
3141<a href="#lua_setlocal"><code>lua_setlocal</code></a>, and <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.
3142For these functions, the pointer is guaranteed to
3143be valid while the caller function is active and
3144the given closure (if one was given) is in the stack.
3145
3146
3147<p>
3148Except for these guarantees,
3149the garbage collector is free to invalidate
3150any pointer to internal strings.
3151
3152
3153
3154
3155
3156
3157
3158<h2>4.2 &ndash; <a name="4.2">C Closures</a></h2>
3159
3160<p>
3161When a C&nbsp;function is created,
3162it is possible to associate some values with it,
3163thus creating a <em>C&nbsp;closure</em>
3164(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
3165these values are called <em>upvalues</em> and are
3166accessible to the function whenever it is called.
3167
3168
3169<p>
3170Whenever a C&nbsp;function is called,
3171its upvalues are located at specific pseudo-indices.
3172These pseudo-indices are produced by the macro
3173<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
3174The first upvalue associated with a function is at index
3175<code>lua_upvalueindex(1)</code>, and so on.
3176Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
3177where <em>n</em> is greater than the number of upvalues of the
3178current function
3179(but not greater than 256,
3180which is one plus the maximum number of upvalues in a closure),
3181produces an acceptable but invalid index.
3182
3183
3184<p>
3185A C&nbsp;closure can also change the values
3186of its corresponding upvalues.
3187
3188
3189
3190
3191
3192<h2>4.3 &ndash; <a name="4.3">Registry</a></h2>
3193
3194<p>
3195Lua provides a <em>registry</em>,
3196a predefined table that can be used by any C&nbsp;code to
3197store whatever Lua values it needs to store.
3198The registry table is always accessible at pseudo-index
3199<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
3200Any C&nbsp;library can store data into this table,
3201but it must take care to choose keys
3202that are different from those used
3203by other libraries, to avoid collisions.
3204Typically, you should use as key a string containing your library name,
3205or a light userdata with the address of a C&nbsp;object in your code,
3206or any Lua object created by your code.
3207As with variable names,
3208string keys starting with an underscore followed by
3209uppercase letters are reserved for Lua.
3210
3211
3212<p>
3213The integer keys in the registry are used
3214by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
3215and by some predefined values.
3216Therefore, integer keys in the registry
3217must not be used for other purposes.
3218
3219
3220<p>
3221When you create a new Lua state,
3222its registry comes with some predefined values.
3223These predefined values are indexed with integer keys
3224defined as constants in <code>lua.h</code>.
3225The following constants are defined:
3226
3227<ul>
3228<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
3229the main thread of the state.
3230(The main thread is the one created together with the state.)
3231</li>
3232
3233<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
3234the global environment.
3235</li>
3236</ul>
3237
3238
3239
3240
3241<h2>4.4 &ndash; <a name="4.4">Error Handling in C</a></h2>
3242
3243
3244
3245<p>
3246Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
3247(Lua will use exceptions if you compile it as C++;
3248search for <code>LUAI_THROW</code> in the source code for details.)
3249When Lua faces any error,
3250such as a memory allocation error or a type error,
3251it <em>raises</em> an error;
3252that is, it does a long jump.
3253A <em>protected environment</em> uses <code>setjmp</code>
3254to set a recovery point;
3255any error jumps to the most recent active recovery point.
3256
3257
3258<p>
3259Inside a C&nbsp;function you can raise an error explicitly
3260by calling <a href="#lua_error"><code>lua_error</code></a>.
3261
3262
3263<p>
3264Most functions in the API can raise an error,
3265for instance due to a memory allocation error.
3266The documentation for each function indicates whether
3267it can raise errors.
3268
3269
3270<p>
3271If an error happens outside any protected environment,
3272Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
3273and then calls <code>abort</code>,
3274thus exiting the host application.
3275Your panic function can avoid this exit by
3276never returning
3277(e.g., doing a long jump to your own recovery point outside Lua).
3278
3279
3280<p>
3281The panic function,
3282as its name implies,
3283is a mechanism of last resort.
3284Programs should avoid it.
3285As a general rule,
3286when a C&nbsp;function is called by Lua with a Lua state,
3287it can do whatever it wants on that Lua state,
3288as it should be already protected.
3289However,
3290when C code operates on other Lua states
3291(e.g., a Lua-state argument to the function,
3292a Lua state stored in the registry, or
3293the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
3294it should use them only in API calls that cannot raise errors.
3295
3296
3297<p>
3298The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
3299in particular, the error object is on the top of the stack.
3300However, there is no guarantee about stack space.
3301To push anything on the stack,
3302the panic function must first check the available space (see <a href="#4.1.1">&sect;4.1.1</a>).
3303
3304
3305
3306
3307
3308<h3>4.4.1 &ndash; <a name="4.4.1">Status Codes</a></h3>
3309
3310<p>
3311Several functions that report errors in the API use the following
3312status codes to indicate different kinds of errors or other conditions:
3313
3314<ul>
3315
3316<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> no errors.</li>
3317
3318<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> a runtime error.</li>
3319
3320<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3321memory allocation error.
3322For such errors, Lua does not call the message handler.
3323</li>
3324
3325<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> error while running the message handler.</li>
3326
3327<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> syntax error during precompilation.</li>
3328
3329<li><b><a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a>: </b> the thread (coroutine) yields.</li>
3330
3331<li><b><a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>: </b> a file-related error;
3332e.g., it cannot open or read the file.</li>
3333
3334</ul><p>
3335These constants are defined in the header file <code>lua.h</code>.
3336
3337
3338
3339
3340
3341
3342
3343<h2>4.5 &ndash; <a name="4.5">Handling Yields in C</a></h2>
3344
3345<p>
3346Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
3347Therefore, if a C&nbsp;function <code>foo</code> calls an API function
3348and this API function yields
3349(directly or indirectly by calling another function that yields),
3350Lua cannot return to <code>foo</code> any more,
3351because the <code>longjmp</code> removes its frame from the C&nbsp;stack.
3352
3353
3354<p>
3355To avoid this kind of problem,
3356Lua raises an error whenever it tries to yield across an API call,
3357except for three functions:
3358<a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3359All those functions receive a <em>continuation function</em>
3360(as a parameter named <code>k</code>) to continue execution after a yield.
3361
3362
3363<p>
3364We need to set some terminology to explain continuations.
3365We have a C&nbsp;function called from Lua which we will call
3366the <em>original function</em>.
3367This original function then calls one of those three functions in the C API,
3368which we will call the <em>callee function</em>,
3369that then yields the current thread.
3370This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
3371or when the callee function is either <a href="#lua_callk"><code>lua_callk</code></a> or <a href="#lua_pcallk"><code>lua_pcallk</code></a>
3372and the function called by them yields.
3373
3374
3375<p>
3376Suppose the running thread yields while executing the callee function.
3377After the thread resumes,
3378it eventually will finish running the callee function.
3379However,
3380the callee function cannot return to the original function,
3381because its frame in the C&nbsp;stack was destroyed by the yield.
3382Instead, Lua calls a <em>continuation function</em>,
3383which was given as an argument to the callee function.
3384As the name implies,
3385the continuation function should continue the task
3386of the original function.
3387
3388
3389<p>
3390As an illustration, consider the following function:
3391
3392<pre>
3393     int original_function (lua_State *L) {
3394       ...     /* code 1 */
3395       status = lua_pcall(L, n, m, h);  /* calls Lua */
3396       ...     /* code 2 */
3397     }
3398</pre><p>
3399Now we want to allow
3400the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
3401First, we can rewrite our function like here:
3402
3403<pre>
3404     int k (lua_State *L, int status, lua_KContext ctx) {
3405       ...  /* code 2 */
3406     }
3407
3408     int original_function (lua_State *L) {
3409       ...     /* code 1 */
3410       return k(L, lua_pcall(L, n, m, h), ctx);
3411     }
3412</pre><p>
3413In the above code,
3414the new function <code>k</code> is a
3415<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
3416which should do all the work that the original function
3417was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
3418Now, we must inform Lua that it must call <code>k</code> if the Lua code
3419being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
3420(errors or yielding),
3421so we rewrite the code as here,
3422replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
3423
3424<pre>
3425     int original_function (lua_State *L) {
3426       ...     /* code 1 */
3427       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
3428     }
3429</pre><p>
3430Note the external, explicit call to the continuation:
3431Lua will call the continuation only if needed, that is,
3432in case of errors or resuming after a yield.
3433If the called function returns normally without ever yielding,
3434<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
3435(Of course, instead of calling the continuation in that case,
3436you can do the equivalent work directly inside the original function.)
3437
3438
3439<p>
3440Besides the Lua state,
3441the continuation function has two other parameters:
3442the final status of the call and the context value (<code>ctx</code>) that
3443was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3444Lua does not use this context value;
3445it only passes this value from the original function to the
3446continuation function.
3447For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3448the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3449except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
3450(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
3451For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
3452the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
3453(For these two functions,
3454Lua will not call the continuation in case of errors,
3455because they do not handle errors.)
3456Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
3457you should call the continuation function
3458with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
3459(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
3460directly the continuation function,
3461because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
3462
3463
3464<p>
3465Lua treats the continuation function as if it were the original function.
3466The continuation function receives the same Lua stack
3467from the original function,
3468in the same state it would be if the callee function had returned.
3469(For instance,
3470after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
3471removed from the stack and replaced by the results from the call.)
3472It also has the same upvalues.
3473Whatever it returns is handled by Lua as if it were the return
3474of the original function.
3475
3476
3477
3478
3479
3480<h2>4.6 &ndash; <a name="4.6">Functions and Types</a></h2>
3481
3482<p>
3483Here we list all functions and types from the C&nbsp;API in
3484alphabetical order.
3485Each function has an indicator like this:
3486<span class="apii">[-o, +p, <em>x</em>]</span>
3487
3488
3489<p>
3490The first field, <code>o</code>,
3491is how many elements the function pops from the stack.
3492The second field, <code>p</code>,
3493is how many elements the function pushes onto the stack.
3494(Any function always pushes its results after popping its arguments.)
3495A field in the form <code>x|y</code> means the function can push (or pop)
3496<code>x</code> or <code>y</code> elements,
3497depending on the situation;
3498an interrogation mark '<code>?</code>' means that
3499we cannot know how many elements the function pops/pushes
3500by looking only at its arguments.
3501(For instance, they may depend on what is in the stack.)
3502The third field, <code>x</code>,
3503tells whether the function may raise errors:
3504'<code>-</code>' means the function never raises any error;
3505'<code>m</code>' means the function may raise only out-of-memory errors;
3506'<code>v</code>' means the function may raise the errors explained in the text;
3507'<code>e</code>' means the function can run arbitrary Lua code,
3508either directly or through metamethods,
3509and therefore may raise any errors.
3510
3511
3512
3513<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
3514<span class="apii">[-0, +0, &ndash;]</span>
3515<pre>int lua_absindex (lua_State *L, int idx);</pre>
3516
3517<p>
3518Converts the acceptable index <code>idx</code>
3519into an equivalent absolute index
3520(that is, one that does not depend on the stack size).
3521
3522
3523
3524
3525
3526<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
3527<pre>typedef void * (*lua_Alloc) (void *ud,
3528                             void *ptr,
3529                             size_t osize,
3530                             size_t nsize);</pre>
3531
3532<p>
3533The type of the memory-allocation function used by Lua states.
3534The allocator function must provide a
3535functionality similar to <code>realloc</code>,
3536but not exactly the same.
3537Its arguments are
3538<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3539<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3540<code>osize</code>, the original size of the block or some code about what
3541is being allocated;
3542and <code>nsize</code>, the new size of the block.
3543
3544
3545<p>
3546When <code>ptr</code> is not <code>NULL</code>,
3547<code>osize</code> is the size of the block pointed by <code>ptr</code>,
3548that is, the size given when it was allocated or reallocated.
3549
3550
3551<p>
3552When <code>ptr</code> is <code>NULL</code>,
3553<code>osize</code> encodes the kind of object that Lua is allocating.
3554<code>osize</code> is any of
3555<a href="#pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a href="#pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a href="#pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
3556<a href="#pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, or <a href="#pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a> when (and only when)
3557Lua is creating a new object of that type.
3558When <code>osize</code> is some other value,
3559Lua is allocating memory for something else.
3560
3561
3562<p>
3563Lua assumes the following behavior from the allocator function:
3564
3565
3566<p>
3567When <code>nsize</code> is zero,
3568the allocator must behave like <code>free</code>
3569and then return <code>NULL</code>.
3570
3571
3572<p>
3573When <code>nsize</code> is not zero,
3574the allocator must behave like <code>realloc</code>.
3575In particular, the allocator returns <code>NULL</code>
3576if and only if it cannot fulfill the request.
3577
3578
3579<p>
3580Here is a simple implementation for the allocator function.
3581It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3582
3583<pre>
3584     static void *l_alloc (void *ud, void *ptr, size_t osize,
3585                                                size_t nsize) {
3586       (void)ud;  (void)osize;  /* not used */
3587       if (nsize == 0) {
3588         free(ptr);
3589         return NULL;
3590       }
3591       else
3592         return realloc(ptr, nsize);
3593     }
3594</pre><p>
3595Note that ISO&nbsp;C ensures
3596that <code>free(NULL)</code> has no effect and that
3597<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3598
3599
3600
3601
3602
3603<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3604<span class="apii">[-(2|1), +1, <em>e</em>]</span>
3605<pre>void lua_arith (lua_State *L, int op);</pre>
3606
3607<p>
3608Performs an arithmetic or bitwise operation over the two values
3609(or one, in the case of negations)
3610at the top of the stack,
3611with the value on the top being the second operand,
3612pops these values, and pushes the result of the operation.
3613The function follows the semantics of the corresponding Lua operator
3614(that is, it may call metamethods).
3615
3616
3617<p>
3618The value of <code>op</code> must be one of the following constants:
3619
3620<ul>
3621
3622<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3623<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3624<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3625<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3626<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3627<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3628<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3629<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3630<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
3631<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li>
3632<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
3633<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
3634<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3635<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3636
3637</ul>
3638
3639
3640
3641
3642<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3643<span class="apii">[-0, +0, &ndash;]</span>
3644<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3645
3646<p>
3647Sets a new panic function and returns the old one (see <a href="#4.4">&sect;4.4</a>).
3648
3649
3650
3651
3652
3653<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3654<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3655<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3656
3657<p>
3658Calls a function.
3659Like regular Lua calls,
3660<code>lua_call</code> respects the <code>__call</code> metamethod.
3661So, here the word "function"
3662means any callable value.
3663
3664
3665<p>
3666To do a call you must use the following protocol:
3667first, the function to be called is pushed onto the stack;
3668then, the arguments to the call are pushed
3669in direct order;
3670that is, the first argument is pushed first.
3671Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3672<code>nargs</code> is the number of arguments that you pushed onto the stack.
3673When the function returns,
3674all arguments and the function value are popped
3675and the call results are pushed onto the stack.
3676The number of results is adjusted to <code>nresults</code>,
3677unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3678In this case, all results from the function are pushed;
3679Lua takes care that the returned values fit into the stack space,
3680but it does not ensure any extra space in the stack.
3681The function results are pushed onto the stack in direct order
3682(the first result is pushed first),
3683so that after the call the last result is on the top of the stack.
3684
3685
3686<p>
3687Any error while calling and running the function is propagated upwards
3688(with a <code>longjmp</code>).
3689
3690
3691<p>
3692The following example shows how the host program can do the
3693equivalent to this Lua code:
3694
3695<pre>
3696     a = f("how", t.x, 14)
3697</pre><p>
3698Here it is in&nbsp;C:
3699
3700<pre>
3701     lua_getglobal(L, "f");                  /* function to be called */
3702     lua_pushliteral(L, "how");                       /* 1st argument */
3703     lua_getglobal(L, "t");                    /* table to be indexed */
3704     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
3705     lua_remove(L, -2);                  /* remove 't' from the stack */
3706     lua_pushinteger(L, 14);                          /* 3rd argument */
3707     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
3708     lua_setglobal(L, "a");                         /* set global 'a' */
3709</pre><p>
3710Note that the code above is <em>balanced</em>:
3711at its end, the stack is back to its original configuration.
3712This is considered good programming practice.
3713
3714
3715
3716
3717
3718<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3719<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3720<pre>void lua_callk (lua_State *L,
3721                int nargs,
3722                int nresults,
3723                lua_KContext ctx,
3724                lua_KFunction k);</pre>
3725
3726<p>
3727This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3728but allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
3729
3730
3731
3732
3733
3734<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3735<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3736
3737<p>
3738Type for C&nbsp;functions.
3739
3740
3741<p>
3742In order to communicate properly with Lua,
3743a C&nbsp;function must use the following protocol,
3744which defines the way parameters and results are passed:
3745a C&nbsp;function receives its arguments from Lua in its stack
3746in direct order (the first argument is pushed first).
3747So, when the function starts,
3748<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3749The first argument (if any) is at index 1
3750and its last argument is at index <code>lua_gettop(L)</code>.
3751To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3752in direct order (the first result is pushed first),
3753and returns in C the number of results.
3754Any other value in the stack below the results will be properly
3755discarded by Lua.
3756Like a Lua function, a C&nbsp;function called by Lua can also return
3757many results.
3758
3759
3760<p>
3761As an example, the following function receives a variable number
3762of numeric arguments and returns their average and their sum:
3763
3764<pre>
3765     static int foo (lua_State *L) {
3766       int n = lua_gettop(L);    /* number of arguments */
3767       lua_Number sum = 0.0;
3768       int i;
3769       for (i = 1; i &lt;= n; i++) {
3770         if (!lua_isnumber(L, i)) {
3771           lua_pushliteral(L, "incorrect argument");
3772           lua_error(L);
3773         }
3774         sum += lua_tonumber(L, i);
3775       }
3776       lua_pushnumber(L, sum/n);        /* first result */
3777       lua_pushnumber(L, sum);         /* second result */
3778       return 2;                   /* number of results */
3779     }
3780</pre>
3781
3782
3783
3784
3785<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3786<span class="apii">[-0, +0, &ndash;]</span>
3787<pre>int lua_checkstack (lua_State *L, int n);</pre>
3788
3789<p>
3790Ensures that the stack has space for at least <code>n</code> extra elements,
3791that is, that you can safely push up to <code>n</code> values into it.
3792It returns false if it cannot fulfill the request,
3793either because it would cause the stack
3794to be greater than a fixed maximum size
3795(typically at least several thousand elements) or
3796because it cannot allocate memory for the extra space.
3797This function never shrinks the stack;
3798if the stack already has space for the extra elements,
3799it is left unchanged.
3800
3801
3802
3803
3804
3805<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3806<span class="apii">[-0, +0, &ndash;]</span>
3807<pre>void lua_close (lua_State *L);</pre>
3808
3809<p>
3810Close all active to-be-closed variables in the main thread,
3811release all objects in the given Lua state
3812(calling the corresponding garbage-collection metamethods, if any),
3813and frees all dynamic memory used by this state.
3814
3815
3816<p>
3817On several platforms, you may not need to call this function,
3818because all resources are naturally released when the host program ends.
3819On the other hand, long-running programs that create multiple states,
3820such as daemons or web servers,
3821will probably need to close states as soon as they are not needed.
3822
3823
3824
3825
3826
3827<hr><h3><a name="lua_closeslot"><code>lua_closeslot</code></a></h3><p>
3828<span class="apii">[-0, +0, <em>e</em>]</span>
3829<pre>void lua_closeslot (lua_State *L, int index);</pre>
3830
3831<p>
3832Close the to-be-closed slot at the given index and set its value to <b>nil</b>.
3833The index must be the last index previously marked to be closed
3834(see <a href="#lua_toclose"><code>lua_toclose</code></a>) that is still active (that is, not closed yet).
3835
3836
3837<p>
3838A <code>__close</code> metamethod cannot yield
3839when called through this function.
3840
3841
3842<p>
3843(This function was introduced in release&nbsp;5.4.3.)
3844
3845
3846
3847
3848
3849<hr><h3><a name="lua_closethread"><code>lua_closethread</code></a></h3><p>
3850<span class="apii">[-0, +?, &ndash;]</span>
3851<pre>int lua_closethread (lua_State *L, lua_State *from);</pre>
3852
3853<p>
3854Resets a thread, cleaning its call stack and closing all pending
3855to-be-closed variables.
3856Returns a status code:
3857<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for no errors in the thread
3858(either the original error that stopped the thread or
3859errors in closing methods),
3860or an error status otherwise.
3861In case of error,
3862leaves the error object on the top of the stack.
3863
3864
3865<p>
3866The parameter <code>from</code> represents the coroutine that is resetting <code>L</code>.
3867If there is no such coroutine,
3868this parameter can be <code>NULL</code>.
3869
3870
3871<p>
3872(This function was introduced in release&nbsp;5.4.6.)
3873
3874
3875
3876
3877
3878<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3879<span class="apii">[-0, +0, <em>e</em>]</span>
3880<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3881
3882<p>
3883Compares two Lua values.
3884Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3885when compared with the value at index <code>index2</code>,
3886following the semantics of the corresponding Lua operator
3887(that is, it may call metamethods).
3888Otherwise returns&nbsp;0.
3889Also returns&nbsp;0 if any of the indices is not valid.
3890
3891
3892<p>
3893The value of <code>op</code> must be one of the following constants:
3894
3895<ul>
3896
3897<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3898<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3899<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3900
3901</ul>
3902
3903
3904
3905
3906<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3907<span class="apii">[-n, +1, <em>e</em>]</span>
3908<pre>void lua_concat (lua_State *L, int n);</pre>
3909
3910<p>
3911Concatenates the <code>n</code> values at the top of the stack,
3912pops them, and leaves the result on the top.
3913If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3914(that is, the function does nothing);
3915if <code>n</code> is 0, the result is the empty string.
3916Concatenation is performed following the usual semantics of Lua
3917(see <a href="#3.4.6">&sect;3.4.6</a>).
3918
3919
3920
3921
3922
3923<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3924<span class="apii">[-0, +0, &ndash;]</span>
3925<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3926
3927<p>
3928Copies the element at index <code>fromidx</code>
3929into the valid index <code>toidx</code>,
3930replacing the value at that position.
3931Values at other positions are not affected.
3932
3933
3934
3935
3936
3937<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3938<span class="apii">[-0, +1, <em>m</em>]</span>
3939<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3940
3941<p>
3942Creates a new empty table and pushes it onto the stack.
3943Parameter <code>narr</code> is a hint for how many elements the table
3944will have as a sequence;
3945parameter <code>nrec</code> is a hint for how many other elements
3946the table will have.
3947Lua may use these hints to preallocate memory for the new table.
3948This preallocation may help performance when you know in advance
3949how many elements the table will have.
3950Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3951
3952
3953
3954
3955
3956<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3957<span class="apii">[-0, +0, &ndash;]</span>
3958<pre>int lua_dump (lua_State *L,
3959                        lua_Writer writer,
3960                        void *data,
3961                        int strip);</pre>
3962
3963<p>
3964Dumps a function as a binary chunk.
3965Receives a Lua function on the top of the stack
3966and produces a binary chunk that,
3967if loaded again,
3968results in a function equivalent to the one dumped.
3969As it produces parts of the chunk,
3970<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3971with the given <code>data</code>
3972to write them.
3973
3974
3975<p>
3976If <code>strip</code> is true,
3977the binary representation may not include all debug information
3978about the function,
3979to save space.
3980
3981
3982<p>
3983The value returned is the error code returned by the last
3984call to the writer;
39850&nbsp;means no errors.
3986
3987
3988<p>
3989This function does not pop the Lua function from the stack.
3990
3991
3992
3993
3994
3995<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3996<span class="apii">[-1, +0, <em>v</em>]</span>
3997<pre>int lua_error (lua_State *L);</pre>
3998
3999<p>
4000Raises a Lua error,
4001using the value on the top of the stack as the error object.
4002This function does a long jump,
4003and therefore never returns
4004(see <a href="#luaL_error"><code>luaL_error</code></a>).
4005
4006
4007
4008
4009
4010<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
4011<span class="apii">[-0, +0, &ndash;]</span>
4012<pre>int lua_gc (lua_State *L, int what, ...);</pre>
4013
4014<p>
4015Controls the garbage collector.
4016
4017
4018<p>
4019This function performs several tasks,
4020according to the value of the parameter <code>what</code>.
4021For options that need extra arguments,
4022they are listed after the option.
4023
4024<ul>
4025
4026<li><b><code>LUA_GCCOLLECT</code>: </b>
4027Performs a full garbage-collection cycle.
4028</li>
4029
4030<li><b><code>LUA_GCSTOP</code>: </b>
4031Stops the garbage collector.
4032</li>
4033
4034<li><b><code>LUA_GCRESTART</code>: </b>
4035Restarts the garbage collector.
4036</li>
4037
4038<li><b><code>LUA_GCCOUNT</code>: </b>
4039Returns the current amount of memory (in Kbytes) in use by Lua.
4040</li>
4041
4042<li><b><code>LUA_GCCOUNTB</code>: </b>
4043Returns the remainder of dividing the current amount of bytes of
4044memory in use by Lua by 1024.
4045</li>
4046
4047<li><b><code>LUA_GCSTEP</code> <code>(int stepsize)</code>: </b>
4048Performs an incremental step of garbage collection,
4049corresponding to the allocation of <code>stepsize</code> Kbytes.
4050</li>
4051
4052<li><b><code>LUA_GCISRUNNING</code>: </b>
4053Returns a boolean that tells whether the collector is running
4054(i.e., not stopped).
4055</li>
4056
4057<li><b><code>LUA_GCINC</code> (int pause, int stepmul, stepsize): </b>
4058Changes the collector to incremental mode
4059with the given parameters (see <a href="#2.5.1">&sect;2.5.1</a>).
4060Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
4061</li>
4062
4063<li><b><code>LUA_GCGEN</code> (int minormul, int majormul): </b>
4064Changes the collector to generational mode
4065with the given parameters (see <a href="#2.5.2">&sect;2.5.2</a>).
4066Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
4067</li>
4068
4069</ul><p>
4070For more details about these options,
4071see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
4072
4073
4074<p>
4075This function should not be called by a finalizer.
4076
4077
4078
4079
4080
4081<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
4082<span class="apii">[-0, +0, &ndash;]</span>
4083<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
4084
4085<p>
4086Returns the memory-allocation function of a given state.
4087If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
4088opaque pointer given when the memory-allocator function was set.
4089
4090
4091
4092
4093
4094<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
4095<span class="apii">[-0, +1, <em>e</em>]</span>
4096<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
4097
4098<p>
4099Pushes onto the stack the value <code>t[k]</code>,
4100where <code>t</code> is the value at the given index.
4101As in Lua, this function may trigger a metamethod
4102for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4103
4104
4105<p>
4106Returns the type of the pushed value.
4107
4108
4109
4110
4111
4112<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
4113<span class="apii">[-0, +0, &ndash;]</span>
4114<pre>void *lua_getextraspace (lua_State *L);</pre>
4115
4116<p>
4117Returns a pointer to a raw memory area associated with the
4118given Lua state.
4119The application can use this area for any purpose;
4120Lua does not use it for anything.
4121
4122
4123<p>
4124Each new thread has this area initialized with a copy
4125of the area of the main thread.
4126
4127
4128<p>
4129By default, this area has the size of a pointer to void,
4130but you can recompile Lua with a different size for this area.
4131(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
4132
4133
4134
4135
4136
4137<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
4138<span class="apii">[-0, +1, <em>e</em>]</span>
4139<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
4140
4141<p>
4142Pushes onto the stack the value of the global <code>name</code>.
4143Returns the type of that value.
4144
4145
4146
4147
4148
4149<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
4150<span class="apii">[-0, +1, <em>e</em>]</span>
4151<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
4152
4153<p>
4154Pushes onto the stack the value <code>t[i]</code>,
4155where <code>t</code> is the value at the given index.
4156As in Lua, this function may trigger a metamethod
4157for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4158
4159
4160<p>
4161Returns the type of the pushed value.
4162
4163
4164
4165
4166
4167<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
4168<span class="apii">[-0, +(0|1), &ndash;]</span>
4169<pre>int lua_getmetatable (lua_State *L, int index);</pre>
4170
4171<p>
4172If the value at the given index has a metatable,
4173the function pushes that metatable onto the stack and returns&nbsp;1.
4174Otherwise,
4175the function returns&nbsp;0 and pushes nothing on the stack.
4176
4177
4178
4179
4180
4181<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
4182<span class="apii">[-1, +1, <em>e</em>]</span>
4183<pre>int lua_gettable (lua_State *L, int index);</pre>
4184
4185<p>
4186Pushes onto the stack the value <code>t[k]</code>,
4187where <code>t</code> is the value at the given index
4188and <code>k</code> is the value on the top of the stack.
4189
4190
4191<p>
4192This function pops the key from the stack,
4193pushing the resulting value in its place.
4194As in Lua, this function may trigger a metamethod
4195for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4196
4197
4198<p>
4199Returns the type of the pushed value.
4200
4201
4202
4203
4204
4205<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
4206<span class="apii">[-0, +0, &ndash;]</span>
4207<pre>int lua_gettop (lua_State *L);</pre>
4208
4209<p>
4210Returns the index of the top element in the stack.
4211Because indices start at&nbsp;1,
4212this result is equal to the number of elements in the stack;
4213in particular, 0&nbsp;means an empty stack.
4214
4215
4216
4217
4218
4219<hr><h3><a name="lua_getiuservalue"><code>lua_getiuservalue</code></a></h3><p>
4220<span class="apii">[-0, +1, &ndash;]</span>
4221<pre>int lua_getiuservalue (lua_State *L, int index, int n);</pre>
4222
4223<p>
4224Pushes onto the stack the <code>n</code>-th user value associated with the
4225full userdata at the given index and
4226returns the type of the pushed value.
4227
4228
4229<p>
4230If the userdata does not have that value,
4231pushes <b>nil</b> and returns <a href="#pdf-LUA_TNONE"><code>LUA_TNONE</code></a>.
4232
4233
4234
4235
4236
4237<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
4238<span class="apii">[-1, +1, &ndash;]</span>
4239<pre>void lua_insert (lua_State *L, int index);</pre>
4240
4241<p>
4242Moves the top element into the given valid index,
4243shifting up the elements above this index to open space.
4244This function cannot be called with a pseudo-index,
4245because a pseudo-index is not an actual stack position.
4246
4247
4248
4249
4250
4251<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
4252<pre>typedef ... lua_Integer;</pre>
4253
4254<p>
4255The type of integers in Lua.
4256
4257
4258<p>
4259By default this type is <code>long long</code>,
4260(usually a 64-bit two-complement integer),
4261but that can be changed to <code>long</code> or <code>int</code>
4262(usually a 32-bit two-complement integer).
4263(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
4264
4265
4266<p>
4267Lua also defines the constants
4268<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
4269with the minimum and the maximum values that fit in this type.
4270
4271
4272
4273
4274
4275<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
4276<span class="apii">[-0, +0, &ndash;]</span>
4277<pre>int lua_isboolean (lua_State *L, int index);</pre>
4278
4279<p>
4280Returns 1 if the value at the given index is a boolean,
4281and 0&nbsp;otherwise.
4282
4283
4284
4285
4286
4287<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
4288<span class="apii">[-0, +0, &ndash;]</span>
4289<pre>int lua_iscfunction (lua_State *L, int index);</pre>
4290
4291<p>
4292Returns 1 if the value at the given index is a C&nbsp;function,
4293and 0&nbsp;otherwise.
4294
4295
4296
4297
4298
4299<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
4300<span class="apii">[-0, +0, &ndash;]</span>
4301<pre>int lua_isfunction (lua_State *L, int index);</pre>
4302
4303<p>
4304Returns 1 if the value at the given index is a function
4305(either C or Lua), and 0&nbsp;otherwise.
4306
4307
4308
4309
4310
4311<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
4312<span class="apii">[-0, +0, &ndash;]</span>
4313<pre>int lua_isinteger (lua_State *L, int index);</pre>
4314
4315<p>
4316Returns 1 if the value at the given index is an integer
4317(that is, the value is a number and is represented as an integer),
4318and 0&nbsp;otherwise.
4319
4320
4321
4322
4323
4324<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
4325<span class="apii">[-0, +0, &ndash;]</span>
4326<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
4327
4328<p>
4329Returns 1 if the value at the given index is a light userdata,
4330and 0&nbsp;otherwise.
4331
4332
4333
4334
4335
4336<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
4337<span class="apii">[-0, +0, &ndash;]</span>
4338<pre>int lua_isnil (lua_State *L, int index);</pre>
4339
4340<p>
4341Returns 1 if the value at the given index is <b>nil</b>,
4342and 0&nbsp;otherwise.
4343
4344
4345
4346
4347
4348<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
4349<span class="apii">[-0, +0, &ndash;]</span>
4350<pre>int lua_isnone (lua_State *L, int index);</pre>
4351
4352<p>
4353Returns 1 if the given index is not valid,
4354and 0&nbsp;otherwise.
4355
4356
4357
4358
4359
4360<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
4361<span class="apii">[-0, +0, &ndash;]</span>
4362<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
4363
4364<p>
4365Returns 1 if the given index is not valid
4366or if the value at this index is <b>nil</b>,
4367and 0&nbsp;otherwise.
4368
4369
4370
4371
4372
4373<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
4374<span class="apii">[-0, +0, &ndash;]</span>
4375<pre>int lua_isnumber (lua_State *L, int index);</pre>
4376
4377<p>
4378Returns 1 if the value at the given index is a number
4379or a string convertible to a number,
4380and 0&nbsp;otherwise.
4381
4382
4383
4384
4385
4386<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
4387<span class="apii">[-0, +0, &ndash;]</span>
4388<pre>int lua_isstring (lua_State *L, int index);</pre>
4389
4390<p>
4391Returns 1 if the value at the given index is a string
4392or a number (which is always convertible to a string),
4393and 0&nbsp;otherwise.
4394
4395
4396
4397
4398
4399<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
4400<span class="apii">[-0, +0, &ndash;]</span>
4401<pre>int lua_istable (lua_State *L, int index);</pre>
4402
4403<p>
4404Returns 1 if the value at the given index is a table,
4405and 0&nbsp;otherwise.
4406
4407
4408
4409
4410
4411<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
4412<span class="apii">[-0, +0, &ndash;]</span>
4413<pre>int lua_isthread (lua_State *L, int index);</pre>
4414
4415<p>
4416Returns 1 if the value at the given index is a thread,
4417and 0&nbsp;otherwise.
4418
4419
4420
4421
4422
4423<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
4424<span class="apii">[-0, +0, &ndash;]</span>
4425<pre>int lua_isuserdata (lua_State *L, int index);</pre>
4426
4427<p>
4428Returns 1 if the value at the given index is a userdata
4429(either full or light), and 0&nbsp;otherwise.
4430
4431
4432
4433
4434
4435<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
4436<span class="apii">[-0, +0, &ndash;]</span>
4437<pre>int lua_isyieldable (lua_State *L);</pre>
4438
4439<p>
4440Returns 1 if the given coroutine can yield,
4441and 0&nbsp;otherwise.
4442
4443
4444
4445
4446
4447<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
4448<pre>typedef ... lua_KContext;</pre>
4449
4450<p>
4451The type for continuation-function contexts.
4452It must be a numeric type.
4453This type is defined as <code>intptr_t</code>
4454when <code>intptr_t</code> is available,
4455so that it can store pointers too.
4456Otherwise, it is defined as <code>ptrdiff_t</code>.
4457
4458
4459
4460
4461
4462<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
4463<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
4464
4465<p>
4466Type for continuation functions (see <a href="#4.5">&sect;4.5</a>).
4467
4468
4469
4470
4471
4472<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
4473<span class="apii">[-0, +1, <em>e</em>]</span>
4474<pre>void lua_len (lua_State *L, int index);</pre>
4475
4476<p>
4477Returns the length of the value at the given index.
4478It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
4479may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
4480The result is pushed on the stack.
4481
4482
4483
4484
4485
4486<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
4487<span class="apii">[-0, +1, &ndash;]</span>
4488<pre>int lua_load (lua_State *L,
4489              lua_Reader reader,
4490              void *data,
4491              const char *chunkname,
4492              const char *mode);</pre>
4493
4494<p>
4495Loads a Lua chunk without running it.
4496If there are no errors,
4497<code>lua_load</code> pushes the compiled chunk as a Lua
4498function on top of the stack.
4499Otherwise, it pushes an error message.
4500
4501
4502<p>
4503The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
4504to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
4505The <code>data</code> argument is an opaque value passed to the reader function.
4506
4507
4508<p>
4509The <code>chunkname</code> argument gives a name to the chunk,
4510which is used for error messages and in debug information (see <a href="#4.7">&sect;4.7</a>).
4511
4512
4513<p>
4514<code>lua_load</code> automatically detects whether the chunk is text or binary
4515and loads it accordingly (see program <code>luac</code>).
4516The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
4517with the addition that
4518a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
4519
4520
4521<p>
4522<code>lua_load</code> uses the stack internally,
4523so the reader function must always leave the stack
4524unmodified when returning.
4525
4526
4527<p>
4528<code>lua_load</code> can return
4529<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>, <a href="#pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>, or <a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>.
4530The function may also return other values corresponding to
4531errors raised by the read function (see <a href="#4.4.1">&sect;4.4.1</a>).
4532
4533
4534<p>
4535If the resulting function has upvalues,
4536its first upvalue is set to the value of the global environment
4537stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.3">&sect;4.3</a>).
4538When loading main chunks,
4539this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
4540Other upvalues are initialized with <b>nil</b>.
4541
4542
4543
4544
4545
4546<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
4547<span class="apii">[-0, +0, &ndash;]</span>
4548<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
4549
4550<p>
4551Creates a new independent state and returns its main thread.
4552Returns <code>NULL</code> if it cannot create the state
4553(due to lack of memory).
4554The argument <code>f</code> is the allocator function;
4555Lua will do all memory allocation for this state
4556through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
4557The second argument, <code>ud</code>, is an opaque pointer that Lua
4558passes to the allocator in every call.
4559
4560
4561
4562
4563
4564<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
4565<span class="apii">[-0, +1, <em>m</em>]</span>
4566<pre>void lua_newtable (lua_State *L);</pre>
4567
4568<p>
4569Creates a new empty table and pushes it onto the stack.
4570It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
4571
4572
4573
4574
4575
4576<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
4577<span class="apii">[-0, +1, <em>m</em>]</span>
4578<pre>lua_State *lua_newthread (lua_State *L);</pre>
4579
4580<p>
4581Creates a new thread, pushes it on the stack,
4582and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
4583The new thread returned by this function shares with the original thread
4584its global environment,
4585but has an independent execution stack.
4586
4587
4588<p>
4589Threads are subject to garbage collection,
4590like any Lua object.
4591
4592
4593
4594
4595
4596<hr><h3><a name="lua_newuserdatauv"><code>lua_newuserdatauv</code></a></h3><p>
4597<span class="apii">[-0, +1, <em>m</em>]</span>
4598<pre>void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);</pre>
4599
4600<p>
4601This function creates and pushes on the stack a new full userdata,
4602with <code>nuvalue</code> associated Lua values, called <code>user values</code>,
4603plus an associated block of raw memory with <code>size</code> bytes.
4604(The user values can be set and read with the functions
4605<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a> and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>.)
4606
4607
4608<p>
4609The function returns the address of the block of memory.
4610Lua ensures that this address is valid as long as
4611the corresponding userdata is alive (see <a href="#2.5">&sect;2.5</a>).
4612Moreover, if the userdata is marked for finalization (see <a href="#2.5.3">&sect;2.5.3</a>),
4613its address is valid at least until the call to its finalizer.
4614
4615
4616
4617
4618
4619<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4620<span class="apii">[-1, +(2|0), <em>v</em>]</span>
4621<pre>int lua_next (lua_State *L, int index);</pre>
4622
4623<p>
4624Pops a key from the stack,
4625and pushes a key&ndash;value pair from the table at the given index,
4626the "next" pair after the given key.
4627If there are no more elements in the table,
4628then <a href="#lua_next"><code>lua_next</code></a> returns&nbsp;0 and pushes nothing.
4629
4630
4631<p>
4632A typical table traversal looks like this:
4633
4634<pre>
4635     /* table is in the stack at index 't' */
4636     lua_pushnil(L);  /* first key */
4637     while (lua_next(L, t) != 0) {
4638       /* uses 'key' (at index -2) and 'value' (at index -1) */
4639       printf("%s - %s\n",
4640              lua_typename(L, lua_type(L, -2)),
4641              lua_typename(L, lua_type(L, -1)));
4642       /* removes 'value'; keeps 'key' for next iteration */
4643       lua_pop(L, 1);
4644     }
4645</pre>
4646
4647<p>
4648While traversing a table,
4649avoid calling <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4650unless you know that the key is actually a string.
4651Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4652the value at the given index;
4653this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4654
4655
4656<p>
4657This function may raise an error if the given key
4658is neither <b>nil</b> nor present in the table.
4659See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4660the table during its traversal.
4661
4662
4663
4664
4665
4666<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4667<pre>typedef ... lua_Number;</pre>
4668
4669<p>
4670The type of floats in Lua.
4671
4672
4673<p>
4674By default this type is double,
4675but that can be changed to a single float or a long double.
4676(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
4677
4678
4679
4680
4681
4682<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4683<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4684
4685<p>
4686Tries to convert a Lua float to a Lua integer;
4687the float <code>n</code> must have an integral value.
4688If that value is within the range of Lua integers,
4689it is converted to an integer and assigned to <code>*p</code>.
4690The macro results in a boolean indicating whether the
4691conversion was successful.
4692(Note that this range test can be tricky to do
4693correctly without this macro, due to rounding.)
4694
4695
4696<p>
4697This macro may evaluate its arguments more than once.
4698
4699
4700
4701
4702
4703<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4704<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4705<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4706
4707<p>
4708Calls a function (or a callable object) in protected mode.
4709
4710
4711<p>
4712Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4713in <a href="#lua_call"><code>lua_call</code></a>.
4714If there are no errors during the call,
4715<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4716However, if there is any error,
4717<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4718pushes a single value on the stack (the error object),
4719and returns an error code.
4720Like <a href="#lua_call"><code>lua_call</code></a>,
4721<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4722and its arguments from the stack.
4723
4724
4725<p>
4726If <code>msgh</code> is 0,
4727then the error object returned on the stack
4728is exactly the original error object.
4729Otherwise, <code>msgh</code> is the stack index of a
4730<em>message handler</em>.
4731(This index cannot be a pseudo-index.)
4732In case of runtime errors,
4733this handler will be called with the error object
4734and its return value will be the object
4735returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4736
4737
4738<p>
4739Typically, the message handler is used to add more debug
4740information to the error object, such as a stack traceback.
4741Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4742since by then the stack has unwound.
4743
4744
4745<p>
4746The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following status codes:
4747<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>, <a href="#pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>, <a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>, or <a href="#pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>.
4748
4749
4750
4751
4752
4753<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4754<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4755<pre>int lua_pcallk (lua_State *L,
4756                int nargs,
4757                int nresults,
4758                int msgh,
4759                lua_KContext ctx,
4760                lua_KFunction k);</pre>
4761
4762<p>
4763This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4764except that it allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
4765
4766
4767
4768
4769
4770<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4771<span class="apii">[-n, +0, <em>e</em>]</span>
4772<pre>void lua_pop (lua_State *L, int n);</pre>
4773
4774<p>
4775Pops <code>n</code> elements from the stack.
4776It is implemented as a macro over <a href="#lua_settop"><code>lua_settop</code></a>.
4777
4778
4779
4780
4781
4782<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4783<span class="apii">[-0, +1, &ndash;]</span>
4784<pre>void lua_pushboolean (lua_State *L, int b);</pre>
4785
4786<p>
4787Pushes a boolean value with value <code>b</code> onto the stack.
4788
4789
4790
4791
4792
4793<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4794<span class="apii">[-n, +1, <em>m</em>]</span>
4795<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4796
4797<p>
4798Pushes a new C&nbsp;closure onto the stack.
4799This function receives a pointer to a C&nbsp;function
4800and pushes onto the stack a Lua value of type <code>function</code> that,
4801when called, invokes the corresponding C&nbsp;function.
4802The parameter <code>n</code> tells how many upvalues this function will have
4803(see <a href="#4.2">&sect;4.2</a>).
4804
4805
4806<p>
4807Any function to be callable by Lua must
4808follow the correct protocol to receive its parameters
4809and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4810
4811
4812<p>
4813When a C&nbsp;function is created,
4814it is possible to associate some values with it,
4815the so called upvalues;
4816these upvalues are then accessible to the function whenever it is called.
4817This association is called a C&nbsp;closure (see <a href="#4.2">&sect;4.2</a>).
4818To create a C&nbsp;closure,
4819first the initial values for its upvalues must be pushed onto the stack.
4820(When there are multiple upvalues, the first value is pushed first.)
4821Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4822is called to create and push the C&nbsp;function onto the stack,
4823with the argument <code>n</code> telling how many values will be
4824associated with the function.
4825<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4826
4827
4828<p>
4829The maximum value for <code>n</code> is 255.
4830
4831
4832<p>
4833When <code>n</code> is zero,
4834this function creates a <em>light C&nbsp;function</em>,
4835which is just a pointer to the C&nbsp;function.
4836In that case, it never raises a memory error.
4837
4838
4839
4840
4841
4842<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4843<span class="apii">[-0, +1, &ndash;]</span>
4844<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4845
4846<p>
4847Pushes a C&nbsp;function onto the stack.
4848This function is equivalent to <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> with no upvalues.
4849
4850
4851
4852
4853
4854<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4855<span class="apii">[-0, +1, <em>v</em>]</span>
4856<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4857
4858<p>
4859Pushes onto the stack a formatted string
4860and returns a pointer to this string (see <a href="#4.1.3">&sect;4.1.3</a>).
4861It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4862but has two important differences.
4863First,
4864you do not have to allocate space for the result;
4865the result is a Lua string and Lua takes care of memory allocation
4866(and deallocation, through garbage collection).
4867Second,
4868the conversion specifiers are quite restricted.
4869There are no flags, widths, or precisions.
4870The conversion specifiers can only be
4871'<code>%%</code>' (inserts the character '<code>%</code>'),
4872'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4873'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4874'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4875'<code>%p</code>' (inserts a pointer),
4876'<code>%d</code>' (inserts an <code>int</code>),
4877'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4878'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4879
4880
4881<p>
4882This function may raise errors due to memory overflow
4883or an invalid conversion specifier.
4884
4885
4886
4887
4888
4889<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4890<span class="apii">[-0, +1, &ndash;]</span>
4891<pre>void lua_pushglobaltable (lua_State *L);</pre>
4892
4893<p>
4894Pushes the global environment onto the stack.
4895
4896
4897
4898
4899
4900<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4901<span class="apii">[-0, +1, &ndash;]</span>
4902<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4903
4904<p>
4905Pushes an integer with value <code>n</code> onto the stack.
4906
4907
4908
4909
4910
4911<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4912<span class="apii">[-0, +1, &ndash;]</span>
4913<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4914
4915<p>
4916Pushes a light userdata onto the stack.
4917
4918
4919<p>
4920Userdata represent C&nbsp;values in Lua.
4921A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4922It is a value (like a number):
4923you do not create it, it has no individual metatable,
4924and it is not collected (as it was never created).
4925A light userdata is equal to "any"
4926light userdata with the same C&nbsp;address.
4927
4928
4929
4930
4931
4932<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4933<span class="apii">[-0, +1, <em>m</em>]</span>
4934<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4935
4936<p>
4937This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
4938but should be used only when <code>s</code> is a literal string.
4939(Lua may optimize this case.)
4940
4941
4942
4943
4944
4945<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4946<span class="apii">[-0, +1, <em>m</em>]</span>
4947<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4948
4949<p>
4950Pushes the string pointed to by <code>s</code> with size <code>len</code>
4951onto the stack.
4952Lua will make or reuse an internal copy of the given string,
4953so the memory at <code>s</code> can be freed or reused immediately after
4954the function returns.
4955The string can contain any binary data,
4956including embedded zeros.
4957
4958
4959<p>
4960Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4961
4962
4963
4964
4965
4966<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4967<span class="apii">[-0, +1, &ndash;]</span>
4968<pre>void lua_pushnil (lua_State *L);</pre>
4969
4970<p>
4971Pushes a nil value onto the stack.
4972
4973
4974
4975
4976
4977<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4978<span class="apii">[-0, +1, &ndash;]</span>
4979<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4980
4981<p>
4982Pushes a float with value <code>n</code> onto the stack.
4983
4984
4985
4986
4987
4988<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4989<span class="apii">[-0, +1, <em>m</em>]</span>
4990<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4991
4992<p>
4993Pushes the zero-terminated string pointed to by <code>s</code>
4994onto the stack.
4995Lua will make or reuse an internal copy of the given string,
4996so the memory at <code>s</code> can be freed or reused immediately after
4997the function returns.
4998
4999
5000<p>
5001Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
5002
5003
5004<p>
5005If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
5006
5007
5008
5009
5010
5011<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
5012<span class="apii">[-0, +1, &ndash;]</span>
5013<pre>int lua_pushthread (lua_State *L);</pre>
5014
5015<p>
5016Pushes the thread represented by <code>L</code> onto the stack.
5017Returns 1 if this thread is the main thread of its state.
5018
5019
5020
5021
5022
5023<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
5024<span class="apii">[-0, +1, &ndash;]</span>
5025<pre>void lua_pushvalue (lua_State *L, int index);</pre>
5026
5027<p>
5028Pushes a copy of the element at the given index
5029onto the stack.
5030
5031
5032
5033
5034
5035<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
5036<span class="apii">[-0, +1, <em>v</em>]</span>
5037<pre>const char *lua_pushvfstring (lua_State *L,
5038                              const char *fmt,
5039                              va_list argp);</pre>
5040
5041<p>
5042Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
5043instead of a variable number of arguments.
5044
5045
5046
5047
5048
5049<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
5050<span class="apii">[-0, +0, &ndash;]</span>
5051<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
5052
5053<p>
5054Returns 1 if the two values in indices <code>index1</code> and
5055<code>index2</code> are primitively equal
5056(that is, equal without calling the <code>__eq</code> metamethod).
5057Otherwise returns&nbsp;0.
5058Also returns&nbsp;0 if any of the indices are not valid.
5059
5060
5061
5062
5063
5064<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
5065<span class="apii">[-1, +1, &ndash;]</span>
5066<pre>int lua_rawget (lua_State *L, int index);</pre>
5067
5068<p>
5069Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
5070(i.e., without metamethods).
5071The value at <code>index</code> must be a table.
5072
5073
5074
5075
5076
5077<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
5078<span class="apii">[-0, +1, &ndash;]</span>
5079<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
5080
5081<p>
5082Pushes onto the stack the value <code>t[n]</code>,
5083where <code>t</code> is the table at the given index.
5084The access is raw,
5085that is, it does not use the <code>__index</code> metavalue.
5086
5087
5088<p>
5089Returns the type of the pushed value.
5090
5091
5092
5093
5094
5095<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
5096<span class="apii">[-0, +1, &ndash;]</span>
5097<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
5098
5099<p>
5100Pushes onto the stack the value <code>t[k]</code>,
5101where <code>t</code> is the table at the given index and
5102<code>k</code> is the pointer <code>p</code> represented as a light userdata.
5103The access is raw;
5104that is, it does not use the <code>__index</code> metavalue.
5105
5106
5107<p>
5108Returns the type of the pushed value.
5109
5110
5111
5112
5113
5114<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
5115<span class="apii">[-0, +0, &ndash;]</span>
5116<pre>lua_Unsigned lua_rawlen (lua_State *L, int index);</pre>
5117
5118<p>
5119Returns the raw "length" of the value at the given index:
5120for strings, this is the string length;
5121for tables, this is the result of the length operator ('<code>#</code>')
5122with no metamethods;
5123for userdata, this is the size of the block of memory allocated
5124for the userdata.
5125For other values, this call returns&nbsp;0.
5126
5127
5128
5129
5130
5131<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
5132<span class="apii">[-2, +0, <em>m</em>]</span>
5133<pre>void lua_rawset (lua_State *L, int index);</pre>
5134
5135<p>
5136Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
5137(i.e., without metamethods).
5138The value at <code>index</code> must be a table.
5139
5140
5141
5142
5143
5144<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
5145<span class="apii">[-1, +0, <em>m</em>]</span>
5146<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
5147
5148<p>
5149Does the equivalent of <code>t[i] = v</code>,
5150where <code>t</code> is the table at the given index
5151and <code>v</code> is the value on the top of the stack.
5152
5153
5154<p>
5155This function pops the value from the stack.
5156The assignment is raw,
5157that is, it does not use the <code>__newindex</code> metavalue.
5158
5159
5160
5161
5162
5163<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
5164<span class="apii">[-1, +0, <em>m</em>]</span>
5165<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
5166
5167<p>
5168Does the equivalent of <code>t[p] = v</code>,
5169where <code>t</code> is the table at the given index,
5170<code>p</code> is encoded as a light userdata,
5171and <code>v</code> is the value on the top of the stack.
5172
5173
5174<p>
5175This function pops the value from the stack.
5176The assignment is raw,
5177that is, it does not use the <code>__newindex</code> metavalue.
5178
5179
5180
5181
5182
5183<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
5184<pre>typedef const char * (*lua_Reader) (lua_State *L,
5185                                    void *data,
5186                                    size_t *size);</pre>
5187
5188<p>
5189The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
5190Every time <a href="#lua_load"><code>lua_load</code></a> needs another piece of the chunk,
5191it calls the reader,
5192passing along its <code>data</code> parameter.
5193The reader must return a pointer to a block of memory
5194with a new piece of the chunk
5195and set <code>size</code> to the block size.
5196The block must exist until the reader function is called again.
5197To signal the end of the chunk,
5198the reader must return <code>NULL</code> or set <code>size</code> to zero.
5199The reader function may return pieces of any size greater than zero.
5200
5201
5202
5203
5204
5205<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
5206<span class="apii">[-0, +0, <em>e</em>]</span>
5207<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
5208
5209<p>
5210Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>.
5211It is defined as a macro:
5212
5213<pre>
5214     #define lua_register(L,n,f) \
5215            (lua_pushcfunction(L, f), lua_setglobal(L, n))
5216</pre>
5217
5218
5219
5220
5221<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
5222<span class="apii">[-1, +0, &ndash;]</span>
5223<pre>void lua_remove (lua_State *L, int index);</pre>
5224
5225<p>
5226Removes the element at the given valid index,
5227shifting down the elements above this index to fill the gap.
5228This function cannot be called with a pseudo-index,
5229because a pseudo-index is not an actual stack position.
5230
5231
5232
5233
5234
5235<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
5236<span class="apii">[-1, +0, &ndash;]</span>
5237<pre>void lua_replace (lua_State *L, int index);</pre>
5238
5239<p>
5240Moves the top element into the given valid index
5241without shifting any element
5242(therefore replacing the value at that given index),
5243and then pops the top element.
5244
5245
5246
5247
5248
5249<hr><h3><a name="lua_resetthread"><code>lua_resetthread</code></a></h3><p>
5250<span class="apii">[-0, +?, &ndash;]</span>
5251<pre>int lua_resetthread (lua_State *L);</pre>
5252
5253<p>
5254This function is deprecated;
5255it is equivalent to <a href="#lua_closethread"><code>lua_closethread</code></a> with
5256<code>from</code> being <code>NULL</code>.
5257
5258
5259
5260
5261
5262<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
5263<span class="apii">[-?, +?, &ndash;]</span>
5264<pre>int lua_resume (lua_State *L, lua_State *from, int nargs,
5265                          int *nresults);</pre>
5266
5267<p>
5268Starts and resumes a coroutine in the given thread <code>L</code>.
5269
5270
5271<p>
5272To start a coroutine,
5273you push the main function plus any arguments
5274onto the empty stack of the thread.
5275then you call <a href="#lua_resume"><code>lua_resume</code></a>,
5276with <code>nargs</code> being the number of arguments.
5277This call returns when the coroutine suspends or finishes its execution.
5278When it returns,
5279<code>*nresults</code> is updated and
5280the top of the stack contains
5281the <code>*nresults</code> values passed to <a href="#lua_yield"><code>lua_yield</code></a>
5282or returned by the body function.
5283<a href="#lua_resume"><code>lua_resume</code></a> returns
5284<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
5285<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
5286without errors,
5287or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
5288In case of errors,
5289the error object is on the top of the stack.
5290
5291
5292<p>
5293To resume a coroutine,
5294you remove the <code>*nresults</code> yielded values from its stack,
5295push the values to be passed as results from <code>yield</code>,
5296and then call <a href="#lua_resume"><code>lua_resume</code></a>.
5297
5298
5299<p>
5300The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
5301If there is no such coroutine,
5302this parameter can be <code>NULL</code>.
5303
5304
5305
5306
5307
5308<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
5309<span class="apii">[-0, +0, &ndash;]</span>
5310<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
5311
5312<p>
5313Rotates the stack elements between the valid index <code>idx</code>
5314and the top of the stack.
5315The elements are rotated <code>n</code> positions in the direction of the top,
5316for a positive <code>n</code>,
5317or <code>-n</code> positions in the direction of the bottom,
5318for a negative <code>n</code>.
5319The absolute value of <code>n</code> must not be greater than the size
5320of the slice being rotated.
5321This function cannot be called with a pseudo-index,
5322because a pseudo-index is not an actual stack position.
5323
5324
5325
5326
5327
5328<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
5329<span class="apii">[-0, +0, &ndash;]</span>
5330<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
5331
5332<p>
5333Changes the allocator function of a given state to <code>f</code>
5334with user data <code>ud</code>.
5335
5336
5337
5338
5339
5340<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
5341<span class="apii">[-1, +0, <em>e</em>]</span>
5342<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
5343
5344<p>
5345Does the equivalent to <code>t[k] = v</code>,
5346where <code>t</code> is the value at the given index
5347and <code>v</code> is the value on the top of the stack.
5348
5349
5350<p>
5351This function pops the value from the stack.
5352As in Lua, this function may trigger a metamethod
5353for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5354
5355
5356
5357
5358
5359<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
5360<span class="apii">[-1, +0, <em>e</em>]</span>
5361<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
5362
5363<p>
5364Pops a value from the stack and
5365sets it as the new value of global <code>name</code>.
5366
5367
5368
5369
5370
5371<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
5372<span class="apii">[-1, +0, <em>e</em>]</span>
5373<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
5374
5375<p>
5376Does the equivalent to <code>t[n] = v</code>,
5377where <code>t</code> is the value at the given index
5378and <code>v</code> is the value on the top of the stack.
5379
5380
5381<p>
5382This function pops the value from the stack.
5383As in Lua, this function may trigger a metamethod
5384for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5385
5386
5387
5388
5389
5390<hr><h3><a name="lua_setiuservalue"><code>lua_setiuservalue</code></a></h3><p>
5391<span class="apii">[-1, +0, &ndash;]</span>
5392<pre>int lua_setiuservalue (lua_State *L, int index, int n);</pre>
5393
5394<p>
5395Pops a value from the stack and sets it as
5396the new <code>n</code>-th user value associated to the
5397full userdata at the given index.
5398Returns 0 if the userdata does not have that value.
5399
5400
5401
5402
5403
5404<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
5405<span class="apii">[-1, +0, &ndash;]</span>
5406<pre>int lua_setmetatable (lua_State *L, int index);</pre>
5407
5408<p>
5409Pops a table or <b>nil</b> from the stack and
5410sets that value as the new metatable for the value at the given index.
5411(<b>nil</b> means no metatable.)
5412
5413
5414<p>
5415(For historical reasons, this function returns an <code>int</code>,
5416which now is always 1.)
5417
5418
5419
5420
5421
5422<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
5423<span class="apii">[-2, +0, <em>e</em>]</span>
5424<pre>void lua_settable (lua_State *L, int index);</pre>
5425
5426<p>
5427Does the equivalent to <code>t[k] = v</code>,
5428where <code>t</code> is the value at the given index,
5429<code>v</code> is the value on the top of the stack,
5430and <code>k</code> is the value just below the top.
5431
5432
5433<p>
5434This function pops both the key and the value from the stack.
5435As in Lua, this function may trigger a metamethod
5436for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5437
5438
5439
5440
5441
5442<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
5443<span class="apii">[-?, +?, <em>e</em>]</span>
5444<pre>void lua_settop (lua_State *L, int index);</pre>
5445
5446<p>
5447Accepts any index, or&nbsp;0,
5448and sets the stack top to this index.
5449If the new top is greater than the old one,
5450then the new elements are filled with <b>nil</b>.
5451If <code>index</code> is&nbsp;0, then all stack elements are removed.
5452
5453
5454<p>
5455This function can run arbitrary code when removing an index
5456marked as to-be-closed from the stack.
5457
5458
5459
5460
5461
5462<hr><h3><a name="lua_setwarnf"><code>lua_setwarnf</code></a></h3><p>
5463<span class="apii">[-0, +0, &ndash;]</span>
5464<pre>void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);</pre>
5465
5466<p>
5467Sets the warning function to be used by Lua to emit warnings
5468(see <a href="#lua_WarnFunction"><code>lua_WarnFunction</code></a>).
5469The <code>ud</code> parameter sets the value <code>ud</code> passed to
5470the warning function.
5471
5472
5473
5474
5475
5476<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
5477<pre>typedef struct lua_State lua_State;</pre>
5478
5479<p>
5480An opaque structure that points to a thread and indirectly
5481(through the thread) to the whole state of a Lua interpreter.
5482The Lua library is fully reentrant:
5483it has no global variables.
5484All information about a state is accessible through this structure.
5485
5486
5487<p>
5488A pointer to this structure must be passed as the first argument to
5489every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
5490which creates a Lua state from scratch.
5491
5492
5493
5494
5495
5496<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
5497<span class="apii">[-0, +0, &ndash;]</span>
5498<pre>int lua_status (lua_State *L);</pre>
5499
5500<p>
5501Returns the status of the thread <code>L</code>.
5502
5503
5504<p>
5505The status can be <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for a normal thread,
5506an error code if the thread finished the execution
5507of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
5508or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
5509
5510
5511<p>
5512You can call functions only in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
5513You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
5514(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
5515(to resume a coroutine).
5516
5517
5518
5519
5520
5521<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
5522<span class="apii">[-0, +1, &ndash;]</span>
5523<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
5524
5525<p>
5526Converts the zero-terminated string <code>s</code> to a number,
5527pushes that number into the stack,
5528and returns the total size of the string,
5529that is, its length plus one.
5530The conversion can result in an integer or a float,
5531according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
5532The string may have leading and trailing whitespaces and a sign.
5533If the string is not a valid numeral,
5534returns 0 and pushes nothing.
5535(Note that the result can be used as a boolean,
5536true if the conversion succeeds.)
5537
5538
5539
5540
5541
5542<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
5543<span class="apii">[-0, +0, &ndash;]</span>
5544<pre>int lua_toboolean (lua_State *L, int index);</pre>
5545
5546<p>
5547Converts the Lua value at the given index to a C&nbsp;boolean
5548value (0&nbsp;or&nbsp;1).
5549Like all tests in Lua,
5550<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
5551different from <b>false</b> and <b>nil</b>;
5552otherwise it returns false.
5553(If you want to accept only actual boolean values,
5554use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
5555
5556
5557
5558
5559
5560<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
5561<span class="apii">[-0, +0, &ndash;]</span>
5562<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
5563
5564<p>
5565Converts a value at the given index to a C&nbsp;function.
5566That value must be a C&nbsp;function;
5567otherwise, returns <code>NULL</code>.
5568
5569
5570
5571
5572
5573<hr><h3><a name="lua_toclose"><code>lua_toclose</code></a></h3><p>
5574<span class="apii">[-0, +0, <em>m</em>]</span>
5575<pre>void lua_toclose (lua_State *L, int index);</pre>
5576
5577<p>
5578Marks the given index in the stack as a
5579to-be-closed slot (see <a href="#3.3.8">&sect;3.3.8</a>).
5580Like a to-be-closed variable in Lua,
5581the value at that slot in the stack will be closed
5582when it goes out of scope.
5583Here, in the context of a C function,
5584to go out of scope means that the running function returns to Lua,
5585or there is an error,
5586or the slot is removed from the stack through
5587<a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>,
5588or there is a call to <a href="#lua_closeslot"><code>lua_closeslot</code></a>.
5589A slot marked as to-be-closed should not be removed from the stack
5590by any other function in the API except <a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>,
5591unless previously deactivated by <a href="#lua_closeslot"><code>lua_closeslot</code></a>.
5592
5593
5594<p>
5595This function should not be called for an index
5596that is equal to or below an active to-be-closed slot.
5597
5598
5599<p>
5600Note that, both in case of errors and of a regular return,
5601by the time the <code>__close</code> metamethod runs,
5602the C&nbsp;stack was already unwound,
5603so that any automatic C&nbsp;variable declared in the calling function
5604(e.g., a buffer) will be out of scope.
5605
5606
5607
5608
5609
5610<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
5611<span class="apii">[-0, +0, &ndash;]</span>
5612<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
5613
5614<p>
5615Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5616
5617
5618
5619
5620
5621<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
5622<span class="apii">[-0, +0, &ndash;]</span>
5623<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
5624
5625<p>
5626Converts the Lua value at the given index
5627to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
5628The Lua value must be an integer,
5629or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
5630otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
5631
5632
5633<p>
5634If <code>isnum</code> is not <code>NULL</code>,
5635its referent is assigned a boolean value that
5636indicates whether the operation succeeded.
5637
5638
5639
5640
5641
5642<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
5643<span class="apii">[-0, +0, <em>m</em>]</span>
5644<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5645
5646<p>
5647Converts the Lua value at the given index to a C&nbsp;string.
5648If <code>len</code> is not <code>NULL</code>,
5649it sets <code>*len</code> with the string length.
5650The Lua value must be a string or a number;
5651otherwise, the function returns <code>NULL</code>.
5652If the value is a number,
5653then <code>lua_tolstring</code> also
5654<em>changes the actual value in the stack to a string</em>.
5655(This change confuses <a href="#lua_next"><code>lua_next</code></a>
5656when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5657
5658
5659<p>
5660<code>lua_tolstring</code> returns a pointer
5661to a string inside the Lua state (see <a href="#4.1.3">&sect;4.1.3</a>).
5662This string always has a zero ('<code>\0</code>')
5663after its last character (as in&nbsp;C),
5664but can contain other zeros in its body.
5665
5666
5667
5668
5669
5670<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5671<span class="apii">[-0, +0, &ndash;]</span>
5672<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5673
5674<p>
5675Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5676
5677
5678
5679
5680
5681<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5682<span class="apii">[-0, +0, &ndash;]</span>
5683<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5684
5685<p>
5686Converts the Lua value at the given index
5687to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5688The Lua value must be a number or a string convertible to a number
5689(see <a href="#3.4.3">&sect;3.4.3</a>);
5690otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5691
5692
5693<p>
5694If <code>isnum</code> is not <code>NULL</code>,
5695its referent is assigned a boolean value that
5696indicates whether the operation succeeded.
5697
5698
5699
5700
5701
5702<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5703<span class="apii">[-0, +0, &ndash;]</span>
5704<pre>const void *lua_topointer (lua_State *L, int index);</pre>
5705
5706<p>
5707Converts the value at the given index to a generic
5708C&nbsp;pointer (<code>void*</code>).
5709The value can be a userdata, a table, a thread, a string, or a function;
5710otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5711Different objects will give different pointers.
5712There is no way to convert the pointer back to its original value.
5713
5714
5715<p>
5716Typically this function is used only for hashing and debug information.
5717
5718
5719
5720
5721
5722<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5723<span class="apii">[-0, +0, <em>m</em>]</span>
5724<pre>const char *lua_tostring (lua_State *L, int index);</pre>
5725
5726<p>
5727Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5728
5729
5730
5731
5732
5733<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5734<span class="apii">[-0, +0, &ndash;]</span>
5735<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5736
5737<p>
5738Converts the value at the given index to a Lua thread
5739(represented as <code>lua_State*</code>).
5740This value must be a thread;
5741otherwise, the function returns <code>NULL</code>.
5742
5743
5744
5745
5746
5747<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5748<span class="apii">[-0, +0, &ndash;]</span>
5749<pre>void *lua_touserdata (lua_State *L, int index);</pre>
5750
5751<p>
5752If the value at the given index is a full userdata,
5753returns its memory-block address.
5754If the value is a light userdata,
5755returns its value (a pointer).
5756Otherwise, returns <code>NULL</code>.
5757
5758
5759
5760
5761
5762<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5763<span class="apii">[-0, +0, &ndash;]</span>
5764<pre>int lua_type (lua_State *L, int index);</pre>
5765
5766<p>
5767Returns the type of the value in the given valid index,
5768or <code>LUA_TNONE</code> for a non-valid but acceptable index.
5769The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5770defined in <code>lua.h</code>:
5771<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5772<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5773<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5774<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5775<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5776<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5777<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5778<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5779and
5780<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5781
5782
5783
5784
5785
5786<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5787<span class="apii">[-0, +0, &ndash;]</span>
5788<pre>const char *lua_typename (lua_State *L, int tp);</pre>
5789
5790<p>
5791Returns the name of the type encoded by the value <code>tp</code>,
5792which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5793
5794
5795
5796
5797
5798<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5799<pre>typedef ... lua_Unsigned;</pre>
5800
5801<p>
5802The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5803
5804
5805
5806
5807
5808<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5809<span class="apii">[-0, +0, &ndash;]</span>
5810<pre>int lua_upvalueindex (int i);</pre>
5811
5812<p>
5813Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5814the running function (see <a href="#4.2">&sect;4.2</a>).
5815<code>i</code> must be in the range <em>[1,256]</em>.
5816
5817
5818
5819
5820
5821<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5822<span class="apii">[-0, +0, &ndash;]</span>
5823<pre>lua_Number lua_version (lua_State *L);</pre>
5824
5825<p>
5826Returns the version number of this core.
5827
5828
5829
5830
5831
5832<hr><h3><a name="lua_WarnFunction"><code>lua_WarnFunction</code></a></h3>
5833<pre>typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);</pre>
5834
5835<p>
5836The type of warning functions, called by Lua to emit warnings.
5837The first parameter is an opaque pointer
5838set by <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>.
5839The second parameter is the warning message.
5840The third parameter is a boolean that
5841indicates whether the message is
5842to be continued by the message in the next call.
5843
5844
5845<p>
5846See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5847
5848
5849
5850
5851
5852<hr><h3><a name="lua_warning"><code>lua_warning</code></a></h3><p>
5853<span class="apii">[-0, +0, &ndash;]</span>
5854<pre>void lua_warning (lua_State *L, const char *msg, int tocont);</pre>
5855
5856<p>
5857Emits a warning with the given message.
5858A message in a call with <code>tocont</code> true should be
5859continued in another call to this function.
5860
5861
5862<p>
5863See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5864
5865
5866
5867
5868
5869<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5870<pre>typedef int (*lua_Writer) (lua_State *L,
5871                           const void* p,
5872                           size_t sz,
5873                           void* ud);</pre>
5874
5875<p>
5876The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5877Every time <a href="#lua_dump"><code>lua_dump</code></a> produces another piece of chunk,
5878it calls the writer,
5879passing along the buffer to be written (<code>p</code>),
5880its size (<code>sz</code>),
5881and the <code>ud</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5882
5883
5884<p>
5885The writer returns an error code:
58860&nbsp;means no errors;
5887any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5888calling the writer again.
5889
5890
5891
5892
5893
5894<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5895<span class="apii">[-?, +?, &ndash;]</span>
5896<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5897
5898<p>
5899Exchange values between different threads of the same state.
5900
5901
5902<p>
5903This function pops <code>n</code> values from the stack <code>from</code>,
5904and pushes them onto the stack <code>to</code>.
5905
5906
5907
5908
5909
5910<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5911<span class="apii">[-?, +?, <em>v</em>]</span>
5912<pre>int lua_yield (lua_State *L, int nresults);</pre>
5913
5914<p>
5915This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5916but it has no continuation (see <a href="#4.5">&sect;4.5</a>).
5917Therefore, when the thread resumes,
5918it continues the function that called
5919the function calling <code>lua_yield</code>.
5920To avoid surprises,
5921this function should be called only in a tail call.
5922
5923
5924
5925
5926
5927<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5928<span class="apii">[-?, +?, <em>v</em>]</span>
5929<pre>int lua_yieldk (lua_State *L,
5930                int nresults,
5931                lua_KContext ctx,
5932                lua_KFunction k);</pre>
5933
5934<p>
5935Yields a coroutine (thread).
5936
5937
5938<p>
5939When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5940the running coroutine suspends its execution,
5941and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5942The parameter <code>nresults</code> is the number of values from the stack
5943that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5944
5945
5946<p>
5947When the coroutine is resumed again,
5948Lua calls the given continuation function <code>k</code> to continue
5949the execution of the C&nbsp;function that yielded (see <a href="#4.5">&sect;4.5</a>).
5950This continuation function receives the same stack
5951from the previous function,
5952with the <code>n</code> results removed and
5953replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5954Moreover,
5955the continuation function receives the value <code>ctx</code>
5956that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5957
5958
5959<p>
5960Usually, this function does not return;
5961when the coroutine eventually resumes,
5962it continues executing the continuation function.
5963However, there is one special case,
5964which is when this function is called
5965from inside a line or a count hook (see <a href="#4.7">&sect;4.7</a>).
5966In that case, <code>lua_yieldk</code> should be called with no continuation
5967(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
5968and the hook should return immediately after the call.
5969Lua will yield and,
5970when the coroutine resumes again,
5971it will continue the normal execution
5972of the (Lua) function that triggered the hook.
5973
5974
5975<p>
5976This function can raise an error if it is called from a thread
5977with a pending C call with no continuation function
5978(what is called a <em>C-call boundary</em>),
5979or it is called from a thread that is not running inside a resume
5980(typically the main thread).
5981
5982
5983
5984
5985
5986
5987
5988<h2>4.7 &ndash; <a name="4.7">The Debug Interface</a></h2>
5989
5990<p>
5991Lua has no built-in debugging facilities.
5992Instead, it offers a special interface
5993by means of functions and <em>hooks</em>.
5994This interface allows the construction of different
5995kinds of debuggers, profilers, and other tools
5996that need "inside information" from the interpreter.
5997
5998
5999
6000<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
6001<pre>typedef struct lua_Debug {
6002  int event;
6003  const char *name;           /* (n) */
6004  const char *namewhat;       /* (n) */
6005  const char *what;           /* (S) */
6006  const char *source;         /* (S) */
6007  size_t srclen;              /* (S) */
6008  int currentline;            /* (l) */
6009  int linedefined;            /* (S) */
6010  int lastlinedefined;        /* (S) */
6011  unsigned char nups;         /* (u) number of upvalues */
6012  unsigned char nparams;      /* (u) number of parameters */
6013  char isvararg;              /* (u) */
6014  char istailcall;            /* (t) */
6015  unsigned short ftransfer;   /* (r) index of first value transferred */
6016  unsigned short ntransfer;   /* (r) number of transferred values */
6017  char short_src[LUA_IDSIZE]; /* (S) */
6018  /* private part */
6019  <em>other fields</em>
6020} lua_Debug;</pre>
6021
6022<p>
6023A structure used to carry different pieces of
6024information about a function or an activation record.
6025<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
6026of this structure, for later use.
6027To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
6028you must call <a href="#lua_getinfo"><code>lua_getinfo</code></a> with an appropriate parameter.
6029(Specifically, to get a field,
6030you must add the letter between parentheses in the field's comment
6031to the parameter <code>what</code> of <a href="#lua_getinfo"><code>lua_getinfo</code></a>.)
6032
6033
6034<p>
6035The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
6036
6037<ul>
6038
6039<li><b><code>source</code>: </b>
6040the source of the chunk that created the function.
6041If <code>source</code> starts with a '<code>@</code>',
6042it means that the function was defined in a file where
6043the file name follows the '<code>@</code>'.
6044If <code>source</code> starts with a '<code>=</code>',
6045the remainder of its contents describes the source in a user-dependent manner.
6046Otherwise,
6047the function was defined in a string where
6048<code>source</code> is that string.
6049</li>
6050
6051<li><b><code>srclen</code>: </b>
6052The length of the string <code>source</code>.
6053</li>
6054
6055<li><b><code>short_src</code>: </b>
6056a "printable" version of <code>source</code>, to be used in error messages.
6057</li>
6058
6059<li><b><code>linedefined</code>: </b>
6060the line number where the definition of the function starts.
6061</li>
6062
6063<li><b><code>lastlinedefined</code>: </b>
6064the line number where the definition of the function ends.
6065</li>
6066
6067<li><b><code>what</code>: </b>
6068the string <code>"Lua"</code> if the function is a Lua function,
6069<code>"C"</code> if it is a C&nbsp;function,
6070<code>"main"</code> if it is the main part of a chunk.
6071</li>
6072
6073<li><b><code>currentline</code>: </b>
6074the current line where the given function is executing.
6075When no line information is available,
6076<code>currentline</code> is set to -1.
6077</li>
6078
6079<li><b><code>name</code>: </b>
6080a reasonable name for the given function.
6081Because functions in Lua are first-class values,
6082they do not have a fixed name:
6083some functions can be the value of multiple global variables,
6084while others can be stored only in a table field.
6085The <code>lua_getinfo</code> function checks how the function was
6086called to find a suitable name.
6087If it cannot find a name,
6088then <code>name</code> is set to <code>NULL</code>.
6089</li>
6090
6091<li><b><code>namewhat</code>: </b>
6092explains the <code>name</code> field.
6093The value of <code>namewhat</code> can be
6094<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
6095<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
6096according to how the function was called.
6097(Lua uses the empty string when no other option seems to apply.)
6098</li>
6099
6100<li><b><code>istailcall</code>: </b>
6101true if this function invocation was called by a tail call.
6102In this case, the caller of this level is not in the stack.
6103</li>
6104
6105<li><b><code>nups</code>: </b>
6106the number of upvalues of the function.
6107</li>
6108
6109<li><b><code>nparams</code>: </b>
6110the number of parameters of the function
6111(always 0&nbsp;for C&nbsp;functions).
6112</li>
6113
6114<li><b><code>isvararg</code>: </b>
6115true if the function is a variadic function
6116(always true for C&nbsp;functions).
6117</li>
6118
6119<li><b><code>ftransfer</code>: </b>
6120the index in the stack of the first value being "transferred",
6121that is, parameters in a call or return values in a return.
6122(The other values are in consecutive indices.)
6123Using this index, you can access and modify these values
6124through <a href="#lua_getlocal"><code>lua_getlocal</code></a> and <a href="#lua_setlocal"><code>lua_setlocal</code></a>.
6125This field is only meaningful during a
6126call hook, denoting the first parameter,
6127or a return hook, denoting the first value being returned.
6128(For call hooks, this value is always 1.)
6129</li>
6130
6131<li><b><code>ntransfer</code>: </b>
6132The number of values being transferred (see previous item).
6133(For calls of Lua functions,
6134this value is always equal to <code>nparams</code>.)
6135</li>
6136
6137</ul>
6138
6139
6140
6141
6142<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
6143<span class="apii">[-0, +0, &ndash;]</span>
6144<pre>lua_Hook lua_gethook (lua_State *L);</pre>
6145
6146<p>
6147Returns the current hook function.
6148
6149
6150
6151
6152
6153<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
6154<span class="apii">[-0, +0, &ndash;]</span>
6155<pre>int lua_gethookcount (lua_State *L);</pre>
6156
6157<p>
6158Returns the current hook count.
6159
6160
6161
6162
6163
6164<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
6165<span class="apii">[-0, +0, &ndash;]</span>
6166<pre>int lua_gethookmask (lua_State *L);</pre>
6167
6168<p>
6169Returns the current hook mask.
6170
6171
6172
6173
6174
6175<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
6176<span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
6177<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
6178
6179<p>
6180Gets information about a specific function or function invocation.
6181
6182
6183<p>
6184To get information about a function invocation,
6185the parameter <code>ar</code> must be a valid activation record that was
6186filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6187given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6188
6189
6190<p>
6191To get information about a function, you push it onto the stack
6192and start the <code>what</code> string with the character '<code>&gt;</code>'.
6193(In that case,
6194<code>lua_getinfo</code> pops the function from the top of the stack.)
6195For instance, to know in which line a function <code>f</code> was defined,
6196you can write the following code:
6197
6198<pre>
6199     lua_Debug ar;
6200     lua_getglobal(L, "f");  /* get global 'f' */
6201     lua_getinfo(L, "&gt;S", &amp;ar);
6202     printf("%d\n", ar.linedefined);
6203</pre>
6204
6205<p>
6206Each character in the string <code>what</code>
6207selects some fields of the structure <code>ar</code> to be filled or
6208a value to be pushed on the stack.
6209(These characters are also documented in the declaration of
6210the structure <a href="#lua_Debug"><code>lua_Debug</code></a>,
6211between parentheses in the comments following each field.)
6212
6213<ul>
6214
6215<li><b>'<code>f</code>': </b>
6216pushes onto the stack the function that is
6217running at the given level;
6218</li>
6219
6220<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
6221</li>
6222
6223<li><b>'<code>n</code>': </b> fills in the fields <code>name</code> and <code>namewhat</code>;
6224</li>
6225
6226<li><b>'<code>r</code>': </b> fills in the fields <code>ftransfer</code> and <code>ntransfer</code>;
6227</li>
6228
6229<li><b>'<code>S</code>': </b>
6230fills in the fields <code>source</code>, <code>short_src</code>,
6231<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
6232</li>
6233
6234<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
6235</li>
6236
6237<li><b>'<code>u</code>': </b> fills in the fields
6238<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
6239</li>
6240
6241<li><b>'<code>L</code>': </b>
6242pushes onto the stack a table whose indices are
6243the lines on the function with some associated code,
6244that is, the lines where you can put a break point.
6245(Lines with no code include empty lines and comments.)
6246If this option is given together with option '<code>f</code>',
6247its table is pushed after the function.
6248This is the only option that can raise a memory error.
6249</li>
6250
6251</ul>
6252
6253<p>
6254This function returns 0 to signal an invalid option in <code>what</code>;
6255even then the valid options are handled correctly.
6256
6257
6258
6259
6260
6261<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
6262<span class="apii">[-0, +(0|1), &ndash;]</span>
6263<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6264
6265<p>
6266Gets information about a local variable or a temporary value
6267of a given activation record or a given function.
6268
6269
6270<p>
6271In the first case,
6272the parameter <code>ar</code> must be a valid activation record that was
6273filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6274given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6275The index <code>n</code> selects which local variable to inspect;
6276see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
6277and names.
6278
6279
6280<p>
6281<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
6282and returns its name.
6283
6284
6285<p>
6286In the second case, <code>ar</code> must be <code>NULL</code> and the function
6287to be inspected must be on the top of the stack.
6288In this case, only parameters of Lua functions are visible
6289(as there is no information about what variables are active)
6290and no values are pushed onto the stack.
6291
6292
6293<p>
6294Returns <code>NULL</code> (and pushes nothing)
6295when the index is greater than
6296the number of active local variables.
6297
6298
6299
6300
6301
6302<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
6303<span class="apii">[-0, +0, &ndash;]</span>
6304<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
6305
6306<p>
6307Gets information about the interpreter runtime stack.
6308
6309
6310<p>
6311This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
6312an identification of the <em>activation record</em>
6313of the function executing at a given level.
6314Level&nbsp;0 is the current running function,
6315whereas level <em>n+1</em> is the function that has called level <em>n</em>
6316(except for tail calls, which do not count in the stack).
6317When called with a level greater than the stack depth,
6318<a href="#lua_getstack"><code>lua_getstack</code></a> returns 0;
6319otherwise it returns 1.
6320
6321
6322
6323
6324
6325<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
6326<span class="apii">[-0, +(0|1), &ndash;]</span>
6327<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
6328
6329<p>
6330Gets information about the <code>n</code>-th upvalue
6331of the closure at index <code>funcindex</code>.
6332It pushes the upvalue's value onto the stack
6333and returns its name.
6334Returns <code>NULL</code> (and pushes nothing)
6335when the index <code>n</code> is greater than the number of upvalues.
6336
6337
6338<p>
6339See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
6340
6341
6342
6343
6344
6345<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
6346<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
6347
6348<p>
6349Type for debugging hook functions.
6350
6351
6352<p>
6353Whenever a hook is called, its <code>ar</code> argument has its field
6354<code>event</code> set to the specific event that triggered the hook.
6355Lua identifies these events with the following constants:
6356<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
6357<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
6358and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
6359Moreover, for line events, the field <code>currentline</code> is also set.
6360To get the value of any other field in <code>ar</code>,
6361the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
6362
6363
6364<p>
6365For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
6366the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
6367in this case, there will be no corresponding return event.
6368
6369
6370<p>
6371While Lua is running a hook, it disables other calls to hooks.
6372Therefore, if a hook calls back Lua to execute a function or a chunk,
6373this execution occurs without any calls to hooks.
6374
6375
6376<p>
6377Hook functions cannot have continuations,
6378that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
6379<a href="#lua_pcallk"><code>lua_pcallk</code></a>, or <a href="#lua_callk"><code>lua_callk</code></a> with a non-null <code>k</code>.
6380
6381
6382<p>
6383Hook functions can yield under the following conditions:
6384Only count and line events can yield;
6385to yield, a hook function must finish its execution
6386calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
6387(that is, with no values).
6388
6389
6390
6391
6392
6393<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
6394<span class="apii">[-0, +0, &ndash;]</span>
6395<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
6396
6397<p>
6398Sets the debugging hook function.
6399
6400
6401<p>
6402Argument <code>f</code> is the hook function.
6403<code>mask</code> specifies on which events the hook will be called:
6404it is formed by a bitwise OR of the constants
6405<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
6406<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
6407<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
6408and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
6409The <code>count</code> argument is only meaningful when the mask
6410includes <code>LUA_MASKCOUNT</code>.
6411For each event, the hook is called as explained below:
6412
6413<ul>
6414
6415<li><b>The call hook: </b> is called when the interpreter calls a function.
6416The hook is called just after Lua enters the new function.
6417</li>
6418
6419<li><b>The return hook: </b> is called when the interpreter returns from a function.
6420The hook is called just before Lua leaves the function.
6421</li>
6422
6423<li><b>The line hook: </b> is called when the interpreter is about to
6424start the execution of a new line of code,
6425or when it jumps back in the code (even to the same line).
6426This event only happens while Lua is executing a Lua function.
6427</li>
6428
6429<li><b>The count hook: </b> is called after the interpreter executes every
6430<code>count</code> instructions.
6431This event only happens while Lua is executing a Lua function.
6432</li>
6433
6434</ul>
6435
6436<p>
6437Hooks are disabled by setting <code>mask</code> to zero.
6438
6439
6440
6441
6442
6443<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
6444<span class="apii">[-(0|1), +0, &ndash;]</span>
6445<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6446
6447<p>
6448Sets the value of a local variable of a given activation record.
6449It assigns the value on the top of the stack
6450to the variable and returns its name.
6451It also pops the value from the stack.
6452
6453
6454<p>
6455Returns <code>NULL</code> (and pops nothing)
6456when the index is greater than
6457the number of active local variables.
6458
6459
6460<p>
6461Parameters <code>ar</code> and <code>n</code> are as in the function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
6462
6463
6464
6465
6466
6467<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
6468<span class="apii">[-(0|1), +0, &ndash;]</span>
6469<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
6470
6471<p>
6472Sets the value of a closure's upvalue.
6473It assigns the value on the top of the stack
6474to the upvalue and returns its name.
6475It also pops the value from the stack.
6476
6477
6478<p>
6479Returns <code>NULL</code> (and pops nothing)
6480when the index <code>n</code> is greater than the number of upvalues.
6481
6482
6483<p>
6484Parameters <code>funcindex</code> and <code>n</code> are as in
6485the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
6486
6487
6488
6489
6490
6491<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
6492<span class="apii">[-0, +0, &ndash;]</span>
6493<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
6494
6495<p>
6496Returns a unique identifier for the upvalue numbered <code>n</code>
6497from the closure at index <code>funcindex</code>.
6498
6499
6500<p>
6501These unique identifiers allow a program to check whether different
6502closures share upvalues.
6503Lua closures that share an upvalue
6504(that is, that access a same external local variable)
6505will return identical ids for those upvalue indices.
6506
6507
6508<p>
6509Parameters <code>funcindex</code> and <code>n</code> are as in
6510the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
6511but <code>n</code> cannot be greater than the number of upvalues.
6512
6513
6514
6515
6516
6517<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
6518<span class="apii">[-0, +0, &ndash;]</span>
6519<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
6520                                    int funcindex2, int n2);</pre>
6521
6522<p>
6523Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
6524refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
6525
6526
6527
6528
6529
6530
6531
6532<h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
6533
6534
6535
6536<p>
6537
6538The <em>auxiliary library</em> provides several convenient functions
6539to interface C with Lua.
6540While the basic API provides the primitive functions for all
6541interactions between C and Lua,
6542the auxiliary library provides higher-level functions for some
6543common tasks.
6544
6545
6546<p>
6547All functions and types from the auxiliary library
6548are defined in header file <code>lauxlib.h</code> and
6549have a prefix <code>luaL_</code>.
6550
6551
6552<p>
6553All functions in the auxiliary library are built on
6554top of the basic API,
6555and so they provide nothing that cannot be done with that API.
6556Nevertheless, the use of the auxiliary library ensures
6557more consistency to your code.
6558
6559
6560<p>
6561Several functions in the auxiliary library use internally some
6562extra stack slots.
6563When a function in the auxiliary library uses less than five slots,
6564it does not check the stack size;
6565it simply assumes that there are enough slots.
6566
6567
6568<p>
6569Several functions in the auxiliary library are used to
6570check C&nbsp;function arguments.
6571Because the error message is formatted for arguments
6572(e.g., "<code>bad argument #1</code>"),
6573you should not use these functions for other stack values.
6574
6575
6576<p>
6577Functions called <code>luaL_check*</code>
6578always raise an error if the check is not satisfied.
6579
6580
6581
6582
6583
6584<h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
6585
6586<p>
6587Here we list all functions and types from the auxiliary library
6588in alphabetical order.
6589
6590
6591
6592<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
6593<span class="apii">[-?, +?, <em>m</em>]</span>
6594<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
6595
6596<p>
6597Adds the byte <code>c</code> to the buffer <code>B</code>
6598(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6599
6600
6601
6602
6603
6604<hr><h3><a name="luaL_addgsub"><code>luaL_addgsub</code></a></h3><p>
6605<span class="apii">[-?, +?, <em>m</em>]</span>
6606<pre>const void luaL_addgsub (luaL_Buffer *B, const char *s,
6607                         const char *p, const char *r);</pre>
6608
6609<p>
6610Adds a copy of the string <code>s</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>),
6611replacing any occurrence of the string <code>p</code>
6612with the string <code>r</code>.
6613
6614
6615
6616
6617
6618<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
6619<span class="apii">[-?, +?, <em>m</em>]</span>
6620<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
6621
6622<p>
6623Adds the string pointed to by <code>s</code> with length <code>l</code> to
6624the buffer <code>B</code>
6625(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6626The string can contain embedded zeros.
6627
6628
6629
6630
6631
6632<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
6633<span class="apii">[-?, +?, &ndash;]</span>
6634<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
6635
6636<p>
6637Adds to the buffer <code>B</code>
6638a string of length <code>n</code> previously copied to the
6639buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
6640
6641
6642
6643
6644
6645<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
6646<span class="apii">[-?, +?, <em>m</em>]</span>
6647<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
6648
6649<p>
6650Adds the zero-terminated string pointed to by <code>s</code>
6651to the buffer <code>B</code>
6652(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6653
6654
6655
6656
6657
6658<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
6659<span class="apii">[-?, +?, <em>m</em>]</span>
6660<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
6661
6662<p>
6663Adds the value on the top of the stack
6664to the buffer <code>B</code>
6665(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6666Pops the value.
6667
6668
6669<p>
6670This is the only function on string buffers that can (and must)
6671be called with an extra element on the stack,
6672which is the value to be added to the buffer.
6673
6674
6675
6676
6677
6678<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
6679<span class="apii">[-0, +0, <em>v</em>]</span>
6680<pre>void luaL_argcheck (lua_State *L,
6681                    int cond,
6682                    int arg,
6683                    const char *extramsg);</pre>
6684
6685<p>
6686Checks whether <code>cond</code> is true.
6687If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
6688
6689
6690
6691
6692
6693<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
6694<span class="apii">[-0, +0, <em>v</em>]</span>
6695<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
6696
6697<p>
6698Raises an error reporting a problem with argument <code>arg</code>
6699of the C&nbsp;function that called it,
6700using a standard message
6701that includes <code>extramsg</code> as a comment:
6702
6703<pre>
6704     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
6705</pre><p>
6706This function never returns.
6707
6708
6709
6710
6711
6712<hr><h3><a name="luaL_argexpected"><code>luaL_argexpected</code></a></h3><p>
6713<span class="apii">[-0, +0, <em>v</em>]</span>
6714<pre>void luaL_argexpected (lua_State *L,
6715                       int cond,
6716                       int arg,
6717                       const char *tname);</pre>
6718
6719<p>
6720Checks whether <code>cond</code> is true.
6721If it is not, raises an error about the type of the argument <code>arg</code>
6722with a standard message (see <a href="#luaL_typeerror"><code>luaL_typeerror</code></a>).
6723
6724
6725
6726
6727
6728<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
6729<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
6730
6731<p>
6732Type for a <em>string buffer</em>.
6733
6734
6735<p>
6736A string buffer allows C&nbsp;code to build Lua strings piecemeal.
6737Its pattern of use is as follows:
6738
6739<ul>
6740
6741<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6742
6743<li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6744
6745<li>
6746Then add string pieces to the buffer calling any of
6747the <code>luaL_add*</code> functions.
6748</li>
6749
6750<li>
6751Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6752This call leaves the final string on the top of the stack.
6753</li>
6754
6755</ul>
6756
6757<p>
6758If you know beforehand the maximum size of the resulting string,
6759you can use the buffer like this:
6760
6761<ul>
6762
6763<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6764
6765<li>Then initialize it and preallocate a space of
6766size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6767
6768<li>Then produce the string into that space.</li>
6769
6770<li>
6771Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6772where <code>sz</code> is the total size of the resulting string
6773copied into that space (which may be less than or
6774equal to the preallocated size).
6775</li>
6776
6777</ul>
6778
6779<p>
6780During its normal operation,
6781a string buffer uses a variable number of stack slots.
6782So, while using a buffer, you cannot assume that you know where
6783the top of the stack is.
6784You can use the stack between successive calls to buffer operations
6785as long as that use is balanced;
6786that is,
6787when you call a buffer operation,
6788the stack is at the same level
6789it was immediately after the previous buffer operation.
6790(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6791After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>,
6792the stack is back to its level when the buffer was initialized,
6793plus the final string on its top.
6794
6795
6796
6797
6798
6799<hr><h3><a name="luaL_buffaddr"><code>luaL_buffaddr</code></a></h3><p>
6800<span class="apii">[-0, +0, &ndash;]</span>
6801<pre>char *luaL_buffaddr (luaL_Buffer *B);</pre>
6802
6803<p>
6804Returns the address of the current content of buffer <code>B</code>
6805(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6806Note that any addition to the buffer may invalidate this address.
6807
6808
6809
6810
6811
6812<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6813<span class="apii">[-0, +?, &ndash;]</span>
6814<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6815
6816<p>
6817Initializes a buffer <code>B</code>
6818(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6819This function does not allocate any space;
6820the buffer must be declared as a variable.
6821
6822
6823
6824
6825
6826<hr><h3><a name="luaL_bufflen"><code>luaL_bufflen</code></a></h3><p>
6827<span class="apii">[-0, +0, &ndash;]</span>
6828<pre>size_t luaL_bufflen (luaL_Buffer *B);</pre>
6829
6830<p>
6831Returns the length of the current content of buffer <code>B</code>
6832(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6833
6834
6835
6836
6837
6838<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6839<span class="apii">[-?, +?, <em>m</em>]</span>
6840<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6841
6842<p>
6843Equivalent to the sequence
6844<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6845
6846
6847
6848
6849
6850<hr><h3><a name="luaL_buffsub"><code>luaL_buffsub</code></a></h3><p>
6851<span class="apii">[-?, +?, &ndash;]</span>
6852<pre>void luaL_buffsub (luaL_Buffer *B, int n);</pre>
6853
6854<p>
6855Removes <code>n</code> bytes from the buffer <code>B</code>
6856(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6857The buffer must have at least that many bytes.
6858
6859
6860
6861
6862
6863<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6864<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6865<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6866
6867<p>
6868Calls a metamethod.
6869
6870
6871<p>
6872If the object at index <code>obj</code> has a metatable and this
6873metatable has a field <code>e</code>,
6874this function calls this field passing the object as its only argument.
6875In this case this function returns true and pushes onto the
6876stack the value returned by the call.
6877If there is no metatable or no metamethod,
6878this function returns false without pushing any value on the stack.
6879
6880
6881
6882
6883
6884<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6885<span class="apii">[-0, +0, <em>v</em>]</span>
6886<pre>void luaL_checkany (lua_State *L, int arg);</pre>
6887
6888<p>
6889Checks whether the function has an argument
6890of any type (including <b>nil</b>) at position <code>arg</code>.
6891
6892
6893
6894
6895
6896<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6897<span class="apii">[-0, +0, <em>v</em>]</span>
6898<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6899
6900<p>
6901Checks whether the function argument <code>arg</code> is an integer
6902(or can be converted to an integer)
6903and returns this integer.
6904
6905
6906
6907
6908
6909<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6910<span class="apii">[-0, +0, <em>v</em>]</span>
6911<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6912
6913<p>
6914Checks whether the function argument <code>arg</code> is a string
6915and returns this string;
6916if <code>l</code> is not <code>NULL</code> fills its referent
6917with the string's length.
6918
6919
6920<p>
6921This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6922so all conversions and caveats of that function apply here.
6923
6924
6925
6926
6927
6928<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6929<span class="apii">[-0, +0, <em>v</em>]</span>
6930<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6931
6932<p>
6933Checks whether the function argument <code>arg</code> is a number
6934and returns this number converted to a <code>lua_Number</code>.
6935
6936
6937
6938
6939
6940<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6941<span class="apii">[-0, +0, <em>v</em>]</span>
6942<pre>int luaL_checkoption (lua_State *L,
6943                      int arg,
6944                      const char *def,
6945                      const char *const lst[]);</pre>
6946
6947<p>
6948Checks whether the function argument <code>arg</code> is a string and
6949searches for this string in the array <code>lst</code>
6950(which must be NULL-terminated).
6951Returns the index in the array where the string was found.
6952Raises an error if the argument is not a string or
6953if the string cannot be found.
6954
6955
6956<p>
6957If <code>def</code> is not <code>NULL</code>,
6958the function uses <code>def</code> as a default value when
6959there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6960
6961
6962<p>
6963This is a useful function for mapping strings to C&nbsp;enums.
6964(The usual convention in Lua libraries is
6965to use strings instead of numbers to select options.)
6966
6967
6968
6969
6970
6971<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6972<span class="apii">[-0, +0, <em>v</em>]</span>
6973<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6974
6975<p>
6976Grows the stack size to <code>top + sz</code> elements,
6977raising an error if the stack cannot grow to that size.
6978<code>msg</code> is an additional text to go into the error message
6979(or <code>NULL</code> for no additional text).
6980
6981
6982
6983
6984
6985<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6986<span class="apii">[-0, +0, <em>v</em>]</span>
6987<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6988
6989<p>
6990Checks whether the function argument <code>arg</code> is a string
6991and returns this string.
6992
6993
6994<p>
6995This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6996so all conversions and caveats of that function apply here.
6997
6998
6999
7000
7001
7002<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
7003<span class="apii">[-0, +0, <em>v</em>]</span>
7004<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
7005
7006<p>
7007Checks whether the function argument <code>arg</code> has type <code>t</code>.
7008See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
7009
7010
7011
7012
7013
7014<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
7015<span class="apii">[-0, +0, <em>v</em>]</span>
7016<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
7017
7018<p>
7019Checks whether the function argument <code>arg</code> is a userdata
7020of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
7021returns the userdata's memory-block address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
7022
7023
7024
7025
7026
7027<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
7028<span class="apii">[-0, +0, <em>v</em>]</span>
7029<pre>void luaL_checkversion (lua_State *L);</pre>
7030
7031<p>
7032Checks whether the code making the call and the Lua library being called
7033are using the same version of Lua and the same numeric types.
7034
7035
7036
7037
7038
7039<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
7040<span class="apii">[-0, +?, <em>m</em>]</span>
7041<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
7042
7043<p>
7044Loads and runs the given file.
7045It is defined as the following macro:
7046
7047<pre>
7048     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
7049</pre><p>
7050It returns&nbsp;0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) if there are no errors,
7051or 1 in case of errors.
7052
7053
7054
7055
7056
7057<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
7058<span class="apii">[-0, +?, &ndash;]</span>
7059<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
7060
7061<p>
7062Loads and runs the given string.
7063It is defined as the following macro:
7064
7065<pre>
7066     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
7067</pre><p>
7068It returns&nbsp;0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) if there are no errors,
7069or 1 in case of errors.
7070
7071
7072
7073
7074
7075<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
7076<span class="apii">[-0, +0, <em>v</em>]</span>
7077<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
7078
7079<p>
7080Raises an error.
7081The error message format is given by <code>fmt</code>
7082plus any extra arguments,
7083following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
7084It also adds at the beginning of the message the file name and
7085the line number where the error occurred,
7086if this information is available.
7087
7088
7089<p>
7090This function never returns,
7091but it is an idiom to use it in C&nbsp;functions
7092as <code>return luaL_error(<em>args</em>)</code>.
7093
7094
7095
7096
7097
7098<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
7099<span class="apii">[-0, +3, <em>m</em>]</span>
7100<pre>int luaL_execresult (lua_State *L, int stat);</pre>
7101
7102<p>
7103This function produces the return values for
7104process-related functions in the standard library
7105(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
7106
7107
7108
7109
7110
7111<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
7112<span class="apii">[-0, +(1|3), <em>m</em>]</span>
7113<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
7114
7115<p>
7116This function produces the return values for
7117file-related functions in the standard library
7118(<a href="#pdf-io.open"><code>io.open</code></a>, <a href="#pdf-os.rename"><code>os.rename</code></a>, <a href="#pdf-file:seek"><code>file:seek</code></a>, etc.).
7119
7120
7121
7122
7123
7124<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
7125<span class="apii">[-0, +(0|1), <em>m</em>]</span>
7126<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
7127
7128<p>
7129Pushes onto the stack the field <code>e</code> from the metatable
7130of the object at index <code>obj</code> and returns the type of the pushed value.
7131If the object does not have a metatable,
7132or if the metatable does not have this field,
7133pushes nothing and returns <code>LUA_TNIL</code>.
7134
7135
7136
7137
7138
7139<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
7140<span class="apii">[-0, +1, <em>m</em>]</span>
7141<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
7142
7143<p>
7144Pushes onto the stack the metatable associated with the name <code>tname</code>
7145in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>),
7146or <b>nil</b> if there is no metatable associated with that name.
7147Returns the type of the pushed value.
7148
7149
7150
7151
7152
7153<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
7154<span class="apii">[-0, +1, <em>e</em>]</span>
7155<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
7156
7157<p>
7158Ensures that the value <code>t[fname]</code>,
7159where <code>t</code> is the value at index <code>idx</code>,
7160is a table,
7161and pushes that table onto the stack.
7162Returns true if it finds a previous table there
7163and false if it creates a new table.
7164
7165
7166
7167
7168
7169<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
7170<span class="apii">[-0, +1, <em>m</em>]</span>
7171<pre>const char *luaL_gsub (lua_State *L,
7172                       const char *s,
7173                       const char *p,
7174                       const char *r);</pre>
7175
7176<p>
7177Creates a copy of string <code>s</code>,
7178replacing any occurrence of the string <code>p</code>
7179with the string <code>r</code>.
7180Pushes the resulting string on the stack and returns it.
7181
7182
7183
7184
7185
7186<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
7187<span class="apii">[-0, +0, <em>e</em>]</span>
7188<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
7189
7190<p>
7191Returns the "length" of the value at the given index
7192as a number;
7193it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
7194Raises an error if the result of the operation is not an integer.
7195(This case can only happen through metamethods.)
7196
7197
7198
7199
7200
7201<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
7202<span class="apii">[-0, +1, &ndash;]</span>
7203<pre>int luaL_loadbuffer (lua_State *L,
7204                     const char *buff,
7205                     size_t sz,
7206                     const char *name);</pre>
7207
7208<p>
7209Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
7210
7211
7212
7213
7214
7215<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
7216<span class="apii">[-0, +1, &ndash;]</span>
7217<pre>int luaL_loadbufferx (lua_State *L,
7218                      const char *buff,
7219                      size_t sz,
7220                      const char *name,
7221                      const char *mode);</pre>
7222
7223<p>
7224Loads a buffer as a Lua chunk.
7225This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
7226buffer pointed to by <code>buff</code> with size <code>sz</code>.
7227
7228
7229<p>
7230This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7231<code>name</code> is the chunk name,
7232used for debug information and error messages.
7233The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7234
7235
7236
7237
7238
7239<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
7240<span class="apii">[-0, +1, <em>m</em>]</span>
7241<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
7242
7243<p>
7244Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
7245
7246
7247
7248
7249
7250<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
7251<span class="apii">[-0, +1, <em>m</em>]</span>
7252<pre>int luaL_loadfilex (lua_State *L, const char *filename,
7253                                            const char *mode);</pre>
7254
7255<p>
7256Loads a file as a Lua chunk.
7257This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
7258named <code>filename</code>.
7259If <code>filename</code> is <code>NULL</code>,
7260then it loads from the standard input.
7261The first line in the file is ignored if it starts with a <code>#</code>.
7262
7263
7264<p>
7265The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7266
7267
7268<p>
7269This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>
7270or <a href="#pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> for file-related errors.
7271
7272
7273<p>
7274As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7275it does not run it.
7276
7277
7278
7279
7280
7281<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
7282<span class="apii">[-0, +1, &ndash;]</span>
7283<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
7284
7285<p>
7286Loads a string as a Lua chunk.
7287This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
7288the zero-terminated string <code>s</code>.
7289
7290
7291<p>
7292This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7293
7294
7295<p>
7296Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7297it does not run it.
7298
7299
7300
7301
7302
7303<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
7304<span class="apii">[-0, +1, <em>m</em>]</span>
7305<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
7306
7307<p>
7308Creates a new table and registers there
7309the functions in the list <code>l</code>.
7310
7311
7312<p>
7313It is implemented as the following macro:
7314
7315<pre>
7316     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
7317</pre><p>
7318The array <code>l</code> must be the actual array,
7319not a pointer to it.
7320
7321
7322
7323
7324
7325<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
7326<span class="apii">[-0, +1, <em>m</em>]</span>
7327<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
7328
7329<p>
7330Creates a new table with a size optimized
7331to store all entries in the array <code>l</code>
7332(but does not actually store them).
7333It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
7334(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
7335
7336
7337<p>
7338It is implemented as a macro.
7339The array <code>l</code> must be the actual array,
7340not a pointer to it.
7341
7342
7343
7344
7345
7346<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
7347<span class="apii">[-0, +1, <em>m</em>]</span>
7348<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
7349
7350<p>
7351If the registry already has the key <code>tname</code>,
7352returns 0.
7353Otherwise,
7354creates a new table to be used as a metatable for userdata,
7355adds to this new table the pair <code>__name = tname</code>,
7356adds to the registry the pair <code>[tname] = new table</code>,
7357and returns 1.
7358
7359
7360<p>
7361In both cases,
7362the function pushes onto the stack the final value associated
7363with <code>tname</code> in the registry.
7364
7365
7366
7367
7368
7369<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
7370<span class="apii">[-0, +0, &ndash;]</span>
7371<pre>lua_State *luaL_newstate (void);</pre>
7372
7373<p>
7374Creates a new Lua state.
7375It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
7376allocator based on the ISO&nbsp;C allocation functions
7377and then sets a warning function and a panic function (see <a href="#4.4">&sect;4.4</a>)
7378that print messages to the standard error output.
7379
7380
7381<p>
7382Returns the new state,
7383or <code>NULL</code> if there is a memory allocation error.
7384
7385
7386
7387
7388
7389<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
7390<span class="apii">[-0, +0, <em>e</em>]</span>
7391<pre>void luaL_openlibs (lua_State *L);</pre>
7392
7393<p>
7394Opens all standard Lua libraries into the given state.
7395
7396
7397
7398
7399
7400<hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
7401<span class="apii">[-0, +0, &ndash;]</span>
7402<pre>T luaL_opt (L, func, arg, dflt);</pre>
7403
7404<p>
7405This macro is defined as follows:
7406
7407<pre>
7408     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
7409</pre><p>
7410In words, if the argument <code>arg</code> is nil or absent,
7411the macro results in the default <code>dflt</code>.
7412Otherwise, it results in the result of calling <code>func</code>
7413with the state <code>L</code> and the argument index <code>arg</code> as
7414arguments.
7415Note that it evaluates the expression <code>dflt</code> only if needed.
7416
7417
7418
7419
7420
7421<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
7422<span class="apii">[-0, +0, <em>v</em>]</span>
7423<pre>lua_Integer luaL_optinteger (lua_State *L,
7424                             int arg,
7425                             lua_Integer d);</pre>
7426
7427<p>
7428If the function argument <code>arg</code> is an integer
7429(or it is convertible to an integer),
7430returns this integer.
7431If this argument is absent or is <b>nil</b>,
7432returns <code>d</code>.
7433Otherwise, raises an error.
7434
7435
7436
7437
7438
7439<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
7440<span class="apii">[-0, +0, <em>v</em>]</span>
7441<pre>const char *luaL_optlstring (lua_State *L,
7442                             int arg,
7443                             const char *d,
7444                             size_t *l);</pre>
7445
7446<p>
7447If the function argument <code>arg</code> is a string,
7448returns this string.
7449If this argument is absent or is <b>nil</b>,
7450returns <code>d</code>.
7451Otherwise, raises an error.
7452
7453
7454<p>
7455If <code>l</code> is not <code>NULL</code>,
7456fills its referent with the result's length.
7457If the result is <code>NULL</code>
7458(only possible when returning <code>d</code> and <code>d == NULL</code>),
7459its length is considered zero.
7460
7461
7462<p>
7463This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
7464so all conversions and caveats of that function apply here.
7465
7466
7467
7468
7469
7470<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
7471<span class="apii">[-0, +0, <em>v</em>]</span>
7472<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
7473
7474<p>
7475If the function argument <code>arg</code> is a number,
7476returns this number as a <code>lua_Number</code>.
7477If this argument is absent or is <b>nil</b>,
7478returns <code>d</code>.
7479Otherwise, raises an error.
7480
7481
7482
7483
7484
7485<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
7486<span class="apii">[-0, +0, <em>v</em>]</span>
7487<pre>const char *luaL_optstring (lua_State *L,
7488                            int arg,
7489                            const char *d);</pre>
7490
7491<p>
7492If the function argument <code>arg</code> is a string,
7493returns this string.
7494If this argument is absent or is <b>nil</b>,
7495returns <code>d</code>.
7496Otherwise, raises an error.
7497
7498
7499
7500
7501
7502<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
7503<span class="apii">[-?, +?, <em>m</em>]</span>
7504<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
7505
7506<p>
7507Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
7508with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
7509
7510
7511
7512
7513
7514<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
7515<span class="apii">[-?, +?, <em>m</em>]</span>
7516<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
7517
7518<p>
7519Returns an address to a space of size <code>sz</code>
7520where you can copy a string to be added to buffer <code>B</code>
7521(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
7522After copying the string into this space you must call
7523<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
7524it to the buffer.
7525
7526
7527
7528
7529
7530<hr><h3><a name="luaL_pushfail"><code>luaL_pushfail</code></a></h3><p>
7531<span class="apii">[-0, +1, &ndash;]</span>
7532<pre>void luaL_pushfail (lua_State *L);</pre>
7533
7534<p>
7535Pushes the <b>fail</b> value onto the stack (see <a href="#6">&sect;6</a>).
7536
7537
7538
7539
7540
7541<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
7542<span class="apii">[-?, +1, <em>m</em>]</span>
7543<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
7544
7545<p>
7546Finishes the use of buffer <code>B</code> leaving the final string on
7547the top of the stack.
7548
7549
7550
7551
7552
7553<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
7554<span class="apii">[-?, +1, <em>m</em>]</span>
7555<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
7556
7557<p>
7558Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
7559
7560
7561
7562
7563
7564<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
7565<span class="apii">[-1, +0, <em>m</em>]</span>
7566<pre>int luaL_ref (lua_State *L, int t);</pre>
7567
7568<p>
7569Creates and returns a <em>reference</em>,
7570in the table at index <code>t</code>,
7571for the object on the top of the stack (and pops the object).
7572
7573
7574<p>
7575A reference is a unique integer key.
7576As long as you do not manually add integer keys into the table <code>t</code>,
7577<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
7578You can retrieve an object referred by the reference <code>r</code>
7579by calling <code>lua_rawgeti(L, t, r)</code>.
7580The function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference.
7581
7582
7583<p>
7584If the object on the top of the stack is <b>nil</b>,
7585<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
7586The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
7587from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
7588
7589
7590
7591
7592
7593<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
7594<pre>typedef struct luaL_Reg {
7595  const char *name;
7596  lua_CFunction func;
7597} luaL_Reg;</pre>
7598
7599<p>
7600Type for arrays of functions to be registered by
7601<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
7602<code>name</code> is the function name and <code>func</code> is a pointer to
7603the function.
7604Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
7605in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
7606
7607
7608
7609
7610
7611<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
7612<span class="apii">[-0, +1, <em>e</em>]</span>
7613<pre>void luaL_requiref (lua_State *L, const char *modname,
7614                    lua_CFunction openf, int glb);</pre>
7615
7616<p>
7617If <code>package.loaded[modname]</code> is not true,
7618calls the function <code>openf</code> with the string <code>modname</code> as an argument
7619and sets the call result to <code>package.loaded[modname]</code>,
7620as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
7621
7622
7623<p>
7624If <code>glb</code> is true,
7625also stores the module into the global <code>modname</code>.
7626
7627
7628<p>
7629Leaves a copy of the module on the stack.
7630
7631
7632
7633
7634
7635<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
7636<span class="apii">[-nup, +0, <em>m</em>]</span>
7637<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
7638
7639<p>
7640Registers all functions in the array <code>l</code>
7641(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
7642(below optional upvalues, see next).
7643
7644
7645<p>
7646When <code>nup</code> is not zero,
7647all functions are created with <code>nup</code> upvalues,
7648initialized with copies of the <code>nup</code> values
7649previously pushed on the stack
7650on top of the library table.
7651These values are popped from the stack after the registration.
7652
7653
7654<p>
7655A function with a <code>NULL</code> value represents a placeholder,
7656which is filled with <b>false</b>.
7657
7658
7659
7660
7661
7662<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
7663<span class="apii">[-0, +0, &ndash;]</span>
7664<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
7665
7666<p>
7667Sets the metatable of the object on the top of the stack
7668as the metatable associated with name <code>tname</code>
7669in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7670
7671
7672
7673
7674
7675<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
7676<pre>typedef struct luaL_Stream {
7677  FILE *f;
7678  lua_CFunction closef;
7679} luaL_Stream;</pre>
7680
7681<p>
7682The standard representation for file handles
7683used by the standard I/O library.
7684
7685
7686<p>
7687A file handle is implemented as a full userdata,
7688with a metatable called <code>LUA_FILEHANDLE</code>
7689(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
7690The metatable is created by the I/O library
7691(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7692
7693
7694<p>
7695This userdata must start with the structure <code>luaL_Stream</code>;
7696it can contain other data after this initial structure.
7697The field <code>f</code> points to the corresponding C stream
7698(or it can be <code>NULL</code> to indicate an incompletely created handle).
7699The field <code>closef</code> points to a Lua function
7700that will be called to close the stream
7701when the handle is closed or collected;
7702this function receives the file handle as its sole argument and
7703must return either a true value, in case of success,
7704or a false value plus an error message, in case of error.
7705Once Lua calls this field,
7706it changes the field value to <code>NULL</code>
7707to signal that the handle is closed.
7708
7709
7710
7711
7712
7713<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
7714<span class="apii">[-0, +0, <em>m</em>]</span>
7715<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
7716
7717<p>
7718This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
7719except that, when the test fails,
7720it returns <code>NULL</code> instead of raising an error.
7721
7722
7723
7724
7725
7726<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
7727<span class="apii">[-0, +1, <em>e</em>]</span>
7728<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
7729
7730<p>
7731Converts any Lua value at the given index to a C&nbsp;string
7732in a reasonable format.
7733The resulting string is pushed onto the stack and also
7734returned by the function (see <a href="#4.1.3">&sect;4.1.3</a>).
7735If <code>len</code> is not <code>NULL</code>,
7736the function also sets <code>*len</code> with the string length.
7737
7738
7739<p>
7740If the value has a metatable with a <code>__tostring</code> field,
7741then <code>luaL_tolstring</code> calls the corresponding metamethod
7742with the value as argument,
7743and uses the result of the call as its result.
7744
7745
7746
7747
7748
7749<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
7750<span class="apii">[-0, +1, <em>m</em>]</span>
7751<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
7752                     int level);</pre>
7753
7754<p>
7755Creates and pushes a traceback of the stack <code>L1</code>.
7756If <code>msg</code> is not <code>NULL</code>, it is appended
7757at the beginning of the traceback.
7758The <code>level</code> parameter tells at which level
7759to start the traceback.
7760
7761
7762
7763
7764
7765<hr><h3><a name="luaL_typeerror"><code>luaL_typeerror</code></a></h3><p>
7766<span class="apii">[-0, +0, <em>v</em>]</span>
7767<pre>int luaL_typeerror (lua_State *L, int arg, const char *tname);</pre>
7768
7769<p>
7770Raises a type error for the argument <code>arg</code>
7771of the C&nbsp;function that called it,
7772using a standard message;
7773<code>tname</code> is a "name" for the expected type.
7774This function never returns.
7775
7776
7777
7778
7779
7780<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
7781<span class="apii">[-0, +0, &ndash;]</span>
7782<pre>const char *luaL_typename (lua_State *L, int index);</pre>
7783
7784<p>
7785Returns the name of the type of the value at the given index.
7786
7787
7788
7789
7790
7791<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
7792<span class="apii">[-0, +0, &ndash;]</span>
7793<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
7794
7795<p>
7796Releases the reference <code>ref</code> from the table at index <code>t</code>
7797(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
7798The entry is removed from the table,
7799so that the referred object can be collected.
7800The reference <code>ref</code> is also freed to be used again.
7801
7802
7803<p>
7804If <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>,
7805<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
7806
7807
7808
7809
7810
7811<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
7812<span class="apii">[-0, +1, <em>m</em>]</span>
7813<pre>void luaL_where (lua_State *L, int lvl);</pre>
7814
7815<p>
7816Pushes onto the stack a string identifying the current position
7817of the control at level <code>lvl</code> in the call stack.
7818Typically this string has the following format:
7819
7820<pre>
7821     <em>chunkname</em>:<em>currentline</em>:
7822</pre><p>
7823Level&nbsp;0 is the running function,
7824level&nbsp;1 is the function that called the running function,
7825etc.
7826
7827
7828<p>
7829This function is used to build a prefix for error messages.
7830
7831
7832
7833
7834
7835
7836
7837<h1>6 &ndash; <a name="6">The Standard Libraries</a></h1>
7838
7839
7840
7841<p>
7842The standard Lua libraries provide useful functions
7843that are implemented in&nbsp;C through the C&nbsp;API.
7844Some of these functions provide essential services to the language
7845(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7846others provide access to outside services (e.g., I/O);
7847and others could be implemented in Lua itself,
7848but that for different reasons
7849deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7850
7851
7852<p>
7853All libraries are implemented through the official C&nbsp;API
7854and are provided as separate C&nbsp;modules.
7855Unless otherwise noted,
7856these library functions do not adjust its number of arguments
7857to its expected parameters.
7858For instance, a function documented as <code>foo(arg)</code>
7859should not be called without an argument.
7860
7861
7862<p>
7863The notation <b>fail</b> means a false value representing
7864some kind of failure.
7865(Currently, <b>fail</b> is equal to <b>nil</b>,
7866but that may change in future versions.
7867The recommendation is to always test the success of these functions
7868with <code>(not status)</code>, instead of <code>(status == nil)</code>.)
7869
7870
7871<p>
7872Currently, Lua has the following standard libraries:
7873
7874<ul>
7875
7876<li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7877
7878<li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7879
7880<li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7881
7882<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7883
7884<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7885
7886<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7887
7888<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7889
7890<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7891
7892<li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7893
7894<li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7895
7896</ul><p>
7897Except for the basic and the package libraries,
7898each library provides all its functions as fields of a global table
7899or as methods of its objects.
7900
7901
7902<p>
7903To have access to these libraries,
7904the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7905which opens all standard libraries.
7906Alternatively,
7907the host program can open them individually by using
7908<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7909<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7910<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7911<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7912<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7913<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF-8 library),
7914<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7915<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7916<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7917<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7918and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7919These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7920
7921
7922
7923
7924
7925<h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7926
7927<p>
7928The basic library provides core functions to Lua.
7929If you do not include this library in your application,
7930you should check carefully whether you need to provide
7931implementations for some of its facilities.
7932
7933
7934<p>
7935<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7936
7937
7938<p>
7939Raises an error if
7940the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7941otherwise, returns all its arguments.
7942In case of error,
7943<code>message</code> is the error object;
7944when absent, it defaults to "<code>assertion failed!</code>"
7945
7946
7947
7948
7949<p>
7950<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7951
7952
7953<p>
7954This function is a generic interface to the garbage collector.
7955It performs different functions according to its first argument, <code>opt</code>:
7956
7957<ul>
7958
7959<li><b>"<code>collect</code>": </b>
7960Performs a full garbage-collection cycle.
7961This is the default option.
7962</li>
7963
7964<li><b>"<code>stop</code>": </b>
7965Stops automatic execution of the garbage collector.
7966The collector will run only when explicitly invoked,
7967until a call to restart it.
7968</li>
7969
7970<li><b>"<code>restart</code>": </b>
7971Restarts automatic execution of the garbage collector.
7972</li>
7973
7974<li><b>"<code>count</code>": </b>
7975Returns the total memory in use by Lua in Kbytes.
7976The value has a fractional part,
7977so that it multiplied by 1024
7978gives the exact number of bytes in use by Lua.
7979</li>
7980
7981<li><b>"<code>step</code>": </b>
7982Performs a garbage-collection step.
7983The step "size" is controlled by <code>arg</code>.
7984With a zero value,
7985the collector will perform one basic (indivisible) step.
7986For non-zero values,
7987the collector will perform as if that amount of memory
7988(in Kbytes) had been allocated by Lua.
7989Returns <b>true</b> if the step finished a collection cycle.
7990</li>
7991
7992<li><b>"<code>isrunning</code>": </b>
7993Returns a boolean that tells whether the collector is running
7994(i.e., not stopped).
7995</li>
7996
7997<li><b>"<code>incremental</code>": </b>
7998Change the collector mode to incremental.
7999This option can be followed by three numbers:
8000the garbage-collector pause,
8001the step multiplier,
8002and the step size (see <a href="#2.5.1">&sect;2.5.1</a>).
8003A zero means to not change that value.
8004</li>
8005
8006<li><b>"<code>generational</code>": </b>
8007Change the collector mode to generational.
8008This option can be followed by two numbers:
8009the garbage-collector minor multiplier
8010and the major multiplier (see <a href="#2.5.2">&sect;2.5.2</a>).
8011A zero means to not change that value.
8012</li>
8013
8014</ul><p>
8015See <a href="#2.5">&sect;2.5</a> for more details about garbage collection
8016and some of these options.
8017
8018
8019<p>
8020This function should not be called by a finalizer.
8021
8022
8023
8024
8025<p>
8026<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
8027Opens the named file and executes its content as a Lua chunk.
8028When called without arguments,
8029<code>dofile</code> executes the content of the standard input (<code>stdin</code>).
8030Returns all values returned by the chunk.
8031In case of errors, <code>dofile</code> propagates the error
8032to its caller.
8033(That is, <code>dofile</code> does not run in protected mode.)
8034
8035
8036
8037
8038<p>
8039<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
8040Raises an error (see <a href="#2.3">&sect;2.3</a>) with <code>message</code> as the error object.
8041This function never returns.
8042
8043
8044<p>
8045Usually, <code>error</code> adds some information about the error position
8046at the beginning of the message, if the message is a string.
8047The <code>level</code> argument specifies how to get the error position.
8048With level&nbsp;1 (the default), the error position is where the
8049<code>error</code> function was called.
8050Level&nbsp;2 points the error to where the function
8051that called <code>error</code> was called; and so on.
8052Passing a level&nbsp;0 avoids the addition of error position information
8053to the message.
8054
8055
8056
8057
8058<p>
8059<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
8060A global variable (not a function) that
8061holds the global environment (see <a href="#2.2">&sect;2.2</a>).
8062Lua itself does not use this variable;
8063changing its value does not affect any environment,
8064nor vice versa.
8065
8066
8067
8068
8069<p>
8070<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
8071
8072
8073<p>
8074If <code>object</code> does not have a metatable, returns <b>nil</b>.
8075Otherwise,
8076if the object's metatable has a <code>__metatable</code> field,
8077returns the associated value.
8078Otherwise, returns the metatable of the given object.
8079
8080
8081
8082
8083<p>
8084<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
8085
8086
8087<p>
8088Returns three values (an iterator function, the table <code>t</code>, and 0)
8089so that the construction
8090
8091<pre>
8092     for i,v in ipairs(t) do <em>body</em> end
8093</pre><p>
8094will iterate over the key&ndash;value pairs
8095(<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
8096up to the first absent index.
8097
8098
8099
8100
8101<p>
8102<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
8103
8104
8105<p>
8106Loads a chunk.
8107
8108
8109<p>
8110If <code>chunk</code> is a string, the chunk is this string.
8111If <code>chunk</code> is a function,
8112<code>load</code> calls it repeatedly to get the chunk pieces.
8113Each call to <code>chunk</code> must return a string that concatenates
8114with previous results.
8115A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
8116
8117
8118<p>
8119If there are no syntactic errors,
8120<code>load</code> returns the compiled chunk as a function;
8121otherwise, it returns <b>fail</b> plus the error message.
8122
8123
8124<p>
8125When you load a main chunk,
8126the resulting function will always have exactly one upvalue,
8127the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
8128However,
8129when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
8130the resulting function can have an arbitrary number of upvalues,
8131and there is no guarantee that its first upvalue will be
8132the <code>_ENV</code> variable.
8133(A non-main function may not even have an <code>_ENV</code> upvalue.)
8134
8135
8136<p>
8137Regardless, if the resulting function has any upvalues,
8138its first upvalue is set to the value of <code>env</code>,
8139if that parameter is given,
8140or to the value of the global environment.
8141Other upvalues are initialized with <b>nil</b>.
8142All upvalues are fresh, that is,
8143they are not shared with any other function.
8144
8145
8146<p>
8147<code>chunkname</code> is used as the name of the chunk for error messages
8148and debug information (see <a href="#4.7">&sect;4.7</a>).
8149When absent,
8150it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
8151or to "<code>=(load)</code>" otherwise.
8152
8153
8154<p>
8155The string <code>mode</code> controls whether the chunk can be text or binary
8156(that is, a precompiled chunk).
8157It may be the string "<code>b</code>" (only binary chunks),
8158"<code>t</code>" (only text chunks),
8159or "<code>bt</code>" (both binary and text).
8160The default is "<code>bt</code>".
8161
8162
8163<p>
8164It is safe to load malformed binary chunks;
8165<code>load</code> signals an appropriate error.
8166However,
8167Lua does not check the consistency of the code inside binary chunks;
8168running maliciously crafted bytecode can crash the interpreter.
8169
8170
8171
8172
8173<p>
8174<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
8175
8176
8177<p>
8178Similar to <a href="#pdf-load"><code>load</code></a>,
8179but gets the chunk from file <code>filename</code>
8180or from the standard input,
8181if no file name is given.
8182
8183
8184
8185
8186<p>
8187<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
8188
8189
8190<p>
8191Allows a program to traverse all fields of a table.
8192Its first argument is a table and its second argument
8193is an index in this table.
8194A call to <code>next</code> returns the next index of the table
8195and its associated value.
8196When called with <b>nil</b> as its second argument,
8197<code>next</code> returns an initial index
8198and its associated value.
8199When called with the last index,
8200or with <b>nil</b> in an empty table,
8201<code>next</code> returns <b>nil</b>.
8202If the second argument is absent, then it is interpreted as <b>nil</b>.
8203In particular,
8204you can use <code>next(t)</code> to check whether a table is empty.
8205
8206
8207<p>
8208The order in which the indices are enumerated is not specified,
8209<em>even for numeric indices</em>.
8210(To traverse a table in numerical order,
8211use a numerical <b>for</b>.)
8212
8213
8214<p>
8215You should not assign any value to a non-existent field in a table
8216during its traversal.
8217You may however modify existing fields.
8218In particular, you may set existing fields to nil.
8219
8220
8221
8222
8223<p>
8224<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
8225
8226
8227<p>
8228If <code>t</code> has a metamethod <code>__pairs</code>,
8229calls it with <code>t</code> as argument and returns the first three
8230results from the call.
8231
8232
8233<p>
8234Otherwise,
8235returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
8236so that the construction
8237
8238<pre>
8239     for k,v in pairs(t) do <em>body</em> end
8240</pre><p>
8241will iterate over all key&ndash;value pairs of table <code>t</code>.
8242
8243
8244<p>
8245See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
8246the table during its traversal.
8247
8248
8249
8250
8251<p>
8252<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
8253
8254
8255<p>
8256Calls the function <code>f</code> with
8257the given arguments in <em>protected mode</em>.
8258This means that any error inside&nbsp;<code>f</code> is not propagated;
8259instead, <code>pcall</code> catches the error
8260and returns a status code.
8261Its first result is the status code (a boolean),
8262which is <b>true</b> if the call succeeds without errors.
8263In such case, <code>pcall</code> also returns all results from the call,
8264after this first result.
8265In case of any error, <code>pcall</code> returns <b>false</b> plus the error object.
8266Note that errors caught by <code>pcall</code> do not call a message handler.
8267
8268
8269
8270
8271<p>
8272<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
8273Receives any number of arguments
8274and prints their values to <code>stdout</code>,
8275converting each argument to a string
8276following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8277
8278
8279<p>
8280The function <code>print</code> is not intended for formatted output,
8281but only as a quick way to show a value,
8282for instance for debugging.
8283For complete control over the output,
8284use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
8285
8286
8287
8288
8289<p>
8290<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
8291Checks whether <code>v1</code> is equal to <code>v2</code>,
8292without invoking the <code>__eq</code> metamethod.
8293Returns a boolean.
8294
8295
8296
8297
8298<p>
8299<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
8300Gets the real value of <code>table[index]</code>,
8301without using the <code>__index</code> metavalue.
8302<code>table</code> must be a table;
8303<code>index</code> may be any value.
8304
8305
8306
8307
8308<p>
8309<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
8310Returns the length of the object <code>v</code>,
8311which must be a table or a string,
8312without invoking the <code>__len</code> metamethod.
8313Returns an integer.
8314
8315
8316
8317
8318<p>
8319<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
8320Sets the real value of <code>table[index]</code> to <code>value</code>,
8321without using the <code>__newindex</code> metavalue.
8322<code>table</code> must be a table,
8323<code>index</code> any value different from <b>nil</b> and NaN,
8324and <code>value</code> any Lua value.
8325
8326
8327<p>
8328This function returns <code>table</code>.
8329
8330
8331
8332
8333<p>
8334<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
8335
8336
8337<p>
8338If <code>index</code> is a number,
8339returns all arguments after argument number <code>index</code>;
8340a negative number indexes from the end (-1 is the last argument).
8341Otherwise, <code>index</code> must be the string <code>"#"</code>,
8342and <code>select</code> returns the total number of extra arguments it received.
8343
8344
8345
8346
8347<p>
8348<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
8349
8350
8351<p>
8352Sets the metatable for the given table.
8353If <code>metatable</code> is <b>nil</b>,
8354removes the metatable of the given table.
8355If the original metatable has a <code>__metatable</code> field,
8356raises an error.
8357
8358
8359<p>
8360This function returns <code>table</code>.
8361
8362
8363<p>
8364To change the metatable of other types from Lua code,
8365you must use the debug library (<a href="#6.10">&sect;6.10</a>).
8366
8367
8368
8369
8370<p>
8371<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
8372
8373
8374<p>
8375When called with no <code>base</code>,
8376<code>tonumber</code> tries to convert its argument to a number.
8377If the argument is already a number or
8378a string convertible to a number,
8379then <code>tonumber</code> returns this number;
8380otherwise, it returns <b>fail</b>.
8381
8382
8383<p>
8384The conversion of strings can result in integers or floats,
8385according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
8386The string may have leading and trailing spaces and a sign.
8387
8388
8389<p>
8390When called with <code>base</code>,
8391then <code>e</code> must be a string to be interpreted as
8392an integer numeral in that base.
8393The base may be any integer between 2 and 36, inclusive.
8394In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
8395represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
8396with '<code>Z</code>' representing 35.
8397If the string <code>e</code> is not a valid numeral in the given base,
8398the function returns <b>fail</b>.
8399
8400
8401
8402
8403<p>
8404<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
8405
8406
8407<p>
8408Receives a value of any type and
8409converts it to a string in a human-readable format.
8410
8411
8412<p>
8413If the metatable of <code>v</code> has a <code>__tostring</code> field,
8414then <code>tostring</code> calls the corresponding value
8415with <code>v</code> as argument,
8416and uses the result of the call as its result.
8417Otherwise, if the metatable of <code>v</code> has a <code>__name</code> field
8418with a string value,
8419<code>tostring</code> may use that string in its final result.
8420
8421
8422<p>
8423For complete control of how numbers are converted,
8424use <a href="#pdf-string.format"><code>string.format</code></a>.
8425
8426
8427
8428
8429<p>
8430<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
8431
8432
8433<p>
8434Returns the type of its only argument, coded as a string.
8435The possible results of this function are
8436"<code>nil</code>" (a string, not the value <b>nil</b>),
8437"<code>number</code>",
8438"<code>string</code>",
8439"<code>boolean</code>",
8440"<code>table</code>",
8441"<code>function</code>",
8442"<code>thread</code>",
8443and "<code>userdata</code>".
8444
8445
8446
8447
8448<p>
8449<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
8450
8451
8452<p>
8453A global variable (not a function) that
8454holds a string containing the running Lua version.
8455The current value of this variable is "<code>Lua 5.4</code>".
8456
8457
8458
8459
8460<p>
8461<hr><h3><a name="pdf-warn"><code>warn (msg1, &middot;&middot;&middot;)</code></a></h3>
8462
8463
8464<p>
8465Emits a warning with a message composed by the concatenation
8466of all its arguments (which should be strings).
8467
8468
8469<p>
8470By convention,
8471a one-piece message starting with '<code>@</code>'
8472is intended to be a <em>control message</em>,
8473which is a message to the warning system itself.
8474In particular, the standard warning function in Lua
8475recognizes the control messages "<code>@off</code>",
8476to stop the emission of warnings,
8477and "<code>@on</code>", to (re)start the emission;
8478it ignores unknown control messages.
8479
8480
8481
8482
8483<p>
8484<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
8485
8486
8487<p>
8488This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
8489except that it sets a new message handler <code>msgh</code>.
8490
8491
8492
8493
8494
8495
8496
8497<h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
8498
8499<p>
8500This library comprises the operations to manipulate coroutines,
8501which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
8502See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
8503
8504
8505<p>
8506<hr><h3><a name="pdf-coroutine.close"><code>coroutine.close (co)</code></a></h3>
8507
8508
8509<p>
8510Closes coroutine <code>co</code>,
8511that is,
8512closes all its pending to-be-closed variables
8513and puts the coroutine in a dead state.
8514The given coroutine must be dead or suspended.
8515In case of error
8516(either the original error that stopped the coroutine or
8517errors in closing methods),
8518returns <b>false</b> plus the error object;
8519otherwise returns <b>true</b>.
8520
8521
8522
8523
8524<p>
8525<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
8526
8527
8528<p>
8529Creates a new coroutine, with body <code>f</code>.
8530<code>f</code> must be a function.
8531Returns this new coroutine,
8532an object with type <code>"thread"</code>.
8533
8534
8535
8536
8537<p>
8538<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ([co])</code></a></h3>
8539
8540
8541<p>
8542Returns <b>true</b> when the coroutine <code>co</code> can yield.
8543The default for <code>co</code> is the running coroutine.
8544
8545
8546<p>
8547A coroutine is yieldable if it is not the main thread and
8548it is not inside a non-yieldable C&nbsp;function.
8549
8550
8551
8552
8553<p>
8554<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
8555
8556
8557<p>
8558Starts or continues the execution of coroutine <code>co</code>.
8559The first time you resume a coroutine,
8560it starts running its body.
8561The values <code>val1</code>, ... are passed
8562as the arguments to the body function.
8563If the coroutine has yielded,
8564<code>resume</code> restarts it;
8565the values <code>val1</code>, ... are passed
8566as the results from the yield.
8567
8568
8569<p>
8570If the coroutine runs without any errors,
8571<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
8572(when the coroutine yields) or any values returned by the body function
8573(when the coroutine terminates).
8574If there is any error,
8575<code>resume</code> returns <b>false</b> plus the error message.
8576
8577
8578
8579
8580<p>
8581<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
8582
8583
8584<p>
8585Returns the running coroutine plus a boolean,
8586<b>true</b> when the running coroutine is the main one.
8587
8588
8589
8590
8591<p>
8592<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
8593
8594
8595<p>
8596Returns the status of the coroutine <code>co</code>, as a string:
8597<code>"running"</code>,
8598if the coroutine is running
8599(that is, it is the one that called <code>status</code>);
8600<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
8601or if it has not started running yet;
8602<code>"normal"</code> if the coroutine is active but not running
8603(that is, it has resumed another coroutine);
8604and <code>"dead"</code> if the coroutine has finished its body function,
8605or if it has stopped with an error.
8606
8607
8608
8609
8610<p>
8611<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
8612
8613
8614<p>
8615Creates a new coroutine, with body <code>f</code>;
8616<code>f</code> must be a function.
8617Returns a function that resumes the coroutine each time it is called.
8618Any arguments passed to this function behave as the
8619extra arguments to <code>resume</code>.
8620The function returns the same values returned by <code>resume</code>,
8621except the first boolean.
8622In case of error,
8623the function closes the coroutine and propagates the error.
8624
8625
8626
8627
8628<p>
8629<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
8630
8631
8632<p>
8633Suspends the execution of the calling coroutine.
8634Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
8635
8636
8637
8638
8639
8640
8641
8642<h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
8643
8644<p>
8645The package library provides basic
8646facilities for loading modules in Lua.
8647It exports one function directly in the global environment:
8648<a href="#pdf-require"><code>require</code></a>.
8649Everything else is exported in the table <a name="pdf-package"><code>package</code></a>.
8650
8651
8652<p>
8653<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
8654
8655
8656<p>
8657Loads the given module.
8658The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
8659to determine whether <code>modname</code> is already loaded.
8660If it is, then <code>require</code> returns the value stored
8661at <code>package.loaded[modname]</code>.
8662(The absence of a second result in this case
8663signals that this call did not have to load the module.)
8664Otherwise, it tries to find a <em>loader</em> for the module.
8665
8666
8667<p>
8668To find a loader,
8669<code>require</code> is guided by the table <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8670Each item in this table is a search function,
8671that searches for the module in a particular way.
8672By changing this table,
8673we can change how <code>require</code> looks for a module.
8674The following explanation is based on the default configuration
8675for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8676
8677
8678<p>
8679First <code>require</code> queries <code>package.preload[modname]</code>.
8680If it has a value,
8681this value (which must be a function) is the loader.
8682Otherwise <code>require</code> searches for a Lua loader using the
8683path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
8684If that also fails, it searches for a C&nbsp;loader using the
8685path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8686If that also fails,
8687it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
8688
8689
8690<p>
8691Once a loader is found,
8692<code>require</code> calls the loader with two arguments:
8693<code>modname</code> and an extra value,
8694a <em>loader data</em>,
8695also returned by the searcher.
8696The loader data can be any value useful to the module;
8697for the default searchers,
8698it indicates where the loader was found.
8699(For instance, if the loader came from a file,
8700this extra value is the file path.)
8701If the loader returns any non-nil value,
8702<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
8703If the loader does not return a non-nil value and
8704has not assigned any value to <code>package.loaded[modname]</code>,
8705then <code>require</code> assigns <b>true</b> to this entry.
8706In any case, <code>require</code> returns the
8707final value of <code>package.loaded[modname]</code>.
8708Besides that value, <code>require</code> also returns as a second result
8709the loader data returned by the searcher,
8710which indicates how <code>require</code> found the module.
8711
8712
8713<p>
8714If there is any error loading or running the module,
8715or if it cannot find any loader for the module,
8716then <code>require</code> raises an error.
8717
8718
8719
8720
8721<p>
8722<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
8723
8724
8725<p>
8726A string describing some compile-time configurations for packages.
8727This string is a sequence of lines:
8728
8729<ul>
8730
8731<li>The first line is the directory separator string.
8732Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
8733
8734<li>The second line is the character that separates templates in a path.
8735Default is '<code>;</code>'.</li>
8736
8737<li>The third line is the string that marks the
8738substitution points in a template.
8739Default is '<code>?</code>'.</li>
8740
8741<li>The fourth line is a string that, in a path in Windows,
8742is replaced by the executable's directory.
8743Default is '<code>!</code>'.</li>
8744
8745<li>The fifth line is a mark to ignore all text after it
8746when building the <code>luaopen_</code> function name.
8747Default is '<code>-</code>'.</li>
8748
8749</ul>
8750
8751
8752
8753<p>
8754<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
8755
8756
8757<p>
8758A string with the path used by <a href="#pdf-require"><code>require</code></a>
8759to search for a C&nbsp;loader.
8760
8761
8762<p>
8763Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
8764it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
8765using the environment variable <a name="pdf-LUA_CPATH_5_4"><code>LUA_CPATH_5_4</code></a>,
8766or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
8767or a default path defined in <code>luaconf.h</code>.
8768
8769
8770
8771
8772<p>
8773<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
8774
8775
8776<p>
8777A table used by <a href="#pdf-require"><code>require</code></a> to control which
8778modules are already loaded.
8779When you require a module <code>modname</code> and
8780<code>package.loaded[modname]</code> is not false,
8781<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
8782
8783
8784<p>
8785This variable is only a reference to the real table;
8786assignments to this variable do not change the
8787table used by <a href="#pdf-require"><code>require</code></a>.
8788The real table is stored in the C registry (see <a href="#4.3">&sect;4.3</a>),
8789indexed by the key <a name="pdf-LUA_LOADED_TABLE"><code>LUA_LOADED_TABLE</code></a>, a string.
8790
8791
8792
8793
8794<p>
8795<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
8796
8797
8798<p>
8799Dynamically links the host program with the C&nbsp;library <code>libname</code>.
8800
8801
8802<p>
8803If <code>funcname</code> is "<code>*</code>",
8804then it only links with the library,
8805making the symbols exported by the library
8806available to other dynamically linked libraries.
8807Otherwise,
8808it looks for a function <code>funcname</code> inside the library
8809and returns this function as a C&nbsp;function.
8810So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
8811(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8812
8813
8814<p>
8815This is a low-level function.
8816It completely bypasses the package and module system.
8817Unlike <a href="#pdf-require"><code>require</code></a>,
8818it does not perform any path searching and
8819does not automatically adds extensions.
8820<code>libname</code> must be the complete file name of the C&nbsp;library,
8821including if necessary a path and an extension.
8822<code>funcname</code> must be the exact name exported by the C&nbsp;library
8823(which may depend on the C&nbsp;compiler and linker used).
8824
8825
8826<p>
8827This functionality is not supported by ISO&nbsp;C.
8828As such, it is only available on some platforms
8829(Windows, Linux, Mac OS X, Solaris, BSD,
8830plus other Unix systems that support the <code>dlfcn</code> standard).
8831
8832
8833<p>
8834This function is inherently insecure,
8835as it allows Lua to call any function in any readable dynamic
8836library in the system.
8837(Lua calls any function assuming the function
8838has a proper prototype and respects a proper protocol
8839(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8840Therefore,
8841calling an arbitrary function in an arbitrary dynamic library
8842more often than not results in an access violation.)
8843
8844
8845
8846
8847<p>
8848<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
8849
8850
8851<p>
8852A string with the path used by <a href="#pdf-require"><code>require</code></a>
8853to search for a Lua loader.
8854
8855
8856<p>
8857At start-up, Lua initializes this variable with
8858the value of the environment variable <a name="pdf-LUA_PATH_5_4"><code>LUA_PATH_5_4</code></a> or
8859the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
8860with a default path defined in <code>luaconf.h</code>,
8861if those environment variables are not defined.
8862A "<code>;;</code>" in the value of the environment variable
8863is replaced by the default path.
8864
8865
8866
8867
8868<p>
8869<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
8870
8871
8872<p>
8873A table to store loaders for specific modules
8874(see <a href="#pdf-require"><code>require</code></a>).
8875
8876
8877<p>
8878This variable is only a reference to the real table;
8879assignments to this variable do not change the
8880table used by <a href="#pdf-require"><code>require</code></a>.
8881The real table is stored in the C registry (see <a href="#4.3">&sect;4.3</a>),
8882indexed by the key <a name="pdf-LUA_PRELOAD_TABLE"><code>LUA_PRELOAD_TABLE</code></a>, a string.
8883
8884
8885
8886
8887<p>
8888<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
8889
8890
8891<p>
8892A table used by <a href="#pdf-require"><code>require</code></a> to control how to find modules.
8893
8894
8895<p>
8896Each entry in this table is a <em>searcher function</em>.
8897When looking for a module,
8898<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
8899with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
8900sole argument.
8901If the searcher finds the module,
8902it returns another function, the module <em>loader</em>,
8903plus an extra value, a <em>loader data</em>,
8904that will be passed to that loader and
8905returned as a second result by <a href="#pdf-require"><code>require</code></a>.
8906If it cannot find the module,
8907it returns a string explaining why
8908(or <b>nil</b> if it has nothing to say).
8909
8910
8911<p>
8912Lua initializes this table with four searcher functions.
8913
8914
8915<p>
8916The first searcher simply looks for a loader in the
8917<a href="#pdf-package.preload"><code>package.preload</code></a> table.
8918
8919
8920<p>
8921The second searcher looks for a loader as a Lua library,
8922using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
8923The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8924
8925
8926<p>
8927The third searcher looks for a loader as a C&nbsp;library,
8928using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8929Again,
8930the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8931For instance,
8932if the C&nbsp;path is the string
8933
8934<pre>
8935     "./?.so;./?.dll;/usr/local/?/init.so"
8936</pre><p>
8937the searcher for module <code>foo</code>
8938will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
8939and <code>/usr/local/foo/init.so</code>, in that order.
8940Once it finds a C&nbsp;library,
8941this searcher first uses a dynamic link facility to link the
8942application with the library.
8943Then it tries to find a C&nbsp;function inside the library to
8944be used as the loader.
8945The name of this C&nbsp;function is the string "<code>luaopen_</code>"
8946concatenated with a copy of the module name where each dot
8947is replaced by an underscore.
8948Moreover, if the module name has a hyphen,
8949its suffix after (and including) the first hyphen is removed.
8950For instance, if the module name is <code>a.b.c-v2.1</code>,
8951the function name will be <code>luaopen_a_b_c</code>.
8952
8953
8954<p>
8955The fourth searcher tries an <em>all-in-one loader</em>.
8956It searches the C&nbsp;path for a library for
8957the root name of the given module.
8958For instance, when requiring <code>a.b.c</code>,
8959it will search for a C&nbsp;library for <code>a</code>.
8960If found, it looks into it for an open function for
8961the submodule;
8962in our example, that would be <code>luaopen_a_b_c</code>.
8963With this facility, a package can pack several C&nbsp;submodules
8964into one single library,
8965with each submodule keeping its original open function.
8966
8967
8968<p>
8969All searchers except the first one (preload) return as the extra value
8970the file path where the module was found,
8971as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8972The first searcher always returns the string "<code>:preload:</code>".
8973
8974
8975<p>
8976Searchers should raise no errors and have no side effects in Lua.
8977(They may have side effects in C,
8978for instance by linking the application with a library.)
8979
8980
8981
8982
8983<p>
8984<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8985
8986
8987<p>
8988Searches for the given <code>name</code> in the given <code>path</code>.
8989
8990
8991<p>
8992A path is a string containing a sequence of
8993<em>templates</em> separated by semicolons.
8994For each template,
8995the function replaces each interrogation mark (if any)
8996in the template with a copy of <code>name</code>
8997wherein all occurrences of <code>sep</code>
8998(a dot, by default)
8999were replaced by <code>rep</code>
9000(the system's directory separator, by default),
9001and then tries to open the resulting file name.
9002
9003
9004<p>
9005For instance, if the path is the string
9006
9007<pre>
9008     "./?.lua;./?.lc;/usr/local/?/init.lua"
9009</pre><p>
9010the search for the name <code>foo.a</code>
9011will try to open the files
9012<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
9013<code>/usr/local/foo/a/init.lua</code>, in that order.
9014
9015
9016<p>
9017Returns the resulting name of the first file that it can
9018open in read mode (after closing the file),
9019or <b>fail</b> plus an error message if none succeeds.
9020(This error message lists all file names it tried to open.)
9021
9022
9023
9024
9025
9026
9027
9028<h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
9029
9030
9031
9032<p>
9033This library provides generic functions for string manipulation,
9034such as finding and extracting substrings, and pattern matching.
9035When indexing a string in Lua, the first character is at position&nbsp;1
9036(not at&nbsp;0, as in C).
9037Indices are allowed to be negative and are interpreted as indexing backwards,
9038from the end of the string.
9039Thus, the last character is at position -1, and so on.
9040
9041
9042<p>
9043The string library provides all its functions inside the table
9044<a name="pdf-string"><code>string</code></a>.
9045It also sets a metatable for strings
9046where the <code>__index</code> field points to the <code>string</code> table.
9047Therefore, you can use the string functions in object-oriented style.
9048For instance, <code>string.byte(s,i)</code>
9049can be written as <code>s:byte(i)</code>.
9050
9051
9052<p>
9053The string library assumes one-byte character encodings.
9054
9055
9056<p>
9057<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
9058Returns the internal numeric codes of the characters <code>s[i]</code>,
9059<code>s[i+1]</code>, ..., <code>s[j]</code>.
9060The default value for <code>i</code> is&nbsp;1;
9061the default value for <code>j</code> is&nbsp;<code>i</code>.
9062These indices are corrected
9063following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
9064
9065
9066<p>
9067Numeric codes are not necessarily portable across platforms.
9068
9069
9070
9071
9072<p>
9073<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
9074Receives zero or more integers.
9075Returns a string with length equal to the number of arguments,
9076in which each character has the internal numeric code equal
9077to its corresponding argument.
9078
9079
9080<p>
9081Numeric codes are not necessarily portable across platforms.
9082
9083
9084
9085
9086<p>
9087<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
9088
9089
9090<p>
9091Returns a string containing a binary representation
9092(a <em>binary chunk</em>)
9093of the given function,
9094so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
9095a copy of the function (but with new upvalues).
9096If <code>strip</code> is a true value,
9097the binary representation may not include all debug information
9098about the function,
9099to save space.
9100
9101
9102<p>
9103Functions with upvalues have only their number of upvalues saved.
9104When (re)loaded,
9105those upvalues receive fresh instances.
9106(See the <a href="#pdf-load"><code>load</code></a> function for details about
9107how these upvalues are initialized.
9108You can use the debug library to serialize
9109and reload the upvalues of a function
9110in a way adequate to your needs.)
9111
9112
9113
9114
9115<p>
9116<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
9117
9118
9119<p>
9120Looks for the first match of
9121<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9122If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
9123where this occurrence starts and ends;
9124otherwise, it returns <b>fail</b>.
9125A third, optional numeric argument <code>init</code> specifies
9126where to start the search;
9127its default value is&nbsp;1 and can be negative.
9128A <b>true</b> as a fourth, optional argument <code>plain</code>
9129turns off the pattern matching facilities,
9130so the function does a plain "find substring" operation,
9131with no characters in <code>pattern</code> being considered magic.
9132
9133
9134<p>
9135If the pattern has captures,
9136then in a successful match
9137the captured values are also returned,
9138after the two indices.
9139
9140
9141
9142
9143<p>
9144<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
9145
9146
9147<p>
9148Returns a formatted version of its variable number of arguments
9149following the description given in its first argument,
9150which must be a string.
9151The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
9152The only differences are that the conversion specifiers and modifiers
9153<code>F</code>, <code>n</code>, <code>*</code>, <code>h</code>, <code>L</code>, and <code>l</code> are not supported
9154and that there is an extra specifier, <code>q</code>.
9155Both width and precision, when present,
9156are limited to two digits.
9157
9158
9159<p>
9160The specifier <code>q</code> formats booleans, nil, numbers, and strings
9161in a way that the result is a valid constant in Lua source code.
9162Booleans and nil are written in the obvious way
9163(<code>true</code>, <code>false</code>, <code>nil</code>).
9164Floats are written in hexadecimal,
9165to preserve full precision.
9166A string is written between double quotes,
9167using escape sequences when necessary to ensure that
9168it can safely be read back by the Lua interpreter.
9169For instance, the call
9170
9171<pre>
9172     string.format('%q', 'a string with "quotes" and \n new line')
9173</pre><p>
9174may produce the string:
9175
9176<pre>
9177     "a string with \"quotes\" and \
9178      new line"
9179</pre><p>
9180This specifier does not support modifiers (flags, width, precision).
9181
9182
9183<p>
9184The conversion specifiers
9185<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
9186<code>G</code>, and <code>g</code> all expect a number as argument.
9187The specifiers <code>c</code>, <code>d</code>,
9188<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
9189expect an integer.
9190When Lua is compiled with a C89 compiler,
9191the specifiers <code>A</code> and <code>a</code> (hexadecimal floats)
9192do not support modifiers.
9193
9194
9195<p>
9196The specifier <code>s</code> expects a string;
9197if its argument is not a string,
9198it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
9199If the specifier has any modifier,
9200the corresponding string argument should not contain embedded zeros.
9201
9202
9203<p>
9204The specifier <code>p</code> formats the pointer
9205returned by <a href="#lua_topointer"><code>lua_topointer</code></a>.
9206That gives a unique string identifier for tables, userdata,
9207threads, strings, and functions.
9208For other values (numbers, nil, booleans),
9209this specifier results in a string representing
9210the pointer <code>NULL</code>.
9211
9212
9213
9214
9215<p>
9216<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern [, init])</code></a></h3>
9217Returns an iterator function that,
9218each time it is called,
9219returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
9220over the string <code>s</code>.
9221If <code>pattern</code> specifies no captures,
9222then the whole match is produced in each call.
9223A third, optional numeric argument <code>init</code> specifies
9224where to start the search;
9225its default value is&nbsp;1 and can be negative.
9226
9227
9228<p>
9229As an example, the following loop
9230will iterate over all the words from string <code>s</code>,
9231printing one per line:
9232
9233<pre>
9234     s = "hello world from Lua"
9235     for w in string.gmatch(s, "%a+") do
9236       print(w)
9237     end
9238</pre><p>
9239The next example collects all pairs <code>key=value</code> from the
9240given string into a table:
9241
9242<pre>
9243     t = {}
9244     s = "from=world, to=Lua"
9245     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
9246       t[k] = v
9247     end
9248</pre>
9249
9250<p>
9251For this function, a caret '<code>^</code>' at the start of a pattern does not
9252work as an anchor, as this would prevent the iteration.
9253
9254
9255
9256
9257<p>
9258<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
9259Returns a copy of <code>s</code>
9260in which all (or the first <code>n</code>, if given)
9261occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
9262replaced by a replacement string specified by <code>repl</code>,
9263which can be a string, a table, or a function.
9264<code>gsub</code> also returns, as its second value,
9265the total number of matches that occurred.
9266The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
9267
9268
9269<p>
9270If <code>repl</code> is a string, then its value is used for replacement.
9271The character&nbsp;<code>%</code> works as an escape character:
9272any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
9273with <em>d</em> between 1 and 9,
9274stands for the value of the <em>d</em>-th captured substring;
9275the sequence <code>%0</code> stands for the whole match;
9276the sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
9277
9278
9279<p>
9280If <code>repl</code> is a table, then the table is queried for every match,
9281using the first capture as the key.
9282
9283
9284<p>
9285If <code>repl</code> is a function, then this function is called every time a
9286match occurs, with all captured substrings passed as arguments,
9287in order.
9288
9289
9290<p>
9291In any case,
9292if the pattern specifies no captures,
9293then it behaves as if the whole pattern was inside a capture.
9294
9295
9296<p>
9297If the value returned by the table query or by the function call
9298is a string or a number,
9299then it is used as the replacement string;
9300otherwise, if it is <b>false</b> or <b>nil</b>,
9301then there is no replacement
9302(that is, the original match is kept in the string).
9303
9304
9305<p>
9306Here are some examples:
9307
9308<pre>
9309     x = string.gsub("hello world", "(%w+)", "%1 %1")
9310     --&gt; x="hello hello world world"
9311
9312     x = string.gsub("hello world", "%w+", "%0 %0", 1)
9313     --&gt; x="hello hello world"
9314
9315     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
9316     --&gt; x="world hello Lua from"
9317
9318     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
9319     --&gt; x="home = /home/roberto, user = roberto"
9320
9321     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
9322           return load(s)()
9323         end)
9324     --&gt; x="4+5 = 9"
9325
9326     local t = {name="lua", version="5.4"}
9327     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
9328     --&gt; x="lua-5.4.tar.gz"
9329</pre>
9330
9331
9332
9333<p>
9334<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
9335
9336
9337<p>
9338Receives a string and returns its length.
9339The empty string <code>""</code> has length 0.
9340Embedded zeros are counted,
9341so <code>"a\000bc\000"</code> has length 5.
9342
9343
9344
9345
9346<p>
9347<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
9348
9349
9350<p>
9351Receives a string and returns a copy of this string with all
9352uppercase letters changed to lowercase.
9353All other characters are left unchanged.
9354The definition of what an uppercase letter is depends on the current locale.
9355
9356
9357
9358
9359<p>
9360<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
9361
9362
9363<p>
9364Looks for the first <em>match</em> of
9365the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9366If it finds one, then <code>match</code> returns
9367the captures from the pattern;
9368otherwise it returns <b>fail</b>.
9369If <code>pattern</code> specifies no captures,
9370then the whole match is returned.
9371A third, optional numeric argument <code>init</code> specifies
9372where to start the search;
9373its default value is&nbsp;1 and can be negative.
9374
9375
9376
9377
9378<p>
9379<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
9380
9381
9382<p>
9383Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
9384serialized in binary form (packed)
9385according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9386
9387
9388
9389
9390<p>
9391<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
9392
9393
9394<p>
9395Returns the length of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
9396with the given format.
9397The format string cannot have the variable-length options
9398'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
9399
9400
9401
9402
9403<p>
9404<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
9405
9406
9407<p>
9408Returns a string that is the concatenation of <code>n</code> copies of
9409the string <code>s</code> separated by the string <code>sep</code>.
9410The default value for <code>sep</code> is the empty string
9411(that is, no separator).
9412Returns the empty string if <code>n</code> is not positive.
9413
9414
9415<p>
9416(Note that it is very easy to exhaust the memory of your machine
9417with a single call to this function.)
9418
9419
9420
9421
9422<p>
9423<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
9424
9425
9426<p>
9427Returns a string that is the string <code>s</code> reversed.
9428
9429
9430
9431
9432<p>
9433<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
9434
9435
9436<p>
9437Returns the substring of <code>s</code> that
9438starts at <code>i</code>  and continues until <code>j</code>;
9439<code>i</code> and <code>j</code> can be negative.
9440If <code>j</code> is absent, then it is assumed to be equal to -1
9441(which is the same as the string length).
9442In particular,
9443the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
9444with length <code>j</code>,
9445and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
9446returns a suffix of <code>s</code>
9447with length <code>i</code>.
9448
9449
9450<p>
9451If, after the translation of negative indices,
9452<code>i</code> is less than 1,
9453it is corrected to 1.
9454If <code>j</code> is greater than the string length,
9455it is corrected to that length.
9456If, after these corrections,
9457<code>i</code> is greater than <code>j</code>,
9458the function returns the empty string.
9459
9460
9461
9462
9463<p>
9464<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
9465
9466
9467<p>
9468Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
9469according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9470An optional <code>pos</code> marks where
9471to start reading in <code>s</code> (default is 1).
9472After the read values,
9473this function also returns the index of the first unread byte in <code>s</code>.
9474
9475
9476
9477
9478<p>
9479<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
9480
9481
9482<p>
9483Receives a string and returns a copy of this string with all
9484lowercase letters changed to uppercase.
9485All other characters are left unchanged.
9486The definition of what a lowercase letter is depends on the current locale.
9487
9488
9489
9490
9491
9492
9493
9494<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
9495
9496
9497
9498<p>
9499Patterns in Lua are described by regular strings,
9500which are interpreted as patterns by the pattern-matching functions
9501<a href="#pdf-string.find"><code>string.find</code></a>,
9502<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
9503<a href="#pdf-string.gsub"><code>string.gsub</code></a>,
9504and <a href="#pdf-string.match"><code>string.match</code></a>.
9505This section describes the syntax and the meaning
9506(that is, what they match) of these strings.
9507
9508
9509
9510
9511
9512<h4>Character Class:</h4><p>
9513A <em>character class</em> is used to represent a set of characters.
9514The following combinations are allowed in describing a character class:
9515
9516<ul>
9517
9518<li><b><em>x</em>: </b>
9519(where <em>x</em> is not one of the <em>magic characters</em>
9520<code>^$()%.[]*+-?</code>)
9521represents the character <em>x</em> itself.
9522</li>
9523
9524<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
9525
9526<li><b><code>%a</code>: </b> represents all letters.</li>
9527
9528<li><b><code>%c</code>: </b> represents all control characters.</li>
9529
9530<li><b><code>%d</code>: </b> represents all digits.</li>
9531
9532<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
9533
9534<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
9535
9536<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
9537
9538<li><b><code>%s</code>: </b> represents all space characters.</li>
9539
9540<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
9541
9542<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
9543
9544<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
9545
9546<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
9547represents the character <em>x</em>.
9548This is the standard way to escape the magic characters.
9549Any non-alphanumeric character
9550(including all punctuation characters, even the non-magical)
9551can be preceded by a '<code>%</code>' to represent itself in a pattern.
9552</li>
9553
9554<li><b><code>[<em>set</em>]</code>: </b>
9555represents the class which is the union of all
9556characters in <em>set</em>.
9557A range of characters can be specified by
9558separating the end characters of the range,
9559in ascending order, with a '<code>-</code>'.
9560All classes <code>%</code><em>x</em> described above can also be used as
9561components in <em>set</em>.
9562All other characters in <em>set</em> represent themselves.
9563For example, <code>[%w_]</code> (or <code>[_%w]</code>)
9564represents all alphanumeric characters plus the underscore,
9565<code>[0-7]</code> represents the octal digits,
9566and <code>[0-7%l%-]</code> represents the octal digits plus
9567the lowercase letters plus the '<code>-</code>' character.
9568
9569
9570<p>
9571You can put a closing square bracket in a set
9572by positioning it as the first character in the set.
9573You can put a hyphen in a set
9574by positioning it as the first or the last character in the set.
9575(You can also use an escape for both cases.)
9576
9577
9578<p>
9579The interaction between ranges and classes is not defined.
9580Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
9581have no meaning.
9582</li>
9583
9584<li><b><code>[^<em>set</em>]</code>: </b>
9585represents the complement of <em>set</em>,
9586where <em>set</em> is interpreted as above.
9587</li>
9588
9589</ul><p>
9590For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
9591the corresponding uppercase letter represents the complement of the class.
9592For instance, <code>%S</code> represents all non-space characters.
9593
9594
9595<p>
9596The definitions of letter, space, and other character groups
9597depend on the current locale.
9598In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
9599
9600
9601
9602
9603
9604<h4>Pattern Item:</h4><p>
9605A <em>pattern item</em> can be
9606
9607<ul>
9608
9609<li>
9610a single character class,
9611which matches any single character in the class;
9612</li>
9613
9614<li>
9615a single character class followed by '<code>*</code>',
9616which matches sequences of zero or more characters in the class.
9617These repetition items will always match the longest possible sequence;
9618</li>
9619
9620<li>
9621a single character class followed by '<code>+</code>',
9622which matches sequences of one or more characters in the class.
9623These repetition items will always match the longest possible sequence;
9624</li>
9625
9626<li>
9627a single character class followed by '<code>-</code>',
9628which also matches sequences of zero or more characters in the class.
9629Unlike '<code>*</code>',
9630these repetition items will always match the shortest possible sequence;
9631</li>
9632
9633<li>
9634a single character class followed by '<code>?</code>',
9635which matches zero or one occurrence of a character in the class.
9636It always matches one occurrence if possible;
9637</li>
9638
9639<li>
9640<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
9641such item matches a substring equal to the <em>n</em>-th captured string
9642(see below);
9643</li>
9644
9645<li>
9646<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
9647such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
9648and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
9649This means that, if one reads the string from left to right,
9650counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
9651the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
9652For instance, the item <code>%b()</code> matches expressions with
9653balanced parentheses.
9654</li>
9655
9656<li>
9657<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
9658such item matches an empty string at any position such that
9659the next character belongs to <em>set</em>
9660and the previous character does not belong to <em>set</em>.
9661The set <em>set</em> is interpreted as previously described.
9662The beginning and the end of the subject are handled as if
9663they were the character '<code>\0</code>'.
9664</li>
9665
9666</ul>
9667
9668
9669
9670
9671<h4>Pattern:</h4><p>
9672A <em>pattern</em> is a sequence of pattern items.
9673A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
9674beginning of the subject string.
9675A '<code>$</code>' at the end of a pattern anchors the match at the
9676end of the subject string.
9677At other positions,
9678'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
9679
9680
9681
9682
9683
9684<h4>Captures:</h4><p>
9685A pattern can contain sub-patterns enclosed in parentheses;
9686they describe <em>captures</em>.
9687When a match succeeds, the substrings of the subject string
9688that match captures are stored (<em>captured</em>) for future use.
9689Captures are numbered according to their left parentheses.
9690For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
9691the part of the string matching <code>"a*(.)%w(%s*)"</code> is
9692stored as the first capture, and therefore has number&nbsp;1;
9693the character matching "<code>.</code>" is captured with number&nbsp;2,
9694and the part matching "<code>%s*</code>" has number&nbsp;3.
9695
9696
9697<p>
9698As a special case, the capture <code>()</code> captures
9699the current string position (a number).
9700For instance, if we apply the pattern <code>"()aa()"</code> on the
9701string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
9702
9703
9704
9705
9706
9707<h4>Multiple matches:</h4><p>
9708The function <a href="#pdf-string.gsub"><code>string.gsub</code></a> and the iterator <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>
9709match multiple occurrences of the given pattern in the subject.
9710For these functions,
9711a new match is considered valid only
9712if it ends at least one byte after the end of the previous match.
9713In other words, the pattern machine never accepts the
9714empty string as a match immediately after another match.
9715As an example,
9716consider the results of the following code:
9717
9718<pre>
9719     &gt; string.gsub("abc", "()a*()", print);
9720     --&gt; 1   2
9721     --&gt; 3   3
9722     --&gt; 4   4
9723</pre><p>
9724The second and third results come from Lua matching an empty
9725string after '<code>b</code>' and another one after '<code>c</code>'.
9726Lua does not match an empty string after '<code>a</code>',
9727because it would end at the same position of the previous match.
9728
9729
9730
9731
9732
9733
9734
9735<h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
9736
9737<p>
9738The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
9739<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
9740is a format string,
9741which describes the layout of the structure being created or read.
9742
9743
9744<p>
9745A format string is a sequence of conversion options.
9746The conversion options are as follows:
9747
9748<ul>
9749<li><b><code>&lt;</code>: </b>sets little endian</li>
9750<li><b><code>&gt;</code>: </b>sets big endian</li>
9751<li><b><code>=</code>: </b>sets native endian</li>
9752<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
9753(default is native alignment)</li>
9754<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
9755<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
9756<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
9757<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
9758<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
9759<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
9760<li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
9761<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
9762<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
9763<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
9764(default is native size)</li>
9765<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
9766(default is native size)</li>
9767<li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
9768<li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
9769<li><b><code>n</code>: </b>a <code>lua_Number</code></li>
9770<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
9771<li><b><code>z</code>: </b>a zero-terminated string</li>
9772<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
9773coded as an unsigned integer with <code>n</code> bytes
9774(default is a <code>size_t</code>)</li>
9775<li><b><code>x</code>: </b>one byte of padding</li>
9776<li><b><code>X<em>op</em></code>: </b>an empty item that aligns
9777according to option <code>op</code>
9778(which is otherwise ignored)</li>
9779<li><b>'<code> </code>': </b>(space) ignored</li>
9780</ul><p>
9781(A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
9782Except for padding, spaces, and configurations
9783(options "<code>xX &lt;=&gt;!</code>"),
9784each option corresponds to an argument in <a href="#pdf-string.pack"><code>string.pack</code></a>
9785or a result in <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9786
9787
9788<p>
9789For options "<code>!<em>n</em></code>", "<code>s<em>n</em></code>", "<code>i<em>n</em></code>", and "<code>I<em>n</em></code>",
9790<code>n</code> can be any integer between 1 and 16.
9791All integral options check overflows;
9792<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
9793<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
9794For the unsigned options,
9795Lua integers are treated as unsigned values too.
9796
9797
9798<p>
9799Any format string starts as if prefixed by "<code>!1=</code>",
9800that is,
9801with maximum alignment of 1 (no alignment)
9802and native endianness.
9803
9804
9805<p>
9806Native endianness assumes that the whole system is
9807either big or little endian.
9808The packing functions will not emulate correctly the behavior
9809of mixed-endian formats.
9810
9811
9812<p>
9813Alignment works as follows:
9814For each option,
9815the format gets extra padding until the data starts
9816at an offset that is a multiple of the minimum between the
9817option size and the maximum alignment;
9818this minimum must be a power of 2.
9819Options "<code>c</code>" and "<code>z</code>" are not aligned;
9820option "<code>s</code>" follows the alignment of its starting integer.
9821
9822
9823<p>
9824All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
9825and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9826
9827
9828
9829
9830
9831
9832
9833<h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
9834
9835<p>
9836This library provides basic support for UTF-8 encoding.
9837It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
9838This library does not provide any support for Unicode other
9839than the handling of the encoding.
9840Any operation that needs the meaning of a character,
9841such as character classification, is outside its scope.
9842
9843
9844<p>
9845Unless stated otherwise,
9846all functions that expect a byte position as a parameter
9847assume that the given position is either the start of a byte sequence
9848or one plus the length of the subject string.
9849As in the string library,
9850negative indices count from the end of the string.
9851
9852
9853<p>
9854Functions that create byte sequences
9855accept all values up to <code>0x7FFFFFFF</code>,
9856as defined in the original UTF-8 specification;
9857that implies byte sequences of up to six bytes.
9858
9859
9860<p>
9861Functions that interpret byte sequences only accept
9862valid sequences (well formed and not overlong).
9863By default, they only accept byte sequences
9864that result in valid Unicode code points,
9865rejecting values greater than <code>10FFFF</code> and surrogates.
9866A boolean argument <code>lax</code>, when available,
9867lifts these checks,
9868so that all values up to <code>0x7FFFFFFF</code> are accepted.
9869(Not well formed and overlong sequences are still rejected.)
9870
9871
9872<p>
9873<hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
9874
9875
9876<p>
9877Receives zero or more integers,
9878converts each one to its corresponding UTF-8 byte sequence
9879and returns a string with the concatenation of all these sequences.
9880
9881
9882
9883
9884<p>
9885<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
9886
9887
9888<p>
9889The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xFD][\x80-\xBF]*</code>"
9890(see <a href="#6.4.1">&sect;6.4.1</a>),
9891which matches exactly one UTF-8 byte sequence,
9892assuming that the subject is a valid UTF-8 string.
9893
9894
9895
9896
9897<p>
9898<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s [, lax])</code></a></h3>
9899
9900
9901<p>
9902Returns values so that the construction
9903
9904<pre>
9905     for p, c in utf8.codes(s) do <em>body</em> end
9906</pre><p>
9907will iterate over all UTF-8 characters in string <code>s</code>,
9908with <code>p</code> being the position (in bytes) and <code>c</code> the code point
9909of each character.
9910It raises an error if it meets any invalid byte sequence.
9911
9912
9913
9914
9915<p>
9916<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j [, lax]]])</code></a></h3>
9917
9918
9919<p>
9920Returns the code points (as integers) from all characters in <code>s</code>
9921that start between byte position <code>i</code> and <code>j</code> (both included).
9922The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
9923It raises an error if it meets any invalid byte sequence.
9924
9925
9926
9927
9928<p>
9929<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j [, lax]]])</code></a></h3>
9930
9931
9932<p>
9933Returns the number of UTF-8 characters in string <code>s</code>
9934that start between positions <code>i</code> and <code>j</code> (both inclusive).
9935The default for <code>i</code> is 1 and for <code>j</code> is -1.
9936If it finds any invalid byte sequence,
9937returns <b>fail</b> plus the position of the first invalid byte.
9938
9939
9940
9941
9942<p>
9943<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
9944
9945
9946<p>
9947Returns the position (in bytes) where the encoding of the
9948<code>n</code>-th character of <code>s</code>
9949(counting from position <code>i</code>) starts.
9950A negative <code>n</code> gets characters before position <code>i</code>.
9951The default for <code>i</code> is 1 when <code>n</code> is non-negative
9952and <code>#s + 1</code> otherwise,
9953so that <code>utf8.offset(s, -n)</code> gets the offset of the
9954<code>n</code>-th character from the end of the string.
9955If the specified character is neither in the subject
9956nor right after its end,
9957the function returns <b>fail</b>.
9958
9959
9960<p>
9961As a special case,
9962when <code>n</code> is 0 the function returns the start of the encoding
9963of the character that contains the <code>i</code>-th byte of <code>s</code>.
9964
9965
9966<p>
9967This function assumes that <code>s</code> is a valid UTF-8 string.
9968
9969
9970
9971
9972
9973
9974
9975<h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
9976
9977<p>
9978This library provides generic functions for table manipulation.
9979It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
9980
9981
9982<p>
9983Remember that, whenever an operation needs the length of a table,
9984all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>).
9985All functions ignore non-numeric keys
9986in the tables given as arguments.
9987
9988
9989<p>
9990<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
9991
9992
9993<p>
9994Given a list where all elements are strings or numbers,
9995returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
9996The default value for <code>sep</code> is the empty string,
9997the default for <code>i</code> is 1,
9998and the default for <code>j</code> is <code>#list</code>.
9999If <code>i</code> is greater than <code>j</code>, returns the empty string.
10000
10001
10002
10003
10004<p>
10005<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
10006
10007
10008<p>
10009Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
10010shifting up the elements
10011<code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
10012The default value for <code>pos</code> is <code>#list+1</code>,
10013so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
10014of the list <code>t</code>.
10015
10016
10017
10018
10019<p>
10020<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
10021
10022
10023<p>
10024Moves elements from the table <code>a1</code> to the table <code>a2</code>,
10025performing the equivalent to the following
10026multiple assignment:
10027<code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
10028The default for <code>a2</code> is <code>a1</code>.
10029The destination range can overlap with the source range.
10030The number of elements to be moved must fit in a Lua integer.
10031
10032
10033<p>
10034Returns the destination table <code>a2</code>.
10035
10036
10037
10038
10039<p>
10040<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
10041
10042
10043<p>
10044Returns a new table with all arguments stored into keys 1, 2, etc.
10045and with a field "<code>n</code>" with the total number of arguments.
10046Note that the resulting table may not be a sequence,
10047if some arguments are <b>nil</b>.
10048
10049
10050
10051
10052<p>
10053<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
10054
10055
10056<p>
10057Removes from <code>list</code> the element at position <code>pos</code>,
10058returning the value of the removed element.
10059When <code>pos</code> is an integer between 1 and <code>#list</code>,
10060it shifts down the elements
10061<code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
10062and erases element <code>list[#list]</code>;
10063The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
10064or <code>#list + 1</code>.
10065
10066
10067<p>
10068The default value for <code>pos</code> is <code>#list</code>,
10069so that a call <code>table.remove(l)</code> removes the last element
10070of the list <code>l</code>.
10071
10072
10073
10074
10075<p>
10076<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
10077
10078
10079<p>
10080Sorts the list elements in a given order, <em>in-place</em>,
10081from <code>list[1]</code> to <code>list[#list]</code>.
10082If <code>comp</code> is given,
10083then it must be a function that receives two list elements
10084and returns true when the first element must come
10085before the second in the final order,
10086so that, after the sort,
10087<code>i &lt;= j</code> implies <code>not comp(list[j],list[i])</code>.
10088If <code>comp</code> is not given,
10089then the standard Lua operator <code>&lt;</code> is used instead.
10090
10091
10092<p>
10093The <code>comp</code> function must define a consistent order;
10094more formally, the function must define a strict weak order.
10095(A weak order is similar to a total order,
10096but it can equate different elements for comparison purposes.)
10097
10098
10099<p>
10100The sort algorithm is not stable:
10101Different elements considered equal by the given order
10102may have their relative positions changed by the sort.
10103
10104
10105
10106
10107<p>
10108<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
10109
10110
10111<p>
10112Returns the elements from the given list.
10113This function is equivalent to
10114
10115<pre>
10116     return list[i], list[i+1], &middot;&middot;&middot;, list[j]
10117</pre><p>
10118By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
10119
10120
10121
10122
10123
10124
10125
10126<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
10127
10128<p>
10129This library provides basic mathematical functions.
10130It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
10131Functions with the annotation "<code>integer/float</code>" give
10132integer results for integer arguments
10133and float results for non-integer arguments.
10134The rounding functions
10135<a href="#pdf-math.ceil"><code>math.ceil</code></a>, <a href="#pdf-math.floor"><code>math.floor</code></a>, and <a href="#pdf-math.modf"><code>math.modf</code></a>
10136return an integer when the result fits in the range of an integer,
10137or a float otherwise.
10138
10139
10140<p>
10141<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
10142
10143
10144<p>
10145Returns the maximum value between <code>x</code> and <code>-x</code>. (integer/float)
10146
10147
10148
10149
10150<p>
10151<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
10152
10153
10154<p>
10155Returns the arc cosine of <code>x</code> (in radians).
10156
10157
10158
10159
10160<p>
10161<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
10162
10163
10164<p>
10165Returns the arc sine of <code>x</code> (in radians).
10166
10167
10168
10169
10170<p>
10171<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
10172
10173
10174<p>
10175
10176Returns the arc tangent of <code>y/x</code> (in radians),
10177using the signs of both arguments to find the
10178quadrant of the result.
10179It also handles correctly the case of <code>x</code> being zero.
10180
10181
10182<p>
10183The default value for <code>x</code> is 1,
10184so that the call <code>math.atan(y)</code>
10185returns the arc tangent of <code>y</code>.
10186
10187
10188
10189
10190<p>
10191<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
10192
10193
10194<p>
10195Returns the smallest integral value greater than or equal to <code>x</code>.
10196
10197
10198
10199
10200<p>
10201<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
10202
10203
10204<p>
10205Returns the cosine of <code>x</code> (assumed to be in radians).
10206
10207
10208
10209
10210<p>
10211<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
10212
10213
10214<p>
10215Converts the angle <code>x</code> from radians to degrees.
10216
10217
10218
10219
10220<p>
10221<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
10222
10223
10224<p>
10225Returns the value <em>e<sup>x</sup></em>
10226(where <code>e</code> is the base of natural logarithms).
10227
10228
10229
10230
10231<p>
10232<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
10233
10234
10235<p>
10236Returns the largest integral value less than or equal to <code>x</code>.
10237
10238
10239
10240
10241<p>
10242<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
10243
10244
10245<p>
10246Returns the remainder of the division of <code>x</code> by <code>y</code>
10247that rounds the quotient towards zero. (integer/float)
10248
10249
10250
10251
10252<p>
10253<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
10254
10255
10256<p>
10257The float value <code>HUGE_VAL</code>,
10258a value greater than any other numeric value.
10259
10260
10261
10262
10263<p>
10264<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
10265
10266
10267<p>
10268Returns the logarithm of <code>x</code> in the given base.
10269The default for <code>base</code> is <em>e</em>
10270(so that the function returns the natural logarithm of <code>x</code>).
10271
10272
10273
10274
10275<p>
10276<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
10277
10278
10279<p>
10280Returns the argument with the maximum value,
10281according to the Lua operator <code>&lt;</code>.
10282
10283
10284
10285
10286<p>
10287<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
10288An integer with the maximum value for an integer.
10289
10290
10291
10292
10293<p>
10294<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
10295
10296
10297<p>
10298Returns the argument with the minimum value,
10299according to the Lua operator <code>&lt;</code>.
10300
10301
10302
10303
10304<p>
10305<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
10306An integer with the minimum value for an integer.
10307
10308
10309
10310
10311<p>
10312<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
10313
10314
10315<p>
10316Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
10317Its second result is always a float.
10318
10319
10320
10321
10322<p>
10323<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
10324
10325
10326<p>
10327The value of <em>&pi;</em>.
10328
10329
10330
10331
10332<p>
10333<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
10334
10335
10336<p>
10337Converts the angle <code>x</code> from degrees to radians.
10338
10339
10340
10341
10342<p>
10343<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
10344
10345
10346<p>
10347When called without arguments,
10348returns a pseudo-random float with uniform distribution
10349in the range  <em>[0,1)</em>.
10350When called with two integers <code>m</code> and <code>n</code>,
10351<code>math.random</code> returns a pseudo-random integer
10352with uniform distribution in the range <em>[m, n]</em>.
10353The call <code>math.random(n)</code>, for a positive <code>n</code>,
10354is equivalent to <code>math.random(1,n)</code>.
10355The call <code>math.random(0)</code> produces an integer with
10356all bits (pseudo)random.
10357
10358
10359<p>
10360This function uses the <code>xoshiro256**</code> algorithm to produce
10361pseudo-random 64-bit integers,
10362which are the results of calls with argument&nbsp;0.
10363Other results (ranges and floats)
10364are unbiased extracted from these integers.
10365
10366
10367<p>
10368Lua initializes its pseudo-random generator with the equivalent of
10369a call to <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with no arguments,
10370so that <code>math.random</code> should generate
10371different sequences of results each time the program runs.
10372
10373
10374
10375
10376<p>
10377<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed ([x [, y]])</code></a></h3>
10378
10379
10380<p>
10381When called with at least one argument,
10382the integer parameters <code>x</code> and <code>y</code> are
10383joined into a 128-bit <em>seed</em> that
10384is used to reinitialize the pseudo-random generator;
10385equal seeds produce equal sequences of numbers.
10386The default for <code>y</code> is zero.
10387
10388
10389<p>
10390When called with no arguments,
10391Lua generates a seed with
10392a weak attempt for randomness.
10393
10394
10395<p>
10396This function returns the two seed components
10397that were effectively used,
10398so that setting them again repeats the sequence.
10399
10400
10401<p>
10402To ensure a required level of randomness to the initial state
10403(or contrarily, to have a deterministic sequence,
10404for instance when debugging a program),
10405you should call <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with explicit arguments.
10406
10407
10408
10409
10410<p>
10411<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
10412
10413
10414<p>
10415Returns the sine of <code>x</code> (assumed to be in radians).
10416
10417
10418
10419
10420<p>
10421<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
10422
10423
10424<p>
10425Returns the square root of <code>x</code>.
10426(You can also use the expression <code>x^0.5</code> to compute this value.)
10427
10428
10429
10430
10431<p>
10432<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
10433
10434
10435<p>
10436Returns the tangent of <code>x</code> (assumed to be in radians).
10437
10438
10439
10440
10441<p>
10442<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
10443
10444
10445<p>
10446If the value <code>x</code> is convertible to an integer,
10447returns that integer.
10448Otherwise, returns <b>fail</b>.
10449
10450
10451
10452
10453<p>
10454<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
10455
10456
10457<p>
10458Returns "<code>integer</code>" if <code>x</code> is an integer,
10459"<code>float</code>" if it is a float,
10460or <b>fail</b> if <code>x</code> is not a number.
10461
10462
10463
10464
10465<p>
10466<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
10467
10468
10469<p>
10470Returns a boolean,
10471<b>true</b> if and only if integer <code>m</code> is below integer <code>n</code> when
10472they are compared as unsigned integers.
10473
10474
10475
10476
10477
10478
10479
10480<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
10481
10482<p>
10483The I/O library provides two different styles for file manipulation.
10484The first one uses implicit file handles;
10485that is, there are operations to set a default input file and a
10486default output file,
10487and all input/output operations are done over these default files.
10488The second style uses explicit file handles.
10489
10490
10491<p>
10492When using implicit file handles,
10493all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
10494When using explicit file handles,
10495the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
10496and then all operations are supplied as methods of the file handle.
10497
10498
10499<p>
10500The metatable for file handles provides metamethods
10501for <code>__gc</code> and <code>__close</code> that try
10502to close the file when called.
10503
10504
10505<p>
10506The table <code>io</code> also provides
10507three predefined file handles with their usual meanings from C:
10508<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>.
10509The I/O library never closes these files.
10510
10511
10512<p>
10513Unless otherwise stated,
10514all I/O functions return <b>fail</b> on failure,
10515plus an error message as a second result and
10516a system-dependent error code as a third result,
10517and some non-false value on success.
10518On non-POSIX systems,
10519the computation of the error message and error code
10520in case of errors
10521may be not thread safe,
10522because they rely on the global C variable <code>errno</code>.
10523
10524
10525<p>
10526<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
10527
10528
10529<p>
10530Equivalent to <code>file:close()</code>.
10531Without a <code>file</code>, closes the default output file.
10532
10533
10534
10535
10536<p>
10537<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
10538
10539
10540<p>
10541Equivalent to <code>io.output():flush()</code>.
10542
10543
10544
10545
10546<p>
10547<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
10548
10549
10550<p>
10551When called with a file name, it opens the named file (in text mode),
10552and sets its handle as the default input file.
10553When called with a file handle,
10554it simply sets this file handle as the default input file.
10555When called without arguments,
10556it returns the current default input file.
10557
10558
10559<p>
10560In case of errors this function raises the error,
10561instead of returning an error code.
10562
10563
10564
10565
10566<p>
10567<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3>
10568
10569
10570<p>
10571Opens the given file name in read mode
10572and returns an iterator function that
10573works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
10574When the iterator function fails to read any value,
10575it automatically closes the file.
10576Besides the iterator function,
10577<code>io.lines</code> returns three other values:
10578two <b>nil</b> values as placeholders,
10579plus the created file handle.
10580Therefore, when used in a generic <b>for</b> loop,
10581the file is closed also if the loop is interrupted by an
10582error or a <b>break</b>.
10583
10584
10585<p>
10586The call <code>io.lines()</code> (with no file name) is equivalent
10587to <code>io.input():lines("l")</code>;
10588that is, it iterates over the lines of the default input file.
10589In this case, the iterator does not close the file when the loop ends.
10590
10591
10592<p>
10593In case of errors opening the file,
10594this function raises the error,
10595instead of returning an error code.
10596
10597
10598
10599
10600<p>
10601<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
10602
10603
10604<p>
10605This function opens a file,
10606in the mode specified in the string <code>mode</code>.
10607In case of success,
10608it returns a new file handle.
10609
10610
10611<p>
10612The <code>mode</code> string can be any of the following:
10613
10614<ul>
10615<li><b>"<code>r</code>": </b> read mode (the default);</li>
10616<li><b>"<code>w</code>": </b> write mode;</li>
10617<li><b>"<code>a</code>": </b> append mode;</li>
10618<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
10619<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
10620<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
10621  writing is only allowed at the end of file.</li>
10622</ul><p>
10623The <code>mode</code> string can also have a '<code>b</code>' at the end,
10624which is needed in some systems to open the file in binary mode.
10625
10626
10627
10628
10629<p>
10630<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
10631
10632
10633<p>
10634Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
10635
10636
10637
10638
10639<p>
10640<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
10641
10642
10643<p>
10644This function is system dependent and is not available
10645on all platforms.
10646
10647
10648<p>
10649Starts the program <code>prog</code> in a separated process and returns
10650a file handle that you can use to read data from this program
10651(if <code>mode</code> is <code>"r"</code>, the default)
10652or to write data to this program
10653(if <code>mode</code> is <code>"w"</code>).
10654
10655
10656
10657
10658<p>
10659<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
10660
10661
10662<p>
10663Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
10664
10665
10666
10667
10668<p>
10669<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
10670
10671
10672<p>
10673In case of success,
10674returns a handle for a temporary file.
10675This file is opened in update mode
10676and it is automatically removed when the program ends.
10677
10678
10679
10680
10681<p>
10682<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
10683
10684
10685<p>
10686Checks whether <code>obj</code> is a valid file handle.
10687Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
10688<code>"closed file"</code> if <code>obj</code> is a closed file handle,
10689or <b>fail</b> if <code>obj</code> is not a file handle.
10690
10691
10692
10693
10694<p>
10695<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
10696
10697
10698<p>
10699Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
10700
10701
10702
10703
10704<p>
10705<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
10706
10707
10708<p>
10709Closes <code>file</code>.
10710Note that files are automatically closed when
10711their handles are garbage collected,
10712but that takes an unpredictable amount of time to happen.
10713
10714
10715<p>
10716When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
10717<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
10718returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
10719
10720
10721
10722
10723<p>
10724<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
10725
10726
10727<p>
10728Saves any written data to <code>file</code>.
10729
10730
10731
10732
10733<p>
10734<hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
10735
10736
10737<p>
10738Returns an iterator function that,
10739each time it is called,
10740reads the file according to the given formats.
10741When no format is given,
10742uses "<code>l</code>" as a default.
10743As an example, the construction
10744
10745<pre>
10746     for c in file:lines(1) do <em>body</em> end
10747</pre><p>
10748will iterate over all characters of the file,
10749starting at the current position.
10750Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
10751when the loop ends.
10752
10753
10754
10755
10756<p>
10757<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
10758
10759
10760<p>
10761Reads the file <code>file</code>,
10762according to the given formats, which specify what to read.
10763For each format,
10764the function returns a string or a number with the characters read,
10765or <b>fail</b> if it cannot read data with the specified format.
10766(In this latter case,
10767the function does not read subsequent formats.)
10768When called without arguments,
10769it uses a default format that reads the next line
10770(see below).
10771
10772
10773<p>
10774The available formats are
10775
10776<ul>
10777
10778<li><b>"<code>n</code>": </b>
10779reads a numeral and returns it as a float or an integer,
10780following the lexical conventions of Lua.
10781(The numeral may have leading whitespaces and a sign.)
10782This format always reads the longest input sequence that
10783is a valid prefix for a numeral;
10784if that prefix does not form a valid numeral
10785(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>")
10786or it is too long (more than 200 characters),
10787it is discarded and the format returns <b>fail</b>.
10788</li>
10789
10790<li><b>"<code>a</code>": </b>
10791reads the whole file, starting at the current position.
10792On end of file, it returns the empty string;
10793this format never fails.
10794</li>
10795
10796<li><b>"<code>l</code>": </b>
10797reads the next line skipping the end of line,
10798returning <b>fail</b> on end of file.
10799This is the default format.
10800</li>
10801
10802<li><b>"<code>L</code>": </b>
10803reads the next line keeping the end-of-line character (if present),
10804returning <b>fail</b> on end of file.
10805</li>
10806
10807<li><b><em>number</em>: </b>
10808reads a string with up to this number of bytes,
10809returning <b>fail</b> on end of file.
10810If <code>number</code> is zero,
10811it reads nothing and returns an empty string,
10812or <b>fail</b> on end of file.
10813</li>
10814
10815</ul><p>
10816The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
10817
10818
10819
10820
10821<p>
10822<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
10823
10824
10825<p>
10826Sets and gets the file position,
10827measured from the beginning of the file,
10828to the position given by <code>offset</code> plus a base
10829specified by the string <code>whence</code>, as follows:
10830
10831<ul>
10832<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
10833<li><b>"<code>cur</code>": </b> base is current position;</li>
10834<li><b>"<code>end</code>": </b> base is end of file;</li>
10835</ul><p>
10836In case of success, <code>seek</code> returns the final file position,
10837measured in bytes from the beginning of the file.
10838If <code>seek</code> fails, it returns <b>fail</b>,
10839plus a string describing the error.
10840
10841
10842<p>
10843The default value for <code>whence</code> is <code>"cur"</code>,
10844and for <code>offset</code> is 0.
10845Therefore, the call <code>file:seek()</code> returns the current
10846file position, without changing it;
10847the call <code>file:seek("set")</code> sets the position to the
10848beginning of the file (and returns 0);
10849and the call <code>file:seek("end")</code> sets the position to the
10850end of the file, and returns its size.
10851
10852
10853
10854
10855<p>
10856<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
10857
10858
10859<p>
10860Sets the buffering mode for a file.
10861There are three available modes:
10862
10863<ul>
10864<li><b>"<code>no</code>": </b> no buffering.</li>
10865<li><b>"<code>full</code>": </b> full buffering.</li>
10866<li><b>"<code>line</code>": </b> line buffering.</li>
10867</ul>
10868
10869<p>
10870For the last two cases,
10871<code>size</code> is a hint for the size of the buffer, in bytes.
10872The default is an appropriate size.
10873
10874
10875<p>
10876The specific behavior of each mode is non portable;
10877check the underlying ISO&nbsp;C function <code>setvbuf</code> in your platform for
10878more details.
10879
10880
10881
10882
10883<p>
10884<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
10885
10886
10887<p>
10888Writes the value of each of its arguments to <code>file</code>.
10889The arguments must be strings or numbers.
10890
10891
10892<p>
10893In case of success, this function returns <code>file</code>.
10894
10895
10896
10897
10898
10899
10900
10901<h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
10902
10903<p>
10904This library is implemented through table <a name="pdf-os"><code>os</code></a>.
10905
10906
10907<p>
10908<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
10909
10910
10911<p>
10912Returns an approximation of the amount in seconds of CPU time
10913used by the program,
10914as returned by the underlying ISO&nbsp;C function <code>clock</code>.
10915
10916
10917
10918
10919<p>
10920<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
10921
10922
10923<p>
10924Returns a string or a table containing date and time,
10925formatted according to the given string <code>format</code>.
10926
10927
10928<p>
10929If the <code>time</code> argument is present,
10930this is the time to be formatted
10931(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
10932Otherwise, <code>date</code> formats the current time.
10933
10934
10935<p>
10936If <code>format</code> starts with '<code>!</code>',
10937then the date is formatted in Coordinated Universal Time.
10938After this optional character,
10939if <code>format</code> is the string "<code>*t</code>",
10940then <code>date</code> returns a table with the following fields:
10941<code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
10942<code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59),
10943<code>sec</code> (0&ndash;61, due to leap seconds),
10944<code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1),
10945<code>yday</code> (day of the year, 1&ndash;366),
10946and <code>isdst</code> (daylight saving flag, a boolean).
10947This last field may be absent
10948if the information is not available.
10949
10950
10951<p>
10952If <code>format</code> is not "<code>*t</code>",
10953then <code>date</code> returns the date as a string,
10954formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
10955
10956
10957<p>
10958If <code>format</code> is absent, it defaults to "<code>%c</code>",
10959which gives a human-readable date and time representation
10960using the current locale.
10961
10962
10963<p>
10964On non-POSIX systems,
10965this function may be not thread safe
10966because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
10967
10968
10969
10970
10971<p>
10972<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
10973
10974
10975<p>
10976Returns the difference, in seconds,
10977from time <code>t1</code> to time <code>t2</code>
10978(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
10979In POSIX, Windows, and some other systems,
10980this value is exactly <code>t2</code><em>-</em><code>t1</code>.
10981
10982
10983
10984
10985<p>
10986<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
10987
10988
10989<p>
10990This function is equivalent to the ISO&nbsp;C function <code>system</code>.
10991It passes <code>command</code> to be executed by an operating system shell.
10992Its first result is <b>true</b>
10993if the command terminated successfully,
10994or <b>fail</b> otherwise.
10995After this first result
10996the function returns a string plus a number,
10997as follows:
10998
10999<ul>
11000
11001<li><b>"<code>exit</code>": </b>
11002the command terminated normally;
11003the following number is the exit status of the command.
11004</li>
11005
11006<li><b>"<code>signal</code>": </b>
11007the command was terminated by a signal;
11008the following number is the signal that terminated the command.
11009</li>
11010
11011</ul>
11012
11013<p>
11014When called without a <code>command</code>,
11015<code>os.execute</code> returns a boolean that is true if a shell is available.
11016
11017
11018
11019
11020<p>
11021<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
11022
11023
11024<p>
11025Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
11026If <code>code</code> is <b>true</b>,
11027the returned status is <code>EXIT_SUCCESS</code>;
11028if <code>code</code> is <b>false</b>,
11029the returned status is <code>EXIT_FAILURE</code>;
11030if <code>code</code> is a number,
11031the returned status is this number.
11032The default value for <code>code</code> is <b>true</b>.
11033
11034
11035<p>
11036If the optional second argument <code>close</code> is true,
11037the function closes the Lua state before exiting (see <a href="#lua_close"><code>lua_close</code></a>).
11038
11039
11040
11041
11042<p>
11043<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
11044
11045
11046<p>
11047Returns the value of the process environment variable <code>varname</code>
11048or <b>fail</b> if the variable is not defined.
11049
11050
11051
11052
11053<p>
11054<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
11055
11056
11057<p>
11058Deletes the file (or empty directory, on POSIX systems)
11059with the given name.
11060If this function fails, it returns <b>fail</b>
11061plus a string describing the error and the error code.
11062Otherwise, it returns true.
11063
11064
11065
11066
11067<p>
11068<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
11069
11070
11071<p>
11072Renames the file or directory named <code>oldname</code> to <code>newname</code>.
11073If this function fails, it returns <b>fail</b>,
11074plus a string describing the error and the error code.
11075Otherwise, it returns true.
11076
11077
11078
11079
11080<p>
11081<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
11082
11083
11084<p>
11085Sets the current locale of the program.
11086<code>locale</code> is a system-dependent string specifying a locale;
11087<code>category</code> is an optional string describing which category to change:
11088<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
11089<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
11090the default category is <code>"all"</code>.
11091The function returns the name of the new locale,
11092or <b>fail</b> if the request cannot be honored.
11093
11094
11095<p>
11096If <code>locale</code> is the empty string,
11097the current locale is set to an implementation-defined native locale.
11098If <code>locale</code> is the string "<code>C</code>",
11099the current locale is set to the standard C locale.
11100
11101
11102<p>
11103When called with <b>nil</b> as the first argument,
11104this function only returns the name of the current locale
11105for the given category.
11106
11107
11108<p>
11109This function may be not thread safe
11110because of its reliance on C&nbsp;function <code>setlocale</code>.
11111
11112
11113
11114
11115<p>
11116<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
11117
11118
11119<p>
11120Returns the current time when called without arguments,
11121or a time representing the local date and time specified by the given table.
11122This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
11123and may have fields
11124<code>hour</code> (default is 12),
11125<code>min</code> (default is 0),
11126<code>sec</code> (default is 0),
11127and <code>isdst</code> (default is <b>nil</b>).
11128Other fields are ignored.
11129For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
11130
11131
11132<p>
11133When the function is called,
11134the values in these fields do not need to be inside their valid ranges.
11135For instance, if <code>sec</code> is -10,
11136it means 10 seconds before the time specified by the other fields;
11137if <code>hour</code> is 1000,
11138it means 1000 hours after the time specified by the other fields.
11139
11140
11141<p>
11142The returned value is a number, whose meaning depends on your system.
11143In POSIX, Windows, and some other systems,
11144this number counts the number
11145of seconds since some given start time (the "epoch").
11146In other systems, the meaning is not specified,
11147and the number returned by <code>time</code> can be used only as an argument to
11148<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
11149
11150
11151<p>
11152When called with a table,
11153<code>os.time</code> also normalizes all the fields
11154documented in the <a href="#pdf-os.date"><code>os.date</code></a> function,
11155so that they represent the same time as before the call
11156but with values inside their valid ranges.
11157
11158
11159
11160
11161<p>
11162<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
11163
11164
11165<p>
11166Returns a string with a file name that can
11167be used for a temporary file.
11168The file must be explicitly opened before its use
11169and explicitly removed when no longer needed.
11170
11171
11172<p>
11173In POSIX systems,
11174this function also creates a file with that name,
11175to avoid security risks.
11176(Someone else might create the file with wrong permissions
11177in the time between getting the name and creating the file.)
11178You still have to open the file to use it
11179and to remove it (even if you do not use it).
11180
11181
11182<p>
11183When possible,
11184you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
11185which automatically removes the file when the program ends.
11186
11187
11188
11189
11190
11191
11192
11193<h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
11194
11195<p>
11196This library provides
11197the functionality of the debug interface (<a href="#4.7">&sect;4.7</a>) to Lua programs.
11198You should exert care when using this library.
11199Several of its functions
11200violate basic assumptions about Lua code
11201(e.g., that variables local to a function
11202cannot be accessed from outside;
11203that userdata metatables cannot be changed by Lua code;
11204that Lua programs do not crash)
11205and therefore can compromise otherwise secure code.
11206Moreover, some functions in this library may be slow.
11207
11208
11209<p>
11210All functions in this library are provided
11211inside the <a name="pdf-debug"><code>debug</code></a> table.
11212All functions that operate over a thread
11213have an optional first argument which is the
11214thread to operate over.
11215The default is always the current thread.
11216
11217
11218<p>
11219<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
11220
11221
11222<p>
11223Enters an interactive mode with the user,
11224running each string that the user enters.
11225Using simple commands and other debug facilities,
11226the user can inspect global and local variables,
11227change their values, evaluate expressions, and so on.
11228A line containing only the word <code>cont</code> finishes this function,
11229so that the caller continues its execution.
11230
11231
11232<p>
11233Note that commands for <code>debug.debug</code> are not lexically nested
11234within any function and so have no direct access to local variables.
11235
11236
11237
11238
11239<p>
11240<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
11241
11242
11243<p>
11244Returns the current hook settings of the thread, as three values:
11245the current hook function, the current hook mask,
11246and the current hook count,
11247as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function.
11248
11249
11250<p>
11251Returns <b>fail</b> if there is no active hook.
11252
11253
11254
11255
11256<p>
11257<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
11258
11259
11260<p>
11261Returns a table with information about a function.
11262You can give the function directly
11263or you can give a number as the value of <code>f</code>,
11264which means the function running at level <code>f</code> of the call stack
11265of the given thread:
11266level&nbsp;0 is the current function (<code>getinfo</code> itself);
11267level&nbsp;1 is the function that called <code>getinfo</code>
11268(except for tail calls, which do not count in the stack);
11269and so on.
11270If <code>f</code> is a number greater than the number of active functions,
11271then <code>getinfo</code> returns <b>fail</b>.
11272
11273
11274<p>
11275The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
11276with the string <code>what</code> describing which fields to fill in.
11277The default for <code>what</code> is to get all information available,
11278except the table of valid lines.
11279If present,
11280the option '<code>f</code>'
11281adds a field named <code>func</code> with the function itself.
11282If present,
11283the option '<code>L</code>'
11284adds a field named <code>activelines</code> with the table of
11285valid lines.
11286
11287
11288<p>
11289For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
11290a name for the current function,
11291if a reasonable name can be found,
11292and the expression <code>debug.getinfo(print)</code>
11293returns a table with all available information
11294about the <a href="#pdf-print"><code>print</code></a> function.
11295
11296
11297
11298
11299<p>
11300<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
11301
11302
11303<p>
11304This function returns the name and the value of the local variable
11305with index <code>local</code> of the function at level <code>f</code> of the stack.
11306This function accesses not only explicit local variables,
11307but also parameters and temporary values.
11308
11309
11310<p>
11311The first parameter or local variable has index&nbsp;1, and so on,
11312following the order that they are declared in the code,
11313counting only the variables that are active
11314in the current scope of the function.
11315Compile-time constants may not appear in this listing,
11316if they were optimized away by the compiler.
11317Negative indices refer to vararg arguments;
11318-1 is the first vararg argument.
11319The function returns <b>fail</b>
11320if there is no variable with the given index,
11321and raises an error when called with a level out of range.
11322(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
11323
11324
11325<p>
11326Variable names starting with '<code>(</code>' (open parenthesis)
11327represent variables with no known names
11328(internal variables such as loop control variables,
11329and variables from chunks saved without debug information).
11330
11331
11332<p>
11333The parameter <code>f</code> may also be a function.
11334In that case, <code>getlocal</code> returns only the name of function parameters.
11335
11336
11337
11338
11339<p>
11340<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
11341
11342
11343<p>
11344Returns the metatable of the given <code>value</code>
11345or <b>nil</b> if it does not have a metatable.
11346
11347
11348
11349
11350<p>
11351<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
11352
11353
11354<p>
11355Returns the registry table (see <a href="#4.3">&sect;4.3</a>).
11356
11357
11358
11359
11360<p>
11361<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
11362
11363
11364<p>
11365This function returns the name and the value of the upvalue
11366with index <code>up</code> of the function <code>f</code>.
11367The function returns <b>fail</b>
11368if there is no upvalue with the given index.
11369
11370
11371<p>
11372(For Lua functions,
11373upvalues are the external local variables that the function uses,
11374and that are consequently included in its closure.)
11375
11376
11377<p>
11378For C&nbsp;functions, this function uses the empty string <code>""</code>
11379as a name for all upvalues.
11380
11381
11382<p>
11383Variable name '<code>?</code>' (interrogation mark)
11384represents variables with no known names
11385(variables from chunks saved without debug information).
11386
11387
11388
11389
11390<p>
11391<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u, n)</code></a></h3>
11392
11393
11394<p>
11395Returns the <code>n</code>-th user value associated
11396to the userdata <code>u</code> plus a boolean,
11397<b>false</b> if the userdata does not have that value.
11398
11399
11400
11401
11402<p>
11403<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
11404
11405
11406<p>
11407Sets the given function as the debug hook.
11408The string <code>mask</code> and the number <code>count</code> describe
11409when the hook will be called.
11410The string mask may have any combination of the following characters,
11411with the given meaning:
11412
11413<ul>
11414<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
11415<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
11416<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
11417</ul><p>
11418Moreover,
11419with a <code>count</code> different from zero,
11420the hook is called also after every <code>count</code> instructions.
11421
11422
11423<p>
11424When called without arguments,
11425<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
11426
11427
11428<p>
11429When the hook is called, its first parameter is a string
11430describing the event that has triggered its call:
11431<code>"call"</code>, <code>"tail call"</code>, <code>"return"</code>,
11432<code>"line"</code>, and <code>"count"</code>.
11433For line events,
11434the hook also gets the new line number as its second parameter.
11435Inside a hook,
11436you can call <code>getinfo</code> with level&nbsp;2 to get more information about
11437the running function.
11438(Level&nbsp;0 is the <code>getinfo</code> function,
11439and level&nbsp;1 is the hook function.)
11440
11441
11442
11443
11444<p>
11445<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
11446
11447
11448<p>
11449This function assigns the value <code>value</code> to the local variable
11450with index <code>local</code> of the function at level <code>level</code> of the stack.
11451The function returns <b>fail</b> if there is no local
11452variable with the given index,
11453and raises an error when called with a <code>level</code> out of range.
11454(You can call <code>getinfo</code> to check whether the level is valid.)
11455Otherwise, it returns the name of the local variable.
11456
11457
11458<p>
11459See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
11460variable indices and names.
11461
11462
11463
11464
11465<p>
11466<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
11467
11468
11469<p>
11470Sets the metatable for the given <code>value</code> to the given <code>table</code>
11471(which can be <b>nil</b>).
11472Returns <code>value</code>.
11473
11474
11475
11476
11477<p>
11478<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
11479
11480
11481<p>
11482This function assigns the value <code>value</code> to the upvalue
11483with index <code>up</code> of the function <code>f</code>.
11484The function returns <b>fail</b> if there is no upvalue
11485with the given index.
11486Otherwise, it returns the name of the upvalue.
11487
11488
11489<p>
11490See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
11491
11492
11493
11494
11495<p>
11496<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value, n)</code></a></h3>
11497
11498
11499<p>
11500Sets the given <code>value</code> as
11501the <code>n</code>-th user value associated to the given <code>udata</code>.
11502<code>udata</code> must be a full userdata.
11503
11504
11505<p>
11506Returns <code>udata</code>,
11507or <b>fail</b> if the userdata does not have that value.
11508
11509
11510
11511
11512<p>
11513<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
11514
11515
11516<p>
11517If <code>message</code> is present but is neither a string nor <b>nil</b>,
11518this function returns <code>message</code> without further processing.
11519Otherwise,
11520it returns a string with a traceback of the call stack.
11521The optional <code>message</code> string is appended
11522at the beginning of the traceback.
11523An optional <code>level</code> number tells at which level
11524to start the traceback
11525(default is 1, the function calling <code>traceback</code>).
11526
11527
11528
11529
11530<p>
11531<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
11532
11533
11534<p>
11535Returns a unique identifier (as a light userdata)
11536for the upvalue numbered <code>n</code>
11537from the given function.
11538
11539
11540<p>
11541These unique identifiers allow a program to check whether different
11542closures share upvalues.
11543Lua closures that share an upvalue
11544(that is, that access a same external local variable)
11545will return identical ids for those upvalue indices.
11546
11547
11548
11549
11550<p>
11551<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
11552
11553
11554<p>
11555Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
11556refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
11557
11558
11559
11560
11561
11562
11563
11564<h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
11565
11566<p>
11567Although Lua has been designed as an extension language,
11568to be embedded in a host C&nbsp;program,
11569it is also frequently used as a standalone language.
11570An interpreter for Lua as a standalone language,
11571called simply <code>lua</code>,
11572is provided with the standard distribution.
11573The standalone interpreter includes
11574all standard libraries.
11575Its usage is:
11576
11577<pre>
11578     lua [options] [script [args]]
11579</pre><p>
11580The options are:
11581
11582<ul>
11583<li><b><code>-e <em>stat</em></code>: </b> execute string <em>stat</em>;</li>
11584<li><b><code>-i</code>: </b> enter interactive mode after running <em>script</em>;</li>
11585<li><b><code>-l <em>mod</em></code>: </b> "require" <em>mod</em> and assign the
11586  result to global <em>mod</em>;</li>
11587<li><b><code>-l <em>g=mod</em></code>: </b> "require" <em>mod</em> and assign the
11588  result to global <em>g</em>;</li>
11589<li><b><code>-v</code>: </b> print version information;</li>
11590<li><b><code>-E</code>: </b> ignore environment variables;</li>
11591<li><b><code>-W</code>: </b> turn warnings on;</li>
11592<li><b><code>--</code>: </b> stop handling options;</li>
11593<li><b><code>-</code>: </b> execute <code>stdin</code> as a file and stop handling options.</li>
11594</ul><p>
11595(The form <code>-l <em>g=mod</em></code> was introduced in release&nbsp;5.4.4.)
11596
11597
11598<p>
11599After handling its options, <code>lua</code> runs the given <em>script</em>.
11600When called without arguments,
11601<code>lua</code> behaves as <code>lua -v -i</code>
11602when the standard input (<code>stdin</code>) is a terminal,
11603and as <code>lua -</code> otherwise.
11604
11605
11606<p>
11607When called without the option <code>-E</code>,
11608the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_4"><code>LUA_INIT_5_4</code></a>
11609(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
11610before running any argument.
11611If the variable content has the format <code>@<em>filename</em></code>,
11612then <code>lua</code> executes the file.
11613Otherwise, <code>lua</code> executes the string itself.
11614
11615
11616<p>
11617When called with the option <code>-E</code>,
11618Lua does not consult any environment variables.
11619In particular,
11620the values of <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
11621are set with the default paths defined in <code>luaconf.h</code>.
11622
11623
11624<p>
11625The options <code>-e</code>, <code>-l</code>, and <code>-W</code> are handled in
11626the order they appear.
11627For instance, an invocation like
11628
11629<pre>
11630     $ lua -e 'a=1' -llib1 script.lua
11631</pre><p>
11632will first set <code>a</code> to 1, then require the library <code>lib1</code>,
11633and finally run the file <code>script.lua</code> with no arguments.
11634(Here <code>$</code> is the shell prompt. Your prompt may be different.)
11635
11636
11637<p>
11638Before running any code,
11639<code>lua</code> collects all command-line arguments
11640in a global table called <code>arg</code>.
11641The script name goes to index 0,
11642the first argument after the script name goes to index 1,
11643and so on.
11644Any arguments before the script name
11645(that is, the interpreter name plus its options)
11646go to negative indices.
11647For instance, in the call
11648
11649<pre>
11650     $ lua -la b.lua t1 t2
11651</pre><p>
11652the table is like this:
11653
11654<pre>
11655     arg = { [-2] = "lua", [-1] = "-la",
11656             [0] = "b.lua",
11657             [1] = "t1", [2] = "t2" }
11658</pre><p>
11659If there is no script in the call,
11660the interpreter name goes to index 0,
11661followed by the other arguments.
11662For instance, the call
11663
11664<pre>
11665     $ lua -e "print(arg[1])"
11666</pre><p>
11667will print "<code>-e</code>".
11668If there is a script,
11669the script is called with arguments
11670<code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
11671Like all chunks in Lua,
11672the script is compiled as a variadic function.
11673
11674
11675<p>
11676In interactive mode,
11677Lua repeatedly prompts and waits for a line.
11678After reading a line,
11679Lua first try to interpret the line as an expression.
11680If it succeeds, it prints its value.
11681Otherwise, it interprets the line as a statement.
11682If you write an incomplete statement,
11683the interpreter waits for its completion
11684by issuing a different prompt.
11685
11686
11687<p>
11688If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
11689then its value is used as the prompt.
11690Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
11691its value is used as the secondary prompt
11692(issued during incomplete statements).
11693
11694
11695<p>
11696In case of unprotected errors in the script,
11697the interpreter reports the error to the standard error stream.
11698If the error object is not a string but
11699has a metamethod <code>__tostring</code>,
11700the interpreter calls this metamethod to produce the final message.
11701Otherwise, the interpreter converts the error object to a string
11702and adds a stack traceback to it.
11703When warnings are on,
11704they are simply printed in the standard error output.
11705
11706
11707<p>
11708When finishing normally,
11709the interpreter closes its main Lua state
11710(see <a href="#lua_close"><code>lua_close</code></a>).
11711The script can avoid this step by
11712calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
11713
11714
11715<p>
11716To allow the use of Lua as a
11717script interpreter in Unix systems,
11718Lua skips the first line of a file chunk if it starts with <code>#</code>.
11719Therefore, Lua scripts can be made into executable programs
11720by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
11721as in
11722
11723<pre>
11724     #!/usr/local/bin/lua
11725</pre><p>
11726Of course,
11727the location of the Lua interpreter may be different in your machine.
11728If <code>lua</code> is in your <code>PATH</code>,
11729then
11730
11731<pre>
11732     #!/usr/bin/env lua
11733</pre><p>
11734is a more portable solution.
11735
11736
11737
11738<h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
11739
11740
11741
11742<p>
11743Here we list the incompatibilities that you may find when moving a program
11744from Lua&nbsp;5.3 to Lua&nbsp;5.4.
11745
11746
11747<p>
11748You can avoid some incompatibilities by compiling Lua with
11749appropriate options (see file <code>luaconf.h</code>).
11750However,
11751all these compatibility options will be removed in the future.
11752More often than not,
11753compatibility issues arise when these compatibility options
11754are removed.
11755So, whenever you have the chance,
11756you should try to test your code with a version of Lua compiled
11757with all compatibility options turned off.
11758That will ease transitions to newer versions of Lua.
11759
11760
11761<p>
11762Lua versions can always change the C API in ways that
11763do not imply source-code changes in a program,
11764such as the numeric values for constants
11765or the implementation of functions as macros.
11766Therefore,
11767you should never assume that binaries are compatible between
11768different Lua versions.
11769Always recompile clients of the Lua API when
11770using a new version.
11771
11772
11773<p>
11774Similarly, Lua versions can always change the internal representation
11775of precompiled chunks;
11776precompiled chunks are not compatible between different Lua versions.
11777
11778
11779<p>
11780The standard paths in the official distribution may
11781change between versions.
11782
11783
11784
11785
11786
11787<h2>8.1 &ndash; <a name="8.1">Incompatibilities in the Language</a></h2>
11788<ul>
11789
11790<li>
11791The coercion of strings to numbers in
11792arithmetic and bitwise operations
11793has been removed from the core language.
11794The string library does a similar job
11795for arithmetic (but not for bitwise) operations
11796using the string metamethods.
11797However, unlike in previous versions,
11798the new implementation preserves the implicit type of the numeral
11799in the string.
11800For instance, the result of <code>"1" + "2"</code> now is an integer,
11801not a float.
11802</li>
11803
11804<li>
11805Literal decimal integer constants that overflow are read as floats,
11806instead of wrapping around.
11807You can use hexadecimal notation for such constants if you
11808want the old behavior
11809(reading them as integers with wrap around).
11810</li>
11811
11812<li>
11813The use of the <code>__lt</code> metamethod to emulate <code>__le</code>
11814has been removed.
11815When needed, this metamethod must be explicitly defined.
11816</li>
11817
11818<li>
11819The semantics of the numerical <b>for</b> loop
11820over integers changed in some details.
11821In particular, the control variable never wraps around.
11822</li>
11823
11824<li>
11825A label for a <b>goto</b> cannot be declared where a label with the same
11826name is visible, even if this other label is declared in an enclosing
11827block.
11828</li>
11829
11830<li>
11831When finalizing an object,
11832Lua does not ignore <code>__gc</code> metamethods that are not functions.
11833Any value will be called, if present.
11834(Non-callable values will generate a warning,
11835like any other error when calling a finalizer.)
11836</li>
11837
11838</ul>
11839
11840
11841
11842
11843<h2>8.2 &ndash; <a name="8.2">Incompatibilities in the Libraries</a></h2>
11844<ul>
11845
11846<li>
11847The function <a href="#pdf-print"><code>print</code></a> does not call <a href="#pdf-tostring"><code>tostring</code></a>
11848to format its arguments;
11849instead, it has this functionality hardwired.
11850You should use <code>__tostring</code> to modify how values are printed.
11851</li>
11852
11853<li>
11854The pseudo-random number generator used by the function <a href="#pdf-math.random"><code>math.random</code></a>
11855now starts with a somewhat random seed.
11856Moreover, it uses a different algorithm.
11857</li>
11858
11859<li>
11860By default, the decoding functions in the <a href="#pdf-utf8"><code>utf8</code></a> library
11861do not accept surrogates as valid code points.
11862An extra parameter in these functions makes them more permissive.
11863</li>
11864
11865<li>
11866The options "<code>setpause</code>" and "<code>setstepmul</code>"
11867of the function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> are deprecated.
11868You should use the new option "<code>incremental</code>" to set them.
11869</li>
11870
11871<li>
11872The function <a href="#pdf-io.lines"><code>io.lines</code></a> now returns four values,
11873instead of just one.
11874That can be a problem when it is used as the sole
11875argument to another function that has optional parameters,
11876such as in <code>load(io.lines(filename, "L"))</code>.
11877To fix that issue,
11878you can wrap the call into parentheses,
11879to adjust its number of results to one.
11880</li>
11881
11882</ul>
11883
11884
11885
11886
11887<h2>8.3 &ndash; <a name="8.3">Incompatibilities in the API</a></h2>
11888
11889
11890<ul>
11891
11892<li>
11893Full userdata now has an arbitrary number of associated user values.
11894Therefore, the functions <code>lua_newuserdata</code>,
11895<code>lua_setuservalue</code>, and <code>lua_getuservalue</code> were
11896replaced by <a href="#lua_newuserdatauv"><code>lua_newuserdatauv</code></a>,
11897<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a>, and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>,
11898which have an extra argument.
11899
11900
11901<p>
11902For compatibility, the old names still work as macros assuming
11903one single user value.
11904Note, however, that userdata with zero user values
11905are more efficient memory-wise.
11906</li>
11907
11908<li>
11909The function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter.
11910This out parameter returns the number of values on
11911the top of the stack that were yielded or returned by the coroutine.
11912(In previous versions,
11913those values were the entire stack.)
11914</li>
11915
11916<li>
11917The function <a href="#lua_version"><code>lua_version</code></a> returns the version number,
11918instead of an address of the version number.
11919The Lua core should work correctly with libraries using their
11920own static copies of the same core,
11921so there is no need to check whether they are using the same
11922address space.
11923</li>
11924
11925<li>
11926The constant <code>LUA_ERRGCMM</code> was removed.
11927Errors in finalizers are never propagated;
11928instead, they generate a warning.
11929</li>
11930
11931<li>
11932The options <code>LUA_GCSETPAUSE</code> and <code>LUA_GCSETSTEPMUL</code>
11933of the function <a href="#lua_gc"><code>lua_gc</code></a> are deprecated.
11934You should use the new option <code>LUA_GCINC</code> to set them.
11935</li>
11936
11937</ul>
11938
11939
11940
11941
11942<h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
11943
11944<p>
11945Here is the complete syntax of Lua in extended BNF.
11946As usual in extended BNF,
11947{A} means 0 or more As,
11948and [A] means an optional A.
11949(For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
11950for a description of the terminals
11951Name, Numeral,
11952and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
11953
11954
11955
11956
11957<pre>
11958
11959	chunk ::= block
11960
11961	block ::= {stat} [retstat]
11962
11963	stat ::=  &lsquo;<b>;</b>&rsquo; |
11964		 varlist &lsquo;<b>=</b>&rsquo; explist |
11965		 functioncall |
11966		 label |
11967		 <b>break</b> |
11968		 <b>goto</b> Name |
11969		 <b>do</b> block <b>end</b> |
11970		 <b>while</b> exp <b>do</b> block <b>end</b> |
11971		 <b>repeat</b> block <b>until</b> exp |
11972		 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
11973		 <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b> |
11974		 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
11975		 <b>function</b> funcname funcbody |
11976		 <b>local</b> <b>function</b> Name funcbody |
11977		 <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
11978
11979	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
11980
11981	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
11982
11983	retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
11984
11985	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
11986
11987	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
11988
11989	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
11990
11991	var ::=  Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
11992
11993	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
11994
11995	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
11996
11997	exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
11998		 prefixexp | tableconstructor | exp binop exp | unop exp
11999
12000	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
12001
12002	functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
12003
12004	args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
12005
12006	functiondef ::= <b>function</b> funcbody
12007
12008	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
12009
12010	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
12011
12012	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
12013
12014	fieldlist ::= field {fieldsep field} [fieldsep]
12015
12016	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
12017
12018	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
12019
12020	binop ::=  &lsquo;<b>+</b>&rsquo; | &lsquo;<b>-</b>&rsquo; | &lsquo;<b>*</b>&rsquo; | &lsquo;<b>/</b>&rsquo; | &lsquo;<b>//</b>&rsquo; | &lsquo;<b>^</b>&rsquo; | &lsquo;<b>%</b>&rsquo; |
12021		 &lsquo;<b>&amp;</b>&rsquo; | &lsquo;<b>~</b>&rsquo; | &lsquo;<b>|</b>&rsquo; | &lsquo;<b>&gt;&gt;</b>&rsquo; | &lsquo;<b>&lt;&lt;</b>&rsquo; | &lsquo;<b>..</b>&rsquo; |
12022		 &lsquo;<b>&lt;</b>&rsquo; | &lsquo;<b>&lt;=</b>&rsquo; | &lsquo;<b>&gt;</b>&rsquo; | &lsquo;<b>&gt;=</b>&rsquo; | &lsquo;<b>==</b>&rsquo; | &lsquo;<b>~=</b>&rsquo; |
12023		 <b>and</b> | <b>or</b>
12024
12025	unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
12026
12027</pre>
12028
12029<p>
12030
12031
12032
12033
12034
12035
12036
12037<P CLASS="footer">
12038Last update:
12039Tue May  2 20:09:38 UTC 2023
12040</P>
12041<!--
12042Last change: revised for Lua 5.4.6
12043-->
12044
12045</body></html>
12046
12047