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;2021 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.
965Except for that, they can do anything,
966such as raise errors, create new objects,
967or even run the garbage collector.
968However, because they can run in unpredictable times,
969it is good practice to restrict each finalizer
970to the minimum necessary to properly release
971its associated resource.
972
973
974<p>
975Any error while running a finalizer generates a warning;
976the error is not propagated.
977
978
979
980
981
982<h3>2.5.4 &ndash; <a name="2.5.4">Weak Tables</a></h3>
983
984<p>
985A <em>weak table</em> is a table whose elements are
986<em>weak references</em>.
987A weak reference is ignored by the garbage collector.
988In other words,
989if the only references to an object are weak references,
990then the garbage collector will collect that object.
991
992
993<p>
994A weak table can have weak keys, weak values, or both.
995A table with weak values allows the collection of its values,
996but prevents the collection of its keys.
997A table with both weak keys and weak values allows the collection of
998both keys and values.
999In any case, if either the key or the value is collected,
1000the whole pair is removed from the table.
1001The weakness of a table is controlled by the
1002<code>__mode</code> field of its metatable.
1003This metavalue, if present, must be one of the following strings:
1004"<code>k</code>", for a table with weak keys;
1005"<code>v</code>", for a table with weak values;
1006or "<code>kv</code>", for a table with both weak keys and values.
1007
1008
1009<p>
1010A table with weak keys and strong values
1011is also called an <em>ephemeron table</em>.
1012In an ephemeron table,
1013a value is considered reachable only if its key is reachable.
1014In particular,
1015if the only reference to a key comes through its value,
1016the pair is removed.
1017
1018
1019<p>
1020Any change in the weakness of a table may take effect only
1021at the next collect cycle.
1022In particular, if you change the weakness to a stronger mode,
1023Lua may still collect some items from that table
1024before the change takes effect.
1025
1026
1027<p>
1028Only objects that have an explicit construction
1029are removed from weak tables.
1030Values, such as numbers and light C&nbsp;functions,
1031are not subject to garbage collection,
1032and therefore are not removed from weak tables
1033(unless their associated values are collected).
1034Although strings are subject to garbage collection,
1035they do not have an explicit construction and
1036their equality is by value;
1037they behave more like values than like objects.
1038Therefore, they are not removed from weak tables.
1039
1040
1041<p>
1042Resurrected objects
1043(that is, objects being finalized
1044and objects accessible only through objects being finalized)
1045have a special behavior in weak tables.
1046They are removed from weak values before running their finalizers,
1047but are removed from weak keys only in the next collection
1048after running their finalizers, when such objects are actually freed.
1049This behavior allows the finalizer to access properties
1050associated with the object through weak tables.
1051
1052
1053<p>
1054If a weak table is among the resurrected objects in a collection cycle,
1055it may not be properly cleared until the next cycle.
1056
1057
1058
1059
1060
1061
1062
1063<h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
1064
1065<p>
1066Lua supports coroutines,
1067also called <em>collaborative multithreading</em>.
1068A coroutine in Lua represents an independent thread of execution.
1069Unlike threads in multithread systems, however,
1070a coroutine only suspends its execution by explicitly calling
1071a yield function.
1072
1073
1074<p>
1075You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1076Its sole argument is a function
1077that is the main function of the coroutine.
1078The <code>create</code> function only creates a new coroutine and
1079returns a handle to it (an object of type <em>thread</em>);
1080it does not start the coroutine.
1081
1082
1083<p>
1084You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1085When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1086passing as its first argument
1087a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1088the coroutine starts its execution by
1089calling its main function.
1090Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
1091as arguments to that function.
1092After the coroutine starts running,
1093it runs until it terminates or <em>yields</em>.
1094
1095
1096<p>
1097A coroutine can terminate its execution in two ways:
1098normally, when its main function returns
1099(explicitly or implicitly, after the last instruction);
1100and abnormally, if there is an unprotected error.
1101In case of normal termination,
1102<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1103plus any values returned by the coroutine main function.
1104In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1105plus the error object.
1106In this case, the coroutine does not unwind its stack,
1107so that it is possible to inspect it after the error
1108with the debug API.
1109
1110
1111<p>
1112A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1113When a coroutine yields,
1114the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1115even if the yield happens inside nested function calls
1116(that is, not in the main function,
1117but in a function directly or indirectly called by the main function).
1118In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1119plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1120The next time you resume the same coroutine,
1121it continues its execution from the point where it yielded,
1122with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1123arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1124
1125
1126<p>
1127Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1128the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1129but instead of returning the coroutine itself,
1130it returns a function that, when called, resumes the coroutine.
1131Any arguments passed to this function
1132go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1133<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>,
1134except the first one (the boolean error code).
1135Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1136the function created by <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>
1137propagates any error to the caller.
1138In this case,
1139the function also closes the coroutine (see <a href="#pdf-coroutine.close"><code>coroutine.close</code></a>).
1140
1141
1142<p>
1143As an example of how coroutines work,
1144consider the following code:
1145
1146<pre>
1147     function foo (a)
1148       print("foo", a)
1149       return coroutine.yield(2*a)
1150     end
1151
1152     co = coroutine.create(function (a,b)
1153           print("co-body", a, b)
1154           local r = foo(a+1)
1155           print("co-body", r)
1156           local r, s = coroutine.yield(a+b, a-b)
1157           print("co-body", r, s)
1158           return b, "end"
1159     end)
1160
1161     print("main", coroutine.resume(co, 1, 10))
1162     print("main", coroutine.resume(co, "r"))
1163     print("main", coroutine.resume(co, "x", "y"))
1164     print("main", coroutine.resume(co, "x", "y"))
1165</pre><p>
1166When you run it, it produces the following output:
1167
1168<pre>
1169     co-body 1       10
1170     foo     2
1171     main    true    4
1172     co-body r
1173     main    true    11      -9
1174     co-body x       y
1175     main    true    10      end
1176     main    false   cannot resume dead coroutine
1177</pre>
1178
1179<p>
1180You can also create and manipulate coroutines through the C API:
1181see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1182and <a href="#lua_yield"><code>lua_yield</code></a>.
1183
1184
1185
1186
1187
1188<h1>3 &ndash; <a name="3">The Language</a></h1>
1189
1190
1191
1192<p>
1193This section describes the lexis, the syntax, and the semantics of Lua.
1194In other words,
1195this section describes
1196which tokens are valid,
1197how they can be combined,
1198and what their combinations mean.
1199
1200
1201<p>
1202Language constructs will be explained using the usual extended BNF notation,
1203in which
1204{<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1205[<em>a</em>]&nbsp;means an optional <em>a</em>.
1206Non-terminals are shown like non-terminal,
1207keywords are shown like <b>kword</b>,
1208and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1209The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1210at the end of this manual.
1211
1212
1213
1214
1215
1216<h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1217
1218<p>
1219Lua is a free-form language.
1220It ignores spaces and comments between lexical elements (tokens),
1221except as delimiters between two tokens.
1222In source code,
1223Lua recognizes as spaces the standard ASCII whitespace
1224characters space, form feed, newline,
1225carriage return, horizontal tab, and vertical tab.
1226
1227
1228<p>
1229<em>Names</em>
1230(also called <em>identifiers</em>)
1231in Lua can be any string of Latin letters,
1232Arabic-Indic digits, and underscores,
1233not beginning with a digit and
1234not being a reserved word.
1235Identifiers are used to name variables, table fields, and labels.
1236
1237
1238<p>
1239The following <em>keywords</em> are reserved
1240and cannot be used as names:
1241
1242
1243<pre>
1244     and       break     do        else      elseif    end
1245     false     for       function  goto      if        in
1246     local     nil       not       or        repeat    return
1247     then      true      until     while
1248</pre>
1249
1250<p>
1251Lua is a case-sensitive language:
1252<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1253are two different, valid names.
1254As a convention,
1255programs should avoid creating
1256names that start with an underscore followed by
1257one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1258
1259
1260<p>
1261The following strings denote other tokens:
1262
1263<pre>
1264     +     -     *     /     %     ^     #
1265     &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
1266     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
1267     (     )     {     }     [     ]     ::
1268     ;     :     ,     .     ..    ...
1269</pre>
1270
1271<p>
1272A <em>short literal string</em>
1273can be delimited by matching single or double quotes,
1274and can contain the following C-like escape sequences:
1275'<code>\a</code>' (bell),
1276'<code>\b</code>' (backspace),
1277'<code>\f</code>' (form feed),
1278'<code>\n</code>' (newline),
1279'<code>\r</code>' (carriage return),
1280'<code>\t</code>' (horizontal tab),
1281'<code>\v</code>' (vertical tab),
1282'<code>\\</code>' (backslash),
1283'<code>\"</code>' (quotation mark [double quote]),
1284and '<code>\'</code>' (apostrophe [single quote]).
1285A backslash followed by a line break
1286results in a newline in the string.
1287The escape sequence '<code>\z</code>' skips the following span
1288of whitespace characters,
1289including line breaks;
1290it is particularly useful to break and indent a long literal string
1291into multiple lines without adding the newlines and spaces
1292into the string contents.
1293A short literal string cannot contain unescaped line breaks
1294nor escapes not forming a valid escape sequence.
1295
1296
1297<p>
1298We can specify any byte in a short literal string,
1299including embedded zeros,
1300by its numeric value.
1301This can be done
1302with the escape sequence <code>\x<em>XX</em></code>,
1303where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1304or with the escape sequence <code>\<em>ddd</em></code>,
1305where <em>ddd</em> is a sequence of up to three decimal digits.
1306(Note that if a decimal escape sequence is to be followed by a digit,
1307it must be expressed using exactly three digits.)
1308
1309
1310<p>
1311The UTF-8 encoding of a Unicode character
1312can be inserted in a literal string with
1313the escape sequence <code>\u{<em>XXX</em>}</code>
1314(with mandatory enclosing braces),
1315where <em>XXX</em> is a sequence of one or more hexadecimal digits
1316representing the character code point.
1317This code point can be any value less than <em>2<sup>31</sup></em>.
1318(Lua uses the original UTF-8 specification here,
1319which is not restricted to valid Unicode code points.)
1320
1321
1322<p>
1323Literal strings can also be defined using a long format
1324enclosed by <em>long brackets</em>.
1325We define an <em>opening long bracket of level <em>n</em></em> as an opening
1326square bracket followed by <em>n</em> equal signs followed by another
1327opening square bracket.
1328So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1329an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1330and so on.
1331A <em>closing long bracket</em> is defined similarly;
1332for instance,
1333a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
1334A <em>long literal</em> starts with an opening long bracket of any level and
1335ends at the first closing long bracket of the same level.
1336It can contain any text except a closing bracket of the same level.
1337Literals in this bracketed form can run for several lines,
1338do not interpret any escape sequences,
1339and ignore long brackets of any other level.
1340Any kind of end-of-line sequence
1341(carriage return, newline, carriage return followed by newline,
1342or newline followed by carriage return)
1343is converted to a simple newline.
1344When the opening long bracket is immediately followed by a newline,
1345the newline is not included in the string.
1346
1347
1348<p>
1349As an example, in a system using ASCII
1350(in which '<code>a</code>' is coded as&nbsp;97,
1351newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1352the five literal strings below denote the same string:
1353
1354<pre>
1355     a = 'alo\n123"'
1356     a = "alo\n123\""
1357     a = '\97lo\10\04923"'
1358     a = [[alo
1359     123"]]
1360     a = [==[
1361     alo
1362     123"]==]
1363</pre>
1364
1365<p>
1366Any byte in a literal string not
1367explicitly affected by the previous rules represents itself.
1368However, Lua opens files for parsing in text mode,
1369and the system's file functions may have problems with
1370some control characters.
1371So, it is safer to represent
1372binary data as a quoted literal with
1373explicit escape sequences for the non-text characters.
1374
1375
1376<p>
1377A <em>numeric constant</em> (or <em>numeral</em>)
1378can be written with an optional fractional part
1379and an optional decimal exponent,
1380marked by a letter '<code>e</code>' or '<code>E</code>'.
1381Lua also accepts hexadecimal constants,
1382which start with <code>0x</code> or <code>0X</code>.
1383Hexadecimal constants also accept an optional fractional part
1384plus an optional binary exponent,
1385marked by a letter '<code>p</code>' or '<code>P</code>'.
1386
1387
1388<p>
1389A numeric constant with a radix point or an exponent
1390denotes a float;
1391otherwise,
1392if its value fits in an integer or it is a hexadecimal constant,
1393it denotes an integer;
1394otherwise (that is, a decimal integer numeral that overflows),
1395it denotes a float.
1396Hexadecimal numerals with neither a radix point nor an exponent
1397always denote an integer value;
1398if the value overflows, it <em>wraps around</em>
1399to fit into a valid integer.
1400
1401
1402<p>
1403Examples of valid integer constants are
1404
1405<pre>
1406     3   345   0xff   0xBEBADA
1407</pre><p>
1408Examples of valid float constants are
1409
1410<pre>
1411     3.0     3.1416     314.16e-2     0.31416E1     34e1
1412     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
1413</pre>
1414
1415<p>
1416A <em>comment</em> starts with a double hyphen (<code>--</code>)
1417anywhere outside a string.
1418If the text immediately after <code>--</code> is not an opening long bracket,
1419the comment is a <em>short comment</em>,
1420which runs until the end of the line.
1421Otherwise, it is a <em>long comment</em>,
1422which runs until the corresponding closing long bracket.
1423
1424
1425
1426
1427
1428<h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1429
1430<p>
1431Variables are places that store values.
1432There are three kinds of variables in Lua:
1433global variables, local variables, and table fields.
1434
1435
1436<p>
1437A single name can denote a global variable or a local variable
1438(or a function's formal parameter,
1439which is a particular kind of local variable):
1440
1441<pre>
1442	var ::= Name
1443</pre><p>
1444Name denotes identifiers (see <a href="#3.1">&sect;3.1</a>).
1445
1446
1447<p>
1448Any variable name is assumed to be global unless explicitly declared
1449as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1450Local variables are <em>lexically scoped</em>:
1451local variables can be freely accessed by functions
1452defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1453
1454
1455<p>
1456Before the first assignment to a variable, its value is <b>nil</b>.
1457
1458
1459<p>
1460Square brackets are used to index a table:
1461
1462<pre>
1463	var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1464</pre><p>
1465The meaning of accesses to table fields can be changed via metatables
1466(see <a href="#2.4">&sect;2.4</a>).
1467
1468
1469<p>
1470The syntax <code>var.Name</code> is just syntactic sugar for
1471<code>var["Name"]</code>:
1472
1473<pre>
1474	var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1475</pre>
1476
1477<p>
1478An access to a global variable <code>x</code>
1479is equivalent to <code>_ENV.x</code>.
1480Due to the way that chunks are compiled,
1481the variable <code>_ENV</code> itself is never global (see <a href="#2.2">&sect;2.2</a>).
1482
1483
1484
1485
1486
1487<h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1488
1489
1490
1491<p>
1492Lua supports an almost conventional set of statements,
1493similar to those in other conventional languages.
1494This set includes
1495blocks, assignments, control structures, function calls,
1496and variable declarations.
1497
1498
1499
1500
1501
1502<h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1503
1504<p>
1505A block is a list of statements,
1506which are executed sequentially:
1507
1508<pre>
1509	block ::= {stat}
1510</pre><p>
1511Lua has <em>empty statements</em>
1512that allow you to separate statements with semicolons,
1513start a block with a semicolon
1514or write two semicolons in sequence:
1515
1516<pre>
1517	stat ::= &lsquo;<b>;</b>&rsquo;
1518</pre>
1519
1520<p>
1521Both function calls and assignments
1522can start with an open parenthesis.
1523This possibility leads to an ambiguity in Lua's grammar.
1524Consider the following fragment:
1525
1526<pre>
1527     a = b + c
1528     (print or io.write)('done')
1529</pre><p>
1530The grammar could see this fragment in two ways:
1531
1532<pre>
1533     a = b + c(print or io.write)('done')
1534
1535     a = b + c; (print or io.write)('done')
1536</pre><p>
1537The current parser always sees such constructions
1538in the first way,
1539interpreting the open parenthesis
1540as the start of the arguments to a call.
1541To avoid this ambiguity,
1542it is a good practice to always precede with a semicolon
1543statements that start with a parenthesis:
1544
1545<pre>
1546     ;(print or io.write)('done')
1547</pre>
1548
1549<p>
1550A block can be explicitly delimited to produce a single statement:
1551
1552<pre>
1553	stat ::= <b>do</b> block <b>end</b>
1554</pre><p>
1555Explicit blocks are useful
1556to control the scope of variable declarations.
1557Explicit blocks are also sometimes used to
1558add a <b>return</b> statement in the middle
1559of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1560
1561
1562
1563
1564
1565<h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1566
1567<p>
1568The unit of compilation of Lua is called a <em>chunk</em>.
1569Syntactically,
1570a chunk is simply a block:
1571
1572<pre>
1573	chunk ::= block
1574</pre>
1575
1576<p>
1577Lua handles a chunk as the body of an anonymous function
1578with a variable number of arguments
1579(see <a href="#3.4.11">&sect;3.4.11</a>).
1580As such, chunks can define local variables,
1581receive arguments, and return values.
1582Moreover, such anonymous function is compiled as in the
1583scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1584The resulting function always has <code>_ENV</code> as its only external variable,
1585even if it does not use that variable.
1586
1587
1588<p>
1589A chunk can be stored in a file or in a string inside the host program.
1590To execute a chunk,
1591Lua first <em>loads</em> it,
1592precompiling the chunk's code into instructions for a virtual machine,
1593and then Lua executes the compiled code
1594with an interpreter for the virtual machine.
1595
1596
1597<p>
1598Chunks can also be precompiled into binary form;
1599see the program <code>luac</code> and the function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1600Programs in source and compiled forms are interchangeable;
1601Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1602
1603
1604
1605
1606
1607<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1608
1609<p>
1610Lua allows multiple assignments.
1611Therefore, the syntax for assignment
1612defines a list of variables on the left side
1613and a list of expressions on the right side.
1614The elements in both lists are separated by commas:
1615
1616<pre>
1617	stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1618	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1619	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1620</pre><p>
1621Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1622
1623
1624<p>
1625Before the assignment,
1626the list of values is <em>adjusted</em> to the length of
1627the list of variables.
1628If there are more values than needed,
1629the excess values are thrown away.
1630If there are fewer values than needed,
1631the list is extended with <b>nil</b>'s.
1632If the list of expressions ends with a function call,
1633then all values returned by that call enter the list of values,
1634before the adjustment
1635(except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1636
1637
1638<p>
1639The assignment statement first evaluates all its expressions
1640and only then the assignments are performed.
1641Thus the code
1642
1643<pre>
1644     i = 3
1645     i, a[i] = i+1, 20
1646</pre><p>
1647sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1648because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1649before it is assigned&nbsp;4.
1650Similarly, the line
1651
1652<pre>
1653     x, y = y, x
1654</pre><p>
1655exchanges the values of <code>x</code> and <code>y</code>,
1656and
1657
1658<pre>
1659     x, y, z = y, z, x
1660</pre><p>
1661cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1662
1663
1664<p>
1665An assignment to a global name <code>x = val</code>
1666is equivalent to the assignment
1667<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1668
1669
1670<p>
1671The meaning of assignments to table fields and
1672global variables (which are actually table fields, too)
1673can be changed via metatables (see <a href="#2.4">&sect;2.4</a>).
1674
1675
1676
1677
1678
1679<h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1680The control structures
1681<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1682familiar syntax:
1683
1684
1685
1686
1687<pre>
1688	stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1689	stat ::= <b>repeat</b> block <b>until</b> exp
1690	stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1691</pre><p>
1692Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1693
1694
1695<p>
1696The condition expression of a
1697control structure can return any value.
1698Both <b>false</b> and <b>nil</b> test false.
1699All values different from <b>nil</b> and <b>false</b> test true.
1700In particular, the number 0 and the empty string also test true.
1701
1702
1703<p>
1704In the <b>repeat</b>&ndash;<b>until</b> loop,
1705the inner block does not end at the <b>until</b> keyword,
1706but only after the condition.
1707So, the condition can refer to local variables
1708declared inside the loop block.
1709
1710
1711<p>
1712The <b>goto</b> statement transfers the program control to a label.
1713For syntactical reasons,
1714labels in Lua are considered statements too:
1715
1716
1717
1718<pre>
1719	stat ::= <b>goto</b> Name
1720	stat ::= label
1721	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1722</pre>
1723
1724<p>
1725A label is visible in the entire block where it is defined,
1726except inside nested functions.
1727A goto may jump to any visible label as long as it does not
1728enter into the scope of a local variable.
1729A label should not be declared
1730where a label with the same name is visible,
1731even if this other label has been declared in an enclosing block.
1732
1733
1734<p>
1735Labels and empty statements are called <em>void statements</em>,
1736as they perform no actions.
1737
1738
1739<p>
1740The <b>break</b> statement terminates the execution of a
1741<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1742skipping to the next statement after the loop:
1743
1744
1745<pre>
1746	stat ::= <b>break</b>
1747</pre><p>
1748A <b>break</b> ends the innermost enclosing loop.
1749
1750
1751<p>
1752The <b>return</b> statement is used to return values
1753from a function or a chunk
1754(which is handled as an anonymous function).
1755
1756Functions can return more than one value,
1757so the syntax for the <b>return</b> statement is
1758
1759<pre>
1760	stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1761</pre>
1762
1763<p>
1764The <b>return</b> statement can only be written
1765as the last statement of a block.
1766If it is necessary to <b>return</b> in the middle of a block,
1767then an explicit inner block can be used,
1768as in the idiom <code>do return end</code>,
1769because now <b>return</b> is the last statement in its (inner) block.
1770
1771
1772
1773
1774
1775<h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1776
1777<p>
1778
1779The <b>for</b> statement has two forms:
1780one numerical and one generic.
1781
1782
1783
1784<h4>The numerical <b>for</b> loop</h4>
1785
1786<p>
1787The numerical <b>for</b> loop repeats a block of code while a
1788control variable goes through an arithmetic progression.
1789It has the following syntax:
1790
1791<pre>
1792	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>
1793</pre><p>
1794The given identifier (Name) defines the control variable,
1795which is a new variable local to the loop body (<em>block</em>).
1796
1797
1798<p>
1799The loop starts by evaluating once the three control expressions.
1800Their values are called respectively
1801the <em>initial value</em>, the <em>limit</em>, and the <em>step</em>.
1802If the step is absent, it defaults to&nbsp;1.
1803
1804
1805<p>
1806If both the initial value and the step are integers,
1807the loop is done with integers;
1808note that the limit may not be an integer.
1809Otherwise, the three values are converted to
1810floats and the loop is done with floats.
1811Beware of floating-point accuracy in this case.
1812
1813
1814<p>
1815After that initialization,
1816the loop body is repeated with the value of the control variable
1817going through an arithmetic progression,
1818starting at the initial value,
1819with a common difference given by the step.
1820A negative step makes a decreasing sequence;
1821a step equal to zero raises an error.
1822The loop continues while the value is less than
1823or equal to the limit
1824(greater than or equal to for a negative step).
1825If the initial value is already greater than the limit
1826(or less than, if the step is negative),
1827the body is not executed.
1828
1829
1830<p>
1831For integer loops,
1832the control variable never wraps around;
1833instead, the loop ends in case of an overflow.
1834
1835
1836<p>
1837You should not change the value of the control variable
1838during the loop.
1839If you need its value after the loop,
1840assign it to another variable before exiting the loop.
1841
1842
1843
1844
1845
1846<h4>The generic <b>for</b> loop</h4>
1847
1848<p>
1849The generic <b>for</b> statement works over functions,
1850called <em>iterators</em>.
1851On each iteration, the iterator function is called to produce a new value,
1852stopping when this new value is <b>nil</b>.
1853The generic <b>for</b> loop has the following syntax:
1854
1855<pre>
1856	stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1857	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1858</pre><p>
1859A <b>for</b> statement like
1860
1861<pre>
1862     for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>body</em> end
1863</pre><p>
1864works as follows.
1865
1866
1867<p>
1868The names <em>var_i</em> declare loop variables local to the loop body.
1869The first of these variables is the <em>control variable</em>.
1870
1871
1872<p>
1873The loop starts by evaluating <em>explist</em>
1874to produce four values:
1875an <em>iterator function</em>,
1876a <em>state</em>,
1877an initial value for the control variable,
1878and a <em>closing value</em>.
1879
1880
1881<p>
1882Then, at each iteration,
1883Lua calls the iterator function with two arguments:
1884the state and the control variable.
1885The results from this call are then assigned to the loop variables,
1886following the rules of multiple assignments (see <a href="#3.3.3">&sect;3.3.3</a>).
1887If the control variable becomes <b>nil</b>,
1888the loop terminates.
1889Otherwise, the body is executed and the loop goes
1890to the next iteration.
1891
1892
1893<p>
1894The closing value behaves like a
1895to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>),
1896which can be used to release resources when the loop ends.
1897Otherwise, it does not interfere with the loop.
1898
1899
1900<p>
1901You should not change the value of the control variable
1902during the loop.
1903
1904
1905
1906
1907
1908
1909
1910<h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1911To allow possible side-effects,
1912function calls can be executed as statements:
1913
1914<pre>
1915	stat ::= functioncall
1916</pre><p>
1917In this case, all returned values are thrown away.
1918Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1919
1920
1921
1922
1923
1924<h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1925Local variables can be declared anywhere inside a block.
1926The declaration can include an initialization:
1927
1928<pre>
1929	stat ::= <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
1930	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
1931</pre><p>
1932If present, an initial assignment has the same semantics
1933of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1934Otherwise, all variables are initialized with <b>nil</b>.
1935
1936
1937<p>
1938Each variable name may be postfixed by an attribute
1939(a name between angle brackets):
1940
1941<pre>
1942	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
1943</pre><p>
1944There are two possible attributes:
1945<code>const</code>, which declares a constant variable,
1946that is, a variable that cannot be assigned to
1947after its initialization;
1948and <code>close</code>, which declares a to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>).
1949A list of variables can contain at most one to-be-closed variable.
1950
1951
1952<p>
1953A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1954and so local variables can be declared in a chunk outside any explicit block.
1955
1956
1957<p>
1958The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1959
1960
1961
1962
1963
1964<h3>3.3.8 &ndash; <a name="3.3.8">To-be-closed Variables</a></h3>
1965
1966<p>
1967A to-be-closed variable behaves like a constant local variable,
1968except that its value is <em>closed</em> whenever the variable
1969goes out of scope, including normal block termination,
1970exiting its block by <b>break</b>/<b>goto</b>/<b>return</b>,
1971or exiting by an error.
1972
1973
1974<p>
1975Here, to <em>close</em> a value means
1976to call its <code>__close</code> metamethod.
1977When calling the metamethod,
1978the value itself is passed as the first argument
1979and the error object that caused the exit (if any)
1980is passed as a second argument;
1981if there was no error, the second argument is <b>nil</b>.
1982
1983
1984<p>
1985The value assigned to a to-be-closed variable
1986must have a <code>__close</code> metamethod
1987or be a false value.
1988(<b>nil</b> and <b>false</b> are ignored as to-be-closed values.)
1989
1990
1991<p>
1992If several to-be-closed variables go out of scope at the same event,
1993they are closed in the reverse order that they were declared.
1994
1995
1996<p>
1997If there is any error while running a closing method,
1998that error is handled like an error in the regular code
1999where the variable was defined.
2000After an error,
2001the other pending closing methods will still be called.
2002
2003
2004<p>
2005If a coroutine yields and is never resumed again,
2006some variables may never go out of scope,
2007and therefore they will never be closed.
2008(These variables are the ones created inside the coroutine
2009and in scope at the point where the coroutine yielded.)
2010Similarly, if a coroutine ends with an error,
2011it does not unwind its stack,
2012so it does not close any variable.
2013In both cases,
2014you can either use finalizers
2015or call <a href="#pdf-coroutine.close"><code>coroutine.close</code></a> to close the variables.
2016However, if the coroutine was created
2017through <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>,
2018then its corresponding function will close the coroutine
2019in case of errors.
2020
2021
2022
2023
2024
2025
2026
2027<h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
2028
2029
2030
2031<p>
2032The basic expressions in Lua are the following:
2033
2034<pre>
2035	exp ::= prefixexp
2036	exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
2037	exp ::= Numeral
2038	exp ::= LiteralString
2039	exp ::= functiondef
2040	exp ::= tableconstructor
2041	exp ::= &lsquo;<b>...</b>&rsquo;
2042	exp ::= exp binop exp
2043	exp ::= unop exp
2044	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
2045</pre>
2046
2047<p>
2048Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
2049variables are explained in <a href="#3.2">&sect;3.2</a>;
2050function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
2051function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
2052table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
2053Vararg expressions,
2054denoted by three dots ('<code>...</code>'), can only be used when
2055directly inside a vararg function;
2056they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
2057
2058
2059<p>
2060Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
2061bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
2062relational 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>),
2063and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
2064Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
2065the unary bitwise NOT (see <a href="#3.4.2">&sect;3.4.2</a>),
2066the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
2067and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
2068
2069
2070<p>
2071Both function calls and vararg expressions can result in multiple values.
2072If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
2073then its return list is adjusted to zero elements,
2074thus discarding all returned values.
2075If an expression is used as the last (or the only) element
2076of a list of expressions,
2077then no adjustment is made
2078(unless the expression is enclosed in parentheses).
2079In all other contexts,
2080Lua adjusts the result list to one element,
2081either discarding all values except the first one
2082or adding a single <b>nil</b> if there are no values.
2083
2084
2085<p>
2086Here are some examples:
2087
2088<pre>
2089     f()                -- adjusted to 0 results
2090     g(f(), x)          -- f() is adjusted to 1 result
2091     g(x, f())          -- g gets x plus all results from f()
2092     a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
2093     a,b = ...          -- a gets the first vararg argument, b gets
2094                        -- the second (both a and b can get nil if there
2095                        -- is no corresponding vararg argument)
2096
2097     a,b,c = x, f()     -- f() is adjusted to 2 results
2098     a,b,c = f()        -- f() is adjusted to 3 results
2099     return f()         -- returns all results from f()
2100     return ...         -- returns all received vararg arguments
2101     return x,y,f()     -- returns x, y, and all results from f()
2102     {f()}              -- creates a list with all results from f()
2103     {...}              -- creates a list with all vararg arguments
2104     {f(), nil}         -- f() is adjusted to 1 result
2105</pre>
2106
2107<p>
2108Any expression enclosed in parentheses always results in only one value.
2109Thus,
2110<code>(f(x,y,z))</code> is always a single value,
2111even if <code>f</code> returns several values.
2112(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
2113or <b>nil</b> if <code>f</code> does not return any values.)
2114
2115
2116
2117
2118
2119<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
2120Lua supports the following arithmetic operators:
2121
2122<ul>
2123<li><b><code>+</code>: </b>addition</li>
2124<li><b><code>-</code>: </b>subtraction</li>
2125<li><b><code>*</code>: </b>multiplication</li>
2126<li><b><code>/</code>: </b>float division</li>
2127<li><b><code>//</code>: </b>floor division</li>
2128<li><b><code>%</code>: </b>modulo</li>
2129<li><b><code>^</code>: </b>exponentiation</li>
2130<li><b><code>-</code>: </b>unary minus</li>
2131</ul>
2132
2133<p>
2134With the exception of exponentiation and float division,
2135the arithmetic operators work as follows:
2136If both operands are integers,
2137the operation is performed over integers and the result is an integer.
2138Otherwise, if both operands are numbers,
2139then they are converted to floats,
2140the operation is performed following the machine's rules
2141for floating-point arithmetic
2142(usually the IEEE 754 standard),
2143and the result is a float.
2144(The string library coerces strings to numbers in
2145arithmetic operations; see <a href="#3.4.3">&sect;3.4.3</a> for details.)
2146
2147
2148<p>
2149Exponentiation and float division (<code>/</code>)
2150always convert their operands to floats
2151and the result is always a float.
2152Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
2153so that it works for non-integer exponents too.
2154
2155
2156<p>
2157Floor division (<code>//</code>) is a division
2158that rounds the quotient towards minus infinity,
2159resulting in the floor of the division of its operands.
2160
2161
2162<p>
2163Modulo is defined as the remainder of a division
2164that rounds the quotient towards minus infinity (floor division).
2165
2166
2167<p>
2168In case of overflows in integer arithmetic,
2169all operations <em>wrap around</em>.
2170
2171
2172
2173<h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
2174Lua supports the following bitwise operators:
2175
2176<ul>
2177<li><b><code>&amp;</code>: </b>bitwise AND</li>
2178<li><b><code>&#124;</code>: </b>bitwise OR</li>
2179<li><b><code>~</code>: </b>bitwise exclusive OR</li>
2180<li><b><code>&gt;&gt;</code>: </b>right shift</li>
2181<li><b><code>&lt;&lt;</code>: </b>left shift</li>
2182<li><b><code>~</code>: </b>unary bitwise NOT</li>
2183</ul>
2184
2185<p>
2186All bitwise operations convert its operands to integers
2187(see <a href="#3.4.3">&sect;3.4.3</a>),
2188operate on all bits of those integers,
2189and result in an integer.
2190
2191
2192<p>
2193Both right and left shifts fill the vacant bits with zeros.
2194Negative displacements shift to the other direction;
2195displacements with absolute values equal to or higher than
2196the number of bits in an integer
2197result in zero (as all bits are shifted out).
2198
2199
2200
2201
2202
2203<h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
2204Lua provides some automatic conversions between some
2205types and representations at run time.
2206Bitwise operators always convert float operands to integers.
2207Exponentiation and float division
2208always convert integer operands to floats.
2209All other arithmetic operations applied to mixed numbers
2210(integers and floats) convert the integer operand to a float.
2211The C API also converts both integers to floats and
2212floats to integers, as needed.
2213Moreover, string concatenation accepts numbers as arguments,
2214besides strings.
2215
2216
2217<p>
2218In a conversion from integer to float,
2219if the integer value has an exact representation as a float,
2220that is the result.
2221Otherwise,
2222the conversion gets the nearest higher or
2223the nearest lower representable value.
2224This kind of conversion never fails.
2225
2226
2227<p>
2228The conversion from float to integer
2229checks whether the float has an exact representation as an integer
2230(that is, the float has an integral value and
2231it is in the range of integer representation).
2232If it does, that representation is the result.
2233Otherwise, the conversion fails.
2234
2235
2236<p>
2237Several places in Lua coerce strings to numbers when necessary.
2238In particular,
2239the string library sets metamethods that try to coerce
2240strings to numbers in all arithmetic operations.
2241If the conversion fails,
2242the library calls the metamethod of the other operand
2243(if present) or it raises an error.
2244Note that bitwise operators do not do this coercion.
2245
2246
2247<p>
2248Nonetheless, it is always a good practice not to rely on these
2249implicit coercions, as they are not always applied;
2250in particular, <code>"1"==1</code> is false and <code>"1"&lt;1</code> raises an error
2251(see <a href="#3.4.4">&sect;3.4.4</a>).
2252These coercions exist mainly for compatibility and may be removed
2253in future versions of the language.
2254
2255
2256<p>
2257A string is converted to an integer or a float
2258following its syntax and the rules of the Lua lexer.
2259The string may have also leading and trailing whitespaces and a sign.
2260All conversions from strings to numbers
2261accept both a dot and the current locale mark
2262as the radix character.
2263(The Lua lexer, however, accepts only a dot.)
2264If the string is not a valid numeral,
2265the conversion fails.
2266If necessary, the result of this first step is then converted
2267to a specific number subtype following the previous rules
2268for conversions between floats and integers.
2269
2270
2271<p>
2272The conversion from numbers to strings uses a
2273non-specified human-readable format.
2274To convert numbers to strings in any specific way,
2275use the function <a href="#pdf-string.format"><code>string.format</code></a>.
2276
2277
2278
2279
2280
2281<h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
2282Lua supports the following relational operators:
2283
2284<ul>
2285<li><b><code>==</code>: </b>equality</li>
2286<li><b><code>~=</code>: </b>inequality</li>
2287<li><b><code>&lt;</code>: </b>less than</li>
2288<li><b><code>&gt;</code>: </b>greater than</li>
2289<li><b><code>&lt;=</code>: </b>less or equal</li>
2290<li><b><code>&gt;=</code>: </b>greater or equal</li>
2291</ul><p>
2292These operators always result in <b>false</b> or <b>true</b>.
2293
2294
2295<p>
2296Equality (<code>==</code>) first compares the type of its operands.
2297If the types are different, then the result is <b>false</b>.
2298Otherwise, the values of the operands are compared.
2299Strings are equal if they have the same byte content.
2300Numbers are equal if they denote the same mathematical value.
2301
2302
2303<p>
2304Tables, userdata, and threads
2305are compared by reference:
2306two objects are considered equal only if they are the same object.
2307Every time you create a new object
2308(a table, a userdata, or a thread),
2309this new object is different from any previously existing object.
2310A function is always equal to itself.
2311Functions with any detectable difference
2312(different behavior, different definition) are always different.
2313Functions created at different times but with no detectable differences
2314may be classified as equal or not
2315(depending on internal caching details).
2316
2317
2318<p>
2319You can change the way that Lua compares tables and userdata
2320by using the <code>__eq</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2321
2322
2323<p>
2324Equality comparisons do not convert strings to numbers
2325or vice versa.
2326Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2327and <code>t[0]</code> and <code>t["0"]</code> denote different
2328entries in a table.
2329
2330
2331<p>
2332The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2333
2334
2335<p>
2336The order operators work as follows.
2337If both arguments are numbers,
2338then they are compared according to their mathematical values,
2339regardless of their subtypes.
2340Otherwise, if both arguments are strings,
2341then their values are compared according to the current locale.
2342Otherwise, Lua tries to call the <code>__lt</code> or the <code>__le</code>
2343metamethod (see <a href="#2.4">&sect;2.4</a>).
2344A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2345and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2346
2347
2348<p>
2349Following the IEEE 754 standard,
2350the special value NaN is considered neither less than,
2351nor equal to, nor greater than any value, including itself.
2352
2353
2354
2355
2356
2357<h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2358The logical operators in Lua are
2359<b>and</b>, <b>or</b>, and <b>not</b>.
2360Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2361all logical operators consider both <b>false</b> and <b>nil</b> as false
2362and anything else as true.
2363
2364
2365<p>
2366The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2367The conjunction operator <b>and</b> returns its first argument
2368if this value is <b>false</b> or <b>nil</b>;
2369otherwise, <b>and</b> returns its second argument.
2370The disjunction operator <b>or</b> returns its first argument
2371if this value is different from <b>nil</b> and <b>false</b>;
2372otherwise, <b>or</b> returns its second argument.
2373Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2374that is,
2375the second operand is evaluated only if necessary.
2376Here are some examples:
2377
2378<pre>
2379     10 or 20            --&gt; 10
2380     10 or error()       --&gt; 10
2381     nil or "a"          --&gt; "a"
2382     nil and 10          --&gt; nil
2383     false and error()   --&gt; false
2384     false and nil       --&gt; false
2385     false or nil        --&gt; nil
2386     10 and 20           --&gt; 20
2387</pre>
2388
2389
2390
2391
2392<h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2393The string concatenation operator in Lua is
2394denoted by two dots ('<code>..</code>').
2395If both operands are strings or numbers,
2396then the numbers are converted to strings
2397in a non-specified format (see <a href="#3.4.3">&sect;3.4.3</a>).
2398Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2399
2400
2401
2402
2403
2404<h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2405
2406<p>
2407The length operator is denoted by the unary prefix operator <code>#</code>.
2408
2409
2410<p>
2411The length of a string is its number of bytes.
2412(That is the usual meaning of string length when each
2413character is one byte.)
2414
2415
2416<p>
2417The length operator applied on a table
2418returns a border in that table.
2419A <em>border</em> in a table <code>t</code> is any natural number
2420that satisfies the following condition:
2421
2422<pre>
2423     (border == 0 or t[border] ~= nil) and t[border + 1] == nil
2424</pre><p>
2425In words,
2426a border is any (natural) index present in the table
2427that is followed by an absent index
2428(or zero, when index 1 is absent).
2429
2430
2431<p>
2432A table with exactly one border is called a <em>sequence</em>.
2433For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence,
2434as it has only one border (5).
2435The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5),
2436and therefore it is not a sequence.
2437(The <b>nil</b> at index 4 is called a <em>hole</em>.)
2438The table <code>{nil, 20, 30, nil, nil, 60, nil}</code>
2439has three borders (0, 3, and 6) and three holes
2440(at indices 1, 4, and 5),
2441so it is not a sequence, too.
2442The table <code>{}</code> is a sequence with border 0.
2443Note that non-natural keys do not interfere
2444with whether a table is a sequence.
2445
2446
2447<p>
2448When <code>t</code> is a sequence,
2449<code>#t</code> returns its only border,
2450which corresponds to the intuitive notion of the length of the sequence.
2451When <code>t</code> is not a sequence,
2452<code>#t</code> can return any of its borders.
2453(The exact one depends on details of
2454the internal representation of the table,
2455which in turn can depend on how the table was populated and
2456the memory addresses of its non-numeric keys.)
2457
2458
2459<p>
2460The computation of the length of a table
2461has a guaranteed worst time of <em>O(log n)</em>,
2462where <em>n</em> is the largest natural key in the table.
2463
2464
2465<p>
2466A program can modify the behavior of the length operator for
2467any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2468
2469
2470
2471
2472
2473<h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2474Operator precedence in Lua follows the table below,
2475from lower to higher priority:
2476
2477<pre>
2478     or
2479     and
2480     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2481     |
2482     ~
2483     &amp;
2484     &lt;&lt;    &gt;&gt;
2485     ..
2486     +     -
2487     *     /     //    %
2488     unary operators (not   #     -     ~)
2489     ^
2490</pre><p>
2491As usual,
2492you can use parentheses to change the precedences of an expression.
2493The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2494operators are right associative.
2495All other binary operators are left associative.
2496
2497
2498
2499
2500
2501<h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2502Table constructors are expressions that create tables.
2503Every time a constructor is evaluated, a new table is created.
2504A constructor can be used to create an empty table
2505or to create a table and initialize some of its fields.
2506The general syntax for constructors is
2507
2508<pre>
2509	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2510	fieldlist ::= field {fieldsep field} [fieldsep]
2511	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2512	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2513</pre>
2514
2515<p>
2516Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2517with key <code>exp1</code> and value <code>exp2</code>.
2518A field of the form <code>name = exp</code> is equivalent to
2519<code>["name"] = exp</code>.
2520Fields of the form <code>exp</code> are equivalent to
2521<code>[i] = exp</code>, where <code>i</code> are consecutive integers
2522starting with 1;
2523fields in the other formats do not affect this counting.
2524For example,
2525
2526<pre>
2527     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2528</pre><p>
2529is equivalent to
2530
2531<pre>
2532     do
2533       local t = {}
2534       t[f(1)] = g
2535       t[1] = "x"         -- 1st exp
2536       t[2] = "y"         -- 2nd exp
2537       t.x = 1            -- t["x"] = 1
2538       t[3] = f(x)        -- 3rd exp
2539       t[30] = 23
2540       t[4] = 45          -- 4th exp
2541       a = t
2542     end
2543</pre>
2544
2545<p>
2546The order of the assignments in a constructor is undefined.
2547(This order would be relevant only when there are repeated keys.)
2548
2549
2550<p>
2551If the last field in the list has the form <code>exp</code>
2552and the expression is a function call or a vararg expression,
2553then all values returned by this expression enter the list consecutively
2554(see <a href="#3.4.10">&sect;3.4.10</a>).
2555
2556
2557<p>
2558The field list can have an optional trailing separator,
2559as a convenience for machine-generated code.
2560
2561
2562
2563
2564
2565<h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2566A function call in Lua has the following syntax:
2567
2568<pre>
2569	functioncall ::= prefixexp args
2570</pre><p>
2571In a function call,
2572first prefixexp and args are evaluated.
2573If the value of prefixexp has type <em>function</em>,
2574then this function is called
2575with the given arguments.
2576Otherwise, if present,
2577the prefixexp <code>__call</code> metamethod is called:
2578its first argument is the value of prefixexp,
2579followed by the original call arguments
2580(see <a href="#2.4">&sect;2.4</a>).
2581
2582
2583<p>
2584The form
2585
2586<pre>
2587	functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2588</pre><p>
2589can be used to emulate methods.
2590A call <code>v:name(<em>args</em>)</code>
2591is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2592except that <code>v</code> is evaluated only once.
2593
2594
2595<p>
2596Arguments have the following syntax:
2597
2598<pre>
2599	args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2600	args ::= tableconstructor
2601	args ::= LiteralString
2602</pre><p>
2603All argument expressions are evaluated before the call.
2604A call of the form <code>f{<em>fields</em>}</code> is
2605syntactic sugar for <code>f({<em>fields</em>})</code>;
2606that is, the argument list is a single new table.
2607A call of the form <code>f'<em>string</em>'</code>
2608(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2609is syntactic sugar for <code>f('<em>string</em>')</code>;
2610that is, the argument list is a single literal string.
2611
2612
2613<p>
2614A call of the form <code>return <em>functioncall</em></code> not in the
2615scope of a to-be-closed variable is called a <em>tail call</em>.
2616Lua implements <em>proper tail calls</em>
2617(or <em>proper tail recursion</em>):
2618in a tail call,
2619the called function reuses the stack entry of the calling function.
2620Therefore, there is no limit on the number of nested tail calls that
2621a program can execute.
2622However, a tail call erases any debug information about the
2623calling function.
2624Note that a tail call only happens with a particular syntax,
2625where the <b>return</b> has one single function call as argument,
2626and it is outside the scope of any to-be-closed variable.
2627This syntax makes the calling function return exactly
2628the returns of the called function,
2629without any intervening action.
2630So, none of the following examples are tail calls:
2631
2632<pre>
2633     return (f(x))        -- results adjusted to 1
2634     return 2 * f(x)      -- result multiplied by 2
2635     return x, f(x)       -- additional results
2636     f(x); return         -- results discarded
2637     return x or f(x)     -- results adjusted to 1
2638</pre>
2639
2640
2641
2642
2643<h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2644
2645<p>
2646The syntax for function definition is
2647
2648<pre>
2649	functiondef ::= <b>function</b> funcbody
2650	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2651</pre>
2652
2653<p>
2654The following syntactic sugar simplifies function definitions:
2655
2656<pre>
2657	stat ::= <b>function</b> funcname funcbody
2658	stat ::= <b>local</b> <b>function</b> Name funcbody
2659	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2660</pre><p>
2661The statement
2662
2663<pre>
2664     function f () <em>body</em> end
2665</pre><p>
2666translates to
2667
2668<pre>
2669     f = function () <em>body</em> end
2670</pre><p>
2671The statement
2672
2673<pre>
2674     function t.a.b.c.f () <em>body</em> end
2675</pre><p>
2676translates to
2677
2678<pre>
2679     t.a.b.c.f = function () <em>body</em> end
2680</pre><p>
2681The statement
2682
2683<pre>
2684     local function f () <em>body</em> end
2685</pre><p>
2686translates to
2687
2688<pre>
2689     local f; f = function () <em>body</em> end
2690</pre><p>
2691not to
2692
2693<pre>
2694     local f = function () <em>body</em> end
2695</pre><p>
2696(This only makes a difference when the body of the function
2697contains references to <code>f</code>.)
2698
2699
2700<p>
2701A function definition is an executable expression,
2702whose value has type <em>function</em>.
2703When Lua precompiles a chunk,
2704all its function bodies are precompiled too,
2705but they are not created yet.
2706Then, whenever Lua executes the function definition,
2707the function is <em>instantiated</em> (or <em>closed</em>).
2708This function instance, or <em>closure</em>,
2709is the final value of the expression.
2710
2711
2712<p>
2713Parameters act as local variables that are
2714initialized with the argument values:
2715
2716<pre>
2717	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2718</pre><p>
2719When a Lua function is called,
2720it adjusts its list of arguments to
2721the length of its list of parameters,
2722unless the function is a <em>vararg function</em>,
2723which is indicated by three dots ('<code>...</code>')
2724at the end of its parameter list.
2725A vararg function does not adjust its argument list;
2726instead, it collects all extra arguments and supplies them
2727to the function through a <em>vararg expression</em>,
2728which is also written as three dots.
2729The value of this expression is a list of all actual extra arguments,
2730similar to a function with multiple results.
2731If a vararg expression is used inside another expression
2732or in the middle of a list of expressions,
2733then its return list is adjusted to one element.
2734If the expression is used as the last element of a list of expressions,
2735then no adjustment is made
2736(unless that last expression is enclosed in parentheses).
2737
2738
2739<p>
2740As an example, consider the following definitions:
2741
2742<pre>
2743     function f(a, b) end
2744     function g(a, b, ...) end
2745     function r() return 1,2,3 end
2746</pre><p>
2747Then, we have the following mapping from arguments to parameters and
2748to the vararg expression:
2749
2750<pre>
2751     CALL             PARAMETERS
2752
2753     f(3)             a=3, b=nil
2754     f(3, 4)          a=3, b=4
2755     f(3, 4, 5)       a=3, b=4
2756     f(r(), 10)       a=1, b=10
2757     f(r())           a=1, b=2
2758
2759     g(3)             a=3, b=nil, ... --&gt;  (nothing)
2760     g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
2761     g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
2762     g(5, r())        a=5, b=1,   ... --&gt;  2  3
2763</pre>
2764
2765<p>
2766Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2767If control reaches the end of a function
2768without encountering a <b>return</b> statement,
2769then the function returns with no results.
2770
2771
2772<p>
2773
2774There is a system-dependent limit on the number of values
2775that a function may return.
2776This limit is guaranteed to be greater than 1000.
2777
2778
2779<p>
2780The <em>colon</em> syntax
2781is used to emulate <em>methods</em>,
2782adding an implicit extra parameter <code>self</code> to the function.
2783Thus, the statement
2784
2785<pre>
2786     function t.a.b.c:f (<em>params</em>) <em>body</em> end
2787</pre><p>
2788is syntactic sugar for
2789
2790<pre>
2791     t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2792</pre>
2793
2794
2795
2796
2797
2798
2799<h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2800
2801<p>
2802
2803Lua is a lexically scoped language.
2804The scope of a local variable begins at the first statement after
2805its declaration and lasts until the last non-void statement
2806of the innermost block that includes the declaration.
2807Consider the following example:
2808
2809<pre>
2810     x = 10                -- global variable
2811     do                    -- new block
2812       local x = x         -- new 'x', with value 10
2813       print(x)            --&gt; 10
2814       x = x+1
2815       do                  -- another block
2816         local x = x+1     -- another 'x'
2817         print(x)          --&gt; 12
2818       end
2819       print(x)            --&gt; 11
2820     end
2821     print(x)              --&gt; 10  (the global one)
2822</pre>
2823
2824<p>
2825Notice that, in a declaration like <code>local x = x</code>,
2826the new <code>x</code> being declared is not in scope yet,
2827and so the second <code>x</code> refers to the outside variable.
2828
2829
2830<p>
2831Because of the lexical scoping rules,
2832local variables can be freely accessed by functions
2833defined inside their scope.
2834A local variable used by an inner function is called an <em>upvalue</em>
2835(or <em>external local variable</em>, or simply <em>external variable</em>)
2836inside the inner function.
2837
2838
2839<p>
2840Notice that each execution of a <b>local</b> statement
2841defines new local variables.
2842Consider the following example:
2843
2844<pre>
2845     a = {}
2846     local x = 20
2847     for i = 1, 10 do
2848       local y = 0
2849       a[i] = function () y = y + 1; return x + y end
2850     end
2851</pre><p>
2852The loop creates ten closures
2853(that is, ten instances of the anonymous function).
2854Each of these closures uses a different <code>y</code> variable,
2855while all of them share the same <code>x</code>.
2856
2857
2858
2859
2860
2861<h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2862
2863
2864
2865<p>
2866
2867This section describes the C&nbsp;API for Lua, that is,
2868the set of C&nbsp;functions available to the host program to communicate
2869with Lua.
2870All API functions and related types and constants
2871are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2872
2873
2874<p>
2875Even when we use the term "function",
2876any facility in the API may be provided as a macro instead.
2877Except where stated otherwise,
2878all such macros use each of their arguments exactly once
2879(except for the first argument, which is always a Lua state),
2880and so do not generate any hidden side-effects.
2881
2882
2883<p>
2884As in most C&nbsp;libraries,
2885the Lua API functions do not check their arguments
2886for validity or consistency.
2887However, you can change this behavior by compiling Lua
2888with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2889
2890
2891<p>
2892The Lua library is fully reentrant:
2893it has no global variables.
2894It keeps all information it needs in a dynamic structure,
2895called the <em>Lua state</em>.
2896
2897
2898<p>
2899Each Lua state has one or more threads,
2900which correspond to independent, cooperative lines of execution.
2901The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread.
2902(Indirectly, through the thread, it also refers to the
2903Lua state associated to the thread.)
2904
2905
2906<p>
2907A pointer to a thread must be passed as the first argument to
2908every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
2909which creates a Lua state from scratch and returns a pointer
2910to the <em>main thread</em> in the new state.
2911
2912
2913
2914
2915
2916<h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2917
2918
2919
2920<p>
2921Lua uses a <em>virtual stack</em> to pass values to and from C.
2922Each element in this stack represents a Lua value
2923(<b>nil</b>, number, string, etc.).
2924Functions in the API can access this stack through the
2925Lua state parameter that they receive.
2926
2927
2928<p>
2929Whenever Lua calls C, the called function gets a new stack,
2930which is independent of previous stacks and of stacks of
2931C&nbsp;functions that are still active.
2932This stack initially contains any arguments to the C&nbsp;function
2933and it is where the C&nbsp;function can store temporary
2934Lua values and must push its results
2935to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2936
2937
2938<p>
2939For convenience,
2940most query operations in the API do not follow a strict stack discipline.
2941Instead, they can refer to any element in the stack
2942by using an <em>index</em>:
2943A positive index represents an absolute stack position,
2944starting at&nbsp;1 as the bottom of the stack;
2945a negative index represents an offset relative to the top of the stack.
2946More specifically, if the stack has <em>n</em> elements,
2947then index&nbsp;1 represents the first element
2948(that is, the element that was pushed onto the stack first)
2949and
2950index&nbsp;<em>n</em> represents the last element;
2951index&nbsp;-1 also represents the last element
2952(that is, the element at the&nbsp;top)
2953and index <em>-n</em> represents the first element.
2954
2955
2956
2957
2958
2959<h3>4.1.1 &ndash; <a name="4.1.1">Stack Size</a></h3>
2960
2961<p>
2962When you interact with the Lua API,
2963you are responsible for ensuring consistency.
2964In particular,
2965<em>you are responsible for controlling stack overflow</em>.
2966When you call any API function,
2967you must ensure the stack has enough room to accommodate the results.
2968
2969
2970<p>
2971There is one exception to the above rule:
2972When you call a Lua function
2973without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2974Lua ensures that the stack has enough space for all results.
2975However, it does not ensure any extra space.
2976So, before pushing anything on the stack after such a call
2977you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2978
2979
2980<p>
2981Whenever Lua calls C,
2982it ensures that the stack has space for
2983at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra elements;
2984that is, you can safely push up to <code>LUA_MINSTACK</code> values into it.
2985<code>LUA_MINSTACK</code> is defined as 20,
2986so that usually you do not have to worry about stack space
2987unless your code has loops pushing elements onto the stack.
2988Whenever necessary,
2989you can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2990to ensure that the stack has enough space for pushing new elements.
2991
2992
2993
2994
2995
2996<h3>4.1.2 &ndash; <a name="4.1.2">Valid and Acceptable Indices</a></h3>
2997
2998<p>
2999Any function in the API that receives stack indices
3000works only with <em>valid indices</em> or <em>acceptable indices</em>.
3001
3002
3003<p>
3004A <em>valid index</em> is an index that refers to a
3005position that stores a modifiable Lua value.
3006It comprises stack indices between&nbsp;1 and the stack top
3007(<code>1 &le; abs(index) &le; top</code>)
3008
3009plus <em>pseudo-indices</em>,
3010which represent some positions that are accessible to C&nbsp;code
3011but that are not in the stack.
3012Pseudo-indices are used to access the registry (see <a href="#4.3">&sect;4.3</a>)
3013and the upvalues of a C&nbsp;function (see <a href="#4.2">&sect;4.2</a>).
3014
3015
3016<p>
3017Functions that do not need a specific mutable position,
3018but only a value (e.g., query functions),
3019can be called with acceptable indices.
3020An <em>acceptable index</em> can be any valid index,
3021but it also can be any positive index after the stack top
3022within the space allocated for the stack,
3023that is, indices up to the stack size.
3024(Note that 0 is never an acceptable index.)
3025Indices to upvalues (see <a href="#4.2">&sect;4.2</a>) greater than the real number
3026of upvalues in the current C&nbsp;function are also acceptable (but invalid).
3027Except when noted otherwise,
3028functions in the API work with acceptable indices.
3029
3030
3031<p>
3032Acceptable indices serve to avoid extra tests
3033against the stack top when querying the stack.
3034For instance, a C&nbsp;function can query its third argument
3035without the need to check whether there is a third argument,
3036that is, without the need to check whether 3 is a valid index.
3037
3038
3039<p>
3040For functions that can be called with acceptable indices,
3041any non-valid index is treated as if it
3042contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
3043which behaves like a nil value.
3044
3045
3046
3047
3048
3049<h3>4.1.3 &ndash; <a name="4.1.3">Pointers to strings</a></h3>
3050
3051<p>
3052Several functions in the API return pointers (<code>const char*</code>)
3053to Lua strings in the stack.
3054(See <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3055<a href="#lua_pushstring"><code>lua_pushstring</code></a>, and <a href="#lua_tolstring"><code>lua_tolstring</code></a>.
3056See also <a href="#luaL_checklstring"><code>luaL_checklstring</code></a>, <a href="#luaL_checkstring"><code>luaL_checkstring</code></a>,
3057and <a href="#luaL_tolstring"><code>luaL_tolstring</code></a> in the auxiliary library.)
3058
3059
3060<p>
3061In general,
3062Lua's garbage collection can free or move internal memory
3063and then invalidate pointers to internal strings.
3064To allow a safe use of these pointers,
3065The API guarantees that any pointer to a string in a stack index
3066is valid while the string value at that index is not removed from the stack.
3067(It can be moved to another index, though.)
3068When the index is a pseudo-index (referring to an upvalue),
3069the pointer is valid while the corresponding call is active and
3070the corresponding upvalue is not modified.
3071
3072
3073<p>
3074Some functions in the debug interface
3075also return pointers to strings,
3076namely <a href="#lua_getlocal"><code>lua_getlocal</code></a>, <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
3077<a href="#lua_setlocal"><code>lua_setlocal</code></a>, and <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.
3078For these functions, the pointer is guaranteed to
3079be valid while the caller function is active and
3080the given closure (if one was given) is in the stack.
3081
3082
3083<p>
3084Except for these guarantees,
3085the garbage collector is free to invalidate
3086any pointer to internal strings.
3087
3088
3089
3090
3091
3092
3093
3094<h2>4.2 &ndash; <a name="4.2">C Closures</a></h2>
3095
3096<p>
3097When a C&nbsp;function is created,
3098it is possible to associate some values with it,
3099thus creating a <em>C&nbsp;closure</em>
3100(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
3101these values are called <em>upvalues</em> and are
3102accessible to the function whenever it is called.
3103
3104
3105<p>
3106Whenever a C&nbsp;function is called,
3107its upvalues are located at specific pseudo-indices.
3108These pseudo-indices are produced by the macro
3109<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
3110The first upvalue associated with a function is at index
3111<code>lua_upvalueindex(1)</code>, and so on.
3112Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
3113where <em>n</em> is greater than the number of upvalues of the
3114current function
3115(but not greater than 256,
3116which is one plus the maximum number of upvalues in a closure),
3117produces an acceptable but invalid index.
3118
3119
3120<p>
3121A C&nbsp;closure can also change the values
3122of its corresponding upvalues.
3123
3124
3125
3126
3127
3128<h2>4.3 &ndash; <a name="4.3">Registry</a></h2>
3129
3130<p>
3131Lua provides a <em>registry</em>,
3132a predefined table that can be used by any C&nbsp;code to
3133store whatever Lua values it needs to store.
3134The registry table is always accessible at pseudo-index
3135<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
3136Any C&nbsp;library can store data into this table,
3137but it must take care to choose keys
3138that are different from those used
3139by other libraries, to avoid collisions.
3140Typically, you should use as key a string containing your library name,
3141or a light userdata with the address of a C&nbsp;object in your code,
3142or any Lua object created by your code.
3143As with variable names,
3144string keys starting with an underscore followed by
3145uppercase letters are reserved for Lua.
3146
3147
3148<p>
3149The integer keys in the registry are used
3150by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
3151and by some predefined values.
3152Therefore, integer keys in the registry
3153must not be used for other purposes.
3154
3155
3156<p>
3157When you create a new Lua state,
3158its registry comes with some predefined values.
3159These predefined values are indexed with integer keys
3160defined as constants in <code>lua.h</code>.
3161The following constants are defined:
3162
3163<ul>
3164<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
3165the main thread of the state.
3166(The main thread is the one created together with the state.)
3167</li>
3168
3169<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
3170the global environment.
3171</li>
3172</ul>
3173
3174
3175
3176
3177<h2>4.4 &ndash; <a name="4.4">Error Handling in C</a></h2>
3178
3179
3180
3181<p>
3182Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
3183(Lua will use exceptions if you compile it as C++;
3184search for <code>LUAI_THROW</code> in the source code for details.)
3185When Lua faces any error,
3186such as a memory allocation error or a type error,
3187it <em>raises</em> an error;
3188that is, it does a long jump.
3189A <em>protected environment</em> uses <code>setjmp</code>
3190to set a recovery point;
3191any error jumps to the most recent active recovery point.
3192
3193
3194<p>
3195Inside a C&nbsp;function you can raise an error explicitly
3196by calling <a href="#lua_error"><code>lua_error</code></a>.
3197
3198
3199<p>
3200Most functions in the API can raise an error,
3201for instance due to a memory allocation error.
3202The documentation for each function indicates whether
3203it can raise errors.
3204
3205
3206<p>
3207If an error happens outside any protected environment,
3208Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
3209and then calls <code>abort</code>,
3210thus exiting the host application.
3211Your panic function can avoid this exit by
3212never returning
3213(e.g., doing a long jump to your own recovery point outside Lua).
3214
3215
3216<p>
3217The panic function,
3218as its name implies,
3219is a mechanism of last resort.
3220Programs should avoid it.
3221As a general rule,
3222when a C&nbsp;function is called by Lua with a Lua state,
3223it can do whatever it wants on that Lua state,
3224as it should be already protected.
3225However,
3226when C code operates on other Lua states
3227(e.g., a Lua-state argument to the function,
3228a Lua state stored in the registry, or
3229the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
3230it should use them only in API calls that cannot raise errors.
3231
3232
3233<p>
3234The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
3235in particular, the error object is on the top of the stack.
3236However, there is no guarantee about stack space.
3237To push anything on the stack,
3238the panic function must first check the available space (see <a href="#4.1.1">&sect;4.1.1</a>).
3239
3240
3241
3242
3243
3244<h3>4.4.1 &ndash; <a name="4.4.1">Status Codes</a></h3>
3245
3246<p>
3247Several functions that report errors in the API use the following
3248status codes to indicate different kinds of errors or other conditions:
3249
3250<ul>
3251
3252<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> no errors.</li>
3253
3254<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> a runtime error.</li>
3255
3256<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3257memory allocation error.
3258For such errors, Lua does not call the message handler.
3259</li>
3260
3261<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> error while running the message handler.</li>
3262
3263<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> syntax error during precompilation.</li>
3264
3265<li><b><a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a>: </b> the thread (coroutine) yields.</li>
3266
3267<li><b><a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>: </b> a file-related error;
3268e.g., it cannot open or read the file.</li>
3269
3270</ul><p>
3271These constants are defined in the header file <code>lua.h</code>.
3272
3273
3274
3275
3276
3277
3278
3279<h2>4.5 &ndash; <a name="4.5">Handling Yields in C</a></h2>
3280
3281<p>
3282Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
3283Therefore, if a C&nbsp;function <code>foo</code> calls an API function
3284and this API function yields
3285(directly or indirectly by calling another function that yields),
3286Lua cannot return to <code>foo</code> any more,
3287because the <code>longjmp</code> removes its frame from the C&nbsp;stack.
3288
3289
3290<p>
3291To avoid this kind of problem,
3292Lua raises an error whenever it tries to yield across an API call,
3293except for three functions:
3294<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>.
3295All those functions receive a <em>continuation function</em>
3296(as a parameter named <code>k</code>) to continue execution after a yield.
3297
3298
3299<p>
3300We need to set some terminology to explain continuations.
3301We have a C&nbsp;function called from Lua which we will call
3302the <em>original function</em>.
3303This original function then calls one of those three functions in the C API,
3304which we will call the <em>callee function</em>,
3305that then yields the current thread.
3306This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
3307or 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>
3308and the function called by them yields.
3309
3310
3311<p>
3312Suppose the running thread yields while executing the callee function.
3313After the thread resumes,
3314it eventually will finish running the callee function.
3315However,
3316the callee function cannot return to the original function,
3317because its frame in the C&nbsp;stack was destroyed by the yield.
3318Instead, Lua calls a <em>continuation function</em>,
3319which was given as an argument to the callee function.
3320As the name implies,
3321the continuation function should continue the task
3322of the original function.
3323
3324
3325<p>
3326As an illustration, consider the following function:
3327
3328<pre>
3329     int original_function (lua_State *L) {
3330       ...     /* code 1 */
3331       status = lua_pcall(L, n, m, h);  /* calls Lua */
3332       ...     /* code 2 */
3333     }
3334</pre><p>
3335Now we want to allow
3336the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
3337First, we can rewrite our function like here:
3338
3339<pre>
3340     int k (lua_State *L, int status, lua_KContext ctx) {
3341       ...  /* code 2 */
3342     }
3343
3344     int original_function (lua_State *L) {
3345       ...     /* code 1 */
3346       return k(L, lua_pcall(L, n, m, h), ctx);
3347     }
3348</pre><p>
3349In the above code,
3350the new function <code>k</code> is a
3351<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
3352which should do all the work that the original function
3353was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
3354Now, we must inform Lua that it must call <code>k</code> if the Lua code
3355being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
3356(errors or yielding),
3357so we rewrite the code as here,
3358replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
3359
3360<pre>
3361     int original_function (lua_State *L) {
3362       ...     /* code 1 */
3363       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
3364     }
3365</pre><p>
3366Note the external, explicit call to the continuation:
3367Lua will call the continuation only if needed, that is,
3368in case of errors or resuming after a yield.
3369If the called function returns normally without ever yielding,
3370<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
3371(Of course, instead of calling the continuation in that case,
3372you can do the equivalent work directly inside the original function.)
3373
3374
3375<p>
3376Besides the Lua state,
3377the continuation function has two other parameters:
3378the final status of the call and the context value (<code>ctx</code>) that
3379was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3380Lua does not use this context value;
3381it only passes this value from the original function to the
3382continuation function.
3383For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3384the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3385except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
3386(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
3387For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
3388the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
3389(For these two functions,
3390Lua will not call the continuation in case of errors,
3391because they do not handle errors.)
3392Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
3393you should call the continuation function
3394with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
3395(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
3396directly the continuation function,
3397because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
3398
3399
3400<p>
3401Lua treats the continuation function as if it were the original function.
3402The continuation function receives the same Lua stack
3403from the original function,
3404in the same state it would be if the callee function had returned.
3405(For instance,
3406after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
3407removed from the stack and replaced by the results from the call.)
3408It also has the same upvalues.
3409Whatever it returns is handled by Lua as if it were the return
3410of the original function.
3411
3412
3413
3414
3415
3416<h2>4.6 &ndash; <a name="4.6">Functions and Types</a></h2>
3417
3418<p>
3419Here we list all functions and types from the C&nbsp;API in
3420alphabetical order.
3421Each function has an indicator like this:
3422<span class="apii">[-o, +p, <em>x</em>]</span>
3423
3424
3425<p>
3426The first field, <code>o</code>,
3427is how many elements the function pops from the stack.
3428The second field, <code>p</code>,
3429is how many elements the function pushes onto the stack.
3430(Any function always pushes its results after popping its arguments.)
3431A field in the form <code>x|y</code> means the function can push (or pop)
3432<code>x</code> or <code>y</code> elements,
3433depending on the situation;
3434an interrogation mark '<code>?</code>' means that
3435we cannot know how many elements the function pops/pushes
3436by looking only at its arguments.
3437(For instance, they may depend on what is in the stack.)
3438The third field, <code>x</code>,
3439tells whether the function may raise errors:
3440'<code>-</code>' means the function never raises any error;
3441'<code>m</code>' means the function may raise only out-of-memory errors;
3442'<code>v</code>' means the function may raise the errors explained in the text;
3443'<code>e</code>' means the function can run arbitrary Lua code,
3444either directly or through metamethods,
3445and therefore may raise any errors.
3446
3447
3448
3449<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
3450<span class="apii">[-0, +0, &ndash;]</span>
3451<pre>int lua_absindex (lua_State *L, int idx);</pre>
3452
3453<p>
3454Converts the acceptable index <code>idx</code>
3455into an equivalent absolute index
3456(that is, one that does not depend on the stack size).
3457
3458
3459
3460
3461
3462<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
3463<pre>typedef void * (*lua_Alloc) (void *ud,
3464                             void *ptr,
3465                             size_t osize,
3466                             size_t nsize);</pre>
3467
3468<p>
3469The type of the memory-allocation function used by Lua states.
3470The allocator function must provide a
3471functionality similar to <code>realloc</code>,
3472but not exactly the same.
3473Its arguments are
3474<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3475<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3476<code>osize</code>, the original size of the block or some code about what
3477is being allocated;
3478and <code>nsize</code>, the new size of the block.
3479
3480
3481<p>
3482When <code>ptr</code> is not <code>NULL</code>,
3483<code>osize</code> is the size of the block pointed by <code>ptr</code>,
3484that is, the size given when it was allocated or reallocated.
3485
3486
3487<p>
3488When <code>ptr</code> is <code>NULL</code>,
3489<code>osize</code> encodes the kind of object that Lua is allocating.
3490<code>osize</code> is any of
3491<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>,
3492<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)
3493Lua is creating a new object of that type.
3494When <code>osize</code> is some other value,
3495Lua is allocating memory for something else.
3496
3497
3498<p>
3499Lua assumes the following behavior from the allocator function:
3500
3501
3502<p>
3503When <code>nsize</code> is zero,
3504the allocator must behave like <code>free</code>
3505and then return <code>NULL</code>.
3506
3507
3508<p>
3509When <code>nsize</code> is not zero,
3510the allocator must behave like <code>realloc</code>.
3511In particular, the allocator returns <code>NULL</code>
3512if and only if it cannot fulfill the request.
3513
3514
3515<p>
3516Here is a simple implementation for the allocator function.
3517It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3518
3519<pre>
3520     static void *l_alloc (void *ud, void *ptr, size_t osize,
3521                                                size_t nsize) {
3522       (void)ud;  (void)osize;  /* not used */
3523       if (nsize == 0) {
3524         free(ptr);
3525         return NULL;
3526       }
3527       else
3528         return realloc(ptr, nsize);
3529     }
3530</pre><p>
3531Note that Standard&nbsp;C ensures
3532that <code>free(NULL)</code> has no effect and that
3533<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3534
3535
3536
3537
3538
3539<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3540<span class="apii">[-(2|1), +1, <em>e</em>]</span>
3541<pre>void lua_arith (lua_State *L, int op);</pre>
3542
3543<p>
3544Performs an arithmetic or bitwise operation over the two values
3545(or one, in the case of negations)
3546at the top of the stack,
3547with the value on the top being the second operand,
3548pops these values, and pushes the result of the operation.
3549The function follows the semantics of the corresponding Lua operator
3550(that is, it may call metamethods).
3551
3552
3553<p>
3554The value of <code>op</code> must be one of the following constants:
3555
3556<ul>
3557
3558<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3559<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3560<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3561<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3562<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3563<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3564<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3565<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3566<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
3567<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li>
3568<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
3569<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
3570<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3571<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3572
3573</ul>
3574
3575
3576
3577
3578<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3579<span class="apii">[-0, +0, &ndash;]</span>
3580<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3581
3582<p>
3583Sets a new panic function and returns the old one (see <a href="#4.4">&sect;4.4</a>).
3584
3585
3586
3587
3588
3589<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3590<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3591<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3592
3593<p>
3594Calls a function.
3595Like regular Lua calls,
3596<code>lua_call</code> respects the <code>__call</code> metamethod.
3597So, here the word "function"
3598means any callable value.
3599
3600
3601<p>
3602To do a call you must use the following protocol:
3603first, the function to be called is pushed onto the stack;
3604then, the arguments to the call are pushed
3605in direct order;
3606that is, the first argument is pushed first.
3607Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3608<code>nargs</code> is the number of arguments that you pushed onto the stack.
3609When the function returns,
3610all arguments and the function value are popped
3611and the call results are pushed onto the stack.
3612The number of results is adjusted to <code>nresults</code>,
3613unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3614In this case, all results from the function are pushed;
3615Lua takes care that the returned values fit into the stack space,
3616but it does not ensure any extra space in the stack.
3617The function results are pushed onto the stack in direct order
3618(the first result is pushed first),
3619so that after the call the last result is on the top of the stack.
3620
3621
3622<p>
3623Any error while calling and running the function is propagated upwards
3624(with a <code>longjmp</code>).
3625
3626
3627<p>
3628The following example shows how the host program can do the
3629equivalent to this Lua code:
3630
3631<pre>
3632     a = f("how", t.x, 14)
3633</pre><p>
3634Here it is in&nbsp;C:
3635
3636<pre>
3637     lua_getglobal(L, "f");                  /* function to be called */
3638     lua_pushliteral(L, "how");                       /* 1st argument */
3639     lua_getglobal(L, "t");                    /* table to be indexed */
3640     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
3641     lua_remove(L, -2);                  /* remove 't' from the stack */
3642     lua_pushinteger(L, 14);                          /* 3rd argument */
3643     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
3644     lua_setglobal(L, "a");                         /* set global 'a' */
3645</pre><p>
3646Note that the code above is <em>balanced</em>:
3647at its end, the stack is back to its original configuration.
3648This is considered good programming practice.
3649
3650
3651
3652
3653
3654<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3655<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3656<pre>void lua_callk (lua_State *L,
3657                int nargs,
3658                int nresults,
3659                lua_KContext ctx,
3660                lua_KFunction k);</pre>
3661
3662<p>
3663This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3664but allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
3665
3666
3667
3668
3669
3670<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3671<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3672
3673<p>
3674Type for C&nbsp;functions.
3675
3676
3677<p>
3678In order to communicate properly with Lua,
3679a C&nbsp;function must use the following protocol,
3680which defines the way parameters and results are passed:
3681a C&nbsp;function receives its arguments from Lua in its stack
3682in direct order (the first argument is pushed first).
3683So, when the function starts,
3684<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3685The first argument (if any) is at index 1
3686and its last argument is at index <code>lua_gettop(L)</code>.
3687To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3688in direct order (the first result is pushed first),
3689and returns in C the number of results.
3690Any other value in the stack below the results will be properly
3691discarded by Lua.
3692Like a Lua function, a C&nbsp;function called by Lua can also return
3693many results.
3694
3695
3696<p>
3697As an example, the following function receives a variable number
3698of numeric arguments and returns their average and their sum:
3699
3700<pre>
3701     static int foo (lua_State *L) {
3702       int n = lua_gettop(L);    /* number of arguments */
3703       lua_Number sum = 0.0;
3704       int i;
3705       for (i = 1; i &lt;= n; i++) {
3706         if (!lua_isnumber(L, i)) {
3707           lua_pushliteral(L, "incorrect argument");
3708           lua_error(L);
3709         }
3710         sum += lua_tonumber(L, i);
3711       }
3712       lua_pushnumber(L, sum/n);        /* first result */
3713       lua_pushnumber(L, sum);         /* second result */
3714       return 2;                   /* number of results */
3715     }
3716</pre>
3717
3718
3719
3720
3721<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3722<span class="apii">[-0, +0, &ndash;]</span>
3723<pre>int lua_checkstack (lua_State *L, int n);</pre>
3724
3725<p>
3726Ensures that the stack has space for at least <code>n</code> extra elements,
3727that is, that you can safely push up to <code>n</code> values into it.
3728It returns false if it cannot fulfill the request,
3729either because it would cause the stack
3730to be greater than a fixed maximum size
3731(typically at least several thousand elements) or
3732because it cannot allocate memory for the extra space.
3733This function never shrinks the stack;
3734if the stack already has space for the extra elements,
3735it is left unchanged.
3736
3737
3738
3739
3740
3741<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3742<span class="apii">[-0, +0, &ndash;]</span>
3743<pre>void lua_close (lua_State *L);</pre>
3744
3745<p>
3746Close all active to-be-closed variables in the main thread,
3747release all objects in the given Lua state
3748(calling the corresponding garbage-collection metamethods, if any),
3749and frees all dynamic memory used by this state.
3750
3751
3752<p>
3753On several platforms, you may not need to call this function,
3754because all resources are naturally released when the host program ends.
3755On the other hand, long-running programs that create multiple states,
3756such as daemons or web servers,
3757will probably need to close states as soon as they are not needed.
3758
3759
3760
3761
3762
3763<hr><h3><a name="lua_closeslot"><code>lua_closeslot</code></a></h3><p>
3764<span class="apii">[-0, +0, <em>e</em>]</span>
3765<pre>void lua_closeslot (lua_State *L, int index);</pre>
3766
3767<p>
3768Close the to-be-closed slot at the given index and set its value to <b>nil</b>.
3769The index must be the last index previously marked to be closed
3770(see <a href="#lua_toclose"><code>lua_toclose</code></a>) that is still active (that is, not closed yet).
3771
3772
3773<p>
3774A <code>__close</code> metamethod cannot yield
3775when called through this function.
3776
3777
3778<p>
3779(Exceptionally, this function was introduced in release 5.4.3.
3780It is not present in previous 5.4 releases.)
3781
3782
3783
3784
3785
3786<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3787<span class="apii">[-0, +0, <em>e</em>]</span>
3788<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3789
3790<p>
3791Compares two Lua values.
3792Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3793when compared with the value at index <code>index2</code>,
3794following the semantics of the corresponding Lua operator
3795(that is, it may call metamethods).
3796Otherwise returns&nbsp;0.
3797Also returns&nbsp;0 if any of the indices is not valid.
3798
3799
3800<p>
3801The value of <code>op</code> must be one of the following constants:
3802
3803<ul>
3804
3805<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3806<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3807<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3808
3809</ul>
3810
3811
3812
3813
3814<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3815<span class="apii">[-n, +1, <em>e</em>]</span>
3816<pre>void lua_concat (lua_State *L, int n);</pre>
3817
3818<p>
3819Concatenates the <code>n</code> values at the top of the stack,
3820pops them, and leaves the result on the top.
3821If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3822(that is, the function does nothing);
3823if <code>n</code> is 0, the result is the empty string.
3824Concatenation is performed following the usual semantics of Lua
3825(see <a href="#3.4.6">&sect;3.4.6</a>).
3826
3827
3828
3829
3830
3831<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3832<span class="apii">[-0, +0, &ndash;]</span>
3833<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3834
3835<p>
3836Copies the element at index <code>fromidx</code>
3837into the valid index <code>toidx</code>,
3838replacing the value at that position.
3839Values at other positions are not affected.
3840
3841
3842
3843
3844
3845<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3846<span class="apii">[-0, +1, <em>m</em>]</span>
3847<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3848
3849<p>
3850Creates a new empty table and pushes it onto the stack.
3851Parameter <code>narr</code> is a hint for how many elements the table
3852will have as a sequence;
3853parameter <code>nrec</code> is a hint for how many other elements
3854the table will have.
3855Lua may use these hints to preallocate memory for the new table.
3856This preallocation may help performance when you know in advance
3857how many elements the table will have.
3858Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3859
3860
3861
3862
3863
3864<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3865<span class="apii">[-0, +0, &ndash;]</span>
3866<pre>int lua_dump (lua_State *L,
3867                        lua_Writer writer,
3868                        void *data,
3869                        int strip);</pre>
3870
3871<p>
3872Dumps a function as a binary chunk.
3873Receives a Lua function on the top of the stack
3874and produces a binary chunk that,
3875if loaded again,
3876results in a function equivalent to the one dumped.
3877As it produces parts of the chunk,
3878<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3879with the given <code>data</code>
3880to write them.
3881
3882
3883<p>
3884If <code>strip</code> is true,
3885the binary representation may not include all debug information
3886about the function,
3887to save space.
3888
3889
3890<p>
3891The value returned is the error code returned by the last
3892call to the writer;
38930&nbsp;means no errors.
3894
3895
3896<p>
3897This function does not pop the Lua function from the stack.
3898
3899
3900
3901
3902
3903<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3904<span class="apii">[-1, +0, <em>v</em>]</span>
3905<pre>int lua_error (lua_State *L);</pre>
3906
3907<p>
3908Raises a Lua error,
3909using the value on the top of the stack as the error object.
3910This function does a long jump,
3911and therefore never returns
3912(see <a href="#luaL_error"><code>luaL_error</code></a>).
3913
3914
3915
3916
3917
3918<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3919<span class="apii">[-0, +0, &ndash;]</span>
3920<pre>int lua_gc (lua_State *L, int what, ...);</pre>
3921
3922<p>
3923Controls the garbage collector.
3924
3925
3926<p>
3927This function performs several tasks,
3928according to the value of the parameter <code>what</code>.
3929For options that need extra arguments,
3930they are listed after the option.
3931
3932<ul>
3933
3934<li><b><code>LUA_GCCOLLECT</code>: </b>
3935Performs a full garbage-collection cycle.
3936</li>
3937
3938<li><b><code>LUA_GCSTOP</code>: </b>
3939Stops the garbage collector.
3940</li>
3941
3942<li><b><code>LUA_GCRESTART</code>: </b>
3943Restarts the garbage collector.
3944</li>
3945
3946<li><b><code>LUA_GCCOUNT</code>: </b>
3947Returns the current amount of memory (in Kbytes) in use by Lua.
3948</li>
3949
3950<li><b><code>LUA_GCCOUNTB</code>: </b>
3951Returns the remainder of dividing the current amount of bytes of
3952memory in use by Lua by 1024.
3953</li>
3954
3955<li><b><code>LUA_GCSTEP</code> <code>(int stepsize)</code>: </b>
3956Performs an incremental step of garbage collection,
3957corresponding to the allocation of <code>stepsize</code> Kbytes.
3958</li>
3959
3960<li><b><code>LUA_GCISRUNNING</code>: </b>
3961Returns a boolean that tells whether the collector is running
3962(i.e., not stopped).
3963</li>
3964
3965<li><b><code>LUA_GCINC</code> (int pause, int stepmul, stepsize): </b>
3966Changes the collector to incremental mode
3967with the given parameters (see <a href="#2.5.1">&sect;2.5.1</a>).
3968Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3969</li>
3970
3971<li><b><code>LUA_GCGEN</code> (int minormul, int majormul): </b>
3972Changes the collector to generational mode
3973with the given parameters (see <a href="#2.5.2">&sect;2.5.2</a>).
3974Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3975</li>
3976
3977</ul><p>
3978For more details about these options,
3979see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3980
3981
3982
3983
3984
3985<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3986<span class="apii">[-0, +0, &ndash;]</span>
3987<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3988
3989<p>
3990Returns the memory-allocation function of a given state.
3991If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3992opaque pointer given when the memory-allocator function was set.
3993
3994
3995
3996
3997
3998<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3999<span class="apii">[-0, +1, <em>e</em>]</span>
4000<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
4001
4002<p>
4003Pushes onto the stack the value <code>t[k]</code>,
4004where <code>t</code> is the value at the given index.
4005As in Lua, this function may trigger a metamethod
4006for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4007
4008
4009<p>
4010Returns the type of the pushed value.
4011
4012
4013
4014
4015
4016<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
4017<span class="apii">[-0, +0, &ndash;]</span>
4018<pre>void *lua_getextraspace (lua_State *L);</pre>
4019
4020<p>
4021Returns a pointer to a raw memory area associated with the
4022given Lua state.
4023The application can use this area for any purpose;
4024Lua does not use it for anything.
4025
4026
4027<p>
4028Each new thread has this area initialized with a copy
4029of the area of the main thread.
4030
4031
4032<p>
4033By default, this area has the size of a pointer to void,
4034but you can recompile Lua with a different size for this area.
4035(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
4036
4037
4038
4039
4040
4041<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
4042<span class="apii">[-0, +1, <em>e</em>]</span>
4043<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
4044
4045<p>
4046Pushes onto the stack the value of the global <code>name</code>.
4047Returns the type of that value.
4048
4049
4050
4051
4052
4053<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
4054<span class="apii">[-0, +1, <em>e</em>]</span>
4055<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
4056
4057<p>
4058Pushes onto the stack the value <code>t[i]</code>,
4059where <code>t</code> is the value at the given index.
4060As in Lua, this function may trigger a metamethod
4061for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4062
4063
4064<p>
4065Returns the type of the pushed value.
4066
4067
4068
4069
4070
4071<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
4072<span class="apii">[-0, +(0|1), &ndash;]</span>
4073<pre>int lua_getmetatable (lua_State *L, int index);</pre>
4074
4075<p>
4076If the value at the given index has a metatable,
4077the function pushes that metatable onto the stack and returns&nbsp;1.
4078Otherwise,
4079the function returns&nbsp;0 and pushes nothing on the stack.
4080
4081
4082
4083
4084
4085<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
4086<span class="apii">[-1, +1, <em>e</em>]</span>
4087<pre>int lua_gettable (lua_State *L, int index);</pre>
4088
4089<p>
4090Pushes onto the stack the value <code>t[k]</code>,
4091where <code>t</code> is the value at the given index
4092and <code>k</code> is the value on the top of the stack.
4093
4094
4095<p>
4096This function pops the key from the stack,
4097pushing the resulting value in its place.
4098As in Lua, this function may trigger a metamethod
4099for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4100
4101
4102<p>
4103Returns the type of the pushed value.
4104
4105
4106
4107
4108
4109<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
4110<span class="apii">[-0, +0, &ndash;]</span>
4111<pre>int lua_gettop (lua_State *L);</pre>
4112
4113<p>
4114Returns the index of the top element in the stack.
4115Because indices start at&nbsp;1,
4116this result is equal to the number of elements in the stack;
4117in particular, 0&nbsp;means an empty stack.
4118
4119
4120
4121
4122
4123<hr><h3><a name="lua_getiuservalue"><code>lua_getiuservalue</code></a></h3><p>
4124<span class="apii">[-0, +1, &ndash;]</span>
4125<pre>int lua_getiuservalue (lua_State *L, int index, int n);</pre>
4126
4127<p>
4128Pushes onto the stack the <code>n</code>-th user value associated with the
4129full userdata at the given index and
4130returns the type of the pushed value.
4131
4132
4133<p>
4134If the userdata does not have that value,
4135pushes <b>nil</b> and returns <a href="#pdf-LUA_TNONE"><code>LUA_TNONE</code></a>.
4136
4137
4138
4139
4140
4141<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
4142<span class="apii">[-1, +1, &ndash;]</span>
4143<pre>void lua_insert (lua_State *L, int index);</pre>
4144
4145<p>
4146Moves the top element into the given valid index,
4147shifting up the elements above this index to open space.
4148This function cannot be called with a pseudo-index,
4149because a pseudo-index is not an actual stack position.
4150
4151
4152
4153
4154
4155<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
4156<pre>typedef ... lua_Integer;</pre>
4157
4158<p>
4159The type of integers in Lua.
4160
4161
4162<p>
4163By default this type is <code>long long</code>,
4164(usually a 64-bit two-complement integer),
4165but that can be changed to <code>long</code> or <code>int</code>
4166(usually a 32-bit two-complement integer).
4167(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
4168
4169
4170<p>
4171Lua also defines the constants
4172<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
4173with the minimum and the maximum values that fit in this type.
4174
4175
4176
4177
4178
4179<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
4180<span class="apii">[-0, +0, &ndash;]</span>
4181<pre>int lua_isboolean (lua_State *L, int index);</pre>
4182
4183<p>
4184Returns 1 if the value at the given index is a boolean,
4185and 0&nbsp;otherwise.
4186
4187
4188
4189
4190
4191<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
4192<span class="apii">[-0, +0, &ndash;]</span>
4193<pre>int lua_iscfunction (lua_State *L, int index);</pre>
4194
4195<p>
4196Returns 1 if the value at the given index is a C&nbsp;function,
4197and 0&nbsp;otherwise.
4198
4199
4200
4201
4202
4203<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
4204<span class="apii">[-0, +0, &ndash;]</span>
4205<pre>int lua_isfunction (lua_State *L, int index);</pre>
4206
4207<p>
4208Returns 1 if the value at the given index is a function
4209(either C or Lua), and 0&nbsp;otherwise.
4210
4211
4212
4213
4214
4215<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
4216<span class="apii">[-0, +0, &ndash;]</span>
4217<pre>int lua_isinteger (lua_State *L, int index);</pre>
4218
4219<p>
4220Returns 1 if the value at the given index is an integer
4221(that is, the value is a number and is represented as an integer),
4222and 0&nbsp;otherwise.
4223
4224
4225
4226
4227
4228<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
4229<span class="apii">[-0, +0, &ndash;]</span>
4230<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
4231
4232<p>
4233Returns 1 if the value at the given index is a light userdata,
4234and 0&nbsp;otherwise.
4235
4236
4237
4238
4239
4240<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
4241<span class="apii">[-0, +0, &ndash;]</span>
4242<pre>int lua_isnil (lua_State *L, int index);</pre>
4243
4244<p>
4245Returns 1 if the value at the given index is <b>nil</b>,
4246and 0&nbsp;otherwise.
4247
4248
4249
4250
4251
4252<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
4253<span class="apii">[-0, +0, &ndash;]</span>
4254<pre>int lua_isnone (lua_State *L, int index);</pre>
4255
4256<p>
4257Returns 1 if the given index is not valid,
4258and 0&nbsp;otherwise.
4259
4260
4261
4262
4263
4264<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
4265<span class="apii">[-0, +0, &ndash;]</span>
4266<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
4267
4268<p>
4269Returns 1 if the given index is not valid
4270or if the value at this index is <b>nil</b>,
4271and 0&nbsp;otherwise.
4272
4273
4274
4275
4276
4277<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
4278<span class="apii">[-0, +0, &ndash;]</span>
4279<pre>int lua_isnumber (lua_State *L, int index);</pre>
4280
4281<p>
4282Returns 1 if the value at the given index is a number
4283or a string convertible to a number,
4284and 0&nbsp;otherwise.
4285
4286
4287
4288
4289
4290<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
4291<span class="apii">[-0, +0, &ndash;]</span>
4292<pre>int lua_isstring (lua_State *L, int index);</pre>
4293
4294<p>
4295Returns 1 if the value at the given index is a string
4296or a number (which is always convertible to a string),
4297and 0&nbsp;otherwise.
4298
4299
4300
4301
4302
4303<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
4304<span class="apii">[-0, +0, &ndash;]</span>
4305<pre>int lua_istable (lua_State *L, int index);</pre>
4306
4307<p>
4308Returns 1 if the value at the given index is a table,
4309and 0&nbsp;otherwise.
4310
4311
4312
4313
4314
4315<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
4316<span class="apii">[-0, +0, &ndash;]</span>
4317<pre>int lua_isthread (lua_State *L, int index);</pre>
4318
4319<p>
4320Returns 1 if the value at the given index is a thread,
4321and 0&nbsp;otherwise.
4322
4323
4324
4325
4326
4327<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
4328<span class="apii">[-0, +0, &ndash;]</span>
4329<pre>int lua_isuserdata (lua_State *L, int index);</pre>
4330
4331<p>
4332Returns 1 if the value at the given index is a userdata
4333(either full or light), and 0&nbsp;otherwise.
4334
4335
4336
4337
4338
4339<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
4340<span class="apii">[-0, +0, &ndash;]</span>
4341<pre>int lua_isyieldable (lua_State *L);</pre>
4342
4343<p>
4344Returns 1 if the given coroutine can yield,
4345and 0&nbsp;otherwise.
4346
4347
4348
4349
4350
4351<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
4352<pre>typedef ... lua_KContext;</pre>
4353
4354<p>
4355The type for continuation-function contexts.
4356It must be a numeric type.
4357This type is defined as <code>intptr_t</code>
4358when <code>intptr_t</code> is available,
4359so that it can store pointers too.
4360Otherwise, it is defined as <code>ptrdiff_t</code>.
4361
4362
4363
4364
4365
4366<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
4367<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
4368
4369<p>
4370Type for continuation functions (see <a href="#4.5">&sect;4.5</a>).
4371
4372
4373
4374
4375
4376<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
4377<span class="apii">[-0, +1, <em>e</em>]</span>
4378<pre>void lua_len (lua_State *L, int index);</pre>
4379
4380<p>
4381Returns the length of the value at the given index.
4382It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
4383may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
4384The result is pushed on the stack.
4385
4386
4387
4388
4389
4390<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
4391<span class="apii">[-0, +1, &ndash;]</span>
4392<pre>int lua_load (lua_State *L,
4393              lua_Reader reader,
4394              void *data,
4395              const char *chunkname,
4396              const char *mode);</pre>
4397
4398<p>
4399Loads a Lua chunk without running it.
4400If there are no errors,
4401<code>lua_load</code> pushes the compiled chunk as a Lua
4402function on top of the stack.
4403Otherwise, it pushes an error message.
4404
4405
4406<p>
4407The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
4408to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
4409The <code>data</code> argument is an opaque value passed to the reader function.
4410
4411
4412<p>
4413The <code>chunkname</code> argument gives a name to the chunk,
4414which is used for error messages and in debug information (see <a href="#4.7">&sect;4.7</a>).
4415
4416
4417<p>
4418<code>lua_load</code> automatically detects whether the chunk is text or binary
4419and loads it accordingly (see program <code>luac</code>).
4420The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
4421with the addition that
4422a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
4423
4424
4425<p>
4426<code>lua_load</code> uses the stack internally,
4427so the reader function must always leave the stack
4428unmodified when returning.
4429
4430
4431<p>
4432<code>lua_load</code> can return
4433<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>.
4434The function may also return other values corresponding to
4435errors raised by the read function (see <a href="#4.4.1">&sect;4.4.1</a>).
4436
4437
4438<p>
4439If the resulting function has upvalues,
4440its first upvalue is set to the value of the global environment
4441stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.3">&sect;4.3</a>).
4442When loading main chunks,
4443this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
4444Other upvalues are initialized with <b>nil</b>.
4445
4446
4447
4448
4449
4450<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
4451<span class="apii">[-0, +0, &ndash;]</span>
4452<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
4453
4454<p>
4455Creates a new independent state and returns its main thread.
4456Returns <code>NULL</code> if it cannot create the state
4457(due to lack of memory).
4458The argument <code>f</code> is the allocator function;
4459Lua will do all memory allocation for this state
4460through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
4461The second argument, <code>ud</code>, is an opaque pointer that Lua
4462passes to the allocator in every call.
4463
4464
4465
4466
4467
4468<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
4469<span class="apii">[-0, +1, <em>m</em>]</span>
4470<pre>void lua_newtable (lua_State *L);</pre>
4471
4472<p>
4473Creates a new empty table and pushes it onto the stack.
4474It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
4475
4476
4477
4478
4479
4480<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
4481<span class="apii">[-0, +1, <em>m</em>]</span>
4482<pre>lua_State *lua_newthread (lua_State *L);</pre>
4483
4484<p>
4485Creates a new thread, pushes it on the stack,
4486and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
4487The new thread returned by this function shares with the original thread
4488its global environment,
4489but has an independent execution stack.
4490
4491
4492<p>
4493Threads are subject to garbage collection,
4494like any Lua object.
4495
4496
4497
4498
4499
4500<hr><h3><a name="lua_newuserdatauv"><code>lua_newuserdatauv</code></a></h3><p>
4501<span class="apii">[-0, +1, <em>m</em>]</span>
4502<pre>void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);</pre>
4503
4504<p>
4505This function creates and pushes on the stack a new full userdata,
4506with <code>nuvalue</code> associated Lua values, called <code>user values</code>,
4507plus an associated block of raw memory with <code>size</code> bytes.
4508(The user values can be set and read with the functions
4509<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a> and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>.)
4510
4511
4512<p>
4513The function returns the address of the block of memory.
4514Lua ensures that this address is valid as long as
4515the corresponding userdata is alive (see <a href="#2.5">&sect;2.5</a>).
4516Moreover, if the userdata is marked for finalization (see <a href="#2.5.3">&sect;2.5.3</a>),
4517its address is valid at least until the call to its finalizer.
4518
4519
4520
4521
4522
4523<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4524<span class="apii">[-1, +(2|0), <em>v</em>]</span>
4525<pre>int lua_next (lua_State *L, int index);</pre>
4526
4527<p>
4528Pops a key from the stack,
4529and pushes a key&ndash;value pair from the table at the given index,
4530the "next" pair after the given key.
4531If there are no more elements in the table,
4532then <a href="#lua_next"><code>lua_next</code></a> returns 0 and pushes nothing.
4533
4534
4535<p>
4536A typical table traversal looks like this:
4537
4538<pre>
4539     /* table is in the stack at index 't' */
4540     lua_pushnil(L);  /* first key */
4541     while (lua_next(L, t) != 0) {
4542       /* uses 'key' (at index -2) and 'value' (at index -1) */
4543       printf("%s - %s\n",
4544              lua_typename(L, lua_type(L, -2)),
4545              lua_typename(L, lua_type(L, -1)));
4546       /* removes 'value'; keeps 'key' for next iteration */
4547       lua_pop(L, 1);
4548     }
4549</pre>
4550
4551<p>
4552While traversing a table,
4553avoid calling <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4554unless you know that the key is actually a string.
4555Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4556the value at the given index;
4557this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4558
4559
4560<p>
4561This function may raise an error if the given key
4562is neither <b>nil</b> nor present in the table.
4563See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4564the table during its traversal.
4565
4566
4567
4568
4569
4570<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4571<pre>typedef ... lua_Number;</pre>
4572
4573<p>
4574The type of floats in Lua.
4575
4576
4577<p>
4578By default this type is double,
4579but that can be changed to a single float or a long double.
4580(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
4581
4582
4583
4584
4585
4586<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4587<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4588
4589<p>
4590Tries to convert a Lua float to a Lua integer;
4591the float <code>n</code> must have an integral value.
4592If that value is within the range of Lua integers,
4593it is converted to an integer and assigned to <code>*p</code>.
4594The macro results in a boolean indicating whether the
4595conversion was successful.
4596(Note that this range test can be tricky to do
4597correctly without this macro, due to rounding.)
4598
4599
4600<p>
4601This macro may evaluate its arguments more than once.
4602
4603
4604
4605
4606
4607<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4608<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4609<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4610
4611<p>
4612Calls a function (or a callable object) in protected mode.
4613
4614
4615<p>
4616Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4617in <a href="#lua_call"><code>lua_call</code></a>.
4618If there are no errors during the call,
4619<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4620However, if there is any error,
4621<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4622pushes a single value on the stack (the error object),
4623and returns an error code.
4624Like <a href="#lua_call"><code>lua_call</code></a>,
4625<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4626and its arguments from the stack.
4627
4628
4629<p>
4630If <code>msgh</code> is 0,
4631then the error object returned on the stack
4632is exactly the original error object.
4633Otherwise, <code>msgh</code> is the stack index of a
4634<em>message handler</em>.
4635(This index cannot be a pseudo-index.)
4636In case of runtime errors,
4637this handler will be called with the error object
4638and its return value will be the object
4639returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4640
4641
4642<p>
4643Typically, the message handler is used to add more debug
4644information to the error object, such as a stack traceback.
4645Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4646since by then the stack has unwound.
4647
4648
4649<p>
4650The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following status codes:
4651<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>.
4652
4653
4654
4655
4656
4657<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4658<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4659<pre>int lua_pcallk (lua_State *L,
4660                int nargs,
4661                int nresults,
4662                int msgh,
4663                lua_KContext ctx,
4664                lua_KFunction k);</pre>
4665
4666<p>
4667This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4668except that it allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
4669
4670
4671
4672
4673
4674<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4675<span class="apii">[-n, +0, <em>e</em>]</span>
4676<pre>void lua_pop (lua_State *L, int n);</pre>
4677
4678<p>
4679Pops <code>n</code> elements from the stack.
4680It is implemented as a macro over <a href="#lua_settop"><code>lua_settop</code></a>.
4681
4682
4683
4684
4685
4686<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4687<span class="apii">[-0, +1, &ndash;]</span>
4688<pre>void lua_pushboolean (lua_State *L, int b);</pre>
4689
4690<p>
4691Pushes a boolean value with value <code>b</code> onto the stack.
4692
4693
4694
4695
4696
4697<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4698<span class="apii">[-n, +1, <em>m</em>]</span>
4699<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4700
4701<p>
4702Pushes a new C&nbsp;closure onto the stack.
4703This function receives a pointer to a C&nbsp;function
4704and pushes onto the stack a Lua value of type <code>function</code> that,
4705when called, invokes the corresponding C&nbsp;function.
4706The parameter <code>n</code> tells how many upvalues this function will have
4707(see <a href="#4.2">&sect;4.2</a>).
4708
4709
4710<p>
4711Any function to be callable by Lua must
4712follow the correct protocol to receive its parameters
4713and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4714
4715
4716<p>
4717When a C&nbsp;function is created,
4718it is possible to associate some values with it,
4719the so called upvalues;
4720these upvalues are then accessible to the function whenever it is called.
4721This association is called a C&nbsp;closure (see <a href="#4.2">&sect;4.2</a>).
4722To create a C&nbsp;closure,
4723first the initial values for its upvalues must be pushed onto the stack.
4724(When there are multiple upvalues, the first value is pushed first.)
4725Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4726is called to create and push the C&nbsp;function onto the stack,
4727with the argument <code>n</code> telling how many values will be
4728associated with the function.
4729<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4730
4731
4732<p>
4733The maximum value for <code>n</code> is 255.
4734
4735
4736<p>
4737When <code>n</code> is zero,
4738this function creates a <em>light C&nbsp;function</em>,
4739which is just a pointer to the C&nbsp;function.
4740In that case, it never raises a memory error.
4741
4742
4743
4744
4745
4746<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4747<span class="apii">[-0, +1, &ndash;]</span>
4748<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4749
4750<p>
4751Pushes a C&nbsp;function onto the stack.
4752This function is equivalent to <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> with no upvalues.
4753
4754
4755
4756
4757
4758<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4759<span class="apii">[-0, +1, <em>v</em>]</span>
4760<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4761
4762<p>
4763Pushes onto the stack a formatted string
4764and returns a pointer to this string (see <a href="#4.1.3">&sect;4.1.3</a>).
4765It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4766but has two important differences.
4767First,
4768you do not have to allocate space for the result;
4769the result is a Lua string and Lua takes care of memory allocation
4770(and deallocation, through garbage collection).
4771Second,
4772the conversion specifiers are quite restricted.
4773There are no flags, widths, or precisions.
4774The conversion specifiers can only be
4775'<code>%%</code>' (inserts the character '<code>%</code>'),
4776'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4777'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4778'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4779'<code>%p</code>' (inserts a pointer),
4780'<code>%d</code>' (inserts an <code>int</code>),
4781'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4782'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4783
4784
4785<p>
4786This function may raise errors due to memory overflow
4787or an invalid conversion specifier.
4788
4789
4790
4791
4792
4793<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4794<span class="apii">[-0, +1, &ndash;]</span>
4795<pre>void lua_pushglobaltable (lua_State *L);</pre>
4796
4797<p>
4798Pushes the global environment onto the stack.
4799
4800
4801
4802
4803
4804<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4805<span class="apii">[-0, +1, &ndash;]</span>
4806<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4807
4808<p>
4809Pushes an integer with value <code>n</code> onto the stack.
4810
4811
4812
4813
4814
4815<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4816<span class="apii">[-0, +1, &ndash;]</span>
4817<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4818
4819<p>
4820Pushes a light userdata onto the stack.
4821
4822
4823<p>
4824Userdata represent C&nbsp;values in Lua.
4825A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4826It is a value (like a number):
4827you do not create it, it has no individual metatable,
4828and it is not collected (as it was never created).
4829A light userdata is equal to "any"
4830light userdata with the same C&nbsp;address.
4831
4832
4833
4834
4835
4836<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4837<span class="apii">[-0, +1, <em>m</em>]</span>
4838<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4839
4840<p>
4841This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
4842but should be used only when <code>s</code> is a literal string.
4843(Lua may optimize this case.)
4844
4845
4846
4847
4848
4849<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4850<span class="apii">[-0, +1, <em>m</em>]</span>
4851<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4852
4853<p>
4854Pushes the string pointed to by <code>s</code> with size <code>len</code>
4855onto the stack.
4856Lua will make or reuse an internal copy of the given string,
4857so the memory at <code>s</code> can be freed or reused immediately after
4858the function returns.
4859The string can contain any binary data,
4860including embedded zeros.
4861
4862
4863<p>
4864Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4865
4866
4867
4868
4869
4870<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4871<span class="apii">[-0, +1, &ndash;]</span>
4872<pre>void lua_pushnil (lua_State *L);</pre>
4873
4874<p>
4875Pushes a nil value onto the stack.
4876
4877
4878
4879
4880
4881<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4882<span class="apii">[-0, +1, &ndash;]</span>
4883<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4884
4885<p>
4886Pushes a float with value <code>n</code> onto the stack.
4887
4888
4889
4890
4891
4892<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4893<span class="apii">[-0, +1, <em>m</em>]</span>
4894<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4895
4896<p>
4897Pushes the zero-terminated string pointed to by <code>s</code>
4898onto the stack.
4899Lua will make or reuse an internal copy of the given string,
4900so the memory at <code>s</code> can be freed or reused immediately after
4901the function returns.
4902
4903
4904<p>
4905Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4906
4907
4908<p>
4909If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4910
4911
4912
4913
4914
4915<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4916<span class="apii">[-0, +1, &ndash;]</span>
4917<pre>int lua_pushthread (lua_State *L);</pre>
4918
4919<p>
4920Pushes the thread represented by <code>L</code> onto the stack.
4921Returns 1 if this thread is the main thread of its state.
4922
4923
4924
4925
4926
4927<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4928<span class="apii">[-0, +1, &ndash;]</span>
4929<pre>void lua_pushvalue (lua_State *L, int index);</pre>
4930
4931<p>
4932Pushes a copy of the element at the given index
4933onto the stack.
4934
4935
4936
4937
4938
4939<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4940<span class="apii">[-0, +1, <em>v</em>]</span>
4941<pre>const char *lua_pushvfstring (lua_State *L,
4942                              const char *fmt,
4943                              va_list argp);</pre>
4944
4945<p>
4946Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4947instead of a variable number of arguments.
4948
4949
4950
4951
4952
4953<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4954<span class="apii">[-0, +0, &ndash;]</span>
4955<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4956
4957<p>
4958Returns 1 if the two values in indices <code>index1</code> and
4959<code>index2</code> are primitively equal
4960(that is, equal without calling the <code>__eq</code> metamethod).
4961Otherwise returns&nbsp;0.
4962Also returns&nbsp;0 if any of the indices are not valid.
4963
4964
4965
4966
4967
4968<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4969<span class="apii">[-1, +1, &ndash;]</span>
4970<pre>int lua_rawget (lua_State *L, int index);</pre>
4971
4972<p>
4973Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4974(i.e., without metamethods).
4975
4976
4977
4978
4979
4980<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4981<span class="apii">[-0, +1, &ndash;]</span>
4982<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4983
4984<p>
4985Pushes onto the stack the value <code>t[n]</code>,
4986where <code>t</code> is the table at the given index.
4987The access is raw,
4988that is, it does not use the <code>__index</code> metavalue.
4989
4990
4991<p>
4992Returns the type of the pushed value.
4993
4994
4995
4996
4997
4998<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4999<span class="apii">[-0, +1, &ndash;]</span>
5000<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
5001
5002<p>
5003Pushes onto the stack the value <code>t[k]</code>,
5004where <code>t</code> is the table at the given index and
5005<code>k</code> is the pointer <code>p</code> represented as a light userdata.
5006The access is raw;
5007that is, it does not use the <code>__index</code> metavalue.
5008
5009
5010<p>
5011Returns the type of the pushed value.
5012
5013
5014
5015
5016
5017<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
5018<span class="apii">[-0, +0, &ndash;]</span>
5019<pre>lua_Unsigned lua_rawlen (lua_State *L, int index);</pre>
5020
5021<p>
5022Returns the raw "length" of the value at the given index:
5023for strings, this is the string length;
5024for tables, this is the result of the length operator ('<code>#</code>')
5025with no metamethods;
5026for userdata, this is the size of the block of memory allocated
5027for the userdata.
5028For other values, this call returns&nbsp;0.
5029
5030
5031
5032
5033
5034<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
5035<span class="apii">[-2, +0, <em>m</em>]</span>
5036<pre>void lua_rawset (lua_State *L, int index);</pre>
5037
5038<p>
5039Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
5040(i.e., without metamethods).
5041
5042
5043
5044
5045
5046<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
5047<span class="apii">[-1, +0, <em>m</em>]</span>
5048<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
5049
5050<p>
5051Does the equivalent of <code>t[i] = v</code>,
5052where <code>t</code> is the table at the given index
5053and <code>v</code> is the value on the top of the stack.
5054
5055
5056<p>
5057This function pops the value from the stack.
5058The assignment is raw,
5059that is, it does not use the <code>__newindex</code> metavalue.
5060
5061
5062
5063
5064
5065<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
5066<span class="apii">[-1, +0, <em>m</em>]</span>
5067<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
5068
5069<p>
5070Does the equivalent of <code>t[p] = v</code>,
5071where <code>t</code> is the table at the given index,
5072<code>p</code> is encoded as a light userdata,
5073and <code>v</code> is the value on the top of the stack.
5074
5075
5076<p>
5077This function pops the value from the stack.
5078The assignment is raw,
5079that is, it does not use the <code>__newindex</code> metavalue.
5080
5081
5082
5083
5084
5085<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
5086<pre>typedef const char * (*lua_Reader) (lua_State *L,
5087                                    void *data,
5088                                    size_t *size);</pre>
5089
5090<p>
5091The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
5092Every time <a href="#lua_load"><code>lua_load</code></a> needs another piece of the chunk,
5093it calls the reader,
5094passing along its <code>data</code> parameter.
5095The reader must return a pointer to a block of memory
5096with a new piece of the chunk
5097and set <code>size</code> to the block size.
5098The block must exist until the reader function is called again.
5099To signal the end of the chunk,
5100the reader must return <code>NULL</code> or set <code>size</code> to zero.
5101The reader function may return pieces of any size greater than zero.
5102
5103
5104
5105
5106
5107<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
5108<span class="apii">[-0, +0, <em>e</em>]</span>
5109<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
5110
5111<p>
5112Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>.
5113It is defined as a macro:
5114
5115<pre>
5116     #define lua_register(L,n,f) \
5117            (lua_pushcfunction(L, f), lua_setglobal(L, n))
5118</pre>
5119
5120
5121
5122
5123<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
5124<span class="apii">[-1, +0, &ndash;]</span>
5125<pre>void lua_remove (lua_State *L, int index);</pre>
5126
5127<p>
5128Removes the element at the given valid index,
5129shifting down the elements above this index to fill the gap.
5130This function cannot be called with a pseudo-index,
5131because a pseudo-index is not an actual stack position.
5132
5133
5134
5135
5136
5137<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
5138<span class="apii">[-1, +0, &ndash;]</span>
5139<pre>void lua_replace (lua_State *L, int index);</pre>
5140
5141<p>
5142Moves the top element into the given valid index
5143without shifting any element
5144(therefore replacing the value at that given index),
5145and then pops the top element.
5146
5147
5148
5149
5150
5151<hr><h3><a name="lua_resetthread"><code>lua_resetthread</code></a></h3><p>
5152<span class="apii">[-0, +?, &ndash;]</span>
5153<pre>int lua_resetthread (lua_State *L);</pre>
5154
5155<p>
5156Resets a thread, cleaning its call stack and closing all pending
5157to-be-closed variables.
5158Returns a status code:
5159<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for no errors in the thread
5160(either the original error that stopped the thread or
5161errors in closing methods),
5162or an error status otherwise.
5163In case of error,
5164leaves the error object on the top of the stack.
5165
5166
5167
5168
5169
5170<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
5171<span class="apii">[-?, +?, &ndash;]</span>
5172<pre>int lua_resume (lua_State *L, lua_State *from, int nargs,
5173                          int *nresults);</pre>
5174
5175<p>
5176Starts and resumes a coroutine in the given thread <code>L</code>.
5177
5178
5179<p>
5180To start a coroutine,
5181you push the main function plus any arguments
5182onto the empty stack of the thread.
5183then you call <a href="#lua_resume"><code>lua_resume</code></a>,
5184with <code>nargs</code> being the number of arguments.
5185This call returns when the coroutine suspends or finishes its execution.
5186When it returns,
5187<code>*nresults</code> is updated and
5188the top of the stack contains
5189the <code>*nresults</code> values passed to <a href="#lua_yield"><code>lua_yield</code></a>
5190or returned by the body function.
5191<a href="#lua_resume"><code>lua_resume</code></a> returns
5192<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
5193<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
5194without errors,
5195or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
5196In case of errors,
5197the error object is on the top of the stack.
5198
5199
5200<p>
5201To resume a coroutine,
5202you remove the <code>*nresults</code> yielded values from its stack,
5203push the values to be passed as results from <code>yield</code>,
5204and then call <a href="#lua_resume"><code>lua_resume</code></a>.
5205
5206
5207<p>
5208The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
5209If there is no such coroutine,
5210this parameter can be <code>NULL</code>.
5211
5212
5213
5214
5215
5216<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
5217<span class="apii">[-0, +0, &ndash;]</span>
5218<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
5219
5220<p>
5221Rotates the stack elements between the valid index <code>idx</code>
5222and the top of the stack.
5223The elements are rotated <code>n</code> positions in the direction of the top,
5224for a positive <code>n</code>,
5225or <code>-n</code> positions in the direction of the bottom,
5226for a negative <code>n</code>.
5227The absolute value of <code>n</code> must not be greater than the size
5228of the slice being rotated.
5229This function cannot be called with a pseudo-index,
5230because a pseudo-index is not an actual stack position.
5231
5232
5233
5234
5235
5236<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
5237<span class="apii">[-0, +0, &ndash;]</span>
5238<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
5239
5240<p>
5241Changes the allocator function of a given state to <code>f</code>
5242with user data <code>ud</code>.
5243
5244
5245
5246
5247
5248<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
5249<span class="apii">[-1, +0, <em>e</em>]</span>
5250<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
5251
5252<p>
5253Does the equivalent to <code>t[k] = v</code>,
5254where <code>t</code> is the value at the given index
5255and <code>v</code> is the value on the top of the stack.
5256
5257
5258<p>
5259This function pops the value from the stack.
5260As in Lua, this function may trigger a metamethod
5261for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5262
5263
5264
5265
5266
5267<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
5268<span class="apii">[-1, +0, <em>e</em>]</span>
5269<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
5270
5271<p>
5272Pops a value from the stack and
5273sets it as the new value of global <code>name</code>.
5274
5275
5276
5277
5278
5279<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
5280<span class="apii">[-1, +0, <em>e</em>]</span>
5281<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
5282
5283<p>
5284Does the equivalent to <code>t[n] = v</code>,
5285where <code>t</code> is the value at the given index
5286and <code>v</code> is the value on the top of the stack.
5287
5288
5289<p>
5290This function pops the value from the stack.
5291As in Lua, this function may trigger a metamethod
5292for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5293
5294
5295
5296
5297
5298<hr><h3><a name="lua_setiuservalue"><code>lua_setiuservalue</code></a></h3><p>
5299<span class="apii">[-1, +0, &ndash;]</span>
5300<pre>int lua_setiuservalue (lua_State *L, int index, int n);</pre>
5301
5302<p>
5303Pops a value from the stack and sets it as
5304the new <code>n</code>-th user value associated to the
5305full userdata at the given index.
5306Returns 0 if the userdata does not have that value.
5307
5308
5309
5310
5311
5312<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
5313<span class="apii">[-1, +0, &ndash;]</span>
5314<pre>int lua_setmetatable (lua_State *L, int index);</pre>
5315
5316<p>
5317Pops a table or <b>nil</b> from the stack and
5318sets that value as the new metatable for the value at the given index.
5319(<b>nil</b> means no metatable.)
5320
5321
5322<p>
5323(For historical reasons, this function returns an <code>int</code>,
5324which now is always 1.)
5325
5326
5327
5328
5329
5330<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
5331<span class="apii">[-2, +0, <em>e</em>]</span>
5332<pre>void lua_settable (lua_State *L, int index);</pre>
5333
5334<p>
5335Does the equivalent to <code>t[k] = v</code>,
5336where <code>t</code> is the value at the given index,
5337<code>v</code> is the value on the top of the stack,
5338and <code>k</code> is the value just below the top.
5339
5340
5341<p>
5342This function pops both the key and the value from the stack.
5343As in Lua, this function may trigger a metamethod
5344for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5345
5346
5347
5348
5349
5350<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
5351<span class="apii">[-?, +?, <em>e</em>]</span>
5352<pre>void lua_settop (lua_State *L, int index);</pre>
5353
5354<p>
5355Accepts any index, or&nbsp;0,
5356and sets the stack top to this index.
5357If the new top is greater than the old one,
5358then the new elements are filled with <b>nil</b>.
5359If <code>index</code> is&nbsp;0, then all stack elements are removed.
5360
5361
5362<p>
5363This function can run arbitrary code when removing an index
5364marked as to-be-closed from the stack.
5365
5366
5367
5368
5369
5370<hr><h3><a name="lua_setwarnf"><code>lua_setwarnf</code></a></h3><p>
5371<span class="apii">[-0, +0, &ndash;]</span>
5372<pre>void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);</pre>
5373
5374<p>
5375Sets the warning function to be used by Lua to emit warnings
5376(see <a href="#lua_WarnFunction"><code>lua_WarnFunction</code></a>).
5377The <code>ud</code> parameter sets the value <code>ud</code> passed to
5378the warning function.
5379
5380
5381
5382
5383
5384<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
5385<pre>typedef struct lua_State lua_State;</pre>
5386
5387<p>
5388An opaque structure that points to a thread and indirectly
5389(through the thread) to the whole state of a Lua interpreter.
5390The Lua library is fully reentrant:
5391it has no global variables.
5392All information about a state is accessible through this structure.
5393
5394
5395<p>
5396A pointer to this structure must be passed as the first argument to
5397every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
5398which creates a Lua state from scratch.
5399
5400
5401
5402
5403
5404<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
5405<span class="apii">[-0, +0, &ndash;]</span>
5406<pre>int lua_status (lua_State *L);</pre>
5407
5408<p>
5409Returns the status of the thread <code>L</code>.
5410
5411
5412<p>
5413The status can be <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for a normal thread,
5414an error code if the thread finished the execution
5415of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
5416or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
5417
5418
5419<p>
5420You can call functions only in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
5421You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
5422(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
5423(to resume a coroutine).
5424
5425
5426
5427
5428
5429<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
5430<span class="apii">[-0, +1, &ndash;]</span>
5431<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
5432
5433<p>
5434Converts the zero-terminated string <code>s</code> to a number,
5435pushes that number into the stack,
5436and returns the total size of the string,
5437that is, its length plus one.
5438The conversion can result in an integer or a float,
5439according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
5440The string may have leading and trailing whitespaces and a sign.
5441If the string is not a valid numeral,
5442returns 0 and pushes nothing.
5443(Note that the result can be used as a boolean,
5444true if the conversion succeeds.)
5445
5446
5447
5448
5449
5450<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
5451<span class="apii">[-0, +0, &ndash;]</span>
5452<pre>int lua_toboolean (lua_State *L, int index);</pre>
5453
5454<p>
5455Converts the Lua value at the given index to a C&nbsp;boolean
5456value (0&nbsp;or&nbsp;1).
5457Like all tests in Lua,
5458<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
5459different from <b>false</b> and <b>nil</b>;
5460otherwise it returns false.
5461(If you want to accept only actual boolean values,
5462use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
5463
5464
5465
5466
5467
5468<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
5469<span class="apii">[-0, +0, &ndash;]</span>
5470<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
5471
5472<p>
5473Converts a value at the given index to a C&nbsp;function.
5474That value must be a C&nbsp;function;
5475otherwise, returns <code>NULL</code>.
5476
5477
5478
5479
5480
5481<hr><h3><a name="lua_toclose"><code>lua_toclose</code></a></h3><p>
5482<span class="apii">[-0, +0, <em>m</em>]</span>
5483<pre>void lua_toclose (lua_State *L, int index);</pre>
5484
5485<p>
5486Marks the given index in the stack as a
5487to-be-closed slot (see <a href="#3.3.8">&sect;3.3.8</a>).
5488Like a to-be-closed variable in Lua,
5489the value at that slot in the stack will be closed
5490when it goes out of scope.
5491Here, in the context of a C function,
5492to go out of scope means that the running function returns to Lua,
5493or there is an error,
5494or the slot is removed from the stack through
5495<a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>,
5496or there is a call to <a href="#lua_closeslot"><code>lua_closeslot</code></a>.
5497A slot marked as to-be-closed should not be removed from the stack
5498by 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>,
5499unless previously deactivated by <a href="#lua_closeslot"><code>lua_closeslot</code></a>.
5500
5501
5502<p>
5503This function should not be called for an index
5504that is equal to or below an active to-be-closed slot.
5505
5506
5507<p>
5508Note that, both in case of errors and of a regular return,
5509by the time the <code>__close</code> metamethod runs,
5510the C&nbsp;stack was already unwound,
5511so that any automatic C&nbsp;variable declared in the calling function
5512(e.g., a buffer) will be out of scope.
5513
5514
5515
5516
5517
5518<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
5519<span class="apii">[-0, +0, &ndash;]</span>
5520<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
5521
5522<p>
5523Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5524
5525
5526
5527
5528
5529<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
5530<span class="apii">[-0, +0, &ndash;]</span>
5531<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
5532
5533<p>
5534Converts the Lua value at the given index
5535to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
5536The Lua value must be an integer,
5537or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
5538otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
5539
5540
5541<p>
5542If <code>isnum</code> is not <code>NULL</code>,
5543its referent is assigned a boolean value that
5544indicates whether the operation succeeded.
5545
5546
5547
5548
5549
5550<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
5551<span class="apii">[-0, +0, <em>m</em>]</span>
5552<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5553
5554<p>
5555Converts the Lua value at the given index to a C&nbsp;string.
5556If <code>len</code> is not <code>NULL</code>,
5557it sets <code>*len</code> with the string length.
5558The Lua value must be a string or a number;
5559otherwise, the function returns <code>NULL</code>.
5560If the value is a number,
5561then <code>lua_tolstring</code> also
5562<em>changes the actual value in the stack to a string</em>.
5563(This change confuses <a href="#lua_next"><code>lua_next</code></a>
5564when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5565
5566
5567<p>
5568<code>lua_tolstring</code> returns a pointer
5569to a string inside the Lua state (see <a href="#4.1.3">&sect;4.1.3</a>).
5570This string always has a zero ('<code>\0</code>')
5571after its last character (as in&nbsp;C),
5572but can contain other zeros in its body.
5573
5574
5575
5576
5577
5578<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5579<span class="apii">[-0, +0, &ndash;]</span>
5580<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5581
5582<p>
5583Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5584
5585
5586
5587
5588
5589<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5590<span class="apii">[-0, +0, &ndash;]</span>
5591<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5592
5593<p>
5594Converts the Lua value at the given index
5595to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5596The Lua value must be a number or a string convertible to a number
5597(see <a href="#3.4.3">&sect;3.4.3</a>);
5598otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5599
5600
5601<p>
5602If <code>isnum</code> is not <code>NULL</code>,
5603its referent is assigned a boolean value that
5604indicates whether the operation succeeded.
5605
5606
5607
5608
5609
5610<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5611<span class="apii">[-0, +0, &ndash;]</span>
5612<pre>const void *lua_topointer (lua_State *L, int index);</pre>
5613
5614<p>
5615Converts the value at the given index to a generic
5616C&nbsp;pointer (<code>void*</code>).
5617The value can be a userdata, a table, a thread, a string, or a function;
5618otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5619Different objects will give different pointers.
5620There is no way to convert the pointer back to its original value.
5621
5622
5623<p>
5624Typically this function is used only for hashing and debug information.
5625
5626
5627
5628
5629
5630<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5631<span class="apii">[-0, +0, <em>m</em>]</span>
5632<pre>const char *lua_tostring (lua_State *L, int index);</pre>
5633
5634<p>
5635Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5636
5637
5638
5639
5640
5641<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5642<span class="apii">[-0, +0, &ndash;]</span>
5643<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5644
5645<p>
5646Converts the value at the given index to a Lua thread
5647(represented as <code>lua_State*</code>).
5648This value must be a thread;
5649otherwise, the function returns <code>NULL</code>.
5650
5651
5652
5653
5654
5655<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5656<span class="apii">[-0, +0, &ndash;]</span>
5657<pre>void *lua_touserdata (lua_State *L, int index);</pre>
5658
5659<p>
5660If the value at the given index is a full userdata,
5661returns its memory-block address.
5662If the value is a light userdata,
5663returns its value (a pointer).
5664Otherwise, returns <code>NULL</code>.
5665
5666
5667
5668
5669
5670<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5671<span class="apii">[-0, +0, &ndash;]</span>
5672<pre>int lua_type (lua_State *L, int index);</pre>
5673
5674<p>
5675Returns the type of the value in the given valid index,
5676or <code>LUA_TNONE</code> for a non-valid but acceptable index.
5677The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5678defined in <code>lua.h</code>:
5679<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5680<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5681<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5682<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5683<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5684<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5685<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5686<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5687and
5688<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5689
5690
5691
5692
5693
5694<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5695<span class="apii">[-0, +0, &ndash;]</span>
5696<pre>const char *lua_typename (lua_State *L, int tp);</pre>
5697
5698<p>
5699Returns the name of the type encoded by the value <code>tp</code>,
5700which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5701
5702
5703
5704
5705
5706<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5707<pre>typedef ... lua_Unsigned;</pre>
5708
5709<p>
5710The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5711
5712
5713
5714
5715
5716<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5717<span class="apii">[-0, +0, &ndash;]</span>
5718<pre>int lua_upvalueindex (int i);</pre>
5719
5720<p>
5721Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5722the running function (see <a href="#4.2">&sect;4.2</a>).
5723<code>i</code> must be in the range <em>[1,256]</em>.
5724
5725
5726
5727
5728
5729<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5730<span class="apii">[-0, +0, &ndash;]</span>
5731<pre>lua_Number lua_version (lua_State *L);</pre>
5732
5733<p>
5734Returns the version number of this core.
5735
5736
5737
5738
5739
5740<hr><h3><a name="lua_WarnFunction"><code>lua_WarnFunction</code></a></h3>
5741<pre>typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);</pre>
5742
5743<p>
5744The type of warning functions, called by Lua to emit warnings.
5745The first parameter is an opaque pointer
5746set by <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>.
5747The second parameter is the warning message.
5748The third parameter is a boolean that
5749indicates whether the message is
5750to be continued by the message in the next call.
5751
5752
5753<p>
5754See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5755
5756
5757
5758
5759
5760<hr><h3><a name="lua_warning"><code>lua_warning</code></a></h3><p>
5761<span class="apii">[-0, +0, &ndash;]</span>
5762<pre>void lua_warning (lua_State *L, const char *msg, int tocont);</pre>
5763
5764<p>
5765Emits a warning with the given message.
5766A message in a call with <code>tocont</code> true should be
5767continued in another call to this function.
5768
5769
5770<p>
5771See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5772
5773
5774
5775
5776
5777<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5778<pre>typedef int (*lua_Writer) (lua_State *L,
5779                           const void* p,
5780                           size_t sz,
5781                           void* ud);</pre>
5782
5783<p>
5784The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5785Every time <a href="#lua_dump"><code>lua_dump</code></a> produces another piece of chunk,
5786it calls the writer,
5787passing along the buffer to be written (<code>p</code>),
5788its size (<code>sz</code>),
5789and the <code>ud</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5790
5791
5792<p>
5793The writer returns an error code:
57940&nbsp;means no errors;
5795any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5796calling the writer again.
5797
5798
5799
5800
5801
5802<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5803<span class="apii">[-?, +?, &ndash;]</span>
5804<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5805
5806<p>
5807Exchange values between different threads of the same state.
5808
5809
5810<p>
5811This function pops <code>n</code> values from the stack <code>from</code>,
5812and pushes them onto the stack <code>to</code>.
5813
5814
5815
5816
5817
5818<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5819<span class="apii">[-?, +?, <em>v</em>]</span>
5820<pre>int lua_yield (lua_State *L, int nresults);</pre>
5821
5822<p>
5823This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5824but it has no continuation (see <a href="#4.5">&sect;4.5</a>).
5825Therefore, when the thread resumes,
5826it continues the function that called
5827the function calling <code>lua_yield</code>.
5828To avoid surprises,
5829this function should be called only in a tail call.
5830
5831
5832
5833
5834
5835<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5836<span class="apii">[-?, +?, <em>v</em>]</span>
5837<pre>int lua_yieldk (lua_State *L,
5838                int nresults,
5839                lua_KContext ctx,
5840                lua_KFunction k);</pre>
5841
5842<p>
5843Yields a coroutine (thread).
5844
5845
5846<p>
5847When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5848the running coroutine suspends its execution,
5849and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5850The parameter <code>nresults</code> is the number of values from the stack
5851that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5852
5853
5854<p>
5855When the coroutine is resumed again,
5856Lua calls the given continuation function <code>k</code> to continue
5857the execution of the C&nbsp;function that yielded (see <a href="#4.5">&sect;4.5</a>).
5858This continuation function receives the same stack
5859from the previous function,
5860with the <code>n</code> results removed and
5861replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5862Moreover,
5863the continuation function receives the value <code>ctx</code>
5864that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5865
5866
5867<p>
5868Usually, this function does not return;
5869when the coroutine eventually resumes,
5870it continues executing the continuation function.
5871However, there is one special case,
5872which is when this function is called
5873from inside a line or a count hook (see <a href="#4.7">&sect;4.7</a>).
5874In that case, <code>lua_yieldk</code> should be called with no continuation
5875(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
5876and the hook should return immediately after the call.
5877Lua will yield and,
5878when the coroutine resumes again,
5879it will continue the normal execution
5880of the (Lua) function that triggered the hook.
5881
5882
5883<p>
5884This function can raise an error if it is called from a thread
5885with a pending C call with no continuation function
5886(what is called a <em>C-call boundary</em>),
5887or it is called from a thread that is not running inside a resume
5888(typically the main thread).
5889
5890
5891
5892
5893
5894
5895
5896<h2>4.7 &ndash; <a name="4.7">The Debug Interface</a></h2>
5897
5898<p>
5899Lua has no built-in debugging facilities.
5900Instead, it offers a special interface
5901by means of functions and <em>hooks</em>.
5902This interface allows the construction of different
5903kinds of debuggers, profilers, and other tools
5904that need "inside information" from the interpreter.
5905
5906
5907
5908<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5909<pre>typedef struct lua_Debug {
5910  int event;
5911  const char *name;           /* (n) */
5912  const char *namewhat;       /* (n) */
5913  const char *what;           /* (S) */
5914  const char *source;         /* (S) */
5915  size_t srclen;              /* (S) */
5916  int currentline;            /* (l) */
5917  int linedefined;            /* (S) */
5918  int lastlinedefined;        /* (S) */
5919  unsigned char nups;         /* (u) number of upvalues */
5920  unsigned char nparams;      /* (u) number of parameters */
5921  char isvararg;              /* (u) */
5922  char istailcall;            /* (t) */
5923  unsigned short ftransfer;   /* (r) index of first value transferred */
5924  unsigned short ntransfer;   /* (r) number of transferred values */
5925  char short_src[LUA_IDSIZE]; /* (S) */
5926  /* private part */
5927  <em>other fields</em>
5928} lua_Debug;</pre>
5929
5930<p>
5931A structure used to carry different pieces of
5932information about a function or an activation record.
5933<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5934of this structure, for later use.
5935To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5936you must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5937
5938
5939<p>
5940The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5941
5942<ul>
5943
5944<li><b><code>source</code>: </b>
5945the source of the chunk that created the function.
5946If <code>source</code> starts with a '<code>@</code>',
5947it means that the function was defined in a file where
5948the file name follows the '<code>@</code>'.
5949If <code>source</code> starts with a '<code>=</code>',
5950the remainder of its contents describes the source in a user-dependent manner.
5951Otherwise,
5952the function was defined in a string where
5953<code>source</code> is that string.
5954</li>
5955
5956<li><b><code>srclen</code>: </b>
5957The length of the string <code>source</code>.
5958</li>
5959
5960<li><b><code>short_src</code>: </b>
5961a "printable" version of <code>source</code>, to be used in error messages.
5962</li>
5963
5964<li><b><code>linedefined</code>: </b>
5965the line number where the definition of the function starts.
5966</li>
5967
5968<li><b><code>lastlinedefined</code>: </b>
5969the line number where the definition of the function ends.
5970</li>
5971
5972<li><b><code>what</code>: </b>
5973the string <code>"Lua"</code> if the function is a Lua function,
5974<code>"C"</code> if it is a C&nbsp;function,
5975<code>"main"</code> if it is the main part of a chunk.
5976</li>
5977
5978<li><b><code>currentline</code>: </b>
5979the current line where the given function is executing.
5980When no line information is available,
5981<code>currentline</code> is set to -1.
5982</li>
5983
5984<li><b><code>name</code>: </b>
5985a reasonable name for the given function.
5986Because functions in Lua are first-class values,
5987they do not have a fixed name:
5988some functions can be the value of multiple global variables,
5989while others can be stored only in a table field.
5990The <code>lua_getinfo</code> function checks how the function was
5991called to find a suitable name.
5992If it cannot find a name,
5993then <code>name</code> is set to <code>NULL</code>.
5994</li>
5995
5996<li><b><code>namewhat</code>: </b>
5997explains the <code>name</code> field.
5998The value of <code>namewhat</code> can be
5999<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
6000<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
6001according to how the function was called.
6002(Lua uses the empty string when no other option seems to apply.)
6003</li>
6004
6005<li><b><code>istailcall</code>: </b>
6006true if this function invocation was called by a tail call.
6007In this case, the caller of this level is not in the stack.
6008</li>
6009
6010<li><b><code>nups</code>: </b>
6011the number of upvalues of the function.
6012</li>
6013
6014<li><b><code>nparams</code>: </b>
6015the number of parameters of the function
6016(always 0&nbsp;for C&nbsp;functions).
6017</li>
6018
6019<li><b><code>isvararg</code>: </b>
6020true if the function is a vararg function
6021(always true for C&nbsp;functions).
6022</li>
6023
6024<li><b><code>ftransfer</code>: </b>
6025the index in the stack of the first value being "transferred",
6026that is, parameters in a call or return values in a return.
6027(The other values are in consecutive indices.)
6028Using this index, you can access and modify these values
6029through <a href="#lua_getlocal"><code>lua_getlocal</code></a> and <a href="#lua_setlocal"><code>lua_setlocal</code></a>.
6030This field is only meaningful during a
6031call hook, denoting the first parameter,
6032or a return hook, denoting the first value being returned.
6033(For call hooks, this value is always 1.)
6034</li>
6035
6036<li><b><code>ntransfer</code>: </b>
6037The number of values being transferred (see previous item).
6038(For calls of Lua functions,
6039this value is always equal to <code>nparams</code>.)
6040</li>
6041
6042</ul>
6043
6044
6045
6046
6047<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
6048<span class="apii">[-0, +0, &ndash;]</span>
6049<pre>lua_Hook lua_gethook (lua_State *L);</pre>
6050
6051<p>
6052Returns the current hook function.
6053
6054
6055
6056
6057
6058<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
6059<span class="apii">[-0, +0, &ndash;]</span>
6060<pre>int lua_gethookcount (lua_State *L);</pre>
6061
6062<p>
6063Returns the current hook count.
6064
6065
6066
6067
6068
6069<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
6070<span class="apii">[-0, +0, &ndash;]</span>
6071<pre>int lua_gethookmask (lua_State *L);</pre>
6072
6073<p>
6074Returns the current hook mask.
6075
6076
6077
6078
6079
6080<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
6081<span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
6082<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
6083
6084<p>
6085Gets information about a specific function or function invocation.
6086
6087
6088<p>
6089To get information about a function invocation,
6090the parameter <code>ar</code> must be a valid activation record that was
6091filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6092given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6093
6094
6095<p>
6096To get information about a function, you push it onto the stack
6097and start the <code>what</code> string with the character '<code>&gt;</code>'.
6098(In that case,
6099<code>lua_getinfo</code> pops the function from the top of the stack.)
6100For instance, to know in which line a function <code>f</code> was defined,
6101you can write the following code:
6102
6103<pre>
6104     lua_Debug ar;
6105     lua_getglobal(L, "f");  /* get global 'f' */
6106     lua_getinfo(L, "&gt;S", &amp;ar);
6107     printf("%d\n", ar.linedefined);
6108</pre>
6109
6110<p>
6111Each character in the string <code>what</code>
6112selects some fields of the structure <code>ar</code> to be filled or
6113a value to be pushed on the stack:
6114
6115<ul>
6116
6117<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
6118</li>
6119
6120<li><b>'<code>S</code>': </b>
6121fills in the fields <code>source</code>, <code>short_src</code>,
6122<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
6123</li>
6124
6125<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
6126</li>
6127
6128<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
6129</li>
6130
6131<li><b>'<code>u</code>': </b> fills in the fields
6132<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
6133</li>
6134
6135<li><b>'<code>f</code>': </b>
6136pushes onto the stack the function that is
6137running at the given level;
6138</li>
6139
6140<li><b>'<code>L</code>': </b>
6141pushes onto the stack a table whose indices are the
6142numbers of the lines that are valid on the function.
6143(A <em>valid line</em> is a line with some associated code,
6144that is, a line where you can put a break point.
6145Non-valid lines include empty lines and comments.)
6146
6147
6148<p>
6149If this option is given together with option '<code>f</code>',
6150its table is pushed after the function.
6151
6152
6153<p>
6154This is the only option that can raise a memory error.
6155</li>
6156
6157</ul>
6158
6159<p>
6160This function returns 0 to signal an invalid option in <code>what</code>;
6161even then the valid options are handled correctly.
6162
6163
6164
6165
6166
6167<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
6168<span class="apii">[-0, +(0|1), &ndash;]</span>
6169<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6170
6171<p>
6172Gets information about a local variable or a temporary value
6173of a given activation record or a given function.
6174
6175
6176<p>
6177In the first case,
6178the parameter <code>ar</code> must be a valid activation record that was
6179filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6180given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6181The index <code>n</code> selects which local variable to inspect;
6182see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
6183and names.
6184
6185
6186<p>
6187<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
6188and returns its name.
6189
6190
6191<p>
6192In the second case, <code>ar</code> must be <code>NULL</code> and the function
6193to be inspected must be on the top of the stack.
6194In this case, only parameters of Lua functions are visible
6195(as there is no information about what variables are active)
6196and no values are pushed onto the stack.
6197
6198
6199<p>
6200Returns <code>NULL</code> (and pushes nothing)
6201when the index is greater than
6202the number of active local variables.
6203
6204
6205
6206
6207
6208<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
6209<span class="apii">[-0, +0, &ndash;]</span>
6210<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
6211
6212<p>
6213Gets information about the interpreter runtime stack.
6214
6215
6216<p>
6217This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
6218an identification of the <em>activation record</em>
6219of the function executing at a given level.
6220Level&nbsp;0 is the current running function,
6221whereas level <em>n+1</em> is the function that has called level <em>n</em>
6222(except for tail calls, which do not count in the stack).
6223When called with a level greater than the stack depth,
6224<a href="#lua_getstack"><code>lua_getstack</code></a> returns 0;
6225otherwise it returns 1.
6226
6227
6228
6229
6230
6231<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
6232<span class="apii">[-0, +(0|1), &ndash;]</span>
6233<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
6234
6235<p>
6236Gets information about the <code>n</code>-th upvalue
6237of the closure at index <code>funcindex</code>.
6238It pushes the upvalue's value onto the stack
6239and returns its name.
6240Returns <code>NULL</code> (and pushes nothing)
6241when the index <code>n</code> is greater than the number of upvalues.
6242
6243
6244<p>
6245See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
6246
6247
6248
6249
6250
6251<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
6252<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
6253
6254<p>
6255Type for debugging hook functions.
6256
6257
6258<p>
6259Whenever a hook is called, its <code>ar</code> argument has its field
6260<code>event</code> set to the specific event that triggered the hook.
6261Lua identifies these events with the following constants:
6262<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
6263<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
6264and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
6265Moreover, for line events, the field <code>currentline</code> is also set.
6266To get the value of any other field in <code>ar</code>,
6267the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
6268
6269
6270<p>
6271For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
6272the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
6273in this case, there will be no corresponding return event.
6274
6275
6276<p>
6277While Lua is running a hook, it disables other calls to hooks.
6278Therefore, if a hook calls back Lua to execute a function or a chunk,
6279this execution occurs without any calls to hooks.
6280
6281
6282<p>
6283Hook functions cannot have continuations,
6284that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
6285<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>.
6286
6287
6288<p>
6289Hook functions can yield under the following conditions:
6290Only count and line events can yield;
6291to yield, a hook function must finish its execution
6292calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
6293(that is, with no values).
6294
6295
6296
6297
6298
6299<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
6300<span class="apii">[-0, +0, &ndash;]</span>
6301<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
6302
6303<p>
6304Sets the debugging hook function.
6305
6306
6307<p>
6308Argument <code>f</code> is the hook function.
6309<code>mask</code> specifies on which events the hook will be called:
6310it is formed by a bitwise OR of the constants
6311<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
6312<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
6313<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
6314and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
6315The <code>count</code> argument is only meaningful when the mask
6316includes <code>LUA_MASKCOUNT</code>.
6317For each event, the hook is called as explained below:
6318
6319<ul>
6320
6321<li><b>The call hook: </b> is called when the interpreter calls a function.
6322The hook is called just after Lua enters the new function.
6323</li>
6324
6325<li><b>The return hook: </b> is called when the interpreter returns from a function.
6326The hook is called just before Lua leaves the function.
6327</li>
6328
6329<li><b>The line hook: </b> is called when the interpreter is about to
6330start the execution of a new line of code,
6331or when it jumps back in the code (even to the same line).
6332This event only happens while Lua is executing a Lua function.
6333</li>
6334
6335<li><b>The count hook: </b> is called after the interpreter executes every
6336<code>count</code> instructions.
6337This event only happens while Lua is executing a Lua function.
6338</li>
6339
6340</ul>
6341
6342<p>
6343Hooks are disabled by setting <code>mask</code> to zero.
6344
6345
6346
6347
6348
6349<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
6350<span class="apii">[-(0|1), +0, &ndash;]</span>
6351<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6352
6353<p>
6354Sets the value of a local variable of a given activation record.
6355It assigns the value on the top of the stack
6356to the variable and returns its name.
6357It also pops the value from the stack.
6358
6359
6360<p>
6361Returns <code>NULL</code> (and pops nothing)
6362when the index is greater than
6363the number of active local variables.
6364
6365
6366<p>
6367Parameters <code>ar</code> and <code>n</code> are as in the function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
6368
6369
6370
6371
6372
6373<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
6374<span class="apii">[-(0|1), +0, &ndash;]</span>
6375<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
6376
6377<p>
6378Sets the value of a closure's upvalue.
6379It assigns the value on the top of the stack
6380to the upvalue and returns its name.
6381It also pops the value from the stack.
6382
6383
6384<p>
6385Returns <code>NULL</code> (and pops nothing)
6386when the index <code>n</code> is greater than the number of upvalues.
6387
6388
6389<p>
6390Parameters <code>funcindex</code> and <code>n</code> are as in
6391the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
6392
6393
6394
6395
6396
6397<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
6398<span class="apii">[-0, +0, &ndash;]</span>
6399<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
6400
6401<p>
6402Returns a unique identifier for the upvalue numbered <code>n</code>
6403from the closure at index <code>funcindex</code>.
6404
6405
6406<p>
6407These unique identifiers allow a program to check whether different
6408closures share upvalues.
6409Lua closures that share an upvalue
6410(that is, that access a same external local variable)
6411will return identical ids for those upvalue indices.
6412
6413
6414<p>
6415Parameters <code>funcindex</code> and <code>n</code> are as in
6416the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
6417but <code>n</code> cannot be greater than the number of upvalues.
6418
6419
6420
6421
6422
6423<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
6424<span class="apii">[-0, +0, &ndash;]</span>
6425<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
6426                                    int funcindex2, int n2);</pre>
6427
6428<p>
6429Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
6430refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
6431
6432
6433
6434
6435
6436
6437
6438<h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
6439
6440
6441
6442<p>
6443
6444The <em>auxiliary library</em> provides several convenient functions
6445to interface C with Lua.
6446While the basic API provides the primitive functions for all
6447interactions between C and Lua,
6448the auxiliary library provides higher-level functions for some
6449common tasks.
6450
6451
6452<p>
6453All functions and types from the auxiliary library
6454are defined in header file <code>lauxlib.h</code> and
6455have a prefix <code>luaL_</code>.
6456
6457
6458<p>
6459All functions in the auxiliary library are built on
6460top of the basic API,
6461and so they provide nothing that cannot be done with that API.
6462Nevertheless, the use of the auxiliary library ensures
6463more consistency to your code.
6464
6465
6466<p>
6467Several functions in the auxiliary library use internally some
6468extra stack slots.
6469When a function in the auxiliary library uses less than five slots,
6470it does not check the stack size;
6471it simply assumes that there are enough slots.
6472
6473
6474<p>
6475Several functions in the auxiliary library are used to
6476check C&nbsp;function arguments.
6477Because the error message is formatted for arguments
6478(e.g., "<code>bad argument #1</code>"),
6479you should not use these functions for other stack values.
6480
6481
6482<p>
6483Functions called <code>luaL_check*</code>
6484always raise an error if the check is not satisfied.
6485
6486
6487
6488
6489
6490<h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
6491
6492<p>
6493Here we list all functions and types from the auxiliary library
6494in alphabetical order.
6495
6496
6497
6498<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
6499<span class="apii">[-?, +?, <em>m</em>]</span>
6500<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
6501
6502<p>
6503Adds the byte <code>c</code> to the buffer <code>B</code>
6504(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6505
6506
6507
6508
6509
6510<hr><h3><a name="luaL_addgsub"><code>luaL_addgsub</code></a></h3><p>
6511<span class="apii">[-0, +0, <em>m</em>]</span>
6512<pre>const void luaL_addgsub (luaL_Buffer *B, const char *s,
6513                         const char *p, const char *r);</pre>
6514
6515<p>
6516Adds a copy of the string <code>s</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>),
6517replacing any occurrence of the string <code>p</code>
6518with the string <code>r</code>.
6519
6520
6521
6522
6523
6524<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
6525<span class="apii">[-?, +?, <em>m</em>]</span>
6526<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
6527
6528<p>
6529Adds the string pointed to by <code>s</code> with length <code>l</code> to
6530the buffer <code>B</code>
6531(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6532The string can contain embedded zeros.
6533
6534
6535
6536
6537
6538<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
6539<span class="apii">[-?, +?, &ndash;]</span>
6540<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
6541
6542<p>
6543Adds to the buffer <code>B</code>
6544a string of length <code>n</code> previously copied to the
6545buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
6546
6547
6548
6549
6550
6551<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
6552<span class="apii">[-?, +?, <em>m</em>]</span>
6553<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
6554
6555<p>
6556Adds the zero-terminated string pointed to by <code>s</code>
6557to the buffer <code>B</code>
6558(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6559
6560
6561
6562
6563
6564<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
6565<span class="apii">[-1, +?, <em>m</em>]</span>
6566<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
6567
6568<p>
6569Adds the value on the top of the stack
6570to the buffer <code>B</code>
6571(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6572Pops the value.
6573
6574
6575<p>
6576This is the only function on string buffers that can (and must)
6577be called with an extra element on the stack,
6578which is the value to be added to the buffer.
6579
6580
6581
6582
6583
6584<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
6585<span class="apii">[-0, +0, <em>v</em>]</span>
6586<pre>void luaL_argcheck (lua_State *L,
6587                    int cond,
6588                    int arg,
6589                    const char *extramsg);</pre>
6590
6591<p>
6592Checks whether <code>cond</code> is true.
6593If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
6594
6595
6596
6597
6598
6599<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
6600<span class="apii">[-0, +0, <em>v</em>]</span>
6601<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
6602
6603<p>
6604Raises an error reporting a problem with argument <code>arg</code>
6605of the C&nbsp;function that called it,
6606using a standard message
6607that includes <code>extramsg</code> as a comment:
6608
6609<pre>
6610     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
6611</pre><p>
6612This function never returns.
6613
6614
6615
6616
6617
6618<hr><h3><a name="luaL_argexpected"><code>luaL_argexpected</code></a></h3><p>
6619<span class="apii">[-0, +0, <em>v</em>]</span>
6620<pre>void luaL_argexpected (lua_State *L,
6621                       int cond,
6622                       int arg,
6623                       const char *tname);</pre>
6624
6625<p>
6626Checks whether <code>cond</code> is true.
6627If it is not, raises an error about the type of the argument <code>arg</code>
6628with a standard message (see <a href="#luaL_typeerror"><code>luaL_typeerror</code></a>).
6629
6630
6631
6632
6633
6634<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
6635<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
6636
6637<p>
6638Type for a <em>string buffer</em>.
6639
6640
6641<p>
6642A string buffer allows C&nbsp;code to build Lua strings piecemeal.
6643Its pattern of use is as follows:
6644
6645<ul>
6646
6647<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6648
6649<li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6650
6651<li>
6652Then add string pieces to the buffer calling any of
6653the <code>luaL_add*</code> functions.
6654</li>
6655
6656<li>
6657Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6658This call leaves the final string on the top of the stack.
6659</li>
6660
6661</ul>
6662
6663<p>
6664If you know beforehand the maximum size of the resulting string,
6665you can use the buffer like this:
6666
6667<ul>
6668
6669<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6670
6671<li>Then initialize it and preallocate a space of
6672size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6673
6674<li>Then produce the string into that space.</li>
6675
6676<li>
6677Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6678where <code>sz</code> is the total size of the resulting string
6679copied into that space (which may be less than or
6680equal to the preallocated size).
6681</li>
6682
6683</ul>
6684
6685<p>
6686During its normal operation,
6687a string buffer uses a variable number of stack slots.
6688So, while using a buffer, you cannot assume that you know where
6689the top of the stack is.
6690You can use the stack between successive calls to buffer operations
6691as long as that use is balanced;
6692that is,
6693when you call a buffer operation,
6694the stack is at the same level
6695it was immediately after the previous buffer operation.
6696(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6697After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>,
6698the stack is back to its level when the buffer was initialized,
6699plus the final string on its top.
6700
6701
6702
6703
6704
6705<hr><h3><a name="luaL_buffaddr"><code>luaL_buffaddr</code></a></h3><p>
6706<span class="apii">[-0, +0, &ndash;]</span>
6707<pre>char *luaL_buffaddr (luaL_Buffer *B);</pre>
6708
6709<p>
6710Returns the address of the current content of buffer <code>B</code>
6711(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6712Note that any addition to the buffer may invalidate this address.
6713
6714
6715
6716
6717
6718<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6719<span class="apii">[-0, +0, &ndash;]</span>
6720<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6721
6722<p>
6723Initializes a buffer <code>B</code>
6724(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6725This function does not allocate any space;
6726the buffer must be declared as a variable.
6727
6728
6729
6730
6731
6732<hr><h3><a name="luaL_bufflen"><code>luaL_bufflen</code></a></h3><p>
6733<span class="apii">[-0, +0, &ndash;]</span>
6734<pre>size_t luaL_bufflen (luaL_Buffer *B);</pre>
6735
6736<p>
6737Returns the length of the current content of buffer <code>B</code>
6738(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6739
6740
6741
6742
6743
6744<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6745<span class="apii">[-?, +?, <em>m</em>]</span>
6746<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6747
6748<p>
6749Equivalent to the sequence
6750<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6751
6752
6753
6754
6755
6756<hr><h3><a name="luaL_buffsub"><code>luaL_buffsub</code></a></h3><p>
6757<span class="apii">[-0, +0, &ndash;]</span>
6758<pre>void luaL_buffsub (luaL_Buffer *B, int n);</pre>
6759
6760<p>
6761Removes <code>n</code> bytes from the the buffer <code>B</code>
6762(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6763The buffer must have at least that many bytes.
6764
6765
6766
6767
6768
6769<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6770<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6771<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6772
6773<p>
6774Calls a metamethod.
6775
6776
6777<p>
6778If the object at index <code>obj</code> has a metatable and this
6779metatable has a field <code>e</code>,
6780this function calls this field passing the object as its only argument.
6781In this case this function returns true and pushes onto the
6782stack the value returned by the call.
6783If there is no metatable or no metamethod,
6784this function returns false without pushing any value on the stack.
6785
6786
6787
6788
6789
6790<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6791<span class="apii">[-0, +0, <em>v</em>]</span>
6792<pre>void luaL_checkany (lua_State *L, int arg);</pre>
6793
6794<p>
6795Checks whether the function has an argument
6796of any type (including <b>nil</b>) at position <code>arg</code>.
6797
6798
6799
6800
6801
6802<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6803<span class="apii">[-0, +0, <em>v</em>]</span>
6804<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6805
6806<p>
6807Checks whether the function argument <code>arg</code> is an integer
6808(or can be converted to an integer)
6809and returns this integer.
6810
6811
6812
6813
6814
6815<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6816<span class="apii">[-0, +0, <em>v</em>]</span>
6817<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6818
6819<p>
6820Checks whether the function argument <code>arg</code> is a string
6821and returns this string;
6822if <code>l</code> is not <code>NULL</code> fills its referent
6823with the string's length.
6824
6825
6826<p>
6827This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6828so all conversions and caveats of that function apply here.
6829
6830
6831
6832
6833
6834<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6835<span class="apii">[-0, +0, <em>v</em>]</span>
6836<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6837
6838<p>
6839Checks whether the function argument <code>arg</code> is a number
6840and returns this number converted to a <code>lua_Number</code>.
6841
6842
6843
6844
6845
6846<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6847<span class="apii">[-0, +0, <em>v</em>]</span>
6848<pre>int luaL_checkoption (lua_State *L,
6849                      int arg,
6850                      const char *def,
6851                      const char *const lst[]);</pre>
6852
6853<p>
6854Checks whether the function argument <code>arg</code> is a string and
6855searches for this string in the array <code>lst</code>
6856(which must be NULL-terminated).
6857Returns the index in the array where the string was found.
6858Raises an error if the argument is not a string or
6859if the string cannot be found.
6860
6861
6862<p>
6863If <code>def</code> is not <code>NULL</code>,
6864the function uses <code>def</code> as a default value when
6865there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6866
6867
6868<p>
6869This is a useful function for mapping strings to C&nbsp;enums.
6870(The usual convention in Lua libraries is
6871to use strings instead of numbers to select options.)
6872
6873
6874
6875
6876
6877<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6878<span class="apii">[-0, +0, <em>v</em>]</span>
6879<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6880
6881<p>
6882Grows the stack size to <code>top + sz</code> elements,
6883raising an error if the stack cannot grow to that size.
6884<code>msg</code> is an additional text to go into the error message
6885(or <code>NULL</code> for no additional text).
6886
6887
6888
6889
6890
6891<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6892<span class="apii">[-0, +0, <em>v</em>]</span>
6893<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6894
6895<p>
6896Checks whether the function argument <code>arg</code> is a string
6897and returns this string.
6898
6899
6900<p>
6901This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6902so all conversions and caveats of that function apply here.
6903
6904
6905
6906
6907
6908<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6909<span class="apii">[-0, +0, <em>v</em>]</span>
6910<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6911
6912<p>
6913Checks whether the function argument <code>arg</code> has type <code>t</code>.
6914See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6915
6916
6917
6918
6919
6920<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6921<span class="apii">[-0, +0, <em>v</em>]</span>
6922<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6923
6924<p>
6925Checks whether the function argument <code>arg</code> is a userdata
6926of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6927returns the userdata's memory-block address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6928
6929
6930
6931
6932
6933<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6934<span class="apii">[-0, +0, <em>v</em>]</span>
6935<pre>void luaL_checkversion (lua_State *L);</pre>
6936
6937<p>
6938Checks whether the code making the call and the Lua library being called
6939are using the same version of Lua and the same numeric types.
6940
6941
6942
6943
6944
6945<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6946<span class="apii">[-0, +?, <em>m</em>]</span>
6947<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6948
6949<p>
6950Loads and runs the given file.
6951It is defined as the following macro:
6952
6953<pre>
6954     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6955</pre><p>
6956It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6957or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6958
6959
6960
6961
6962
6963<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6964<span class="apii">[-0, +?, &ndash;]</span>
6965<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6966
6967<p>
6968Loads and runs the given string.
6969It is defined as the following macro:
6970
6971<pre>
6972     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6973</pre><p>
6974It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6975or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6976
6977
6978
6979
6980
6981<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6982<span class="apii">[-0, +0, <em>v</em>]</span>
6983<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6984
6985<p>
6986Raises an error.
6987The error message format is given by <code>fmt</code>
6988plus any extra arguments,
6989following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6990It also adds at the beginning of the message the file name and
6991the line number where the error occurred,
6992if this information is available.
6993
6994
6995<p>
6996This function never returns,
6997but it is an idiom to use it in C&nbsp;functions
6998as <code>return luaL_error(<em>args</em>)</code>.
6999
7000
7001
7002
7003
7004<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
7005<span class="apii">[-0, +3, <em>m</em>]</span>
7006<pre>int luaL_execresult (lua_State *L, int stat);</pre>
7007
7008<p>
7009This function produces the return values for
7010process-related functions in the standard library
7011(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
7012
7013
7014
7015
7016
7017<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
7018<span class="apii">[-0, +(1|3), <em>m</em>]</span>
7019<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
7020
7021<p>
7022This function produces the return values for
7023file-related functions in the standard library
7024(<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.).
7025
7026
7027
7028
7029
7030<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
7031<span class="apii">[-0, +(0|1), <em>m</em>]</span>
7032<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
7033
7034<p>
7035Pushes onto the stack the field <code>e</code> from the metatable
7036of the object at index <code>obj</code> and returns the type of the pushed value.
7037If the object does not have a metatable,
7038or if the metatable does not have this field,
7039pushes nothing and returns <code>LUA_TNIL</code>.
7040
7041
7042
7043
7044
7045<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
7046<span class="apii">[-0, +1, <em>m</em>]</span>
7047<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
7048
7049<p>
7050Pushes onto the stack the metatable associated with the name <code>tname</code>
7051in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>),
7052or <b>nil</b> if there is no metatable associated with that name.
7053Returns the type of the pushed value.
7054
7055
7056
7057
7058
7059<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
7060<span class="apii">[-0, +1, <em>e</em>]</span>
7061<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
7062
7063<p>
7064Ensures that the value <code>t[fname]</code>,
7065where <code>t</code> is the value at index <code>idx</code>,
7066is a table,
7067and pushes that table onto the stack.
7068Returns true if it finds a previous table there
7069and false if it creates a new table.
7070
7071
7072
7073
7074
7075<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
7076<span class="apii">[-0, +1, <em>m</em>]</span>
7077<pre>const char *luaL_gsub (lua_State *L,
7078                       const char *s,
7079                       const char *p,
7080                       const char *r);</pre>
7081
7082<p>
7083Creates a copy of string <code>s</code>,
7084replacing any occurrence of the string <code>p</code>
7085with the string <code>r</code>.
7086Pushes the resulting string on the stack and returns it.
7087
7088
7089
7090
7091
7092<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
7093<span class="apii">[-0, +0, <em>e</em>]</span>
7094<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
7095
7096<p>
7097Returns the "length" of the value at the given index
7098as a number;
7099it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
7100Raises an error if the result of the operation is not an integer.
7101(This case can only happen through metamethods.)
7102
7103
7104
7105
7106
7107<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
7108<span class="apii">[-0, +1, &ndash;]</span>
7109<pre>int luaL_loadbuffer (lua_State *L,
7110                     const char *buff,
7111                     size_t sz,
7112                     const char *name);</pre>
7113
7114<p>
7115Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
7116
7117
7118
7119
7120
7121<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
7122<span class="apii">[-0, +1, &ndash;]</span>
7123<pre>int luaL_loadbufferx (lua_State *L,
7124                      const char *buff,
7125                      size_t sz,
7126                      const char *name,
7127                      const char *mode);</pre>
7128
7129<p>
7130Loads a buffer as a Lua chunk.
7131This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
7132buffer pointed to by <code>buff</code> with size <code>sz</code>.
7133
7134
7135<p>
7136This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7137<code>name</code> is the chunk name,
7138used for debug information and error messages.
7139The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7140
7141
7142
7143
7144
7145<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
7146<span class="apii">[-0, +1, <em>m</em>]</span>
7147<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
7148
7149<p>
7150Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
7151
7152
7153
7154
7155
7156<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
7157<span class="apii">[-0, +1, <em>m</em>]</span>
7158<pre>int luaL_loadfilex (lua_State *L, const char *filename,
7159                                            const char *mode);</pre>
7160
7161<p>
7162Loads a file as a Lua chunk.
7163This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
7164named <code>filename</code>.
7165If <code>filename</code> is <code>NULL</code>,
7166then it loads from the standard input.
7167The first line in the file is ignored if it starts with a <code>#</code>.
7168
7169
7170<p>
7171The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7172
7173
7174<p>
7175This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>
7176or <a href="#pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> for file-related errors.
7177
7178
7179<p>
7180As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7181it does not run it.
7182
7183
7184
7185
7186
7187<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
7188<span class="apii">[-0, +1, &ndash;]</span>
7189<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
7190
7191<p>
7192Loads a string as a Lua chunk.
7193This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
7194the zero-terminated string <code>s</code>.
7195
7196
7197<p>
7198This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7199
7200
7201<p>
7202Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7203it does not run it.
7204
7205
7206
7207
7208
7209<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
7210<span class="apii">[-0, +1, <em>m</em>]</span>
7211<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
7212
7213<p>
7214Creates a new table and registers there
7215the functions in the list <code>l</code>.
7216
7217
7218<p>
7219It is implemented as the following macro:
7220
7221<pre>
7222     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
7223</pre><p>
7224The array <code>l</code> must be the actual array,
7225not a pointer to it.
7226
7227
7228
7229
7230
7231<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
7232<span class="apii">[-0, +1, <em>m</em>]</span>
7233<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
7234
7235<p>
7236Creates a new table with a size optimized
7237to store all entries in the array <code>l</code>
7238(but does not actually store them).
7239It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
7240(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
7241
7242
7243<p>
7244It is implemented as a macro.
7245The array <code>l</code> must be the actual array,
7246not a pointer to it.
7247
7248
7249
7250
7251
7252<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
7253<span class="apii">[-0, +1, <em>m</em>]</span>
7254<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
7255
7256<p>
7257If the registry already has the key <code>tname</code>,
7258returns 0.
7259Otherwise,
7260creates a new table to be used as a metatable for userdata,
7261adds to this new table the pair <code>__name = tname</code>,
7262adds to the registry the pair <code>[tname] = new table</code>,
7263and returns 1.
7264
7265
7266<p>
7267In both cases,
7268the function pushes onto the stack the final value associated
7269with <code>tname</code> in the registry.
7270
7271
7272
7273
7274
7275<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
7276<span class="apii">[-0, +0, &ndash;]</span>
7277<pre>lua_State *luaL_newstate (void);</pre>
7278
7279<p>
7280Creates a new Lua state.
7281It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
7282allocator based on the standard&nbsp;C allocation functions
7283and then sets a warning function and a panic function (see <a href="#4.4">&sect;4.4</a>)
7284that print messages to the standard error output.
7285
7286
7287<p>
7288Returns the new state,
7289or <code>NULL</code> if there is a memory allocation error.
7290
7291
7292
7293
7294
7295<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
7296<span class="apii">[-0, +0, <em>e</em>]</span>
7297<pre>void luaL_openlibs (lua_State *L);</pre>
7298
7299<p>
7300Opens all standard Lua libraries into the given state.
7301
7302
7303
7304
7305
7306<hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
7307<span class="apii">[-0, +0, &ndash;]</span>
7308<pre>T luaL_opt (L, func, arg, dflt);</pre>
7309
7310<p>
7311This macro is defined as follows:
7312
7313<pre>
7314     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
7315</pre><p>
7316In words, if the argument <code>arg</code> is nil or absent,
7317the macro results in the default <code>dflt</code>.
7318Otherwise, it results in the result of calling <code>func</code>
7319with the state <code>L</code> and the argument index <code>arg</code> as
7320arguments.
7321Note that it evaluates the expression <code>dflt</code> only if needed.
7322
7323
7324
7325
7326
7327<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
7328<span class="apii">[-0, +0, <em>v</em>]</span>
7329<pre>lua_Integer luaL_optinteger (lua_State *L,
7330                             int arg,
7331                             lua_Integer d);</pre>
7332
7333<p>
7334If the function argument <code>arg</code> is an integer
7335(or it is convertible to an integer),
7336returns this integer.
7337If this argument is absent or is <b>nil</b>,
7338returns <code>d</code>.
7339Otherwise, raises an error.
7340
7341
7342
7343
7344
7345<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
7346<span class="apii">[-0, +0, <em>v</em>]</span>
7347<pre>const char *luaL_optlstring (lua_State *L,
7348                             int arg,
7349                             const char *d,
7350                             size_t *l);</pre>
7351
7352<p>
7353If the function argument <code>arg</code> is a string,
7354returns this string.
7355If this argument is absent or is <b>nil</b>,
7356returns <code>d</code>.
7357Otherwise, raises an error.
7358
7359
7360<p>
7361If <code>l</code> is not <code>NULL</code>,
7362fills its referent with the result's length.
7363If the result is <code>NULL</code>
7364(only possible when returning <code>d</code> and <code>d == NULL</code>),
7365its length is considered zero.
7366
7367
7368<p>
7369This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
7370so all conversions and caveats of that function apply here.
7371
7372
7373
7374
7375
7376<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
7377<span class="apii">[-0, +0, <em>v</em>]</span>
7378<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
7379
7380<p>
7381If the function argument <code>arg</code> is a number,
7382returns this number as a <code>lua_Number</code>.
7383If this argument is absent or is <b>nil</b>,
7384returns <code>d</code>.
7385Otherwise, raises an error.
7386
7387
7388
7389
7390
7391<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
7392<span class="apii">[-0, +0, <em>v</em>]</span>
7393<pre>const char *luaL_optstring (lua_State *L,
7394                            int arg,
7395                            const char *d);</pre>
7396
7397<p>
7398If the function argument <code>arg</code> is a string,
7399returns this string.
7400If this argument is absent or is <b>nil</b>,
7401returns <code>d</code>.
7402Otherwise, raises an error.
7403
7404
7405
7406
7407
7408<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
7409<span class="apii">[-?, +?, <em>m</em>]</span>
7410<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
7411
7412<p>
7413Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
7414with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
7415
7416
7417
7418
7419
7420<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
7421<span class="apii">[-?, +?, <em>m</em>]</span>
7422<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
7423
7424<p>
7425Returns an address to a space of size <code>sz</code>
7426where you can copy a string to be added to buffer <code>B</code>
7427(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
7428After copying the string into this space you must call
7429<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
7430it to the buffer.
7431
7432
7433
7434
7435
7436<hr><h3><a name="luaL_pushfail"><code>luaL_pushfail</code></a></h3><p>
7437<span class="apii">[-0, +1, &ndash;]</span>
7438<pre>void luaL_pushfail (lua_State *L);</pre>
7439
7440<p>
7441Pushes the <b>fail</b> value onto the stack (see <a href="#6">&sect;6</a>).
7442
7443
7444
7445
7446
7447<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
7448<span class="apii">[-?, +1, <em>m</em>]</span>
7449<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
7450
7451<p>
7452Finishes the use of buffer <code>B</code> leaving the final string on
7453the top of the stack.
7454
7455
7456
7457
7458
7459<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
7460<span class="apii">[-?, +1, <em>m</em>]</span>
7461<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
7462
7463<p>
7464Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
7465
7466
7467
7468
7469
7470<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
7471<span class="apii">[-1, +0, <em>m</em>]</span>
7472<pre>int luaL_ref (lua_State *L, int t);</pre>
7473
7474<p>
7475Creates and returns a <em>reference</em>,
7476in the table at index <code>t</code>,
7477for the object on the top of the stack (and pops the object).
7478
7479
7480<p>
7481A reference is a unique integer key.
7482As long as you do not manually add integer keys into the table <code>t</code>,
7483<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
7484You can retrieve an object referred by the reference <code>r</code>
7485by calling <code>lua_rawgeti(L, t, r)</code>.
7486The function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference.
7487
7488
7489<p>
7490If the object on the top of the stack is <b>nil</b>,
7491<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
7492The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
7493from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
7494
7495
7496
7497
7498
7499<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
7500<pre>typedef struct luaL_Reg {
7501  const char *name;
7502  lua_CFunction func;
7503} luaL_Reg;</pre>
7504
7505<p>
7506Type for arrays of functions to be registered by
7507<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
7508<code>name</code> is the function name and <code>func</code> is a pointer to
7509the function.
7510Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
7511in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
7512
7513
7514
7515
7516
7517<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
7518<span class="apii">[-0, +1, <em>e</em>]</span>
7519<pre>void luaL_requiref (lua_State *L, const char *modname,
7520                    lua_CFunction openf, int glb);</pre>
7521
7522<p>
7523If <code>package.loaded[modname]</code> is not true,
7524calls the function <code>openf</code> with the string <code>modname</code> as an argument
7525and sets the call result to <code>package.loaded[modname]</code>,
7526as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
7527
7528
7529<p>
7530If <code>glb</code> is true,
7531also stores the module into the global <code>modname</code>.
7532
7533
7534<p>
7535Leaves a copy of the module on the stack.
7536
7537
7538
7539
7540
7541<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
7542<span class="apii">[-nup, +0, <em>m</em>]</span>
7543<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
7544
7545<p>
7546Registers all functions in the array <code>l</code>
7547(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
7548(below optional upvalues, see next).
7549
7550
7551<p>
7552When <code>nup</code> is not zero,
7553all functions are created with <code>nup</code> upvalues,
7554initialized with copies of the <code>nup</code> values
7555previously pushed on the stack
7556on top of the library table.
7557These values are popped from the stack after the registration.
7558
7559
7560
7561
7562
7563<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
7564<span class="apii">[-0, +0, &ndash;]</span>
7565<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
7566
7567<p>
7568Sets the metatable of the object on the top of the stack
7569as the metatable associated with name <code>tname</code>
7570in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7571
7572
7573
7574
7575
7576<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
7577<pre>typedef struct luaL_Stream {
7578  FILE *f;
7579  lua_CFunction closef;
7580} luaL_Stream;</pre>
7581
7582<p>
7583The standard representation for file handles
7584used by the standard I/O library.
7585
7586
7587<p>
7588A file handle is implemented as a full userdata,
7589with a metatable called <code>LUA_FILEHANDLE</code>
7590(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
7591The metatable is created by the I/O library
7592(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7593
7594
7595<p>
7596This userdata must start with the structure <code>luaL_Stream</code>;
7597it can contain other data after this initial structure.
7598The field <code>f</code> points to the corresponding C stream
7599(or it can be <code>NULL</code> to indicate an incompletely created handle).
7600The field <code>closef</code> points to a Lua function
7601that will be called to close the stream
7602when the handle is closed or collected;
7603this function receives the file handle as its sole argument and
7604must return either a true value, in case of success,
7605or a false value plus an error message, in case of error.
7606Once Lua calls this field,
7607it changes the field value to <code>NULL</code>
7608to signal that the handle is closed.
7609
7610
7611
7612
7613
7614<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
7615<span class="apii">[-0, +0, <em>m</em>]</span>
7616<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
7617
7618<p>
7619This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
7620except that, when the test fails,
7621it returns <code>NULL</code> instead of raising an error.
7622
7623
7624
7625
7626
7627<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
7628<span class="apii">[-0, +1, <em>e</em>]</span>
7629<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
7630
7631<p>
7632Converts any Lua value at the given index to a C&nbsp;string
7633in a reasonable format.
7634The resulting string is pushed onto the stack and also
7635returned by the function (see <a href="#4.1.3">&sect;4.1.3</a>).
7636If <code>len</code> is not <code>NULL</code>,
7637the function also sets <code>*len</code> with the string length.
7638
7639
7640<p>
7641If the value has a metatable with a <code>__tostring</code> field,
7642then <code>luaL_tolstring</code> calls the corresponding metamethod
7643with the value as argument,
7644and uses the result of the call as its result.
7645
7646
7647
7648
7649
7650<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
7651<span class="apii">[-0, +1, <em>m</em>]</span>
7652<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
7653                     int level);</pre>
7654
7655<p>
7656Creates and pushes a traceback of the stack <code>L1</code>.
7657If <code>msg</code> is not <code>NULL</code>, it is appended
7658at the beginning of the traceback.
7659The <code>level</code> parameter tells at which level
7660to start the traceback.
7661
7662
7663
7664
7665
7666<hr><h3><a name="luaL_typeerror"><code>luaL_typeerror</code></a></h3><p>
7667<span class="apii">[-0, +0, <em>v</em>]</span>
7668<pre>const char *luaL_typeerror (lua_State *L,
7669                                      int arg,
7670                                      const char *tname);</pre>
7671
7672<p>
7673Raises a type error for the argument <code>arg</code>
7674of the C&nbsp;function that called it,
7675using a standard message;
7676<code>tname</code> is a "name" for the expected type.
7677This function never returns.
7678
7679
7680
7681
7682
7683<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
7684<span class="apii">[-0, +0, &ndash;]</span>
7685<pre>const char *luaL_typename (lua_State *L, int index);</pre>
7686
7687<p>
7688Returns the name of the type of the value at the given index.
7689
7690
7691
7692
7693
7694<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
7695<span class="apii">[-0, +0, &ndash;]</span>
7696<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
7697
7698<p>
7699Releases the reference <code>ref</code> from the table at index <code>t</code>
7700(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
7701The entry is removed from the table,
7702so that the referred object can be collected.
7703The reference <code>ref</code> is also freed to be used again.
7704
7705
7706<p>
7707If <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>,
7708<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
7709
7710
7711
7712
7713
7714<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
7715<span class="apii">[-0, +1, <em>m</em>]</span>
7716<pre>void luaL_where (lua_State *L, int lvl);</pre>
7717
7718<p>
7719Pushes onto the stack a string identifying the current position
7720of the control at level <code>lvl</code> in the call stack.
7721Typically this string has the following format:
7722
7723<pre>
7724     <em>chunkname</em>:<em>currentline</em>:
7725</pre><p>
7726Level&nbsp;0 is the running function,
7727level&nbsp;1 is the function that called the running function,
7728etc.
7729
7730
7731<p>
7732This function is used to build a prefix for error messages.
7733
7734
7735
7736
7737
7738
7739
7740<h1>6 &ndash; <a name="6">The Standard Libraries</a></h1>
7741
7742
7743
7744<p>
7745The standard Lua libraries provide useful functions
7746that are implemented in&nbsp;C through the C&nbsp;API.
7747Some of these functions provide essential services to the language
7748(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7749others provide access to outside services (e.g., I/O);
7750and others could be implemented in Lua itself,
7751but that for different reasons
7752deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7753
7754
7755<p>
7756All libraries are implemented through the official C&nbsp;API
7757and are provided as separate C&nbsp;modules.
7758Unless otherwise noted,
7759these library functions do not adjust its number of arguments
7760to its expected parameters.
7761For instance, a function documented as <code>foo(arg)</code>
7762should not be called without an argument.
7763
7764
7765<p>
7766The notation <b>fail</b> means a false value representing
7767some kind of failure.
7768(Currently, <b>fail</b> is equal to <b>nil</b>,
7769but that may change in future versions.
7770The recommendation is to always test the success of these functions
7771with <code>(not status)</code>, instead of <code>(status == nil)</code>.)
7772
7773
7774<p>
7775Currently, Lua has the following standard libraries:
7776
7777<ul>
7778
7779<li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7780
7781<li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7782
7783<li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7784
7785<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7786
7787<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7788
7789<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7790
7791<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7792
7793<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7794
7795<li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7796
7797<li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7798
7799</ul><p>
7800Except for the basic and the package libraries,
7801each library provides all its functions as fields of a global table
7802or as methods of its objects.
7803
7804
7805<p>
7806To have access to these libraries,
7807the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7808which opens all standard libraries.
7809Alternatively,
7810the host program can open them individually by using
7811<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7812<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7813<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7814<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7815<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7816<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF-8 library),
7817<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7818<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7819<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7820<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7821and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7822These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7823
7824
7825
7826
7827
7828<h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7829
7830<p>
7831The basic library provides core functions to Lua.
7832If you do not include this library in your application,
7833you should check carefully whether you need to provide
7834implementations for some of its facilities.
7835
7836
7837<p>
7838<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7839
7840
7841<p>
7842Raises an error if
7843the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7844otherwise, returns all its arguments.
7845In case of error,
7846<code>message</code> is the error object;
7847when absent, it defaults to "<code>assertion failed!</code>"
7848
7849
7850
7851
7852<p>
7853<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7854
7855
7856<p>
7857This function is a generic interface to the garbage collector.
7858It performs different functions according to its first argument, <code>opt</code>:
7859
7860<ul>
7861
7862<li><b>"<code>collect</code>": </b>
7863Performs a full garbage-collection cycle.
7864This is the default option.
7865</li>
7866
7867<li><b>"<code>stop</code>": </b>
7868Stops automatic execution of the garbage collector.
7869The collector will run only when explicitly invoked,
7870until a call to restart it.
7871</li>
7872
7873<li><b>"<code>restart</code>": </b>
7874Restarts automatic execution of the garbage collector.
7875</li>
7876
7877<li><b>"<code>count</code>": </b>
7878Returns the total memory in use by Lua in Kbytes.
7879The value has a fractional part,
7880so that it multiplied by 1024
7881gives the exact number of bytes in use by Lua.
7882</li>
7883
7884<li><b>"<code>step</code>": </b>
7885Performs a garbage-collection step.
7886The step "size" is controlled by <code>arg</code>.
7887With a zero value,
7888the collector will perform one basic (indivisible) step.
7889For non-zero values,
7890the collector will perform as if that amount of memory
7891(in Kbytes) had been allocated by Lua.
7892Returns <b>true</b> if the step finished a collection cycle.
7893</li>
7894
7895<li><b>"<code>isrunning</code>": </b>
7896Returns a boolean that tells whether the collector is running
7897(i.e., not stopped).
7898</li>
7899
7900<li><b>"<code>incremental</code>": </b>
7901Change the collector mode to incremental.
7902This option can be followed by three numbers:
7903the garbage-collector pause,
7904the step multiplier,
7905and the step size (see <a href="#2.5.1">&sect;2.5.1</a>).
7906A zero means to not change that value.
7907</li>
7908
7909<li><b>"<code>generational</code>": </b>
7910Change the collector mode to generational.
7911This option can be followed by two numbers:
7912the garbage-collector minor multiplier
7913and the major multiplier (see <a href="#2.5.2">&sect;2.5.2</a>).
7914A zero means to not change that value.
7915</li>
7916
7917</ul><p>
7918See <a href="#2.5">&sect;2.5</a> for more details about garbage collection
7919and some of these options.
7920
7921
7922
7923
7924<p>
7925<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7926Opens the named file and executes its content as a Lua chunk.
7927When called without arguments,
7928<code>dofile</code> executes the content of the standard input (<code>stdin</code>).
7929Returns all values returned by the chunk.
7930In case of errors, <code>dofile</code> propagates the error
7931to its caller.
7932(That is, <code>dofile</code> does not run in protected mode.)
7933
7934
7935
7936
7937<p>
7938<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7939Raises an error (see <a href="#2.3">&sect;2.3</a>) with @{message} as the error object.
7940This function never returns.
7941
7942
7943<p>
7944Usually, <code>error</code> adds some information about the error position
7945at the beginning of the message, if the message is a string.
7946The <code>level</code> argument specifies how to get the error position.
7947With level&nbsp;1 (the default), the error position is where the
7948<code>error</code> function was called.
7949Level&nbsp;2 points the error to where the function
7950that called <code>error</code> was called; and so on.
7951Passing a level&nbsp;0 avoids the addition of error position information
7952to the message.
7953
7954
7955
7956
7957<p>
7958<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7959A global variable (not a function) that
7960holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7961Lua itself does not use this variable;
7962changing its value does not affect any environment,
7963nor vice versa.
7964
7965
7966
7967
7968<p>
7969<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7970
7971
7972<p>
7973If <code>object</code> does not have a metatable, returns <b>nil</b>.
7974Otherwise,
7975if the object's metatable has a <code>__metatable</code> field,
7976returns the associated value.
7977Otherwise, returns the metatable of the given object.
7978
7979
7980
7981
7982<p>
7983<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7984
7985
7986<p>
7987Returns three values (an iterator function, the table <code>t</code>, and 0)
7988so that the construction
7989
7990<pre>
7991     for i,v in ipairs(t) do <em>body</em> end
7992</pre><p>
7993will iterate over the key&ndash;value pairs
7994(<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7995up to the first absent index.
7996
7997
7998
7999
8000<p>
8001<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
8002
8003
8004<p>
8005Loads a chunk.
8006
8007
8008<p>
8009If <code>chunk</code> is a string, the chunk is this string.
8010If <code>chunk</code> is a function,
8011<code>load</code> calls it repeatedly to get the chunk pieces.
8012Each call to <code>chunk</code> must return a string that concatenates
8013with previous results.
8014A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
8015
8016
8017<p>
8018If there are no syntactic errors,
8019<code>load</code> returns the compiled chunk as a function;
8020otherwise, it returns <b>fail</b> plus the error message.
8021
8022
8023<p>
8024When you load a main chunk,
8025the resulting function will always have exactly one upvalue,
8026the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
8027However,
8028when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
8029the resulting function can have an arbitrary number of upvalues,
8030and there is no guarantee that its first upvalue will be
8031the <code>_ENV</code> variable.
8032(A non-main function may not even have an <code>_ENV</code> upvalue.)
8033
8034
8035<p>
8036Regardless, if the resulting function has any upvalues,
8037its first upvalue is set to the value of <code>env</code>,
8038if that parameter is given,
8039or to the value of the global environment.
8040Other upvalues are initialized with <b>nil</b>.
8041All upvalues are fresh, that is,
8042they are not shared with any other function.
8043
8044
8045<p>
8046<code>chunkname</code> is used as the name of the chunk for error messages
8047and debug information (see <a href="#4.7">&sect;4.7</a>).
8048When absent,
8049it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
8050or to "<code>=(load)</code>" otherwise.
8051
8052
8053<p>
8054The string <code>mode</code> controls whether the chunk can be text or binary
8055(that is, a precompiled chunk).
8056It may be the string "<code>b</code>" (only binary chunks),
8057"<code>t</code>" (only text chunks),
8058or "<code>bt</code>" (both binary and text).
8059The default is "<code>bt</code>".
8060
8061
8062<p>
8063It is safe to load malformed binary chunks;
8064<code>load</code> signals an appropriate error.
8065However,
8066Lua does not check the consistency of the code inside binary chunks;
8067running maliciously crafted bytecode can crash the interpreter.
8068
8069
8070
8071
8072<p>
8073<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
8074
8075
8076<p>
8077Similar to <a href="#pdf-load"><code>load</code></a>,
8078but gets the chunk from file <code>filename</code>
8079or from the standard input,
8080if no file name is given.
8081
8082
8083
8084
8085<p>
8086<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
8087
8088
8089<p>
8090Allows a program to traverse all fields of a table.
8091Its first argument is a table and its second argument
8092is an index in this table.
8093A call to <code>next</code> returns the next index of the table
8094and its associated value.
8095When called with <b>nil</b> as its second argument,
8096<code>next</code> returns an initial index
8097and its associated value.
8098When called with the last index,
8099or with <b>nil</b> in an empty table,
8100<code>next</code> returns <b>nil</b>.
8101If the second argument is absent, then it is interpreted as <b>nil</b>.
8102In particular,
8103you can use <code>next(t)</code> to check whether a table is empty.
8104
8105
8106<p>
8107The order in which the indices are enumerated is not specified,
8108<em>even for numeric indices</em>.
8109(To traverse a table in numerical order,
8110use a numerical <b>for</b>.)
8111
8112
8113<p>
8114The behavior of <code>next</code> is undefined if,
8115during the traversal,
8116you assign any value to a non-existent field in the table.
8117You may however modify existing fields.
8118In particular, you may set existing fields to nil.
8119
8120
8121
8122
8123<p>
8124<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
8125
8126
8127<p>
8128If <code>t</code> has a metamethod <code>__pairs</code>,
8129calls it with <code>t</code> as argument and returns the first three
8130results from the call.
8131
8132
8133<p>
8134Otherwise,
8135returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
8136so that the construction
8137
8138<pre>
8139     for k,v in pairs(t) do <em>body</em> end
8140</pre><p>
8141will iterate over all key&ndash;value pairs of table <code>t</code>.
8142
8143
8144<p>
8145See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
8146the table during its traversal.
8147
8148
8149
8150
8151<p>
8152<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
8153
8154
8155<p>
8156Calls the function <code>f</code> with
8157the given arguments in <em>protected mode</em>.
8158This means that any error inside&nbsp;<code>f</code> is not propagated;
8159instead, <code>pcall</code> catches the error
8160and returns a status code.
8161Its first result is the status code (a boolean),
8162which is true if the call succeeds without errors.
8163In such case, <code>pcall</code> also returns all results from the call,
8164after this first result.
8165In case of any error, <code>pcall</code> returns <b>false</b> plus the error object.
8166Note that errors caught by <code>pcall</code> do not call a message handler.
8167
8168
8169
8170
8171<p>
8172<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
8173Receives any number of arguments
8174and prints their values to <code>stdout</code>,
8175converting each argument to a string
8176following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8177
8178
8179<p>
8180The function <code>print</code> is not intended for formatted output,
8181but only as a quick way to show a value,
8182for instance for debugging.
8183For complete control over the output,
8184use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
8185
8186
8187
8188
8189<p>
8190<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
8191Checks whether <code>v1</code> is equal to <code>v2</code>,
8192without invoking the <code>__eq</code> metamethod.
8193Returns a boolean.
8194
8195
8196
8197
8198<p>
8199<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
8200Gets the real value of <code>table[index]</code>,
8201without using the <code>__index</code> metavalue.
8202<code>table</code> must be a table;
8203<code>index</code> may be any value.
8204
8205
8206
8207
8208<p>
8209<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
8210Returns the length of the object <code>v</code>,
8211which must be a table or a string,
8212without invoking the <code>__len</code> metamethod.
8213Returns an integer.
8214
8215
8216
8217
8218<p>
8219<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
8220Sets the real value of <code>table[index]</code> to <code>value</code>,
8221without using the <code>__newindex</code> metavalue.
8222<code>table</code> must be a table,
8223<code>index</code> any value different from <b>nil</b> and NaN,
8224and <code>value</code> any Lua value.
8225
8226
8227<p>
8228This function returns <code>table</code>.
8229
8230
8231
8232
8233<p>
8234<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
8235
8236
8237<p>
8238If <code>index</code> is a number,
8239returns all arguments after argument number <code>index</code>;
8240a negative number indexes from the end (-1 is the last argument).
8241Otherwise, <code>index</code> must be the string <code>"#"</code>,
8242and <code>select</code> returns the total number of extra arguments it received.
8243
8244
8245
8246
8247<p>
8248<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
8249
8250
8251<p>
8252Sets the metatable for the given table.
8253If <code>metatable</code> is <b>nil</b>,
8254removes the metatable of the given table.
8255If the original metatable has a <code>__metatable</code> field,
8256raises an error.
8257
8258
8259<p>
8260This function returns <code>table</code>.
8261
8262
8263<p>
8264To change the metatable of other types from Lua code,
8265you must use the debug library (<a href="#6.10">&sect;6.10</a>).
8266
8267
8268
8269
8270<p>
8271<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
8272
8273
8274<p>
8275When called with no <code>base</code>,
8276<code>tonumber</code> tries to convert its argument to a number.
8277If the argument is already a number or
8278a string convertible to a number,
8279then <code>tonumber</code> returns this number;
8280otherwise, it returns <b>fail</b>.
8281
8282
8283<p>
8284The conversion of strings can result in integers or floats,
8285according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
8286The string may have leading and trailing spaces and a sign.
8287
8288
8289<p>
8290When called with <code>base</code>,
8291then <code>e</code> must be a string to be interpreted as
8292an integer numeral in that base.
8293The base may be any integer between 2 and 36, inclusive.
8294In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
8295represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
8296with '<code>Z</code>' representing 35.
8297If the string <code>e</code> is not a valid numeral in the given base,
8298the function returns <b>fail</b>.
8299
8300
8301
8302
8303<p>
8304<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
8305
8306
8307<p>
8308Receives a value of any type and
8309converts it to a string in a human-readable format.
8310
8311
8312<p>
8313If the metatable of <code>v</code> has a <code>__tostring</code> field,
8314then <code>tostring</code> calls the corresponding value
8315with <code>v</code> as argument,
8316and uses the result of the call as its result.
8317Otherwise, if the metatable of <code>v</code> has a <code>__name</code> field
8318with a string value,
8319<code>tostring</code> may use that string in its final result.
8320
8321
8322<p>
8323For complete control of how numbers are converted,
8324use <a href="#pdf-string.format"><code>string.format</code></a>.
8325
8326
8327
8328
8329<p>
8330<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
8331
8332
8333<p>
8334Returns the type of its only argument, coded as a string.
8335The possible results of this function are
8336"<code>nil</code>" (a string, not the value <b>nil</b>),
8337"<code>number</code>",
8338"<code>string</code>",
8339"<code>boolean</code>",
8340"<code>table</code>",
8341"<code>function</code>",
8342"<code>thread</code>",
8343and "<code>userdata</code>".
8344
8345
8346
8347
8348<p>
8349<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
8350
8351
8352<p>
8353A global variable (not a function) that
8354holds a string containing the running Lua version.
8355The current value of this variable is "<code>Lua 5.4</code>".
8356
8357
8358
8359
8360<p>
8361<hr><h3><a name="pdf-warn"><code>warn (msg1, &middot;&middot;&middot;)</code></a></h3>
8362
8363
8364<p>
8365Emits a warning with a message composed by the concatenation
8366of all its arguments (which should be strings).
8367
8368
8369<p>
8370By convention,
8371a one-piece message starting with '<code>@</code>'
8372is intended to be a <em>control message</em>,
8373which is a message to the warning system itself.
8374In particular, the standard warning function in Lua
8375recognizes the control messages "<code>@off</code>",
8376to stop the emission of warnings,
8377and "<code>@on</code>", to (re)start the emission;
8378it ignores unknown control messages.
8379
8380
8381
8382
8383<p>
8384<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
8385
8386
8387<p>
8388This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
8389except that it sets a new message handler <code>msgh</code>.
8390
8391
8392
8393
8394
8395
8396
8397<h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
8398
8399<p>
8400This library comprises the operations to manipulate coroutines,
8401which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
8402See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
8403
8404
8405<p>
8406<hr><h3><a name="pdf-coroutine.close"><code>coroutine.close (co)</code></a></h3>
8407
8408
8409<p>
8410Closes coroutine <code>co</code>,
8411that is,
8412closes all its pending to-be-closed variables
8413and puts the coroutine in a dead state.
8414The given coroutine must be dead or suspended.
8415In case of error
8416(either the original error that stopped the coroutine or
8417errors in closing methods),
8418returns <b>false</b> plus the error object;
8419otherwise returns <b>true</b>.
8420
8421
8422
8423
8424<p>
8425<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
8426
8427
8428<p>
8429Creates a new coroutine, with body <code>f</code>.
8430<code>f</code> must be a function.
8431Returns this new coroutine,
8432an object with type <code>"thread"</code>.
8433
8434
8435
8436
8437<p>
8438<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ([co])</code></a></h3>
8439
8440
8441<p>
8442Returns true when the coroutine <code>co</code> can yield.
8443The default for <code>co</code> is the running coroutine.
8444
8445
8446<p>
8447A coroutine is yieldable if it is not the main thread and
8448it is not inside a non-yieldable C&nbsp;function.
8449
8450
8451
8452
8453<p>
8454<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
8455
8456
8457<p>
8458Starts or continues the execution of coroutine <code>co</code>.
8459The first time you resume a coroutine,
8460it starts running its body.
8461The values <code>val1</code>, ... are passed
8462as the arguments to the body function.
8463If the coroutine has yielded,
8464<code>resume</code> restarts it;
8465the values <code>val1</code>, ... are passed
8466as the results from the yield.
8467
8468
8469<p>
8470If the coroutine runs without any errors,
8471<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
8472(when the coroutine yields) or any values returned by the body function
8473(when the coroutine terminates).
8474If there is any error,
8475<code>resume</code> returns <b>false</b> plus the error message.
8476
8477
8478
8479
8480<p>
8481<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
8482
8483
8484<p>
8485Returns the running coroutine plus a boolean,
8486true when the running coroutine is the main one.
8487
8488
8489
8490
8491<p>
8492<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
8493
8494
8495<p>
8496Returns the status of the coroutine <code>co</code>, as a string:
8497<code>"running"</code>,
8498if the coroutine is running
8499(that is, it is the one that called <code>status</code>);
8500<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
8501or if it has not started running yet;
8502<code>"normal"</code> if the coroutine is active but not running
8503(that is, it has resumed another coroutine);
8504and <code>"dead"</code> if the coroutine has finished its body function,
8505or if it has stopped with an error.
8506
8507
8508
8509
8510<p>
8511<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
8512
8513
8514<p>
8515Creates a new coroutine, with body <code>f</code>;
8516<code>f</code> must be a function.
8517Returns a function that resumes the coroutine each time it is called.
8518Any arguments passed to this function behave as the
8519extra arguments to <code>resume</code>.
8520The function returns the same values returned by <code>resume</code>,
8521except the first boolean.
8522In case of error,
8523the function closes the coroutine and propagates the error.
8524
8525
8526
8527
8528<p>
8529<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
8530
8531
8532<p>
8533Suspends the execution of the calling coroutine.
8534Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
8535
8536
8537
8538
8539
8540
8541
8542<h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
8543
8544<p>
8545The package library provides basic
8546facilities for loading modules in Lua.
8547It exports one function directly in the global environment:
8548<a href="#pdf-require"><code>require</code></a>.
8549Everything else is exported in the table <a name="pdf-package"><code>package</code></a>.
8550
8551
8552<p>
8553<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
8554
8555
8556<p>
8557Loads the given module.
8558The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
8559to determine whether <code>modname</code> is already loaded.
8560If it is, then <code>require</code> returns the value stored
8561at <code>package.loaded[modname]</code>.
8562(The absence of a second result in this case
8563signals that this call did not have to load the module.)
8564Otherwise, it tries to find a <em>loader</em> for the module.
8565
8566
8567<p>
8568To find a loader,
8569<code>require</code> is guided by the table <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8570Each item in this table is a search function,
8571that searches for the module in a particular way.
8572By changing this table,
8573we can change how <code>require</code> looks for a module.
8574The following explanation is based on the default configuration
8575for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8576
8577
8578<p>
8579First <code>require</code> queries <code>package.preload[modname]</code>.
8580If it has a value,
8581this value (which must be a function) is the loader.
8582Otherwise <code>require</code> searches for a Lua loader using the
8583path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
8584If that also fails, it searches for a C&nbsp;loader using the
8585path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8586If that also fails,
8587it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
8588
8589
8590<p>
8591Once a loader is found,
8592<code>require</code> calls the loader with two arguments:
8593<code>modname</code> and an extra value,
8594a <em>loader data</em>,
8595also returned by the searcher.
8596The loader data can be any value useful to the module;
8597for the default searchers,
8598it indicates where the loader was found.
8599(For instance, if the loader came from a file,
8600this extra value is the file path.)
8601If the loader returns any non-nil value,
8602<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
8603If the loader does not return a non-nil value and
8604has not assigned any value to <code>package.loaded[modname]</code>,
8605then <code>require</code> assigns <b>true</b> to this entry.
8606In any case, <code>require</code> returns the
8607final value of <code>package.loaded[modname]</code>.
8608Besides that value, <code>require</code> also returns as a second result
8609the loader data returned by the searcher,
8610which indicates how <code>require</code> found the module.
8611
8612
8613<p>
8614If there is any error loading or running the module,
8615or if it cannot find any loader for the module,
8616then <code>require</code> raises an error.
8617
8618
8619
8620
8621<p>
8622<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
8623
8624
8625<p>
8626A string describing some compile-time configurations for packages.
8627This string is a sequence of lines:
8628
8629<ul>
8630
8631<li>The first line is the directory separator string.
8632Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
8633
8634<li>The second line is the character that separates templates in a path.
8635Default is '<code>;</code>'.</li>
8636
8637<li>The third line is the string that marks the
8638substitution points in a template.
8639Default is '<code>?</code>'.</li>
8640
8641<li>The fourth line is a string that, in a path in Windows,
8642is replaced by the executable's directory.
8643Default is '<code>!</code>'.</li>
8644
8645<li>The fifth line is a mark to ignore all text after it
8646when building the <code>luaopen_</code> function name.
8647Default is '<code>-</code>'.</li>
8648
8649</ul>
8650
8651
8652
8653<p>
8654<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
8655
8656
8657<p>
8658A string with the path used by <a href="#pdf-require"><code>require</code></a>
8659to search for a C&nbsp;loader.
8660
8661
8662<p>
8663Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
8664it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
8665using the environment variable <a name="pdf-LUA_CPATH_5_4"><code>LUA_CPATH_5_4</code></a>,
8666or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
8667or a default path defined in <code>luaconf.h</code>.
8668
8669
8670
8671
8672<p>
8673<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
8674
8675
8676<p>
8677A table used by <a href="#pdf-require"><code>require</code></a> to control which
8678modules are already loaded.
8679When you require a module <code>modname</code> and
8680<code>package.loaded[modname]</code> is not false,
8681<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
8682
8683
8684<p>
8685This variable is only a reference to the real table;
8686assignments to this variable do not change the
8687table used by <a href="#pdf-require"><code>require</code></a>.
8688
8689
8690
8691
8692<p>
8693<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
8694
8695
8696<p>
8697Dynamically links the host program with the C&nbsp;library <code>libname</code>.
8698
8699
8700<p>
8701If <code>funcname</code> is "<code>*</code>",
8702then it only links with the library,
8703making the symbols exported by the library
8704available to other dynamically linked libraries.
8705Otherwise,
8706it looks for a function <code>funcname</code> inside the library
8707and returns this function as a C&nbsp;function.
8708So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
8709(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8710
8711
8712<p>
8713This is a low-level function.
8714It completely bypasses the package and module system.
8715Unlike <a href="#pdf-require"><code>require</code></a>,
8716it does not perform any path searching and
8717does not automatically adds extensions.
8718<code>libname</code> must be the complete file name of the C&nbsp;library,
8719including if necessary a path and an extension.
8720<code>funcname</code> must be the exact name exported by the C&nbsp;library
8721(which may depend on the C&nbsp;compiler and linker used).
8722
8723
8724<p>
8725This function is not supported by Standard&nbsp;C.
8726As such, it is only available on some platforms
8727(Windows, Linux, Mac OS X, Solaris, BSD,
8728plus other Unix systems that support the <code>dlfcn</code> standard).
8729
8730
8731<p>
8732This function is inherently insecure,
8733as it allows Lua to call any function in any readable dynamic
8734library in the system.
8735(Lua calls any function assuming the function
8736has a proper prototype and respects a proper protocol
8737(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8738Therefore,
8739calling an arbitrary function in an arbitrary dynamic library
8740more often than not results in an access violation.)
8741
8742
8743
8744
8745<p>
8746<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
8747
8748
8749<p>
8750A string with the path used by <a href="#pdf-require"><code>require</code></a>
8751to search for a Lua loader.
8752
8753
8754<p>
8755At start-up, Lua initializes this variable with
8756the value of the environment variable <a name="pdf-LUA_PATH_5_4"><code>LUA_PATH_5_4</code></a> or
8757the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
8758with a default path defined in <code>luaconf.h</code>,
8759if those environment variables are not defined.
8760A "<code>;;</code>" in the value of the environment variable
8761is replaced by the default path.
8762
8763
8764
8765
8766<p>
8767<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
8768
8769
8770<p>
8771A table to store loaders for specific modules
8772(see <a href="#pdf-require"><code>require</code></a>).
8773
8774
8775<p>
8776This variable is only a reference to the real table;
8777assignments to this variable do not change the
8778table used by <a href="#pdf-require"><code>require</code></a>.
8779
8780
8781
8782
8783<p>
8784<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
8785
8786
8787<p>
8788A table used by <a href="#pdf-require"><code>require</code></a> to control how to find modules.
8789
8790
8791<p>
8792Each entry in this table is a <em>searcher function</em>.
8793When looking for a module,
8794<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
8795with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
8796sole argument.
8797If the searcher finds the module,
8798it returns another function, the module <em>loader</em>,
8799plus an extra value, a <em>loader data</em>,
8800that will be passed to that loader and
8801returned as a second result by <a href="#pdf-require"><code>require</code></a>.
8802If it cannot find the module,
8803it returns a string explaining why
8804(or <b>nil</b> if it has nothing to say).
8805
8806
8807<p>
8808Lua initializes this table with four searcher functions.
8809
8810
8811<p>
8812The first searcher simply looks for a loader in the
8813<a href="#pdf-package.preload"><code>package.preload</code></a> table.
8814
8815
8816<p>
8817The second searcher looks for a loader as a Lua library,
8818using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
8819The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8820
8821
8822<p>
8823The third searcher looks for a loader as a C&nbsp;library,
8824using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8825Again,
8826the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8827For instance,
8828if the C&nbsp;path is the string
8829
8830<pre>
8831     "./?.so;./?.dll;/usr/local/?/init.so"
8832</pre><p>
8833the searcher for module <code>foo</code>
8834will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
8835and <code>/usr/local/foo/init.so</code>, in that order.
8836Once it finds a C&nbsp;library,
8837this searcher first uses a dynamic link facility to link the
8838application with the library.
8839Then it tries to find a C&nbsp;function inside the library to
8840be used as the loader.
8841The name of this C&nbsp;function is the string "<code>luaopen_</code>"
8842concatenated with a copy of the module name where each dot
8843is replaced by an underscore.
8844Moreover, if the module name has a hyphen,
8845its suffix after (and including) the first hyphen is removed.
8846For instance, if the module name is <code>a.b.c-v2.1</code>,
8847the function name will be <code>luaopen_a_b_c</code>.
8848
8849
8850<p>
8851The fourth searcher tries an <em>all-in-one loader</em>.
8852It searches the C&nbsp;path for a library for
8853the root name of the given module.
8854For instance, when requiring <code>a.b.c</code>,
8855it will search for a C&nbsp;library for <code>a</code>.
8856If found, it looks into it for an open function for
8857the submodule;
8858in our example, that would be <code>luaopen_a_b_c</code>.
8859With this facility, a package can pack several C&nbsp;submodules
8860into one single library,
8861with each submodule keeping its original open function.
8862
8863
8864<p>
8865All searchers except the first one (preload) return as the extra value
8866the file path where the module was found,
8867as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8868The first searcher always returns the string "<code>:preload:</code>".
8869
8870
8871<p>
8872Searchers should raise no errors and have no side effects in Lua.
8873(They may have side effects in C,
8874for instance by linking the application with a library.)
8875
8876
8877
8878
8879<p>
8880<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8881
8882
8883<p>
8884Searches for the given <code>name</code> in the given <code>path</code>.
8885
8886
8887<p>
8888A path is a string containing a sequence of
8889<em>templates</em> separated by semicolons.
8890For each template,
8891the function replaces each interrogation mark (if any)
8892in the template with a copy of <code>name</code>
8893wherein all occurrences of <code>sep</code>
8894(a dot, by default)
8895were replaced by <code>rep</code>
8896(the system's directory separator, by default),
8897and then tries to open the resulting file name.
8898
8899
8900<p>
8901For instance, if the path is the string
8902
8903<pre>
8904     "./?.lua;./?.lc;/usr/local/?/init.lua"
8905</pre><p>
8906the search for the name <code>foo.a</code>
8907will try to open the files
8908<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8909<code>/usr/local/foo/a/init.lua</code>, in that order.
8910
8911
8912<p>
8913Returns the resulting name of the first file that it can
8914open in read mode (after closing the file),
8915or <b>fail</b> plus an error message if none succeeds.
8916(This error message lists all file names it tried to open.)
8917
8918
8919
8920
8921
8922
8923
8924<h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8925
8926
8927
8928<p>
8929This library provides generic functions for string manipulation,
8930such as finding and extracting substrings, and pattern matching.
8931When indexing a string in Lua, the first character is at position&nbsp;1
8932(not at&nbsp;0, as in C).
8933Indices are allowed to be negative and are interpreted as indexing backwards,
8934from the end of the string.
8935Thus, the last character is at position -1, and so on.
8936
8937
8938<p>
8939The string library provides all its functions inside the table
8940<a name="pdf-string"><code>string</code></a>.
8941It also sets a metatable for strings
8942where the <code>__index</code> field points to the <code>string</code> table.
8943Therefore, you can use the string functions in object-oriented style.
8944For instance, <code>string.byte(s,i)</code>
8945can be written as <code>s:byte(i)</code>.
8946
8947
8948<p>
8949The string library assumes one-byte character encodings.
8950
8951
8952<p>
8953<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8954Returns the internal numeric codes of the characters <code>s[i]</code>,
8955<code>s[i+1]</code>, ..., <code>s[j]</code>.
8956The default value for <code>i</code> is&nbsp;1;
8957the default value for <code>j</code> is&nbsp;<code>i</code>.
8958These indices are corrected
8959following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8960
8961
8962<p>
8963Numeric codes are not necessarily portable across platforms.
8964
8965
8966
8967
8968<p>
8969<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8970Receives zero or more integers.
8971Returns a string with length equal to the number of arguments,
8972in which each character has the internal numeric code equal
8973to its corresponding argument.
8974
8975
8976<p>
8977Numeric codes are not necessarily portable across platforms.
8978
8979
8980
8981
8982<p>
8983<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8984
8985
8986<p>
8987Returns a string containing a binary representation
8988(a <em>binary chunk</em>)
8989of the given function,
8990so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8991a copy of the function (but with new upvalues).
8992If <code>strip</code> is a true value,
8993the binary representation may not include all debug information
8994about the function,
8995to save space.
8996
8997
8998<p>
8999Functions with upvalues have only their number of upvalues saved.
9000When (re)loaded,
9001those upvalues receive fresh instances.
9002(See the <a href="#pdf-load"><code>load</code></a> function for details about
9003how these upvalues are initialized.
9004You can use the debug library to serialize
9005and reload the upvalues of a function
9006in a way adequate to your needs.)
9007
9008
9009
9010
9011<p>
9012<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
9013
9014
9015<p>
9016Looks for the first match of
9017<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9018If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
9019where this occurrence starts and ends;
9020otherwise, it returns <b>fail</b>.
9021A third, optional numeric argument <code>init</code> specifies
9022where to start the search;
9023its default value is&nbsp;1 and can be negative.
9024A value of <b>true</b> as a fourth, optional argument <code>plain</code>
9025turns off the pattern matching facilities,
9026so the function does a plain "find substring" operation,
9027with no characters in <code>pattern</code> being considered magic.
9028
9029
9030<p>
9031If the pattern has captures,
9032then in a successful match
9033the captured values are also returned,
9034after the two indices.
9035
9036
9037
9038
9039<p>
9040<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
9041
9042
9043<p>
9044Returns a formatted version of its variable number of arguments
9045following the description given in its first argument,
9046which must be a string.
9047The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
9048The only differences are that the conversion specifiers and modifiers
9049<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, and <code>n</code> are not supported
9050and that there is an extra specifier, <code>q</code>.
9051
9052
9053<p>
9054The specifier <code>q</code> formats booleans, nil, numbers, and strings
9055in a way that the result is a valid constant in Lua source code.
9056Booleans and nil are written in the obvious way
9057(<code>true</code>, <code>false</code>, <code>nil</code>).
9058Floats are written in hexadecimal,
9059to preserve full precision.
9060A string is written between double quotes,
9061using escape sequences when necessary to ensure that
9062it can safely be read back by the Lua interpreter.
9063For instance, the call
9064
9065<pre>
9066     string.format('%q', 'a string with "quotes" and \n new line')
9067</pre><p>
9068may produce the string:
9069
9070<pre>
9071     "a string with \"quotes\" and \
9072      new line"
9073</pre><p>
9074This specifier does not support modifiers (flags, width, length).
9075
9076
9077<p>
9078The conversion specifiers
9079<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
9080<code>G</code>, and <code>g</code> all expect a number as argument.
9081The specifiers <code>c</code>, <code>d</code>,
9082<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
9083expect an integer.
9084When Lua is compiled with a C89 compiler,
9085the specifiers <code>A</code> and <code>a</code> (hexadecimal floats)
9086do not support modifiers.
9087
9088
9089<p>
9090The specifier <code>s</code> expects a string;
9091if its argument is not a string,
9092it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
9093If the specifier has any modifier,
9094the corresponding string argument should not contain embedded zeros.
9095
9096
9097<p>
9098The specifier <code>p</code> formats the pointer
9099returned by <a href="#lua_topointer"><code>lua_topointer</code></a>.
9100That gives a unique string identifier for tables, userdata,
9101threads, strings, and functions.
9102For other values (numbers, nil, booleans),
9103this specifier results in a string representing
9104the pointer <code>NULL</code>.
9105
9106
9107
9108
9109<p>
9110<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern [, init])</code></a></h3>
9111Returns an iterator function that,
9112each time it is called,
9113returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
9114over the string <code>s</code>.
9115If <code>pattern</code> specifies no captures,
9116then the whole match is produced in each call.
9117A third, optional numeric argument <code>init</code> specifies
9118where to start the search;
9119its default value is&nbsp;1 and can be negative.
9120
9121
9122<p>
9123As an example, the following loop
9124will iterate over all the words from string <code>s</code>,
9125printing one per line:
9126
9127<pre>
9128     s = "hello world from Lua"
9129     for w in string.gmatch(s, "%a+") do
9130       print(w)
9131     end
9132</pre><p>
9133The next example collects all pairs <code>key=value</code> from the
9134given string into a table:
9135
9136<pre>
9137     t = {}
9138     s = "from=world, to=Lua"
9139     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
9140       t[k] = v
9141     end
9142</pre>
9143
9144<p>
9145For this function, a caret '<code>^</code>' at the start of a pattern does not
9146work as an anchor, as this would prevent the iteration.
9147
9148
9149
9150
9151<p>
9152<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
9153Returns a copy of <code>s</code>
9154in which all (or the first <code>n</code>, if given)
9155occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
9156replaced by a replacement string specified by <code>repl</code>,
9157which can be a string, a table, or a function.
9158<code>gsub</code> also returns, as its second value,
9159the total number of matches that occurred.
9160The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
9161
9162
9163<p>
9164If <code>repl</code> is a string, then its value is used for replacement.
9165The character&nbsp;<code>%</code> works as an escape character:
9166any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
9167with <em>d</em> between 1 and 9,
9168stands for the value of the <em>d</em>-th captured substring;
9169the sequence <code>%0</code> stands for the whole match;
9170the sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
9171
9172
9173<p>
9174If <code>repl</code> is a table, then the table is queried for every match,
9175using the first capture as the key.
9176
9177
9178<p>
9179If <code>repl</code> is a function, then this function is called every time a
9180match occurs, with all captured substrings passed as arguments,
9181in order.
9182
9183
9184<p>
9185In any case,
9186if the pattern specifies no captures,
9187then it behaves as if the whole pattern was inside a capture.
9188
9189
9190<p>
9191If the value returned by the table query or by the function call
9192is a string or a number,
9193then it is used as the replacement string;
9194otherwise, if it is <b>false</b> or <b>nil</b>,
9195then there is no replacement
9196(that is, the original match is kept in the string).
9197
9198
9199<p>
9200Here are some examples:
9201
9202<pre>
9203     x = string.gsub("hello world", "(%w+)", "%1 %1")
9204     --&gt; x="hello hello world world"
9205
9206     x = string.gsub("hello world", "%w+", "%0 %0", 1)
9207     --&gt; x="hello hello world"
9208
9209     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
9210     --&gt; x="world hello Lua from"
9211
9212     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
9213     --&gt; x="home = /home/roberto, user = roberto"
9214
9215     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
9216           return load(s)()
9217         end)
9218     --&gt; x="4+5 = 9"
9219
9220     local t = {name="lua", version="5.4"}
9221     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
9222     --&gt; x="lua-5.4.tar.gz"
9223</pre>
9224
9225
9226
9227<p>
9228<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
9229
9230
9231<p>
9232Receives a string and returns its length.
9233The empty string <code>""</code> has length 0.
9234Embedded zeros are counted,
9235so <code>"a\000bc\000"</code> has length 5.
9236
9237
9238
9239
9240<p>
9241<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
9242
9243
9244<p>
9245Receives a string and returns a copy of this string with all
9246uppercase letters changed to lowercase.
9247All other characters are left unchanged.
9248The definition of what an uppercase letter is depends on the current locale.
9249
9250
9251
9252
9253<p>
9254<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
9255
9256
9257<p>
9258Looks for the first <em>match</em> of
9259the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9260If it finds one, then <code>match</code> returns
9261the captures from the pattern;
9262otherwise it returns <b>fail</b>.
9263If <code>pattern</code> specifies no captures,
9264then the whole match is returned.
9265A third, optional numeric argument <code>init</code> specifies
9266where to start the search;
9267its default value is&nbsp;1 and can be negative.
9268
9269
9270
9271
9272<p>
9273<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
9274
9275
9276<p>
9277Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
9278serialized in binary form (packed)
9279according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9280
9281
9282
9283
9284<p>
9285<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
9286
9287
9288<p>
9289Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
9290with the given format.
9291The format string cannot have the variable-length options
9292'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
9293
9294
9295
9296
9297<p>
9298<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
9299
9300
9301<p>
9302Returns a string that is the concatenation of <code>n</code> copies of
9303the string <code>s</code> separated by the string <code>sep</code>.
9304The default value for <code>sep</code> is the empty string
9305(that is, no separator).
9306Returns the empty string if <code>n</code> is not positive.
9307
9308
9309<p>
9310(Note that it is very easy to exhaust the memory of your machine
9311with a single call to this function.)
9312
9313
9314
9315
9316<p>
9317<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
9318
9319
9320<p>
9321Returns a string that is the string <code>s</code> reversed.
9322
9323
9324
9325
9326<p>
9327<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
9328
9329
9330<p>
9331Returns the substring of <code>s</code> that
9332starts at <code>i</code>  and continues until <code>j</code>;
9333<code>i</code> and <code>j</code> can be negative.
9334If <code>j</code> is absent, then it is assumed to be equal to -1
9335(which is the same as the string length).
9336In particular,
9337the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
9338with length <code>j</code>,
9339and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
9340returns a suffix of <code>s</code>
9341with length <code>i</code>.
9342
9343
9344<p>
9345If, after the translation of negative indices,
9346<code>i</code> is less than 1,
9347it is corrected to 1.
9348If <code>j</code> is greater than the string length,
9349it is corrected to that length.
9350If, after these corrections,
9351<code>i</code> is greater than <code>j</code>,
9352the function returns the empty string.
9353
9354
9355
9356
9357<p>
9358<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
9359
9360
9361<p>
9362Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
9363according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9364An optional <code>pos</code> marks where
9365to start reading in <code>s</code> (default is 1).
9366After the read values,
9367this function also returns the index of the first unread byte in <code>s</code>.
9368
9369
9370
9371
9372<p>
9373<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
9374
9375
9376<p>
9377Receives a string and returns a copy of this string with all
9378lowercase letters changed to uppercase.
9379All other characters are left unchanged.
9380The definition of what a lowercase letter is depends on the current locale.
9381
9382
9383
9384
9385
9386
9387
9388<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
9389
9390
9391
9392<p>
9393Patterns in Lua are described by regular strings,
9394which are interpreted as patterns by the pattern-matching functions
9395<a href="#pdf-string.find"><code>string.find</code></a>,
9396<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
9397<a href="#pdf-string.gsub"><code>string.gsub</code></a>,
9398and <a href="#pdf-string.match"><code>string.match</code></a>.
9399This section describes the syntax and the meaning
9400(that is, what they match) of these strings.
9401
9402
9403
9404
9405
9406<h4>Character Class:</h4><p>
9407A <em>character class</em> is used to represent a set of characters.
9408The following combinations are allowed in describing a character class:
9409
9410<ul>
9411
9412<li><b><em>x</em>: </b>
9413(where <em>x</em> is not one of the <em>magic characters</em>
9414<code>^$()%.[]*+-?</code>)
9415represents the character <em>x</em> itself.
9416</li>
9417
9418<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
9419
9420<li><b><code>%a</code>: </b> represents all letters.</li>
9421
9422<li><b><code>%c</code>: </b> represents all control characters.</li>
9423
9424<li><b><code>%d</code>: </b> represents all digits.</li>
9425
9426<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
9427
9428<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
9429
9430<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
9431
9432<li><b><code>%s</code>: </b> represents all space characters.</li>
9433
9434<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
9435
9436<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
9437
9438<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
9439
9440<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
9441represents the character <em>x</em>.
9442This is the standard way to escape the magic characters.
9443Any non-alphanumeric character
9444(including all punctuation characters, even the non-magical)
9445can be preceded by a '<code>%</code>' to represent itself in a pattern.
9446</li>
9447
9448<li><b><code>[<em>set</em>]</code>: </b>
9449represents the class which is the union of all
9450characters in <em>set</em>.
9451A range of characters can be specified by
9452separating the end characters of the range,
9453in ascending order, with a '<code>-</code>'.
9454All classes <code>%</code><em>x</em> described above can also be used as
9455components in <em>set</em>.
9456All other characters in <em>set</em> represent themselves.
9457For example, <code>[%w_]</code> (or <code>[_%w]</code>)
9458represents all alphanumeric characters plus the underscore,
9459<code>[0-7]</code> represents the octal digits,
9460and <code>[0-7%l%-]</code> represents the octal digits plus
9461the lowercase letters plus the '<code>-</code>' character.
9462
9463
9464<p>
9465You can put a closing square bracket in a set
9466by positioning it as the first character in the set.
9467You can put a hyphen in a set
9468by positioning it as the first or the last character in the set.
9469(You can also use an escape for both cases.)
9470
9471
9472<p>
9473The interaction between ranges and classes is not defined.
9474Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
9475have no meaning.
9476</li>
9477
9478<li><b><code>[^<em>set</em>]</code>: </b>
9479represents the complement of <em>set</em>,
9480where <em>set</em> is interpreted as above.
9481</li>
9482
9483</ul><p>
9484For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
9485the corresponding uppercase letter represents the complement of the class.
9486For instance, <code>%S</code> represents all non-space characters.
9487
9488
9489<p>
9490The definitions of letter, space, and other character groups
9491depend on the current locale.
9492In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
9493
9494
9495
9496
9497
9498<h4>Pattern Item:</h4><p>
9499A <em>pattern item</em> can be
9500
9501<ul>
9502
9503<li>
9504a single character class,
9505which matches any single character in the class;
9506</li>
9507
9508<li>
9509a single character class followed by '<code>*</code>',
9510which matches sequences of zero or more characters in the class.
9511These repetition items will always match the longest possible sequence;
9512</li>
9513
9514<li>
9515a single character class followed by '<code>+</code>',
9516which matches sequences of one or more characters in the class.
9517These repetition items will always match the longest possible sequence;
9518</li>
9519
9520<li>
9521a single character class followed by '<code>-</code>',
9522which also matches sequences of zero or more characters in the class.
9523Unlike '<code>*</code>',
9524these repetition items will always match the shortest possible sequence;
9525</li>
9526
9527<li>
9528a single character class followed by '<code>?</code>',
9529which matches zero or one occurrence of a character in the class.
9530It always matches one occurrence if possible;
9531</li>
9532
9533<li>
9534<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
9535such item matches a substring equal to the <em>n</em>-th captured string
9536(see below);
9537</li>
9538
9539<li>
9540<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
9541such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
9542and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
9543This means that, if one reads the string from left to right,
9544counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
9545the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
9546For instance, the item <code>%b()</code> matches expressions with
9547balanced parentheses.
9548</li>
9549
9550<li>
9551<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
9552such item matches an empty string at any position such that
9553the next character belongs to <em>set</em>
9554and the previous character does not belong to <em>set</em>.
9555The set <em>set</em> is interpreted as previously described.
9556The beginning and the end of the subject are handled as if
9557they were the character '<code>\0</code>'.
9558</li>
9559
9560</ul>
9561
9562
9563
9564
9565<h4>Pattern:</h4><p>
9566A <em>pattern</em> is a sequence of pattern items.
9567A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
9568beginning of the subject string.
9569A '<code>$</code>' at the end of a pattern anchors the match at the
9570end of the subject string.
9571At other positions,
9572'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
9573
9574
9575
9576
9577
9578<h4>Captures:</h4><p>
9579A pattern can contain sub-patterns enclosed in parentheses;
9580they describe <em>captures</em>.
9581When a match succeeds, the substrings of the subject string
9582that match captures are stored (<em>captured</em>) for future use.
9583Captures are numbered according to their left parentheses.
9584For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
9585the part of the string matching <code>"a*(.)%w(%s*)"</code> is
9586stored as the first capture, and therefore has number&nbsp;1;
9587the character matching "<code>.</code>" is captured with number&nbsp;2,
9588and the part matching "<code>%s*</code>" has number&nbsp;3.
9589
9590
9591<p>
9592As a special case, the capture <code>()</code> captures
9593the current string position (a number).
9594For instance, if we apply the pattern <code>"()aa()"</code> on the
9595string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
9596
9597
9598
9599
9600
9601<h4>Multiple matches:</h4><p>
9602The function <a href="#pdf-string.gsub"><code>string.gsub</code></a> and the iterator <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>
9603match multiple occurrences of the given pattern in the subject.
9604For these functions,
9605a new match is considered valid only
9606if it ends at least one byte after the end of the previous match.
9607In other words, the pattern machine never accepts the
9608empty string as a match immediately after another match.
9609As an example,
9610consider the results of the following code:
9611
9612<pre>
9613     &gt; string.gsub("abc", "()a*()", print);
9614     --&gt; 1   2
9615     --&gt; 3   3
9616     --&gt; 4   4
9617</pre><p>
9618The second and third results come from Lua matching an empty
9619string after '<code>b</code>' and another one after '<code>c</code>'.
9620Lua does not match an empty string after '<code>a</code>',
9621because it would end at the same position of the previous match.
9622
9623
9624
9625
9626
9627
9628
9629<h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
9630
9631<p>
9632The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
9633<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
9634is a format string,
9635which describes the layout of the structure being created or read.
9636
9637
9638<p>
9639A format string is a sequence of conversion options.
9640The conversion options are as follows:
9641
9642<ul>
9643<li><b><code>&lt;</code>: </b>sets little endian</li>
9644<li><b><code>&gt;</code>: </b>sets big endian</li>
9645<li><b><code>=</code>: </b>sets native endian</li>
9646<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
9647(default is native alignment)</li>
9648<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
9649<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
9650<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
9651<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
9652<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
9653<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
9654<li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
9655<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
9656<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
9657<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
9658(default is native size)</li>
9659<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
9660(default is native size)</li>
9661<li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
9662<li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
9663<li><b><code>n</code>: </b>a <code>lua_Number</code></li>
9664<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
9665<li><b><code>z</code>: </b>a zero-terminated string</li>
9666<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
9667coded as an unsigned integer with <code>n</code> bytes
9668(default is a <code>size_t</code>)</li>
9669<li><b><code>x</code>: </b>one byte of padding</li>
9670<li><b><code>X<em>op</em></code>: </b>an empty item that aligns
9671according to option <code>op</code>
9672(which is otherwise ignored)</li>
9673<li><b>'<code> </code>': </b>(space) ignored</li>
9674</ul><p>
9675(A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
9676Except for padding, spaces, and configurations
9677(options "<code>xX &lt;=&gt;!</code>"),
9678each option corresponds to an argument in <a href="#pdf-string.pack"><code>string.pack</code></a>
9679or a result in <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9680
9681
9682<p>
9683For 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>",
9684<code>n</code> can be any integer between 1 and 16.
9685All integral options check overflows;
9686<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
9687<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
9688For the unsigned options,
9689Lua integers are treated as unsigned values too.
9690
9691
9692<p>
9693Any format string starts as if prefixed by "<code>!1=</code>",
9694that is,
9695with maximum alignment of 1 (no alignment)
9696and native endianness.
9697
9698
9699<p>
9700Native endianness assumes that the whole system is
9701either big or little endian.
9702The packing functions will not emulate correctly the behavior
9703of mixed-endian formats.
9704
9705
9706<p>
9707Alignment works as follows:
9708For each option,
9709the format gets extra padding until the data starts
9710at an offset that is a multiple of the minimum between the
9711option size and the maximum alignment;
9712this minimum must be a power of 2.
9713Options "<code>c</code>" and "<code>z</code>" are not aligned;
9714option "<code>s</code>" follows the alignment of its starting integer.
9715
9716
9717<p>
9718All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
9719and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9720
9721
9722
9723
9724
9725
9726
9727<h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
9728
9729<p>
9730This library provides basic support for UTF-8 encoding.
9731It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
9732This library does not provide any support for Unicode other
9733than the handling of the encoding.
9734Any operation that needs the meaning of a character,
9735such as character classification, is outside its scope.
9736
9737
9738<p>
9739Unless stated otherwise,
9740all functions that expect a byte position as a parameter
9741assume that the given position is either the start of a byte sequence
9742or one plus the length of the subject string.
9743As in the string library,
9744negative indices count from the end of the string.
9745
9746
9747<p>
9748Functions that create byte sequences
9749accept all values up to <code>0x7FFFFFFF</code>,
9750as defined in the original UTF-8 specification;
9751that implies byte sequences of up to six bytes.
9752
9753
9754<p>
9755Functions that interpret byte sequences only accept
9756valid sequences (well formed and not overlong).
9757By default, they only accept byte sequences
9758that result in valid Unicode code points,
9759rejecting values greater than <code>10FFFF</code> and surrogates.
9760A boolean argument <code>lax</code>, when available,
9761lifts these checks,
9762so that all values up to <code>0x7FFFFFFF</code> are accepted.
9763(Not well formed and overlong sequences are still rejected.)
9764
9765
9766<p>
9767<hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
9768
9769
9770<p>
9771Receives zero or more integers,
9772converts each one to its corresponding UTF-8 byte sequence
9773and returns a string with the concatenation of all these sequences.
9774
9775
9776
9777
9778<p>
9779<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
9780
9781
9782<p>
9783The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xFD][\x80-\xBF]*</code>"
9784(see <a href="#6.4.1">&sect;6.4.1</a>),
9785which matches exactly one UTF-8 byte sequence,
9786assuming that the subject is a valid UTF-8 string.
9787
9788
9789
9790
9791<p>
9792<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s [, lax])</code></a></h3>
9793
9794
9795<p>
9796Returns values so that the construction
9797
9798<pre>
9799     for p, c in utf8.codes(s) do <em>body</em> end
9800</pre><p>
9801will iterate over all UTF-8 characters in string <code>s</code>,
9802with <code>p</code> being the position (in bytes) and <code>c</code> the code point
9803of each character.
9804It raises an error if it meets any invalid byte sequence.
9805
9806
9807
9808
9809<p>
9810<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j [, lax]]])</code></a></h3>
9811
9812
9813<p>
9814Returns the code points (as integers) from all characters in <code>s</code>
9815that start between byte position <code>i</code> and <code>j</code> (both included).
9816The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
9817It raises an error if it meets any invalid byte sequence.
9818
9819
9820
9821
9822<p>
9823<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j [, lax]]])</code></a></h3>
9824
9825
9826<p>
9827Returns the number of UTF-8 characters in string <code>s</code>
9828that start between positions <code>i</code> and <code>j</code> (both inclusive).
9829The default for <code>i</code> is 1 and for <code>j</code> is -1.
9830If it finds any invalid byte sequence,
9831returns <b>fail</b> plus the position of the first invalid byte.
9832
9833
9834
9835
9836<p>
9837<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
9838
9839
9840<p>
9841Returns the position (in bytes) where the encoding of the
9842<code>n</code>-th character of <code>s</code>
9843(counting from position <code>i</code>) starts.
9844A negative <code>n</code> gets characters before position <code>i</code>.
9845The default for <code>i</code> is 1 when <code>n</code> is non-negative
9846and <code>#s + 1</code> otherwise,
9847so that <code>utf8.offset(s, -n)</code> gets the offset of the
9848<code>n</code>-th character from the end of the string.
9849If the specified character is neither in the subject
9850nor right after its end,
9851the function returns <b>fail</b>.
9852
9853
9854<p>
9855As a special case,
9856when <code>n</code> is 0 the function returns the start of the encoding
9857of the character that contains the <code>i</code>-th byte of <code>s</code>.
9858
9859
9860<p>
9861This function assumes that <code>s</code> is a valid UTF-8 string.
9862
9863
9864
9865
9866
9867
9868
9869<h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
9870
9871<p>
9872This library provides generic functions for table manipulation.
9873It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
9874
9875
9876<p>
9877Remember that, whenever an operation needs the length of a table,
9878all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>).
9879All functions ignore non-numeric keys
9880in the tables given as arguments.
9881
9882
9883<p>
9884<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
9885
9886
9887<p>
9888Given a list where all elements are strings or numbers,
9889returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
9890The default value for <code>sep</code> is the empty string,
9891the default for <code>i</code> is 1,
9892and the default for <code>j</code> is <code>#list</code>.
9893If <code>i</code> is greater than <code>j</code>, returns the empty string.
9894
9895
9896
9897
9898<p>
9899<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
9900
9901
9902<p>
9903Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
9904shifting up the elements
9905<code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
9906The default value for <code>pos</code> is <code>#list+1</code>,
9907so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
9908of the list <code>t</code>.
9909
9910
9911
9912
9913<p>
9914<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
9915
9916
9917<p>
9918Moves elements from the table <code>a1</code> to the table <code>a2</code>,
9919performing the equivalent to the following
9920multiple assignment:
9921<code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
9922The default for <code>a2</code> is <code>a1</code>.
9923The destination range can overlap with the source range.
9924The number of elements to be moved must fit in a Lua integer.
9925
9926
9927<p>
9928Returns the destination table <code>a2</code>.
9929
9930
9931
9932
9933<p>
9934<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
9935
9936
9937<p>
9938Returns a new table with all arguments stored into keys 1, 2, etc.
9939and with a field "<code>n</code>" with the total number of arguments.
9940Note that the resulting table may not be a sequence,
9941if some arguments are <b>nil</b>.
9942
9943
9944
9945
9946<p>
9947<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
9948
9949
9950<p>
9951Removes from <code>list</code> the element at position <code>pos</code>,
9952returning the value of the removed element.
9953When <code>pos</code> is an integer between 1 and <code>#list</code>,
9954it shifts down the elements
9955<code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
9956and erases element <code>list[#list]</code>;
9957The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
9958or <code>#list + 1</code>.
9959
9960
9961<p>
9962The default value for <code>pos</code> is <code>#list</code>,
9963so that a call <code>table.remove(l)</code> removes the last element
9964of the list <code>l</code>.
9965
9966
9967
9968
9969<p>
9970<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
9971
9972
9973<p>
9974Sorts the list elements in a given order, <em>in-place</em>,
9975from <code>list[1]</code> to <code>list[#list]</code>.
9976If <code>comp</code> is given,
9977then it must be a function that receives two list elements
9978and returns true when the first element must come
9979before the second in the final order,
9980so that, after the sort,
9981<code>i &lt;= j</code> implies <code>not comp(list[j],list[i])</code>.
9982If <code>comp</code> is not given,
9983then the standard Lua operator <code>&lt;</code> is used instead.
9984
9985
9986<p>
9987The <code>comp</code> function must define a consistent order;
9988more formally, the function must define a strict weak order.
9989(A weak order is similar to a total order,
9990but it can equate different elements for comparison purposes.)
9991
9992
9993<p>
9994The sort algorithm is not stable:
9995Different elements considered equal by the given order
9996may have their relative positions changed by the sort.
9997
9998
9999
10000
10001<p>
10002<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
10003
10004
10005<p>
10006Returns the elements from the given list.
10007This function is equivalent to
10008
10009<pre>
10010     return list[i], list[i+1], &middot;&middot;&middot;, list[j]
10011</pre><p>
10012By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
10013
10014
10015
10016
10017
10018
10019
10020<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
10021
10022<p>
10023This library provides basic mathematical functions.
10024It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
10025Functions with the annotation "<code>integer/float</code>" give
10026integer results for integer arguments
10027and float results for non-integer arguments.
10028The rounding functions
10029<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>
10030return an integer when the result fits in the range of an integer,
10031or a float otherwise.
10032
10033
10034<p>
10035<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
10036
10037
10038<p>
10039Returns the maximum value between <code>x</code> and <code>-x</code>. (integer/float)
10040
10041
10042
10043
10044<p>
10045<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
10046
10047
10048<p>
10049Returns the arc cosine of <code>x</code> (in radians).
10050
10051
10052
10053
10054<p>
10055<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
10056
10057
10058<p>
10059Returns the arc sine of <code>x</code> (in radians).
10060
10061
10062
10063
10064<p>
10065<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
10066
10067
10068<p>
10069
10070Returns the arc tangent of <code>y/x</code> (in radians),
10071but uses the signs of both arguments to find the
10072quadrant of the result.
10073It also handles correctly the case of <code>x</code> being zero.
10074
10075
10076<p>
10077The default value for <code>x</code> is 1,
10078so that the call <code>math.atan(y)</code>
10079returns the arc tangent of <code>y</code>.
10080
10081
10082
10083
10084<p>
10085<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
10086
10087
10088<p>
10089Returns the smallest integral value greater than or equal to <code>x</code>.
10090
10091
10092
10093
10094<p>
10095<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
10096
10097
10098<p>
10099Returns the cosine of <code>x</code> (assumed to be in radians).
10100
10101
10102
10103
10104<p>
10105<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
10106
10107
10108<p>
10109Converts the angle <code>x</code> from radians to degrees.
10110
10111
10112
10113
10114<p>
10115<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
10116
10117
10118<p>
10119Returns the value <em>e<sup>x</sup></em>
10120(where <code>e</code> is the base of natural logarithms).
10121
10122
10123
10124
10125<p>
10126<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
10127
10128
10129<p>
10130Returns the largest integral value less than or equal to <code>x</code>.
10131
10132
10133
10134
10135<p>
10136<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
10137
10138
10139<p>
10140Returns the remainder of the division of <code>x</code> by <code>y</code>
10141that rounds the quotient towards zero. (integer/float)
10142
10143
10144
10145
10146<p>
10147<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
10148
10149
10150<p>
10151The float value <code>HUGE_VAL</code>,
10152a value greater than any other numeric value.
10153
10154
10155
10156
10157<p>
10158<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
10159
10160
10161<p>
10162Returns the logarithm of <code>x</code> in the given base.
10163The default for <code>base</code> is <em>e</em>
10164(so that the function returns the natural logarithm of <code>x</code>).
10165
10166
10167
10168
10169<p>
10170<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
10171
10172
10173<p>
10174Returns the argument with the maximum value,
10175according to the Lua operator <code>&lt;</code>.
10176
10177
10178
10179
10180<p>
10181<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
10182An integer with the maximum value for an integer.
10183
10184
10185
10186
10187<p>
10188<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
10189
10190
10191<p>
10192Returns the argument with the minimum value,
10193according to the Lua operator <code>&lt;</code>.
10194
10195
10196
10197
10198<p>
10199<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
10200An integer with the minimum value for an integer.
10201
10202
10203
10204
10205<p>
10206<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
10207
10208
10209<p>
10210Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
10211Its second result is always a float.
10212
10213
10214
10215
10216<p>
10217<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
10218
10219
10220<p>
10221The value of <em>&pi;</em>.
10222
10223
10224
10225
10226<p>
10227<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
10228
10229
10230<p>
10231Converts the angle <code>x</code> from degrees to radians.
10232
10233
10234
10235
10236<p>
10237<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
10238
10239
10240<p>
10241When called without arguments,
10242returns a pseudo-random float with uniform distribution
10243in the range  <em>[0,1)</em>.
10244When called with two integers <code>m</code> and <code>n</code>,
10245<code>math.random</code> returns a pseudo-random integer
10246with uniform distribution in the range <em>[m, n]</em>.
10247The call <code>math.random(n)</code>, for a positive <code>n</code>,
10248is equivalent to <code>math.random(1,n)</code>.
10249The call <code>math.random(0)</code> produces an integer with
10250all bits (pseudo)random.
10251
10252
10253<p>
10254This function uses the <code>xoshiro256**</code> algorithm to produce
10255pseudo-random 64-bit integers,
10256which are the results of calls with argument&nbsp;0.
10257Other results (ranges and floats)
10258are unbiased extracted from these integers.
10259
10260
10261<p>
10262Lua initializes its pseudo-random generator with the equivalent of
10263a call to <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with no arguments,
10264so that <code>math.random</code> should generate
10265different sequences of results each time the program runs.
10266
10267
10268
10269
10270<p>
10271<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed ([x [, y]])</code></a></h3>
10272
10273
10274<p>
10275When called with at least one argument,
10276the integer parameters <code>x</code> and <code>y</code> are
10277joined into a 128-bit <em>seed</em> that
10278is used to reinitialize the pseudo-random generator;
10279equal seeds produce equal sequences of numbers.
10280The default for <code>y</code> is zero.
10281
10282
10283<p>
10284When called with no arguments,
10285Lua generates a seed with
10286a weak attempt for randomness.
10287
10288
10289<p>
10290This function returns the two seed components
10291that were effectively used,
10292so that setting them again repeats the sequence.
10293
10294
10295<p>
10296To ensure a required level of randomness to the initial state
10297(or contrarily, to have a deterministic sequence,
10298for instance when debugging a program),
10299you should call <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with explicit arguments.
10300
10301
10302
10303
10304<p>
10305<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
10306
10307
10308<p>
10309Returns the sine of <code>x</code> (assumed to be in radians).
10310
10311
10312
10313
10314<p>
10315<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
10316
10317
10318<p>
10319Returns the square root of <code>x</code>.
10320(You can also use the expression <code>x^0.5</code> to compute this value.)
10321
10322
10323
10324
10325<p>
10326<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
10327
10328
10329<p>
10330Returns the tangent of <code>x</code> (assumed to be in radians).
10331
10332
10333
10334
10335<p>
10336<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
10337
10338
10339<p>
10340If the value <code>x</code> is convertible to an integer,
10341returns that integer.
10342Otherwise, returns <b>fail</b>.
10343
10344
10345
10346
10347<p>
10348<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
10349
10350
10351<p>
10352Returns "<code>integer</code>" if <code>x</code> is an integer,
10353"<code>float</code>" if it is a float,
10354or <b>fail</b> if <code>x</code> is not a number.
10355
10356
10357
10358
10359<p>
10360<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
10361
10362
10363<p>
10364Returns a boolean,
10365true if and only if integer <code>m</code> is below integer <code>n</code> when
10366they are compared as unsigned integers.
10367
10368
10369
10370
10371
10372
10373
10374<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
10375
10376<p>
10377The I/O library provides two different styles for file manipulation.
10378The first one uses implicit file handles;
10379that is, there are operations to set a default input file and a
10380default output file,
10381and all input/output operations are done over these default files.
10382The second style uses explicit file handles.
10383
10384
10385<p>
10386When using implicit file handles,
10387all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
10388When using explicit file handles,
10389the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
10390and then all operations are supplied as methods of the file handle.
10391
10392
10393<p>
10394The metatable for file handles provides metamethods
10395for <code>__gc</code> and <code>__close</code> that try
10396to close the file when called.
10397
10398
10399<p>
10400The table <code>io</code> also provides
10401three predefined file handles with their usual meanings from C:
10402<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>.
10403The I/O library never closes these files.
10404
10405
10406<p>
10407Unless otherwise stated,
10408all I/O functions return <b>fail</b> on failure,
10409plus an error message as a second result and
10410a system-dependent error code as a third result,
10411and some non-false value on success.
10412On non-POSIX systems,
10413the computation of the error message and error code
10414in case of errors
10415may be not thread safe,
10416because they rely on the global C variable <code>errno</code>.
10417
10418
10419<p>
10420<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
10421
10422
10423<p>
10424Equivalent to <code>file:close()</code>.
10425Without a <code>file</code>, closes the default output file.
10426
10427
10428
10429
10430<p>
10431<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
10432
10433
10434<p>
10435Equivalent to <code>io.output():flush()</code>.
10436
10437
10438
10439
10440<p>
10441<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
10442
10443
10444<p>
10445When called with a file name, it opens the named file (in text mode),
10446and sets its handle as the default input file.
10447When called with a file handle,
10448it simply sets this file handle as the default input file.
10449When called without arguments,
10450it returns the current default input file.
10451
10452
10453<p>
10454In case of errors this function raises the error,
10455instead of returning an error code.
10456
10457
10458
10459
10460<p>
10461<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3>
10462
10463
10464<p>
10465Opens the given file name in read mode
10466and returns an iterator function that
10467works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
10468When the iterator function fails to read any value,
10469it automatically closes the file.
10470Besides the iterator function,
10471<code>io.lines</code> returns three other values:
10472two <b>nil</b> values as placeholders,
10473plus the created file handle.
10474Therefore, when used in a generic <b>for</b> loop,
10475the file is closed also if the loop is interrupted by an
10476error or a <b>break</b>.
10477
10478
10479<p>
10480The call <code>io.lines()</code> (with no file name) is equivalent
10481to <code>io.input():lines("l")</code>;
10482that is, it iterates over the lines of the default input file.
10483In this case, the iterator does not close the file when the loop ends.
10484
10485
10486<p>
10487In case of errors opening the file,
10488this function raises the error,
10489instead of returning an error code.
10490
10491
10492
10493
10494<p>
10495<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
10496
10497
10498<p>
10499This function opens a file,
10500in the mode specified in the string <code>mode</code>.
10501In case of success,
10502it returns a new file handle.
10503
10504
10505<p>
10506The <code>mode</code> string can be any of the following:
10507
10508<ul>
10509<li><b>"<code>r</code>": </b> read mode (the default);</li>
10510<li><b>"<code>w</code>": </b> write mode;</li>
10511<li><b>"<code>a</code>": </b> append mode;</li>
10512<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
10513<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
10514<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
10515  writing is only allowed at the end of file.</li>
10516</ul><p>
10517The <code>mode</code> string can also have a '<code>b</code>' at the end,
10518which is needed in some systems to open the file in binary mode.
10519
10520
10521
10522
10523<p>
10524<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
10525
10526
10527<p>
10528Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
10529
10530
10531
10532
10533<p>
10534<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
10535
10536
10537<p>
10538This function is system dependent and is not available
10539on all platforms.
10540
10541
10542<p>
10543Starts the program <code>prog</code> in a separated process and returns
10544a file handle that you can use to read data from this program
10545(if <code>mode</code> is <code>"r"</code>, the default)
10546or to write data to this program
10547(if <code>mode</code> is <code>"w"</code>).
10548
10549
10550
10551
10552<p>
10553<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
10554
10555
10556<p>
10557Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
10558
10559
10560
10561
10562<p>
10563<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
10564
10565
10566<p>
10567In case of success,
10568returns a handle for a temporary file.
10569This file is opened in update mode
10570and it is automatically removed when the program ends.
10571
10572
10573
10574
10575<p>
10576<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
10577
10578
10579<p>
10580Checks whether <code>obj</code> is a valid file handle.
10581Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
10582<code>"closed file"</code> if <code>obj</code> is a closed file handle,
10583or <b>fail</b> if <code>obj</code> is not a file handle.
10584
10585
10586
10587
10588<p>
10589<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
10590
10591
10592<p>
10593Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
10594
10595
10596
10597
10598<p>
10599<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
10600
10601
10602<p>
10603Closes <code>file</code>.
10604Note that files are automatically closed when
10605their handles are garbage collected,
10606but that takes an unpredictable amount of time to happen.
10607
10608
10609<p>
10610When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
10611<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
10612returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
10613
10614
10615
10616
10617<p>
10618<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
10619
10620
10621<p>
10622Saves any written data to <code>file</code>.
10623
10624
10625
10626
10627<p>
10628<hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
10629
10630
10631<p>
10632Returns an iterator function that,
10633each time it is called,
10634reads the file according to the given formats.
10635When no format is given,
10636uses "<code>l</code>" as a default.
10637As an example, the construction
10638
10639<pre>
10640     for c in file:lines(1) do <em>body</em> end
10641</pre><p>
10642will iterate over all characters of the file,
10643starting at the current position.
10644Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
10645when the loop ends.
10646
10647
10648
10649
10650<p>
10651<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
10652
10653
10654<p>
10655Reads the file <code>file</code>,
10656according to the given formats, which specify what to read.
10657For each format,
10658the function returns a string or a number with the characters read,
10659or <b>fail</b> if it cannot read data with the specified format.
10660(In this latter case,
10661the function does not read subsequent formats.)
10662When called without arguments,
10663it uses a default format that reads the next line
10664(see below).
10665
10666
10667<p>
10668The available formats are
10669
10670<ul>
10671
10672<li><b>"<code>n</code>": </b>
10673reads a numeral and returns it as a float or an integer,
10674following the lexical conventions of Lua.
10675(The numeral may have leading whitespaces and a sign.)
10676This format always reads the longest input sequence that
10677is a valid prefix for a numeral;
10678if that prefix does not form a valid numeral
10679(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>")
10680or it is too long (more than 200 characters),
10681it is discarded and the format returns <b>fail</b>.
10682</li>
10683
10684<li><b>"<code>a</code>": </b>
10685reads the whole file, starting at the current position.
10686On end of file, it returns the empty string;
10687this format never fails.
10688</li>
10689
10690<li><b>"<code>l</code>": </b>
10691reads the next line skipping the end of line,
10692returning <b>fail</b> on end of file.
10693This is the default format.
10694</li>
10695
10696<li><b>"<code>L</code>": </b>
10697reads the next line keeping the end-of-line character (if present),
10698returning <b>fail</b> on end of file.
10699</li>
10700
10701<li><b><em>number</em>: </b>
10702reads a string with up to this number of bytes,
10703returning <b>fail</b> on end of file.
10704If <code>number</code> is zero,
10705it reads nothing and returns an empty string,
10706or <b>fail</b> on end of file.
10707</li>
10708
10709</ul><p>
10710The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
10711
10712
10713
10714
10715<p>
10716<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
10717
10718
10719<p>
10720Sets and gets the file position,
10721measured from the beginning of the file,
10722to the position given by <code>offset</code> plus a base
10723specified by the string <code>whence</code>, as follows:
10724
10725<ul>
10726<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
10727<li><b>"<code>cur</code>": </b> base is current position;</li>
10728<li><b>"<code>end</code>": </b> base is end of file;</li>
10729</ul><p>
10730In case of success, <code>seek</code> returns the final file position,
10731measured in bytes from the beginning of the file.
10732If <code>seek</code> fails, it returns <b>fail</b>,
10733plus a string describing the error.
10734
10735
10736<p>
10737The default value for <code>whence</code> is <code>"cur"</code>,
10738and for <code>offset</code> is 0.
10739Therefore, the call <code>file:seek()</code> returns the current
10740file position, without changing it;
10741the call <code>file:seek("set")</code> sets the position to the
10742beginning of the file (and returns 0);
10743and the call <code>file:seek("end")</code> sets the position to the
10744end of the file, and returns its size.
10745
10746
10747
10748
10749<p>
10750<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
10751
10752
10753<p>
10754Sets the buffering mode for a file.
10755There are three available modes:
10756
10757<ul>
10758<li><b>"<code>no</code>": </b> no buffering.</li>
10759<li><b>"<code>full</code>": </b> full buffering.</li>
10760<li><b>"<code>line</code>": </b> line buffering.</li>
10761</ul>
10762
10763<p>
10764For the last two cases,
10765<code>size</code> is a hint for the size of the buffer, in bytes.
10766The default is an appropriate size.
10767
10768
10769<p>
10770The specific behavior of each mode is non portable;
10771check the underlying ISO&nbsp;C function <code>setvbuf</code> in your platform for
10772more details.
10773
10774
10775
10776
10777<p>
10778<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
10779
10780
10781<p>
10782Writes the value of each of its arguments to <code>file</code>.
10783The arguments must be strings or numbers.
10784
10785
10786<p>
10787In case of success, this function returns <code>file</code>.
10788
10789
10790
10791
10792
10793
10794
10795<h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
10796
10797<p>
10798This library is implemented through table <a name="pdf-os"><code>os</code></a>.
10799
10800
10801<p>
10802<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
10803
10804
10805<p>
10806Returns an approximation of the amount in seconds of CPU time
10807used by the program,
10808as returned by the underlying ISO&nbsp;C function <code>clock</code>.
10809
10810
10811
10812
10813<p>
10814<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
10815
10816
10817<p>
10818Returns a string or a table containing date and time,
10819formatted according to the given string <code>format</code>.
10820
10821
10822<p>
10823If the <code>time</code> argument is present,
10824this is the time to be formatted
10825(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
10826Otherwise, <code>date</code> formats the current time.
10827
10828
10829<p>
10830If <code>format</code> starts with '<code>!</code>',
10831then the date is formatted in Coordinated Universal Time.
10832After this optional character,
10833if <code>format</code> is the string "<code>*t</code>",
10834then <code>date</code> returns a table with the following fields:
10835<code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
10836<code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59),
10837<code>sec</code> (0&ndash;61, due to leap seconds),
10838<code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1),
10839<code>yday</code> (day of the year, 1&ndash;366),
10840and <code>isdst</code> (daylight saving flag, a boolean).
10841This last field may be absent
10842if the information is not available.
10843
10844
10845<p>
10846If <code>format</code> is not "<code>*t</code>",
10847then <code>date</code> returns the date as a string,
10848formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
10849
10850
10851<p>
10852If <code>format</code> is absent, it defaults to "<code>%c</code>",
10853which gives a human-readable date and time representation
10854using the current locale.
10855
10856
10857<p>
10858On non-POSIX systems,
10859this function may be not thread safe
10860because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
10861
10862
10863
10864
10865<p>
10866<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
10867
10868
10869<p>
10870Returns the difference, in seconds,
10871from time <code>t1</code> to time <code>t2</code>
10872(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
10873In POSIX, Windows, and some other systems,
10874this value is exactly <code>t2</code><em>-</em><code>t1</code>.
10875
10876
10877
10878
10879<p>
10880<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
10881
10882
10883<p>
10884This function is equivalent to the ISO&nbsp;C function <code>system</code>.
10885It passes <code>command</code> to be executed by an operating system shell.
10886Its first result is <b>true</b>
10887if the command terminated successfully,
10888or <b>fail</b> otherwise.
10889After this first result
10890the function returns a string plus a number,
10891as follows:
10892
10893<ul>
10894
10895<li><b>"<code>exit</code>": </b>
10896the command terminated normally;
10897the following number is the exit status of the command.
10898</li>
10899
10900<li><b>"<code>signal</code>": </b>
10901the command was terminated by a signal;
10902the following number is the signal that terminated the command.
10903</li>
10904
10905</ul>
10906
10907<p>
10908When called without a <code>command</code>,
10909<code>os.execute</code> returns a boolean that is true if a shell is available.
10910
10911
10912
10913
10914<p>
10915<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
10916
10917
10918<p>
10919Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
10920If <code>code</code> is <b>true</b>,
10921the returned status is <code>EXIT_SUCCESS</code>;
10922if <code>code</code> is <b>false</b>,
10923the returned status is <code>EXIT_FAILURE</code>;
10924if <code>code</code> is a number,
10925the returned status is this number.
10926The default value for <code>code</code> is <b>true</b>.
10927
10928
10929<p>
10930If the optional second argument <code>close</code> is true,
10931closes the Lua state before exiting.
10932
10933
10934
10935
10936<p>
10937<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
10938
10939
10940<p>
10941Returns the value of the process environment variable <code>varname</code>
10942or <b>fail</b> if the variable is not defined.
10943
10944
10945
10946
10947<p>
10948<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
10949
10950
10951<p>
10952Deletes the file (or empty directory, on POSIX systems)
10953with the given name.
10954If this function fails, it returns <b>fail</b>
10955plus a string describing the error and the error code.
10956Otherwise, it returns true.
10957
10958
10959
10960
10961<p>
10962<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
10963
10964
10965<p>
10966Renames the file or directory named <code>oldname</code> to <code>newname</code>.
10967If this function fails, it returns <b>fail</b>,
10968plus a string describing the error and the error code.
10969Otherwise, it returns true.
10970
10971
10972
10973
10974<p>
10975<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
10976
10977
10978<p>
10979Sets the current locale of the program.
10980<code>locale</code> is a system-dependent string specifying a locale;
10981<code>category</code> is an optional string describing which category to change:
10982<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
10983<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
10984the default category is <code>"all"</code>.
10985The function returns the name of the new locale,
10986or <b>fail</b> if the request cannot be honored.
10987
10988
10989<p>
10990If <code>locale</code> is the empty string,
10991the current locale is set to an implementation-defined native locale.
10992If <code>locale</code> is the string "<code>C</code>",
10993the current locale is set to the standard C locale.
10994
10995
10996<p>
10997When called with <b>nil</b> as the first argument,
10998this function only returns the name of the current locale
10999for the given category.
11000
11001
11002<p>
11003This function may be not thread safe
11004because of its reliance on C&nbsp;function <code>setlocale</code>.
11005
11006
11007
11008
11009<p>
11010<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
11011
11012
11013<p>
11014Returns the current time when called without arguments,
11015or a time representing the local date and time specified by the given table.
11016This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
11017and may have fields
11018<code>hour</code> (default is 12),
11019<code>min</code> (default is 0),
11020<code>sec</code> (default is 0),
11021and <code>isdst</code> (default is <b>nil</b>).
11022Other fields are ignored.
11023For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
11024
11025
11026<p>
11027When the function is called,
11028the values in these fields do not need to be inside their valid ranges.
11029For instance, if <code>sec</code> is -10,
11030it means 10 seconds before the time specified by the other fields;
11031if <code>hour</code> is 1000,
11032it means 1000 hours after the time specified by the other fields.
11033
11034
11035<p>
11036The returned value is a number, whose meaning depends on your system.
11037In POSIX, Windows, and some other systems,
11038this number counts the number
11039of seconds since some given start time (the "epoch").
11040In other systems, the meaning is not specified,
11041and the number returned by <code>time</code> can be used only as an argument to
11042<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
11043
11044
11045<p>
11046When called with a table,
11047<code>os.time</code> also normalizes all the fields
11048documented in the <a href="#pdf-os.date"><code>os.date</code></a> function,
11049so that they represent the same time as before the call
11050but with values inside their valid ranges.
11051
11052
11053
11054
11055<p>
11056<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
11057
11058
11059<p>
11060Returns a string with a file name that can
11061be used for a temporary file.
11062The file must be explicitly opened before its use
11063and explicitly removed when no longer needed.
11064
11065
11066<p>
11067In POSIX systems,
11068this function also creates a file with that name,
11069to avoid security risks.
11070(Someone else might create the file with wrong permissions
11071in the time between getting the name and creating the file.)
11072You still have to open the file to use it
11073and to remove it (even if you do not use it).
11074
11075
11076<p>
11077When possible,
11078you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
11079which automatically removes the file when the program ends.
11080
11081
11082
11083
11084
11085
11086
11087<h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
11088
11089<p>
11090This library provides
11091the functionality of the debug interface (<a href="#4.7">&sect;4.7</a>) to Lua programs.
11092You should exert care when using this library.
11093Several of its functions
11094violate basic assumptions about Lua code
11095(e.g., that variables local to a function
11096cannot be accessed from outside;
11097that userdata metatables cannot be changed by Lua code;
11098that Lua programs do not crash)
11099and therefore can compromise otherwise secure code.
11100Moreover, some functions in this library may be slow.
11101
11102
11103<p>
11104All functions in this library are provided
11105inside the <a name="pdf-debug"><code>debug</code></a> table.
11106All functions that operate over a thread
11107have an optional first argument which is the
11108thread to operate over.
11109The default is always the current thread.
11110
11111
11112<p>
11113<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
11114
11115
11116<p>
11117Enters an interactive mode with the user,
11118running each string that the user enters.
11119Using simple commands and other debug facilities,
11120the user can inspect global and local variables,
11121change their values, evaluate expressions, and so on.
11122A line containing only the word <code>cont</code> finishes this function,
11123so that the caller continues its execution.
11124
11125
11126<p>
11127Note that commands for <code>debug.debug</code> are not lexically nested
11128within any function and so have no direct access to local variables.
11129
11130
11131
11132
11133<p>
11134<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
11135
11136
11137<p>
11138Returns the current hook settings of the thread, as three values:
11139the current hook function, the current hook mask,
11140and the current hook count,
11141as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function.
11142
11143
11144<p>
11145Returns <b>fail</b> if there is no active hook.
11146
11147
11148
11149
11150<p>
11151<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
11152
11153
11154<p>
11155Returns a table with information about a function.
11156You can give the function directly
11157or you can give a number as the value of <code>f</code>,
11158which means the function running at level <code>f</code> of the call stack
11159of the given thread:
11160level&nbsp;0 is the current function (<code>getinfo</code> itself);
11161level&nbsp;1 is the function that called <code>getinfo</code>
11162(except for tail calls, which do not count in the stack);
11163and so on.
11164If <code>f</code> is a number greater than the number of active functions,
11165then <code>getinfo</code> returns <b>fail</b>.
11166
11167
11168<p>
11169The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
11170with the string <code>what</code> describing which fields to fill in.
11171The default for <code>what</code> is to get all information available,
11172except the table of valid lines.
11173If present,
11174the option '<code>f</code>'
11175adds a field named <code>func</code> with the function itself.
11176If present,
11177the option '<code>L</code>'
11178adds a field named <code>activelines</code> with the table of
11179valid lines.
11180
11181
11182<p>
11183For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
11184a name for the current function,
11185if a reasonable name can be found,
11186and the expression <code>debug.getinfo(print)</code>
11187returns a table with all available information
11188about the <a href="#pdf-print"><code>print</code></a> function.
11189
11190
11191
11192
11193<p>
11194<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
11195
11196
11197<p>
11198This function returns the name and the value of the local variable
11199with index <code>local</code> of the function at level <code>f</code> of the stack.
11200This function accesses not only explicit local variables,
11201but also parameters and temporary values.
11202
11203
11204<p>
11205The first parameter or local variable has index&nbsp;1, and so on,
11206following the order that they are declared in the code,
11207counting only the variables that are active
11208in the current scope of the function.
11209Compile-time constants may not appear in this listing,
11210if they were optimized away by the compiler.
11211Negative indices refer to vararg arguments;
11212-1 is the first vararg argument.
11213The function returns <b>fail</b>
11214if there is no variable with the given index,
11215and raises an error when called with a level out of range.
11216(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
11217
11218
11219<p>
11220Variable names starting with '<code>(</code>' (open parenthesis)
11221represent variables with no known names
11222(internal variables such as loop control variables,
11223and variables from chunks saved without debug information).
11224
11225
11226<p>
11227The parameter <code>f</code> may also be a function.
11228In that case, <code>getlocal</code> returns only the name of function parameters.
11229
11230
11231
11232
11233<p>
11234<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
11235
11236
11237<p>
11238Returns the metatable of the given <code>value</code>
11239or <b>nil</b> if it does not have a metatable.
11240
11241
11242
11243
11244<p>
11245<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
11246
11247
11248<p>
11249Returns the registry table (see <a href="#4.3">&sect;4.3</a>).
11250
11251
11252
11253
11254<p>
11255<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
11256
11257
11258<p>
11259This function returns the name and the value of the upvalue
11260with index <code>up</code> of the function <code>f</code>.
11261The function returns <b>fail</b>
11262if there is no upvalue with the given index.
11263
11264
11265<p>
11266(For Lua functions,
11267upvalues are the external local variables that the function uses,
11268and that are consequently included in its closure.)
11269
11270
11271<p>
11272For C&nbsp;functions, this function uses the empty string <code>""</code>
11273as a name for all upvalues.
11274
11275
11276<p>
11277Variable name '<code>?</code>' (interrogation mark)
11278represents variables with no known names
11279(variables from chunks saved without debug information).
11280
11281
11282
11283
11284<p>
11285<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u, n)</code></a></h3>
11286
11287
11288<p>
11289Returns the <code>n</code>-th user value associated
11290to the userdata <code>u</code> plus a boolean,
11291<b>false</b> if the userdata does not have that value.
11292
11293
11294
11295
11296<p>
11297<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
11298
11299
11300<p>
11301Sets the given function as the debug hook.
11302The string <code>mask</code> and the number <code>count</code> describe
11303when the hook will be called.
11304The string mask may have any combination of the following characters,
11305with the given meaning:
11306
11307<ul>
11308<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
11309<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
11310<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
11311</ul><p>
11312Moreover,
11313with a <code>count</code> different from zero,
11314the hook is called also after every <code>count</code> instructions.
11315
11316
11317<p>
11318When called without arguments,
11319<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
11320
11321
11322<p>
11323When the hook is called, its first parameter is a string
11324describing the event that has triggered its call:
11325<code>"call"</code>, <code>"tail call"</code>, <code>"return"</code>,
11326<code>"line"</code>, and <code>"count"</code>.
11327For line events,
11328the hook also gets the new line number as its second parameter.
11329Inside a hook,
11330you can call <code>getinfo</code> with level&nbsp;2 to get more information about
11331the running function.
11332(Level&nbsp;0 is the <code>getinfo</code> function,
11333and level&nbsp;1 is the hook function.)
11334
11335
11336
11337
11338<p>
11339<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
11340
11341
11342<p>
11343This function assigns the value <code>value</code> to the local variable
11344with index <code>local</code> of the function at level <code>level</code> of the stack.
11345The function returns <b>fail</b> if there is no local
11346variable with the given index,
11347and raises an error when called with a <code>level</code> out of range.
11348(You can call <code>getinfo</code> to check whether the level is valid.)
11349Otherwise, it returns the name of the local variable.
11350
11351
11352<p>
11353See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
11354variable indices and names.
11355
11356
11357
11358
11359<p>
11360<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
11361
11362
11363<p>
11364Sets the metatable for the given <code>value</code> to the given <code>table</code>
11365(which can be <b>nil</b>).
11366Returns <code>value</code>.
11367
11368
11369
11370
11371<p>
11372<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
11373
11374
11375<p>
11376This function assigns the value <code>value</code> to the upvalue
11377with index <code>up</code> of the function <code>f</code>.
11378The function returns <b>fail</b> if there is no upvalue
11379with the given index.
11380Otherwise, it returns the name of the upvalue.
11381
11382
11383<p>
11384See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
11385
11386
11387
11388
11389<p>
11390<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value, n)</code></a></h3>
11391
11392
11393<p>
11394Sets the given <code>value</code> as
11395the <code>n</code>-th user value associated to the given <code>udata</code>.
11396<code>udata</code> must be a full userdata.
11397
11398
11399<p>
11400Returns <code>udata</code>,
11401or <b>fail</b> if the userdata does not have that value.
11402
11403
11404
11405
11406<p>
11407<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
11408
11409
11410<p>
11411If <code>message</code> is present but is neither a string nor <b>nil</b>,
11412this function returns <code>message</code> without further processing.
11413Otherwise,
11414it returns a string with a traceback of the call stack.
11415The optional <code>message</code> string is appended
11416at the beginning of the traceback.
11417An optional <code>level</code> number tells at which level
11418to start the traceback
11419(default is 1, the function calling <code>traceback</code>).
11420
11421
11422
11423
11424<p>
11425<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
11426
11427
11428<p>
11429Returns a unique identifier (as a light userdata)
11430for the upvalue numbered <code>n</code>
11431from the given function.
11432
11433
11434<p>
11435These unique identifiers allow a program to check whether different
11436closures share upvalues.
11437Lua closures that share an upvalue
11438(that is, that access a same external local variable)
11439will return identical ids for those upvalue indices.
11440
11441
11442
11443
11444<p>
11445<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
11446
11447
11448<p>
11449Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
11450refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
11451
11452
11453
11454
11455
11456
11457
11458<h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
11459
11460<p>
11461Although Lua has been designed as an extension language,
11462to be embedded in a host C&nbsp;program,
11463it is also frequently used as a standalone language.
11464An interpreter for Lua as a standalone language,
11465called simply <code>lua</code>,
11466is provided with the standard distribution.
11467The standalone interpreter includes
11468all standard libraries.
11469Its usage is:
11470
11471<pre>
11472     lua [options] [script [args]]
11473</pre><p>
11474The options are:
11475
11476<ul>
11477<li><b><code>-e <em>stat</em></code>: </b> execute string <em>stat</em>;</li>
11478<li><b><code>-i</code>: </b> enter interactive mode after running <em>script</em>;</li>
11479<li><b><code>-l <em>mod</em></code>: </b> "require" <em>mod</em> and assign the
11480  result to global <em>mod</em>;</li>
11481<li><b><code>-v</code>: </b> print version information;</li>
11482<li><b><code>-E</code>: </b> ignore environment variables;</li>
11483<li><b><code>-W</code>: </b> turn warnings on;</li>
11484<li><b><code>--</code>: </b> stop handling options;</li>
11485<li><b><code>-</code>: </b> execute <code>stdin</code> as a file and stop handling options.</li>
11486</ul><p>
11487After handling its options, <code>lua</code> runs the given <em>script</em>.
11488When called without arguments,
11489<code>lua</code> behaves as <code>lua -v -i</code>
11490when the standard input (<code>stdin</code>) is a terminal,
11491and as <code>lua -</code> otherwise.
11492
11493
11494<p>
11495When called without the option <code>-E</code>,
11496the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_4"><code>LUA_INIT_5_4</code></a>
11497(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
11498before running any argument.
11499If the variable content has the format <code>@<em>filename</em></code>,
11500then <code>lua</code> executes the file.
11501Otherwise, <code>lua</code> executes the string itself.
11502
11503
11504<p>
11505When called with the option <code>-E</code>,
11506Lua does not consult any environment variables.
11507In particular,
11508the values of <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
11509are set with the default paths defined in <code>luaconf.h</code>.
11510
11511
11512<p>
11513The options <code>-e</code>, <code>-l</code>, and <code>-W</code> are handled in
11514the order they appear.
11515For instance, an invocation like
11516
11517<pre>
11518     $ lua -e 'a=1' -llib1 script.lua
11519</pre><p>
11520will first set <code>a</code> to 1, then require the library <code>lib1</code>,
11521and finally run the file <code>script.lua</code> with no arguments.
11522(Here <code>$</code> is the shell prompt. Your prompt may be different.)
11523
11524
11525<p>
11526Before running any code,
11527<code>lua</code> collects all command-line arguments
11528in a global table called <code>arg</code>.
11529The script name goes to index 0,
11530the first argument after the script name goes to index 1,
11531and so on.
11532Any arguments before the script name
11533(that is, the interpreter name plus its options)
11534go to negative indices.
11535For instance, in the call
11536
11537<pre>
11538     $ lua -la b.lua t1 t2
11539</pre><p>
11540the table is like this:
11541
11542<pre>
11543     arg = { [-2] = "lua", [-1] = "-la",
11544             [0] = "b.lua",
11545             [1] = "t1", [2] = "t2" }
11546</pre><p>
11547If there is no script in the call,
11548the interpreter name goes to index 0,
11549followed by the other arguments.
11550For instance, the call
11551
11552<pre>
11553     $ lua -e "print(arg[1])"
11554</pre><p>
11555will print "<code>-e</code>".
11556If there is a script,
11557the script is called with arguments
11558<code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
11559Like all chunks in Lua,
11560the script is compiled as a vararg function.
11561
11562
11563<p>
11564In interactive mode,
11565Lua repeatedly prompts and waits for a line.
11566After reading a line,
11567Lua first try to interpret the line as an expression.
11568If it succeeds, it prints its value.
11569Otherwise, it interprets the line as a statement.
11570If you write an incomplete statement,
11571the interpreter waits for its completion
11572by issuing a different prompt.
11573
11574
11575<p>
11576If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
11577then its value is used as the prompt.
11578Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
11579its value is used as the secondary prompt
11580(issued during incomplete statements).
11581
11582
11583<p>
11584In case of unprotected errors in the script,
11585the interpreter reports the error to the standard error stream.
11586If the error object is not a string but
11587has a metamethod <code>__tostring</code>,
11588the interpreter calls this metamethod to produce the final message.
11589Otherwise, the interpreter converts the error object to a string
11590and adds a stack traceback to it.
11591When warnings are on,
11592they are simply printed in the standard error output.
11593
11594
11595<p>
11596When finishing normally,
11597the interpreter closes its main Lua state
11598(see <a href="#lua_close"><code>lua_close</code></a>).
11599The script can avoid this step by
11600calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
11601
11602
11603<p>
11604To allow the use of Lua as a
11605script interpreter in Unix systems,
11606Lua skips the first line of a file chunk if it starts with <code>#</code>.
11607Therefore, Lua scripts can be made into executable programs
11608by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
11609as in
11610
11611<pre>
11612     #!/usr/local/bin/lua
11613</pre><p>
11614Of course,
11615the location of the Lua interpreter may be different in your machine.
11616If <code>lua</code> is in your <code>PATH</code>,
11617then
11618
11619<pre>
11620     #!/usr/bin/env lua
11621</pre><p>
11622is a more portable solution.
11623
11624
11625
11626<h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
11627
11628
11629
11630<p>
11631Here we list the incompatibilities that you may find when moving a program
11632from Lua&nbsp;5.3 to Lua&nbsp;5.4.
11633
11634
11635<p>
11636You can avoid some incompatibilities by compiling Lua with
11637appropriate options (see file <code>luaconf.h</code>).
11638However,
11639all these compatibility options will be removed in the future.
11640More often than not,
11641compatibility issues arise when these compatibility options
11642are removed.
11643So, whenever you have the chance,
11644you should try to test your code with a version of Lua compiled
11645with all compatibility options turned off.
11646That will ease transitions to newer versions of Lua.
11647
11648
11649<p>
11650Lua versions can always change the C API in ways that
11651do not imply source-code changes in a program,
11652such as the numeric values for constants
11653or the implementation of functions as macros.
11654Therefore,
11655you should never assume that binaries are compatible between
11656different Lua versions.
11657Always recompile clients of the Lua API when
11658using a new version.
11659
11660
11661<p>
11662Similarly, Lua versions can always change the internal representation
11663of precompiled chunks;
11664precompiled chunks are not compatible between different Lua versions.
11665
11666
11667<p>
11668The standard paths in the official distribution may
11669change between versions.
11670
11671
11672
11673
11674
11675<h2>8.1 &ndash; <a name="8.1">Incompatibilities in the Language</a></h2>
11676<ul>
11677
11678<li>
11679The coercion of strings to numbers in
11680arithmetic and bitwise operations
11681has been removed from the core language.
11682The string library does a similar job
11683for arithmetic (but not for bitwise) operations
11684using the string metamethods.
11685However, unlike in previous versions,
11686the new implementation preserves the implicit type of the numeral
11687in the string.
11688For instance, the result of <code>"1" + "2"</code> now is an integer,
11689not a float.
11690</li>
11691
11692<li>
11693Literal decimal integer constants that overflow are read as floats,
11694instead of wrapping around.
11695You can use hexadecimal notation for such constants if you
11696want the old behavior
11697(reading them as integers with wrap around).
11698</li>
11699
11700<li>
11701The use of the <code>__lt</code> metamethod to emulate <code>__le</code>
11702has been removed.
11703When needed, this metamethod must be explicitly defined.
11704</li>
11705
11706<li>
11707The semantics of the numerical <b>for</b> loop
11708over integers changed in some details.
11709In particular, the control variable never wraps around.
11710</li>
11711
11712<li>
11713A label for a <b>goto</b> cannot be declared where a label with the same
11714name is visible, even if this other label is declared in an enclosing
11715block.
11716</li>
11717
11718<li>
11719When finalizing an object,
11720Lua does not ignore <code>__gc</code> metamethods that are not functions.
11721Any value will be called, if present.
11722(Non-callable values will generate a warning,
11723like any other error when calling a finalizer.)
11724</li>
11725
11726</ul>
11727
11728
11729
11730
11731<h2>8.2 &ndash; <a name="8.2">Incompatibilities in the Libraries</a></h2>
11732<ul>
11733
11734<li>
11735The function <a href="#pdf-print"><code>print</code></a> does not call <a href="#pdf-tostring"><code>tostring</code></a>
11736to format its arguments;
11737instead, it has this functionality hardwired.
11738You should use <code>__tostring</code> to modify how values are printed.
11739</li>
11740
11741<li>
11742The pseudo-random number generator used by the function <a href="#pdf-math.random"><code>math.random</code></a>
11743now starts with a somewhat random seed.
11744Moreover, it uses a different algorithm.
11745</li>
11746
11747<li>
11748By default, the decoding functions in the <a href="#pdf-utf8"><code>utf8</code></a> library
11749do not accept surrogates as valid code points.
11750An extra parameter in these functions makes them more permissive.
11751</li>
11752
11753<li>
11754The options "<code>setpause</code>" and "<code>setstepmul</code>"
11755of the function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> are deprecated.
11756You should use the new option "<code>incremental</code>" to set them.
11757</li>
11758
11759<li>
11760The function <a href="#pdf-io.lines"><code>io.lines</code></a> now returns four values,
11761instead of just one.
11762That can be a problem when it is used as the sole
11763argument to another function that has optional parameters,
11764such as in <code>load(io.lines(filename, "L"))</code>.
11765To fix that issue,
11766you can wrap the call into parentheses,
11767to adjust its number of results to one.
11768</li>
11769
11770</ul>
11771
11772
11773
11774
11775<h2>8.3 &ndash; <a name="8.3">Incompatibilities in the API</a></h2>
11776
11777
11778<ul>
11779
11780<li>
11781Full userdata now has an arbitrary number of associated user values.
11782Therefore, the functions <code>lua_newuserdata</code>,
11783<code>lua_setuservalue</code>, and <code>lua_getuservalue</code> were
11784replaced by <a href="#lua_newuserdatauv"><code>lua_newuserdatauv</code></a>,
11785<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a>, and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>,
11786which have an extra argument.
11787
11788
11789<p>
11790For compatibility, the old names still work as macros assuming
11791one single user value.
11792Note, however, that userdata with zero user values
11793are more efficient memory-wise.
11794</li>
11795
11796<li>
11797The function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter.
11798This out parameter returns the number of values on
11799the top of the stack that were yielded or returned by the coroutine.
11800(In previous versions,
11801those values were the entire stack.)
11802</li>
11803
11804<li>
11805The function <a href="#lua_version"><code>lua_version</code></a> returns the version number,
11806instead of an address of the version number.
11807The Lua core should work correctly with libraries using their
11808own static copies of the same core,
11809so there is no need to check whether they are using the same
11810address space.
11811</li>
11812
11813<li>
11814The constant <code>LUA_ERRGCMM</code> was removed.
11815Errors in finalizers are never propagated;
11816instead, they generate a warning.
11817</li>
11818
11819<li>
11820The options <code>LUA_GCSETPAUSE</code> and <code>LUA_GCSETSTEPMUL</code>
11821of the function <a href="#lua_gc"><code>lua_gc</code></a> are deprecated.
11822You should use the new option <code>LUA_GCINC</code> to set them.
11823</li>
11824
11825</ul>
11826
11827
11828
11829
11830<h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
11831
11832<p>
11833Here is the complete syntax of Lua in extended BNF.
11834As usual in extended BNF,
11835{A} means 0 or more As,
11836and [A] means an optional A.
11837(For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
11838for a description of the terminals
11839Name, Numeral,
11840and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
11841
11842
11843
11844
11845<pre>
11846
11847	chunk ::= block
11848
11849	block ::= {stat} [retstat]
11850
11851	stat ::=  &lsquo;<b>;</b>&rsquo; |
11852		 varlist &lsquo;<b>=</b>&rsquo; explist |
11853		 functioncall |
11854		 label |
11855		 <b>break</b> |
11856		 <b>goto</b> Name |
11857		 <b>do</b> block <b>end</b> |
11858		 <b>while</b> exp <b>do</b> block <b>end</b> |
11859		 <b>repeat</b> block <b>until</b> exp |
11860		 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
11861		 <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> |
11862		 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
11863		 <b>function</b> funcname funcbody |
11864		 <b>local</b> <b>function</b> Name funcbody |
11865		 <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
11866
11867	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
11868
11869	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
11870
11871	retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
11872
11873	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
11874
11875	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
11876
11877	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
11878
11879	var ::=  Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
11880
11881	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
11882
11883	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
11884
11885	exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
11886		 prefixexp | tableconstructor | exp binop exp | unop exp
11887
11888	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
11889
11890	functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
11891
11892	args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
11893
11894	functiondef ::= <b>function</b> funcbody
11895
11896	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
11897
11898	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
11899
11900	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
11901
11902	fieldlist ::= field {fieldsep field} [fieldsep]
11903
11904	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
11905
11906	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
11907
11908	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; |
11909		 &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; |
11910		 &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; |
11911		 <b>and</b> | <b>or</b>
11912
11913	unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
11914
11915</pre>
11916
11917<p>
11918
11919
11920
11921
11922
11923
11924
11925<P CLASS="footer">
11926Last update:
11927Mon Mar 15 13:39:42 UTC 2021
11928</P>
11929<!--
11930Last change: revised for Lua 5.4.3
11931-->
11932
11933</body></html>
11934
11935