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 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.
146
147
148<p>
149The type <em>number</em> represents both
150integer numbers and real (floating-point) numbers,
151using two subtypes: <em>integer</em> and <em>float</em>.
152Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
153but you can also compile Lua so that it
154uses 32-bit integers and/or single-precision (32-bit) floats.
155The option with 32 bits for both integers and floats
156is particularly attractive
157for small machines and embedded systems.
158(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
159
160
161<p>
162Unless stated otherwise,
163any overflow when manipulating integer values <em>wrap around</em>,
164according to the usual rules of two-complement arithmetic.
165(In other words,
166the actual result is the unique representable integer
167that is equal modulo <em>2<sup>n</sup></em> to the mathematical result,
168where <em>n</em> is the number of bits of the integer type.)
169
170
171<p>
172Lua has explicit rules about when each subtype is used,
173but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
174Therefore,
175the programmer may choose to mostly ignore the difference
176between integers and floats
177or to assume complete control over the representation of each number.
178
179
180<p>
181The type <em>string</em> represents immutable sequences of bytes.
182
183Lua is 8-bit clean:
184strings can contain any 8-bit value,
185including embedded zeros ('<code>\0</code>').
186Lua is also encoding-agnostic;
187it makes no assumptions about the contents of a string.
188The length of any string in Lua must fit in a Lua integer.
189
190
191<p>
192Lua can call (and manipulate) functions written in Lua and
193functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
194Both are represented by the type <em>function</em>.
195
196
197<p>
198The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
199be stored in Lua variables.
200A userdata value represents a block of raw memory.
201There are two kinds of userdata:
202<em>full userdata</em>,
203which is an object with a block of memory managed by Lua,
204and <em>light userdata</em>,
205which is simply a C&nbsp;pointer value.
206Userdata has no predefined operations in Lua,
207except assignment and identity test.
208By using <em>metatables</em>,
209the programmer can define operations for full userdata values
210(see <a href="#2.4">&sect;2.4</a>).
211Userdata values cannot be created or modified in Lua,
212only through the C&nbsp;API.
213This guarantees the integrity of data owned by
214the host program and C&nbsp;libraries.
215
216
217<p>
218The type <em>thread</em> represents independent threads of execution
219and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
220Lua threads are not related to operating-system threads.
221Lua supports coroutines on all systems,
222even those that do not support threads natively.
223
224
225<p>
226The type <em>table</em> implements associative arrays,
227that is, arrays that can have as indices not only numbers,
228but any Lua value except <b>nil</b> and NaN.
229(<em>Not a Number</em> is a special floating-point value
230used by the IEEE 754 standard to represent
231undefined numerical results, such as <code>0/0</code>.)
232Tables can be <em>heterogeneous</em>;
233that is, they can contain values of all types (except <b>nil</b>).
234Any key associated to the value <b>nil</b> is not considered part of the table.
235Conversely, any key that is not part of a table has
236an associated value <b>nil</b>.
237
238
239<p>
240Tables are the sole data-structuring mechanism in Lua;
241they can be used to represent ordinary arrays, lists,
242symbol tables, sets, records, graphs, trees, etc.
243To represent records, Lua uses the field name as an index.
244The language supports this representation by
245providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
246There are several convenient ways to create tables in Lua
247(see <a href="#3.4.9">&sect;3.4.9</a>).
248
249
250<p>
251Like indices,
252the values of table fields can be of any type.
253In particular,
254because functions are first-class values,
255table fields can contain functions.
256Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
257
258
259<p>
260The indexing of tables follows
261the definition of raw equality in the language.
262The expressions <code>a[i]</code> and <code>a[j]</code>
263denote the same table element
264if and only if <code>i</code> and <code>j</code> are raw equal
265(that is, equal without metamethods).
266In particular, floats with integral values
267are equal to their respective integers
268(e.g., <code>1.0 == 1</code>).
269To avoid ambiguities,
270any float used as a key that is equal to an integer
271is converted to that integer.
272For instance, if you write <code>a[2.0] = true</code>,
273the actual key inserted into the table will be the integer <code>2</code>.
274
275
276<p>
277Tables, functions, threads, and (full) userdata values are <em>objects</em>:
278variables do not actually <em>contain</em> these values,
279only <em>references</em> to them.
280Assignment, parameter passing, and function returns
281always manipulate references to such values;
282these operations do not imply any kind of copy.
283
284
285<p>
286The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
287of a given value (see <a href="#pdf-type"><code>type</code></a>).
288
289
290
291
292
293<h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
294
295<p>
296As we will discuss further in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
297any reference to a free name
298(that is, a name not bound to any declaration) <code>var</code>
299is syntactically translated to <code>_ENV.var</code>.
300Moreover, every chunk is compiled in the scope of
301an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
302so <code>_ENV</code> itself is never a free name in a chunk.
303
304
305<p>
306Despite the existence of this external <code>_ENV</code> variable and
307the translation of free names,
308<code>_ENV</code> is a completely regular name.
309In particular,
310you can define new variables and parameters with that name.
311Each reference to a free name uses the <code>_ENV</code> that is
312visible at that point in the program,
313following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
314
315
316<p>
317Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
318
319
320<p>
321Lua keeps a distinguished environment called the <em>global environment</em>.
322This value is kept at a special index in the C registry (see <a href="#4.3">&sect;4.3</a>).
323In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
324(<a href="#pdf-_G"><code>_G</code></a> is never used internally,
325so changing its value will affect only your own code.)
326
327
328<p>
329When Lua loads a chunk,
330the default value for its <code>_ENV</code> variable
331is the global environment (see <a href="#pdf-load"><code>load</code></a>).
332Therefore, by default,
333free names in Lua code refer to entries in the global environment
334and, therefore, they are also called <em>global variables</em>.
335Moreover, all standard libraries are loaded in the global environment
336and some functions there operate on that environment.
337You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
338to load a chunk with a different environment.
339(In C, you have to load the chunk and then change the value
340of its first upvalue; see <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.)
341
342
343
344
345
346<h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
347
348<p>
349Several operations in Lua can <em>raise</em> an error.
350An error interrupts the normal flow of the program,
351which can continue by <em>catching</em> the error.
352
353
354<p>
355Lua code can explicitly raise an error by calling the
356<a href="#pdf-error"><code>error</code></a> function.
357(This function never returns.)
358
359
360<p>
361To catch errors in Lua,
362you can do a <em>protected call</em>,
363using <a href="#pdf-pcall"><code>pcall</code></a> (or <a href="#pdf-xpcall"><code>xpcall</code></a>).
364The function <a href="#pdf-pcall"><code>pcall</code></a> calls a given function in <em>protected mode</em>.
365Any error while running the function stops its execution,
366and control returns immediately to <code>pcall</code>,
367which returns a status code.
368
369
370<p>
371Because Lua is an embedded extension language,
372Lua code starts running by a call
373from C&nbsp;code in the host program.
374(When you use Lua standalone,
375the <code>lua</code> application is the host program.)
376Usually, this call is protected;
377so, when an otherwise unprotected error occurs during
378the compilation or execution of a Lua chunk,
379control returns to the host,
380which can take appropriate measures,
381such as printing an error message.
382
383
384<p>
385Whenever there is an error,
386an <em>error object</em>
387is propagated with information about the error.
388Lua itself only generates errors whose error object is a string,
389but programs may generate errors with
390any value as the error object.
391It is up to the Lua program or its host to handle such error objects.
392For historical reasons,
393an error object is often called an <em>error message</em>,
394even though it does not have to be a string.
395
396
397<p>
398When you use <a href="#pdf-xpcall"><code>xpcall</code></a> (or <a href="#lua_pcall"><code>lua_pcall</code></a>, in C)
399you may give a <em>message handler</em>
400to be called in case of errors.
401This function is called with the original error object
402and returns a new error object.
403It is called before the error unwinds the stack,
404so that it can gather more information about the error,
405for instance by inspecting the stack and creating a stack traceback.
406This message handler is still protected by the protected call;
407so, an error inside the message handler
408will call the message handler again.
409If this loop goes on for too long,
410Lua breaks it and returns an appropriate message.
411The message handler is called only for regular runtime errors.
412It is not called for memory-allocation errors
413nor for errors while running finalizers or other message handlers.
414
415
416<p>
417Lua also offers a system of <em>warnings</em> (see <a href="#pdf-warn"><code>warn</code></a>).
418Unlike errors, warnings do not interfere
419in any way with program execution.
420They typically only generate a message to the user,
421although this behavior can be adapted from C (see <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>).
422
423
424
425
426
427<h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
428
429<p>
430Every value in Lua can have a <em>metatable</em>.
431This <em>metatable</em> is an ordinary Lua table
432that defines the behavior of the original value
433under certain events.
434You can change several aspects of the behavior
435of a value by setting specific fields in its metatable.
436For instance, when a non-numeric value is the operand of an addition,
437Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
438If it finds one,
439Lua calls this function to perform the addition.
440
441
442<p>
443The key for each event in a metatable is a string
444with the event name prefixed by two underscores;
445the corresponding value is called a <em>metavalue</em>.
446For most events, the metavalue must be a function,
447which is then called a <em>metamethod</em>.
448In the previous example, the key is the string "<code>__add</code>"
449and the metamethod is the function that performs the addition.
450Unless stated otherwise,
451a metamethod may in fact be any callable value,
452which is either a function or a value with a <code>__call</code> metamethod.
453
454
455<p>
456You can query the metatable of any value
457using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
458Lua queries metamethods in metatables using a raw access (see <a href="#pdf-rawget"><code>rawget</code></a>).
459
460
461<p>
462You can replace the metatable of tables
463using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
464You cannot change the metatable of other types from Lua code,
465except by using the debug library (<a href="#6.10">&sect;6.10</a>).
466
467
468<p>
469Tables and full userdata have individual metatables,
470although multiple tables and userdata can share their metatables.
471Values of all other types share one single metatable per type;
472that is, there is one single metatable for all numbers,
473one for all strings, etc.
474By default, a value has no metatable,
475but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
476
477
478<p>
479A detailed list of operations controlled by metatables is given next.
480Each event is identified by its corresponding key.
481By convention, all metatable keys used by Lua are composed by
482two underscores followed by lowercase Latin letters.
483
484
485
486<ul>
487
488<li><b><code>__add</code>: </b>
489the addition (<code>+</code>) operation.
490If any operand for an addition is not a number,
491Lua will try to call a metamethod.
492It starts by checking the first operand (even if it is a number);
493if that operand does not define a metamethod for <code>__add</code>,
494then Lua will check the second operand.
495If Lua can find a metamethod,
496it calls the metamethod with the two operands as arguments,
497and the result of the call
498(adjusted to one value)
499is the result of the operation.
500Otherwise, if no metamethod is found,
501Lua raises an error.
502</li>
503
504<li><b><code>__sub</code>: </b>
505the subtraction (<code>-</code>) operation.
506Behavior similar to the addition operation.
507</li>
508
509<li><b><code>__mul</code>: </b>
510the multiplication (<code>*</code>) operation.
511Behavior similar to the addition operation.
512</li>
513
514<li><b><code>__div</code>: </b>
515the division (<code>/</code>) operation.
516Behavior similar to the addition operation.
517</li>
518
519<li><b><code>__mod</code>: </b>
520the modulo (<code>%</code>) operation.
521Behavior similar to the addition operation.
522</li>
523
524<li><b><code>__pow</code>: </b>
525the exponentiation (<code>^</code>) operation.
526Behavior similar to the addition operation.
527</li>
528
529<li><b><code>__unm</code>: </b>
530the negation (unary <code>-</code>) operation.
531Behavior similar to the addition operation.
532</li>
533
534<li><b><code>__idiv</code>: </b>
535the floor division (<code>//</code>) operation.
536Behavior similar to the addition operation.
537</li>
538
539<li><b><code>__band</code>: </b>
540the bitwise AND (<code>&amp;</code>) operation.
541Behavior similar to the addition operation,
542except that Lua will try a metamethod
543if any operand is neither an integer
544nor a float coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
545</li>
546
547<li><b><code>__bor</code>: </b>
548the bitwise OR (<code>|</code>) operation.
549Behavior similar to the bitwise AND operation.
550</li>
551
552<li><b><code>__bxor</code>: </b>
553the bitwise exclusive OR (binary <code>~</code>) operation.
554Behavior similar to the bitwise AND operation.
555</li>
556
557<li><b><code>__bnot</code>: </b>
558the bitwise NOT (unary <code>~</code>) operation.
559Behavior similar to the bitwise AND operation.
560</li>
561
562<li><b><code>__shl</code>: </b>
563the bitwise left shift (<code>&lt;&lt;</code>) operation.
564Behavior similar to the bitwise AND operation.
565</li>
566
567<li><b><code>__shr</code>: </b>
568the bitwise right shift (<code>&gt;&gt;</code>) operation.
569Behavior similar to the bitwise AND operation.
570</li>
571
572<li><b><code>__concat</code>: </b>
573the concatenation (<code>..</code>) operation.
574Behavior similar to the addition operation,
575except that Lua will try a metamethod
576if any operand is neither a string nor a number
577(which is always coercible to a string).
578</li>
579
580<li><b><code>__len</code>: </b>
581the length (<code>#</code>) operation.
582If the object is not a string,
583Lua will try its metamethod.
584If there is a metamethod,
585Lua calls it with the object as argument,
586and the result of the call
587(always adjusted to one value)
588is the result of the operation.
589If there is no metamethod but the object is a table,
590then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
591Otherwise, Lua raises an error.
592</li>
593
594<li><b><code>__eq</code>: </b>
595the equal (<code>==</code>) operation.
596Behavior similar to the addition operation,
597except that Lua will try a metamethod only when the values
598being compared are either both tables or both full userdata
599and they are not primitively equal.
600The result of the call is always converted to a boolean.
601</li>
602
603<li><b><code>__lt</code>: </b>
604the less than (<code>&lt;</code>) operation.
605Behavior similar to the addition operation,
606except that Lua will try a metamethod only when the values
607being compared are neither both numbers nor both strings.
608Moreover, the result of the call is always converted to a boolean.
609</li>
610
611<li><b><code>__le</code>: </b>
612the less equal (<code>&lt;=</code>) operation.
613Behavior similar to the less than operation.
614</li>
615
616<li><b><code>__index</code>: </b>
617The indexing access operation <code>table[key]</code>.
618This event happens when <code>table</code> is not a table or
619when <code>key</code> is not present in <code>table</code>.
620The metavalue is looked up in the metatable of <code>table</code>.
621
622
623<p>
624The metavalue for this event can be either a function, a table,
625or any value with an <code>__index</code> metavalue.
626If it is a function,
627it is called with <code>table</code> and <code>key</code> as arguments,
628and the result of the call
629(adjusted to one value)
630is the result of the operation.
631Otherwise,
632the final result is the result of indexing this metavalue with <code>key</code>.
633This indexing is regular, not raw,
634and therefore can trigger another <code>__index</code> metavalue.
635</li>
636
637<li><b><code>__newindex</code>: </b>
638The indexing assignment <code>table[key] = value</code>.
639Like the index event,
640this event happens when <code>table</code> is not a table or
641when <code>key</code> is not present in <code>table</code>.
642The metavalue is looked up in the metatable of <code>table</code>.
643
644
645<p>
646Like with indexing,
647the metavalue for this event can be either a function, a table,
648or any value with an <code>__newindex</code> metavalue.
649If it is a function,
650it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
651Otherwise,
652Lua repeats the indexing assignment over this metavalue
653with the same key and value.
654This assignment is regular, not raw,
655and therefore can trigger another <code>__newindex</code> metavalue.
656
657
658<p>
659Whenever a <code>__newindex</code> metavalue is invoked,
660Lua does not perform the primitive assignment.
661If needed,
662the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
663to do the assignment.
664</li>
665
666<li><b><code>__call</code>: </b>
667The call operation <code>func(args)</code>.
668This event happens when Lua tries to call a non-function value
669(that is, <code>func</code> is not a function).
670The metamethod is looked up in <code>func</code>.
671If present,
672the metamethod is called with <code>func</code> as its first argument,
673followed by the arguments of the original call (<code>args</code>).
674All results of the call
675are the results of the operation.
676This is the only metamethod that allows multiple results.
677</li>
678
679</ul>
680
681<p>
682In addition to the previous list,
683the interpreter also respects the following keys in metatables:
684<code>__gc</code> (see <a href="#2.5.3">&sect;2.5.3</a>),
685<code>__close</code> (see <a href="#3.3.8">&sect;3.3.8</a>),
686<code>__mode</code> (see <a href="#2.5.4">&sect;2.5.4</a>),
687and <code>__name</code>.
688(The entry <code>__name</code>,
689when it contains a string,
690may be used by <a href="#pdf-tostring"><code>tostring</code></a> and in error messages.)
691
692
693<p>
694For the unary operators (negation, length, and bitwise NOT),
695the metamethod is computed and called with a dummy second operand,
696equal to the first one.
697This extra operand is only to simplify Lua's internals
698(by making these operators behave like a binary operation)
699and may be removed in future versions.
700For most uses this extra operand is irrelevant.
701
702
703<p>
704Because metatables are regular tables,
705they can contain arbitrary fields,
706not only the event names defined above.
707Some functions in the standard library
708(e.g., <a href="#pdf-tostring"><code>tostring</code></a>)
709use other fields in metatables for their own purposes.
710
711
712<p>
713It is a good practice to add all needed metamethods to a table
714before setting it as a metatable of some object.
715In particular, the <code>__gc</code> metamethod works only when this order
716is followed (see <a href="#2.5.3">&sect;2.5.3</a>).
717It is also a good practice to set the metatable of an object
718right after its creation.
719
720
721
722
723
724<h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
725
726
727
728<p>
729Lua performs automatic memory management.
730This means that
731you do not have to worry about allocating memory for new objects
732or freeing it when the objects are no longer needed.
733Lua manages memory automatically by running
734a <em>garbage collector</em> to collect all <em>dead</em> objects.
735All memory used by Lua is subject to automatic management:
736strings, tables, userdata, functions, threads, internal structures, etc.
737
738
739<p>
740An object is considered <em>dead</em>
741as soon as the collector can be sure the object
742will not be accessed again in the normal execution of the program.
743("Normal execution" here excludes finalizers,
744which can resurrect dead objects (see <a href="#2.5.3">&sect;2.5.3</a>),
745and excludes also operations using the debug library.)
746Note that the time when the collector can be sure that an object
747is dead may not coincide with the programmer's expectations.
748The only guarantees are that Lua will not collect an object
749that may still be accessed in the normal execution of the program,
750and it will eventually collect an object
751that is inaccessible from Lua.
752(Here,
753<em>inaccessible from Lua</em> means that neither a variable nor
754another live object refer to the object.)
755Because Lua has no knowledge about C&nbsp;code,
756it never collects objects accessible through the registry (see <a href="#4.3">&sect;4.3</a>),
757which includes the global environment (see <a href="#2.2">&sect;2.2</a>).
758
759
760<p>
761The garbage collector (GC) in Lua can work in two modes:
762incremental and generational.
763
764
765<p>
766The default GC mode with the default parameters
767are adequate for most uses.
768However, programs that waste a large proportion of their time
769allocating and freeing memory can benefit from other settings.
770Keep in mind that the GC behavior is non-portable
771both across platforms and across different Lua releases;
772therefore, optimal settings are also non-portable.
773
774
775<p>
776You can change the GC mode and parameters by calling
777<a href="#lua_gc"><code>lua_gc</code></a> in&nbsp;C
778or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
779You can also use these functions to control
780the collector directly (e.g., to stop and restart it).
781
782
783
784
785
786<h3>2.5.1 &ndash; <a name="2.5.1">Incremental Garbage Collection</a></h3>
787
788<p>
789In incremental mode,
790each GC cycle performs a mark-and-sweep collection in small steps
791interleaved with the program's execution.
792In this mode,
793the collector uses three numbers to control its garbage-collection cycles:
794the <em>garbage-collector pause</em>,
795the <em>garbage-collector step multiplier</em>,
796and the <em>garbage-collector step size</em>.
797
798
799<p>
800The garbage-collector pause
801controls how long the collector waits before starting a new cycle.
802The collector starts a new cycle when the use of memory
803hits <em>n%</em> of the use after the previous collection.
804Larger values make the collector less aggressive.
805Values equal to or less than 100 mean the collector will not wait to
806start a new cycle.
807A value of 200 means that the collector waits for the total memory in use
808to double before starting a new cycle.
809The default value is 200; the maximum value is 1000.
810
811
812<p>
813The garbage-collector step multiplier
814controls the speed of the collector relative to
815memory allocation,
816that is,
817how many elements it marks or sweeps for each
818kilobyte of memory allocated.
819Larger values make the collector more aggressive but also increase
820the size of each incremental step.
821You should not use values less than 100,
822because they make the collector too slow and
823can result in the collector never finishing a cycle.
824The default value is 100;  the maximum value is 1000.
825
826
827<p>
828The garbage-collector step size controls the
829size of each incremental step,
830specifically how many bytes the interpreter allocates
831before performing a step.
832This parameter is logarithmic:
833A value of <em>n</em> means the interpreter will allocate <em>2<sup>n</sup></em>
834bytes between steps and perform equivalent work during the step.
835A large value (e.g., 60) makes the collector a stop-the-world
836(non-incremental) collector.
837The default value is 13,
838which means steps of approximately 8&nbsp;Kbytes.
839
840
841
842
843
844<h3>2.5.2 &ndash; <a name="2.5.2">Generational Garbage Collection</a></h3>
845
846<p>
847In generational mode,
848the collector does frequent <em>minor</em> collections,
849which traverses only objects recently created.
850If after a minor collection the use of memory is still above a limit,
851the collector does a stop-the-world <em>major</em> collection,
852which traverses all objects.
853The generational mode uses two parameters:
854the <em>minor multiplier</em> and the <em>the major multiplier</em>.
855
856
857<p>
858The minor multiplier controls the frequency of minor collections.
859For a minor multiplier <em>x</em>,
860a new minor collection will be done when memory
861grows <em>x%</em> larger than the memory in use after the previous major
862collection.
863For instance, for a multiplier of 20,
864the collector will do a minor collection when the use of memory
865gets 20% larger than the use after the previous major collection.
866The default value is 20; the maximum value is 200.
867
868
869<p>
870The major multiplier controls the frequency of major collections.
871For a major multiplier <em>x</em>,
872a new major collection will be done when memory
873grows <em>x%</em> larger than the memory in use after the previous major
874collection.
875For instance, for a multiplier of 100,
876the collector will do a major collection when the use of memory
877gets larger than twice the use after the previous collection.
878The default value is 100; the maximum value is 1000.
879
880
881
882
883
884<h3>2.5.3 &ndash; <a name="2.5.3">Garbage-Collection Metamethods</a></h3>
885
886<p>
887You can set garbage-collector metamethods for tables
888and, using the C&nbsp;API,
889for full userdata (see <a href="#2.4">&sect;2.4</a>).
890These metamethods, called <em>finalizers</em>,
891are called when the garbage collector detects that the
892corresponding table or userdata is dead.
893Finalizers allow you to coordinate Lua's garbage collection
894with external resource management such as closing files,
895network or database connections,
896or freeing your own memory.
897
898
899<p>
900For an object (table or userdata) to be finalized when collected,
901you must <em>mark</em> it for finalization.
902
903You mark an object for finalization when you set its metatable
904and the metatable has a field indexed by the string "<code>__gc</code>".
905Note that if you set a metatable without a <code>__gc</code> field
906and later create that field in the metatable,
907the object will not be marked for finalization.
908
909
910<p>
911When a marked object becomes dead,
912it is not collected immediately by the garbage collector.
913Instead, Lua puts it in a list.
914After the collection,
915Lua goes through that list.
916For each object in the list,
917it checks the object's <code>__gc</code> metamethod:
918If it is present,
919Lua calls it with the object as its single argument.
920
921
922<p>
923At the end of each garbage-collection cycle,
924the finalizers are called in
925the reverse order that the objects were marked for finalization,
926among those collected in that cycle;
927that is, the first finalizer to be called is the one associated
928with the object marked last in the program.
929The execution of each finalizer may occur at any point during
930the execution of the regular code.
931
932
933<p>
934Because the object being collected must still be used by the finalizer,
935that object (and other objects accessible only through it)
936must be <em>resurrected</em> by Lua.
937Usually, this resurrection is transient,
938and the object memory is freed in the next garbage-collection cycle.
939However, if the finalizer stores the object in some global place
940(e.g., a global variable),
941then the resurrection is permanent.
942Moreover, if the finalizer marks a finalizing object for finalization again,
943its finalizer will be called again in the next cycle where the
944object is dead.
945In any case,
946the object memory is freed only in a GC cycle where
947the object is dead and not marked for finalization.
948
949
950<p>
951When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
952Lua calls the finalizers of all objects marked for finalization,
953following the reverse order that they were marked.
954If any finalizer marks objects for collection during that phase,
955these marks have no effect.
956
957
958<p>
959Finalizers cannot yield.
960Except for that, they can do anything,
961such as raise errors, create new objects,
962or even run the garbage collector.
963However, because they can run in unpredictable times,
964it is good practice to restrict each finalizer
965to the minimum necessary to properly release
966its associated resource.
967
968
969<p>
970Any error while running a finalizer generates a warning;
971the error is not propagated.
972
973
974
975
976
977<h3>2.5.4 &ndash; <a name="2.5.4">Weak Tables</a></h3>
978
979<p>
980A <em>weak table</em> is a table whose elements are
981<em>weak references</em>.
982A weak reference is ignored by the garbage collector.
983In other words,
984if the only references to an object are weak references,
985then the garbage collector will collect that object.
986
987
988<p>
989A weak table can have weak keys, weak values, or both.
990A table with weak values allows the collection of its values,
991but prevents the collection of its keys.
992A table with both weak keys and weak values allows the collection of
993both keys and values.
994In any case, if either the key or the value is collected,
995the whole pair is removed from the table.
996The weakness of a table is controlled by the
997<code>__mode</code> field of its metatable.
998This metavalue, if present, must be one of the following strings:
999"<code>k</code>", for a table with weak keys;
1000"<code>v</code>", for a table with weak values;
1001or "<code>kv</code>", for a table with both weak keys and values.
1002
1003
1004<p>
1005A table with weak keys and strong values
1006is also called an <em>ephemeron table</em>.
1007In an ephemeron table,
1008a value is considered reachable only if its key is reachable.
1009In particular,
1010if the only reference to a key comes through its value,
1011the pair is removed.
1012
1013
1014<p>
1015Any change in the weakness of a table may take effect only
1016at the next collect cycle.
1017In particular, if you change the weakness to a stronger mode,
1018Lua may still collect some items from that table
1019before the change takes effect.
1020
1021
1022<p>
1023Only objects that have an explicit construction
1024are removed from weak tables.
1025Values, such as numbers and light C&nbsp;functions,
1026are not subject to garbage collection,
1027and therefore are not removed from weak tables
1028(unless their associated values are collected).
1029Although strings are subject to garbage collection,
1030they do not have an explicit construction and
1031their equality is by value;
1032they behave more like values than like objects.
1033Therefore, they are not removed from weak tables.
1034
1035
1036<p>
1037Resurrected objects
1038(that is, objects being finalized
1039and objects accessible only through objects being finalized)
1040have a special behavior in weak tables.
1041They are removed from weak values before running their finalizers,
1042but are removed from weak keys only in the next collection
1043after running their finalizers, when such objects are actually freed.
1044This behavior allows the finalizer to access properties
1045associated with the object through weak tables.
1046
1047
1048<p>
1049If a weak table is among the resurrected objects in a collection cycle,
1050it may not be properly cleared until the next cycle.
1051
1052
1053
1054
1055
1056
1057
1058<h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
1059
1060<p>
1061Lua supports coroutines,
1062also called <em>collaborative multithreading</em>.
1063A coroutine in Lua represents an independent thread of execution.
1064Unlike threads in multithread systems, however,
1065a coroutine only suspends its execution by explicitly calling
1066a yield function.
1067
1068
1069<p>
1070You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1071Its sole argument is a function
1072that is the main function of the coroutine.
1073The <code>create</code> function only creates a new coroutine and
1074returns a handle to it (an object of type <em>thread</em>);
1075it does not start the coroutine.
1076
1077
1078<p>
1079You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1080When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1081passing as its first argument
1082a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1083the coroutine starts its execution by
1084calling its main function.
1085Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
1086as arguments to that function.
1087After the coroutine starts running,
1088it runs until it terminates or <em>yields</em>.
1089
1090
1091<p>
1092A coroutine can terminate its execution in two ways:
1093normally, when its main function returns
1094(explicitly or implicitly, after the last instruction);
1095and abnormally, if there is an unprotected error.
1096In case of normal termination,
1097<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1098plus any values returned by the coroutine main function.
1099In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1100plus the error object.
1101In this case, the coroutine does not unwind its stack,
1102so that it is possible to inspect it after the error
1103with the debug API.
1104
1105
1106<p>
1107A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1108When a coroutine yields,
1109the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1110even if the yield happens inside nested function calls
1111(that is, not in the main function,
1112but in a function directly or indirectly called by the main function).
1113In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1114plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1115The next time you resume the same coroutine,
1116it continues its execution from the point where it yielded,
1117with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1118arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1119
1120
1121<p>
1122Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1123the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1124but instead of returning the coroutine itself,
1125it returns a function that, when called, resumes the coroutine.
1126Any arguments passed to this function
1127go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1128<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>,
1129except the first one (the boolean error code).
1130Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1131the function created by <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>
1132propagates any error to the caller.
1133In this case,
1134the function also closes the coroutine (see <a href="#pdf-coroutine.close"><code>coroutine.close</code></a>).
1135
1136
1137<p>
1138As an example of how coroutines work,
1139consider the following code:
1140
1141<pre>
1142     function foo (a)
1143       print("foo", a)
1144       return coroutine.yield(2*a)
1145     end
1146
1147     co = coroutine.create(function (a,b)
1148           print("co-body", a, b)
1149           local r = foo(a+1)
1150           print("co-body", r)
1151           local r, s = coroutine.yield(a+b, a-b)
1152           print("co-body", r, s)
1153           return b, "end"
1154     end)
1155
1156     print("main", coroutine.resume(co, 1, 10))
1157     print("main", coroutine.resume(co, "r"))
1158     print("main", coroutine.resume(co, "x", "y"))
1159     print("main", coroutine.resume(co, "x", "y"))
1160</pre><p>
1161When you run it, it produces the following output:
1162
1163<pre>
1164     co-body 1       10
1165     foo     2
1166     main    true    4
1167     co-body r
1168     main    true    11      -9
1169     co-body x       y
1170     main    true    10      end
1171     main    false   cannot resume dead coroutine
1172</pre>
1173
1174<p>
1175You can also create and manipulate coroutines through the C API:
1176see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1177and <a href="#lua_yield"><code>lua_yield</code></a>.
1178
1179
1180
1181
1182
1183<h1>3 &ndash; <a name="3">The Language</a></h1>
1184
1185
1186
1187<p>
1188This section describes the lexis, the syntax, and the semantics of Lua.
1189In other words,
1190this section describes
1191which tokens are valid,
1192how they can be combined,
1193and what their combinations mean.
1194
1195
1196<p>
1197Language constructs will be explained using the usual extended BNF notation,
1198in which
1199{<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1200[<em>a</em>]&nbsp;means an optional <em>a</em>.
1201Non-terminals are shown like non-terminal,
1202keywords are shown like <b>kword</b>,
1203and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1204The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1205at the end of this manual.
1206
1207
1208
1209
1210
1211<h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1212
1213<p>
1214Lua is a free-form language.
1215It ignores spaces and comments between lexical elements (tokens),
1216except as delimiters between two tokens.
1217In source code,
1218Lua recognizes as spaces the standard ASCII whitespace
1219characters space, form feed, newline,
1220carriage return, horizontal tab, and vertical tab.
1221
1222
1223<p>
1224<em>Names</em>
1225(also called <em>identifiers</em>)
1226in Lua can be any string of Latin letters,
1227Arabic-Indic digits, and underscores,
1228not beginning with a digit and
1229not being a reserved word.
1230Identifiers are used to name variables, table fields, and labels.
1231
1232
1233<p>
1234The following <em>keywords</em> are reserved
1235and cannot be used as names:
1236
1237
1238<pre>
1239     and       break     do        else      elseif    end
1240     false     for       function  goto      if        in
1241     local     nil       not       or        repeat    return
1242     then      true      until     while
1243</pre>
1244
1245<p>
1246Lua is a case-sensitive language:
1247<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1248are two different, valid names.
1249As a convention,
1250programs should avoid creating
1251names that start with an underscore followed by
1252one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1253
1254
1255<p>
1256The following strings denote other tokens:
1257
1258<pre>
1259     +     -     *     /     %     ^     #
1260     &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
1261     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
1262     (     )     {     }     [     ]     ::
1263     ;     :     ,     .     ..    ...
1264</pre>
1265
1266<p>
1267A <em>short literal string</em>
1268can be delimited by matching single or double quotes,
1269and can contain the following C-like escape sequences:
1270'<code>\a</code>' (bell),
1271'<code>\b</code>' (backspace),
1272'<code>\f</code>' (form feed),
1273'<code>\n</code>' (newline),
1274'<code>\r</code>' (carriage return),
1275'<code>\t</code>' (horizontal tab),
1276'<code>\v</code>' (vertical tab),
1277'<code>\\</code>' (backslash),
1278'<code>\"</code>' (quotation mark [double quote]),
1279and '<code>\'</code>' (apostrophe [single quote]).
1280A backslash followed by a line break
1281results in a newline in the string.
1282The escape sequence '<code>\z</code>' skips the following span
1283of whitespace characters,
1284including line breaks;
1285it is particularly useful to break and indent a long literal string
1286into multiple lines without adding the newlines and spaces
1287into the string contents.
1288A short literal string cannot contain unescaped line breaks
1289nor escapes not forming a valid escape sequence.
1290
1291
1292<p>
1293We can specify any byte in a short literal string,
1294including embedded zeros,
1295by its numeric value.
1296This can be done
1297with the escape sequence <code>\x<em>XX</em></code>,
1298where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1299or with the escape sequence <code>\<em>ddd</em></code>,
1300where <em>ddd</em> is a sequence of up to three decimal digits.
1301(Note that if a decimal escape sequence is to be followed by a digit,
1302it must be expressed using exactly three digits.)
1303
1304
1305<p>
1306The UTF-8 encoding of a Unicode character
1307can be inserted in a literal string with
1308the escape sequence <code>\u{<em>XXX</em>}</code>
1309(with mandatory enclosing braces),
1310where <em>XXX</em> is a sequence of one or more hexadecimal digits
1311representing the character code point.
1312This code point can be any value less than <em>2<sup>31</sup></em>.
1313(Lua uses the original UTF-8 specification here,
1314which is not restricted to valid Unicode code points.)
1315
1316
1317<p>
1318Literal strings can also be defined using a long format
1319enclosed by <em>long brackets</em>.
1320We define an <em>opening long bracket of level <em>n</em></em> as an opening
1321square bracket followed by <em>n</em> equal signs followed by another
1322opening square bracket.
1323So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1324an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1325and so on.
1326A <em>closing long bracket</em> is defined similarly;
1327for instance,
1328a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
1329A <em>long literal</em> starts with an opening long bracket of any level and
1330ends at the first closing long bracket of the same level.
1331It can contain any text except a closing bracket of the same level.
1332Literals in this bracketed form can run for several lines,
1333do not interpret any escape sequences,
1334and ignore long brackets of any other level.
1335Any kind of end-of-line sequence
1336(carriage return, newline, carriage return followed by newline,
1337or newline followed by carriage return)
1338is converted to a simple newline.
1339When the opening long bracket is immediately followed by a newline,
1340the newline is not included in the string.
1341
1342
1343<p>
1344As an example, in a system using ASCII
1345(in which '<code>a</code>' is coded as&nbsp;97,
1346newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1347the five literal strings below denote the same string:
1348
1349<pre>
1350     a = 'alo\n123"'
1351     a = "alo\n123\""
1352     a = '\97lo\10\04923"'
1353     a = [[alo
1354     123"]]
1355     a = [==[
1356     alo
1357     123"]==]
1358</pre>
1359
1360<p>
1361Any byte in a literal string not
1362explicitly affected by the previous rules represents itself.
1363However, Lua opens files for parsing in text mode,
1364and the system's file functions may have problems with
1365some control characters.
1366So, it is safer to represent
1367binary data as a quoted literal with
1368explicit escape sequences for the non-text characters.
1369
1370
1371<p>
1372A <em>numeric constant</em> (or <em>numeral</em>)
1373can be written with an optional fractional part
1374and an optional decimal exponent,
1375marked by a letter '<code>e</code>' or '<code>E</code>'.
1376Lua also accepts hexadecimal constants,
1377which start with <code>0x</code> or <code>0X</code>.
1378Hexadecimal constants also accept an optional fractional part
1379plus an optional binary exponent,
1380marked by a letter '<code>p</code>' or '<code>P</code>'.
1381
1382
1383<p>
1384A numeric constant with a radix point or an exponent
1385denotes a float;
1386otherwise,
1387if its value fits in an integer or it is a hexadecimal constant,
1388it denotes an integer;
1389otherwise (that is, a decimal integer numeral that overflows),
1390it denotes a float.
1391Hexadecimal numerals with neither a radix point nor an exponent
1392always denote an integer value;
1393if the value overflows, it <em>wraps around</em>
1394to fit into a valid integer.
1395
1396
1397<p>
1398Examples of valid integer constants are
1399
1400<pre>
1401     3   345   0xff   0xBEBADA
1402</pre><p>
1403Examples of valid float constants are
1404
1405<pre>
1406     3.0     3.1416     314.16e-2     0.31416E1     34e1
1407     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
1408</pre>
1409
1410<p>
1411A <em>comment</em> starts with a double hyphen (<code>--</code>)
1412anywhere outside a string.
1413If the text immediately after <code>--</code> is not an opening long bracket,
1414the comment is a <em>short comment</em>,
1415which runs until the end of the line.
1416Otherwise, it is a <em>long comment</em>,
1417which runs until the corresponding closing long bracket.
1418
1419
1420
1421
1422
1423<h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1424
1425<p>
1426Variables are places that store values.
1427There are three kinds of variables in Lua:
1428global variables, local variables, and table fields.
1429
1430
1431<p>
1432A single name can denote a global variable or a local variable
1433(or a function's formal parameter,
1434which is a particular kind of local variable):
1435
1436<pre>
1437	var ::= Name
1438</pre><p>
1439Name denotes identifiers (see <a href="#3.1">&sect;3.1</a>).
1440
1441
1442<p>
1443Any variable name is assumed to be global unless explicitly declared
1444as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1445Local variables are <em>lexically scoped</em>:
1446local variables can be freely accessed by functions
1447defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1448
1449
1450<p>
1451Before the first assignment to a variable, its value is <b>nil</b>.
1452
1453
1454<p>
1455Square brackets are used to index a table:
1456
1457<pre>
1458	var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1459</pre><p>
1460The meaning of accesses to table fields can be changed via metatables
1461(see <a href="#2.4">&sect;2.4</a>).
1462
1463
1464<p>
1465The syntax <code>var.Name</code> is just syntactic sugar for
1466<code>var["Name"]</code>:
1467
1468<pre>
1469	var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1470</pre>
1471
1472<p>
1473An access to a global variable <code>x</code>
1474is equivalent to <code>_ENV.x</code>.
1475Due to the way that chunks are compiled,
1476the variable <code>_ENV</code> itself is never global (see <a href="#2.2">&sect;2.2</a>).
1477
1478
1479
1480
1481
1482<h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1483
1484
1485
1486<p>
1487Lua supports an almost conventional set of statements,
1488similar to those in other conventional languages.
1489This set includes
1490blocks, assignments, control structures, function calls,
1491and variable declarations.
1492
1493
1494
1495
1496
1497<h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1498
1499<p>
1500A block is a list of statements,
1501which are executed sequentially:
1502
1503<pre>
1504	block ::= {stat}
1505</pre><p>
1506Lua has <em>empty statements</em>
1507that allow you to separate statements with semicolons,
1508start a block with a semicolon
1509or write two semicolons in sequence:
1510
1511<pre>
1512	stat ::= &lsquo;<b>;</b>&rsquo;
1513</pre>
1514
1515<p>
1516Both function calls and assignments
1517can start with an open parenthesis.
1518This possibility leads to an ambiguity in Lua's grammar.
1519Consider the following fragment:
1520
1521<pre>
1522     a = b + c
1523     (print or io.write)('done')
1524</pre><p>
1525The grammar could see this fragment in two ways:
1526
1527<pre>
1528     a = b + c(print or io.write)('done')
1529
1530     a = b + c; (print or io.write)('done')
1531</pre><p>
1532The current parser always sees such constructions
1533in the first way,
1534interpreting the open parenthesis
1535as the start of the arguments to a call.
1536To avoid this ambiguity,
1537it is a good practice to always precede with a semicolon
1538statements that start with a parenthesis:
1539
1540<pre>
1541     ;(print or io.write)('done')
1542</pre>
1543
1544<p>
1545A block can be explicitly delimited to produce a single statement:
1546
1547<pre>
1548	stat ::= <b>do</b> block <b>end</b>
1549</pre><p>
1550Explicit blocks are useful
1551to control the scope of variable declarations.
1552Explicit blocks are also sometimes used to
1553add a <b>return</b> statement in the middle
1554of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1555
1556
1557
1558
1559
1560<h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1561
1562<p>
1563The unit of compilation of Lua is called a <em>chunk</em>.
1564Syntactically,
1565a chunk is simply a block:
1566
1567<pre>
1568	chunk ::= block
1569</pre>
1570
1571<p>
1572Lua handles a chunk as the body of an anonymous function
1573with a variable number of arguments
1574(see <a href="#3.4.11">&sect;3.4.11</a>).
1575As such, chunks can define local variables,
1576receive arguments, and return values.
1577Moreover, such anonymous function is compiled as in the
1578scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1579The resulting function always has <code>_ENV</code> as its only external variable,
1580even if it does not use that variable.
1581
1582
1583<p>
1584A chunk can be stored in a file or in a string inside the host program.
1585To execute a chunk,
1586Lua first <em>loads</em> it,
1587precompiling the chunk's code into instructions for a virtual machine,
1588and then Lua executes the compiled code
1589with an interpreter for the virtual machine.
1590
1591
1592<p>
1593Chunks can also be precompiled into binary form;
1594see the program <code>luac</code> and the function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1595Programs in source and compiled forms are interchangeable;
1596Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1597
1598
1599
1600
1601
1602<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1603
1604<p>
1605Lua allows multiple assignments.
1606Therefore, the syntax for assignment
1607defines a list of variables on the left side
1608and a list of expressions on the right side.
1609The elements in both lists are separated by commas:
1610
1611<pre>
1612	stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1613	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1614	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1615</pre><p>
1616Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1617
1618
1619<p>
1620Before the assignment,
1621the list of values is <em>adjusted</em> to the length of
1622the list of variables.
1623If there are more values than needed,
1624the excess values are thrown away.
1625If there are fewer values than needed,
1626the list is extended with <b>nil</b>'s.
1627If the list of expressions ends with a function call,
1628then all values returned by that call enter the list of values,
1629before the adjustment
1630(except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1631
1632
1633<p>
1634The assignment statement first evaluates all its expressions
1635and only then the assignments are performed.
1636Thus the code
1637
1638<pre>
1639     i = 3
1640     i, a[i] = i+1, 20
1641</pre><p>
1642sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1643because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1644before it is assigned&nbsp;4.
1645Similarly, the line
1646
1647<pre>
1648     x, y = y, x
1649</pre><p>
1650exchanges the values of <code>x</code> and <code>y</code>,
1651and
1652
1653<pre>
1654     x, y, z = y, z, x
1655</pre><p>
1656cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1657
1658
1659<p>
1660An assignment to a global name <code>x = val</code>
1661is equivalent to the assignment
1662<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1663
1664
1665<p>
1666The meaning of assignments to table fields and
1667global variables (which are actually table fields, too)
1668can be changed via metatables (see <a href="#2.4">&sect;2.4</a>).
1669
1670
1671
1672
1673
1674<h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1675The control structures
1676<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1677familiar syntax:
1678
1679
1680
1681
1682<pre>
1683	stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1684	stat ::= <b>repeat</b> block <b>until</b> exp
1685	stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1686</pre><p>
1687Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1688
1689
1690<p>
1691The condition expression of a
1692control structure can return any value.
1693Both <b>false</b> and <b>nil</b> test false.
1694All values different from <b>nil</b> and <b>false</b> test true.
1695In particular, the number 0 and the empty string also test true.
1696
1697
1698<p>
1699In the <b>repeat</b>&ndash;<b>until</b> loop,
1700the inner block does not end at the <b>until</b> keyword,
1701but only after the condition.
1702So, the condition can refer to local variables
1703declared inside the loop block.
1704
1705
1706<p>
1707The <b>goto</b> statement transfers the program control to a label.
1708For syntactical reasons,
1709labels in Lua are considered statements too:
1710
1711
1712
1713<pre>
1714	stat ::= <b>goto</b> Name
1715	stat ::= label
1716	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1717</pre>
1718
1719<p>
1720A label is visible in the entire block where it is defined,
1721except inside nested functions.
1722A goto may jump to any visible label as long as it does not
1723enter into the scope of a local variable.
1724A label should not be declared
1725where a label with the same name is visible,
1726even if this other label has been declared in an enclosing block.
1727
1728
1729<p>
1730Labels and empty statements are called <em>void statements</em>,
1731as they perform no actions.
1732
1733
1734<p>
1735The <b>break</b> statement terminates the execution of a
1736<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1737skipping to the next statement after the loop:
1738
1739
1740<pre>
1741	stat ::= <b>break</b>
1742</pre><p>
1743A <b>break</b> ends the innermost enclosing loop.
1744
1745
1746<p>
1747The <b>return</b> statement is used to return values
1748from a function or a chunk
1749(which is handled as an anonymous function).
1750
1751Functions can return more than one value,
1752so the syntax for the <b>return</b> statement is
1753
1754<pre>
1755	stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1756</pre>
1757
1758<p>
1759The <b>return</b> statement can only be written
1760as the last statement of a block.
1761If it is necessary to <b>return</b> in the middle of a block,
1762then an explicit inner block can be used,
1763as in the idiom <code>do return end</code>,
1764because now <b>return</b> is the last statement in its (inner) block.
1765
1766
1767
1768
1769
1770<h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1771
1772<p>
1773
1774The <b>for</b> statement has two forms:
1775one numerical and one generic.
1776
1777
1778
1779<h4>The numerical <b>for</b> loop</h4>
1780
1781<p>
1782The numerical <b>for</b> loop repeats a block of code while a
1783control variable goes through an arithmetic progression.
1784It has the following syntax:
1785
1786<pre>
1787	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>
1788</pre><p>
1789The given identifier (Name) defines the control variable,
1790which is a new variable local to the loop body (<em>block</em>).
1791
1792
1793<p>
1794The loop starts by evaluating once the three control expressions.
1795Their values are called respectively
1796the <em>initial value</em>, the <em>limit</em>, and the <em>step</em>.
1797If the step is absent, it defaults to&nbsp;1.
1798
1799
1800<p>
1801If both the initial value and the step are integers,
1802the loop is done with integers;
1803note that the limit may not be an integer.
1804Otherwise, the three values are converted to
1805floats and the loop is done with floats.
1806Beware of floating-point accuracy in this case.
1807
1808
1809<p>
1810After that initialization,
1811the loop body is repeated with the value of the control variable
1812going through an arithmetic progression,
1813starting at the initial value,
1814with a common difference given by the step.
1815A negative step makes a decreasing sequence;
1816a step equal to zero raises an error.
1817The loop continues while the value is less than
1818or equal to the limit
1819(greater than or equal to for a negative step).
1820If the initial value is already greater than the limit
1821(or less than, if the step is negative),
1822the body is not executed.
1823
1824
1825<p>
1826For integer loops,
1827the control variable never wraps around;
1828instead, the loop ends in case of an overflow.
1829
1830
1831<p>
1832You should not change the value of the control variable
1833during the loop.
1834If you need its value after the loop,
1835assign it to another variable before exiting the loop.
1836
1837
1838
1839
1840
1841<h4>The generic <b>for</b> loop</h4>
1842
1843<p>
1844The generic <b>for</b> statement works over functions,
1845called <em>iterators</em>.
1846On each iteration, the iterator function is called to produce a new value,
1847stopping when this new value is <b>nil</b>.
1848The generic <b>for</b> loop has the following syntax:
1849
1850<pre>
1851	stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1852	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1853</pre><p>
1854A <b>for</b> statement like
1855
1856<pre>
1857     for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>body</em> end
1858</pre><p>
1859works as follows.
1860
1861
1862<p>
1863The names <em>var_i</em> declare loop variables local to the loop body.
1864The first of these variables is the <em>control variable</em>.
1865
1866
1867<p>
1868The loop starts by evaluating <em>explist</em>
1869to produce four values:
1870an <em>iterator function</em>,
1871a <em>state</em>,
1872an initial value for the control variable,
1873and a <em>closing value</em>.
1874
1875
1876<p>
1877Then, at each iteration,
1878Lua calls the iterator function with two arguments:
1879the state and the control variable.
1880The results from this call are then assigned to the loop variables,
1881following the rules of multiple assignments (see <a href="#3.3.3">&sect;3.3.3</a>).
1882If the control variable becomes <b>nil</b>,
1883the loop terminates.
1884Otherwise, the body is executed and the loop goes
1885to the next iteration.
1886
1887
1888<p>
1889The closing value behaves like a
1890to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>),
1891which can be used to release resources when the loop ends.
1892Otherwise, it does not interfere with the loop.
1893
1894
1895<p>
1896You should not change the value of the control variable
1897during the loop.
1898
1899
1900
1901
1902
1903
1904
1905<h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1906To allow possible side-effects,
1907function calls can be executed as statements:
1908
1909<pre>
1910	stat ::= functioncall
1911</pre><p>
1912In this case, all returned values are thrown away.
1913Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1914
1915
1916
1917
1918
1919<h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1920Local variables can be declared anywhere inside a block.
1921The declaration can include an initialization:
1922
1923<pre>
1924	stat ::= <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
1925	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
1926</pre><p>
1927If present, an initial assignment has the same semantics
1928of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1929Otherwise, all variables are initialized with <b>nil</b>.
1930
1931
1932<p>
1933Each variable name may be postfixed by an attribute
1934(a name between angle brackets):
1935
1936<pre>
1937	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
1938</pre><p>
1939There are two possible attributes:
1940<code>const</code>, which declares a constant variable,
1941that is, a variable that cannot be assigned to
1942after its initialization;
1943and <code>close</code>, which declares a to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>).
1944A list of variables can contain at most one to-be-closed variable.
1945
1946
1947<p>
1948A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1949and so local variables can be declared in a chunk outside any explicit block.
1950
1951
1952<p>
1953The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1954
1955
1956
1957
1958
1959<h3>3.3.8 &ndash; <a name="3.3.8">To-be-closed Variables</a></h3>
1960
1961<p>
1962A to-be-closed variable behaves like a constant local variable,
1963except that its value is <em>closed</em> whenever the variable
1964goes out of scope, including normal block termination,
1965exiting its block by <b>break</b>/<b>goto</b>/<b>return</b>,
1966or exiting by an error.
1967
1968
1969<p>
1970Here, to <em>close</em> a value means
1971to call its <code>__close</code> metamethod.
1972When calling the metamethod,
1973the value itself is passed as the first argument
1974and the error object that caused the exit (if any)
1975is passed as a second argument;
1976if there was no error, the second argument is <b>nil</b>.
1977
1978
1979<p>
1980The value assigned to a to-be-closed variable
1981must have a <code>__close</code> metamethod
1982or be a false value.
1983(<b>nil</b> and <b>false</b> are ignored as to-be-closed values.)
1984
1985
1986<p>
1987If several to-be-closed variables go out of scope at the same event,
1988they are closed in the reverse order that they were declared.
1989
1990
1991<p>
1992If there is any error while running a closing method,
1993that error is handled like an error in the regular code
1994where the variable was defined.
1995However, Lua may call the method one more time.
1996
1997
1998<p>
1999After an error,
2000the other pending closing methods will still be called.
2001Errors in these methods
2002interrupt the respective method and generate a warning,
2003but are otherwise ignored;
2004the error reported is only the original one.
2005
2006
2007<p>
2008If a coroutine yields and is never resumed again,
2009some variables may never go out of scope,
2010and therefore they will never be closed.
2011(These variables are the ones created inside the coroutine
2012and in scope at the point where the coroutine yielded.)
2013Similarly, if a coroutine ends with an error,
2014it does not unwind its stack,
2015so it does not close any variable.
2016In both cases,
2017you can either use finalizers
2018or call <a href="#pdf-coroutine.close"><code>coroutine.close</code></a> to close the variables.
2019However, if the coroutine was created
2020through <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>,
2021then its corresponding function will close the coroutine
2022in case of errors.
2023
2024
2025
2026
2027
2028
2029
2030<h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
2031
2032
2033
2034<p>
2035The basic expressions in Lua are the following:
2036
2037<pre>
2038	exp ::= prefixexp
2039	exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
2040	exp ::= Numeral
2041	exp ::= LiteralString
2042	exp ::= functiondef
2043	exp ::= tableconstructor
2044	exp ::= &lsquo;<b>...</b>&rsquo;
2045	exp ::= exp binop exp
2046	exp ::= unop exp
2047	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
2048</pre>
2049
2050<p>
2051Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
2052variables are explained in <a href="#3.2">&sect;3.2</a>;
2053function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
2054function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
2055table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
2056Vararg expressions,
2057denoted by three dots ('<code>...</code>'), can only be used when
2058directly inside a vararg function;
2059they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
2060
2061
2062<p>
2063Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
2064bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
2065relational 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>),
2066and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
2067Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
2068the unary bitwise NOT (see <a href="#3.4.2">&sect;3.4.2</a>),
2069the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
2070and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
2071
2072
2073<p>
2074Both function calls and vararg expressions can result in multiple values.
2075If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
2076then its return list is adjusted to zero elements,
2077thus discarding all returned values.
2078If an expression is used as the last (or the only) element
2079of a list of expressions,
2080then no adjustment is made
2081(unless the expression is enclosed in parentheses).
2082In all other contexts,
2083Lua adjusts the result list to one element,
2084either discarding all values except the first one
2085or adding a single <b>nil</b> if there are no values.
2086
2087
2088<p>
2089Here are some examples:
2090
2091<pre>
2092     f()                -- adjusted to 0 results
2093     g(f(), x)          -- f() is adjusted to 1 result
2094     g(x, f())          -- g gets x plus all results from f()
2095     a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
2096     a,b = ...          -- a gets the first vararg argument, b gets
2097                        -- the second (both a and b can get nil if there
2098                        -- is no corresponding vararg argument)
2099
2100     a,b,c = x, f()     -- f() is adjusted to 2 results
2101     a,b,c = f()        -- f() is adjusted to 3 results
2102     return f()         -- returns all results from f()
2103     return ...         -- returns all received vararg arguments
2104     return x,y,f()     -- returns x, y, and all results from f()
2105     {f()}              -- creates a list with all results from f()
2106     {...}              -- creates a list with all vararg arguments
2107     {f(), nil}         -- f() is adjusted to 1 result
2108</pre>
2109
2110<p>
2111Any expression enclosed in parentheses always results in only one value.
2112Thus,
2113<code>(f(x,y,z))</code> is always a single value,
2114even if <code>f</code> returns several values.
2115(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
2116or <b>nil</b> if <code>f</code> does not return any values.)
2117
2118
2119
2120
2121
2122<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
2123Lua supports the following arithmetic operators:
2124
2125<ul>
2126<li><b><code>+</code>: </b>addition</li>
2127<li><b><code>-</code>: </b>subtraction</li>
2128<li><b><code>*</code>: </b>multiplication</li>
2129<li><b><code>/</code>: </b>float division</li>
2130<li><b><code>//</code>: </b>floor division</li>
2131<li><b><code>%</code>: </b>modulo</li>
2132<li><b><code>^</code>: </b>exponentiation</li>
2133<li><b><code>-</code>: </b>unary minus</li>
2134</ul>
2135
2136<p>
2137With the exception of exponentiation and float division,
2138the arithmetic operators work as follows:
2139If both operands are integers,
2140the operation is performed over integers and the result is an integer.
2141Otherwise, if both operands are numbers,
2142then they are converted to floats,
2143the operation is performed following the machine's rules
2144for floating-point arithmetic
2145(usually the IEEE 754 standard),
2146and the result is a float.
2147(The string library coerces strings to numbers in
2148arithmetic operations; see <a href="#3.4.3">&sect;3.4.3</a> for details.)
2149
2150
2151<p>
2152Exponentiation and float division (<code>/</code>)
2153always convert their operands to floats
2154and the result is always a float.
2155Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
2156so that it works for non-integer exponents too.
2157
2158
2159<p>
2160Floor division (<code>//</code>) is a division
2161that rounds the quotient towards minus infinity,
2162resulting in the floor of the division of its operands.
2163
2164
2165<p>
2166Modulo is defined as the remainder of a division
2167that rounds the quotient towards minus infinity (floor division).
2168
2169
2170<p>
2171In case of overflows in integer arithmetic,
2172all operations <em>wrap around</em>.
2173
2174
2175
2176<h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
2177Lua supports the following bitwise operators:
2178
2179<ul>
2180<li><b><code>&amp;</code>: </b>bitwise AND</li>
2181<li><b><code>&#124;</code>: </b>bitwise OR</li>
2182<li><b><code>~</code>: </b>bitwise exclusive OR</li>
2183<li><b><code>&gt;&gt;</code>: </b>right shift</li>
2184<li><b><code>&lt;&lt;</code>: </b>left shift</li>
2185<li><b><code>~</code>: </b>unary bitwise NOT</li>
2186</ul>
2187
2188<p>
2189All bitwise operations convert its operands to integers
2190(see <a href="#3.4.3">&sect;3.4.3</a>),
2191operate on all bits of those integers,
2192and result in an integer.
2193
2194
2195<p>
2196Both right and left shifts fill the vacant bits with zeros.
2197Negative displacements shift to the other direction;
2198displacements with absolute values equal to or higher than
2199the number of bits in an integer
2200result in zero (as all bits are shifted out).
2201
2202
2203
2204
2205
2206<h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
2207Lua provides some automatic conversions between some
2208types and representations at run time.
2209Bitwise operators always convert float operands to integers.
2210Exponentiation and float division
2211always convert integer operands to floats.
2212All other arithmetic operations applied to mixed numbers
2213(integers and floats) convert the integer operand to a float.
2214The C API also converts both integers to floats and
2215floats to integers, as needed.
2216Moreover, string concatenation accepts numbers as arguments,
2217besides strings.
2218
2219
2220<p>
2221In a conversion from integer to float,
2222if the integer value has an exact representation as a float,
2223that is the result.
2224Otherwise,
2225the conversion gets the nearest higher or
2226the nearest lower representable value.
2227This kind of conversion never fails.
2228
2229
2230<p>
2231The conversion from float to integer
2232checks whether the float has an exact representation as an integer
2233(that is, the float has an integral value and
2234it is in the range of integer representation).
2235If it does, that representation is the result.
2236Otherwise, the conversion fails.
2237
2238
2239<p>
2240Several places in Lua coerce strings to numbers when necessary.
2241In particular,
2242the string library sets metamethods that try to coerce
2243strings to numbers in all arithmetic operations.
2244If the conversion fails,
2245the library calls the metamethod of the other operand
2246(if present) or it raises an error.
2247Note that bitwise operators do not do this coercion.
2248
2249
2250<p>
2251Nonetheless, it is always a good practice not to rely on these
2252implicit coercions, as they are not always applied;
2253in particular, <code>"1"==1</code> is false and <code>"1"&lt;1</code> raises an error
2254(see <a href="#3.4.4">&sect;3.4.4</a>).
2255These coercions exist mainly for compatibility and may be removed
2256in future versions of the language.
2257
2258
2259<p>
2260A string is converted to an integer or a float
2261following its syntax and the rules of the Lua lexer.
2262The string may have also leading and trailing whitespaces and a sign.
2263All conversions from strings to numbers
2264accept both a dot and the current locale mark
2265as the radix character.
2266(The Lua lexer, however, accepts only a dot.)
2267If the string is not a valid numeral,
2268the conversion fails.
2269If necessary, the result of this first step is then converted
2270to a specific number subtype following the previous rules
2271for conversions between floats and integers.
2272
2273
2274<p>
2275The conversion from numbers to strings uses a
2276non-specified human-readable format.
2277To convert numbers to strings in any specific way,
2278use the function <a href="#pdf-string.format"><code>string.format</code></a>.
2279
2280
2281
2282
2283
2284<h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
2285Lua supports the following relational operators:
2286
2287<ul>
2288<li><b><code>==</code>: </b>equality</li>
2289<li><b><code>~=</code>: </b>inequality</li>
2290<li><b><code>&lt;</code>: </b>less than</li>
2291<li><b><code>&gt;</code>: </b>greater than</li>
2292<li><b><code>&lt;=</code>: </b>less or equal</li>
2293<li><b><code>&gt;=</code>: </b>greater or equal</li>
2294</ul><p>
2295These operators always result in <b>false</b> or <b>true</b>.
2296
2297
2298<p>
2299Equality (<code>==</code>) first compares the type of its operands.
2300If the types are different, then the result is <b>false</b>.
2301Otherwise, the values of the operands are compared.
2302Strings are equal if they have the same byte content.
2303Numbers are equal if they denote the same mathematical value.
2304
2305
2306<p>
2307Tables, userdata, and threads
2308are compared by reference:
2309two objects are considered equal only if they are the same object.
2310Every time you create a new object
2311(a table, a userdata, or a thread),
2312this new object is different from any previously existing object.
2313A function is always equal to itself.
2314Functions with any detectable difference
2315(different behavior, different definition) are always different.
2316Functions created at different times but with no detectable differences
2317may be classified as equal or not
2318(depending on internal caching details).
2319
2320
2321<p>
2322You can change the way that Lua compares tables and userdata
2323by using the <code>__eq</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2324
2325
2326<p>
2327Equality comparisons do not convert strings to numbers
2328or vice versa.
2329Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2330and <code>t[0]</code> and <code>t["0"]</code> denote different
2331entries in a table.
2332
2333
2334<p>
2335The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2336
2337
2338<p>
2339The order operators work as follows.
2340If both arguments are numbers,
2341then they are compared according to their mathematical values,
2342regardless of their subtypes.
2343Otherwise, if both arguments are strings,
2344then their values are compared according to the current locale.
2345Otherwise, Lua tries to call the <code>__lt</code> or the <code>__le</code>
2346metamethod (see <a href="#2.4">&sect;2.4</a>).
2347A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2348and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2349
2350
2351<p>
2352Following the IEEE 754 standard,
2353the special value NaN is considered neither less than,
2354nor equal to, nor greater than any value, including itself.
2355
2356
2357
2358
2359
2360<h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2361The logical operators in Lua are
2362<b>and</b>, <b>or</b>, and <b>not</b>.
2363Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2364all logical operators consider both <b>false</b> and <b>nil</b> as false
2365and anything else as true.
2366
2367
2368<p>
2369The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2370The conjunction operator <b>and</b> returns its first argument
2371if this value is <b>false</b> or <b>nil</b>;
2372otherwise, <b>and</b> returns its second argument.
2373The disjunction operator <b>or</b> returns its first argument
2374if this value is different from <b>nil</b> and <b>false</b>;
2375otherwise, <b>or</b> returns its second argument.
2376Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2377that is,
2378the second operand is evaluated only if necessary.
2379Here are some examples:
2380
2381<pre>
2382     10 or 20            --&gt; 10
2383     10 or error()       --&gt; 10
2384     nil or "a"          --&gt; "a"
2385     nil and 10          --&gt; nil
2386     false and error()   --&gt; false
2387     false and nil       --&gt; false
2388     false or nil        --&gt; nil
2389     10 and 20           --&gt; 20
2390</pre>
2391
2392
2393
2394
2395<h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2396The string concatenation operator in Lua is
2397denoted by two dots ('<code>..</code>').
2398If both operands are strings or numbers,
2399then the numbers are converted to strings
2400in a non-specified format (see <a href="#3.4.3">&sect;3.4.3</a>).
2401Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2402
2403
2404
2405
2406
2407<h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2408
2409<p>
2410The length operator is denoted by the unary prefix operator <code>#</code>.
2411
2412
2413<p>
2414The length of a string is its number of bytes.
2415(That is the usual meaning of string length when each
2416character is one byte.)
2417
2418
2419<p>
2420The length operator applied on a table
2421returns a border in that table.
2422A <em>border</em> in a table <code>t</code> is any natural number
2423that satisfies the following condition:
2424
2425<pre>
2426     (border == 0 or t[border] ~= nil) and t[border + 1] == nil
2427</pre><p>
2428In words,
2429a border is any (natural) index present in the table
2430that is followed by an absent index
2431(or zero, when index 1 is absent).
2432
2433
2434<p>
2435A table with exactly one border is called a <em>sequence</em>.
2436For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence,
2437as it has only one border (5).
2438The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5),
2439and therefore it is not a sequence.
2440(The <b>nil</b> at index 4 is called a <em>hole</em>.)
2441The table <code>{nil, 20, 30, nil, nil, 60, nil}</code>
2442has three borders (0, 3, and 6) and three holes
2443(at indices 1, 4, and 5),
2444so it is not a sequence, too.
2445The table <code>{}</code> is a sequence with border 0.
2446Note that non-natural keys do not interfere
2447with whether a table is a sequence.
2448
2449
2450<p>
2451When <code>t</code> is a sequence,
2452<code>#t</code> returns its only border,
2453which corresponds to the intuitive notion of the length of the sequence.
2454When <code>t</code> is not a sequence,
2455<code>#t</code> can return any of its borders.
2456(The exact one depends on details of
2457the internal representation of the table,
2458which in turn can depend on how the table was populated and
2459the memory addresses of its non-numeric keys.)
2460
2461
2462<p>
2463The computation of the length of a table
2464has a guaranteed worst time of <em>O(log n)</em>,
2465where <em>n</em> is the largest natural key in the table.
2466
2467
2468<p>
2469A program can modify the behavior of the length operator for
2470any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2471
2472
2473
2474
2475
2476<h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2477Operator precedence in Lua follows the table below,
2478from lower to higher priority:
2479
2480<pre>
2481     or
2482     and
2483     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2484     |
2485     ~
2486     &amp;
2487     &lt;&lt;    &gt;&gt;
2488     ..
2489     +     -
2490     *     /     //    %
2491     unary operators (not   #     -     ~)
2492     ^
2493</pre><p>
2494As usual,
2495you can use parentheses to change the precedences of an expression.
2496The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2497operators are right associative.
2498All other binary operators are left associative.
2499
2500
2501
2502
2503
2504<h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2505Table constructors are expressions that create tables.
2506Every time a constructor is evaluated, a new table is created.
2507A constructor can be used to create an empty table
2508or to create a table and initialize some of its fields.
2509The general syntax for constructors is
2510
2511<pre>
2512	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2513	fieldlist ::= field {fieldsep field} [fieldsep]
2514	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2515	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2516</pre>
2517
2518<p>
2519Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2520with key <code>exp1</code> and value <code>exp2</code>.
2521A field of the form <code>name = exp</code> is equivalent to
2522<code>["name"] = exp</code>.
2523Fields of the form <code>exp</code> are equivalent to
2524<code>[i] = exp</code>, where <code>i</code> are consecutive integers
2525starting with 1;
2526fields in the other formats do not affect this counting.
2527For example,
2528
2529<pre>
2530     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2531</pre><p>
2532is equivalent to
2533
2534<pre>
2535     do
2536       local t = {}
2537       t[f(1)] = g
2538       t[1] = "x"         -- 1st exp
2539       t[2] = "y"         -- 2nd exp
2540       t.x = 1            -- t["x"] = 1
2541       t[3] = f(x)        -- 3rd exp
2542       t[30] = 23
2543       t[4] = 45          -- 4th exp
2544       a = t
2545     end
2546</pre>
2547
2548<p>
2549The order of the assignments in a constructor is undefined.
2550(This order would be relevant only when there are repeated keys.)
2551
2552
2553<p>
2554If the last field in the list has the form <code>exp</code>
2555and the expression is a function call or a vararg expression,
2556then all values returned by this expression enter the list consecutively
2557(see <a href="#3.4.10">&sect;3.4.10</a>).
2558
2559
2560<p>
2561The field list can have an optional trailing separator,
2562as a convenience for machine-generated code.
2563
2564
2565
2566
2567
2568<h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2569A function call in Lua has the following syntax:
2570
2571<pre>
2572	functioncall ::= prefixexp args
2573</pre><p>
2574In a function call,
2575first prefixexp and args are evaluated.
2576If the value of prefixexp has type <em>function</em>,
2577then this function is called
2578with the given arguments.
2579Otherwise, if present,
2580the prefixexp <code>__call</code> metamethod is called:
2581its first argument is the value of prefixexp,
2582followed by the original call arguments
2583(see <a href="#2.4">&sect;2.4</a>).
2584
2585
2586<p>
2587The form
2588
2589<pre>
2590	functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2591</pre><p>
2592can be used to emulate methods.
2593A call <code>v:name(<em>args</em>)</code>
2594is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2595except that <code>v</code> is evaluated only once.
2596
2597
2598<p>
2599Arguments have the following syntax:
2600
2601<pre>
2602	args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2603	args ::= tableconstructor
2604	args ::= LiteralString
2605</pre><p>
2606All argument expressions are evaluated before the call.
2607A call of the form <code>f{<em>fields</em>}</code> is
2608syntactic sugar for <code>f({<em>fields</em>})</code>;
2609that is, the argument list is a single new table.
2610A call of the form <code>f'<em>string</em>'</code>
2611(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2612is syntactic sugar for <code>f('<em>string</em>')</code>;
2613that is, the argument list is a single literal string.
2614
2615
2616<p>
2617A call of the form <code>return <em>functioncall</em></code> not in the
2618scope of a to-be-closed variable is called a <em>tail call</em>.
2619Lua implements <em>proper tail calls</em>
2620(or <em>proper tail recursion</em>):
2621in a tail call,
2622the called function reuses the stack entry of the calling function.
2623Therefore, there is no limit on the number of nested tail calls that
2624a program can execute.
2625However, a tail call erases any debug information about the
2626calling function.
2627Note that a tail call only happens with a particular syntax,
2628where the <b>return</b> has one single function call as argument,
2629and it is outside the scope of any to-be-closed variable.
2630This syntax makes the calling function return exactly
2631the returns of the called function,
2632without any intervening action.
2633So, none of the following examples are tail calls:
2634
2635<pre>
2636     return (f(x))        -- results adjusted to 1
2637     return 2 * f(x)      -- result multiplied by 2
2638     return x, f(x)       -- additional results
2639     f(x); return         -- results discarded
2640     return x or f(x)     -- results adjusted to 1
2641</pre>
2642
2643
2644
2645
2646<h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2647
2648<p>
2649The syntax for function definition is
2650
2651<pre>
2652	functiondef ::= <b>function</b> funcbody
2653	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2654</pre>
2655
2656<p>
2657The following syntactic sugar simplifies function definitions:
2658
2659<pre>
2660	stat ::= <b>function</b> funcname funcbody
2661	stat ::= <b>local</b> <b>function</b> Name funcbody
2662	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2663</pre><p>
2664The statement
2665
2666<pre>
2667     function f () <em>body</em> end
2668</pre><p>
2669translates to
2670
2671<pre>
2672     f = function () <em>body</em> end
2673</pre><p>
2674The statement
2675
2676<pre>
2677     function t.a.b.c.f () <em>body</em> end
2678</pre><p>
2679translates to
2680
2681<pre>
2682     t.a.b.c.f = function () <em>body</em> end
2683</pre><p>
2684The statement
2685
2686<pre>
2687     local function f () <em>body</em> end
2688</pre><p>
2689translates to
2690
2691<pre>
2692     local f; f = function () <em>body</em> end
2693</pre><p>
2694not to
2695
2696<pre>
2697     local f = function () <em>body</em> end
2698</pre><p>
2699(This only makes a difference when the body of the function
2700contains references to <code>f</code>.)
2701
2702
2703<p>
2704A function definition is an executable expression,
2705whose value has type <em>function</em>.
2706When Lua precompiles a chunk,
2707all its function bodies are precompiled too,
2708but they are not created yet.
2709Then, whenever Lua executes the function definition,
2710the function is <em>instantiated</em> (or <em>closed</em>).
2711This function instance, or <em>closure</em>,
2712is the final value of the expression.
2713
2714
2715<p>
2716Parameters act as local variables that are
2717initialized with the argument values:
2718
2719<pre>
2720	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2721</pre><p>
2722When a Lua function is called,
2723it adjusts its list of arguments to
2724the length of its list of parameters,
2725unless the function is a <em>vararg function</em>,
2726which is indicated by three dots ('<code>...</code>')
2727at the end of its parameter list.
2728A vararg function does not adjust its argument list;
2729instead, it collects all extra arguments and supplies them
2730to the function through a <em>vararg expression</em>,
2731which is also written as three dots.
2732The value of this expression is a list of all actual extra arguments,
2733similar to a function with multiple results.
2734If a vararg expression is used inside another expression
2735or in the middle of a list of expressions,
2736then its return list is adjusted to one element.
2737If the expression is used as the last element of a list of expressions,
2738then no adjustment is made
2739(unless that last expression is enclosed in parentheses).
2740
2741
2742<p>
2743As an example, consider the following definitions:
2744
2745<pre>
2746     function f(a, b) end
2747     function g(a, b, ...) end
2748     function r() return 1,2,3 end
2749</pre><p>
2750Then, we have the following mapping from arguments to parameters and
2751to the vararg expression:
2752
2753<pre>
2754     CALL             PARAMETERS
2755
2756     f(3)             a=3, b=nil
2757     f(3, 4)          a=3, b=4
2758     f(3, 4, 5)       a=3, b=4
2759     f(r(), 10)       a=1, b=10
2760     f(r())           a=1, b=2
2761
2762     g(3)             a=3, b=nil, ... --&gt;  (nothing)
2763     g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
2764     g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
2765     g(5, r())        a=5, b=1,   ... --&gt;  2  3
2766</pre>
2767
2768<p>
2769Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2770If control reaches the end of a function
2771without encountering a <b>return</b> statement,
2772then the function returns with no results.
2773
2774
2775<p>
2776
2777There is a system-dependent limit on the number of values
2778that a function may return.
2779This limit is guaranteed to be greater than 1000.
2780
2781
2782<p>
2783The <em>colon</em> syntax
2784is used to emulate <em>methods</em>,
2785adding an implicit extra parameter <code>self</code> to the function.
2786Thus, the statement
2787
2788<pre>
2789     function t.a.b.c:f (<em>params</em>) <em>body</em> end
2790</pre><p>
2791is syntactic sugar for
2792
2793<pre>
2794     t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2795</pre>
2796
2797
2798
2799
2800
2801
2802<h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2803
2804<p>
2805
2806Lua is a lexically scoped language.
2807The scope of a local variable begins at the first statement after
2808its declaration and lasts until the last non-void statement
2809of the innermost block that includes the declaration.
2810Consider the following example:
2811
2812<pre>
2813     x = 10                -- global variable
2814     do                    -- new block
2815       local x = x         -- new 'x', with value 10
2816       print(x)            --&gt; 10
2817       x = x+1
2818       do                  -- another block
2819         local x = x+1     -- another 'x'
2820         print(x)          --&gt; 12
2821       end
2822       print(x)            --&gt; 11
2823     end
2824     print(x)              --&gt; 10  (the global one)
2825</pre>
2826
2827<p>
2828Notice that, in a declaration like <code>local x = x</code>,
2829the new <code>x</code> being declared is not in scope yet,
2830and so the second <code>x</code> refers to the outside variable.
2831
2832
2833<p>
2834Because of the lexical scoping rules,
2835local variables can be freely accessed by functions
2836defined inside their scope.
2837A local variable used by an inner function is called an <em>upvalue</em>
2838(or <em>external local variable</em>, or simply <em>external variable</em>)
2839inside the inner function.
2840
2841
2842<p>
2843Notice that each execution of a <b>local</b> statement
2844defines new local variables.
2845Consider the following example:
2846
2847<pre>
2848     a = {}
2849     local x = 20
2850     for i = 1, 10 do
2851       local y = 0
2852       a[i] = function () y = y + 1; return x + y end
2853     end
2854</pre><p>
2855The loop creates ten closures
2856(that is, ten instances of the anonymous function).
2857Each of these closures uses a different <code>y</code> variable,
2858while all of them share the same <code>x</code>.
2859
2860
2861
2862
2863
2864<h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2865
2866
2867
2868<p>
2869
2870This section describes the C&nbsp;API for Lua, that is,
2871the set of C&nbsp;functions available to the host program to communicate
2872with Lua.
2873All API functions and related types and constants
2874are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2875
2876
2877<p>
2878Even when we use the term "function",
2879any facility in the API may be provided as a macro instead.
2880Except where stated otherwise,
2881all such macros use each of their arguments exactly once
2882(except for the first argument, which is always a Lua state),
2883and so do not generate any hidden side-effects.
2884
2885
2886<p>
2887As in most C&nbsp;libraries,
2888the Lua API functions do not check their arguments
2889for validity or consistency.
2890However, you can change this behavior by compiling Lua
2891with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2892
2893
2894<p>
2895The Lua library is fully reentrant:
2896it has no global variables.
2897It keeps all information it needs in a dynamic structure,
2898called the <em>Lua state</em>.
2899
2900
2901<p>
2902Each Lua state has one or more threads,
2903which correspond to independent, cooperative lines of execution.
2904The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread.
2905(Indirectly, through the thread, it also refers to the
2906Lua state associated to the thread.)
2907
2908
2909<p>
2910A pointer to a thread must be passed as the first argument to
2911every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
2912which creates a Lua state from scratch and returns a pointer
2913to the <em>main thread</em> in the new state.
2914
2915
2916
2917
2918
2919<h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2920
2921
2922
2923<p>
2924Lua uses a <em>virtual stack</em> to pass values to and from C.
2925Each element in this stack represents a Lua value
2926(<b>nil</b>, number, string, etc.).
2927Functions in the API can access this stack through the
2928Lua state parameter that they receive.
2929
2930
2931<p>
2932Whenever Lua calls C, the called function gets a new stack,
2933which is independent of previous stacks and of stacks of
2934C&nbsp;functions that are still active.
2935This stack initially contains any arguments to the C&nbsp;function
2936and it is where the C&nbsp;function can store temporary
2937Lua values and must push its results
2938to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2939
2940
2941<p>
2942For convenience,
2943most query operations in the API do not follow a strict stack discipline.
2944Instead, they can refer to any element in the stack
2945by using an <em>index</em>:
2946A positive index represents an absolute stack position,
2947starting at&nbsp;1 as the bottom of the stack;
2948a negative index represents an offset relative to the top of the stack.
2949More specifically, if the stack has <em>n</em> elements,
2950then index&nbsp;1 represents the first element
2951(that is, the element that was pushed onto the stack first)
2952and
2953index&nbsp;<em>n</em> represents the last element;
2954index&nbsp;-1 also represents the last element
2955(that is, the element at the&nbsp;top)
2956and index <em>-n</em> represents the first element.
2957
2958
2959
2960
2961
2962<h3>4.1.1 &ndash; <a name="4.1.1">Stack Size</a></h3>
2963
2964<p>
2965When you interact with the Lua API,
2966you are responsible for ensuring consistency.
2967In particular,
2968<em>you are responsible for controlling stack overflow</em>.
2969You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2970to ensure that the stack has enough space for pushing new elements.
2971
2972
2973<p>
2974Whenever Lua calls C,
2975it ensures that the stack has space for
2976at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra elements;
2977that is, you can safely push up to <code>LUA_MINSTACK</code> values into it.
2978<code>LUA_MINSTACK</code> is defined as 20,
2979so that usually you do not have to worry about stack space
2980unless your code has loops pushing elements onto the stack.
2981
2982
2983<p>
2984When you call a Lua function
2985without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2986Lua ensures that the stack has enough space for all results,
2987but it does not ensure any extra space.
2988So, before pushing anything on the stack after such a call
2989you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2990
2991
2992
2993
2994
2995<h3>4.1.2 &ndash; <a name="4.1.2">Valid and Acceptable Indices</a></h3>
2996
2997<p>
2998Any function in the API that receives stack indices
2999works only with <em>valid indices</em> or <em>acceptable indices</em>.
3000
3001
3002<p>
3003A <em>valid index</em> is an index that refers to a
3004position that stores a modifiable Lua value.
3005It comprises stack indices between&nbsp;1 and the stack top
3006(<code>1 &le; abs(index) &le; top</code>)
3007
3008plus <em>pseudo-indices</em>,
3009which represent some positions that are accessible to C&nbsp;code
3010but that are not in the stack.
3011Pseudo-indices are used to access the registry (see <a href="#4.3">&sect;4.3</a>)
3012and the upvalues of a C&nbsp;function (see <a href="#4.2">&sect;4.2</a>).
3013
3014
3015<p>
3016Functions that do not need a specific mutable position,
3017but only a value (e.g., query functions),
3018can be called with acceptable indices.
3019An <em>acceptable index</em> can be any valid index,
3020but it also can be any positive index after the stack top
3021within the space allocated for the stack,
3022that is, indices up to the stack size.
3023(Note that 0 is never an acceptable index.)
3024Indices to upvalues (see <a href="#4.2">&sect;4.2</a>) greater than the real number
3025of upvalues in the current C&nbsp;function are also acceptable (but invalid).
3026Except when noted otherwise,
3027functions in the API work with acceptable indices.
3028
3029
3030<p>
3031Acceptable indices serve to avoid extra tests
3032against the stack top when querying the stack.
3033For instance, a C&nbsp;function can query its third argument
3034without the need to check whether there is a third argument,
3035that is, without the need to check whether 3 is a valid index.
3036
3037
3038<p>
3039For functions that can be called with acceptable indices,
3040any non-valid index is treated as if it
3041contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
3042which behaves like a nil value.
3043
3044
3045
3046
3047
3048<h3>4.1.3 &ndash; <a name="4.1.3">Pointers to strings</a></h3>
3049
3050<p>
3051Several functions in the API return pointers (<code>const char*</code>)
3052to Lua strings in the stack.
3053(See <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3054<a href="#lua_pushstring"><code>lua_pushstring</code></a>, and <a href="#lua_tolstring"><code>lua_tolstring</code></a>.
3055See also <a href="#luaL_checklstring"><code>luaL_checklstring</code></a>, <a href="#luaL_checkstring"><code>luaL_checkstring</code></a>,
3056and <a href="#luaL_tolstring"><code>luaL_tolstring</code></a> in the auxiliary library.)
3057
3058
3059<p>
3060In general,
3061Lua's garbage collection can free or move internal memory
3062and then invalidate pointers to internal strings.
3063To allow a safe use of these pointers,
3064The API guarantees that any pointer to a string in a stack index
3065is valid while the value at that index is neither modified nor popped.
3066When the index is a pseudo-index (referring to an upvalue),
3067the pointer is valid while the corresponding call is active and
3068the corresponding upvalue is not modified.
3069
3070
3071<p>
3072Some functions in the debug interface
3073also return pointers to strings,
3074namely <a href="#lua_getlocal"><code>lua_getlocal</code></a>, <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
3075<a href="#lua_setlocal"><code>lua_setlocal</code></a>, and <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.
3076For these functions, the pointer is guaranteed to
3077be valid while the caller function is active and
3078the given closure (if one was given) is in the stack.
3079
3080
3081<p>
3082Except for these guarantees,
3083the garbage collector is free to invalidate
3084any pointer to internal strings.
3085
3086
3087
3088
3089
3090
3091
3092<h2>4.2 &ndash; <a name="4.2">C Closures</a></h2>
3093
3094<p>
3095When a C&nbsp;function is created,
3096it is possible to associate some values with it,
3097thus creating a <em>C&nbsp;closure</em>
3098(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
3099these values are called <em>upvalues</em> and are
3100accessible to the function whenever it is called.
3101
3102
3103<p>
3104Whenever a C&nbsp;function is called,
3105its upvalues are located at specific pseudo-indices.
3106These pseudo-indices are produced by the macro
3107<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
3108The first upvalue associated with a function is at index
3109<code>lua_upvalueindex(1)</code>, and so on.
3110Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
3111where <em>n</em> is greater than the number of upvalues of the
3112current function
3113(but not greater than 256,
3114which is one plus the maximum number of upvalues in a closure),
3115produces an acceptable but invalid index.
3116
3117
3118<p>
3119A C&nbsp;closure can also change the values
3120of its corresponding upvalues.
3121
3122
3123
3124
3125
3126<h2>4.3 &ndash; <a name="4.3">Registry</a></h2>
3127
3128<p>
3129Lua provides a <em>registry</em>,
3130a predefined table that can be used by any C&nbsp;code to
3131store whatever Lua values it needs to store.
3132The registry table is always accessible at pseudo-index
3133<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
3134Any C&nbsp;library can store data into this table,
3135but it must take care to choose keys
3136that are different from those used
3137by other libraries, to avoid collisions.
3138Typically, you should use as key a string containing your library name,
3139or a light userdata with the address of a C&nbsp;object in your code,
3140or any Lua object created by your code.
3141As with variable names,
3142string keys starting with an underscore followed by
3143uppercase letters are reserved for Lua.
3144
3145
3146<p>
3147The integer keys in the registry are used
3148by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
3149and by some predefined values.
3150Therefore, integer keys in the registry
3151must not be used for other purposes.
3152
3153
3154<p>
3155When you create a new Lua state,
3156its registry comes with some predefined values.
3157These predefined values are indexed with integer keys
3158defined as constants in <code>lua.h</code>.
3159The following constants are defined:
3160
3161<ul>
3162<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
3163the main thread of the state.
3164(The main thread is the one created together with the state.)
3165</li>
3166
3167<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
3168the global environment.
3169</li>
3170</ul>
3171
3172
3173
3174
3175<h2>4.4 &ndash; <a name="4.4">Error Handling in C</a></h2>
3176
3177
3178
3179<p>
3180Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
3181(Lua will use exceptions if you compile it as C++;
3182search for <code>LUAI_THROW</code> in the source code for details.)
3183When Lua faces any error,
3184such as a memory allocation error or a type error,
3185it <em>raises</em> an error;
3186that is, it does a long jump.
3187A <em>protected environment</em> uses <code>setjmp</code>
3188to set a recovery point;
3189any error jumps to the most recent active recovery point.
3190
3191
3192<p>
3193Inside a C&nbsp;function you can raise an error explicitly
3194by calling <a href="#lua_error"><code>lua_error</code></a>.
3195
3196
3197<p>
3198Most functions in the API can raise an error,
3199for instance due to a memory allocation error.
3200The documentation for each function indicates whether
3201it can raise errors.
3202
3203
3204<p>
3205If an error happens outside any protected environment,
3206Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
3207and then calls <code>abort</code>,
3208thus exiting the host application.
3209Your panic function can avoid this exit by
3210never returning
3211(e.g., doing a long jump to your own recovery point outside Lua).
3212
3213
3214<p>
3215The panic function,
3216as its name implies,
3217is a mechanism of last resort.
3218Programs should avoid it.
3219As a general rule,
3220when a C&nbsp;function is called by Lua with a Lua state,
3221it can do whatever it wants on that Lua state,
3222as it should be already protected.
3223However,
3224when C code operates on other Lua states
3225(e.g., a Lua-state argument to the function,
3226a Lua state stored in the registry, or
3227the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
3228it should use them only in API calls that cannot raise errors.
3229
3230
3231<p>
3232The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
3233in particular, the error object is on the top of the stack.
3234However, there is no guarantee about stack space.
3235To push anything on the stack,
3236the panic function must first check the available space (see <a href="#4.1.1">&sect;4.1.1</a>).
3237
3238
3239
3240
3241
3242<h3>4.4.1 &ndash; <a name="4.4.1">Status Codes</a></h3>
3243
3244<p>
3245Several functions that report errors in the API use the following
3246status codes to indicate different kinds of errors or other conditions:
3247
3248<ul>
3249
3250<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> no errors.</li>
3251
3252<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> a runtime error.</li>
3253
3254<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3255memory allocation error.
3256For such errors, Lua does not call the message handler.
3257</li>
3258
3259<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> error while running the message handler.</li>
3260
3261<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> syntax error during precompilation.</li>
3262
3263<li><b><a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a>: </b> the thread (coroutine) yields.</li>
3264
3265<li><b><a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>: </b> a file-related error;
3266e.g., it cannot open or read the file.</li>
3267
3268</ul><p>
3269These constants are defined in the header file <code>lua.h</code>.
3270
3271
3272
3273
3274
3275
3276
3277<h2>4.5 &ndash; <a name="4.5">Handling Yields in C</a></h2>
3278
3279<p>
3280Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
3281Therefore, if a C&nbsp;function <code>foo</code> calls an API function
3282and this API function yields
3283(directly or indirectly by calling another function that yields),
3284Lua cannot return to <code>foo</code> any more,
3285because the <code>longjmp</code> removes its frame from the C stack.
3286
3287
3288<p>
3289To avoid this kind of problem,
3290Lua raises an error whenever it tries to yield across an API call,
3291except for three functions:
3292<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>.
3293All those functions receive a <em>continuation function</em>
3294(as a parameter named <code>k</code>) to continue execution after a yield.
3295
3296
3297<p>
3298We need to set some terminology to explain continuations.
3299We have a C&nbsp;function called from Lua which we will call
3300the <em>original function</em>.
3301This original function then calls one of those three functions in the C API,
3302which we will call the <em>callee function</em>,
3303that then yields the current thread.
3304This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
3305or 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>
3306and the function called by them yields.
3307
3308
3309<p>
3310Suppose the running thread yields while executing the callee function.
3311After the thread resumes,
3312it eventually will finish running the callee function.
3313However,
3314the callee function cannot return to the original function,
3315because its frame in the C stack was destroyed by the yield.
3316Instead, Lua calls a <em>continuation function</em>,
3317which was given as an argument to the callee function.
3318As the name implies,
3319the continuation function should continue the task
3320of the original function.
3321
3322
3323<p>
3324As an illustration, consider the following function:
3325
3326<pre>
3327     int original_function (lua_State *L) {
3328       ...     /* code 1 */
3329       status = lua_pcall(L, n, m, h);  /* calls Lua */
3330       ...     /* code 2 */
3331     }
3332</pre><p>
3333Now we want to allow
3334the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
3335First, we can rewrite our function like here:
3336
3337<pre>
3338     int k (lua_State *L, int status, lua_KContext ctx) {
3339       ...  /* code 2 */
3340     }
3341
3342     int original_function (lua_State *L) {
3343       ...     /* code 1 */
3344       return k(L, lua_pcall(L, n, m, h), ctx);
3345     }
3346</pre><p>
3347In the above code,
3348the new function <code>k</code> is a
3349<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
3350which should do all the work that the original function
3351was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
3352Now, we must inform Lua that it must call <code>k</code> if the Lua code
3353being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
3354(errors or yielding),
3355so we rewrite the code as here,
3356replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
3357
3358<pre>
3359     int original_function (lua_State *L) {
3360       ...     /* code 1 */
3361       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
3362     }
3363</pre><p>
3364Note the external, explicit call to the continuation:
3365Lua will call the continuation only if needed, that is,
3366in case of errors or resuming after a yield.
3367If the called function returns normally without ever yielding,
3368<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
3369(Of course, instead of calling the continuation in that case,
3370you can do the equivalent work directly inside the original function.)
3371
3372
3373<p>
3374Besides the Lua state,
3375the continuation function has two other parameters:
3376the final status of the call and the context value (<code>ctx</code>) that
3377was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3378Lua does not use this context value;
3379it only passes this value from the original function to the
3380continuation function.
3381For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3382the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3383except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
3384(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
3385For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
3386the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
3387(For these two functions,
3388Lua will not call the continuation in case of errors,
3389because they do not handle errors.)
3390Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
3391you should call the continuation function
3392with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
3393(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
3394directly the continuation function,
3395because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
3396
3397
3398<p>
3399Lua treats the continuation function as if it were the original function.
3400The continuation function receives the same Lua stack
3401from the original function,
3402in the same state it would be if the callee function had returned.
3403(For instance,
3404after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
3405removed from the stack and replaced by the results from the call.)
3406It also has the same upvalues.
3407Whatever it returns is handled by Lua as if it were the return
3408of the original function.
3409
3410
3411
3412
3413
3414<h2>4.6 &ndash; <a name="4.6">Functions and Types</a></h2>
3415
3416<p>
3417Here we list all functions and types from the C&nbsp;API in
3418alphabetical order.
3419Each function has an indicator like this:
3420<span class="apii">[-o, +p, <em>x</em>]</span>
3421
3422
3423<p>
3424The first field, <code>o</code>,
3425is how many elements the function pops from the stack.
3426The second field, <code>p</code>,
3427is how many elements the function pushes onto the stack.
3428(Any function always pushes its results after popping its arguments.)
3429A field in the form <code>x|y</code> means the function can push (or pop)
3430<code>x</code> or <code>y</code> elements,
3431depending on the situation;
3432an interrogation mark '<code>?</code>' means that
3433we cannot know how many elements the function pops/pushes
3434by looking only at its arguments.
3435(For instance, they may depend on what is in the stack.)
3436The third field, <code>x</code>,
3437tells whether the function may raise errors:
3438'<code>-</code>' means the function never raises any error;
3439'<code>m</code>' means the function may raise only out-of-memory errors;
3440'<code>v</code>' means the function may raise the errors explained in the text;
3441'<code>e</code>' means the function can run arbitrary Lua code,
3442either directly or through metamethods,
3443and therefore may raise any errors.
3444
3445
3446
3447<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
3448<span class="apii">[-0, +0, &ndash;]</span>
3449<pre>int lua_absindex (lua_State *L, int idx);</pre>
3450
3451<p>
3452Converts the acceptable index <code>idx</code>
3453into an equivalent absolute index
3454(that is, one that does not depend on the stack top).
3455
3456
3457
3458
3459
3460<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
3461<pre>typedef void * (*lua_Alloc) (void *ud,
3462                             void *ptr,
3463                             size_t osize,
3464                             size_t nsize);</pre>
3465
3466<p>
3467The type of the memory-allocation function used by Lua states.
3468The allocator function must provide a
3469functionality similar to <code>realloc</code>,
3470but not exactly the same.
3471Its arguments are
3472<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3473<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3474<code>osize</code>, the original size of the block or some code about what
3475is being allocated;
3476and <code>nsize</code>, the new size of the block.
3477
3478
3479<p>
3480When <code>ptr</code> is not <code>NULL</code>,
3481<code>osize</code> is the size of the block pointed by <code>ptr</code>,
3482that is, the size given when it was allocated or reallocated.
3483
3484
3485<p>
3486When <code>ptr</code> is <code>NULL</code>,
3487<code>osize</code> encodes the kind of object that Lua is allocating.
3488<code>osize</code> is any of
3489<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>,
3490<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)
3491Lua is creating a new object of that type.
3492When <code>osize</code> is some other value,
3493Lua is allocating memory for something else.
3494
3495
3496<p>
3497Lua assumes the following behavior from the allocator function:
3498
3499
3500<p>
3501When <code>nsize</code> is zero,
3502the allocator must behave like <code>free</code>
3503and then return <code>NULL</code>.
3504
3505
3506<p>
3507When <code>nsize</code> is not zero,
3508the allocator must behave like <code>realloc</code>.
3509In particular, the allocator returns <code>NULL</code>
3510if and only if it cannot fulfill the request.
3511
3512
3513<p>
3514Here is a simple implementation for the allocator function.
3515It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3516
3517<pre>
3518     static void *l_alloc (void *ud, void *ptr, size_t osize,
3519                                                size_t nsize) {
3520       (void)ud;  (void)osize;  /* not used */
3521       if (nsize == 0) {
3522         free(ptr);
3523         return NULL;
3524       }
3525       else
3526         return realloc(ptr, nsize);
3527     }
3528</pre><p>
3529Note that Standard&nbsp;C ensures
3530that <code>free(NULL)</code> has no effect and that
3531<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3532
3533
3534
3535
3536
3537<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3538<span class="apii">[-(2|1), +1, <em>e</em>]</span>
3539<pre>void lua_arith (lua_State *L, int op);</pre>
3540
3541<p>
3542Performs an arithmetic or bitwise operation over the two values
3543(or one, in the case of negations)
3544at the top of the stack,
3545with the value on the top being the second operand,
3546pops these values, and pushes the result of the operation.
3547The function follows the semantics of the corresponding Lua operator
3548(that is, it may call metamethods).
3549
3550
3551<p>
3552The value of <code>op</code> must be one of the following constants:
3553
3554<ul>
3555
3556<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3557<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3558<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3559<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3560<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3561<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3562<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3563<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3564<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
3565<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li>
3566<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
3567<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
3568<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3569<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3570
3571</ul>
3572
3573
3574
3575
3576<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3577<span class="apii">[-0, +0, &ndash;]</span>
3578<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3579
3580<p>
3581Sets a new panic function and returns the old one (see <a href="#4.4">&sect;4.4</a>).
3582
3583
3584
3585
3586
3587<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3588<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3589<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3590
3591<p>
3592Calls a function.
3593Like regular Lua calls,
3594<code>lua_call</code> respects the <code>__call</code> metamethod.
3595So, here the word "function"
3596means any callable value.
3597
3598
3599<p>
3600To do a call you must use the following protocol:
3601first, the function to be called is pushed onto the stack;
3602then, the arguments to the call are pushed
3603in direct order;
3604that is, the first argument is pushed first.
3605Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3606<code>nargs</code> is the number of arguments that you pushed onto the stack.
3607When the function returns,
3608all arguments and the function value are popped
3609and the call results are pushed onto the stack.
3610The number of results is adjusted to <code>nresults</code>,
3611unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3612In this case, all results from the function are pushed;
3613Lua takes care that the returned values fit into the stack space,
3614but it does not ensure any extra space in the stack.
3615The function results are pushed onto the stack in direct order
3616(the first result is pushed first),
3617so that after the call the last result is on the top of the stack.
3618
3619
3620<p>
3621Any error while calling and running the function is propagated upwards
3622(with a <code>longjmp</code>).
3623
3624
3625<p>
3626The following example shows how the host program can do the
3627equivalent to this Lua code:
3628
3629<pre>
3630     a = f("how", t.x, 14)
3631</pre><p>
3632Here it is in&nbsp;C:
3633
3634<pre>
3635     lua_getglobal(L, "f");                  /* function to be called */
3636     lua_pushliteral(L, "how");                       /* 1st argument */
3637     lua_getglobal(L, "t");                    /* table to be indexed */
3638     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
3639     lua_remove(L, -2);                  /* remove 't' from the stack */
3640     lua_pushinteger(L, 14);                          /* 3rd argument */
3641     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
3642     lua_setglobal(L, "a");                         /* set global 'a' */
3643</pre><p>
3644Note that the code above is <em>balanced</em>:
3645at its end, the stack is back to its original configuration.
3646This is considered good programming practice.
3647
3648
3649
3650
3651
3652<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3653<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3654<pre>void lua_callk (lua_State *L,
3655                int nargs,
3656                int nresults,
3657                lua_KContext ctx,
3658                lua_KFunction k);</pre>
3659
3660<p>
3661This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3662but allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
3663
3664
3665
3666
3667
3668<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3669<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3670
3671<p>
3672Type for C&nbsp;functions.
3673
3674
3675<p>
3676In order to communicate properly with Lua,
3677a C&nbsp;function must use the following protocol,
3678which defines the way parameters and results are passed:
3679a C&nbsp;function receives its arguments from Lua in its stack
3680in direct order (the first argument is pushed first).
3681So, when the function starts,
3682<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3683The first argument (if any) is at index 1
3684and its last argument is at index <code>lua_gettop(L)</code>.
3685To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3686in direct order (the first result is pushed first),
3687and returns in C the number of results.
3688Any other value in the stack below the results will be properly
3689discarded by Lua.
3690Like a Lua function, a C&nbsp;function called by Lua can also return
3691many results.
3692
3693
3694<p>
3695As an example, the following function receives a variable number
3696of numeric arguments and returns their average and their sum:
3697
3698<pre>
3699     static int foo (lua_State *L) {
3700       int n = lua_gettop(L);    /* number of arguments */
3701       lua_Number sum = 0.0;
3702       int i;
3703       for (i = 1; i &lt;= n; i++) {
3704         if (!lua_isnumber(L, i)) {
3705           lua_pushliteral(L, "incorrect argument");
3706           lua_error(L);
3707         }
3708         sum += lua_tonumber(L, i);
3709       }
3710       lua_pushnumber(L, sum/n);        /* first result */
3711       lua_pushnumber(L, sum);         /* second result */
3712       return 2;                   /* number of results */
3713     }
3714</pre>
3715
3716
3717
3718
3719<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3720<span class="apii">[-0, +0, &ndash;]</span>
3721<pre>int lua_checkstack (lua_State *L, int n);</pre>
3722
3723<p>
3724Ensures that the stack has space for at least <code>n</code> extra elements,
3725that is, that you can safely push up to <code>n</code> values into it.
3726It returns false if it cannot fulfill the request,
3727either because it would cause the stack
3728to be greater than a fixed maximum size
3729(typically at least several thousand elements) or
3730because it cannot allocate memory for the extra space.
3731This function never shrinks the stack;
3732if the stack already has space for the extra elements,
3733it is left unchanged.
3734
3735
3736
3737
3738
3739<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3740<span class="apii">[-0, +0, &ndash;]</span>
3741<pre>void lua_close (lua_State *L);</pre>
3742
3743<p>
3744Close all active to-be-closed variables in the main thread,
3745release all objects in the given Lua state
3746(calling the corresponding garbage-collection metamethods, if any),
3747and frees all dynamic memory used by this state.
3748
3749
3750<p>
3751On several platforms, you may not need to call this function,
3752because all resources are naturally released when the host program ends.
3753On the other hand, long-running programs that create multiple states,
3754such as daemons or web servers,
3755will probably need to close states as soon as they are not needed.
3756
3757
3758
3759
3760
3761<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3762<span class="apii">[-0, +0, <em>e</em>]</span>
3763<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3764
3765<p>
3766Compares two Lua values.
3767Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3768when compared with the value at index <code>index2</code>,
3769following the semantics of the corresponding Lua operator
3770(that is, it may call metamethods).
3771Otherwise returns&nbsp;0.
3772Also returns&nbsp;0 if any of the indices is not valid.
3773
3774
3775<p>
3776The value of <code>op</code> must be one of the following constants:
3777
3778<ul>
3779
3780<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3781<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3782<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3783
3784</ul>
3785
3786
3787
3788
3789<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3790<span class="apii">[-n, +1, <em>e</em>]</span>
3791<pre>void lua_concat (lua_State *L, int n);</pre>
3792
3793<p>
3794Concatenates the <code>n</code> values at the top of the stack,
3795pops them, and leaves the result on the top.
3796If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3797(that is, the function does nothing);
3798if <code>n</code> is 0, the result is the empty string.
3799Concatenation is performed following the usual semantics of Lua
3800(see <a href="#3.4.6">&sect;3.4.6</a>).
3801
3802
3803
3804
3805
3806<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3807<span class="apii">[-0, +0, &ndash;]</span>
3808<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3809
3810<p>
3811Copies the element at index <code>fromidx</code>
3812into the valid index <code>toidx</code>,
3813replacing the value at that position.
3814Values at other positions are not affected.
3815
3816
3817
3818
3819
3820<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3821<span class="apii">[-0, +1, <em>m</em>]</span>
3822<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3823
3824<p>
3825Creates a new empty table and pushes it onto the stack.
3826Parameter <code>narr</code> is a hint for how many elements the table
3827will have as a sequence;
3828parameter <code>nrec</code> is a hint for how many other elements
3829the table will have.
3830Lua may use these hints to preallocate memory for the new table.
3831This preallocation may help performance when you know in advance
3832how many elements the table will have.
3833Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3834
3835
3836
3837
3838
3839<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3840<span class="apii">[-0, +0, &ndash;]</span>
3841<pre>int lua_dump (lua_State *L,
3842                        lua_Writer writer,
3843                        void *data,
3844                        int strip);</pre>
3845
3846<p>
3847Dumps a function as a binary chunk.
3848Receives a Lua function on the top of the stack
3849and produces a binary chunk that,
3850if loaded again,
3851results in a function equivalent to the one dumped.
3852As it produces parts of the chunk,
3853<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3854with the given <code>data</code>
3855to write them.
3856
3857
3858<p>
3859If <code>strip</code> is true,
3860the binary representation may not include all debug information
3861about the function,
3862to save space.
3863
3864
3865<p>
3866The value returned is the error code returned by the last
3867call to the writer;
38680&nbsp;means no errors.
3869
3870
3871<p>
3872This function does not pop the Lua function from the stack.
3873
3874
3875
3876
3877
3878<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3879<span class="apii">[-1, +0, <em>v</em>]</span>
3880<pre>int lua_error (lua_State *L);</pre>
3881
3882<p>
3883Raises a Lua error,
3884using the value on the top of the stack as the error object.
3885This function does a long jump,
3886and therefore never returns
3887(see <a href="#luaL_error"><code>luaL_error</code></a>).
3888
3889
3890
3891
3892
3893<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3894<span class="apii">[-0, +0, &ndash;]</span>
3895<pre>int lua_gc (lua_State *L, int what, ...);</pre>
3896
3897<p>
3898Controls the garbage collector.
3899
3900
3901<p>
3902This function performs several tasks,
3903according to the value of the parameter <code>what</code>.
3904For options that need extra arguments,
3905they are listed after the option.
3906
3907<ul>
3908
3909<li><b><code>LUA_GCCOLLECT</code>: </b>
3910Performs a full garbage-collection cycle.
3911</li>
3912
3913<li><b><code>LUA_GCSTOP</code>: </b>
3914Stops the garbage collector.
3915</li>
3916
3917<li><b><code>LUA_GCRESTART</code>: </b>
3918Restarts the garbage collector.
3919</li>
3920
3921<li><b><code>LUA_GCCOUNT</code>: </b>
3922Returns the current amount of memory (in Kbytes) in use by Lua.
3923</li>
3924
3925<li><b><code>LUA_GCCOUNTB</code>: </b>
3926Returns the remainder of dividing the current amount of bytes of
3927memory in use by Lua by 1024.
3928</li>
3929
3930<li><b><code>LUA_GCSTEP</code> <code>(int stepsize)</code>: </b>
3931Performs an incremental step of garbage collection,
3932corresponding to the allocation of <code>stepsize</code> Kbytes.
3933</li>
3934
3935<li><b><code>LUA_GCISRUNNING</code>: </b>
3936Returns a boolean that tells whether the collector is running
3937(i.e., not stopped).
3938</li>
3939
3940<li><b><code>LUA_GCINC</code> (int pause, int stepmul, stepsize): </b>
3941Changes the collector to incremental mode
3942with the given parameters (see <a href="#2.5.1">&sect;2.5.1</a>).
3943Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3944</li>
3945
3946<li><b><code>LUA_GCGEN</code> (int minormul, int majormul): </b>
3947Changes the collector to generational mode
3948with the given parameters (see <a href="#2.5.2">&sect;2.5.2</a>).
3949Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3950</li>
3951
3952</ul><p>
3953For more details about these options,
3954see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3955
3956
3957
3958
3959
3960<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3961<span class="apii">[-0, +0, &ndash;]</span>
3962<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3963
3964<p>
3965Returns the memory-allocation function of a given state.
3966If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3967opaque pointer given when the memory-allocator function was set.
3968
3969
3970
3971
3972
3973<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3974<span class="apii">[-0, +1, <em>e</em>]</span>
3975<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
3976
3977<p>
3978Pushes onto the stack the value <code>t[k]</code>,
3979where <code>t</code> is the value at the given index.
3980As in Lua, this function may trigger a metamethod
3981for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3982
3983
3984<p>
3985Returns the type of the pushed value.
3986
3987
3988
3989
3990
3991<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
3992<span class="apii">[-0, +0, &ndash;]</span>
3993<pre>void *lua_getextraspace (lua_State *L);</pre>
3994
3995<p>
3996Returns a pointer to a raw memory area associated with the
3997given Lua state.
3998The application can use this area for any purpose;
3999Lua does not use it for anything.
4000
4001
4002<p>
4003Each new thread has this area initialized with a copy
4004of the area of the main thread.
4005
4006
4007<p>
4008By default, this area has the size of a pointer to void,
4009but you can recompile Lua with a different size for this area.
4010(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
4011
4012
4013
4014
4015
4016<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
4017<span class="apii">[-0, +1, <em>e</em>]</span>
4018<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
4019
4020<p>
4021Pushes onto the stack the value of the global <code>name</code>.
4022Returns the type of that value.
4023
4024
4025
4026
4027
4028<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
4029<span class="apii">[-0, +1, <em>e</em>]</span>
4030<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
4031
4032<p>
4033Pushes onto the stack the value <code>t[i]</code>,
4034where <code>t</code> is the value at the given index.
4035As in Lua, this function may trigger a metamethod
4036for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4037
4038
4039<p>
4040Returns the type of the pushed value.
4041
4042
4043
4044
4045
4046<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
4047<span class="apii">[-0, +(0|1), &ndash;]</span>
4048<pre>int lua_getmetatable (lua_State *L, int index);</pre>
4049
4050<p>
4051If the value at the given index has a metatable,
4052the function pushes that metatable onto the stack and returns&nbsp;1.
4053Otherwise,
4054the function returns&nbsp;0 and pushes nothing on the stack.
4055
4056
4057
4058
4059
4060<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
4061<span class="apii">[-1, +1, <em>e</em>]</span>
4062<pre>int lua_gettable (lua_State *L, int index);</pre>
4063
4064<p>
4065Pushes onto the stack the value <code>t[k]</code>,
4066where <code>t</code> is the value at the given index
4067and <code>k</code> is the value on the top of the stack.
4068
4069
4070<p>
4071This function pops the key from the stack,
4072pushing the resulting value in its place.
4073As in Lua, this function may trigger a metamethod
4074for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4075
4076
4077<p>
4078Returns the type of the pushed value.
4079
4080
4081
4082
4083
4084<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
4085<span class="apii">[-0, +0, &ndash;]</span>
4086<pre>int lua_gettop (lua_State *L);</pre>
4087
4088<p>
4089Returns the index of the top element in the stack.
4090Because indices start at&nbsp;1,
4091this result is equal to the number of elements in the stack;
4092in particular, 0&nbsp;means an empty stack.
4093
4094
4095
4096
4097
4098<hr><h3><a name="lua_getiuservalue"><code>lua_getiuservalue</code></a></h3><p>
4099<span class="apii">[-0, +1, &ndash;]</span>
4100<pre>int lua_getiuservalue (lua_State *L, int index, int n);</pre>
4101
4102<p>
4103Pushes onto the stack the <code>n</code>-th user value associated with the
4104full userdata at the given index and
4105returns the type of the pushed value.
4106
4107
4108<p>
4109If the userdata does not have that value,
4110pushes <b>nil</b> and returns <a href="#pdf-LUA_TNONE"><code>LUA_TNONE</code></a>.
4111
4112
4113
4114
4115
4116<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
4117<span class="apii">[-1, +1, &ndash;]</span>
4118<pre>void lua_insert (lua_State *L, int index);</pre>
4119
4120<p>
4121Moves the top element into the given valid index,
4122shifting up the elements above this index to open space.
4123This function cannot be called with a pseudo-index,
4124because a pseudo-index is not an actual stack position.
4125
4126
4127
4128
4129
4130<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
4131<pre>typedef ... lua_Integer;</pre>
4132
4133<p>
4134The type of integers in Lua.
4135
4136
4137<p>
4138By default this type is <code>long long</code>,
4139(usually a 64-bit two-complement integer),
4140but that can be changed to <code>long</code> or <code>int</code>
4141(usually a 32-bit two-complement integer).
4142(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
4143
4144
4145<p>
4146Lua also defines the constants
4147<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
4148with the minimum and the maximum values that fit in this type.
4149
4150
4151
4152
4153
4154<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
4155<span class="apii">[-0, +0, &ndash;]</span>
4156<pre>int lua_isboolean (lua_State *L, int index);</pre>
4157
4158<p>
4159Returns 1 if the value at the given index is a boolean,
4160and 0&nbsp;otherwise.
4161
4162
4163
4164
4165
4166<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
4167<span class="apii">[-0, +0, &ndash;]</span>
4168<pre>int lua_iscfunction (lua_State *L, int index);</pre>
4169
4170<p>
4171Returns 1 if the value at the given index is a C&nbsp;function,
4172and 0&nbsp;otherwise.
4173
4174
4175
4176
4177
4178<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
4179<span class="apii">[-0, +0, &ndash;]</span>
4180<pre>int lua_isfunction (lua_State *L, int index);</pre>
4181
4182<p>
4183Returns 1 if the value at the given index is a function
4184(either C or Lua), and 0&nbsp;otherwise.
4185
4186
4187
4188
4189
4190<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
4191<span class="apii">[-0, +0, &ndash;]</span>
4192<pre>int lua_isinteger (lua_State *L, int index);</pre>
4193
4194<p>
4195Returns 1 if the value at the given index is an integer
4196(that is, the value is a number and is represented as an integer),
4197and 0&nbsp;otherwise.
4198
4199
4200
4201
4202
4203<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
4204<span class="apii">[-0, +0, &ndash;]</span>
4205<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
4206
4207<p>
4208Returns 1 if the value at the given index is a light userdata,
4209and 0&nbsp;otherwise.
4210
4211
4212
4213
4214
4215<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
4216<span class="apii">[-0, +0, &ndash;]</span>
4217<pre>int lua_isnil (lua_State *L, int index);</pre>
4218
4219<p>
4220Returns 1 if the value at the given index is <b>nil</b>,
4221and 0&nbsp;otherwise.
4222
4223
4224
4225
4226
4227<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
4228<span class="apii">[-0, +0, &ndash;]</span>
4229<pre>int lua_isnone (lua_State *L, int index);</pre>
4230
4231<p>
4232Returns 1 if the given index is not valid,
4233and 0&nbsp;otherwise.
4234
4235
4236
4237
4238
4239<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
4240<span class="apii">[-0, +0, &ndash;]</span>
4241<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
4242
4243<p>
4244Returns 1 if the given index is not valid
4245or if the value at this index is <b>nil</b>,
4246and 0&nbsp;otherwise.
4247
4248
4249
4250
4251
4252<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
4253<span class="apii">[-0, +0, &ndash;]</span>
4254<pre>int lua_isnumber (lua_State *L, int index);</pre>
4255
4256<p>
4257Returns 1 if the value at the given index is a number
4258or a string convertible to a number,
4259and 0&nbsp;otherwise.
4260
4261
4262
4263
4264
4265<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
4266<span class="apii">[-0, +0, &ndash;]</span>
4267<pre>int lua_isstring (lua_State *L, int index);</pre>
4268
4269<p>
4270Returns 1 if the value at the given index is a string
4271or a number (which is always convertible to a string),
4272and 0&nbsp;otherwise.
4273
4274
4275
4276
4277
4278<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
4279<span class="apii">[-0, +0, &ndash;]</span>
4280<pre>int lua_istable (lua_State *L, int index);</pre>
4281
4282<p>
4283Returns 1 if the value at the given index is a table,
4284and 0&nbsp;otherwise.
4285
4286
4287
4288
4289
4290<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
4291<span class="apii">[-0, +0, &ndash;]</span>
4292<pre>int lua_isthread (lua_State *L, int index);</pre>
4293
4294<p>
4295Returns 1 if the value at the given index is a thread,
4296and 0&nbsp;otherwise.
4297
4298
4299
4300
4301
4302<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
4303<span class="apii">[-0, +0, &ndash;]</span>
4304<pre>int lua_isuserdata (lua_State *L, int index);</pre>
4305
4306<p>
4307Returns 1 if the value at the given index is a userdata
4308(either full or light), and 0&nbsp;otherwise.
4309
4310
4311
4312
4313
4314<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
4315<span class="apii">[-0, +0, &ndash;]</span>
4316<pre>int lua_isyieldable (lua_State *L);</pre>
4317
4318<p>
4319Returns 1 if the given coroutine can yield,
4320and 0&nbsp;otherwise.
4321
4322
4323
4324
4325
4326<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
4327<pre>typedef ... lua_KContext;</pre>
4328
4329<p>
4330The type for continuation-function contexts.
4331It must be a numeric type.
4332This type is defined as <code>intptr_t</code>
4333when <code>intptr_t</code> is available,
4334so that it can store pointers too.
4335Otherwise, it is defined as <code>ptrdiff_t</code>.
4336
4337
4338
4339
4340
4341<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
4342<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
4343
4344<p>
4345Type for continuation functions (see <a href="#4.5">&sect;4.5</a>).
4346
4347
4348
4349
4350
4351<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
4352<span class="apii">[-0, +1, <em>e</em>]</span>
4353<pre>void lua_len (lua_State *L, int index);</pre>
4354
4355<p>
4356Returns the length of the value at the given index.
4357It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
4358may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
4359The result is pushed on the stack.
4360
4361
4362
4363
4364
4365<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
4366<span class="apii">[-0, +1, &ndash;]</span>
4367<pre>int lua_load (lua_State *L,
4368              lua_Reader reader,
4369              void *data,
4370              const char *chunkname,
4371              const char *mode);</pre>
4372
4373<p>
4374Loads a Lua chunk without running it.
4375If there are no errors,
4376<code>lua_load</code> pushes the compiled chunk as a Lua
4377function on top of the stack.
4378Otherwise, it pushes an error message.
4379
4380
4381<p>
4382The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
4383to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
4384The <code>data</code> argument is an opaque value passed to the reader function.
4385
4386
4387<p>
4388The <code>chunkname</code> argument gives a name to the chunk,
4389which is used for error messages and in debug information (see <a href="#4.7">&sect;4.7</a>).
4390
4391
4392<p>
4393<code>lua_load</code> automatically detects whether the chunk is text or binary
4394and loads it accordingly (see program <code>luac</code>).
4395The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
4396with the addition that
4397a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
4398
4399
4400<p>
4401<code>lua_load</code> uses the stack internally,
4402so the reader function must always leave the stack
4403unmodified when returning.
4404
4405
4406<p>
4407<code>lua_load</code> can return
4408<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>.
4409The function may also return other values corresponding to
4410errors raised by the read function (see <a href="#4.4.1">&sect;4.4.1</a>).
4411
4412
4413<p>
4414If the resulting function has upvalues,
4415its first upvalue is set to the value of the global environment
4416stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.3">&sect;4.3</a>).
4417When loading main chunks,
4418this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
4419Other upvalues are initialized with <b>nil</b>.
4420
4421
4422
4423
4424
4425<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
4426<span class="apii">[-0, +0, &ndash;]</span>
4427<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
4428
4429<p>
4430Creates a new independent state and returns its main thread.
4431Returns <code>NULL</code> if it cannot create the state
4432(due to lack of memory).
4433The argument <code>f</code> is the allocator function;
4434Lua will do all memory allocation for this state
4435through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
4436The second argument, <code>ud</code>, is an opaque pointer that Lua
4437passes to the allocator in every call.
4438
4439
4440
4441
4442
4443<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
4444<span class="apii">[-0, +1, <em>m</em>]</span>
4445<pre>void lua_newtable (lua_State *L);</pre>
4446
4447<p>
4448Creates a new empty table and pushes it onto the stack.
4449It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
4450
4451
4452
4453
4454
4455<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
4456<span class="apii">[-0, +1, <em>m</em>]</span>
4457<pre>lua_State *lua_newthread (lua_State *L);</pre>
4458
4459<p>
4460Creates a new thread, pushes it on the stack,
4461and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
4462The new thread returned by this function shares with the original thread
4463its global environment,
4464but has an independent execution stack.
4465
4466
4467<p>
4468Threads are subject to garbage collection,
4469like any Lua object.
4470
4471
4472
4473
4474
4475<hr><h3><a name="lua_newuserdatauv"><code>lua_newuserdatauv</code></a></h3><p>
4476<span class="apii">[-0, +1, <em>m</em>]</span>
4477<pre>void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);</pre>
4478
4479<p>
4480This function creates and pushes on the stack a new full userdata,
4481with <code>nuvalue</code> associated Lua values, called <code>user values</code>,
4482plus an associated block of raw memory with <code>size</code> bytes.
4483(The user values can be set and read with the functions
4484<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a> and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>.)
4485
4486
4487<p>
4488The function returns the address of the block of memory.
4489Lua ensures that this address is valid as long as
4490the corresponding userdata is alive (see <a href="#2.5">&sect;2.5</a>).
4491Moreover, if the userdata is marked for finalization (see <a href="#2.5.3">&sect;2.5.3</a>),
4492its address is valid at least until the call to its finalizer.
4493
4494
4495
4496
4497
4498<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4499<span class="apii">[-1, +(2|0), <em>v</em>]</span>
4500<pre>int lua_next (lua_State *L, int index);</pre>
4501
4502<p>
4503Pops a key from the stack,
4504and pushes a key&ndash;value pair from the table at the given index,
4505the "next" pair after the given key.
4506If there are no more elements in the table,
4507then <a href="#lua_next"><code>lua_next</code></a> returns 0 and pushes nothing.
4508
4509
4510<p>
4511A typical table traversal looks like this:
4512
4513<pre>
4514     /* table is in the stack at index 't' */
4515     lua_pushnil(L);  /* first key */
4516     while (lua_next(L, t) != 0) {
4517       /* uses 'key' (at index -2) and 'value' (at index -1) */
4518       printf("%s - %s\n",
4519              lua_typename(L, lua_type(L, -2)),
4520              lua_typename(L, lua_type(L, -1)));
4521       /* removes 'value'; keeps 'key' for next iteration */
4522       lua_pop(L, 1);
4523     }
4524</pre>
4525
4526<p>
4527While traversing a table,
4528avoid calling <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4529unless you know that the key is actually a string.
4530Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4531the value at the given index;
4532this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4533
4534
4535<p>
4536This function may raise an error if the given key
4537is neither <b>nil</b> nor present in the table.
4538See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4539the table during its traversal.
4540
4541
4542
4543
4544
4545<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4546<pre>typedef ... lua_Number;</pre>
4547
4548<p>
4549The type of floats in Lua.
4550
4551
4552<p>
4553By default this type is double,
4554but that can be changed to a single float or a long double.
4555(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
4556
4557
4558
4559
4560
4561<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4562<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4563
4564<p>
4565Tries to convert a Lua float to a Lua integer;
4566the float <code>n</code> must have an integral value.
4567If that value is within the range of Lua integers,
4568it is converted to an integer and assigned to <code>*p</code>.
4569The macro results in a boolean indicating whether the
4570conversion was successful.
4571(Note that this range test can be tricky to do
4572correctly without this macro, due to rounding.)
4573
4574
4575<p>
4576This macro may evaluate its arguments more than once.
4577
4578
4579
4580
4581
4582<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4583<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4584<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4585
4586<p>
4587Calls a function (or a callable object) in protected mode.
4588
4589
4590<p>
4591Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4592in <a href="#lua_call"><code>lua_call</code></a>.
4593If there are no errors during the call,
4594<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4595However, if there is any error,
4596<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4597pushes a single value on the stack (the error object),
4598and returns an error code.
4599Like <a href="#lua_call"><code>lua_call</code></a>,
4600<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4601and its arguments from the stack.
4602
4603
4604<p>
4605If <code>msgh</code> is 0,
4606then the error object returned on the stack
4607is exactly the original error object.
4608Otherwise, <code>msgh</code> is the stack index of a
4609<em>message handler</em>.
4610(This index cannot be a pseudo-index.)
4611In case of runtime errors,
4612this handler will be called with the error object
4613and its return value will be the object
4614returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4615
4616
4617<p>
4618Typically, the message handler is used to add more debug
4619information to the error object, such as a stack traceback.
4620Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4621since by then the stack has unwound.
4622
4623
4624<p>
4625The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following status codes:
4626<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>.
4627
4628
4629
4630
4631
4632<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4633<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4634<pre>int lua_pcallk (lua_State *L,
4635                int nargs,
4636                int nresults,
4637                int msgh,
4638                lua_KContext ctx,
4639                lua_KFunction k);</pre>
4640
4641<p>
4642This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4643except that it allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
4644
4645
4646
4647
4648
4649<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4650<span class="apii">[-n, +0, &ndash;]</span>
4651<pre>void lua_pop (lua_State *L, int n);</pre>
4652
4653<p>
4654Pops <code>n</code> elements from the stack.
4655
4656
4657
4658
4659
4660<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4661<span class="apii">[-0, +1, &ndash;]</span>
4662<pre>void lua_pushboolean (lua_State *L, int b);</pre>
4663
4664<p>
4665Pushes a boolean value with value <code>b</code> onto the stack.
4666
4667
4668
4669
4670
4671<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4672<span class="apii">[-n, +1, <em>m</em>]</span>
4673<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4674
4675<p>
4676Pushes a new C&nbsp;closure onto the stack.
4677This function receives a pointer to a C&nbsp;function
4678and pushes onto the stack a Lua value of type <code>function</code> that,
4679when called, invokes the corresponding C&nbsp;function.
4680The parameter <code>n</code> tells how many upvalues this function will have
4681(see <a href="#4.2">&sect;4.2</a>).
4682
4683
4684<p>
4685Any function to be callable by Lua must
4686follow the correct protocol to receive its parameters
4687and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4688
4689
4690<p>
4691When a C&nbsp;function is created,
4692it is possible to associate some values with it,
4693the so called upvalues;
4694these upvalues are then accessible to the function whenever it is called.
4695This association is called a C&nbsp;closure (see <a href="#4.2">&sect;4.2</a>).
4696To create a C&nbsp;closure,
4697first the initial values for its upvalues must be pushed onto the stack.
4698(When there are multiple upvalues, the first value is pushed first.)
4699Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4700is called to create and push the C&nbsp;function onto the stack,
4701with the argument <code>n</code> telling how many values will be
4702associated with the function.
4703<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4704
4705
4706<p>
4707The maximum value for <code>n</code> is 255.
4708
4709
4710<p>
4711When <code>n</code> is zero,
4712this function creates a <em>light C&nbsp;function</em>,
4713which is just a pointer to the C&nbsp;function.
4714In that case, it never raises a memory error.
4715
4716
4717
4718
4719
4720<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4721<span class="apii">[-0, +1, &ndash;]</span>
4722<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4723
4724<p>
4725Pushes a C&nbsp;function onto the stack.
4726This function is equivalent to <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> with no upvalues.
4727
4728
4729
4730
4731
4732<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4733<span class="apii">[-0, +1, <em>v</em>]</span>
4734<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4735
4736<p>
4737Pushes onto the stack a formatted string
4738and returns a pointer to this string (see <a href="#4.1.3">&sect;4.1.3</a>).
4739It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4740but has two important differences.
4741First,
4742you do not have to allocate space for the result;
4743the result is a Lua string and Lua takes care of memory allocation
4744(and deallocation, through garbage collection).
4745Second,
4746the conversion specifiers are quite restricted.
4747There are no flags, widths, or precisions.
4748The conversion specifiers can only be
4749'<code>%%</code>' (inserts the character '<code>%</code>'),
4750'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4751'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4752'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4753'<code>%p</code>' (inserts a pointer),
4754'<code>%d</code>' (inserts an <code>int</code>),
4755'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4756'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4757
4758
4759<p>
4760This function may raise errors due to memory overflow
4761or an invalid conversion specifier.
4762
4763
4764
4765
4766
4767<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4768<span class="apii">[-0, +1, &ndash;]</span>
4769<pre>void lua_pushglobaltable (lua_State *L);</pre>
4770
4771<p>
4772Pushes the global environment onto the stack.
4773
4774
4775
4776
4777
4778<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4779<span class="apii">[-0, +1, &ndash;]</span>
4780<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4781
4782<p>
4783Pushes an integer with value <code>n</code> onto the stack.
4784
4785
4786
4787
4788
4789<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4790<span class="apii">[-0, +1, &ndash;]</span>
4791<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4792
4793<p>
4794Pushes a light userdata onto the stack.
4795
4796
4797<p>
4798Userdata represent C&nbsp;values in Lua.
4799A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4800It is a value (like a number):
4801you do not create it, it has no individual metatable,
4802and it is not collected (as it was never created).
4803A light userdata is equal to "any"
4804light userdata with the same C&nbsp;address.
4805
4806
4807
4808
4809
4810<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4811<span class="apii">[-0, +1, <em>m</em>]</span>
4812<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4813
4814<p>
4815This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
4816but should be used only when <code>s</code> is a literal string.
4817(Lua may optimize this case.)
4818
4819
4820
4821
4822
4823<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4824<span class="apii">[-0, +1, <em>m</em>]</span>
4825<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4826
4827<p>
4828Pushes the string pointed to by <code>s</code> with size <code>len</code>
4829onto the stack.
4830Lua will make or reuse an internal copy of the given string,
4831so the memory at <code>s</code> can be freed or reused immediately after
4832the function returns.
4833The string can contain any binary data,
4834including embedded zeros.
4835
4836
4837<p>
4838Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4839
4840
4841
4842
4843
4844<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4845<span class="apii">[-0, +1, &ndash;]</span>
4846<pre>void lua_pushnil (lua_State *L);</pre>
4847
4848<p>
4849Pushes a nil value onto the stack.
4850
4851
4852
4853
4854
4855<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4856<span class="apii">[-0, +1, &ndash;]</span>
4857<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4858
4859<p>
4860Pushes a float with value <code>n</code> onto the stack.
4861
4862
4863
4864
4865
4866<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4867<span class="apii">[-0, +1, <em>m</em>]</span>
4868<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4869
4870<p>
4871Pushes the zero-terminated string pointed to by <code>s</code>
4872onto the stack.
4873Lua will make or reuse an internal copy of the given string,
4874so the memory at <code>s</code> can be freed or reused immediately after
4875the function returns.
4876
4877
4878<p>
4879Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4880
4881
4882<p>
4883If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4884
4885
4886
4887
4888
4889<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4890<span class="apii">[-0, +1, &ndash;]</span>
4891<pre>int lua_pushthread (lua_State *L);</pre>
4892
4893<p>
4894Pushes the thread represented by <code>L</code> onto the stack.
4895Returns 1 if this thread is the main thread of its state.
4896
4897
4898
4899
4900
4901<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4902<span class="apii">[-0, +1, &ndash;]</span>
4903<pre>void lua_pushvalue (lua_State *L, int index);</pre>
4904
4905<p>
4906Pushes a copy of the element at the given index
4907onto the stack.
4908
4909
4910
4911
4912
4913<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4914<span class="apii">[-0, +1, <em>v</em>]</span>
4915<pre>const char *lua_pushvfstring (lua_State *L,
4916                              const char *fmt,
4917                              va_list argp);</pre>
4918
4919<p>
4920Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4921instead of a variable number of arguments.
4922
4923
4924
4925
4926
4927<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4928<span class="apii">[-0, +0, &ndash;]</span>
4929<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4930
4931<p>
4932Returns 1 if the two values in indices <code>index1</code> and
4933<code>index2</code> are primitively equal
4934(that is, equal without calling the <code>__eq</code> metamethod).
4935Otherwise returns&nbsp;0.
4936Also returns&nbsp;0 if any of the indices are not valid.
4937
4938
4939
4940
4941
4942<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4943<span class="apii">[-1, +1, &ndash;]</span>
4944<pre>int lua_rawget (lua_State *L, int index);</pre>
4945
4946<p>
4947Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4948(i.e., without metamethods).
4949
4950
4951
4952
4953
4954<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4955<span class="apii">[-0, +1, &ndash;]</span>
4956<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4957
4958<p>
4959Pushes onto the stack the value <code>t[n]</code>,
4960where <code>t</code> is the table at the given index.
4961The access is raw,
4962that is, it does not use the <code>__index</code> metavalue.
4963
4964
4965<p>
4966Returns the type of the pushed value.
4967
4968
4969
4970
4971
4972<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4973<span class="apii">[-0, +1, &ndash;]</span>
4974<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4975
4976<p>
4977Pushes onto the stack the value <code>t[k]</code>,
4978where <code>t</code> is the table at the given index and
4979<code>k</code> is the pointer <code>p</code> represented as a light userdata.
4980The access is raw;
4981that is, it does not use the <code>__index</code> metavalue.
4982
4983
4984<p>
4985Returns the type of the pushed value.
4986
4987
4988
4989
4990
4991<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
4992<span class="apii">[-0, +0, &ndash;]</span>
4993<pre>lua_Unsigned lua_rawlen (lua_State *L, int index);</pre>
4994
4995<p>
4996Returns the raw "length" of the value at the given index:
4997for strings, this is the string length;
4998for tables, this is the result of the length operator ('<code>#</code>')
4999with no metamethods;
5000for userdata, this is the size of the block of memory allocated
5001for the userdata.
5002For other values, this call returns&nbsp;0.
5003
5004
5005
5006
5007
5008<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
5009<span class="apii">[-2, +0, <em>m</em>]</span>
5010<pre>void lua_rawset (lua_State *L, int index);</pre>
5011
5012<p>
5013Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
5014(i.e., without metamethods).
5015
5016
5017
5018
5019
5020<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
5021<span class="apii">[-1, +0, <em>m</em>]</span>
5022<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
5023
5024<p>
5025Does the equivalent of <code>t[i] = v</code>,
5026where <code>t</code> is the table at the given index
5027and <code>v</code> is the value on the top of the stack.
5028
5029
5030<p>
5031This function pops the value from the stack.
5032The assignment is raw,
5033that is, it does not use the <code>__newindex</code> metavalue.
5034
5035
5036
5037
5038
5039<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
5040<span class="apii">[-1, +0, <em>m</em>]</span>
5041<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
5042
5043<p>
5044Does the equivalent of <code>t[p] = v</code>,
5045where <code>t</code> is the table at the given index,
5046<code>p</code> is encoded as a light userdata,
5047and <code>v</code> is the value on the top of the stack.
5048
5049
5050<p>
5051This function pops the value from the stack.
5052The assignment is raw,
5053that is, it does not use the <code>__newindex</code> metavalue.
5054
5055
5056
5057
5058
5059<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
5060<pre>typedef const char * (*lua_Reader) (lua_State *L,
5061                                    void *data,
5062                                    size_t *size);</pre>
5063
5064<p>
5065The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
5066Every time <a href="#lua_load"><code>lua_load</code></a> needs another piece of the chunk,
5067it calls the reader,
5068passing along its <code>data</code> parameter.
5069The reader must return a pointer to a block of memory
5070with a new piece of the chunk
5071and set <code>size</code> to the block size.
5072The block must exist until the reader function is called again.
5073To signal the end of the chunk,
5074the reader must return <code>NULL</code> or set <code>size</code> to zero.
5075The reader function may return pieces of any size greater than zero.
5076
5077
5078
5079
5080
5081<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
5082<span class="apii">[-0, +0, <em>e</em>]</span>
5083<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
5084
5085<p>
5086Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>.
5087It is defined as a macro:
5088
5089<pre>
5090     #define lua_register(L,n,f) \
5091            (lua_pushcfunction(L, f), lua_setglobal(L, n))
5092</pre>
5093
5094
5095
5096
5097<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
5098<span class="apii">[-1, +0, &ndash;]</span>
5099<pre>void lua_remove (lua_State *L, int index);</pre>
5100
5101<p>
5102Removes the element at the given valid index,
5103shifting down the elements above this index to fill the gap.
5104This function cannot be called with a pseudo-index,
5105because a pseudo-index is not an actual stack position.
5106
5107
5108
5109
5110
5111<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
5112<span class="apii">[-1, +0, &ndash;]</span>
5113<pre>void lua_replace (lua_State *L, int index);</pre>
5114
5115<p>
5116Moves the top element into the given valid index
5117without shifting any element
5118(therefore replacing the value at that given index),
5119and then pops the top element.
5120
5121
5122
5123
5124
5125<hr><h3><a name="lua_resetthread"><code>lua_resetthread</code></a></h3><p>
5126<span class="apii">[-0, +?, &ndash;]</span>
5127<pre>int lua_resetthread (lua_State *L);</pre>
5128
5129<p>
5130Resets a thread, cleaning its call stack and closing all pending
5131to-be-closed variables.
5132Returns a status code:
5133<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for no errors in closing methods,
5134or an error status otherwise.
5135In case of error,
5136leaves the error object on the top of the stack,
5137
5138
5139
5140
5141
5142<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
5143<span class="apii">[-?, +?, &ndash;]</span>
5144<pre>int lua_resume (lua_State *L, lua_State *from, int nargs,
5145                          int *nresults);</pre>
5146
5147<p>
5148Starts and resumes a coroutine in the given thread <code>L</code>.
5149
5150
5151<p>
5152To start a coroutine,
5153you push the main function plus any arguments
5154onto the empty stack of the thread.
5155then you call <a href="#lua_resume"><code>lua_resume</code></a>,
5156with <code>nargs</code> being the number of arguments.
5157This call returns when the coroutine suspends or finishes its execution.
5158When it returns,
5159<code>*nresults</code> is updated and
5160the top of the stack contains
5161the <code>*nresults</code> values passed to <a href="#lua_yield"><code>lua_yield</code></a>
5162or returned by the body function.
5163<a href="#lua_resume"><code>lua_resume</code></a> returns
5164<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
5165<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
5166without errors,
5167or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
5168In case of errors,
5169the error object is on the top of the stack.
5170
5171
5172<p>
5173To resume a coroutine,
5174you remove the <code>*nresults</code> yielded values from its stack,
5175push the values to be passed as results from <code>yield</code>,
5176and then call <a href="#lua_resume"><code>lua_resume</code></a>.
5177
5178
5179<p>
5180The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
5181If there is no such coroutine,
5182this parameter can be <code>NULL</code>.
5183
5184
5185
5186
5187
5188<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
5189<span class="apii">[-0, +0, &ndash;]</span>
5190<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
5191
5192<p>
5193Rotates the stack elements between the valid index <code>idx</code>
5194and the top of the stack.
5195The elements are rotated <code>n</code> positions in the direction of the top,
5196for a positive <code>n</code>,
5197or <code>-n</code> positions in the direction of the bottom,
5198for a negative <code>n</code>.
5199The absolute value of <code>n</code> must not be greater than the size
5200of the slice being rotated.
5201This function cannot be called with a pseudo-index,
5202because a pseudo-index is not an actual stack position.
5203
5204
5205
5206
5207
5208<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
5209<span class="apii">[-0, +0, &ndash;]</span>
5210<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
5211
5212<p>
5213Changes the allocator function of a given state to <code>f</code>
5214with user data <code>ud</code>.
5215
5216
5217
5218
5219
5220<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
5221<span class="apii">[-1, +0, <em>e</em>]</span>
5222<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
5223
5224<p>
5225Does the equivalent to <code>t[k] = v</code>,
5226where <code>t</code> is the value at the given index
5227and <code>v</code> is the value on the top of the stack.
5228
5229
5230<p>
5231This function pops the value from the stack.
5232As in Lua, this function may trigger a metamethod
5233for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5234
5235
5236
5237
5238
5239<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
5240<span class="apii">[-1, +0, <em>e</em>]</span>
5241<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
5242
5243<p>
5244Pops a value from the stack and
5245sets it as the new value of global <code>name</code>.
5246
5247
5248
5249
5250
5251<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
5252<span class="apii">[-1, +0, <em>e</em>]</span>
5253<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
5254
5255<p>
5256Does the equivalent to <code>t[n] = v</code>,
5257where <code>t</code> is the value at the given index
5258and <code>v</code> is the value on the top of the stack.
5259
5260
5261<p>
5262This function pops the value from the stack.
5263As in Lua, this function may trigger a metamethod
5264for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5265
5266
5267
5268
5269
5270<hr><h3><a name="lua_setiuservalue"><code>lua_setiuservalue</code></a></h3><p>
5271<span class="apii">[-1, +0, &ndash;]</span>
5272<pre>int lua_setiuservalue (lua_State *L, int index, int n);</pre>
5273
5274<p>
5275Pops a value from the stack and sets it as
5276the new <code>n</code>-th user value associated to the
5277full userdata at the given index.
5278Returns 0 if the userdata does not have that value.
5279
5280
5281
5282
5283
5284<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
5285<span class="apii">[-1, +0, &ndash;]</span>
5286<pre>int lua_setmetatable (lua_State *L, int index);</pre>
5287
5288<p>
5289Pops a table or <b>nil</b> from the stack and
5290sets that value as the new metatable for the value at the given index.
5291(<b>nil</b> means no metatable.)
5292
5293
5294<p>
5295(For historical reasons, this function returns an <code>int</code>,
5296which now is always 1.)
5297
5298
5299
5300
5301
5302<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
5303<span class="apii">[-2, +0, <em>e</em>]</span>
5304<pre>void lua_settable (lua_State *L, int index);</pre>
5305
5306<p>
5307Does the equivalent to <code>t[k] = v</code>,
5308where <code>t</code> is the value at the given index,
5309<code>v</code> is the value on the top of the stack,
5310and <code>k</code> is the value just below the top.
5311
5312
5313<p>
5314This function pops both the key and the value from the stack.
5315As in Lua, this function may trigger a metamethod
5316for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5317
5318
5319
5320
5321
5322<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
5323<span class="apii">[-?, +?, &ndash;]</span>
5324<pre>void lua_settop (lua_State *L, int index);</pre>
5325
5326<p>
5327Accepts any index, or&nbsp;0,
5328and sets the stack top to this index.
5329If the new top is greater than the old one,
5330then the new elements are filled with <b>nil</b>.
5331If <code>index</code> is&nbsp;0, then all stack elements are removed.
5332
5333
5334
5335
5336
5337<hr><h3><a name="lua_setwarnf"><code>lua_setwarnf</code></a></h3><p>
5338<span class="apii">[-0, +0, &ndash;]</span>
5339<pre>void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);</pre>
5340
5341<p>
5342Sets the warning function to be used by Lua to emit warnings
5343(see <a href="#lua_WarnFunction"><code>lua_WarnFunction</code></a>).
5344The <code>ud</code> parameter sets the value <code>ud</code> passed to
5345the warning function.
5346
5347
5348
5349
5350
5351<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
5352<pre>typedef struct lua_State lua_State;</pre>
5353
5354<p>
5355An opaque structure that points to a thread and indirectly
5356(through the thread) to the whole state of a Lua interpreter.
5357The Lua library is fully reentrant:
5358it has no global variables.
5359All information about a state is accessible through this structure.
5360
5361
5362<p>
5363A pointer to this structure must be passed as the first argument to
5364every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
5365which creates a Lua state from scratch.
5366
5367
5368
5369
5370
5371<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
5372<span class="apii">[-0, +0, &ndash;]</span>
5373<pre>int lua_status (lua_State *L);</pre>
5374
5375<p>
5376Returns the status of the thread <code>L</code>.
5377
5378
5379<p>
5380The status can be <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for a normal thread,
5381an error code if the thread finished the execution
5382of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
5383or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
5384
5385
5386<p>
5387You can call functions only in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
5388You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
5389(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
5390(to resume a coroutine).
5391
5392
5393
5394
5395
5396<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
5397<span class="apii">[-0, +1, &ndash;]</span>
5398<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
5399
5400<p>
5401Converts the zero-terminated string <code>s</code> to a number,
5402pushes that number into the stack,
5403and returns the total size of the string,
5404that is, its length plus one.
5405The conversion can result in an integer or a float,
5406according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
5407The string may have leading and trailing whitespaces and a sign.
5408If the string is not a valid numeral,
5409returns 0 and pushes nothing.
5410(Note that the result can be used as a boolean,
5411true if the conversion succeeds.)
5412
5413
5414
5415
5416
5417<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
5418<span class="apii">[-0, +0, &ndash;]</span>
5419<pre>int lua_toboolean (lua_State *L, int index);</pre>
5420
5421<p>
5422Converts the Lua value at the given index to a C&nbsp;boolean
5423value (0&nbsp;or&nbsp;1).
5424Like all tests in Lua,
5425<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
5426different from <b>false</b> and <b>nil</b>;
5427otherwise it returns false.
5428(If you want to accept only actual boolean values,
5429use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
5430
5431
5432
5433
5434
5435<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
5436<span class="apii">[-0, +0, &ndash;]</span>
5437<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
5438
5439<p>
5440Converts a value at the given index to a C&nbsp;function.
5441That value must be a C&nbsp;function;
5442otherwise, returns <code>NULL</code>.
5443
5444
5445
5446
5447
5448<hr><h3><a name="lua_toclose"><code>lua_toclose</code></a></h3><p>
5449<span class="apii">[-0, +0, <em>m</em>]</span>
5450<pre>void lua_toclose (lua_State *L, int index);</pre>
5451
5452<p>
5453Marks the given index in the stack as a
5454to-be-closed "variable" (see <a href="#3.3.8">&sect;3.3.8</a>).
5455Like a to-be-closed variable in Lua,
5456the value at that index in the stack will be closed
5457when it goes out of scope.
5458Here, in the context of a C function,
5459to go out of scope means that the running function returns to Lua,
5460there is an error,
5461or the index is removed from the stack through
5462<a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>.
5463An index marked as to-be-closed should not be removed from the stack
5464by 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>.
5465
5466
5467<p>
5468This function should not be called for an index
5469that is equal to or below an active to-be-closed index.
5470
5471
5472<p>
5473In the case of an out-of-memory error,
5474the value in the given index is immediately closed,
5475as if it was already marked.
5476
5477
5478<p>
5479Note that, both in case of errors and of a regular return,
5480by the time the <code>__close</code> metamethod runs,
5481the C&nbsp;stack was already unwound,
5482so that any automatic C variable declared in the calling function
5483will be out of scope.
5484
5485
5486
5487
5488
5489<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
5490<span class="apii">[-0, +0, &ndash;]</span>
5491<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
5492
5493<p>
5494Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5495
5496
5497
5498
5499
5500<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
5501<span class="apii">[-0, +0, &ndash;]</span>
5502<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
5503
5504<p>
5505Converts the Lua value at the given index
5506to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
5507The Lua value must be an integer,
5508or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
5509otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
5510
5511
5512<p>
5513If <code>isnum</code> is not <code>NULL</code>,
5514its referent is assigned a boolean value that
5515indicates whether the operation succeeded.
5516
5517
5518
5519
5520
5521<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
5522<span class="apii">[-0, +0, <em>m</em>]</span>
5523<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5524
5525<p>
5526Converts the Lua value at the given index to a C&nbsp;string.
5527If <code>len</code> is not <code>NULL</code>,
5528it sets <code>*len</code> with the string length.
5529The Lua value must be a string or a number;
5530otherwise, the function returns <code>NULL</code>.
5531If the value is a number,
5532then <code>lua_tolstring</code> also
5533<em>changes the actual value in the stack to a string</em>.
5534(This change confuses <a href="#lua_next"><code>lua_next</code></a>
5535when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5536
5537
5538<p>
5539<code>lua_tolstring</code> returns a pointer
5540to a string inside the Lua state (see <a href="#4.1.3">&sect;4.1.3</a>).
5541This string always has a zero ('<code>\0</code>')
5542after its last character (as in&nbsp;C),
5543but can contain other zeros in its body.
5544
5545
5546
5547
5548
5549<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5550<span class="apii">[-0, +0, &ndash;]</span>
5551<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5552
5553<p>
5554Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5555
5556
5557
5558
5559
5560<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5561<span class="apii">[-0, +0, &ndash;]</span>
5562<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5563
5564<p>
5565Converts the Lua value at the given index
5566to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5567The Lua value must be a number or a string convertible to a number
5568(see <a href="#3.4.3">&sect;3.4.3</a>);
5569otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5570
5571
5572<p>
5573If <code>isnum</code> is not <code>NULL</code>,
5574its referent is assigned a boolean value that
5575indicates whether the operation succeeded.
5576
5577
5578
5579
5580
5581<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5582<span class="apii">[-0, +0, &ndash;]</span>
5583<pre>const void *lua_topointer (lua_State *L, int index);</pre>
5584
5585<p>
5586Converts the value at the given index to a generic
5587C&nbsp;pointer (<code>void*</code>).
5588The value can be a userdata, a table, a thread, a string, or a function;
5589otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5590Different objects will give different pointers.
5591There is no way to convert the pointer back to its original value.
5592
5593
5594<p>
5595Typically this function is used only for hashing and debug information.
5596
5597
5598
5599
5600
5601<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5602<span class="apii">[-0, +0, <em>m</em>]</span>
5603<pre>const char *lua_tostring (lua_State *L, int index);</pre>
5604
5605<p>
5606Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5607
5608
5609
5610
5611
5612<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5613<span class="apii">[-0, +0, &ndash;]</span>
5614<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5615
5616<p>
5617Converts the value at the given index to a Lua thread
5618(represented as <code>lua_State*</code>).
5619This value must be a thread;
5620otherwise, the function returns <code>NULL</code>.
5621
5622
5623
5624
5625
5626<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5627<span class="apii">[-0, +0, &ndash;]</span>
5628<pre>void *lua_touserdata (lua_State *L, int index);</pre>
5629
5630<p>
5631If the value at the given index is a full userdata,
5632returns its memory-block address.
5633If the value is a light userdata,
5634returns its value (a pointer).
5635Otherwise, returns <code>NULL</code>.
5636
5637
5638
5639
5640
5641<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5642<span class="apii">[-0, +0, &ndash;]</span>
5643<pre>int lua_type (lua_State *L, int index);</pre>
5644
5645<p>
5646Returns the type of the value in the given valid index,
5647or <code>LUA_TNONE</code> for a non-valid but acceptable index.
5648The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5649defined in <code>lua.h</code>:
5650<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5651<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5652<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5653<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5654<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5655<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5656<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5657<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5658and
5659<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5660
5661
5662
5663
5664
5665<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5666<span class="apii">[-0, +0, &ndash;]</span>
5667<pre>const char *lua_typename (lua_State *L, int tp);</pre>
5668
5669<p>
5670Returns the name of the type encoded by the value <code>tp</code>,
5671which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5672
5673
5674
5675
5676
5677<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5678<pre>typedef ... lua_Unsigned;</pre>
5679
5680<p>
5681The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5682
5683
5684
5685
5686
5687<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5688<span class="apii">[-0, +0, &ndash;]</span>
5689<pre>int lua_upvalueindex (int i);</pre>
5690
5691<p>
5692Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5693the running function (see <a href="#4.2">&sect;4.2</a>).
5694<code>i</code> must be in the range <em>[1,256]</em>.
5695
5696
5697
5698
5699
5700<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5701<span class="apii">[-0, +0, &ndash;]</span>
5702<pre>lua_Number lua_version (lua_State *L);</pre>
5703
5704<p>
5705Returns the version number of this core.
5706
5707
5708
5709
5710
5711<hr><h3><a name="lua_WarnFunction"><code>lua_WarnFunction</code></a></h3>
5712<pre>typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);</pre>
5713
5714<p>
5715The type of warning functions, called by Lua to emit warnings.
5716The first parameter is an opaque pointer
5717set by <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>.
5718The second parameter is the warning message.
5719The third parameter is a boolean that
5720indicates whether the message is
5721to be continued by the message in the next call.
5722
5723
5724<p>
5725See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5726
5727
5728
5729
5730
5731<hr><h3><a name="lua_warning"><code>lua_warning</code></a></h3><p>
5732<span class="apii">[-0, +0, &ndash;]</span>
5733<pre>void lua_warning (lua_State *L, const char *msg, int tocont);</pre>
5734
5735<p>
5736Emits a warning with the given message.
5737A message in a call with <code>tocont</code> true should be
5738continued in another call to this function.
5739
5740
5741<p>
5742See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5743
5744
5745
5746
5747
5748<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5749<pre>typedef int (*lua_Writer) (lua_State *L,
5750                           const void* p,
5751                           size_t sz,
5752                           void* ud);</pre>
5753
5754<p>
5755The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5756Every time <a href="#lua_dump"><code>lua_dump</code></a> produces another piece of chunk,
5757it calls the writer,
5758passing along the buffer to be written (<code>p</code>),
5759its size (<code>sz</code>),
5760and the <code>ud</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5761
5762
5763<p>
5764The writer returns an error code:
57650&nbsp;means no errors;
5766any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5767calling the writer again.
5768
5769
5770
5771
5772
5773<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5774<span class="apii">[-?, +?, &ndash;]</span>
5775<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5776
5777<p>
5778Exchange values between different threads of the same state.
5779
5780
5781<p>
5782This function pops <code>n</code> values from the stack <code>from</code>,
5783and pushes them onto the stack <code>to</code>.
5784
5785
5786
5787
5788
5789<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5790<span class="apii">[-?, +?, <em>v</em>]</span>
5791<pre>int lua_yield (lua_State *L, int nresults);</pre>
5792
5793<p>
5794This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5795but it has no continuation (see <a href="#4.5">&sect;4.5</a>).
5796Therefore, when the thread resumes,
5797it continues the function that called
5798the function calling <code>lua_yield</code>.
5799To avoid surprises,
5800this function should be called only in a tail call.
5801
5802
5803
5804
5805
5806<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5807<span class="apii">[-?, +?, <em>v</em>]</span>
5808<pre>int lua_yieldk (lua_State *L,
5809                int nresults,
5810                lua_KContext ctx,
5811                lua_KFunction k);</pre>
5812
5813<p>
5814Yields a coroutine (thread).
5815
5816
5817<p>
5818When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5819the running coroutine suspends its execution,
5820and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5821The parameter <code>nresults</code> is the number of values from the stack
5822that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5823
5824
5825<p>
5826When the coroutine is resumed again,
5827Lua calls the given continuation function <code>k</code> to continue
5828the execution of the C&nbsp;function that yielded (see <a href="#4.5">&sect;4.5</a>).
5829This continuation function receives the same stack
5830from the previous function,
5831with the <code>n</code> results removed and
5832replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5833Moreover,
5834the continuation function receives the value <code>ctx</code>
5835that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5836
5837
5838<p>
5839Usually, this function does not return;
5840when the coroutine eventually resumes,
5841it continues executing the continuation function.
5842However, there is one special case,
5843which is when this function is called
5844from inside a line or a count hook (see <a href="#4.7">&sect;4.7</a>).
5845In that case, <code>lua_yieldk</code> should be called with no continuation
5846(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
5847and the hook should return immediately after the call.
5848Lua will yield and,
5849when the coroutine resumes again,
5850it will continue the normal execution
5851of the (Lua) function that triggered the hook.
5852
5853
5854<p>
5855This function can raise an error if it is called from a thread
5856with a pending C call with no continuation function
5857(what is called a <em>C-call boundary</em>),
5858or it is called from a thread that is not running inside a resume
5859(typically the main thread).
5860
5861
5862
5863
5864
5865
5866
5867<h2>4.7 &ndash; <a name="4.7">The Debug Interface</a></h2>
5868
5869<p>
5870Lua has no built-in debugging facilities.
5871Instead, it offers a special interface
5872by means of functions and <em>hooks</em>.
5873This interface allows the construction of different
5874kinds of debuggers, profilers, and other tools
5875that need "inside information" from the interpreter.
5876
5877
5878
5879<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5880<pre>typedef struct lua_Debug {
5881  int event;
5882  const char *name;           /* (n) */
5883  const char *namewhat;       /* (n) */
5884  const char *what;           /* (S) */
5885  const char *source;         /* (S) */
5886  size_t srclen;              /* (S) */
5887  int currentline;            /* (l) */
5888  int linedefined;            /* (S) */
5889  int lastlinedefined;        /* (S) */
5890  unsigned char nups;         /* (u) number of upvalues */
5891  unsigned char nparams;      /* (u) number of parameters */
5892  char isvararg;              /* (u) */
5893  char istailcall;            /* (t) */
5894  unsigned short ftransfer;   /* (r) index of first value transferred */
5895  unsigned short ntransfer;   /* (r) number of transferred values */
5896  char short_src[LUA_IDSIZE]; /* (S) */
5897  /* private part */
5898  <em>other fields</em>
5899} lua_Debug;</pre>
5900
5901<p>
5902A structure used to carry different pieces of
5903information about a function or an activation record.
5904<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5905of this structure, for later use.
5906To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5907you must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5908
5909
5910<p>
5911The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5912
5913<ul>
5914
5915<li><b><code>source</code>: </b>
5916the source of the chunk that created the function.
5917If <code>source</code> starts with a '<code>@</code>',
5918it means that the function was defined in a file where
5919the file name follows the '<code>@</code>'.
5920If <code>source</code> starts with a '<code>=</code>',
5921the remainder of its contents describes the source in a user-dependent manner.
5922Otherwise,
5923the function was defined in a string where
5924<code>source</code> is that string.
5925</li>
5926
5927<li><b><code>srclen</code>: </b>
5928The length of the string <code>source</code>.
5929</li>
5930
5931<li><b><code>short_src</code>: </b>
5932a "printable" version of <code>source</code>, to be used in error messages.
5933</li>
5934
5935<li><b><code>linedefined</code>: </b>
5936the line number where the definition of the function starts.
5937</li>
5938
5939<li><b><code>lastlinedefined</code>: </b>
5940the line number where the definition of the function ends.
5941</li>
5942
5943<li><b><code>what</code>: </b>
5944the string <code>"Lua"</code> if the function is a Lua function,
5945<code>"C"</code> if it is a C&nbsp;function,
5946<code>"main"</code> if it is the main part of a chunk.
5947</li>
5948
5949<li><b><code>currentline</code>: </b>
5950the current line where the given function is executing.
5951When no line information is available,
5952<code>currentline</code> is set to -1.
5953</li>
5954
5955<li><b><code>name</code>: </b>
5956a reasonable name for the given function.
5957Because functions in Lua are first-class values,
5958they do not have a fixed name:
5959some functions can be the value of multiple global variables,
5960while others can be stored only in a table field.
5961The <code>lua_getinfo</code> function checks how the function was
5962called to find a suitable name.
5963If it cannot find a name,
5964then <code>name</code> is set to <code>NULL</code>.
5965</li>
5966
5967<li><b><code>namewhat</code>: </b>
5968explains the <code>name</code> field.
5969The value of <code>namewhat</code> can be
5970<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
5971<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
5972according to how the function was called.
5973(Lua uses the empty string when no other option seems to apply.)
5974</li>
5975
5976<li><b><code>istailcall</code>: </b>
5977true if this function invocation was called by a tail call.
5978In this case, the caller of this level is not in the stack.
5979</li>
5980
5981<li><b><code>nups</code>: </b>
5982the number of upvalues of the function.
5983</li>
5984
5985<li><b><code>nparams</code>: </b>
5986the number of parameters of the function
5987(always 0&nbsp;for C&nbsp;functions).
5988</li>
5989
5990<li><b><code>isvararg</code>: </b>
5991true if the function is a vararg function
5992(always true for C&nbsp;functions).
5993</li>
5994
5995<li><b><code>ftransfer</code>: </b>
5996the index in the stack of the first value being "transferred",
5997that is, parameters in a call or return values in a return.
5998(The other values are in consecutive indices.)
5999Using this index, you can access and modify these values
6000through <a href="#lua_getlocal"><code>lua_getlocal</code></a> and <a href="#lua_setlocal"><code>lua_setlocal</code></a>.
6001This field is only meaningful during a
6002call hook, denoting the first parameter,
6003or a return hook, denoting the first value being returned.
6004(For call hooks, this value is always 1.)
6005</li>
6006
6007<li><b><code>ntransfer</code>: </b>
6008The number of values being transferred (see previous item).
6009(For calls of Lua functions,
6010this value is always equal to <code>nparams</code>.)
6011</li>
6012
6013</ul>
6014
6015
6016
6017
6018<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
6019<span class="apii">[-0, +0, &ndash;]</span>
6020<pre>lua_Hook lua_gethook (lua_State *L);</pre>
6021
6022<p>
6023Returns the current hook function.
6024
6025
6026
6027
6028
6029<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
6030<span class="apii">[-0, +0, &ndash;]</span>
6031<pre>int lua_gethookcount (lua_State *L);</pre>
6032
6033<p>
6034Returns the current hook count.
6035
6036
6037
6038
6039
6040<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
6041<span class="apii">[-0, +0, &ndash;]</span>
6042<pre>int lua_gethookmask (lua_State *L);</pre>
6043
6044<p>
6045Returns the current hook mask.
6046
6047
6048
6049
6050
6051<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
6052<span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
6053<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
6054
6055<p>
6056Gets information about a specific function or function invocation.
6057
6058
6059<p>
6060To get information about a function invocation,
6061the parameter <code>ar</code> must be a valid activation record that was
6062filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6063given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6064
6065
6066<p>
6067To get information about a function, you push it onto the stack
6068and start the <code>what</code> string with the character '<code>&gt;</code>'.
6069(In that case,
6070<code>lua_getinfo</code> pops the function from the top of the stack.)
6071For instance, to know in which line a function <code>f</code> was defined,
6072you can write the following code:
6073
6074<pre>
6075     lua_Debug ar;
6076     lua_getglobal(L, "f");  /* get global 'f' */
6077     lua_getinfo(L, "&gt;S", &amp;ar);
6078     printf("%d\n", ar.linedefined);
6079</pre>
6080
6081<p>
6082Each character in the string <code>what</code>
6083selects some fields of the structure <code>ar</code> to be filled or
6084a value to be pushed on the stack:
6085
6086<ul>
6087
6088<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
6089</li>
6090
6091<li><b>'<code>S</code>': </b>
6092fills in the fields <code>source</code>, <code>short_src</code>,
6093<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
6094</li>
6095
6096<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
6097</li>
6098
6099<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
6100</li>
6101
6102<li><b>'<code>u</code>': </b> fills in the fields
6103<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
6104</li>
6105
6106<li><b>'<code>f</code>': </b>
6107pushes onto the stack the function that is
6108running at the given level;
6109</li>
6110
6111<li><b>'<code>L</code>': </b>
6112pushes onto the stack a table whose indices are the
6113numbers of the lines that are valid on the function.
6114(A <em>valid line</em> is a line with some associated code,
6115that is, a line where you can put a break point.
6116Non-valid lines include empty lines and comments.)
6117
6118
6119<p>
6120If this option is given together with option '<code>f</code>',
6121its table is pushed after the function.
6122
6123
6124<p>
6125This is the only option that can raise a memory error.
6126</li>
6127
6128</ul>
6129
6130<p>
6131This function returns 0 to signal an invalid option in <code>what</code>;
6132even then the valid options are handled correctly.
6133
6134
6135
6136
6137
6138<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
6139<span class="apii">[-0, +(0|1), &ndash;]</span>
6140<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6141
6142<p>
6143Gets information about a local variable or a temporary value
6144of a given activation record or a given function.
6145
6146
6147<p>
6148In the first case,
6149the parameter <code>ar</code> must be a valid activation record that was
6150filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6151given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6152The index <code>n</code> selects which local variable to inspect;
6153see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
6154and names.
6155
6156
6157<p>
6158<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
6159and returns its name.
6160
6161
6162<p>
6163In the second case, <code>ar</code> must be <code>NULL</code> and the function
6164to be inspected must be on the top of the stack.
6165In this case, only parameters of Lua functions are visible
6166(as there is no information about what variables are active)
6167and no values are pushed onto the stack.
6168
6169
6170<p>
6171Returns <code>NULL</code> (and pushes nothing)
6172when the index is greater than
6173the number of active local variables.
6174
6175
6176
6177
6178
6179<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
6180<span class="apii">[-0, +0, &ndash;]</span>
6181<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
6182
6183<p>
6184Gets information about the interpreter runtime stack.
6185
6186
6187<p>
6188This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
6189an identification of the <em>activation record</em>
6190of the function executing at a given level.
6191Level&nbsp;0 is the current running function,
6192whereas level <em>n+1</em> is the function that has called level <em>n</em>
6193(except for tail calls, which do not count in the stack).
6194When called with a level greater than the stack depth,
6195<a href="#lua_getstack"><code>lua_getstack</code></a> returns 0;
6196otherwise it returns 1.
6197
6198
6199
6200
6201
6202<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
6203<span class="apii">[-0, +(0|1), &ndash;]</span>
6204<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
6205
6206<p>
6207Gets information about the <code>n</code>-th upvalue
6208of the closure at index <code>funcindex</code>.
6209It pushes the upvalue's value onto the stack
6210and returns its name.
6211Returns <code>NULL</code> (and pushes nothing)
6212when the index <code>n</code> is greater than the number of upvalues.
6213
6214
6215<p>
6216See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
6217
6218
6219
6220
6221
6222<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
6223<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
6224
6225<p>
6226Type for debugging hook functions.
6227
6228
6229<p>
6230Whenever a hook is called, its <code>ar</code> argument has its field
6231<code>event</code> set to the specific event that triggered the hook.
6232Lua identifies these events with the following constants:
6233<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
6234<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
6235and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
6236Moreover, for line events, the field <code>currentline</code> is also set.
6237To get the value of any other field in <code>ar</code>,
6238the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
6239
6240
6241<p>
6242For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
6243the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
6244in this case, there will be no corresponding return event.
6245
6246
6247<p>
6248While Lua is running a hook, it disables other calls to hooks.
6249Therefore, if a hook calls back Lua to execute a function or a chunk,
6250this execution occurs without any calls to hooks.
6251
6252
6253<p>
6254Hook functions cannot have continuations,
6255that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
6256<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>.
6257
6258
6259<p>
6260Hook functions can yield under the following conditions:
6261Only count and line events can yield;
6262to yield, a hook function must finish its execution
6263calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
6264(that is, with no values).
6265
6266
6267
6268
6269
6270<hr><h3><a name="lua_setcstacklimit"><code>lua_setcstacklimit</code></a></h3><p>
6271<span class="apii">[-0, +0, &ndash;]</span>
6272<pre>int (lua_setcstacklimit) (lua_State *L, unsigned int limit);</pre>
6273
6274<p>
6275Sets a new limit for the C stack.
6276This limit controls how deeply nested calls can go in Lua,
6277with the intent of avoiding a stack overflow.
6278Returns the old limit in case of success,
6279or zero in case of error.
6280For more details about this function,
6281see <a href="#pdf-debug.setcstacklimit"><code>debug.setcstacklimit</code></a>,
6282its equivalent in the standard library.
6283
6284
6285
6286
6287
6288<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
6289<span class="apii">[-0, +0, &ndash;]</span>
6290<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
6291
6292<p>
6293Sets the debugging hook function.
6294
6295
6296<p>
6297Argument <code>f</code> is the hook function.
6298<code>mask</code> specifies on which events the hook will be called:
6299it is formed by a bitwise OR of the constants
6300<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
6301<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
6302<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
6303and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
6304The <code>count</code> argument is only meaningful when the mask
6305includes <code>LUA_MASKCOUNT</code>.
6306For each event, the hook is called as explained below:
6307
6308<ul>
6309
6310<li><b>The call hook: </b> is called when the interpreter calls a function.
6311The hook is called just after Lua enters the new function.
6312</li>
6313
6314<li><b>The return hook: </b> is called when the interpreter returns from a function.
6315The hook is called just before Lua leaves the function.
6316</li>
6317
6318<li><b>The line hook: </b> is called when the interpreter is about to
6319start the execution of a new line of code,
6320or when it jumps back in the code (even to the same line).
6321This event only happens while Lua is executing a Lua function.
6322</li>
6323
6324<li><b>The count hook: </b> is called after the interpreter executes every
6325<code>count</code> instructions.
6326This event only happens while Lua is executing a Lua function.
6327</li>
6328
6329</ul>
6330
6331<p>
6332Hooks are disabled by setting <code>mask</code> to zero.
6333
6334
6335
6336
6337
6338<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
6339<span class="apii">[-(0|1), +0, &ndash;]</span>
6340<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6341
6342<p>
6343Sets the value of a local variable of a given activation record.
6344It assigns the value on the top of the stack
6345to the variable and returns its name.
6346It also pops the value from the stack.
6347
6348
6349<p>
6350Returns <code>NULL</code> (and pops nothing)
6351when the index is greater than
6352the number of active local variables.
6353
6354
6355<p>
6356Parameters <code>ar</code> and <code>n</code> are as in the function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
6357
6358
6359
6360
6361
6362<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
6363<span class="apii">[-(0|1), +0, &ndash;]</span>
6364<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
6365
6366<p>
6367Sets the value of a closure's upvalue.
6368It assigns the value on the top of the stack
6369to the upvalue and returns its name.
6370It also pops the value from the stack.
6371
6372
6373<p>
6374Returns <code>NULL</code> (and pops nothing)
6375when the index <code>n</code> is greater than the number of upvalues.
6376
6377
6378<p>
6379Parameters <code>funcindex</code> and <code>n</code> are as in
6380the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
6381
6382
6383
6384
6385
6386<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
6387<span class="apii">[-0, +0, &ndash;]</span>
6388<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
6389
6390<p>
6391Returns a unique identifier for the upvalue numbered <code>n</code>
6392from the closure at index <code>funcindex</code>.
6393
6394
6395<p>
6396These unique identifiers allow a program to check whether different
6397closures share upvalues.
6398Lua closures that share an upvalue
6399(that is, that access a same external local variable)
6400will return identical ids for those upvalue indices.
6401
6402
6403<p>
6404Parameters <code>funcindex</code> and <code>n</code> are as in
6405the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
6406but <code>n</code> cannot be greater than the number of upvalues.
6407
6408
6409
6410
6411
6412<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
6413<span class="apii">[-0, +0, &ndash;]</span>
6414<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
6415                                    int funcindex2, int n2);</pre>
6416
6417<p>
6418Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
6419refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
6420
6421
6422
6423
6424
6425
6426
6427<h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
6428
6429
6430
6431<p>
6432
6433The <em>auxiliary library</em> provides several convenient functions
6434to interface C with Lua.
6435While the basic API provides the primitive functions for all
6436interactions between C and Lua,
6437the auxiliary library provides higher-level functions for some
6438common tasks.
6439
6440
6441<p>
6442All functions and types from the auxiliary library
6443are defined in header file <code>lauxlib.h</code> and
6444have a prefix <code>luaL_</code>.
6445
6446
6447<p>
6448All functions in the auxiliary library are built on
6449top of the basic API,
6450and so they provide nothing that cannot be done with that API.
6451Nevertheless, the use of the auxiliary library ensures
6452more consistency to your code.
6453
6454
6455<p>
6456Several functions in the auxiliary library use internally some
6457extra stack slots.
6458When a function in the auxiliary library uses less than five slots,
6459it does not check the stack size;
6460it simply assumes that there are enough slots.
6461
6462
6463<p>
6464Several functions in the auxiliary library are used to
6465check C&nbsp;function arguments.
6466Because the error message is formatted for arguments
6467(e.g., "<code>bad argument #1</code>"),
6468you should not use these functions for other stack values.
6469
6470
6471<p>
6472Functions called <code>luaL_check*</code>
6473always raise an error if the check is not satisfied.
6474
6475
6476
6477
6478
6479<h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
6480
6481<p>
6482Here we list all functions and types from the auxiliary library
6483in alphabetical order.
6484
6485
6486
6487<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
6488<span class="apii">[-?, +?, <em>m</em>]</span>
6489<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
6490
6491<p>
6492Adds the byte <code>c</code> to the buffer <code>B</code>
6493(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6494
6495
6496
6497
6498
6499<hr><h3><a name="luaL_addgsub"><code>luaL_addgsub</code></a></h3><p>
6500<span class="apii">[-0, +0, <em>m</em>]</span>
6501<pre>const void luaL_addgsub (luaL_Buffer *B, const char *s,
6502                         const char *p, const char *r);</pre>
6503
6504<p>
6505Adds a copy of the string <code>s</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>),
6506replacing any occurrence of the string <code>p</code>
6507with the string <code>r</code>.
6508
6509
6510
6511
6512
6513<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
6514<span class="apii">[-?, +?, <em>m</em>]</span>
6515<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
6516
6517<p>
6518Adds the string pointed to by <code>s</code> with length <code>l</code> to
6519the buffer <code>B</code>
6520(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6521The string can contain embedded zeros.
6522
6523
6524
6525
6526
6527<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
6528<span class="apii">[-?, +?, &ndash;]</span>
6529<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
6530
6531<p>
6532Adds to the buffer <code>B</code>
6533a string of length <code>n</code> previously copied to the
6534buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
6535
6536
6537
6538
6539
6540<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
6541<span class="apii">[-?, +?, <em>m</em>]</span>
6542<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
6543
6544<p>
6545Adds the zero-terminated string pointed to by <code>s</code>
6546to the buffer <code>B</code>
6547(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6548
6549
6550
6551
6552
6553<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
6554<span class="apii">[-1, +?, <em>m</em>]</span>
6555<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
6556
6557<p>
6558Adds the value on the top of the stack
6559to the buffer <code>B</code>
6560(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6561Pops the value.
6562
6563
6564<p>
6565This is the only function on string buffers that can (and must)
6566be called with an extra element on the stack,
6567which is the value to be added to the buffer.
6568
6569
6570
6571
6572
6573<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
6574<span class="apii">[-0, +0, <em>v</em>]</span>
6575<pre>void luaL_argcheck (lua_State *L,
6576                    int cond,
6577                    int arg,
6578                    const char *extramsg);</pre>
6579
6580<p>
6581Checks whether <code>cond</code> is true.
6582If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
6583
6584
6585
6586
6587
6588<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
6589<span class="apii">[-0, +0, <em>v</em>]</span>
6590<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
6591
6592<p>
6593Raises an error reporting a problem with argument <code>arg</code>
6594of the C&nbsp;function that called it,
6595using a standard message
6596that includes <code>extramsg</code> as a comment:
6597
6598<pre>
6599     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
6600</pre><p>
6601This function never returns.
6602
6603
6604
6605
6606
6607<hr><h3><a name="luaL_argexpected"><code>luaL_argexpected</code></a></h3><p>
6608<span class="apii">[-0, +0, <em>v</em>]</span>
6609<pre>void luaL_argexpected (lua_State *L,
6610                       int cond,
6611                       int arg,
6612                       const char *tname);</pre>
6613
6614<p>
6615Checks whether <code>cond</code> is true.
6616If it is not, raises an error about the type of the argument <code>arg</code>
6617with a standard message (see <a href="#luaL_typeerror"><code>luaL_typeerror</code></a>).
6618
6619
6620
6621
6622
6623<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
6624<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
6625
6626<p>
6627Type for a <em>string buffer</em>.
6628
6629
6630<p>
6631A string buffer allows C&nbsp;code to build Lua strings piecemeal.
6632Its pattern of use is as follows:
6633
6634<ul>
6635
6636<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6637
6638<li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6639
6640<li>
6641Then add string pieces to the buffer calling any of
6642the <code>luaL_add*</code> functions.
6643</li>
6644
6645<li>
6646Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6647This call leaves the final string on the top of the stack.
6648</li>
6649
6650</ul>
6651
6652<p>
6653If you know beforehand the maximum size of the resulting string,
6654you can use the buffer like this:
6655
6656<ul>
6657
6658<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6659
6660<li>Then initialize it and preallocate a space of
6661size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6662
6663<li>Then produce the string into that space.</li>
6664
6665<li>
6666Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6667where <code>sz</code> is the total size of the resulting string
6668copied into that space (which may be less than or
6669equal to the preallocated size).
6670</li>
6671
6672</ul>
6673
6674<p>
6675During its normal operation,
6676a string buffer uses a variable number of stack slots.
6677So, while using a buffer, you cannot assume that you know where
6678the top of the stack is.
6679You can use the stack between successive calls to buffer operations
6680as long as that use is balanced;
6681that is,
6682when you call a buffer operation,
6683the stack is at the same level
6684it was immediately after the previous buffer operation.
6685(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6686After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>,
6687the stack is back to its level when the buffer was initialized,
6688plus the final string on its top.
6689
6690
6691
6692
6693
6694<hr><h3><a name="luaL_buffaddr"><code>luaL_buffaddr</code></a></h3><p>
6695<span class="apii">[-0, +0, &ndash;]</span>
6696<pre>char *luaL_buffaddr (luaL_Buffer *B);</pre>
6697
6698<p>
6699Returns the address of the current content of buffer <code>B</code>
6700(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6701Note that any addition to the buffer may invalidate this address.
6702
6703
6704
6705
6706
6707<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6708<span class="apii">[-0, +0, &ndash;]</span>
6709<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6710
6711<p>
6712Initializes a buffer <code>B</code>
6713(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6714This function does not allocate any space;
6715the buffer must be declared as a variable.
6716
6717
6718
6719
6720
6721<hr><h3><a name="luaL_bufflen"><code>luaL_bufflen</code></a></h3><p>
6722<span class="apii">[-0, +0, &ndash;]</span>
6723<pre>size_t luaL_bufflen (luaL_Buffer *B);</pre>
6724
6725<p>
6726Returns the length of the current content of buffer <code>B</code>
6727(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6728
6729
6730
6731
6732
6733<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6734<span class="apii">[-?, +?, <em>m</em>]</span>
6735<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6736
6737<p>
6738Equivalent to the sequence
6739<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6740
6741
6742
6743
6744
6745<hr><h3><a name="luaL_buffsub"><code>luaL_buffsub</code></a></h3><p>
6746<span class="apii">[-0, +0, &ndash;]</span>
6747<pre>void luaL_buffsub (luaL_Buffer *B, int n);</pre>
6748
6749<p>
6750Removes <code>n</code> bytes from the the buffer <code>B</code>
6751(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6752The buffer must have at least that many bytes.
6753
6754
6755
6756
6757
6758<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6759<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6760<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6761
6762<p>
6763Calls a metamethod.
6764
6765
6766<p>
6767If the object at index <code>obj</code> has a metatable and this
6768metatable has a field <code>e</code>,
6769this function calls this field passing the object as its only argument.
6770In this case this function returns true and pushes onto the
6771stack the value returned by the call.
6772If there is no metatable or no metamethod,
6773this function returns false without pushing any value on the stack.
6774
6775
6776
6777
6778
6779<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6780<span class="apii">[-0, +0, <em>v</em>]</span>
6781<pre>void luaL_checkany (lua_State *L, int arg);</pre>
6782
6783<p>
6784Checks whether the function has an argument
6785of any type (including <b>nil</b>) at position <code>arg</code>.
6786
6787
6788
6789
6790
6791<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6792<span class="apii">[-0, +0, <em>v</em>]</span>
6793<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6794
6795<p>
6796Checks whether the function argument <code>arg</code> is an integer
6797(or can be converted to an integer)
6798and returns this integer.
6799
6800
6801
6802
6803
6804<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6805<span class="apii">[-0, +0, <em>v</em>]</span>
6806<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6807
6808<p>
6809Checks whether the function argument <code>arg</code> is a string
6810and returns this string;
6811if <code>l</code> is not <code>NULL</code> fills its referent
6812with the string's length.
6813
6814
6815<p>
6816This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6817so all conversions and caveats of that function apply here.
6818
6819
6820
6821
6822
6823<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6824<span class="apii">[-0, +0, <em>v</em>]</span>
6825<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6826
6827<p>
6828Checks whether the function argument <code>arg</code> is a number
6829and returns this number converted to a <code>lua_Number</code>.
6830
6831
6832
6833
6834
6835<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6836<span class="apii">[-0, +0, <em>v</em>]</span>
6837<pre>int luaL_checkoption (lua_State *L,
6838                      int arg,
6839                      const char *def,
6840                      const char *const lst[]);</pre>
6841
6842<p>
6843Checks whether the function argument <code>arg</code> is a string and
6844searches for this string in the array <code>lst</code>
6845(which must be NULL-terminated).
6846Returns the index in the array where the string was found.
6847Raises an error if the argument is not a string or
6848if the string cannot be found.
6849
6850
6851<p>
6852If <code>def</code> is not <code>NULL</code>,
6853the function uses <code>def</code> as a default value when
6854there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6855
6856
6857<p>
6858This is a useful function for mapping strings to C&nbsp;enums.
6859(The usual convention in Lua libraries is
6860to use strings instead of numbers to select options.)
6861
6862
6863
6864
6865
6866<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6867<span class="apii">[-0, +0, <em>v</em>]</span>
6868<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6869
6870<p>
6871Grows the stack size to <code>top + sz</code> elements,
6872raising an error if the stack cannot grow to that size.
6873<code>msg</code> is an additional text to go into the error message
6874(or <code>NULL</code> for no additional text).
6875
6876
6877
6878
6879
6880<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6881<span class="apii">[-0, +0, <em>v</em>]</span>
6882<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6883
6884<p>
6885Checks whether the function argument <code>arg</code> is a string
6886and returns this string.
6887
6888
6889<p>
6890This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6891so all conversions and caveats of that function apply here.
6892
6893
6894
6895
6896
6897<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6898<span class="apii">[-0, +0, <em>v</em>]</span>
6899<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6900
6901<p>
6902Checks whether the function argument <code>arg</code> has type <code>t</code>.
6903See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6904
6905
6906
6907
6908
6909<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6910<span class="apii">[-0, +0, <em>v</em>]</span>
6911<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6912
6913<p>
6914Checks whether the function argument <code>arg</code> is a userdata
6915of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6916returns the userdata's memory-block address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6917
6918
6919
6920
6921
6922<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6923<span class="apii">[-0, +0, <em>v</em>]</span>
6924<pre>void luaL_checkversion (lua_State *L);</pre>
6925
6926<p>
6927Checks whether the code making the call and the Lua library being called
6928are using the same version of Lua and the same numeric types.
6929
6930
6931
6932
6933
6934<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6935<span class="apii">[-0, +?, <em>m</em>]</span>
6936<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6937
6938<p>
6939Loads and runs the given file.
6940It is defined as the following macro:
6941
6942<pre>
6943     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6944</pre><p>
6945It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6946or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6947
6948
6949
6950
6951
6952<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6953<span class="apii">[-0, +?, &ndash;]</span>
6954<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6955
6956<p>
6957Loads and runs the given string.
6958It is defined as the following macro:
6959
6960<pre>
6961     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6962</pre><p>
6963It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6964or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6965
6966
6967
6968
6969
6970<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6971<span class="apii">[-0, +0, <em>v</em>]</span>
6972<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6973
6974<p>
6975Raises an error.
6976The error message format is given by <code>fmt</code>
6977plus any extra arguments,
6978following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6979It also adds at the beginning of the message the file name and
6980the line number where the error occurred,
6981if this information is available.
6982
6983
6984<p>
6985This function never returns,
6986but it is an idiom to use it in C&nbsp;functions
6987as <code>return luaL_error(<em>args</em>)</code>.
6988
6989
6990
6991
6992
6993<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
6994<span class="apii">[-0, +3, <em>m</em>]</span>
6995<pre>int luaL_execresult (lua_State *L, int stat);</pre>
6996
6997<p>
6998This function produces the return values for
6999process-related functions in the standard library
7000(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
7001
7002
7003
7004
7005
7006<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
7007<span class="apii">[-0, +(1|3), <em>m</em>]</span>
7008<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
7009
7010<p>
7011This function produces the return values for
7012file-related functions in the standard library
7013(<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.).
7014
7015
7016
7017
7018
7019<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
7020<span class="apii">[-0, +(0|1), <em>m</em>]</span>
7021<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
7022
7023<p>
7024Pushes onto the stack the field <code>e</code> from the metatable
7025of the object at index <code>obj</code> and returns the type of the pushed value.
7026If the object does not have a metatable,
7027or if the metatable does not have this field,
7028pushes nothing and returns <code>LUA_TNIL</code>.
7029
7030
7031
7032
7033
7034<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
7035<span class="apii">[-0, +1, <em>m</em>]</span>
7036<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
7037
7038<p>
7039Pushes onto the stack the metatable associated with the name <code>tname</code>
7040in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>),
7041or <b>nil</b> if there is no metatable associated with that name.
7042Returns the type of the pushed value.
7043
7044
7045
7046
7047
7048<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
7049<span class="apii">[-0, +1, <em>e</em>]</span>
7050<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
7051
7052<p>
7053Ensures that the value <code>t[fname]</code>,
7054where <code>t</code> is the value at index <code>idx</code>,
7055is a table,
7056and pushes that table onto the stack.
7057Returns true if it finds a previous table there
7058and false if it creates a new table.
7059
7060
7061
7062
7063
7064<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
7065<span class="apii">[-0, +1, <em>m</em>]</span>
7066<pre>const char *luaL_gsub (lua_State *L,
7067                       const char *s,
7068                       const char *p,
7069                       const char *r);</pre>
7070
7071<p>
7072Creates a copy of string <code>s</code>,
7073replacing any occurrence of the string <code>p</code>
7074with the string <code>r</code>.
7075Pushes the resulting string on the stack and returns it.
7076
7077
7078
7079
7080
7081<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
7082<span class="apii">[-0, +0, <em>e</em>]</span>
7083<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
7084
7085<p>
7086Returns the "length" of the value at the given index
7087as a number;
7088it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
7089Raises an error if the result of the operation is not an integer.
7090(This case can only happen through metamethods.)
7091
7092
7093
7094
7095
7096<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
7097<span class="apii">[-0, +1, &ndash;]</span>
7098<pre>int luaL_loadbuffer (lua_State *L,
7099                     const char *buff,
7100                     size_t sz,
7101                     const char *name);</pre>
7102
7103<p>
7104Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
7105
7106
7107
7108
7109
7110<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
7111<span class="apii">[-0, +1, &ndash;]</span>
7112<pre>int luaL_loadbufferx (lua_State *L,
7113                      const char *buff,
7114                      size_t sz,
7115                      const char *name,
7116                      const char *mode);</pre>
7117
7118<p>
7119Loads a buffer as a Lua chunk.
7120This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
7121buffer pointed to by <code>buff</code> with size <code>sz</code>.
7122
7123
7124<p>
7125This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7126<code>name</code> is the chunk name,
7127used for debug information and error messages.
7128The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7129
7130
7131
7132
7133
7134<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
7135<span class="apii">[-0, +1, <em>m</em>]</span>
7136<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
7137
7138<p>
7139Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
7140
7141
7142
7143
7144
7145<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
7146<span class="apii">[-0, +1, <em>m</em>]</span>
7147<pre>int luaL_loadfilex (lua_State *L, const char *filename,
7148                                            const char *mode);</pre>
7149
7150<p>
7151Loads a file as a Lua chunk.
7152This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
7153named <code>filename</code>.
7154If <code>filename</code> is <code>NULL</code>,
7155then it loads from the standard input.
7156The first line in the file is ignored if it starts with a <code>#</code>.
7157
7158
7159<p>
7160The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7161
7162
7163<p>
7164This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>
7165or <a href="#pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> for file-related errors.
7166
7167
7168<p>
7169As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7170it does not run it.
7171
7172
7173
7174
7175
7176<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
7177<span class="apii">[-0, +1, &ndash;]</span>
7178<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
7179
7180<p>
7181Loads a string as a Lua chunk.
7182This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
7183the zero-terminated string <code>s</code>.
7184
7185
7186<p>
7187This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7188
7189
7190<p>
7191Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7192it does not run it.
7193
7194
7195
7196
7197
7198<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
7199<span class="apii">[-0, +1, <em>m</em>]</span>
7200<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
7201
7202<p>
7203Creates a new table and registers there
7204the functions in the list <code>l</code>.
7205
7206
7207<p>
7208It is implemented as the following macro:
7209
7210<pre>
7211     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
7212</pre><p>
7213The array <code>l</code> must be the actual array,
7214not a pointer to it.
7215
7216
7217
7218
7219
7220<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
7221<span class="apii">[-0, +1, <em>m</em>]</span>
7222<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
7223
7224<p>
7225Creates a new table with a size optimized
7226to store all entries in the array <code>l</code>
7227(but does not actually store them).
7228It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
7229(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
7230
7231
7232<p>
7233It is implemented as a macro.
7234The array <code>l</code> must be the actual array,
7235not a pointer to it.
7236
7237
7238
7239
7240
7241<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
7242<span class="apii">[-0, +1, <em>m</em>]</span>
7243<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
7244
7245<p>
7246If the registry already has the key <code>tname</code>,
7247returns 0.
7248Otherwise,
7249creates a new table to be used as a metatable for userdata,
7250adds to this new table the pair <code>__name = tname</code>,
7251adds to the registry the pair <code>[tname] = new table</code>,
7252and returns 1.
7253
7254
7255<p>
7256In both cases,
7257the function pushes onto the stack the final value associated
7258with <code>tname</code> in the registry.
7259
7260
7261
7262
7263
7264<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
7265<span class="apii">[-0, +0, &ndash;]</span>
7266<pre>lua_State *luaL_newstate (void);</pre>
7267
7268<p>
7269Creates a new Lua state.
7270It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
7271allocator based on the standard&nbsp;C allocation functions
7272and then sets a warning function and a panic function (see <a href="#4.4">&sect;4.4</a>)
7273that print messages to the standard error output.
7274
7275
7276<p>
7277Returns the new state,
7278or <code>NULL</code> if there is a memory allocation error.
7279
7280
7281
7282
7283
7284<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
7285<span class="apii">[-0, +0, <em>e</em>]</span>
7286<pre>void luaL_openlibs (lua_State *L);</pre>
7287
7288<p>
7289Opens all standard Lua libraries into the given state.
7290
7291
7292
7293
7294
7295<hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
7296<span class="apii">[-0, +0, &ndash;]</span>
7297<pre>T luaL_opt (L, func, arg, dflt);</pre>
7298
7299<p>
7300This macro is defined as follows:
7301
7302<pre>
7303     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
7304</pre><p>
7305In words, if the argument <code>arg</code> is nil or absent,
7306the macro results in the default <code>dflt</code>.
7307Otherwise, it results in the result of calling <code>func</code>
7308with the state <code>L</code> and the argument index <code>arg</code> as
7309arguments.
7310Note that it evaluates the expression <code>dflt</code> only if needed.
7311
7312
7313
7314
7315
7316<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
7317<span class="apii">[-0, +0, <em>v</em>]</span>
7318<pre>lua_Integer luaL_optinteger (lua_State *L,
7319                             int arg,
7320                             lua_Integer d);</pre>
7321
7322<p>
7323If the function argument <code>arg</code> is an integer
7324(or it is convertible to an integer),
7325returns this integer.
7326If this argument is absent or is <b>nil</b>,
7327returns <code>d</code>.
7328Otherwise, raises an error.
7329
7330
7331
7332
7333
7334<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
7335<span class="apii">[-0, +0, <em>v</em>]</span>
7336<pre>const char *luaL_optlstring (lua_State *L,
7337                             int arg,
7338                             const char *d,
7339                             size_t *l);</pre>
7340
7341<p>
7342If the function argument <code>arg</code> is a string,
7343returns this string.
7344If this argument is absent or is <b>nil</b>,
7345returns <code>d</code>.
7346Otherwise, raises an error.
7347
7348
7349<p>
7350If <code>l</code> is not <code>NULL</code>,
7351fills its referent with the result's length.
7352If the result is <code>NULL</code>
7353(only possible when returning <code>d</code> and <code>d == NULL</code>),
7354its length is considered zero.
7355
7356
7357<p>
7358This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
7359so all conversions and caveats of that function apply here.
7360
7361
7362
7363
7364
7365<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
7366<span class="apii">[-0, +0, <em>v</em>]</span>
7367<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
7368
7369<p>
7370If the function argument <code>arg</code> is a number,
7371returns this number as a <code>lua_Number</code>.
7372If this argument is absent or is <b>nil</b>,
7373returns <code>d</code>.
7374Otherwise, raises an error.
7375
7376
7377
7378
7379
7380<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
7381<span class="apii">[-0, +0, <em>v</em>]</span>
7382<pre>const char *luaL_optstring (lua_State *L,
7383                            int arg,
7384                            const char *d);</pre>
7385
7386<p>
7387If the function argument <code>arg</code> is a string,
7388returns this string.
7389If this argument is absent or is <b>nil</b>,
7390returns <code>d</code>.
7391Otherwise, raises an error.
7392
7393
7394
7395
7396
7397<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
7398<span class="apii">[-?, +?, <em>m</em>]</span>
7399<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
7400
7401<p>
7402Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
7403with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
7404
7405
7406
7407
7408
7409<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
7410<span class="apii">[-?, +?, <em>m</em>]</span>
7411<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
7412
7413<p>
7414Returns an address to a space of size <code>sz</code>
7415where you can copy a string to be added to buffer <code>B</code>
7416(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
7417After copying the string into this space you must call
7418<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
7419it to the buffer.
7420
7421
7422
7423
7424
7425<hr><h3><a name="luaL_pushfail"><code>luaL_pushfail</code></a></h3><p>
7426<span class="apii">[-0, +1, &ndash;]</span>
7427<pre>void luaL_pushfail (lua_State *L);</pre>
7428
7429<p>
7430Pushes the <b>fail</b> value onto the stack (see <a href="#6">&sect;6</a>).
7431
7432
7433
7434
7435
7436<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
7437<span class="apii">[-?, +1, <em>m</em>]</span>
7438<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
7439
7440<p>
7441Finishes the use of buffer <code>B</code> leaving the final string on
7442the top of the stack.
7443
7444
7445
7446
7447
7448<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
7449<span class="apii">[-?, +1, <em>m</em>]</span>
7450<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
7451
7452<p>
7453Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
7454
7455
7456
7457
7458
7459<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
7460<span class="apii">[-1, +0, <em>m</em>]</span>
7461<pre>int luaL_ref (lua_State *L, int t);</pre>
7462
7463<p>
7464Creates and returns a <em>reference</em>,
7465in the table at index <code>t</code>,
7466for the object on the top of the stack (and pops the object).
7467
7468
7469<p>
7470A reference is a unique integer key.
7471As long as you do not manually add integer keys into the table <code>t</code>,
7472<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
7473You can retrieve an object referred by the reference <code>r</code>
7474by calling <code>lua_rawgeti(L, t, r)</code>.
7475The function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference.
7476
7477
7478<p>
7479If the object on the top of the stack is <b>nil</b>,
7480<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
7481The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
7482from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
7483
7484
7485
7486
7487
7488<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
7489<pre>typedef struct luaL_Reg {
7490  const char *name;
7491  lua_CFunction func;
7492} luaL_Reg;</pre>
7493
7494<p>
7495Type for arrays of functions to be registered by
7496<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
7497<code>name</code> is the function name and <code>func</code> is a pointer to
7498the function.
7499Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
7500in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
7501
7502
7503
7504
7505
7506<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
7507<span class="apii">[-0, +1, <em>e</em>]</span>
7508<pre>void luaL_requiref (lua_State *L, const char *modname,
7509                    lua_CFunction openf, int glb);</pre>
7510
7511<p>
7512If <code>package.loaded[modname]</code> is not true,
7513calls the function <code>openf</code> with the string <code>modname</code> as an argument
7514and sets the call result to <code>package.loaded[modname]</code>,
7515as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
7516
7517
7518<p>
7519If <code>glb</code> is true,
7520also stores the module into the global <code>modname</code>.
7521
7522
7523<p>
7524Leaves a copy of the module on the stack.
7525
7526
7527
7528
7529
7530<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
7531<span class="apii">[-nup, +0, <em>m</em>]</span>
7532<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
7533
7534<p>
7535Registers all functions in the array <code>l</code>
7536(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
7537(below optional upvalues, see next).
7538
7539
7540<p>
7541When <code>nup</code> is not zero,
7542all functions are created with <code>nup</code> upvalues,
7543initialized with copies of the <code>nup</code> values
7544previously pushed on the stack
7545on top of the library table.
7546These values are popped from the stack after the registration.
7547
7548
7549
7550
7551
7552<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
7553<span class="apii">[-0, +0, &ndash;]</span>
7554<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
7555
7556<p>
7557Sets the metatable of the object on the top of the stack
7558as the metatable associated with name <code>tname</code>
7559in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7560
7561
7562
7563
7564
7565<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
7566<pre>typedef struct luaL_Stream {
7567  FILE *f;
7568  lua_CFunction closef;
7569} luaL_Stream;</pre>
7570
7571<p>
7572The standard representation for file handles
7573used by the standard I/O library.
7574
7575
7576<p>
7577A file handle is implemented as a full userdata,
7578with a metatable called <code>LUA_FILEHANDLE</code>
7579(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
7580The metatable is created by the I/O library
7581(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7582
7583
7584<p>
7585This userdata must start with the structure <code>luaL_Stream</code>;
7586it can contain other data after this initial structure.
7587The field <code>f</code> points to the corresponding C stream
7588(or it can be <code>NULL</code> to indicate an incompletely created handle).
7589The field <code>closef</code> points to a Lua function
7590that will be called to close the stream
7591when the handle is closed or collected;
7592this function receives the file handle as its sole argument and
7593must return either a true value, in case of success,
7594or a false value plus an error message, in case of error.
7595Once Lua calls this field,
7596it changes the field value to <code>NULL</code>
7597to signal that the handle is closed.
7598
7599
7600
7601
7602
7603<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
7604<span class="apii">[-0, +0, <em>m</em>]</span>
7605<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
7606
7607<p>
7608This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
7609except that, when the test fails,
7610it returns <code>NULL</code> instead of raising an error.
7611
7612
7613
7614
7615
7616<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
7617<span class="apii">[-0, +1, <em>e</em>]</span>
7618<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
7619
7620<p>
7621Converts any Lua value at the given index to a C&nbsp;string
7622in a reasonable format.
7623The resulting string is pushed onto the stack and also
7624returned by the function (see <a href="#4.1.3">&sect;4.1.3</a>).
7625If <code>len</code> is not <code>NULL</code>,
7626the function also sets <code>*len</code> with the string length.
7627
7628
7629<p>
7630If the value has a metatable with a <code>__tostring</code> field,
7631then <code>luaL_tolstring</code> calls the corresponding metamethod
7632with the value as argument,
7633and uses the result of the call as its result.
7634
7635
7636
7637
7638
7639<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
7640<span class="apii">[-0, +1, <em>m</em>]</span>
7641<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
7642                     int level);</pre>
7643
7644<p>
7645Creates and pushes a traceback of the stack <code>L1</code>.
7646If <code>msg</code> is not <code>NULL</code>, it is appended
7647at the beginning of the traceback.
7648The <code>level</code> parameter tells at which level
7649to start the traceback.
7650
7651
7652
7653
7654
7655<hr><h3><a name="luaL_typeerror"><code>luaL_typeerror</code></a></h3><p>
7656<span class="apii">[-0, +0, <em>v</em>]</span>
7657<pre>const char *luaL_typeerror (lua_State *L,
7658                                      int arg,
7659                                      const char *tname);</pre>
7660
7661<p>
7662Raises a type error for the argument <code>arg</code>
7663of the C&nbsp;function that called it,
7664using a standard message;
7665<code>tname</code> is a "name" for the expected type.
7666This function never returns.
7667
7668
7669
7670
7671
7672<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
7673<span class="apii">[-0, +0, &ndash;]</span>
7674<pre>const char *luaL_typename (lua_State *L, int index);</pre>
7675
7676<p>
7677Returns the name of the type of the value at the given index.
7678
7679
7680
7681
7682
7683<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
7684<span class="apii">[-0, +0, &ndash;]</span>
7685<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
7686
7687<p>
7688Releases the reference <code>ref</code> from the table at index <code>t</code>
7689(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
7690The entry is removed from the table,
7691so that the referred object can be collected.
7692The reference <code>ref</code> is also freed to be used again.
7693
7694
7695<p>
7696If <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>,
7697<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
7698
7699
7700
7701
7702
7703<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
7704<span class="apii">[-0, +1, <em>m</em>]</span>
7705<pre>void luaL_where (lua_State *L, int lvl);</pre>
7706
7707<p>
7708Pushes onto the stack a string identifying the current position
7709of the control at level <code>lvl</code> in the call stack.
7710Typically this string has the following format:
7711
7712<pre>
7713     <em>chunkname</em>:<em>currentline</em>:
7714</pre><p>
7715Level&nbsp;0 is the running function,
7716level&nbsp;1 is the function that called the running function,
7717etc.
7718
7719
7720<p>
7721This function is used to build a prefix for error messages.
7722
7723
7724
7725
7726
7727
7728
7729<h1>6 &ndash; <a name="6">The Standard Libraries</a></h1>
7730
7731
7732
7733<p>
7734The standard Lua libraries provide useful functions
7735that are implemented in&nbsp;C through the C&nbsp;API.
7736Some of these functions provide essential services to the language
7737(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7738others provide access to outside services (e.g., I/O);
7739and others could be implemented in Lua itself,
7740but that for different reasons
7741deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7742
7743
7744<p>
7745All libraries are implemented through the official C&nbsp;API
7746and are provided as separate C&nbsp;modules.
7747Unless otherwise noted,
7748these library functions do not adjust its number of arguments
7749to its expected parameters.
7750For instance, a function documented as <code>foo(arg)</code>
7751should not be called without an argument.
7752
7753
7754<p>
7755The notation <b>fail</b> means a false value representing
7756some kind of failure.
7757(Currently, <b>fail</b> is equal to <b>nil</b>,
7758but that may change in future versions.
7759The recommendation is to always test the success of these functions
7760with <code>(not status)</code>, instead of <code>(status == nil)</code>.)
7761
7762
7763<p>
7764Currently, Lua has the following standard libraries:
7765
7766<ul>
7767
7768<li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7769
7770<li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7771
7772<li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7773
7774<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7775
7776<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7777
7778<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7779
7780<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7781
7782<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7783
7784<li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7785
7786<li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7787
7788</ul><p>
7789Except for the basic and the package libraries,
7790each library provides all its functions as fields of a global table
7791or as methods of its objects.
7792
7793
7794<p>
7795To have access to these libraries,
7796the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7797which opens all standard libraries.
7798Alternatively,
7799the host program can open them individually by using
7800<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7801<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7802<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7803<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7804<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7805<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF-8 library),
7806<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7807<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7808<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7809<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7810and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7811These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7812
7813
7814
7815
7816
7817<h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7818
7819<p>
7820The basic library provides core functions to Lua.
7821If you do not include this library in your application,
7822you should check carefully whether you need to provide
7823implementations for some of its facilities.
7824
7825
7826<p>
7827<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7828
7829
7830<p>
7831Raises an error if
7832the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7833otherwise, returns all its arguments.
7834In case of error,
7835<code>message</code> is the error object;
7836when absent, it defaults to "<code>assertion failed!</code>"
7837
7838
7839
7840
7841<p>
7842<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7843
7844
7845<p>
7846This function is a generic interface to the garbage collector.
7847It performs different functions according to its first argument, <code>opt</code>:
7848
7849<ul>
7850
7851<li><b>"<code>collect</code>": </b>
7852Performs a full garbage-collection cycle.
7853This is the default option.
7854</li>
7855
7856<li><b>"<code>stop</code>": </b>
7857Stops automatic execution of the garbage collector.
7858The collector will run only when explicitly invoked,
7859until a call to restart it.
7860</li>
7861
7862<li><b>"<code>restart</code>": </b>
7863Restarts automatic execution of the garbage collector.
7864</li>
7865
7866<li><b>"<code>count</code>": </b>
7867Returns the total memory in use by Lua in Kbytes.
7868The value has a fractional part,
7869so that it multiplied by 1024
7870gives the exact number of bytes in use by Lua.
7871</li>
7872
7873<li><b>"<code>step</code>": </b>
7874Performs a garbage-collection step.
7875The step "size" is controlled by <code>arg</code>.
7876With a zero value,
7877the collector will perform one basic (indivisible) step.
7878For non-zero values,
7879the collector will perform as if that amount of memory
7880(in Kbytes) had been allocated by Lua.
7881Returns <b>true</b> if the step finished a collection cycle.
7882</li>
7883
7884<li><b>"<code>isrunning</code>": </b>
7885Returns a boolean that tells whether the collector is running
7886(i.e., not stopped).
7887</li>
7888
7889<li><b>"<code>incremental</code>": </b>
7890Change the collector mode to incremental.
7891This option can be followed by three numbers:
7892the garbage-collector pause,
7893the step multiplier,
7894and the step size (see <a href="#2.5.1">&sect;2.5.1</a>).
7895A zero means to not change that value.
7896</li>
7897
7898<li><b>"<code>generational</code>": </b>
7899Change the collector mode to generational.
7900This option can be followed by two numbers:
7901the garbage-collector minor multiplier
7902and the major multiplier (see <a href="#2.5.2">&sect;2.5.2</a>).
7903A zero means to not change that value.
7904</li>
7905
7906</ul><p>
7907See <a href="#2.5">&sect;2.5</a> for more details about garbage collection
7908and some of these options.
7909
7910
7911
7912
7913<p>
7914<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7915Opens the named file and executes its content as a Lua chunk.
7916When called without arguments,
7917<code>dofile</code> executes the content of the standard input (<code>stdin</code>).
7918Returns all values returned by the chunk.
7919In case of errors, <code>dofile</code> propagates the error
7920to its caller.
7921(That is, <code>dofile</code> does not run in protected mode.)
7922
7923
7924
7925
7926<p>
7927<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7928Raises an error (see <a href="#2.3">&sect;2.3</a>) with @{message} as the error object.
7929This function never returns.
7930
7931
7932<p>
7933Usually, <code>error</code> adds some information about the error position
7934at the beginning of the message, if the message is a string.
7935The <code>level</code> argument specifies how to get the error position.
7936With level&nbsp;1 (the default), the error position is where the
7937<code>error</code> function was called.
7938Level&nbsp;2 points the error to where the function
7939that called <code>error</code> was called; and so on.
7940Passing a level&nbsp;0 avoids the addition of error position information
7941to the message.
7942
7943
7944
7945
7946<p>
7947<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7948A global variable (not a function) that
7949holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7950Lua itself does not use this variable;
7951changing its value does not affect any environment,
7952nor vice versa.
7953
7954
7955
7956
7957<p>
7958<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7959
7960
7961<p>
7962If <code>object</code> does not have a metatable, returns <b>nil</b>.
7963Otherwise,
7964if the object's metatable has a <code>__metatable</code> field,
7965returns the associated value.
7966Otherwise, returns the metatable of the given object.
7967
7968
7969
7970
7971<p>
7972<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7973
7974
7975<p>
7976Returns three values (an iterator function, the table <code>t</code>, and 0)
7977so that the construction
7978
7979<pre>
7980     for i,v in ipairs(t) do <em>body</em> end
7981</pre><p>
7982will iterate over the key&ndash;value pairs
7983(<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7984up to the first absent index.
7985
7986
7987
7988
7989<p>
7990<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
7991
7992
7993<p>
7994Loads a chunk.
7995
7996
7997<p>
7998If <code>chunk</code> is a string, the chunk is this string.
7999If <code>chunk</code> is a function,
8000<code>load</code> calls it repeatedly to get the chunk pieces.
8001Each call to <code>chunk</code> must return a string that concatenates
8002with previous results.
8003A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
8004
8005
8006<p>
8007If there are no syntactic errors,
8008<code>load</code> returns the compiled chunk as a function;
8009otherwise, it returns <b>fail</b> plus the error message.
8010
8011
8012<p>
8013When you load a main chunk,
8014the resulting function will always have exactly one upvalue,
8015the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
8016However,
8017when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
8018the resulting function can have an arbitrary number of upvalues,
8019and there is no guarantee that its first upvalue will be
8020the <code>_ENV</code> variable.
8021(A non-main function may not even have an <code>_ENV</code> upvalue.)
8022
8023
8024<p>
8025Regardless, if the resulting function has any upvalues,
8026its first upvalue is set to the value of <code>env</code>,
8027if that parameter is given,
8028or to the value of the global environment.
8029Other upvalues are initialized with <b>nil</b>.
8030All upvalues are fresh, that is,
8031they are not shared with any other function.
8032
8033
8034<p>
8035<code>chunkname</code> is used as the name of the chunk for error messages
8036and debug information (see <a href="#4.7">&sect;4.7</a>).
8037When absent,
8038it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
8039or to "<code>=(load)</code>" otherwise.
8040
8041
8042<p>
8043The string <code>mode</code> controls whether the chunk can be text or binary
8044(that is, a precompiled chunk).
8045It may be the string "<code>b</code>" (only binary chunks),
8046"<code>t</code>" (only text chunks),
8047or "<code>bt</code>" (both binary and text).
8048The default is "<code>bt</code>".
8049
8050
8051<p>
8052It is safe to load malformed binary chunks;
8053<code>load</code> signals an appropriate error.
8054However,
8055Lua does not check the consistency of the code inside binary chunks;
8056running maliciously crafted bytecode can crash the interpreter.
8057
8058
8059
8060
8061<p>
8062<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
8063
8064
8065<p>
8066Similar to <a href="#pdf-load"><code>load</code></a>,
8067but gets the chunk from file <code>filename</code>
8068or from the standard input,
8069if no file name is given.
8070
8071
8072
8073
8074<p>
8075<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
8076
8077
8078<p>
8079Allows a program to traverse all fields of a table.
8080Its first argument is a table and its second argument
8081is an index in this table.
8082A call to <code>next</code> returns the next index of the table
8083and its associated value.
8084When called with <b>nil</b> as its second argument,
8085<code>next</code> returns an initial index
8086and its associated value.
8087When called with the last index,
8088or with <b>nil</b> in an empty table,
8089<code>next</code> returns <b>nil</b>.
8090If the second argument is absent, then it is interpreted as <b>nil</b>.
8091In particular,
8092you can use <code>next(t)</code> to check whether a table is empty.
8093
8094
8095<p>
8096The order in which the indices are enumerated is not specified,
8097<em>even for numeric indices</em>.
8098(To traverse a table in numerical order,
8099use a numerical <b>for</b>.)
8100
8101
8102<p>
8103The behavior of <code>next</code> is undefined if,
8104during the traversal,
8105you assign any value to a non-existent field in the table.
8106You may however modify existing fields.
8107In particular, you may set existing fields to nil.
8108
8109
8110
8111
8112<p>
8113<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
8114
8115
8116<p>
8117If <code>t</code> has a metamethod <code>__pairs</code>,
8118calls it with <code>t</code> as argument and returns the first three
8119results from the call.
8120
8121
8122<p>
8123Otherwise,
8124returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
8125so that the construction
8126
8127<pre>
8128     for k,v in pairs(t) do <em>body</em> end
8129</pre><p>
8130will iterate over all key&ndash;value pairs of table <code>t</code>.
8131
8132
8133<p>
8134See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
8135the table during its traversal.
8136
8137
8138
8139
8140<p>
8141<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
8142
8143
8144<p>
8145Calls the function <code>f</code> with
8146the given arguments in <em>protected mode</em>.
8147This means that any error inside&nbsp;<code>f</code> is not propagated;
8148instead, <code>pcall</code> catches the error
8149and returns a status code.
8150Its first result is the status code (a boolean),
8151which is true if the call succeeds without errors.
8152In such case, <code>pcall</code> also returns all results from the call,
8153after this first result.
8154In case of any error, <code>pcall</code> returns <b>false</b> plus the error object.
8155Note that errors caught by <code>pcall</code> do not call a message handler.
8156
8157
8158
8159
8160<p>
8161<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
8162Receives any number of arguments
8163and prints their values to <code>stdout</code>,
8164converting each argument to a string
8165following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8166
8167
8168<p>
8169The function <code>print</code> is not intended for formatted output,
8170but only as a quick way to show a value,
8171for instance for debugging.
8172For complete control over the output,
8173use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
8174
8175
8176
8177
8178<p>
8179<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
8180Checks whether <code>v1</code> is equal to <code>v2</code>,
8181without invoking the <code>__eq</code> metamethod.
8182Returns a boolean.
8183
8184
8185
8186
8187<p>
8188<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
8189Gets the real value of <code>table[index]</code>,
8190without using the <code>__index</code> metavalue.
8191<code>table</code> must be a table;
8192<code>index</code> may be any value.
8193
8194
8195
8196
8197<p>
8198<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
8199Returns the length of the object <code>v</code>,
8200which must be a table or a string,
8201without invoking the <code>__len</code> metamethod.
8202Returns an integer.
8203
8204
8205
8206
8207<p>
8208<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
8209Sets the real value of <code>table[index]</code> to <code>value</code>,
8210without using the <code>__newindex</code> metavalue.
8211<code>table</code> must be a table,
8212<code>index</code> any value different from <b>nil</b> and NaN,
8213and <code>value</code> any Lua value.
8214
8215
8216<p>
8217This function returns <code>table</code>.
8218
8219
8220
8221
8222<p>
8223<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
8224
8225
8226<p>
8227If <code>index</code> is a number,
8228returns all arguments after argument number <code>index</code>;
8229a negative number indexes from the end (-1 is the last argument).
8230Otherwise, <code>index</code> must be the string <code>"#"</code>,
8231and <code>select</code> returns the total number of extra arguments it received.
8232
8233
8234
8235
8236<p>
8237<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
8238
8239
8240<p>
8241Sets the metatable for the given table.
8242If <code>metatable</code> is <b>nil</b>,
8243removes the metatable of the given table.
8244If the original metatable has a <code>__metatable</code> field,
8245raises an error.
8246
8247
8248<p>
8249This function returns <code>table</code>.
8250
8251
8252<p>
8253To change the metatable of other types from Lua code,
8254you must use the debug library (<a href="#6.10">&sect;6.10</a>).
8255
8256
8257
8258
8259<p>
8260<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
8261
8262
8263<p>
8264When called with no <code>base</code>,
8265<code>tonumber</code> tries to convert its argument to a number.
8266If the argument is already a number or
8267a string convertible to a number,
8268then <code>tonumber</code> returns this number;
8269otherwise, it returns <b>fail</b>.
8270
8271
8272<p>
8273The conversion of strings can result in integers or floats,
8274according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
8275The string may have leading and trailing spaces and a sign.
8276
8277
8278<p>
8279When called with <code>base</code>,
8280then <code>e</code> must be a string to be interpreted as
8281an integer numeral in that base.
8282The base may be any integer between 2 and 36, inclusive.
8283In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
8284represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
8285with '<code>Z</code>' representing 35.
8286If the string <code>e</code> is not a valid numeral in the given base,
8287the function returns <b>fail</b>.
8288
8289
8290
8291
8292<p>
8293<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
8294
8295
8296<p>
8297Receives a value of any type and
8298converts it to a string in a human-readable format.
8299
8300
8301<p>
8302If the metatable of <code>v</code> has a <code>__tostring</code> field,
8303then <code>tostring</code> calls the corresponding value
8304with <code>v</code> as argument,
8305and uses the result of the call as its result.
8306Otherwise, if the metatable of <code>v</code> has a <code>__name</code> field
8307with a string value,
8308<code>tostring</code> may use that string in its final result.
8309
8310
8311<p>
8312For complete control of how numbers are converted,
8313use <a href="#pdf-string.format"><code>string.format</code></a>.
8314
8315
8316
8317
8318<p>
8319<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
8320
8321
8322<p>
8323Returns the type of its only argument, coded as a string.
8324The possible results of this function are
8325"<code>nil</code>" (a string, not the value <b>nil</b>),
8326"<code>number</code>",
8327"<code>string</code>",
8328"<code>boolean</code>",
8329"<code>table</code>",
8330"<code>function</code>",
8331"<code>thread</code>",
8332and "<code>userdata</code>".
8333
8334
8335
8336
8337<p>
8338<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
8339
8340
8341<p>
8342A global variable (not a function) that
8343holds a string containing the running Lua version.
8344The current value of this variable is "<code>Lua 5.4</code>".
8345
8346
8347
8348
8349<p>
8350<hr><h3><a name="pdf-warn"><code>warn (msg1, &middot;&middot;&middot;)</code></a></h3>
8351
8352
8353<p>
8354Emits a warning with a message composed by the concatenation
8355of all its arguments (which should be strings).
8356
8357
8358<p>
8359By convention,
8360a one-piece message starting with '<code>@</code>'
8361is intended to be a <em>control message</em>,
8362which is a message to the warning system itself.
8363In particular, the standard warning function in Lua
8364recognizes the control messages "<code>@off</code>",
8365to stop the emission of warnings,
8366and "<code>@on</code>", to (re)start the emission;
8367it ignores unknown control messages.
8368
8369
8370
8371
8372<p>
8373<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
8374
8375
8376<p>
8377This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
8378except that it sets a new message handler <code>msgh</code>.
8379
8380
8381
8382
8383
8384
8385
8386<h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
8387
8388<p>
8389This library comprises the operations to manipulate coroutines,
8390which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
8391See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
8392
8393
8394<p>
8395<hr><h3><a name="pdf-coroutine.close"><code>coroutine.close (co)</code></a></h3>
8396
8397
8398<p>
8399Closes coroutine <code>co</code>,
8400that is,
8401closes all its pending to-be-closed variables
8402and puts the coroutine in a dead state.
8403The given coroutine must be dead or suspended.
8404In case of error closing some variable,
8405returns <b>false</b> plus the error object;
8406otherwise returns <b>true</b>.
8407
8408
8409
8410
8411<p>
8412<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
8413
8414
8415<p>
8416Creates a new coroutine, with body <code>f</code>.
8417<code>f</code> must be a function.
8418Returns this new coroutine,
8419an object with type <code>"thread"</code>.
8420
8421
8422
8423
8424<p>
8425<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ([co])</code></a></h3>
8426
8427
8428<p>
8429Returns true when the coroutine <code>co</code> can yield.
8430The default for <code>co</code> is the running coroutine.
8431
8432
8433<p>
8434A coroutine is yieldable if it is not the main thread and
8435it is not inside a non-yieldable C&nbsp;function.
8436
8437
8438
8439
8440<p>
8441<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
8442
8443
8444<p>
8445Starts or continues the execution of coroutine <code>co</code>.
8446The first time you resume a coroutine,
8447it starts running its body.
8448The values <code>val1</code>, ... are passed
8449as the arguments to the body function.
8450If the coroutine has yielded,
8451<code>resume</code> restarts it;
8452the values <code>val1</code>, ... are passed
8453as the results from the yield.
8454
8455
8456<p>
8457If the coroutine runs without any errors,
8458<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
8459(when the coroutine yields) or any values returned by the body function
8460(when the coroutine terminates).
8461If there is any error,
8462<code>resume</code> returns <b>false</b> plus the error message.
8463
8464
8465
8466
8467<p>
8468<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
8469
8470
8471<p>
8472Returns the running coroutine plus a boolean,
8473true when the running coroutine is the main one.
8474
8475
8476
8477
8478<p>
8479<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
8480
8481
8482<p>
8483Returns the status of the coroutine <code>co</code>, as a string:
8484<code>"running"</code>,
8485if the coroutine is running
8486(that is, it is the one that called <code>status</code>);
8487<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
8488or if it has not started running yet;
8489<code>"normal"</code> if the coroutine is active but not running
8490(that is, it has resumed another coroutine);
8491and <code>"dead"</code> if the coroutine has finished its body function,
8492or if it has stopped with an error.
8493
8494
8495
8496
8497<p>
8498<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
8499
8500
8501<p>
8502Creates a new coroutine, with body <code>f</code>;
8503<code>f</code> must be a function.
8504Returns a function that resumes the coroutine each time it is called.
8505Any arguments passed to this function behave as the
8506extra arguments to <code>resume</code>.
8507The function returns the same values returned by <code>resume</code>,
8508except the first boolean.
8509In case of error,
8510the function closes the coroutine and propagates the error.
8511
8512
8513
8514
8515<p>
8516<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
8517
8518
8519<p>
8520Suspends the execution of the calling coroutine.
8521Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
8522
8523
8524
8525
8526
8527
8528
8529<h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
8530
8531<p>
8532The package library provides basic
8533facilities for loading modules in Lua.
8534It exports one function directly in the global environment:
8535<a href="#pdf-require"><code>require</code></a>.
8536Everything else is exported in the table <a name="pdf-package"><code>package</code></a>.
8537
8538
8539<p>
8540<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
8541
8542
8543<p>
8544Loads the given module.
8545The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
8546to determine whether <code>modname</code> is already loaded.
8547If it is, then <code>require</code> returns the value stored
8548at <code>package.loaded[modname]</code>.
8549(The absence of a second result in this case
8550signals that this call did not have to load the module.)
8551Otherwise, it tries to find a <em>loader</em> for the module.
8552
8553
8554<p>
8555To find a loader,
8556<code>require</code> is guided by the table <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8557Each item in this table is a search function,
8558that searches for the module in a particular way.
8559By changing this table,
8560we can change how <code>require</code> looks for a module.
8561The following explanation is based on the default configuration
8562for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8563
8564
8565<p>
8566First <code>require</code> queries <code>package.preload[modname]</code>.
8567If it has a value,
8568this value (which must be a function) is the loader.
8569Otherwise <code>require</code> searches for a Lua loader using the
8570path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
8571If that also fails, it searches for a C&nbsp;loader using the
8572path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8573If that also fails,
8574it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
8575
8576
8577<p>
8578Once a loader is found,
8579<code>require</code> calls the loader with two arguments:
8580<code>modname</code> and an extra value,
8581a <em>loader data</em>,
8582also returned by the searcher.
8583The loader data can be any value useful to the module;
8584for the default searchers,
8585it indicates where the loader was found.
8586(For instance, if the loader came from a file,
8587this extra value is the file path.)
8588If the loader returns any non-nil value,
8589<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
8590If the loader does not return a non-nil value and
8591has not assigned any value to <code>package.loaded[modname]</code>,
8592then <code>require</code> assigns <b>true</b> to this entry.
8593In any case, <code>require</code> returns the
8594final value of <code>package.loaded[modname]</code>.
8595Besides that value, <code>require</code> also returns as a second result
8596the loader data returned by the searcher,
8597which indicates how <code>require</code> found the module.
8598
8599
8600<p>
8601If there is any error loading or running the module,
8602or if it cannot find any loader for the module,
8603then <code>require</code> raises an error.
8604
8605
8606
8607
8608<p>
8609<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
8610
8611
8612<p>
8613A string describing some compile-time configurations for packages.
8614This string is a sequence of lines:
8615
8616<ul>
8617
8618<li>The first line is the directory separator string.
8619Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
8620
8621<li>The second line is the character that separates templates in a path.
8622Default is '<code>;</code>'.</li>
8623
8624<li>The third line is the string that marks the
8625substitution points in a template.
8626Default is '<code>?</code>'.</li>
8627
8628<li>The fourth line is a string that, in a path in Windows,
8629is replaced by the executable's directory.
8630Default is '<code>!</code>'.</li>
8631
8632<li>The fifth line is a mark to ignore all text after it
8633when building the <code>luaopen_</code> function name.
8634Default is '<code>-</code>'.</li>
8635
8636</ul>
8637
8638
8639
8640<p>
8641<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
8642
8643
8644<p>
8645A string with the path used by <a href="#pdf-require"><code>require</code></a>
8646to search for a C&nbsp;loader.
8647
8648
8649<p>
8650Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
8651it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
8652using the environment variable <a name="pdf-LUA_CPATH_5_4"><code>LUA_CPATH_5_4</code></a>,
8653or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
8654or a default path defined in <code>luaconf.h</code>.
8655
8656
8657
8658
8659<p>
8660<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
8661
8662
8663<p>
8664A table used by <a href="#pdf-require"><code>require</code></a> to control which
8665modules are already loaded.
8666When you require a module <code>modname</code> and
8667<code>package.loaded[modname]</code> is not false,
8668<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
8669
8670
8671<p>
8672This variable is only a reference to the real table;
8673assignments to this variable do not change the
8674table used by <a href="#pdf-require"><code>require</code></a>.
8675
8676
8677
8678
8679<p>
8680<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
8681
8682
8683<p>
8684Dynamically links the host program with the C&nbsp;library <code>libname</code>.
8685
8686
8687<p>
8688If <code>funcname</code> is "<code>*</code>",
8689then it only links with the library,
8690making the symbols exported by the library
8691available to other dynamically linked libraries.
8692Otherwise,
8693it looks for a function <code>funcname</code> inside the library
8694and returns this function as a C&nbsp;function.
8695So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
8696(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8697
8698
8699<p>
8700This is a low-level function.
8701It completely bypasses the package and module system.
8702Unlike <a href="#pdf-require"><code>require</code></a>,
8703it does not perform any path searching and
8704does not automatically adds extensions.
8705<code>libname</code> must be the complete file name of the C&nbsp;library,
8706including if necessary a path and an extension.
8707<code>funcname</code> must be the exact name exported by the C&nbsp;library
8708(which may depend on the C&nbsp;compiler and linker used).
8709
8710
8711<p>
8712This function is not supported by Standard&nbsp;C.
8713As such, it is only available on some platforms
8714(Windows, Linux, Mac OS X, Solaris, BSD,
8715plus other Unix systems that support the <code>dlfcn</code> standard).
8716
8717
8718<p>
8719This function is inherently insecure,
8720as it allows Lua to call any function in any readable dynamic
8721library in the system.
8722(Lua calls any function assuming the function
8723has a proper prototype and respects a proper protocol
8724(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8725Therefore,
8726calling an arbitrary function in an arbitrary dynamic library
8727more often than not results in an access violation.)
8728
8729
8730
8731
8732<p>
8733<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
8734
8735
8736<p>
8737A string with the path used by <a href="#pdf-require"><code>require</code></a>
8738to search for a Lua loader.
8739
8740
8741<p>
8742At start-up, Lua initializes this variable with
8743the value of the environment variable <a name="pdf-LUA_PATH_5_4"><code>LUA_PATH_5_4</code></a> or
8744the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
8745with a default path defined in <code>luaconf.h</code>,
8746if those environment variables are not defined.
8747A "<code>;;</code>" in the value of the environment variable
8748is replaced by the default path.
8749
8750
8751
8752
8753<p>
8754<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
8755
8756
8757<p>
8758A table to store loaders for specific modules
8759(see <a href="#pdf-require"><code>require</code></a>).
8760
8761
8762<p>
8763This variable is only a reference to the real table;
8764assignments to this variable do not change the
8765table used by <a href="#pdf-require"><code>require</code></a>.
8766
8767
8768
8769
8770<p>
8771<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
8772
8773
8774<p>
8775A table used by <a href="#pdf-require"><code>require</code></a> to control how to find modules.
8776
8777
8778<p>
8779Each entry in this table is a <em>searcher function</em>.
8780When looking for a module,
8781<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
8782with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
8783sole argument.
8784If the searcher finds the module,
8785it returns another function, the module <em>loader</em>,
8786plus an extra value, a <em>loader data</em>,
8787that will be passed to that loader and
8788returned as a second result by <a href="#pdf-require"><code>require</code></a>.
8789If it cannot find the module,
8790it returns a string explaining why
8791(or <b>nil</b> if it has nothing to say).
8792
8793
8794<p>
8795Lua initializes this table with four searcher functions.
8796
8797
8798<p>
8799The first searcher simply looks for a loader in the
8800<a href="#pdf-package.preload"><code>package.preload</code></a> table.
8801
8802
8803<p>
8804The second searcher looks for a loader as a Lua library,
8805using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
8806The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8807
8808
8809<p>
8810The third searcher looks for a loader as a C&nbsp;library,
8811using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8812Again,
8813the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8814For instance,
8815if the C&nbsp;path is the string
8816
8817<pre>
8818     "./?.so;./?.dll;/usr/local/?/init.so"
8819</pre><p>
8820the searcher for module <code>foo</code>
8821will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
8822and <code>/usr/local/foo/init.so</code>, in that order.
8823Once it finds a C&nbsp;library,
8824this searcher first uses a dynamic link facility to link the
8825application with the library.
8826Then it tries to find a C&nbsp;function inside the library to
8827be used as the loader.
8828The name of this C&nbsp;function is the string "<code>luaopen_</code>"
8829concatenated with a copy of the module name where each dot
8830is replaced by an underscore.
8831Moreover, if the module name has a hyphen,
8832its suffix after (and including) the first hyphen is removed.
8833For instance, if the module name is <code>a.b.c-v2.1</code>,
8834the function name will be <code>luaopen_a_b_c</code>.
8835
8836
8837<p>
8838The fourth searcher tries an <em>all-in-one loader</em>.
8839It searches the C&nbsp;path for a library for
8840the root name of the given module.
8841For instance, when requiring <code>a.b.c</code>,
8842it will search for a C&nbsp;library for <code>a</code>.
8843If found, it looks into it for an open function for
8844the submodule;
8845in our example, that would be <code>luaopen_a_b_c</code>.
8846With this facility, a package can pack several C&nbsp;submodules
8847into one single library,
8848with each submodule keeping its original open function.
8849
8850
8851<p>
8852All searchers except the first one (preload) return as the extra value
8853the file path where the module was found,
8854as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8855The first searcher always returns the string "<code>:preload:</code>".
8856
8857
8858<p>
8859Searchers should raise no errors and have no side effects in Lua.
8860(They may have side effects in C,
8861for instance by linking the application with a library.)
8862
8863
8864
8865
8866<p>
8867<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8868
8869
8870<p>
8871Searches for the given <code>name</code> in the given <code>path</code>.
8872
8873
8874<p>
8875A path is a string containing a sequence of
8876<em>templates</em> separated by semicolons.
8877For each template,
8878the function replaces each interrogation mark (if any)
8879in the template with a copy of <code>name</code>
8880wherein all occurrences of <code>sep</code>
8881(a dot, by default)
8882were replaced by <code>rep</code>
8883(the system's directory separator, by default),
8884and then tries to open the resulting file name.
8885
8886
8887<p>
8888For instance, if the path is the string
8889
8890<pre>
8891     "./?.lua;./?.lc;/usr/local/?/init.lua"
8892</pre><p>
8893the search for the name <code>foo.a</code>
8894will try to open the files
8895<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8896<code>/usr/local/foo/a/init.lua</code>, in that order.
8897
8898
8899<p>
8900Returns the resulting name of the first file that it can
8901open in read mode (after closing the file),
8902or <b>fail</b> plus an error message if none succeeds.
8903(This error message lists all file names it tried to open.)
8904
8905
8906
8907
8908
8909
8910
8911<h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8912
8913
8914
8915<p>
8916This library provides generic functions for string manipulation,
8917such as finding and extracting substrings, and pattern matching.
8918When indexing a string in Lua, the first character is at position&nbsp;1
8919(not at&nbsp;0, as in C).
8920Indices are allowed to be negative and are interpreted as indexing backwards,
8921from the end of the string.
8922Thus, the last character is at position -1, and so on.
8923
8924
8925<p>
8926The string library provides all its functions inside the table
8927<a name="pdf-string"><code>string</code></a>.
8928It also sets a metatable for strings
8929where the <code>__index</code> field points to the <code>string</code> table.
8930Therefore, you can use the string functions in object-oriented style.
8931For instance, <code>string.byte(s,i)</code>
8932can be written as <code>s:byte(i)</code>.
8933
8934
8935<p>
8936The string library assumes one-byte character encodings.
8937
8938
8939<p>
8940<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8941Returns the internal numeric codes of the characters <code>s[i]</code>,
8942<code>s[i+1]</code>, ..., <code>s[j]</code>.
8943The default value for <code>i</code> is&nbsp;1;
8944the default value for <code>j</code> is&nbsp;<code>i</code>.
8945These indices are corrected
8946following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8947
8948
8949<p>
8950Numeric codes are not necessarily portable across platforms.
8951
8952
8953
8954
8955<p>
8956<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8957Receives zero or more integers.
8958Returns a string with length equal to the number of arguments,
8959in which each character has the internal numeric code equal
8960to its corresponding argument.
8961
8962
8963<p>
8964Numeric codes are not necessarily portable across platforms.
8965
8966
8967
8968
8969<p>
8970<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8971
8972
8973<p>
8974Returns a string containing a binary representation
8975(a <em>binary chunk</em>)
8976of the given function,
8977so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8978a copy of the function (but with new upvalues).
8979If <code>strip</code> is a true value,
8980the binary representation may not include all debug information
8981about the function,
8982to save space.
8983
8984
8985<p>
8986Functions with upvalues have only their number of upvalues saved.
8987When (re)loaded,
8988those upvalues receive fresh instances.
8989(See the <a href="#pdf-load"><code>load</code></a> function for details about
8990how these upvalues are initialized.
8991You can use the debug library to serialize
8992and reload the upvalues of a function
8993in a way adequate to your needs.)
8994
8995
8996
8997
8998<p>
8999<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
9000
9001
9002<p>
9003Looks for the first match of
9004<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9005If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
9006where this occurrence starts and ends;
9007otherwise, it returns <b>fail</b>.
9008A third, optional numeric argument <code>init</code> specifies
9009where to start the search;
9010its default value is&nbsp;1 and can be negative.
9011A value of <b>true</b> as a fourth, optional argument <code>plain</code>
9012turns off the pattern matching facilities,
9013so the function does a plain "find substring" operation,
9014with no characters in <code>pattern</code> being considered magic.
9015
9016
9017<p>
9018If the pattern has captures,
9019then in a successful match
9020the captured values are also returned,
9021after the two indices.
9022
9023
9024
9025
9026<p>
9027<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
9028
9029
9030<p>
9031Returns a formatted version of its variable number of arguments
9032following the description given in its first argument,
9033which must be a string.
9034The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
9035The only differences are that the conversion specifiers and modifiers
9036<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, and <code>n</code> are not supported
9037and that there is an extra specifier, <code>q</code>.
9038
9039
9040<p>
9041The specifier <code>q</code> formats booleans, nil, numbers, and strings
9042in a way that the result is a valid constant in Lua source code.
9043Booleans and nil are written in the obvious way
9044(<code>true</code>, <code>false</code>, <code>nil</code>).
9045Floats are written in hexadecimal,
9046to preserve full precision.
9047A string is written between double quotes,
9048using escape sequences when necessary to ensure that
9049it can safely be read back by the Lua interpreter.
9050For instance, the call
9051
9052<pre>
9053     string.format('%q', 'a string with "quotes" and \n new line')
9054</pre><p>
9055may produce the string:
9056
9057<pre>
9058     "a string with \"quotes\" and \
9059      new line"
9060</pre><p>
9061This specifier does not support modifiers (flags, width, length).
9062
9063
9064<p>
9065The conversion specifiers
9066<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
9067<code>G</code>, and <code>g</code> all expect a number as argument.
9068The specifiers <code>c</code>, <code>d</code>,
9069<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
9070expect an integer.
9071When Lua is compiled with a C89 compiler,
9072the specifiers <code>A</code> and <code>a</code> (hexadecimal floats)
9073do not support modifiers.
9074
9075
9076<p>
9077The specifier <code>s</code> expects a string;
9078if its argument is not a string,
9079it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
9080If the specifier has any modifier,
9081the corresponding string argument should not contain embedded zeros.
9082
9083
9084<p>
9085The specifier <code>p</code> formats the pointer
9086returned by <a href="#lua_topointer"><code>lua_topointer</code></a>.
9087That gives a unique string identifier for tables, userdata,
9088threads, strings, and functions.
9089For other values (numbers, nil, booleans),
9090this specifier results in a string representing
9091the pointer <code>NULL</code>.
9092
9093
9094
9095
9096<p>
9097<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern [, init])</code></a></h3>
9098Returns an iterator function that,
9099each time it is called,
9100returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
9101over the string <code>s</code>.
9102If <code>pattern</code> specifies no captures,
9103then the whole match is produced in each call.
9104A third, optional numeric argument <code>init</code> specifies
9105where to start the search;
9106its default value is&nbsp;1 and can be negative.
9107
9108
9109<p>
9110As an example, the following loop
9111will iterate over all the words from string <code>s</code>,
9112printing one per line:
9113
9114<pre>
9115     s = "hello world from Lua"
9116     for w in string.gmatch(s, "%a+") do
9117       print(w)
9118     end
9119</pre><p>
9120The next example collects all pairs <code>key=value</code> from the
9121given string into a table:
9122
9123<pre>
9124     t = {}
9125     s = "from=world, to=Lua"
9126     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
9127       t[k] = v
9128     end
9129</pre>
9130
9131<p>
9132For this function, a caret '<code>^</code>' at the start of a pattern does not
9133work as an anchor, as this would prevent the iteration.
9134
9135
9136
9137
9138<p>
9139<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
9140Returns a copy of <code>s</code>
9141in which all (or the first <code>n</code>, if given)
9142occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
9143replaced by a replacement string specified by <code>repl</code>,
9144which can be a string, a table, or a function.
9145<code>gsub</code> also returns, as its second value,
9146the total number of matches that occurred.
9147The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
9148
9149
9150<p>
9151If <code>repl</code> is a string, then its value is used for replacement.
9152The character&nbsp;<code>%</code> works as an escape character:
9153any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
9154with <em>d</em> between 1 and 9,
9155stands for the value of the <em>d</em>-th captured substring;
9156the sequence <code>%0</code> stands for the whole match;
9157the sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
9158
9159
9160<p>
9161If <code>repl</code> is a table, then the table is queried for every match,
9162using the first capture as the key.
9163
9164
9165<p>
9166If <code>repl</code> is a function, then this function is called every time a
9167match occurs, with all captured substrings passed as arguments,
9168in order.
9169
9170
9171<p>
9172In any case,
9173if the pattern specifies no captures,
9174then it behaves as if the whole pattern was inside a capture.
9175
9176
9177<p>
9178If the value returned by the table query or by the function call
9179is a string or a number,
9180then it is used as the replacement string;
9181otherwise, if it is <b>false</b> or <b>nil</b>,
9182then there is no replacement
9183(that is, the original match is kept in the string).
9184
9185
9186<p>
9187Here are some examples:
9188
9189<pre>
9190     x = string.gsub("hello world", "(%w+)", "%1 %1")
9191     --&gt; x="hello hello world world"
9192
9193     x = string.gsub("hello world", "%w+", "%0 %0", 1)
9194     --&gt; x="hello hello world"
9195
9196     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
9197     --&gt; x="world hello Lua from"
9198
9199     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
9200     --&gt; x="home = /home/roberto, user = roberto"
9201
9202     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
9203           return load(s)()
9204         end)
9205     --&gt; x="4+5 = 9"
9206
9207     local t = {name="lua", version="5.4"}
9208     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
9209     --&gt; x="lua-5.4.tar.gz"
9210</pre>
9211
9212
9213
9214<p>
9215<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
9216
9217
9218<p>
9219Receives a string and returns its length.
9220The empty string <code>""</code> has length 0.
9221Embedded zeros are counted,
9222so <code>"a\000bc\000"</code> has length 5.
9223
9224
9225
9226
9227<p>
9228<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
9229
9230
9231<p>
9232Receives a string and returns a copy of this string with all
9233uppercase letters changed to lowercase.
9234All other characters are left unchanged.
9235The definition of what an uppercase letter is depends on the current locale.
9236
9237
9238
9239
9240<p>
9241<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
9242
9243
9244<p>
9245Looks for the first <em>match</em> of
9246the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9247If it finds one, then <code>match</code> returns
9248the captures from the pattern;
9249otherwise it returns <b>fail</b>.
9250If <code>pattern</code> specifies no captures,
9251then the whole match is returned.
9252A third, optional numeric argument <code>init</code> specifies
9253where to start the search;
9254its default value is&nbsp;1 and can be negative.
9255
9256
9257
9258
9259<p>
9260<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
9261
9262
9263<p>
9264Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
9265serialized in binary form (packed)
9266according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9267
9268
9269
9270
9271<p>
9272<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
9273
9274
9275<p>
9276Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
9277with the given format.
9278The format string cannot have the variable-length options
9279'<code>s</code>' or '<code>z</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.rep"><code>string.rep (s, n [, sep])</code></a></h3>
9286
9287
9288<p>
9289Returns a string that is the concatenation of <code>n</code> copies of
9290the string <code>s</code> separated by the string <code>sep</code>.
9291The default value for <code>sep</code> is the empty string
9292(that is, no separator).
9293Returns the empty string if <code>n</code> is not positive.
9294
9295
9296<p>
9297(Note that it is very easy to exhaust the memory of your machine
9298with a single call to this function.)
9299
9300
9301
9302
9303<p>
9304<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
9305
9306
9307<p>
9308Returns a string that is the string <code>s</code> reversed.
9309
9310
9311
9312
9313<p>
9314<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
9315
9316
9317<p>
9318Returns the substring of <code>s</code> that
9319starts at <code>i</code>  and continues until <code>j</code>;
9320<code>i</code> and <code>j</code> can be negative.
9321If <code>j</code> is absent, then it is assumed to be equal to -1
9322(which is the same as the string length).
9323In particular,
9324the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
9325with length <code>j</code>,
9326and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
9327returns a suffix of <code>s</code>
9328with length <code>i</code>.
9329
9330
9331<p>
9332If, after the translation of negative indices,
9333<code>i</code> is less than 1,
9334it is corrected to 1.
9335If <code>j</code> is greater than the string length,
9336it is corrected to that length.
9337If, after these corrections,
9338<code>i</code> is greater than <code>j</code>,
9339the function returns the empty string.
9340
9341
9342
9343
9344<p>
9345<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
9346
9347
9348<p>
9349Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
9350according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9351An optional <code>pos</code> marks where
9352to start reading in <code>s</code> (default is 1).
9353After the read values,
9354this function also returns the index of the first unread byte in <code>s</code>.
9355
9356
9357
9358
9359<p>
9360<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
9361
9362
9363<p>
9364Receives a string and returns a copy of this string with all
9365lowercase letters changed to uppercase.
9366All other characters are left unchanged.
9367The definition of what a lowercase letter is depends on the current locale.
9368
9369
9370
9371
9372
9373
9374
9375<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
9376
9377
9378
9379<p>
9380Patterns in Lua are described by regular strings,
9381which are interpreted as patterns by the pattern-matching functions
9382<a href="#pdf-string.find"><code>string.find</code></a>,
9383<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
9384<a href="#pdf-string.gsub"><code>string.gsub</code></a>,
9385and <a href="#pdf-string.match"><code>string.match</code></a>.
9386This section describes the syntax and the meaning
9387(that is, what they match) of these strings.
9388
9389
9390
9391
9392
9393<h4>Character Class:</h4><p>
9394A <em>character class</em> is used to represent a set of characters.
9395The following combinations are allowed in describing a character class:
9396
9397<ul>
9398
9399<li><b><em>x</em>: </b>
9400(where <em>x</em> is not one of the <em>magic characters</em>
9401<code>^$()%.[]*+-?</code>)
9402represents the character <em>x</em> itself.
9403</li>
9404
9405<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
9406
9407<li><b><code>%a</code>: </b> represents all letters.</li>
9408
9409<li><b><code>%c</code>: </b> represents all control characters.</li>
9410
9411<li><b><code>%d</code>: </b> represents all digits.</li>
9412
9413<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
9414
9415<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
9416
9417<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
9418
9419<li><b><code>%s</code>: </b> represents all space characters.</li>
9420
9421<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
9422
9423<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
9424
9425<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
9426
9427<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
9428represents the character <em>x</em>.
9429This is the standard way to escape the magic characters.
9430Any non-alphanumeric character
9431(including all punctuation characters, even the non-magical)
9432can be preceded by a '<code>%</code>' to represent itself in a pattern.
9433</li>
9434
9435<li><b><code>[<em>set</em>]</code>: </b>
9436represents the class which is the union of all
9437characters in <em>set</em>.
9438A range of characters can be specified by
9439separating the end characters of the range,
9440in ascending order, with a '<code>-</code>'.
9441All classes <code>%</code><em>x</em> described above can also be used as
9442components in <em>set</em>.
9443All other characters in <em>set</em> represent themselves.
9444For example, <code>[%w_]</code> (or <code>[_%w]</code>)
9445represents all alphanumeric characters plus the underscore,
9446<code>[0-7]</code> represents the octal digits,
9447and <code>[0-7%l%-]</code> represents the octal digits plus
9448the lowercase letters plus the '<code>-</code>' character.
9449
9450
9451<p>
9452You can put a closing square bracket in a set
9453by positioning it as the first character in the set.
9454You can put a hyphen in a set
9455by positioning it as the first or the last character in the set.
9456(You can also use an escape for both cases.)
9457
9458
9459<p>
9460The interaction between ranges and classes is not defined.
9461Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
9462have no meaning.
9463</li>
9464
9465<li><b><code>[^<em>set</em>]</code>: </b>
9466represents the complement of <em>set</em>,
9467where <em>set</em> is interpreted as above.
9468</li>
9469
9470</ul><p>
9471For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
9472the corresponding uppercase letter represents the complement of the class.
9473For instance, <code>%S</code> represents all non-space characters.
9474
9475
9476<p>
9477The definitions of letter, space, and other character groups
9478depend on the current locale.
9479In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
9480
9481
9482
9483
9484
9485<h4>Pattern Item:</h4><p>
9486A <em>pattern item</em> can be
9487
9488<ul>
9489
9490<li>
9491a single character class,
9492which matches any single character in the class;
9493</li>
9494
9495<li>
9496a single character class followed by '<code>*</code>',
9497which matches sequences of zero or more characters in the class.
9498These repetition items will always match the longest possible sequence;
9499</li>
9500
9501<li>
9502a single character class followed by '<code>+</code>',
9503which matches sequences of one or more characters in the class.
9504These repetition items will always match the longest possible sequence;
9505</li>
9506
9507<li>
9508a single character class followed by '<code>-</code>',
9509which also matches sequences of zero or more characters in the class.
9510Unlike '<code>*</code>',
9511these repetition items will always match the shortest possible sequence;
9512</li>
9513
9514<li>
9515a single character class followed by '<code>?</code>',
9516which matches zero or one occurrence of a character in the class.
9517It always matches one occurrence if possible;
9518</li>
9519
9520<li>
9521<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
9522such item matches a substring equal to the <em>n</em>-th captured string
9523(see below);
9524</li>
9525
9526<li>
9527<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
9528such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
9529and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
9530This means that, if one reads the string from left to right,
9531counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
9532the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
9533For instance, the item <code>%b()</code> matches expressions with
9534balanced parentheses.
9535</li>
9536
9537<li>
9538<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
9539such item matches an empty string at any position such that
9540the next character belongs to <em>set</em>
9541and the previous character does not belong to <em>set</em>.
9542The set <em>set</em> is interpreted as previously described.
9543The beginning and the end of the subject are handled as if
9544they were the character '<code>\0</code>'.
9545</li>
9546
9547</ul>
9548
9549
9550
9551
9552<h4>Pattern:</h4><p>
9553A <em>pattern</em> is a sequence of pattern items.
9554A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
9555beginning of the subject string.
9556A '<code>$</code>' at the end of a pattern anchors the match at the
9557end of the subject string.
9558At other positions,
9559'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
9560
9561
9562
9563
9564
9565<h4>Captures:</h4><p>
9566A pattern can contain sub-patterns enclosed in parentheses;
9567they describe <em>captures</em>.
9568When a match succeeds, the substrings of the subject string
9569that match captures are stored (<em>captured</em>) for future use.
9570Captures are numbered according to their left parentheses.
9571For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
9572the part of the string matching <code>"a*(.)%w(%s*)"</code> is
9573stored as the first capture, and therefore has number&nbsp;1;
9574the character matching "<code>.</code>" is captured with number&nbsp;2,
9575and the part matching "<code>%s*</code>" has number&nbsp;3.
9576
9577
9578<p>
9579As a special case, the capture <code>()</code> captures
9580the current string position (a number).
9581For instance, if we apply the pattern <code>"()aa()"</code> on the
9582string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
9583
9584
9585
9586
9587
9588<h4>Multiple matches:</h4><p>
9589The function <a href="#pdf-string.gsub"><code>string.gsub</code></a> and the iterator <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>
9590match multiple occurrences of the given pattern in the subject.
9591For these functions,
9592a new match is considered valid only
9593if it ends at least one byte after the end of the previous match.
9594In other words, the pattern machine never accepts the
9595empty string as a match immediately after another match.
9596As an example,
9597consider the results of the following code:
9598
9599<pre>
9600     &gt; string.gsub("abc", "()a*()", print);
9601     --&gt; 1   2
9602     --&gt; 3   3
9603     --&gt; 4   4
9604</pre><p>
9605The second and third results come from Lua matching an empty
9606string after '<code>b</code>' and another one after '<code>c</code>'.
9607Lua does not match an empty string after '<code>a</code>',
9608because it would end at the same position of the previous match.
9609
9610
9611
9612
9613
9614
9615
9616<h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
9617
9618<p>
9619The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
9620<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
9621is a format string,
9622which describes the layout of the structure being created or read.
9623
9624
9625<p>
9626A format string is a sequence of conversion options.
9627The conversion options are as follows:
9628
9629<ul>
9630<li><b><code>&lt;</code>: </b>sets little endian</li>
9631<li><b><code>&gt;</code>: </b>sets big endian</li>
9632<li><b><code>=</code>: </b>sets native endian</li>
9633<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
9634(default is native alignment)</li>
9635<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
9636<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
9637<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
9638<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
9639<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
9640<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
9641<li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
9642<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
9643<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
9644<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
9645(default is native size)</li>
9646<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
9647(default is native size)</li>
9648<li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
9649<li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
9650<li><b><code>n</code>: </b>a <code>lua_Number</code></li>
9651<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
9652<li><b><code>z</code>: </b>a zero-terminated string</li>
9653<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
9654coded as an unsigned integer with <code>n</code> bytes
9655(default is a <code>size_t</code>)</li>
9656<li><b><code>x</code>: </b>one byte of padding</li>
9657<li><b><code>X<em>op</em></code>: </b>an empty item that aligns
9658according to option <code>op</code>
9659(which is otherwise ignored)</li>
9660<li><b>'<code> </code>': </b>(space) ignored</li>
9661</ul><p>
9662(A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
9663Except for padding, spaces, and configurations
9664(options "<code>xX &lt;=&gt;!</code>"),
9665each option corresponds to an argument in <a href="#pdf-string.pack"><code>string.pack</code></a>
9666or a result in <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9667
9668
9669<p>
9670For 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>",
9671<code>n</code> can be any integer between 1 and 16.
9672All integral options check overflows;
9673<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
9674<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
9675For the unsigned options,
9676Lua integers are treated as unsigned values too.
9677
9678
9679<p>
9680Any format string starts as if prefixed by "<code>!1=</code>",
9681that is,
9682with maximum alignment of 1 (no alignment)
9683and native endianness.
9684
9685
9686<p>
9687Native endianness assumes that the whole system is
9688either big or little endian.
9689The packing functions will not emulate correctly the behavior
9690of mixed-endian formats.
9691
9692
9693<p>
9694Alignment works as follows:
9695For each option,
9696the format gets extra padding until the data starts
9697at an offset that is a multiple of the minimum between the
9698option size and the maximum alignment;
9699this minimum must be a power of 2.
9700Options "<code>c</code>" and "<code>z</code>" are not aligned;
9701option "<code>s</code>" follows the alignment of its starting integer.
9702
9703
9704<p>
9705All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
9706and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9707
9708
9709
9710
9711
9712
9713
9714<h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
9715
9716<p>
9717This library provides basic support for UTF-8 encoding.
9718It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
9719This library does not provide any support for Unicode other
9720than the handling of the encoding.
9721Any operation that needs the meaning of a character,
9722such as character classification, is outside its scope.
9723
9724
9725<p>
9726Unless stated otherwise,
9727all functions that expect a byte position as a parameter
9728assume that the given position is either the start of a byte sequence
9729or one plus the length of the subject string.
9730As in the string library,
9731negative indices count from the end of the string.
9732
9733
9734<p>
9735Functions that create byte sequences
9736accept all values up to <code>0x7FFFFFFF</code>,
9737as defined in the original UTF-8 specification;
9738that implies byte sequences of up to six bytes.
9739
9740
9741<p>
9742Functions that interpret byte sequences only accept
9743valid sequences (well formed and not overlong).
9744By default, they only accept byte sequences
9745that result in valid Unicode code points,
9746rejecting values greater than <code>10FFFF</code> and surrogates.
9747A boolean argument <code>lax</code>, when available,
9748lifts these checks,
9749so that all values up to <code>0x7FFFFFFF</code> are accepted.
9750(Not well formed and overlong sequences are still rejected.)
9751
9752
9753<p>
9754<hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
9755
9756
9757<p>
9758Receives zero or more integers,
9759converts each one to its corresponding UTF-8 byte sequence
9760and returns a string with the concatenation of all these sequences.
9761
9762
9763
9764
9765<p>
9766<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
9767
9768
9769<p>
9770The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xFD][\x80-\xBF]*</code>"
9771(see <a href="#6.4.1">&sect;6.4.1</a>),
9772which matches exactly one UTF-8 byte sequence,
9773assuming that the subject is a valid UTF-8 string.
9774
9775
9776
9777
9778<p>
9779<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s [, lax])</code></a></h3>
9780
9781
9782<p>
9783Returns values so that the construction
9784
9785<pre>
9786     for p, c in utf8.codes(s) do <em>body</em> end
9787</pre><p>
9788will iterate over all UTF-8 characters in string <code>s</code>,
9789with <code>p</code> being the position (in bytes) and <code>c</code> the code point
9790of each character.
9791It raises an error if it meets any invalid byte sequence.
9792
9793
9794
9795
9796<p>
9797<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j [, lax]]])</code></a></h3>
9798
9799
9800<p>
9801Returns the code points (as integers) from all characters in <code>s</code>
9802that start between byte position <code>i</code> and <code>j</code> (both included).
9803The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
9804It raises an error if it meets any invalid byte sequence.
9805
9806
9807
9808
9809<p>
9810<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j [, lax]]])</code></a></h3>
9811
9812
9813<p>
9814Returns the number of UTF-8 characters in string <code>s</code>
9815that start between positions <code>i</code> and <code>j</code> (both inclusive).
9816The default for <code>i</code> is 1 and for <code>j</code> is -1.
9817If it finds any invalid byte sequence,
9818returns <b>fail</b> plus the position of the first invalid byte.
9819
9820
9821
9822
9823<p>
9824<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
9825
9826
9827<p>
9828Returns the position (in bytes) where the encoding of the
9829<code>n</code>-th character of <code>s</code>
9830(counting from position <code>i</code>) starts.
9831A negative <code>n</code> gets characters before position <code>i</code>.
9832The default for <code>i</code> is 1 when <code>n</code> is non-negative
9833and <code>#s + 1</code> otherwise,
9834so that <code>utf8.offset(s, -n)</code> gets the offset of the
9835<code>n</code>-th character from the end of the string.
9836If the specified character is neither in the subject
9837nor right after its end,
9838the function returns <b>fail</b>.
9839
9840
9841<p>
9842As a special case,
9843when <code>n</code> is 0 the function returns the start of the encoding
9844of the character that contains the <code>i</code>-th byte of <code>s</code>.
9845
9846
9847<p>
9848This function assumes that <code>s</code> is a valid UTF-8 string.
9849
9850
9851
9852
9853
9854
9855
9856<h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
9857
9858<p>
9859This library provides generic functions for table manipulation.
9860It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
9861
9862
9863<p>
9864Remember that, whenever an operation needs the length of a table,
9865all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>).
9866All functions ignore non-numeric keys
9867in the tables given as arguments.
9868
9869
9870<p>
9871<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
9872
9873
9874<p>
9875Given a list where all elements are strings or numbers,
9876returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
9877The default value for <code>sep</code> is the empty string,
9878the default for <code>i</code> is 1,
9879and the default for <code>j</code> is <code>#list</code>.
9880If <code>i</code> is greater than <code>j</code>, returns the empty string.
9881
9882
9883
9884
9885<p>
9886<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
9887
9888
9889<p>
9890Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
9891shifting up the elements
9892<code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
9893The default value for <code>pos</code> is <code>#list+1</code>,
9894so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
9895of the list <code>t</code>.
9896
9897
9898
9899
9900<p>
9901<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
9902
9903
9904<p>
9905Moves elements from the table <code>a1</code> to the table <code>a2</code>,
9906performing the equivalent to the following
9907multiple assignment:
9908<code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
9909The default for <code>a2</code> is <code>a1</code>.
9910The destination range can overlap with the source range.
9911The number of elements to be moved must fit in a Lua integer.
9912
9913
9914<p>
9915Returns the destination table <code>a2</code>.
9916
9917
9918
9919
9920<p>
9921<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
9922
9923
9924<p>
9925Returns a new table with all arguments stored into keys 1, 2, etc.
9926and with a field "<code>n</code>" with the total number of arguments.
9927Note that the resulting table may not be a sequence,
9928if some arguments are <b>nil</b>.
9929
9930
9931
9932
9933<p>
9934<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
9935
9936
9937<p>
9938Removes from <code>list</code> the element at position <code>pos</code>,
9939returning the value of the removed element.
9940When <code>pos</code> is an integer between 1 and <code>#list</code>,
9941it shifts down the elements
9942<code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
9943and erases element <code>list[#list]</code>;
9944The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
9945or <code>#list + 1</code>.
9946
9947
9948<p>
9949The default value for <code>pos</code> is <code>#list</code>,
9950so that a call <code>table.remove(l)</code> removes the last element
9951of the list <code>l</code>.
9952
9953
9954
9955
9956<p>
9957<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
9958
9959
9960<p>
9961Sorts the list elements in a given order, <em>in-place</em>,
9962from <code>list[1]</code> to <code>list[#list]</code>.
9963If <code>comp</code> is given,
9964then it must be a function that receives two list elements
9965and returns true when the first element must come
9966before the second in the final order
9967(so that, after the sort,
9968<code>i &lt; j</code> implies <code>not comp(list[j],list[i])</code>).
9969If <code>comp</code> is not given,
9970then the standard Lua operator <code>&lt;</code> is used instead.
9971
9972
9973<p>
9974Note that the <code>comp</code> function must define
9975a strict partial order over the elements in the list;
9976that is, it must be asymmetric and transitive.
9977Otherwise, no valid sort may be possible.
9978
9979
9980<p>
9981The sort algorithm is not stable:
9982elements considered equal by the given order
9983may have their relative positions changed by the sort.
9984
9985
9986
9987
9988<p>
9989<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
9990
9991
9992<p>
9993Returns the elements from the given list.
9994This function is equivalent to
9995
9996<pre>
9997     return list[i], list[i+1], &middot;&middot;&middot;, list[j]
9998</pre><p>
9999By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
10000
10001
10002
10003
10004
10005
10006
10007<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
10008
10009<p>
10010This library provides basic mathematical functions.
10011It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
10012Functions with the annotation "<code>integer/float</code>" give
10013integer results for integer arguments
10014and float results for non-integer arguments.
10015The rounding functions
10016<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>
10017return an integer when the result fits in the range of an integer,
10018or a float otherwise.
10019
10020
10021<p>
10022<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
10023
10024
10025<p>
10026Returns the maximum value between <code>x</code> and <code>-x</code>. (integer/float)
10027
10028
10029
10030
10031<p>
10032<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
10033
10034
10035<p>
10036Returns the arc cosine of <code>x</code> (in radians).
10037
10038
10039
10040
10041<p>
10042<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
10043
10044
10045<p>
10046Returns the arc sine of <code>x</code> (in radians).
10047
10048
10049
10050
10051<p>
10052<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
10053
10054
10055<p>
10056
10057Returns the arc tangent of <code>y/x</code> (in radians),
10058but uses the signs of both arguments to find the
10059quadrant of the result.
10060It also handles correctly the case of <code>x</code> being zero.
10061
10062
10063<p>
10064The default value for <code>x</code> is 1,
10065so that the call <code>math.atan(y)</code>
10066returns the arc tangent of <code>y</code>.
10067
10068
10069
10070
10071<p>
10072<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
10073
10074
10075<p>
10076Returns the smallest integral value greater than or equal to <code>x</code>.
10077
10078
10079
10080
10081<p>
10082<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
10083
10084
10085<p>
10086Returns the cosine of <code>x</code> (assumed to be in radians).
10087
10088
10089
10090
10091<p>
10092<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
10093
10094
10095<p>
10096Converts the angle <code>x</code> from radians to degrees.
10097
10098
10099
10100
10101<p>
10102<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
10103
10104
10105<p>
10106Returns the value <em>e<sup>x</sup></em>
10107(where <code>e</code> is the base of natural logarithms).
10108
10109
10110
10111
10112<p>
10113<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
10114
10115
10116<p>
10117Returns the largest integral value less than or equal to <code>x</code>.
10118
10119
10120
10121
10122<p>
10123<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
10124
10125
10126<p>
10127Returns the remainder of the division of <code>x</code> by <code>y</code>
10128that rounds the quotient towards zero. (integer/float)
10129
10130
10131
10132
10133<p>
10134<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
10135
10136
10137<p>
10138The float value <code>HUGE_VAL</code>,
10139a value greater than any other numeric value.
10140
10141
10142
10143
10144<p>
10145<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
10146
10147
10148<p>
10149Returns the logarithm of <code>x</code> in the given base.
10150The default for <code>base</code> is <em>e</em>
10151(so that the function returns the natural logarithm of <code>x</code>).
10152
10153
10154
10155
10156<p>
10157<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
10158
10159
10160<p>
10161Returns the argument with the maximum value,
10162according to the Lua operator <code>&lt;</code>.
10163
10164
10165
10166
10167<p>
10168<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
10169An integer with the maximum value for an integer.
10170
10171
10172
10173
10174<p>
10175<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
10176
10177
10178<p>
10179Returns the argument with the minimum value,
10180according to the Lua operator <code>&lt;</code>.
10181
10182
10183
10184
10185<p>
10186<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
10187An integer with the minimum value for an integer.
10188
10189
10190
10191
10192<p>
10193<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
10194
10195
10196<p>
10197Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
10198Its second result is always a float.
10199
10200
10201
10202
10203<p>
10204<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
10205
10206
10207<p>
10208The value of <em>&pi;</em>.
10209
10210
10211
10212
10213<p>
10214<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
10215
10216
10217<p>
10218Converts the angle <code>x</code> from degrees to radians.
10219
10220
10221
10222
10223<p>
10224<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
10225
10226
10227<p>
10228When called without arguments,
10229returns a pseudo-random float with uniform distribution
10230in the range  <em>[0,1)</em>.
10231When called with two integers <code>m</code> and <code>n</code>,
10232<code>math.random</code> returns a pseudo-random integer
10233with uniform distribution in the range <em>[m, n]</em>.
10234The call <code>math.random(n)</code>, for a positive <code>n</code>,
10235is equivalent to <code>math.random(1,n)</code>.
10236The call <code>math.random(0)</code> produces an integer with
10237all bits (pseudo)random.
10238
10239
10240<p>
10241This function uses the <code>xoshiro256**</code> algorithm to produce
10242pseudo-random 64-bit integers,
10243which are the results of calls with argument&nbsp;0.
10244Other results (ranges and floats)
10245are unbiased extracted from these integers.
10246
10247
10248<p>
10249Lua initializes its pseudo-random generator with the equivalent of
10250a call to <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with no arguments,
10251so that <code>math.random</code> should generate
10252different sequences of results each time the program runs.
10253
10254
10255
10256
10257<p>
10258<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed ([x [, y]])</code></a></h3>
10259
10260
10261<p>
10262When called with at least one argument,
10263the integer parameters <code>x</code> and <code>y</code> are
10264joined into a 128-bit <em>seed</em> that
10265is used to reinitialize the pseudo-random generator;
10266equal seeds produce equal sequences of numbers.
10267The default for <code>y</code> is zero.
10268
10269
10270<p>
10271When called with no arguments,
10272Lua generates a seed with
10273a weak attempt for randomness.
10274
10275
10276<p>
10277This function returns the two seed components
10278that were effectively used,
10279so that setting them again repeats the sequence.
10280
10281
10282<p>
10283To ensure a required level of randomness to the initial state
10284(or contrarily, to have a deterministic sequence,
10285for instance when debugging a program),
10286you should call <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with explicit arguments.
10287
10288
10289
10290
10291<p>
10292<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
10293
10294
10295<p>
10296Returns the sine of <code>x</code> (assumed to be in radians).
10297
10298
10299
10300
10301<p>
10302<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
10303
10304
10305<p>
10306Returns the square root of <code>x</code>.
10307(You can also use the expression <code>x^0.5</code> to compute this value.)
10308
10309
10310
10311
10312<p>
10313<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
10314
10315
10316<p>
10317Returns the tangent of <code>x</code> (assumed to be in radians).
10318
10319
10320
10321
10322<p>
10323<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
10324
10325
10326<p>
10327If the value <code>x</code> is convertible to an integer,
10328returns that integer.
10329Otherwise, returns <b>fail</b>.
10330
10331
10332
10333
10334<p>
10335<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
10336
10337
10338<p>
10339Returns "<code>integer</code>" if <code>x</code> is an integer,
10340"<code>float</code>" if it is a float,
10341or <b>fail</b> if <code>x</code> is not a number.
10342
10343
10344
10345
10346<p>
10347<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
10348
10349
10350<p>
10351Returns a boolean,
10352true if and only if integer <code>m</code> is below integer <code>n</code> when
10353they are compared as unsigned integers.
10354
10355
10356
10357
10358
10359
10360
10361<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
10362
10363<p>
10364The I/O library provides two different styles for file manipulation.
10365The first one uses implicit file handles;
10366that is, there are operations to set a default input file and a
10367default output file,
10368and all input/output operations are done over these default files.
10369The second style uses explicit file handles.
10370
10371
10372<p>
10373When using implicit file handles,
10374all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
10375When using explicit file handles,
10376the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
10377and then all operations are supplied as methods of the file handle.
10378
10379
10380<p>
10381The metatable for file handles provides metamethods
10382for <code>__gc</code> and <code>__close</code> that try
10383to close the file when called.
10384
10385
10386<p>
10387The table <code>io</code> also provides
10388three predefined file handles with their usual meanings from C:
10389<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>.
10390The I/O library never closes these files.
10391
10392
10393<p>
10394Unless otherwise stated,
10395all I/O functions return <b>fail</b> on failure,
10396plus an error message as a second result and
10397a system-dependent error code as a third result,
10398and some non-false value on success.
10399On non-POSIX systems,
10400the computation of the error message and error code
10401in case of errors
10402may be not thread safe,
10403because they rely on the global C variable <code>errno</code>.
10404
10405
10406<p>
10407<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
10408
10409
10410<p>
10411Equivalent to <code>file:close()</code>.
10412Without a <code>file</code>, closes the default output file.
10413
10414
10415
10416
10417<p>
10418<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
10419
10420
10421<p>
10422Equivalent to <code>io.output():flush()</code>.
10423
10424
10425
10426
10427<p>
10428<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
10429
10430
10431<p>
10432When called with a file name, it opens the named file (in text mode),
10433and sets its handle as the default input file.
10434When called with a file handle,
10435it simply sets this file handle as the default input file.
10436When called without arguments,
10437it returns the current default input file.
10438
10439
10440<p>
10441In case of errors this function raises the error,
10442instead of returning an error code.
10443
10444
10445
10446
10447<p>
10448<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3>
10449
10450
10451<p>
10452Opens the given file name in read mode
10453and returns an iterator function that
10454works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
10455When the iterator function fails to read any value,
10456it automatically closes the file.
10457Besides the iterator function,
10458<code>io.lines</code> returns three other values:
10459two <b>nil</b> values as placeholders,
10460plus the created file handle.
10461Therefore, when used in a generic <b>for</b> loop,
10462the file is closed also if the loop is interrupted by an
10463error or a <b>break</b>.
10464
10465
10466<p>
10467The call <code>io.lines()</code> (with no file name) is equivalent
10468to <code>io.input():lines("l")</code>;
10469that is, it iterates over the lines of the default input file.
10470In this case, the iterator does not close the file when the loop ends.
10471
10472
10473<p>
10474In case of errors opening the file,
10475this function raises the error,
10476instead of returning an error code.
10477
10478
10479
10480
10481<p>
10482<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
10483
10484
10485<p>
10486This function opens a file,
10487in the mode specified in the string <code>mode</code>.
10488In case of success,
10489it returns a new file handle.
10490
10491
10492<p>
10493The <code>mode</code> string can be any of the following:
10494
10495<ul>
10496<li><b>"<code>r</code>": </b> read mode (the default);</li>
10497<li><b>"<code>w</code>": </b> write mode;</li>
10498<li><b>"<code>a</code>": </b> append mode;</li>
10499<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
10500<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
10501<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
10502  writing is only allowed at the end of file.</li>
10503</ul><p>
10504The <code>mode</code> string can also have a '<code>b</code>' at the end,
10505which is needed in some systems to open the file in binary mode.
10506
10507
10508
10509
10510<p>
10511<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
10512
10513
10514<p>
10515Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
10516
10517
10518
10519
10520<p>
10521<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
10522
10523
10524<p>
10525This function is system dependent and is not available
10526on all platforms.
10527
10528
10529<p>
10530Starts the program <code>prog</code> in a separated process and returns
10531a file handle that you can use to read data from this program
10532(if <code>mode</code> is <code>"r"</code>, the default)
10533or to write data to this program
10534(if <code>mode</code> is <code>"w"</code>).
10535
10536
10537
10538
10539<p>
10540<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
10541
10542
10543<p>
10544Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
10545
10546
10547
10548
10549<p>
10550<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
10551
10552
10553<p>
10554In case of success,
10555returns a handle for a temporary file.
10556This file is opened in update mode
10557and it is automatically removed when the program ends.
10558
10559
10560
10561
10562<p>
10563<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
10564
10565
10566<p>
10567Checks whether <code>obj</code> is a valid file handle.
10568Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
10569<code>"closed file"</code> if <code>obj</code> is a closed file handle,
10570or <b>fail</b> if <code>obj</code> is not a file handle.
10571
10572
10573
10574
10575<p>
10576<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
10577
10578
10579<p>
10580Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
10581
10582
10583
10584
10585<p>
10586<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
10587
10588
10589<p>
10590Closes <code>file</code>.
10591Note that files are automatically closed when
10592their handles are garbage collected,
10593but that takes an unpredictable amount of time to happen.
10594
10595
10596<p>
10597When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
10598<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
10599returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
10600
10601
10602
10603
10604<p>
10605<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
10606
10607
10608<p>
10609Saves any written data to <code>file</code>.
10610
10611
10612
10613
10614<p>
10615<hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
10616
10617
10618<p>
10619Returns an iterator function that,
10620each time it is called,
10621reads the file according to the given formats.
10622When no format is given,
10623uses "<code>l</code>" as a default.
10624As an example, the construction
10625
10626<pre>
10627     for c in file:lines(1) do <em>body</em> end
10628</pre><p>
10629will iterate over all characters of the file,
10630starting at the current position.
10631Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
10632when the loop ends.
10633
10634
10635
10636
10637<p>
10638<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
10639
10640
10641<p>
10642Reads the file <code>file</code>,
10643according to the given formats, which specify what to read.
10644For each format,
10645the function returns a string or a number with the characters read,
10646or <b>fail</b> if it cannot read data with the specified format.
10647(In this latter case,
10648the function does not read subsequent formats.)
10649When called without arguments,
10650it uses a default format that reads the next line
10651(see below).
10652
10653
10654<p>
10655The available formats are
10656
10657<ul>
10658
10659<li><b>"<code>n</code>": </b>
10660reads a numeral and returns it as a float or an integer,
10661following the lexical conventions of Lua.
10662(The numeral may have leading whitespaces and a sign.)
10663This format always reads the longest input sequence that
10664is a valid prefix for a numeral;
10665if that prefix does not form a valid numeral
10666(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>")
10667or it is too long (more than 200 characters),
10668it is discarded and the format returns <b>fail</b>.
10669</li>
10670
10671<li><b>"<code>a</code>": </b>
10672reads the whole file, starting at the current position.
10673On end of file, it returns the empty string;
10674this format never fails.
10675</li>
10676
10677<li><b>"<code>l</code>": </b>
10678reads the next line skipping the end of line,
10679returning <b>fail</b> on end of file.
10680This is the default format.
10681</li>
10682
10683<li><b>"<code>L</code>": </b>
10684reads the next line keeping the end-of-line character (if present),
10685returning <b>fail</b> on end of file.
10686</li>
10687
10688<li><b><em>number</em>: </b>
10689reads a string with up to this number of bytes,
10690returning <b>fail</b> on end of file.
10691If <code>number</code> is zero,
10692it reads nothing and returns an empty string,
10693or <b>fail</b> on end of file.
10694</li>
10695
10696</ul><p>
10697The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
10698
10699
10700
10701
10702<p>
10703<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
10704
10705
10706<p>
10707Sets and gets the file position,
10708measured from the beginning of the file,
10709to the position given by <code>offset</code> plus a base
10710specified by the string <code>whence</code>, as follows:
10711
10712<ul>
10713<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
10714<li><b>"<code>cur</code>": </b> base is current position;</li>
10715<li><b>"<code>end</code>": </b> base is end of file;</li>
10716</ul><p>
10717In case of success, <code>seek</code> returns the final file position,
10718measured in bytes from the beginning of the file.
10719If <code>seek</code> fails, it returns <b>fail</b>,
10720plus a string describing the error.
10721
10722
10723<p>
10724The default value for <code>whence</code> is <code>"cur"</code>,
10725and for <code>offset</code> is 0.
10726Therefore, the call <code>file:seek()</code> returns the current
10727file position, without changing it;
10728the call <code>file:seek("set")</code> sets the position to the
10729beginning of the file (and returns 0);
10730and the call <code>file:seek("end")</code> sets the position to the
10731end of the file, and returns its size.
10732
10733
10734
10735
10736<p>
10737<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
10738
10739
10740<p>
10741Sets the buffering mode for a file.
10742There are three available modes:
10743
10744<ul>
10745<li><b>"<code>no</code>": </b> no buffering.</li>
10746<li><b>"<code>full</code>": </b> full buffering.</li>
10747<li><b>"<code>line</code>": </b> line buffering.</li>
10748</ul>
10749
10750<p>
10751For the last two cases,
10752<code>size</code> is a hint for the size of the buffer, in bytes.
10753The default is an appropriate size.
10754
10755
10756<p>
10757The specific behavior of each mode is non portable;
10758check the underlying ISO&nbsp;C function <code>setvbuf</code> in your platform for
10759more details.
10760
10761
10762
10763
10764<p>
10765<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
10766
10767
10768<p>
10769Writes the value of each of its arguments to <code>file</code>.
10770The arguments must be strings or numbers.
10771
10772
10773<p>
10774In case of success, this function returns <code>file</code>.
10775
10776
10777
10778
10779
10780
10781
10782<h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
10783
10784<p>
10785This library is implemented through table <a name="pdf-os"><code>os</code></a>.
10786
10787
10788<p>
10789<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
10790
10791
10792<p>
10793Returns an approximation of the amount in seconds of CPU time
10794used by the program,
10795as returned by the underlying ISO&nbsp;C function <code>clock</code>.
10796
10797
10798
10799
10800<p>
10801<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
10802
10803
10804<p>
10805Returns a string or a table containing date and time,
10806formatted according to the given string <code>format</code>.
10807
10808
10809<p>
10810If the <code>time</code> argument is present,
10811this is the time to be formatted
10812(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
10813Otherwise, <code>date</code> formats the current time.
10814
10815
10816<p>
10817If <code>format</code> starts with '<code>!</code>',
10818then the date is formatted in Coordinated Universal Time.
10819After this optional character,
10820if <code>format</code> is the string "<code>*t</code>",
10821then <code>date</code> returns a table with the following fields:
10822<code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
10823<code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59),
10824<code>sec</code> (0&ndash;61, due to leap seconds),
10825<code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1),
10826<code>yday</code> (day of the year, 1&ndash;366),
10827and <code>isdst</code> (daylight saving flag, a boolean).
10828This last field may be absent
10829if the information is not available.
10830
10831
10832<p>
10833If <code>format</code> is not "<code>*t</code>",
10834then <code>date</code> returns the date as a string,
10835formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
10836
10837
10838<p>
10839If <code>format</code> is absent, it defaults to "<code>%c</code>",
10840which gives a human-readable date and time representation
10841using the current locale.
10842
10843
10844<p>
10845On non-POSIX systems,
10846this function may be not thread safe
10847because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
10848
10849
10850
10851
10852<p>
10853<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
10854
10855
10856<p>
10857Returns the difference, in seconds,
10858from time <code>t1</code> to time <code>t2</code>
10859(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
10860In POSIX, Windows, and some other systems,
10861this value is exactly <code>t2</code><em>-</em><code>t1</code>.
10862
10863
10864
10865
10866<p>
10867<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
10868
10869
10870<p>
10871This function is equivalent to the ISO&nbsp;C function <code>system</code>.
10872It passes <code>command</code> to be executed by an operating system shell.
10873Its first result is <b>true</b>
10874if the command terminated successfully,
10875or <b>fail</b> otherwise.
10876After this first result
10877the function returns a string plus a number,
10878as follows:
10879
10880<ul>
10881
10882<li><b>"<code>exit</code>": </b>
10883the command terminated normally;
10884the following number is the exit status of the command.
10885</li>
10886
10887<li><b>"<code>signal</code>": </b>
10888the command was terminated by a signal;
10889the following number is the signal that terminated the command.
10890</li>
10891
10892</ul>
10893
10894<p>
10895When called without a <code>command</code>,
10896<code>os.execute</code> returns a boolean that is true if a shell is available.
10897
10898
10899
10900
10901<p>
10902<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
10903
10904
10905<p>
10906Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
10907If <code>code</code> is <b>true</b>,
10908the returned status is <code>EXIT_SUCCESS</code>;
10909if <code>code</code> is <b>false</b>,
10910the returned status is <code>EXIT_FAILURE</code>;
10911if <code>code</code> is a number,
10912the returned status is this number.
10913The default value for <code>code</code> is <b>true</b>.
10914
10915
10916<p>
10917If the optional second argument <code>close</code> is true,
10918closes the Lua state before exiting.
10919
10920
10921
10922
10923<p>
10924<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
10925
10926
10927<p>
10928Returns the value of the process environment variable <code>varname</code>
10929or <b>fail</b> if the variable is not defined.
10930
10931
10932
10933
10934<p>
10935<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
10936
10937
10938<p>
10939Deletes the file (or empty directory, on POSIX systems)
10940with the given name.
10941If this function fails, it returns <b>fail</b>
10942plus a string describing the error and the error code.
10943Otherwise, it returns true.
10944
10945
10946
10947
10948<p>
10949<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
10950
10951
10952<p>
10953Renames the file or directory named <code>oldname</code> to <code>newname</code>.
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.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
10963
10964
10965<p>
10966Sets the current locale of the program.
10967<code>locale</code> is a system-dependent string specifying a locale;
10968<code>category</code> is an optional string describing which category to change:
10969<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
10970<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
10971the default category is <code>"all"</code>.
10972The function returns the name of the new locale,
10973or <b>fail</b> if the request cannot be honored.
10974
10975
10976<p>
10977If <code>locale</code> is the empty string,
10978the current locale is set to an implementation-defined native locale.
10979If <code>locale</code> is the string "<code>C</code>",
10980the current locale is set to the standard C locale.
10981
10982
10983<p>
10984When called with <b>nil</b> as the first argument,
10985this function only returns the name of the current locale
10986for the given category.
10987
10988
10989<p>
10990This function may be not thread safe
10991because of its reliance on C&nbsp;function <code>setlocale</code>.
10992
10993
10994
10995
10996<p>
10997<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
10998
10999
11000<p>
11001Returns the current time when called without arguments,
11002or a time representing the local date and time specified by the given table.
11003This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
11004and may have fields
11005<code>hour</code> (default is 12),
11006<code>min</code> (default is 0),
11007<code>sec</code> (default is 0),
11008and <code>isdst</code> (default is <b>nil</b>).
11009Other fields are ignored.
11010For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
11011
11012
11013<p>
11014When the function is called,
11015the values in these fields do not need to be inside their valid ranges.
11016For instance, if <code>sec</code> is -10,
11017it means 10 seconds before the time specified by the other fields;
11018if <code>hour</code> is 1000,
11019it means 1000 hours after the time specified by the other fields.
11020
11021
11022<p>
11023The returned value is a number, whose meaning depends on your system.
11024In POSIX, Windows, and some other systems,
11025this number counts the number
11026of seconds since some given start time (the "epoch").
11027In other systems, the meaning is not specified,
11028and the number returned by <code>time</code> can be used only as an argument to
11029<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
11030
11031
11032<p>
11033When called with a table,
11034<code>os.time</code> also normalizes all the fields
11035documented in the <a href="#pdf-os.date"><code>os.date</code></a> function,
11036so that they represent the same time as before the call
11037but with values inside their valid ranges.
11038
11039
11040
11041
11042<p>
11043<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
11044
11045
11046<p>
11047Returns a string with a file name that can
11048be used for a temporary file.
11049The file must be explicitly opened before its use
11050and explicitly removed when no longer needed.
11051
11052
11053<p>
11054In POSIX systems,
11055this function also creates a file with that name,
11056to avoid security risks.
11057(Someone else might create the file with wrong permissions
11058in the time between getting the name and creating the file.)
11059You still have to open the file to use it
11060and to remove it (even if you do not use it).
11061
11062
11063<p>
11064When possible,
11065you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
11066which automatically removes the file when the program ends.
11067
11068
11069
11070
11071
11072
11073
11074<h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
11075
11076<p>
11077This library provides
11078the functionality of the debug interface (<a href="#4.7">&sect;4.7</a>) to Lua programs.
11079You should exert care when using this library.
11080Several of its functions
11081violate basic assumptions about Lua code
11082(e.g., that variables local to a function
11083cannot be accessed from outside;
11084that userdata metatables cannot be changed by Lua code;
11085that Lua programs do not crash)
11086and therefore can compromise otherwise secure code.
11087Moreover, some functions in this library may be slow.
11088
11089
11090<p>
11091All functions in this library are provided
11092inside the <a name="pdf-debug"><code>debug</code></a> table.
11093All functions that operate over a thread
11094have an optional first argument which is the
11095thread to operate over.
11096The default is always the current thread.
11097
11098
11099<p>
11100<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
11101
11102
11103<p>
11104Enters an interactive mode with the user,
11105running each string that the user enters.
11106Using simple commands and other debug facilities,
11107the user can inspect global and local variables,
11108change their values, evaluate expressions, and so on.
11109A line containing only the word <code>cont</code> finishes this function,
11110so that the caller continues its execution.
11111
11112
11113<p>
11114Note that commands for <code>debug.debug</code> are not lexically nested
11115within any function and so have no direct access to local variables.
11116
11117
11118
11119
11120<p>
11121<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
11122
11123
11124<p>
11125Returns the current hook settings of the thread, as three values:
11126the current hook function, the current hook mask,
11127and the current hook count,
11128as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function.
11129
11130
11131<p>
11132Returns <b>fail</b> if there is no active hook.
11133
11134
11135
11136
11137<p>
11138<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
11139
11140
11141<p>
11142Returns a table with information about a function.
11143You can give the function directly
11144or you can give a number as the value of <code>f</code>,
11145which means the function running at level <code>f</code> of the call stack
11146of the given thread:
11147level&nbsp;0 is the current function (<code>getinfo</code> itself);
11148level&nbsp;1 is the function that called <code>getinfo</code>
11149(except for tail calls, which do not count in the stack);
11150and so on.
11151If <code>f</code> is a number greater than the number of active functions,
11152then <code>getinfo</code> returns <b>fail</b>.
11153
11154
11155<p>
11156The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
11157with the string <code>what</code> describing which fields to fill in.
11158The default for <code>what</code> is to get all information available,
11159except the table of valid lines.
11160If present,
11161the option '<code>f</code>'
11162adds a field named <code>func</code> with the function itself.
11163If present,
11164the option '<code>L</code>'
11165adds a field named <code>activelines</code> with the table of
11166valid lines.
11167
11168
11169<p>
11170For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
11171a name for the current function,
11172if a reasonable name can be found,
11173and the expression <code>debug.getinfo(print)</code>
11174returns a table with all available information
11175about the <a href="#pdf-print"><code>print</code></a> function.
11176
11177
11178
11179
11180<p>
11181<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
11182
11183
11184<p>
11185This function returns the name and the value of the local variable
11186with index <code>local</code> of the function at level <code>f</code> of the stack.
11187This function accesses not only explicit local variables,
11188but also parameters and temporary values.
11189
11190
11191<p>
11192The first parameter or local variable has index&nbsp;1, and so on,
11193following the order that they are declared in the code,
11194counting only the variables that are active
11195in the current scope of the function.
11196Compile-time constants may not appear in this listing,
11197if they were optimized away by the compiler.
11198Negative indices refer to vararg arguments;
11199-1 is the first vararg argument.
11200The function returns <b>fail</b>
11201if there is no variable with the given index,
11202and raises an error when called with a level out of range.
11203(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
11204
11205
11206<p>
11207Variable names starting with '<code>(</code>' (open parenthesis)
11208represent variables with no known names
11209(internal variables such as loop control variables,
11210and variables from chunks saved without debug information).
11211
11212
11213<p>
11214The parameter <code>f</code> may also be a function.
11215In that case, <code>getlocal</code> returns only the name of function parameters.
11216
11217
11218
11219
11220<p>
11221<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
11222
11223
11224<p>
11225Returns the metatable of the given <code>value</code>
11226or <b>nil</b> if it does not have a metatable.
11227
11228
11229
11230
11231<p>
11232<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
11233
11234
11235<p>
11236Returns the registry table (see <a href="#4.3">&sect;4.3</a>).
11237
11238
11239
11240
11241<p>
11242<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
11243
11244
11245<p>
11246This function returns the name and the value of the upvalue
11247with index <code>up</code> of the function <code>f</code>.
11248The function returns <b>fail</b>
11249if there is no upvalue with the given index.
11250
11251
11252<p>
11253(For Lua functions,
11254upvalues are the external local variables that the function uses,
11255and that are consequently included in its closure.)
11256
11257
11258<p>
11259For C&nbsp;functions, this function uses the empty string <code>""</code>
11260as a name for all upvalues.
11261
11262
11263<p>
11264Variable name '<code>?</code>' (interrogation mark)
11265represents variables with no known names
11266(variables from chunks saved without debug information).
11267
11268
11269
11270
11271<p>
11272<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u, n)</code></a></h3>
11273
11274
11275<p>
11276Returns the <code>n</code>-th user value associated
11277to the userdata <code>u</code> plus a boolean,
11278<b>false</b> if the userdata does not have that value.
11279
11280
11281
11282
11283<p>
11284<hr><h3><a name="pdf-debug.setcstacklimit"><code>debug.setcstacklimit (limit)</code></a></h3>
11285
11286
11287<p>
11288Sets a new limit for the C stack.
11289This limit controls how deeply nested calls can go in Lua,
11290with the intent of avoiding a stack overflow.
11291A limit too small restricts recursive calls pointlessly;
11292a limit too large exposes the interpreter to stack-overflow crashes.
11293Unfortunately, there is no way to know a priori
11294the maximum safe limit for a platform.
11295
11296
11297<p>
11298Each call made from Lua code counts one unit.
11299Other operations (e.g., calls made from C to Lua or resuming a coroutine)
11300may have a higher cost.
11301
11302
11303<p>
11304This function has the following restrictions:
11305
11306<ul>
11307<li>It can only be called from the main coroutine (thread);</li>
11308<li>It cannot be called while handling a stack-overflow error;</li>
11309<li><code>limit</code> must be less than 40000;</li>
11310<li><code>limit</code> cannot be less than the amount of C stack in use.</li>
11311</ul><p>
11312If a call does not respect some restriction,
11313it returns a false value.
11314Otherwise,
11315the call returns the old limit.
11316
11317
11318
11319
11320<p>
11321<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
11322
11323
11324<p>
11325Sets the given function as the debug hook.
11326The string <code>mask</code> and the number <code>count</code> describe
11327when the hook will be called.
11328The string mask may have any combination of the following characters,
11329with the given meaning:
11330
11331<ul>
11332<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
11333<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
11334<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
11335</ul><p>
11336Moreover,
11337with a <code>count</code> different from zero,
11338the hook is called also after every <code>count</code> instructions.
11339
11340
11341<p>
11342When called without arguments,
11343<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
11344
11345
11346<p>
11347When the hook is called, its first parameter is a string
11348describing the event that has triggered its call:
11349<code>"call"</code>, <code>"tail call"</code>, <code>"return"</code>,
11350<code>"line"</code>, and <code>"count"</code>.
11351For line events,
11352the hook also gets the new line number as its second parameter.
11353Inside a hook,
11354you can call <code>getinfo</code> with level&nbsp;2 to get more information about
11355the running function.
11356(Level&nbsp;0 is the <code>getinfo</code> function,
11357and level&nbsp;1 is the hook function.)
11358
11359
11360
11361
11362<p>
11363<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
11364
11365
11366<p>
11367This function assigns the value <code>value</code> to the local variable
11368with index <code>local</code> of the function at level <code>level</code> of the stack.
11369The function returns <b>fail</b> if there is no local
11370variable with the given index,
11371and raises an error when called with a <code>level</code> out of range.
11372(You can call <code>getinfo</code> to check whether the level is valid.)
11373Otherwise, it returns the name of the local variable.
11374
11375
11376<p>
11377See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
11378variable indices and names.
11379
11380
11381
11382
11383<p>
11384<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
11385
11386
11387<p>
11388Sets the metatable for the given <code>value</code> to the given <code>table</code>
11389(which can be <b>nil</b>).
11390Returns <code>value</code>.
11391
11392
11393
11394
11395<p>
11396<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
11397
11398
11399<p>
11400This function assigns the value <code>value</code> to the upvalue
11401with index <code>up</code> of the function <code>f</code>.
11402The function returns <b>fail</b> if there is no upvalue
11403with the given index.
11404Otherwise, it returns the name of the upvalue.
11405
11406
11407<p>
11408See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
11409
11410
11411
11412
11413<p>
11414<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value, n)</code></a></h3>
11415
11416
11417<p>
11418Sets the given <code>value</code> as
11419the <code>n</code>-th user value associated to the given <code>udata</code>.
11420<code>udata</code> must be a full userdata.
11421
11422
11423<p>
11424Returns <code>udata</code>,
11425or <b>fail</b> if the userdata does not have that value.
11426
11427
11428
11429
11430<p>
11431<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
11432
11433
11434<p>
11435If <code>message</code> is present but is neither a string nor <b>nil</b>,
11436this function returns <code>message</code> without further processing.
11437Otherwise,
11438it returns a string with a traceback of the call stack.
11439The optional <code>message</code> string is appended
11440at the beginning of the traceback.
11441An optional <code>level</code> number tells at which level
11442to start the traceback
11443(default is 1, the function calling <code>traceback</code>).
11444
11445
11446
11447
11448<p>
11449<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
11450
11451
11452<p>
11453Returns a unique identifier (as a light userdata)
11454for the upvalue numbered <code>n</code>
11455from the given function.
11456
11457
11458<p>
11459These unique identifiers allow a program to check whether different
11460closures share upvalues.
11461Lua closures that share an upvalue
11462(that is, that access a same external local variable)
11463will return identical ids for those upvalue indices.
11464
11465
11466
11467
11468<p>
11469<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
11470
11471
11472<p>
11473Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
11474refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
11475
11476
11477
11478
11479
11480
11481
11482<h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
11483
11484<p>
11485Although Lua has been designed as an extension language,
11486to be embedded in a host C&nbsp;program,
11487it is also frequently used as a standalone language.
11488An interpreter for Lua as a standalone language,
11489called simply <code>lua</code>,
11490is provided with the standard distribution.
11491The standalone interpreter includes
11492all standard libraries.
11493Its usage is:
11494
11495<pre>
11496     lua [options] [script [args]]
11497</pre><p>
11498The options are:
11499
11500<ul>
11501<li><b><code>-e <em>stat</em></code>: </b> execute string <em>stat</em>;</li>
11502<li><b><code>-i</code>: </b> enter interactive mode after running <em>script</em>;</li>
11503<li><b><code>-l <em>mod</em></code>: </b> "require" <em>mod</em> and assign the
11504  result to global <em>mod</em>;</li>
11505<li><b><code>-v</code>: </b> print version information;</li>
11506<li><b><code>-E</code>: </b> ignore environment variables;</li>
11507<li><b><code>-W</code>: </b> turn warnings on;</li>
11508<li><b><code>--</code>: </b> stop handling options;</li>
11509<li><b><code>-</code>: </b> execute <code>stdin</code> as a file and stop handling options.</li>
11510</ul><p>
11511After handling its options, <code>lua</code> runs the given <em>script</em>.
11512When called without arguments,
11513<code>lua</code> behaves as <code>lua -v -i</code>
11514when the standard input (<code>stdin</code>) is a terminal,
11515and as <code>lua -</code> otherwise.
11516
11517
11518<p>
11519When called without the option <code>-E</code>,
11520the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_4"><code>LUA_INIT_5_4</code></a>
11521(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
11522before running any argument.
11523If the variable content has the format <code>@<em>filename</em></code>,
11524then <code>lua</code> executes the file.
11525Otherwise, <code>lua</code> executes the string itself.
11526
11527
11528<p>
11529When called with the option <code>-E</code>,
11530Lua does not consult any environment variables.
11531In particular,
11532the values of <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
11533are set with the default paths defined in <code>luaconf.h</code>.
11534
11535
11536<p>
11537The options <code>-e</code>, <code>-l</code>, and <code>-W</code> are handled in
11538the order they appear.
11539For instance, an invocation like
11540
11541<pre>
11542     $ lua -e 'a=1' -llib1 script.lua
11543</pre><p>
11544will first set <code>a</code> to 1, then require the library <code>lib1</code>,
11545and finally run the file <code>script.lua</code> with no arguments.
11546(Here <code>$</code> is the shell prompt. Your prompt may be different.)
11547
11548
11549<p>
11550Before running any code,
11551<code>lua</code> collects all command-line arguments
11552in a global table called <code>arg</code>.
11553The script name goes to index 0,
11554the first argument after the script name goes to index 1,
11555and so on.
11556Any arguments before the script name
11557(that is, the interpreter name plus its options)
11558go to negative indices.
11559For instance, in the call
11560
11561<pre>
11562     $ lua -la b.lua t1 t2
11563</pre><p>
11564the table is like this:
11565
11566<pre>
11567     arg = { [-2] = "lua", [-1] = "-la",
11568             [0] = "b.lua",
11569             [1] = "t1", [2] = "t2" }
11570</pre><p>
11571If there is no script in the call,
11572the interpreter name goes to index 0,
11573followed by the other arguments.
11574For instance, the call
11575
11576<pre>
11577     $ lua -e "print(arg[1])"
11578</pre><p>
11579will print "<code>-e</code>".
11580If there is a script,
11581the script is called with arguments
11582<code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
11583Like all chunks in Lua,
11584the script is compiled as a vararg function.
11585
11586
11587<p>
11588In interactive mode,
11589Lua repeatedly prompts and waits for a line.
11590After reading a line,
11591Lua first try to interpret the line as an expression.
11592If it succeeds, it prints its value.
11593Otherwise, it interprets the line as a statement.
11594If you write an incomplete statement,
11595the interpreter waits for its completion
11596by issuing a different prompt.
11597
11598
11599<p>
11600If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
11601then its value is used as the prompt.
11602Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
11603its value is used as the secondary prompt
11604(issued during incomplete statements).
11605
11606
11607<p>
11608In case of unprotected errors in the script,
11609the interpreter reports the error to the standard error stream.
11610If the error object is not a string but
11611has a metamethod <code>__tostring</code>,
11612the interpreter calls this metamethod to produce the final message.
11613Otherwise, the interpreter converts the error object to a string
11614and adds a stack traceback to it.
11615When warnings are on,
11616they are simply printed in the standard error output.
11617
11618
11619<p>
11620When finishing normally,
11621the interpreter closes its main Lua state
11622(see <a href="#lua_close"><code>lua_close</code></a>).
11623The script can avoid this step by
11624calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
11625
11626
11627<p>
11628To allow the use of Lua as a
11629script interpreter in Unix systems,
11630Lua skips the first line of a file chunk if it starts with <code>#</code>.
11631Therefore, Lua scripts can be made into executable programs
11632by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
11633as in
11634
11635<pre>
11636     #!/usr/local/bin/lua
11637</pre><p>
11638Of course,
11639the location of the Lua interpreter may be different in your machine.
11640If <code>lua</code> is in your <code>PATH</code>,
11641then
11642
11643<pre>
11644     #!/usr/bin/env lua
11645</pre><p>
11646is a more portable solution.
11647
11648
11649
11650<h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
11651
11652
11653
11654<p>
11655Here we list the incompatibilities that you may find when moving a program
11656from Lua&nbsp;5.3 to Lua&nbsp;5.4.
11657
11658
11659<p>
11660You can avoid some incompatibilities by compiling Lua with
11661appropriate options (see file <code>luaconf.h</code>).
11662However,
11663all these compatibility options will be removed in the future.
11664More often than not,
11665compatibility issues arise when these compatibility options
11666are removed.
11667So, whenever you have the chance,
11668you should try to test your code with a version of Lua compiled
11669with all compatibility options turned off.
11670That will ease transitions to newer versions of Lua.
11671
11672
11673<p>
11674Lua versions can always change the C API in ways that
11675do not imply source-code changes in a program,
11676such as the numeric values for constants
11677or the implementation of functions as macros.
11678Therefore,
11679you should never assume that binaries are compatible between
11680different Lua versions.
11681Always recompile clients of the Lua API when
11682using a new version.
11683
11684
11685<p>
11686Similarly, Lua versions can always change the internal representation
11687of precompiled chunks;
11688precompiled chunks are not compatible between different Lua versions.
11689
11690
11691<p>
11692The standard paths in the official distribution may
11693change between versions.
11694
11695
11696
11697
11698
11699<h2>8.1 &ndash; <a name="8.1">Incompatibilities in the Language</a></h2>
11700<ul>
11701
11702<li>
11703The coercion of strings to numbers in
11704arithmetic and bitwise operations
11705has been removed from the core language.
11706The string library does a similar job
11707for arithmetic (but not for bitwise) operations
11708using the string metamethods.
11709However, unlike in previous versions,
11710the new implementation preserves the implicit type of the numeral
11711in the string.
11712For instance, the result of <code>"1" + "2"</code> now is an integer,
11713not a float.
11714</li>
11715
11716<li>
11717Literal decimal integer constants that overflow are read as floats,
11718instead of wrapping around.
11719You can use hexadecimal notation for such constants if you
11720want the old behavior
11721(reading them as integers with wrap around).
11722</li>
11723
11724<li>
11725The use of the <code>__lt</code> metamethod to emulate <code>__le</code>
11726has been removed.
11727When needed, this metamethod must be explicitly defined.
11728</li>
11729
11730<li>
11731The semantics of the numerical <b>for</b> loop
11732over integers changed in some details.
11733In particular, the control variable never wraps around.
11734</li>
11735
11736<li>
11737A label for a <b>goto</b> cannot be declared where a label with the same
11738name is visible, even if this other label is declared in an enclosing
11739block.
11740</li>
11741
11742<li>
11743When finalizing an object,
11744Lua does not ignore <code>__gc</code> metamethods that are not functions.
11745Any value will be called, if present.
11746(Non-callable values will generate a warning,
11747like any other error when calling a finalizer.)
11748</li>
11749
11750</ul>
11751
11752
11753
11754
11755<h2>8.2 &ndash; <a name="8.2">Incompatibilities in the Libraries</a></h2>
11756<ul>
11757
11758<li>
11759The function <a href="#pdf-print"><code>print</code></a> does not call <a href="#pdf-tostring"><code>tostring</code></a>
11760to format its arguments;
11761instead, it has this functionality hardwired.
11762You should use <code>__tostring</code> to modify how values are printed.
11763</li>
11764
11765<li>
11766The pseudo-random number generator used by the function <a href="#pdf-math.random"><code>math.random</code></a>
11767now starts with a somewhat random seed.
11768Moreover, it uses a different algorithm.
11769</li>
11770
11771<li>
11772By default, the decoding functions in the <a href="#pdf-utf8"><code>utf8</code></a> library
11773do not accept surrogates as valid code points.
11774An extra parameter in these functions makes them more permissive.
11775</li>
11776
11777<li>
11778The options "<code>setpause</code>" and "<code>setstepmul</code>"
11779of the function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> are deprecated.
11780You should use the new option "<code>incremental</code>" to set them.
11781</li>
11782
11783<li>
11784The function <a href="#pdf-io.lines"><code>io.lines</code></a> now returns four values,
11785instead of just one.
11786That can be a problem when it is used as the sole
11787argument to another function that has optional parameters,
11788such as in <code>load(io.lines(filename, "L"))</code>.
11789To fix that issue,
11790you can wrap the call into parentheses,
11791to adjust its number of results to one.
11792</li>
11793
11794</ul>
11795
11796
11797
11798
11799<h2>8.3 &ndash; <a name="8.3">Incompatibilities in the API</a></h2>
11800
11801
11802<ul>
11803
11804<li>
11805Full userdata now has an arbitrary number of associated user values.
11806Therefore, the functions <code>lua_newuserdata</code>,
11807<code>lua_setuservalue</code>, and <code>lua_getuservalue</code> were
11808replaced by <a href="#lua_newuserdatauv"><code>lua_newuserdatauv</code></a>,
11809<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a>, and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>,
11810which have an extra argument.
11811
11812
11813<p>
11814For compatibility, the old names still work as macros assuming
11815one single user value.
11816Note, however, that userdata with zero user values
11817are more efficient memory-wise.
11818</li>
11819
11820<li>
11821The function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter.
11822This out parameter returns the number of values on
11823the top of the stack that were yielded or returned by the coroutine.
11824(In previous versions,
11825those values were the entire stack.)
11826</li>
11827
11828<li>
11829The function <a href="#lua_version"><code>lua_version</code></a> returns the version number,
11830instead of an address of the version number.
11831The Lua core should work correctly with libraries using their
11832own static copies of the same core,
11833so there is no need to check whether they are using the same
11834address space.
11835</li>
11836
11837<li>
11838The constant <code>LUA_ERRGCMM</code> was removed.
11839Errors in finalizers are never propagated;
11840instead, they generate a warning.
11841</li>
11842
11843<li>
11844The options <code>LUA_GCSETPAUSE</code> and <code>LUA_GCSETSTEPMUL</code>
11845of the function <a href="#lua_gc"><code>lua_gc</code></a> are deprecated.
11846You should use the new option <code>LUA_GCINC</code> to set them.
11847</li>
11848
11849</ul>
11850
11851
11852
11853
11854<h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
11855
11856<p>
11857Here is the complete syntax of Lua in extended BNF.
11858As usual in extended BNF,
11859{A} means 0 or more As,
11860and [A] means an optional A.
11861(For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
11862for a description of the terminals
11863Name, Numeral,
11864and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
11865
11866
11867
11868
11869<pre>
11870
11871	chunk ::= block
11872
11873	block ::= {stat} [retstat]
11874
11875	stat ::=  &lsquo;<b>;</b>&rsquo; |
11876		 varlist &lsquo;<b>=</b>&rsquo; explist |
11877		 functioncall |
11878		 label |
11879		 <b>break</b> |
11880		 <b>goto</b> Name |
11881		 <b>do</b> block <b>end</b> |
11882		 <b>while</b> exp <b>do</b> block <b>end</b> |
11883		 <b>repeat</b> block <b>until</b> exp |
11884		 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
11885		 <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> |
11886		 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
11887		 <b>function</b> funcname funcbody |
11888		 <b>local</b> <b>function</b> Name funcbody |
11889		 <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
11890
11891	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
11892
11893	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
11894
11895	retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
11896
11897	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
11898
11899	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
11900
11901	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
11902
11903	var ::=  Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
11904
11905	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
11906
11907	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
11908
11909	exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
11910		 prefixexp | tableconstructor | exp binop exp | unop exp
11911
11912	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
11913
11914	functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
11915
11916	args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
11917
11918	functiondef ::= <b>function</b> funcbody
11919
11920	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
11921
11922	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
11923
11924	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
11925
11926	fieldlist ::= field {fieldsep field} [fieldsep]
11927
11928	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
11929
11930	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
11931
11932	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; |
11933		 &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; |
11934		 &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; |
11935		 <b>and</b> | <b>or</b>
11936
11937	unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
11938
11939</pre>
11940
11941<p>
11942
11943
11944
11945
11946
11947
11948
11949<P CLASS="footer">
11950Last update:
11951Wed Sep 30 09:46:30 UTC 2020
11952</P>
11953<!--
11954Last change: revised for Lua 5.4.1
11955-->
11956
11957</body></html>
11958
11959