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>.
2969When you call any API function,
2970you must ensure the stack has enough room to accommodate the results.
2971
2972
2973<p>
2974There is one exception to the above rule:
2975When you call a Lua function
2976without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2977Lua ensures that the stack has enough space for all results.
2978However, it does not ensure any extra space.
2979So, before pushing anything on the stack after such a call
2980you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2981
2982
2983<p>
2984Whenever Lua calls C,
2985it ensures that the stack has space for
2986at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra elements;
2987that is, you can safely push up to <code>LUA_MINSTACK</code> values into it.
2988<code>LUA_MINSTACK</code> is defined as 20,
2989so that usually you do not have to worry about stack space
2990unless your code has loops pushing elements onto the stack.
2991Whenever necessary,
2992you can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2993to ensure that the stack has enough space for pushing new elements.
2994
2995
2996
2997
2998
2999<h3>4.1.2 &ndash; <a name="4.1.2">Valid and Acceptable Indices</a></h3>
3000
3001<p>
3002Any function in the API that receives stack indices
3003works only with <em>valid indices</em> or <em>acceptable indices</em>.
3004
3005
3006<p>
3007A <em>valid index</em> is an index that refers to a
3008position that stores a modifiable Lua value.
3009It comprises stack indices between&nbsp;1 and the stack top
3010(<code>1 &le; abs(index) &le; top</code>)
3011
3012plus <em>pseudo-indices</em>,
3013which represent some positions that are accessible to C&nbsp;code
3014but that are not in the stack.
3015Pseudo-indices are used to access the registry (see <a href="#4.3">&sect;4.3</a>)
3016and the upvalues of a C&nbsp;function (see <a href="#4.2">&sect;4.2</a>).
3017
3018
3019<p>
3020Functions that do not need a specific mutable position,
3021but only a value (e.g., query functions),
3022can be called with acceptable indices.
3023An <em>acceptable index</em> can be any valid index,
3024but it also can be any positive index after the stack top
3025within the space allocated for the stack,
3026that is, indices up to the stack size.
3027(Note that 0 is never an acceptable index.)
3028Indices to upvalues (see <a href="#4.2">&sect;4.2</a>) greater than the real number
3029of upvalues in the current C&nbsp;function are also acceptable (but invalid).
3030Except when noted otherwise,
3031functions in the API work with acceptable indices.
3032
3033
3034<p>
3035Acceptable indices serve to avoid extra tests
3036against the stack top when querying the stack.
3037For instance, a C&nbsp;function can query its third argument
3038without the need to check whether there is a third argument,
3039that is, without the need to check whether 3 is a valid index.
3040
3041
3042<p>
3043For functions that can be called with acceptable indices,
3044any non-valid index is treated as if it
3045contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
3046which behaves like a nil value.
3047
3048
3049
3050
3051
3052<h3>4.1.3 &ndash; <a name="4.1.3">Pointers to strings</a></h3>
3053
3054<p>
3055Several functions in the API return pointers (<code>const char*</code>)
3056to Lua strings in the stack.
3057(See <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3058<a href="#lua_pushstring"><code>lua_pushstring</code></a>, and <a href="#lua_tolstring"><code>lua_tolstring</code></a>.
3059See also <a href="#luaL_checklstring"><code>luaL_checklstring</code></a>, <a href="#luaL_checkstring"><code>luaL_checkstring</code></a>,
3060and <a href="#luaL_tolstring"><code>luaL_tolstring</code></a> in the auxiliary library.)
3061
3062
3063<p>
3064In general,
3065Lua's garbage collection can free or move internal memory
3066and then invalidate pointers to internal strings.
3067To allow a safe use of these pointers,
3068The API guarantees that any pointer to a string in a stack index
3069is valid while the string value at that index is not removed from the stack.
3070(It can be moved to another index, though.)
3071When the index is a pseudo-index (referring to an upvalue),
3072the pointer is valid while the corresponding call is active and
3073the corresponding upvalue is not modified.
3074
3075
3076<p>
3077Some functions in the debug interface
3078also return pointers to strings,
3079namely <a href="#lua_getlocal"><code>lua_getlocal</code></a>, <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
3080<a href="#lua_setlocal"><code>lua_setlocal</code></a>, and <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.
3081For these functions, the pointer is guaranteed to
3082be valid while the caller function is active and
3083the given closure (if one was given) is in the stack.
3084
3085
3086<p>
3087Except for these guarantees,
3088the garbage collector is free to invalidate
3089any pointer to internal strings.
3090
3091
3092
3093
3094
3095
3096
3097<h2>4.2 &ndash; <a name="4.2">C Closures</a></h2>
3098
3099<p>
3100When a C&nbsp;function is created,
3101it is possible to associate some values with it,
3102thus creating a <em>C&nbsp;closure</em>
3103(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
3104these values are called <em>upvalues</em> and are
3105accessible to the function whenever it is called.
3106
3107
3108<p>
3109Whenever a C&nbsp;function is called,
3110its upvalues are located at specific pseudo-indices.
3111These pseudo-indices are produced by the macro
3112<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
3113The first upvalue associated with a function is at index
3114<code>lua_upvalueindex(1)</code>, and so on.
3115Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
3116where <em>n</em> is greater than the number of upvalues of the
3117current function
3118(but not greater than 256,
3119which is one plus the maximum number of upvalues in a closure),
3120produces an acceptable but invalid index.
3121
3122
3123<p>
3124A C&nbsp;closure can also change the values
3125of its corresponding upvalues.
3126
3127
3128
3129
3130
3131<h2>4.3 &ndash; <a name="4.3">Registry</a></h2>
3132
3133<p>
3134Lua provides a <em>registry</em>,
3135a predefined table that can be used by any C&nbsp;code to
3136store whatever Lua values it needs to store.
3137The registry table is always accessible at pseudo-index
3138<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
3139Any C&nbsp;library can store data into this table,
3140but it must take care to choose keys
3141that are different from those used
3142by other libraries, to avoid collisions.
3143Typically, you should use as key a string containing your library name,
3144or a light userdata with the address of a C&nbsp;object in your code,
3145or any Lua object created by your code.
3146As with variable names,
3147string keys starting with an underscore followed by
3148uppercase letters are reserved for Lua.
3149
3150
3151<p>
3152The integer keys in the registry are used
3153by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
3154and by some predefined values.
3155Therefore, integer keys in the registry
3156must not be used for other purposes.
3157
3158
3159<p>
3160When you create a new Lua state,
3161its registry comes with some predefined values.
3162These predefined values are indexed with integer keys
3163defined as constants in <code>lua.h</code>.
3164The following constants are defined:
3165
3166<ul>
3167<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
3168the main thread of the state.
3169(The main thread is the one created together with the state.)
3170</li>
3171
3172<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
3173the global environment.
3174</li>
3175</ul>
3176
3177
3178
3179
3180<h2>4.4 &ndash; <a name="4.4">Error Handling in C</a></h2>
3181
3182
3183
3184<p>
3185Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
3186(Lua will use exceptions if you compile it as C++;
3187search for <code>LUAI_THROW</code> in the source code for details.)
3188When Lua faces any error,
3189such as a memory allocation error or a type error,
3190it <em>raises</em> an error;
3191that is, it does a long jump.
3192A <em>protected environment</em> uses <code>setjmp</code>
3193to set a recovery point;
3194any error jumps to the most recent active recovery point.
3195
3196
3197<p>
3198Inside a C&nbsp;function you can raise an error explicitly
3199by calling <a href="#lua_error"><code>lua_error</code></a>.
3200
3201
3202<p>
3203Most functions in the API can raise an error,
3204for instance due to a memory allocation error.
3205The documentation for each function indicates whether
3206it can raise errors.
3207
3208
3209<p>
3210If an error happens outside any protected environment,
3211Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
3212and then calls <code>abort</code>,
3213thus exiting the host application.
3214Your panic function can avoid this exit by
3215never returning
3216(e.g., doing a long jump to your own recovery point outside Lua).
3217
3218
3219<p>
3220The panic function,
3221as its name implies,
3222is a mechanism of last resort.
3223Programs should avoid it.
3224As a general rule,
3225when a C&nbsp;function is called by Lua with a Lua state,
3226it can do whatever it wants on that Lua state,
3227as it should be already protected.
3228However,
3229when C code operates on other Lua states
3230(e.g., a Lua-state argument to the function,
3231a Lua state stored in the registry, or
3232the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
3233it should use them only in API calls that cannot raise errors.
3234
3235
3236<p>
3237The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
3238in particular, the error object is on the top of the stack.
3239However, there is no guarantee about stack space.
3240To push anything on the stack,
3241the panic function must first check the available space (see <a href="#4.1.1">&sect;4.1.1</a>).
3242
3243
3244
3245
3246
3247<h3>4.4.1 &ndash; <a name="4.4.1">Status Codes</a></h3>
3248
3249<p>
3250Several functions that report errors in the API use the following
3251status codes to indicate different kinds of errors or other conditions:
3252
3253<ul>
3254
3255<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> no errors.</li>
3256
3257<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> a runtime error.</li>
3258
3259<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3260memory allocation error.
3261For such errors, Lua does not call the message handler.
3262</li>
3263
3264<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> error while running the message handler.</li>
3265
3266<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> syntax error during precompilation.</li>
3267
3268<li><b><a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a>: </b> the thread (coroutine) yields.</li>
3269
3270<li><b><a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>: </b> a file-related error;
3271e.g., it cannot open or read the file.</li>
3272
3273</ul><p>
3274These constants are defined in the header file <code>lua.h</code>.
3275
3276
3277
3278
3279
3280
3281
3282<h2>4.5 &ndash; <a name="4.5">Handling Yields in C</a></h2>
3283
3284<p>
3285Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
3286Therefore, if a C&nbsp;function <code>foo</code> calls an API function
3287and this API function yields
3288(directly or indirectly by calling another function that yields),
3289Lua cannot return to <code>foo</code> any more,
3290because the <code>longjmp</code> removes its frame from the C&nbsp;stack.
3291
3292
3293<p>
3294To avoid this kind of problem,
3295Lua raises an error whenever it tries to yield across an API call,
3296except for three functions:
3297<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>.
3298All those functions receive a <em>continuation function</em>
3299(as a parameter named <code>k</code>) to continue execution after a yield.
3300
3301
3302<p>
3303We need to set some terminology to explain continuations.
3304We have a C&nbsp;function called from Lua which we will call
3305the <em>original function</em>.
3306This original function then calls one of those three functions in the C API,
3307which we will call the <em>callee function</em>,
3308that then yields the current thread.
3309This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
3310or 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>
3311and the function called by them yields.
3312
3313
3314<p>
3315Suppose the running thread yields while executing the callee function.
3316After the thread resumes,
3317it eventually will finish running the callee function.
3318However,
3319the callee function cannot return to the original function,
3320because its frame in the C&nbsp;stack was destroyed by the yield.
3321Instead, Lua calls a <em>continuation function</em>,
3322which was given as an argument to the callee function.
3323As the name implies,
3324the continuation function should continue the task
3325of the original function.
3326
3327
3328<p>
3329As an illustration, consider the following function:
3330
3331<pre>
3332     int original_function (lua_State *L) {
3333       ...     /* code 1 */
3334       status = lua_pcall(L, n, m, h);  /* calls Lua */
3335       ...     /* code 2 */
3336     }
3337</pre><p>
3338Now we want to allow
3339the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
3340First, we can rewrite our function like here:
3341
3342<pre>
3343     int k (lua_State *L, int status, lua_KContext ctx) {
3344       ...  /* code 2 */
3345     }
3346     
3347     int original_function (lua_State *L) {
3348       ...     /* code 1 */
3349       return k(L, lua_pcall(L, n, m, h), ctx);
3350     }
3351</pre><p>
3352In the above code,
3353the new function <code>k</code> is a
3354<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
3355which should do all the work that the original function
3356was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
3357Now, we must inform Lua that it must call <code>k</code> if the Lua code
3358being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
3359(errors or yielding),
3360so we rewrite the code as here,
3361replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
3362
3363<pre>
3364     int original_function (lua_State *L) {
3365       ...     /* code 1 */
3366       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
3367     }
3368</pre><p>
3369Note the external, explicit call to the continuation:
3370Lua will call the continuation only if needed, that is,
3371in case of errors or resuming after a yield.
3372If the called function returns normally without ever yielding,
3373<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
3374(Of course, instead of calling the continuation in that case,
3375you can do the equivalent work directly inside the original function.)
3376
3377
3378<p>
3379Besides the Lua state,
3380the continuation function has two other parameters:
3381the final status of the call and the context value (<code>ctx</code>) that
3382was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3383Lua does not use this context value;
3384it only passes this value from the original function to the
3385continuation function.
3386For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3387the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3388except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
3389(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
3390For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
3391the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
3392(For these two functions,
3393Lua will not call the continuation in case of errors,
3394because they do not handle errors.)
3395Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
3396you should call the continuation function
3397with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
3398(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
3399directly the continuation function,
3400because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
3401
3402
3403<p>
3404Lua treats the continuation function as if it were the original function.
3405The continuation function receives the same Lua stack
3406from the original function,
3407in the same state it would be if the callee function had returned.
3408(For instance,
3409after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
3410removed from the stack and replaced by the results from the call.)
3411It also has the same upvalues.
3412Whatever it returns is handled by Lua as if it were the return
3413of the original function.
3414
3415
3416
3417
3418
3419<h2>4.6 &ndash; <a name="4.6">Functions and Types</a></h2>
3420
3421<p>
3422Here we list all functions and types from the C&nbsp;API in
3423alphabetical order.
3424Each function has an indicator like this:
3425<span class="apii">[-o, +p, <em>x</em>]</span>
3426
3427
3428<p>
3429The first field, <code>o</code>,
3430is how many elements the function pops from the stack.
3431The second field, <code>p</code>,
3432is how many elements the function pushes onto the stack.
3433(Any function always pushes its results after popping its arguments.)
3434A field in the form <code>x|y</code> means the function can push (or pop)
3435<code>x</code> or <code>y</code> elements,
3436depending on the situation;
3437an interrogation mark '<code>?</code>' means that
3438we cannot know how many elements the function pops/pushes
3439by looking only at its arguments.
3440(For instance, they may depend on what is in the stack.)
3441The third field, <code>x</code>,
3442tells whether the function may raise errors:
3443'<code>-</code>' means the function never raises any error;
3444'<code>m</code>' means the function may raise only out-of-memory errors;
3445'<code>v</code>' means the function may raise the errors explained in the text;
3446'<code>e</code>' means the function can run arbitrary Lua code,
3447either directly or through metamethods,
3448and therefore may raise any errors.
3449
3450
3451
3452<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
3453<span class="apii">[-0, +0, &ndash;]</span>
3454<pre>int lua_absindex (lua_State *L, int idx);</pre>
3455
3456<p>
3457Converts the acceptable index <code>idx</code>
3458into an equivalent absolute index
3459(that is, one that does not depend on the stack size).
3460
3461
3462
3463
3464
3465<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
3466<pre>typedef void * (*lua_Alloc) (void *ud,
3467                             void *ptr,
3468                             size_t osize,
3469                             size_t nsize);</pre>
3470
3471<p>
3472The type of the memory-allocation function used by Lua states.
3473The allocator function must provide a
3474functionality similar to <code>realloc</code>,
3475but not exactly the same.
3476Its arguments are
3477<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3478<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3479<code>osize</code>, the original size of the block or some code about what
3480is being allocated;
3481and <code>nsize</code>, the new size of the block.
3482
3483
3484<p>
3485When <code>ptr</code> is not <code>NULL</code>,
3486<code>osize</code> is the size of the block pointed by <code>ptr</code>,
3487that is, the size given when it was allocated or reallocated.
3488
3489
3490<p>
3491When <code>ptr</code> is <code>NULL</code>,
3492<code>osize</code> encodes the kind of object that Lua is allocating.
3493<code>osize</code> is any of
3494<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>,
3495<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)
3496Lua is creating a new object of that type.
3497When <code>osize</code> is some other value,
3498Lua is allocating memory for something else.
3499
3500
3501<p>
3502Lua assumes the following behavior from the allocator function:
3503
3504
3505<p>
3506When <code>nsize</code> is zero,
3507the allocator must behave like <code>free</code>
3508and then return <code>NULL</code>.
3509
3510
3511<p>
3512When <code>nsize</code> is not zero,
3513the allocator must behave like <code>realloc</code>.
3514In particular, the allocator returns <code>NULL</code>
3515if and only if it cannot fulfill the request.
3516
3517
3518<p>
3519Here is a simple implementation for the allocator function.
3520It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3521
3522<pre>
3523     static void *l_alloc (void *ud, void *ptr, size_t osize,
3524                                                size_t nsize) {
3525       (void)ud;  (void)osize;  /* not used */
3526       if (nsize == 0) {
3527         free(ptr);
3528         return NULL;
3529       }
3530       else
3531         return realloc(ptr, nsize);
3532     }
3533</pre><p>
3534Note that Standard&nbsp;C ensures
3535that <code>free(NULL)</code> has no effect and that
3536<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3537
3538
3539
3540
3541
3542<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3543<span class="apii">[-(2|1), +1, <em>e</em>]</span>
3544<pre>void lua_arith (lua_State *L, int op);</pre>
3545
3546<p>
3547Performs an arithmetic or bitwise operation over the two values
3548(or one, in the case of negations)
3549at the top of the stack,
3550with the value on the top being the second operand,
3551pops these values, and pushes the result of the operation.
3552The function follows the semantics of the corresponding Lua operator
3553(that is, it may call metamethods).
3554
3555
3556<p>
3557The value of <code>op</code> must be one of the following constants:
3558
3559<ul>
3560
3561<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3562<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3563<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3564<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3565<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3566<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3567<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3568<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3569<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
3570<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li>
3571<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
3572<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
3573<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3574<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3575
3576</ul>
3577
3578
3579
3580
3581<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3582<span class="apii">[-0, +0, &ndash;]</span>
3583<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3584
3585<p>
3586Sets a new panic function and returns the old one (see <a href="#4.4">&sect;4.4</a>).
3587
3588
3589
3590
3591
3592<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3593<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3594<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3595
3596<p>
3597Calls a function.
3598Like regular Lua calls,
3599<code>lua_call</code> respects the <code>__call</code> metamethod.
3600So, here the word "function"
3601means any callable value.
3602
3603
3604<p>
3605To do a call you must use the following protocol:
3606first, the function to be called is pushed onto the stack;
3607then, the arguments to the call are pushed
3608in direct order;
3609that is, the first argument is pushed first.
3610Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3611<code>nargs</code> is the number of arguments that you pushed onto the stack.
3612When the function returns,
3613all arguments and the function value are popped
3614and the call results are pushed onto the stack.
3615The number of results is adjusted to <code>nresults</code>,
3616unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3617In this case, all results from the function are pushed;
3618Lua takes care that the returned values fit into the stack space,
3619but it does not ensure any extra space in the stack.
3620The function results are pushed onto the stack in direct order
3621(the first result is pushed first),
3622so that after the call the last result is on the top of the stack.
3623
3624
3625<p>
3626Any error while calling and running the function is propagated upwards
3627(with a <code>longjmp</code>).
3628
3629
3630<p>
3631The following example shows how the host program can do the
3632equivalent to this Lua code:
3633
3634<pre>
3635     a = f("how", t.x, 14)
3636</pre><p>
3637Here it is in&nbsp;C:
3638
3639<pre>
3640     lua_getglobal(L, "f");                  /* function to be called */
3641     lua_pushliteral(L, "how");                       /* 1st argument */
3642     lua_getglobal(L, "t");                    /* table to be indexed */
3643     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
3644     lua_remove(L, -2);                  /* remove 't' from the stack */
3645     lua_pushinteger(L, 14);                          /* 3rd argument */
3646     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
3647     lua_setglobal(L, "a");                         /* set global 'a' */
3648</pre><p>
3649Note that the code above is <em>balanced</em>:
3650at its end, the stack is back to its original configuration.
3651This is considered good programming practice.
3652
3653
3654
3655
3656
3657<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3658<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3659<pre>void lua_callk (lua_State *L,
3660                int nargs,
3661                int nresults,
3662                lua_KContext ctx,
3663                lua_KFunction k);</pre>
3664
3665<p>
3666This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3667but allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
3668
3669
3670
3671
3672
3673<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3674<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3675
3676<p>
3677Type for C&nbsp;functions.
3678
3679
3680<p>
3681In order to communicate properly with Lua,
3682a C&nbsp;function must use the following protocol,
3683which defines the way parameters and results are passed:
3684a C&nbsp;function receives its arguments from Lua in its stack
3685in direct order (the first argument is pushed first).
3686So, when the function starts,
3687<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3688The first argument (if any) is at index 1
3689and its last argument is at index <code>lua_gettop(L)</code>.
3690To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3691in direct order (the first result is pushed first),
3692and returns in C the number of results.
3693Any other value in the stack below the results will be properly
3694discarded by Lua.
3695Like a Lua function, a C&nbsp;function called by Lua can also return
3696many results.
3697
3698
3699<p>
3700As an example, the following function receives a variable number
3701of numeric arguments and returns their average and their sum:
3702
3703<pre>
3704     static int foo (lua_State *L) {
3705       int n = lua_gettop(L);    /* number of arguments */
3706       lua_Number sum = 0.0;
3707       int i;
3708       for (i = 1; i &lt;= n; i++) {
3709         if (!lua_isnumber(L, i)) {
3710           lua_pushliteral(L, "incorrect argument");
3711           lua_error(L);
3712         }
3713         sum += lua_tonumber(L, i);
3714       }
3715       lua_pushnumber(L, sum/n);        /* first result */
3716       lua_pushnumber(L, sum);         /* second result */
3717       return 2;                   /* number of results */
3718     }
3719</pre>
3720
3721
3722
3723
3724<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3725<span class="apii">[-0, +0, &ndash;]</span>
3726<pre>int lua_checkstack (lua_State *L, int n);</pre>
3727
3728<p>
3729Ensures that the stack has space for at least <code>n</code> extra elements,
3730that is, that you can safely push up to <code>n</code> values into it.
3731It returns false if it cannot fulfill the request,
3732either because it would cause the stack
3733to be greater than a fixed maximum size
3734(typically at least several thousand elements) or
3735because it cannot allocate memory for the extra space.
3736This function never shrinks the stack;
3737if the stack already has space for the extra elements,
3738it is left unchanged.
3739
3740
3741
3742
3743
3744<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3745<span class="apii">[-0, +0, &ndash;]</span>
3746<pre>void lua_close (lua_State *L);</pre>
3747
3748<p>
3749Close all active to-be-closed variables in the main thread,
3750release all objects in the given Lua state
3751(calling the corresponding garbage-collection metamethods, if any),
3752and frees all dynamic memory used by this state.
3753
3754
3755<p>
3756On several platforms, you may not need to call this function,
3757because all resources are naturally released when the host program ends.
3758On the other hand, long-running programs that create multiple states,
3759such as daemons or web servers,
3760will probably need to close states as soon as they are not needed.
3761
3762
3763
3764
3765
3766<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3767<span class="apii">[-0, +0, <em>e</em>]</span>
3768<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3769
3770<p>
3771Compares two Lua values.
3772Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3773when compared with the value at index <code>index2</code>,
3774following the semantics of the corresponding Lua operator
3775(that is, it may call metamethods).
3776Otherwise returns&nbsp;0.
3777Also returns&nbsp;0 if any of the indices is not valid.
3778
3779
3780<p>
3781The value of <code>op</code> must be one of the following constants:
3782
3783<ul>
3784
3785<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3786<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3787<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3788
3789</ul>
3790
3791
3792
3793
3794<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3795<span class="apii">[-n, +1, <em>e</em>]</span>
3796<pre>void lua_concat (lua_State *L, int n);</pre>
3797
3798<p>
3799Concatenates the <code>n</code> values at the top of the stack,
3800pops them, and leaves the result on the top.
3801If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3802(that is, the function does nothing);
3803if <code>n</code> is 0, the result is the empty string.
3804Concatenation is performed following the usual semantics of Lua
3805(see <a href="#3.4.6">&sect;3.4.6</a>).
3806
3807
3808
3809
3810
3811<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3812<span class="apii">[-0, +0, &ndash;]</span>
3813<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3814
3815<p>
3816Copies the element at index <code>fromidx</code>
3817into the valid index <code>toidx</code>,
3818replacing the value at that position.
3819Values at other positions are not affected.
3820
3821
3822
3823
3824
3825<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3826<span class="apii">[-0, +1, <em>m</em>]</span>
3827<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3828
3829<p>
3830Creates a new empty table and pushes it onto the stack.
3831Parameter <code>narr</code> is a hint for how many elements the table
3832will have as a sequence;
3833parameter <code>nrec</code> is a hint for how many other elements
3834the table will have.
3835Lua may use these hints to preallocate memory for the new table.
3836This preallocation may help performance when you know in advance
3837how many elements the table will have.
3838Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3839
3840
3841
3842
3843
3844<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3845<span class="apii">[-0, +0, &ndash;]</span>
3846<pre>int lua_dump (lua_State *L,
3847                        lua_Writer writer,
3848                        void *data,
3849                        int strip);</pre>
3850
3851<p>
3852Dumps a function as a binary chunk.
3853Receives a Lua function on the top of the stack
3854and produces a binary chunk that,
3855if loaded again,
3856results in a function equivalent to the one dumped.
3857As it produces parts of the chunk,
3858<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3859with the given <code>data</code>
3860to write them.
3861
3862
3863<p>
3864If <code>strip</code> is true,
3865the binary representation may not include all debug information
3866about the function,
3867to save space.
3868
3869
3870<p>
3871The value returned is the error code returned by the last
3872call to the writer;
38730&nbsp;means no errors.
3874
3875
3876<p>
3877This function does not pop the Lua function from the stack.
3878
3879
3880
3881
3882
3883<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3884<span class="apii">[-1, +0, <em>v</em>]</span>
3885<pre>int lua_error (lua_State *L);</pre>
3886
3887<p>
3888Raises a Lua error,
3889using the value on the top of the stack as the error object.
3890This function does a long jump,
3891and therefore never returns
3892(see <a href="#luaL_error"><code>luaL_error</code></a>).
3893
3894
3895
3896
3897
3898<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3899<span class="apii">[-0, +0, &ndash;]</span>
3900<pre>int lua_gc (lua_State *L, int what, ...);</pre>
3901
3902<p>
3903Controls the garbage collector.
3904
3905
3906<p>
3907This function performs several tasks,
3908according to the value of the parameter <code>what</code>.
3909For options that need extra arguments,
3910they are listed after the option.
3911
3912<ul>
3913
3914<li><b><code>LUA_GCCOLLECT</code>: </b>
3915Performs a full garbage-collection cycle.
3916</li>
3917
3918<li><b><code>LUA_GCSTOP</code>: </b>
3919Stops the garbage collector.
3920</li>
3921
3922<li><b><code>LUA_GCRESTART</code>: </b>
3923Restarts the garbage collector.
3924</li>
3925
3926<li><b><code>LUA_GCCOUNT</code>: </b>
3927Returns the current amount of memory (in Kbytes) in use by Lua.
3928</li>
3929
3930<li><b><code>LUA_GCCOUNTB</code>: </b>
3931Returns the remainder of dividing the current amount of bytes of
3932memory in use by Lua by 1024.
3933</li>
3934
3935<li><b><code>LUA_GCSTEP</code> <code>(int stepsize)</code>: </b>
3936Performs an incremental step of garbage collection,
3937corresponding to the allocation of <code>stepsize</code> Kbytes.
3938</li>
3939
3940<li><b><code>LUA_GCISRUNNING</code>: </b>
3941Returns a boolean that tells whether the collector is running
3942(i.e., not stopped).
3943</li>
3944
3945<li><b><code>LUA_GCINC</code> (int pause, int stepmul, stepsize): </b>
3946Changes the collector to incremental mode
3947with the given parameters (see <a href="#2.5.1">&sect;2.5.1</a>).
3948Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3949</li>
3950
3951<li><b><code>LUA_GCGEN</code> (int minormul, int majormul): </b>
3952Changes the collector to generational mode
3953with the given parameters (see <a href="#2.5.2">&sect;2.5.2</a>).
3954Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3955</li>
3956
3957</ul><p>
3958For more details about these options,
3959see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3960
3961
3962
3963
3964
3965<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3966<span class="apii">[-0, +0, &ndash;]</span>
3967<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3968
3969<p>
3970Returns the memory-allocation function of a given state.
3971If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3972opaque pointer given when the memory-allocator function was set.
3973
3974
3975
3976
3977
3978<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3979<span class="apii">[-0, +1, <em>e</em>]</span>
3980<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
3981
3982<p>
3983Pushes onto the stack the value <code>t[k]</code>,
3984where <code>t</code> is the value at the given index.
3985As in Lua, this function may trigger a metamethod
3986for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3987
3988
3989<p>
3990Returns the type of the pushed value.
3991
3992
3993
3994
3995
3996<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
3997<span class="apii">[-0, +0, &ndash;]</span>
3998<pre>void *lua_getextraspace (lua_State *L);</pre>
3999
4000<p>
4001Returns a pointer to a raw memory area associated with the
4002given Lua state.
4003The application can use this area for any purpose;
4004Lua does not use it for anything.
4005
4006
4007<p>
4008Each new thread has this area initialized with a copy
4009of the area of the main thread.
4010
4011
4012<p>
4013By default, this area has the size of a pointer to void,
4014but you can recompile Lua with a different size for this area.
4015(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
4016
4017
4018
4019
4020
4021<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
4022<span class="apii">[-0, +1, <em>e</em>]</span>
4023<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
4024
4025<p>
4026Pushes onto the stack the value of the global <code>name</code>.
4027Returns the type of that value.
4028
4029
4030
4031
4032
4033<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
4034<span class="apii">[-0, +1, <em>e</em>]</span>
4035<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
4036
4037<p>
4038Pushes onto the stack the value <code>t[i]</code>,
4039where <code>t</code> is the value at the given index.
4040As in Lua, this function may trigger a metamethod
4041for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4042
4043
4044<p>
4045Returns the type of the pushed value.
4046
4047
4048
4049
4050
4051<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
4052<span class="apii">[-0, +(0|1), &ndash;]</span>
4053<pre>int lua_getmetatable (lua_State *L, int index);</pre>
4054
4055<p>
4056If the value at the given index has a metatable,
4057the function pushes that metatable onto the stack and returns&nbsp;1.
4058Otherwise,
4059the function returns&nbsp;0 and pushes nothing on the stack.
4060
4061
4062
4063
4064
4065<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
4066<span class="apii">[-1, +1, <em>e</em>]</span>
4067<pre>int lua_gettable (lua_State *L, int index);</pre>
4068
4069<p>
4070Pushes onto the stack the value <code>t[k]</code>,
4071where <code>t</code> is the value at the given index
4072and <code>k</code> is the value on the top of the stack.
4073
4074
4075<p>
4076This function pops the key from the stack,
4077pushing the resulting value in its place.
4078As in Lua, this function may trigger a metamethod
4079for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4080
4081
4082<p>
4083Returns the type of the pushed value.
4084
4085
4086
4087
4088
4089<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
4090<span class="apii">[-0, +0, &ndash;]</span>
4091<pre>int lua_gettop (lua_State *L);</pre>
4092
4093<p>
4094Returns the index of the top element in the stack.
4095Because indices start at&nbsp;1,
4096this result is equal to the number of elements in the stack;
4097in particular, 0&nbsp;means an empty stack.
4098
4099
4100
4101
4102
4103<hr><h3><a name="lua_getiuservalue"><code>lua_getiuservalue</code></a></h3><p>
4104<span class="apii">[-0, +1, &ndash;]</span>
4105<pre>int lua_getiuservalue (lua_State *L, int index, int n);</pre>
4106
4107<p>
4108Pushes onto the stack the <code>n</code>-th user value associated with the
4109full userdata at the given index and
4110returns the type of the pushed value.
4111
4112
4113<p>
4114If the userdata does not have that value,
4115pushes <b>nil</b> and returns <a href="#pdf-LUA_TNONE"><code>LUA_TNONE</code></a>.
4116
4117
4118
4119
4120
4121<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
4122<span class="apii">[-1, +1, &ndash;]</span>
4123<pre>void lua_insert (lua_State *L, int index);</pre>
4124
4125<p>
4126Moves the top element into the given valid index,
4127shifting up the elements above this index to open space.
4128This function cannot be called with a pseudo-index,
4129because a pseudo-index is not an actual stack position.
4130
4131
4132
4133
4134
4135<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
4136<pre>typedef ... lua_Integer;</pre>
4137
4138<p>
4139The type of integers in Lua.
4140
4141
4142<p>
4143By default this type is <code>long long</code>,
4144(usually a 64-bit two-complement integer),
4145but that can be changed to <code>long</code> or <code>int</code>
4146(usually a 32-bit two-complement integer).
4147(See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
4148
4149
4150<p>
4151Lua also defines the constants
4152<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
4153with the minimum and the maximum values that fit in this type.
4154
4155
4156
4157
4158
4159<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
4160<span class="apii">[-0, +0, &ndash;]</span>
4161<pre>int lua_isboolean (lua_State *L, int index);</pre>
4162
4163<p>
4164Returns 1 if the value at the given index is a boolean,
4165and 0&nbsp;otherwise.
4166
4167
4168
4169
4170
4171<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
4172<span class="apii">[-0, +0, &ndash;]</span>
4173<pre>int lua_iscfunction (lua_State *L, int index);</pre>
4174
4175<p>
4176Returns 1 if the value at the given index is a C&nbsp;function,
4177and 0&nbsp;otherwise.
4178
4179
4180
4181
4182
4183<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
4184<span class="apii">[-0, +0, &ndash;]</span>
4185<pre>int lua_isfunction (lua_State *L, int index);</pre>
4186
4187<p>
4188Returns 1 if the value at the given index is a function
4189(either C or Lua), and 0&nbsp;otherwise.
4190
4191
4192
4193
4194
4195<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
4196<span class="apii">[-0, +0, &ndash;]</span>
4197<pre>int lua_isinteger (lua_State *L, int index);</pre>
4198
4199<p>
4200Returns 1 if the value at the given index is an integer
4201(that is, the value is a number and is represented as an integer),
4202and 0&nbsp;otherwise.
4203
4204
4205
4206
4207
4208<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
4209<span class="apii">[-0, +0, &ndash;]</span>
4210<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
4211
4212<p>
4213Returns 1 if the value at the given index is a light userdata,
4214and 0&nbsp;otherwise.
4215
4216
4217
4218
4219
4220<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
4221<span class="apii">[-0, +0, &ndash;]</span>
4222<pre>int lua_isnil (lua_State *L, int index);</pre>
4223
4224<p>
4225Returns 1 if the value at the given index is <b>nil</b>,
4226and 0&nbsp;otherwise.
4227
4228
4229
4230
4231
4232<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
4233<span class="apii">[-0, +0, &ndash;]</span>
4234<pre>int lua_isnone (lua_State *L, int index);</pre>
4235
4236<p>
4237Returns 1 if the given index is not valid,
4238and 0&nbsp;otherwise.
4239
4240
4241
4242
4243
4244<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
4245<span class="apii">[-0, +0, &ndash;]</span>
4246<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
4247
4248<p>
4249Returns 1 if the given index is not valid
4250or if the value at this index is <b>nil</b>,
4251and 0&nbsp;otherwise.
4252
4253
4254
4255
4256
4257<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
4258<span class="apii">[-0, +0, &ndash;]</span>
4259<pre>int lua_isnumber (lua_State *L, int index);</pre>
4260
4261<p>
4262Returns 1 if the value at the given index is a number
4263or a string convertible to a number,
4264and 0&nbsp;otherwise.
4265
4266
4267
4268
4269
4270<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
4271<span class="apii">[-0, +0, &ndash;]</span>
4272<pre>int lua_isstring (lua_State *L, int index);</pre>
4273
4274<p>
4275Returns 1 if the value at the given index is a string
4276or a number (which is always convertible to a string),
4277and 0&nbsp;otherwise.
4278
4279
4280
4281
4282
4283<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
4284<span class="apii">[-0, +0, &ndash;]</span>
4285<pre>int lua_istable (lua_State *L, int index);</pre>
4286
4287<p>
4288Returns 1 if the value at the given index is a table,
4289and 0&nbsp;otherwise.
4290
4291
4292
4293
4294
4295<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
4296<span class="apii">[-0, +0, &ndash;]</span>
4297<pre>int lua_isthread (lua_State *L, int index);</pre>
4298
4299<p>
4300Returns 1 if the value at the given index is a thread,
4301and 0&nbsp;otherwise.
4302
4303
4304
4305
4306
4307<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
4308<span class="apii">[-0, +0, &ndash;]</span>
4309<pre>int lua_isuserdata (lua_State *L, int index);</pre>
4310
4311<p>
4312Returns 1 if the value at the given index is a userdata
4313(either full or light), and 0&nbsp;otherwise.
4314
4315
4316
4317
4318
4319<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
4320<span class="apii">[-0, +0, &ndash;]</span>
4321<pre>int lua_isyieldable (lua_State *L);</pre>
4322
4323<p>
4324Returns 1 if the given coroutine can yield,
4325and 0&nbsp;otherwise.
4326
4327
4328
4329
4330
4331<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
4332<pre>typedef ... lua_KContext;</pre>
4333
4334<p>
4335The type for continuation-function contexts.
4336It must be a numeric type.
4337This type is defined as <code>intptr_t</code>
4338when <code>intptr_t</code> is available,
4339so that it can store pointers too.
4340Otherwise, it is defined as <code>ptrdiff_t</code>.
4341
4342
4343
4344
4345
4346<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
4347<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
4348
4349<p>
4350Type for continuation functions (see <a href="#4.5">&sect;4.5</a>).
4351
4352
4353
4354
4355
4356<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
4357<span class="apii">[-0, +1, <em>e</em>]</span>
4358<pre>void lua_len (lua_State *L, int index);</pre>
4359
4360<p>
4361Returns the length of the value at the given index.
4362It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
4363may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
4364The result is pushed on the stack.
4365
4366
4367
4368
4369
4370<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
4371<span class="apii">[-0, +1, &ndash;]</span>
4372<pre>int lua_load (lua_State *L,
4373              lua_Reader reader,
4374              void *data,
4375              const char *chunkname,
4376              const char *mode);</pre>
4377
4378<p>
4379Loads a Lua chunk without running it.
4380If there are no errors,
4381<code>lua_load</code> pushes the compiled chunk as a Lua
4382function on top of the stack.
4383Otherwise, it pushes an error message.
4384
4385
4386<p>
4387The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
4388to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
4389The <code>data</code> argument is an opaque value passed to the reader function.
4390
4391
4392<p>
4393The <code>chunkname</code> argument gives a name to the chunk,
4394which is used for error messages and in debug information (see <a href="#4.7">&sect;4.7</a>).
4395
4396
4397<p>
4398<code>lua_load</code> automatically detects whether the chunk is text or binary
4399and loads it accordingly (see program <code>luac</code>).
4400The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
4401with the addition that
4402a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
4403
4404
4405<p>
4406<code>lua_load</code> uses the stack internally,
4407so the reader function must always leave the stack
4408unmodified when returning.
4409
4410
4411<p>
4412<code>lua_load</code> can return
4413<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>.
4414The function may also return other values corresponding to
4415errors raised by the read function (see <a href="#4.4.1">&sect;4.4.1</a>).
4416
4417
4418<p>
4419If the resulting function has upvalues,
4420its first upvalue is set to the value of the global environment
4421stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.3">&sect;4.3</a>).
4422When loading main chunks,
4423this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
4424Other upvalues are initialized with <b>nil</b>.
4425
4426
4427
4428
4429
4430<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
4431<span class="apii">[-0, +0, &ndash;]</span>
4432<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
4433
4434<p>
4435Creates a new independent state and returns its main thread.
4436Returns <code>NULL</code> if it cannot create the state
4437(due to lack of memory).
4438The argument <code>f</code> is the allocator function;
4439Lua will do all memory allocation for this state
4440through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
4441The second argument, <code>ud</code>, is an opaque pointer that Lua
4442passes to the allocator in every call.
4443
4444
4445
4446
4447
4448<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
4449<span class="apii">[-0, +1, <em>m</em>]</span>
4450<pre>void lua_newtable (lua_State *L);</pre>
4451
4452<p>
4453Creates a new empty table and pushes it onto the stack.
4454It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
4455
4456
4457
4458
4459
4460<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
4461<span class="apii">[-0, +1, <em>m</em>]</span>
4462<pre>lua_State *lua_newthread (lua_State *L);</pre>
4463
4464<p>
4465Creates a new thread, pushes it on the stack,
4466and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
4467The new thread returned by this function shares with the original thread
4468its global environment,
4469but has an independent execution stack.
4470
4471
4472<p>
4473Threads are subject to garbage collection,
4474like any Lua object.
4475
4476
4477
4478
4479
4480<hr><h3><a name="lua_newuserdatauv"><code>lua_newuserdatauv</code></a></h3><p>
4481<span class="apii">[-0, +1, <em>m</em>]</span>
4482<pre>void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);</pre>
4483
4484<p>
4485This function creates and pushes on the stack a new full userdata,
4486with <code>nuvalue</code> associated Lua values, called <code>user values</code>,
4487plus an associated block of raw memory with <code>size</code> bytes.
4488(The user values can be set and read with the functions
4489<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a> and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>.)
4490
4491
4492<p>
4493The function returns the address of the block of memory.
4494Lua ensures that this address is valid as long as
4495the corresponding userdata is alive (see <a href="#2.5">&sect;2.5</a>).
4496Moreover, if the userdata is marked for finalization (see <a href="#2.5.3">&sect;2.5.3</a>),
4497its address is valid at least until the call to its finalizer.
4498
4499
4500
4501
4502
4503<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4504<span class="apii">[-1, +(2|0), <em>v</em>]</span>
4505<pre>int lua_next (lua_State *L, int index);</pre>
4506
4507<p>
4508Pops a key from the stack,
4509and pushes a key&ndash;value pair from the table at the given index,
4510the "next" pair after the given key.
4511If there are no more elements in the table,
4512then <a href="#lua_next"><code>lua_next</code></a> returns 0 and pushes nothing.
4513
4514
4515<p>
4516A typical table traversal looks like this:
4517
4518<pre>
4519     /* table is in the stack at index 't' */
4520     lua_pushnil(L);  /* first key */
4521     while (lua_next(L, t) != 0) {
4522       /* uses 'key' (at index -2) and 'value' (at index -1) */
4523       printf("%s - %s\n",
4524              lua_typename(L, lua_type(L, -2)),
4525              lua_typename(L, lua_type(L, -1)));
4526       /* removes 'value'; keeps 'key' for next iteration */
4527       lua_pop(L, 1);
4528     }
4529</pre>
4530
4531<p>
4532While traversing a table,
4533avoid calling <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4534unless you know that the key is actually a string.
4535Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4536the value at the given index;
4537this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4538
4539
4540<p>
4541This function may raise an error if the given key
4542is neither <b>nil</b> nor present in the table.
4543See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4544the table during its traversal.
4545
4546
4547
4548
4549
4550<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4551<pre>typedef ... lua_Number;</pre>
4552
4553<p>
4554The type of floats in Lua.
4555
4556
4557<p>
4558By default this type is double,
4559but that can be changed to a single float or a long double.
4560(See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
4561
4562
4563
4564
4565
4566<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4567<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4568
4569<p>
4570Tries to convert a Lua float to a Lua integer;
4571the float <code>n</code> must have an integral value.
4572If that value is within the range of Lua integers,
4573it is converted to an integer and assigned to <code>*p</code>.
4574The macro results in a boolean indicating whether the
4575conversion was successful.
4576(Note that this range test can be tricky to do
4577correctly without this macro, due to rounding.)
4578
4579
4580<p>
4581This macro may evaluate its arguments more than once.
4582
4583
4584
4585
4586
4587<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4588<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4589<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4590
4591<p>
4592Calls a function (or a callable object) in protected mode.
4593
4594
4595<p>
4596Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4597in <a href="#lua_call"><code>lua_call</code></a>.
4598If there are no errors during the call,
4599<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4600However, if there is any error,
4601<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4602pushes a single value on the stack (the error object),
4603and returns an error code.
4604Like <a href="#lua_call"><code>lua_call</code></a>,
4605<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4606and its arguments from the stack.
4607
4608
4609<p>
4610If <code>msgh</code> is 0,
4611then the error object returned on the stack
4612is exactly the original error object.
4613Otherwise, <code>msgh</code> is the stack index of a
4614<em>message handler</em>.
4615(This index cannot be a pseudo-index.)
4616In case of runtime errors,
4617this handler will be called with the error object
4618and its return value will be the object
4619returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4620
4621
4622<p>
4623Typically, the message handler is used to add more debug
4624information to the error object, such as a stack traceback.
4625Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4626since by then the stack has unwound.
4627
4628
4629<p>
4630The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following status codes:
4631<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>.
4632
4633
4634
4635
4636
4637<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4638<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4639<pre>int lua_pcallk (lua_State *L,
4640                int nargs,
4641                int nresults,
4642                int msgh,
4643                lua_KContext ctx,
4644                lua_KFunction k);</pre>
4645
4646<p>
4647This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4648except that it allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
4649
4650
4651
4652
4653
4654<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4655<span class="apii">[-n, +0, <em>e</em>]</span>
4656<pre>void lua_pop (lua_State *L, int n);</pre>
4657
4658<p>
4659Pops <code>n</code> elements from the stack.
4660
4661
4662<p>
4663This function can run arbitrary code when removing an index
4664marked as to-be-closed from the stack.
4665
4666
4667
4668
4669
4670<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4671<span class="apii">[-0, +1, &ndash;]</span>
4672<pre>void lua_pushboolean (lua_State *L, int b);</pre>
4673
4674<p>
4675Pushes a boolean value with value <code>b</code> onto the stack.
4676
4677
4678
4679
4680
4681<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4682<span class="apii">[-n, +1, <em>m</em>]</span>
4683<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4684
4685<p>
4686Pushes a new C&nbsp;closure onto the stack.
4687This function receives a pointer to a C&nbsp;function
4688and pushes onto the stack a Lua value of type <code>function</code> that,
4689when called, invokes the corresponding C&nbsp;function.
4690The parameter <code>n</code> tells how many upvalues this function will have
4691(see <a href="#4.2">&sect;4.2</a>).
4692
4693
4694<p>
4695Any function to be callable by Lua must
4696follow the correct protocol to receive its parameters
4697and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4698
4699
4700<p>
4701When a C&nbsp;function is created,
4702it is possible to associate some values with it,
4703the so called upvalues;
4704these upvalues are then accessible to the function whenever it is called.
4705This association is called a C&nbsp;closure (see <a href="#4.2">&sect;4.2</a>).
4706To create a C&nbsp;closure,
4707first the initial values for its upvalues must be pushed onto the stack.
4708(When there are multiple upvalues, the first value is pushed first.)
4709Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4710is called to create and push the C&nbsp;function onto the stack,
4711with the argument <code>n</code> telling how many values will be
4712associated with the function.
4713<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4714
4715
4716<p>
4717The maximum value for <code>n</code> is 255.
4718
4719
4720<p>
4721When <code>n</code> is zero,
4722this function creates a <em>light C&nbsp;function</em>,
4723which is just a pointer to the C&nbsp;function.
4724In that case, it never raises a memory error.
4725
4726
4727
4728
4729
4730<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4731<span class="apii">[-0, +1, &ndash;]</span>
4732<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4733
4734<p>
4735Pushes a C&nbsp;function onto the stack.
4736This function is equivalent to <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> with no upvalues.
4737
4738
4739
4740
4741
4742<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4743<span class="apii">[-0, +1, <em>v</em>]</span>
4744<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4745
4746<p>
4747Pushes onto the stack a formatted string
4748and returns a pointer to this string (see <a href="#4.1.3">&sect;4.1.3</a>).
4749It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4750but has two important differences.
4751First,
4752you do not have to allocate space for the result;
4753the result is a Lua string and Lua takes care of memory allocation
4754(and deallocation, through garbage collection).
4755Second,
4756the conversion specifiers are quite restricted.
4757There are no flags, widths, or precisions.
4758The conversion specifiers can only be
4759'<code>%%</code>' (inserts the character '<code>%</code>'),
4760'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4761'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4762'<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4763'<code>%p</code>' (inserts a pointer),
4764'<code>%d</code>' (inserts an <code>int</code>),
4765'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4766'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4767
4768
4769<p>
4770This function may raise errors due to memory overflow
4771or an invalid conversion specifier.
4772
4773
4774
4775
4776
4777<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4778<span class="apii">[-0, +1, &ndash;]</span>
4779<pre>void lua_pushglobaltable (lua_State *L);</pre>
4780
4781<p>
4782Pushes the global environment onto the stack.
4783
4784
4785
4786
4787
4788<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4789<span class="apii">[-0, +1, &ndash;]</span>
4790<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4791
4792<p>
4793Pushes an integer with value <code>n</code> onto the stack.
4794
4795
4796
4797
4798
4799<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4800<span class="apii">[-0, +1, &ndash;]</span>
4801<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4802
4803<p>
4804Pushes a light userdata onto the stack.
4805
4806
4807<p>
4808Userdata represent C&nbsp;values in Lua.
4809A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4810It is a value (like a number):
4811you do not create it, it has no individual metatable,
4812and it is not collected (as it was never created).
4813A light userdata is equal to "any"
4814light userdata with the same C&nbsp;address.
4815
4816
4817
4818
4819
4820<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4821<span class="apii">[-0, +1, <em>m</em>]</span>
4822<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4823
4824<p>
4825This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
4826but should be used only when <code>s</code> is a literal string.
4827(Lua may optimize this case.)
4828
4829
4830
4831
4832
4833<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4834<span class="apii">[-0, +1, <em>m</em>]</span>
4835<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4836
4837<p>
4838Pushes the string pointed to by <code>s</code> with size <code>len</code>
4839onto the stack.
4840Lua will make or reuse an internal copy of the given string,
4841so the memory at <code>s</code> can be freed or reused immediately after
4842the function returns.
4843The string can contain any binary data,
4844including embedded zeros.
4845
4846
4847<p>
4848Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4849
4850
4851
4852
4853
4854<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4855<span class="apii">[-0, +1, &ndash;]</span>
4856<pre>void lua_pushnil (lua_State *L);</pre>
4857
4858<p>
4859Pushes a nil value onto the stack.
4860
4861
4862
4863
4864
4865<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4866<span class="apii">[-0, +1, &ndash;]</span>
4867<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4868
4869<p>
4870Pushes a float with value <code>n</code> onto the stack.
4871
4872
4873
4874
4875
4876<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4877<span class="apii">[-0, +1, <em>m</em>]</span>
4878<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4879
4880<p>
4881Pushes the zero-terminated string pointed to by <code>s</code>
4882onto the stack.
4883Lua will make or reuse an internal copy of the given string,
4884so the memory at <code>s</code> can be freed or reused immediately after
4885the function returns.
4886
4887
4888<p>
4889Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4890
4891
4892<p>
4893If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4894
4895
4896
4897
4898
4899<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4900<span class="apii">[-0, +1, &ndash;]</span>
4901<pre>int lua_pushthread (lua_State *L);</pre>
4902
4903<p>
4904Pushes the thread represented by <code>L</code> onto the stack.
4905Returns 1 if this thread is the main thread of its state.
4906
4907
4908
4909
4910
4911<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4912<span class="apii">[-0, +1, &ndash;]</span>
4913<pre>void lua_pushvalue (lua_State *L, int index);</pre>
4914
4915<p>
4916Pushes a copy of the element at the given index
4917onto the stack.
4918
4919
4920
4921
4922
4923<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4924<span class="apii">[-0, +1, <em>v</em>]</span>
4925<pre>const char *lua_pushvfstring (lua_State *L,
4926                              const char *fmt,
4927                              va_list argp);</pre>
4928
4929<p>
4930Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4931instead of a variable number of arguments.
4932
4933
4934
4935
4936
4937<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4938<span class="apii">[-0, +0, &ndash;]</span>
4939<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4940
4941<p>
4942Returns 1 if the two values in indices <code>index1</code> and
4943<code>index2</code> are primitively equal
4944(that is, equal without calling the <code>__eq</code> metamethod).
4945Otherwise returns&nbsp;0.
4946Also returns&nbsp;0 if any of the indices are not valid.
4947
4948
4949
4950
4951
4952<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4953<span class="apii">[-1, +1, &ndash;]</span>
4954<pre>int lua_rawget (lua_State *L, int index);</pre>
4955
4956<p>
4957Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4958(i.e., without metamethods).
4959
4960
4961
4962
4963
4964<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4965<span class="apii">[-0, +1, &ndash;]</span>
4966<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4967
4968<p>
4969Pushes onto the stack the value <code>t[n]</code>,
4970where <code>t</code> is the table at the given index.
4971The access is raw,
4972that is, it does not use the <code>__index</code> metavalue.
4973
4974
4975<p>
4976Returns the type of the pushed value.
4977
4978
4979
4980
4981
4982<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4983<span class="apii">[-0, +1, &ndash;]</span>
4984<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4985
4986<p>
4987Pushes onto the stack the value <code>t[k]</code>,
4988where <code>t</code> is the table at the given index and
4989<code>k</code> is the pointer <code>p</code> represented as a light userdata.
4990The access is raw;
4991that is, it does not use the <code>__index</code> metavalue.
4992
4993
4994<p>
4995Returns the type of the pushed value.
4996
4997
4998
4999
5000
5001<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
5002<span class="apii">[-0, +0, &ndash;]</span>
5003<pre>lua_Unsigned lua_rawlen (lua_State *L, int index);</pre>
5004
5005<p>
5006Returns the raw "length" of the value at the given index:
5007for strings, this is the string length;
5008for tables, this is the result of the length operator ('<code>#</code>')
5009with no metamethods;
5010for userdata, this is the size of the block of memory allocated
5011for the userdata.
5012For other values, this call returns&nbsp;0.
5013
5014
5015
5016
5017
5018<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
5019<span class="apii">[-2, +0, <em>m</em>]</span>
5020<pre>void lua_rawset (lua_State *L, int index);</pre>
5021
5022<p>
5023Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
5024(i.e., without metamethods).
5025
5026
5027
5028
5029
5030<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
5031<span class="apii">[-1, +0, <em>m</em>]</span>
5032<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
5033
5034<p>
5035Does the equivalent of <code>t[i] = v</code>,
5036where <code>t</code> is the table at the given index
5037and <code>v</code> is the value on the top of the stack.
5038
5039
5040<p>
5041This function pops the value from the stack.
5042The assignment is raw,
5043that is, it does not use the <code>__newindex</code> metavalue.
5044
5045
5046
5047
5048
5049<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
5050<span class="apii">[-1, +0, <em>m</em>]</span>
5051<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
5052
5053<p>
5054Does the equivalent of <code>t[p] = v</code>,
5055where <code>t</code> is the table at the given index,
5056<code>p</code> is encoded as a light userdata,
5057and <code>v</code> is the value on the top of the stack.
5058
5059
5060<p>
5061This function pops the value from the stack.
5062The assignment is raw,
5063that is, it does not use the <code>__newindex</code> metavalue.
5064
5065
5066
5067
5068
5069<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
5070<pre>typedef const char * (*lua_Reader) (lua_State *L,
5071                                    void *data,
5072                                    size_t *size);</pre>
5073
5074<p>
5075The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
5076Every time <a href="#lua_load"><code>lua_load</code></a> needs another piece of the chunk,
5077it calls the reader,
5078passing along its <code>data</code> parameter.
5079The reader must return a pointer to a block of memory
5080with a new piece of the chunk
5081and set <code>size</code> to the block size.
5082The block must exist until the reader function is called again.
5083To signal the end of the chunk,
5084the reader must return <code>NULL</code> or set <code>size</code> to zero.
5085The reader function may return pieces of any size greater than zero.
5086
5087
5088
5089
5090
5091<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
5092<span class="apii">[-0, +0, <em>e</em>]</span>
5093<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
5094
5095<p>
5096Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>.
5097It is defined as a macro:
5098
5099<pre>
5100     #define lua_register(L,n,f) \
5101            (lua_pushcfunction(L, f), lua_setglobal(L, n))
5102</pre>
5103
5104
5105
5106
5107<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
5108<span class="apii">[-1, +0, &ndash;]</span>
5109<pre>void lua_remove (lua_State *L, int index);</pre>
5110
5111<p>
5112Removes the element at the given valid index,
5113shifting down the elements above this index to fill the gap.
5114This function cannot be called with a pseudo-index,
5115because a pseudo-index is not an actual stack position.
5116
5117
5118
5119
5120
5121<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
5122<span class="apii">[-1, +0, &ndash;]</span>
5123<pre>void lua_replace (lua_State *L, int index);</pre>
5124
5125<p>
5126Moves the top element into the given valid index
5127without shifting any element
5128(therefore replacing the value at that given index),
5129and then pops the top element.
5130
5131
5132
5133
5134
5135<hr><h3><a name="lua_resetthread"><code>lua_resetthread</code></a></h3><p>
5136<span class="apii">[-0, +?, &ndash;]</span>
5137<pre>int lua_resetthread (lua_State *L);</pre>
5138
5139<p>
5140Resets a thread, cleaning its call stack and closing all pending
5141to-be-closed variables.
5142Returns a status code:
5143<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for no errors in closing methods,
5144or an error status otherwise.
5145In case of error,
5146leaves the error object on the top of the stack,
5147
5148
5149
5150
5151
5152<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
5153<span class="apii">[-?, +?, &ndash;]</span>
5154<pre>int lua_resume (lua_State *L, lua_State *from, int nargs,
5155                          int *nresults);</pre>
5156
5157<p>
5158Starts and resumes a coroutine in the given thread <code>L</code>.
5159
5160
5161<p>
5162To start a coroutine,
5163you push the main function plus any arguments
5164onto the empty stack of the thread.
5165then you call <a href="#lua_resume"><code>lua_resume</code></a>,
5166with <code>nargs</code> being the number of arguments.
5167This call returns when the coroutine suspends or finishes its execution.
5168When it returns,
5169<code>*nresults</code> is updated and
5170the top of the stack contains
5171the <code>*nresults</code> values passed to <a href="#lua_yield"><code>lua_yield</code></a>
5172or returned by the body function.
5173<a href="#lua_resume"><code>lua_resume</code></a> returns
5174<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
5175<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
5176without errors,
5177or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
5178In case of errors,
5179the error object is on the top of the stack.
5180
5181
5182<p>
5183To resume a coroutine,
5184you remove the <code>*nresults</code> yielded values from its stack,
5185push the values to be passed as results from <code>yield</code>,
5186and then call <a href="#lua_resume"><code>lua_resume</code></a>.
5187
5188
5189<p>
5190The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
5191If there is no such coroutine,
5192this parameter can be <code>NULL</code>.
5193
5194
5195
5196
5197
5198<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
5199<span class="apii">[-0, +0, &ndash;]</span>
5200<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
5201
5202<p>
5203Rotates the stack elements between the valid index <code>idx</code>
5204and the top of the stack.
5205The elements are rotated <code>n</code> positions in the direction of the top,
5206for a positive <code>n</code>,
5207or <code>-n</code> positions in the direction of the bottom,
5208for a negative <code>n</code>.
5209The absolute value of <code>n</code> must not be greater than the size
5210of the slice being rotated.
5211This function cannot be called with a pseudo-index,
5212because a pseudo-index is not an actual stack position.
5213
5214
5215
5216
5217
5218<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
5219<span class="apii">[-0, +0, &ndash;]</span>
5220<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
5221
5222<p>
5223Changes the allocator function of a given state to <code>f</code>
5224with user data <code>ud</code>.
5225
5226
5227
5228
5229
5230<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
5231<span class="apii">[-1, +0, <em>e</em>]</span>
5232<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
5233
5234<p>
5235Does the equivalent to <code>t[k] = v</code>,
5236where <code>t</code> is the value at the given index
5237and <code>v</code> is the value on the top of the stack.
5238
5239
5240<p>
5241This function pops the value from the stack.
5242As in Lua, this function may trigger a metamethod
5243for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5244
5245
5246
5247
5248
5249<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
5250<span class="apii">[-1, +0, <em>e</em>]</span>
5251<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
5252
5253<p>
5254Pops a value from the stack and
5255sets it as the new value of global <code>name</code>.
5256
5257
5258
5259
5260
5261<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
5262<span class="apii">[-1, +0, <em>e</em>]</span>
5263<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
5264
5265<p>
5266Does the equivalent to <code>t[n] = v</code>,
5267where <code>t</code> is the value at the given index
5268and <code>v</code> is the value on the top of the stack.
5269
5270
5271<p>
5272This function pops the value from the stack.
5273As in Lua, this function may trigger a metamethod
5274for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5275
5276
5277
5278
5279
5280<hr><h3><a name="lua_setiuservalue"><code>lua_setiuservalue</code></a></h3><p>
5281<span class="apii">[-1, +0, &ndash;]</span>
5282<pre>int lua_setiuservalue (lua_State *L, int index, int n);</pre>
5283
5284<p>
5285Pops a value from the stack and sets it as
5286the new <code>n</code>-th user value associated to the
5287full userdata at the given index.
5288Returns 0 if the userdata does not have that value.
5289
5290
5291
5292
5293
5294<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
5295<span class="apii">[-1, +0, &ndash;]</span>
5296<pre>int lua_setmetatable (lua_State *L, int index);</pre>
5297
5298<p>
5299Pops a table or <b>nil</b> from the stack and
5300sets that value as the new metatable for the value at the given index.
5301(<b>nil</b> means no metatable.)
5302
5303
5304<p>
5305(For historical reasons, this function returns an <code>int</code>,
5306which now is always 1.)
5307
5308
5309
5310
5311
5312<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
5313<span class="apii">[-2, +0, <em>e</em>]</span>
5314<pre>void lua_settable (lua_State *L, int index);</pre>
5315
5316<p>
5317Does the equivalent to <code>t[k] = v</code>,
5318where <code>t</code> is the value at the given index,
5319<code>v</code> is the value on the top of the stack,
5320and <code>k</code> is the value just below the top.
5321
5322
5323<p>
5324This function pops both the key and the value from the stack.
5325As in Lua, this function may trigger a metamethod
5326for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5327
5328
5329
5330
5331
5332<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
5333<span class="apii">[-?, +?, <em>e</em>]</span>
5334<pre>void lua_settop (lua_State *L, int index);</pre>
5335
5336<p>
5337Accepts any index, or&nbsp;0,
5338and sets the stack top to this index.
5339If the new top is greater than the old one,
5340then the new elements are filled with <b>nil</b>.
5341If <code>index</code> is&nbsp;0, then all stack elements are removed.
5342
5343
5344<p>
5345This function can run arbitrary code when removing an index
5346marked as to-be-closed from the stack.
5347
5348
5349
5350
5351
5352<hr><h3><a name="lua_setwarnf"><code>lua_setwarnf</code></a></h3><p>
5353<span class="apii">[-0, +0, &ndash;]</span>
5354<pre>void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);</pre>
5355
5356<p>
5357Sets the warning function to be used by Lua to emit warnings
5358(see <a href="#lua_WarnFunction"><code>lua_WarnFunction</code></a>).
5359The <code>ud</code> parameter sets the value <code>ud</code> passed to
5360the warning function.
5361
5362
5363
5364
5365
5366<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
5367<pre>typedef struct lua_State lua_State;</pre>
5368
5369<p>
5370An opaque structure that points to a thread and indirectly
5371(through the thread) to the whole state of a Lua interpreter.
5372The Lua library is fully reentrant:
5373it has no global variables.
5374All information about a state is accessible through this structure.
5375
5376
5377<p>
5378A pointer to this structure must be passed as the first argument to
5379every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
5380which creates a Lua state from scratch.
5381
5382
5383
5384
5385
5386<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
5387<span class="apii">[-0, +0, &ndash;]</span>
5388<pre>int lua_status (lua_State *L);</pre>
5389
5390<p>
5391Returns the status of the thread <code>L</code>.
5392
5393
5394<p>
5395The status can be <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for a normal thread,
5396an error code if the thread finished the execution
5397of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
5398or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
5399
5400
5401<p>
5402You can call functions only in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
5403You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
5404(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
5405(to resume a coroutine).
5406
5407
5408
5409
5410
5411<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
5412<span class="apii">[-0, +1, &ndash;]</span>
5413<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
5414
5415<p>
5416Converts the zero-terminated string <code>s</code> to a number,
5417pushes that number into the stack,
5418and returns the total size of the string,
5419that is, its length plus one.
5420The conversion can result in an integer or a float,
5421according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
5422The string may have leading and trailing whitespaces and a sign.
5423If the string is not a valid numeral,
5424returns 0 and pushes nothing.
5425(Note that the result can be used as a boolean,
5426true if the conversion succeeds.)
5427
5428
5429
5430
5431
5432<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
5433<span class="apii">[-0, +0, &ndash;]</span>
5434<pre>int lua_toboolean (lua_State *L, int index);</pre>
5435
5436<p>
5437Converts the Lua value at the given index to a C&nbsp;boolean
5438value (0&nbsp;or&nbsp;1).
5439Like all tests in Lua,
5440<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
5441different from <b>false</b> and <b>nil</b>;
5442otherwise it returns false.
5443(If you want to accept only actual boolean values,
5444use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
5445
5446
5447
5448
5449
5450<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
5451<span class="apii">[-0, +0, &ndash;]</span>
5452<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
5453
5454<p>
5455Converts a value at the given index to a C&nbsp;function.
5456That value must be a C&nbsp;function;
5457otherwise, returns <code>NULL</code>.
5458
5459
5460
5461
5462
5463<hr><h3><a name="lua_toclose"><code>lua_toclose</code></a></h3><p>
5464<span class="apii">[-0, +0, <em>m</em>]</span>
5465<pre>void lua_toclose (lua_State *L, int index);</pre>
5466
5467<p>
5468Marks the given index in the stack as a
5469to-be-closed "variable" (see <a href="#3.3.8">&sect;3.3.8</a>).
5470Like a to-be-closed variable in Lua,
5471the value at that index in the stack will be closed
5472when it goes out of scope.
5473Here, in the context of a C function,
5474to go out of scope means that the running function returns to Lua,
5475there is an error,
5476or the index is removed from the stack through
5477<a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>.
5478An index marked as to-be-closed should not be removed from the stack
5479by 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>.
5480
5481
5482<p>
5483This function should not be called for an index
5484that is equal to or below an active to-be-closed index.
5485
5486
5487<p>
5488In the case of an out-of-memory error,
5489the value in the given index is immediately closed,
5490as if it was already marked.
5491
5492
5493<p>
5494Note that, both in case of errors and of a regular return,
5495by the time the <code>__close</code> metamethod runs,
5496the C&nbsp;stack was already unwound,
5497so that any automatic C&nbsp;variable declared in the calling function
5498will be out of scope.
5499
5500
5501
5502
5503
5504<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
5505<span class="apii">[-0, +0, &ndash;]</span>
5506<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
5507
5508<p>
5509Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5510
5511
5512
5513
5514
5515<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
5516<span class="apii">[-0, +0, &ndash;]</span>
5517<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
5518
5519<p>
5520Converts the Lua value at the given index
5521to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
5522The Lua value must be an integer,
5523or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
5524otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
5525
5526
5527<p>
5528If <code>isnum</code> is not <code>NULL</code>,
5529its referent is assigned a boolean value that
5530indicates whether the operation succeeded.
5531
5532
5533
5534
5535
5536<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
5537<span class="apii">[-0, +0, <em>m</em>]</span>
5538<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5539
5540<p>
5541Converts the Lua value at the given index to a C&nbsp;string.
5542If <code>len</code> is not <code>NULL</code>,
5543it sets <code>*len</code> with the string length.
5544The Lua value must be a string or a number;
5545otherwise, the function returns <code>NULL</code>.
5546If the value is a number,
5547then <code>lua_tolstring</code> also
5548<em>changes the actual value in the stack to a string</em>.
5549(This change confuses <a href="#lua_next"><code>lua_next</code></a>
5550when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5551
5552
5553<p>
5554<code>lua_tolstring</code> returns a pointer
5555to a string inside the Lua state (see <a href="#4.1.3">&sect;4.1.3</a>).
5556This string always has a zero ('<code>\0</code>')
5557after its last character (as in&nbsp;C),
5558but can contain other zeros in its body.
5559
5560
5561
5562
5563
5564<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5565<span class="apii">[-0, +0, &ndash;]</span>
5566<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5567
5568<p>
5569Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5570
5571
5572
5573
5574
5575<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5576<span class="apii">[-0, +0, &ndash;]</span>
5577<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5578
5579<p>
5580Converts the Lua value at the given index
5581to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5582The Lua value must be a number or a string convertible to a number
5583(see <a href="#3.4.3">&sect;3.4.3</a>);
5584otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5585
5586
5587<p>
5588If <code>isnum</code> is not <code>NULL</code>,
5589its referent is assigned a boolean value that
5590indicates whether the operation succeeded.
5591
5592
5593
5594
5595
5596<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5597<span class="apii">[-0, +0, &ndash;]</span>
5598<pre>const void *lua_topointer (lua_State *L, int index);</pre>
5599
5600<p>
5601Converts the value at the given index to a generic
5602C&nbsp;pointer (<code>void*</code>).
5603The value can be a userdata, a table, a thread, a string, or a function;
5604otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5605Different objects will give different pointers.
5606There is no way to convert the pointer back to its original value.
5607
5608
5609<p>
5610Typically this function is used only for hashing and debug information.
5611
5612
5613
5614
5615
5616<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5617<span class="apii">[-0, +0, <em>m</em>]</span>
5618<pre>const char *lua_tostring (lua_State *L, int index);</pre>
5619
5620<p>
5621Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5622
5623
5624
5625
5626
5627<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5628<span class="apii">[-0, +0, &ndash;]</span>
5629<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5630
5631<p>
5632Converts the value at the given index to a Lua thread
5633(represented as <code>lua_State*</code>).
5634This value must be a thread;
5635otherwise, the function returns <code>NULL</code>.
5636
5637
5638
5639
5640
5641<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5642<span class="apii">[-0, +0, &ndash;]</span>
5643<pre>void *lua_touserdata (lua_State *L, int index);</pre>
5644
5645<p>
5646If the value at the given index is a full userdata,
5647returns its memory-block address.
5648If the value is a light userdata,
5649returns its value (a pointer).
5650Otherwise, returns <code>NULL</code>.
5651
5652
5653
5654
5655
5656<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5657<span class="apii">[-0, +0, &ndash;]</span>
5658<pre>int lua_type (lua_State *L, int index);</pre>
5659
5660<p>
5661Returns the type of the value in the given valid index,
5662or <code>LUA_TNONE</code> for a non-valid but acceptable index.
5663The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5664defined in <code>lua.h</code>:
5665<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5666<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5667<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5668<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5669<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5670<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5671<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5672<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5673and
5674<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5675
5676
5677
5678
5679
5680<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5681<span class="apii">[-0, +0, &ndash;]</span>
5682<pre>const char *lua_typename (lua_State *L, int tp);</pre>
5683
5684<p>
5685Returns the name of the type encoded by the value <code>tp</code>,
5686which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5687
5688
5689
5690
5691
5692<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5693<pre>typedef ... lua_Unsigned;</pre>
5694
5695<p>
5696The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5697
5698
5699
5700
5701
5702<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5703<span class="apii">[-0, +0, &ndash;]</span>
5704<pre>int lua_upvalueindex (int i);</pre>
5705
5706<p>
5707Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5708the running function (see <a href="#4.2">&sect;4.2</a>).
5709<code>i</code> must be in the range <em>[1,256]</em>.
5710
5711
5712
5713
5714
5715<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5716<span class="apii">[-0, +0, &ndash;]</span>
5717<pre>lua_Number lua_version (lua_State *L);</pre>
5718
5719<p>
5720Returns the version number of this core.
5721
5722
5723
5724
5725
5726<hr><h3><a name="lua_WarnFunction"><code>lua_WarnFunction</code></a></h3>
5727<pre>typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);</pre>
5728
5729<p>
5730The type of warning functions, called by Lua to emit warnings.
5731The first parameter is an opaque pointer
5732set by <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>.
5733The second parameter is the warning message.
5734The third parameter is a boolean that
5735indicates whether the message is
5736to be continued by the message in the next call.
5737
5738
5739<p>
5740See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5741
5742
5743
5744
5745
5746<hr><h3><a name="lua_warning"><code>lua_warning</code></a></h3><p>
5747<span class="apii">[-0, +0, &ndash;]</span>
5748<pre>void lua_warning (lua_State *L, const char *msg, int tocont);</pre>
5749
5750<p>
5751Emits a warning with the given message.
5752A message in a call with <code>tocont</code> true should be
5753continued in another call to this function.
5754
5755
5756<p>
5757See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5758
5759
5760
5761
5762
5763<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5764<pre>typedef int (*lua_Writer) (lua_State *L,
5765                           const void* p,
5766                           size_t sz,
5767                           void* ud);</pre>
5768
5769<p>
5770The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5771Every time <a href="#lua_dump"><code>lua_dump</code></a> produces another piece of chunk,
5772it calls the writer,
5773passing along the buffer to be written (<code>p</code>),
5774its size (<code>sz</code>),
5775and the <code>ud</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5776
5777
5778<p>
5779The writer returns an error code:
57800&nbsp;means no errors;
5781any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5782calling the writer again.
5783
5784
5785
5786
5787
5788<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5789<span class="apii">[-?, +?, &ndash;]</span>
5790<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5791
5792<p>
5793Exchange values between different threads of the same state.
5794
5795
5796<p>
5797This function pops <code>n</code> values from the stack <code>from</code>,
5798and pushes them onto the stack <code>to</code>.
5799
5800
5801
5802
5803
5804<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5805<span class="apii">[-?, +?, <em>v</em>]</span>
5806<pre>int lua_yield (lua_State *L, int nresults);</pre>
5807
5808<p>
5809This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5810but it has no continuation (see <a href="#4.5">&sect;4.5</a>).
5811Therefore, when the thread resumes,
5812it continues the function that called
5813the function calling <code>lua_yield</code>.
5814To avoid surprises,
5815this function should be called only in a tail call.
5816
5817
5818
5819
5820
5821<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5822<span class="apii">[-?, +?, <em>v</em>]</span>
5823<pre>int lua_yieldk (lua_State *L,
5824                int nresults,
5825                lua_KContext ctx,
5826                lua_KFunction k);</pre>
5827
5828<p>
5829Yields a coroutine (thread).
5830
5831
5832<p>
5833When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5834the running coroutine suspends its execution,
5835and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5836The parameter <code>nresults</code> is the number of values from the stack
5837that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5838
5839
5840<p>
5841When the coroutine is resumed again,
5842Lua calls the given continuation function <code>k</code> to continue
5843the execution of the C&nbsp;function that yielded (see <a href="#4.5">&sect;4.5</a>).
5844This continuation function receives the same stack
5845from the previous function,
5846with the <code>n</code> results removed and
5847replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5848Moreover,
5849the continuation function receives the value <code>ctx</code>
5850that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5851
5852
5853<p>
5854Usually, this function does not return;
5855when the coroutine eventually resumes,
5856it continues executing the continuation function.
5857However, there is one special case,
5858which is when this function is called
5859from inside a line or a count hook (see <a href="#4.7">&sect;4.7</a>).
5860In that case, <code>lua_yieldk</code> should be called with no continuation
5861(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
5862and the hook should return immediately after the call.
5863Lua will yield and,
5864when the coroutine resumes again,
5865it will continue the normal execution
5866of the (Lua) function that triggered the hook.
5867
5868
5869<p>
5870This function can raise an error if it is called from a thread
5871with a pending C call with no continuation function
5872(what is called a <em>C-call boundary</em>),
5873or it is called from a thread that is not running inside a resume
5874(typically the main thread).
5875
5876
5877
5878
5879
5880
5881
5882<h2>4.7 &ndash; <a name="4.7">The Debug Interface</a></h2>
5883
5884<p>
5885Lua has no built-in debugging facilities.
5886Instead, it offers a special interface
5887by means of functions and <em>hooks</em>.
5888This interface allows the construction of different
5889kinds of debuggers, profilers, and other tools
5890that need "inside information" from the interpreter.
5891
5892
5893
5894<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5895<pre>typedef struct lua_Debug {
5896  int event;
5897  const char *name;           /* (n) */
5898  const char *namewhat;       /* (n) */
5899  const char *what;           /* (S) */
5900  const char *source;         /* (S) */
5901  size_t srclen;              /* (S) */
5902  int currentline;            /* (l) */
5903  int linedefined;            /* (S) */
5904  int lastlinedefined;        /* (S) */
5905  unsigned char nups;         /* (u) number of upvalues */
5906  unsigned char nparams;      /* (u) number of parameters */
5907  char isvararg;              /* (u) */
5908  char istailcall;            /* (t) */
5909  unsigned short ftransfer;   /* (r) index of first value transferred */
5910  unsigned short ntransfer;   /* (r) number of transferred values */
5911  char short_src[LUA_IDSIZE]; /* (S) */
5912  /* private part */
5913  <em>other fields</em>
5914} lua_Debug;</pre>
5915
5916<p>
5917A structure used to carry different pieces of
5918information about a function or an activation record.
5919<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5920of this structure, for later use.
5921To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5922you must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5923
5924
5925<p>
5926The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5927
5928<ul>
5929
5930<li><b><code>source</code>: </b>
5931the source of the chunk that created the function.
5932If <code>source</code> starts with a '<code>@</code>',
5933it means that the function was defined in a file where
5934the file name follows the '<code>@</code>'.
5935If <code>source</code> starts with a '<code>=</code>',
5936the remainder of its contents describes the source in a user-dependent manner.
5937Otherwise,
5938the function was defined in a string where
5939<code>source</code> is that string.
5940</li>
5941
5942<li><b><code>srclen</code>: </b>
5943The length of the string <code>source</code>.
5944</li>
5945
5946<li><b><code>short_src</code>: </b>
5947a "printable" version of <code>source</code>, to be used in error messages.
5948</li>
5949
5950<li><b><code>linedefined</code>: </b>
5951the line number where the definition of the function starts.
5952</li>
5953
5954<li><b><code>lastlinedefined</code>: </b>
5955the line number where the definition of the function ends.
5956</li>
5957
5958<li><b><code>what</code>: </b>
5959the string <code>"Lua"</code> if the function is a Lua function,
5960<code>"C"</code> if it is a C&nbsp;function,
5961<code>"main"</code> if it is the main part of a chunk.
5962</li>
5963
5964<li><b><code>currentline</code>: </b>
5965the current line where the given function is executing.
5966When no line information is available,
5967<code>currentline</code> is set to -1.
5968</li>
5969
5970<li><b><code>name</code>: </b>
5971a reasonable name for the given function.
5972Because functions in Lua are first-class values,
5973they do not have a fixed name:
5974some functions can be the value of multiple global variables,
5975while others can be stored only in a table field.
5976The <code>lua_getinfo</code> function checks how the function was
5977called to find a suitable name.
5978If it cannot find a name,
5979then <code>name</code> is set to <code>NULL</code>.
5980</li>
5981
5982<li><b><code>namewhat</code>: </b>
5983explains the <code>name</code> field.
5984The value of <code>namewhat</code> can be
5985<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
5986<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
5987according to how the function was called.
5988(Lua uses the empty string when no other option seems to apply.)
5989</li>
5990
5991<li><b><code>istailcall</code>: </b>
5992true if this function invocation was called by a tail call.
5993In this case, the caller of this level is not in the stack.
5994</li>
5995
5996<li><b><code>nups</code>: </b>
5997the number of upvalues of the function.
5998</li>
5999
6000<li><b><code>nparams</code>: </b>
6001the number of parameters of the function
6002(always 0&nbsp;for C&nbsp;functions).
6003</li>
6004
6005<li><b><code>isvararg</code>: </b>
6006true if the function is a vararg function
6007(always true for C&nbsp;functions).
6008</li>
6009
6010<li><b><code>ftransfer</code>: </b>
6011the index in the stack of the first value being "transferred",
6012that is, parameters in a call or return values in a return.
6013(The other values are in consecutive indices.)
6014Using this index, you can access and modify these values
6015through <a href="#lua_getlocal"><code>lua_getlocal</code></a> and <a href="#lua_setlocal"><code>lua_setlocal</code></a>.
6016This field is only meaningful during a
6017call hook, denoting the first parameter,
6018or a return hook, denoting the first value being returned.
6019(For call hooks, this value is always 1.)
6020</li>
6021
6022<li><b><code>ntransfer</code>: </b>
6023The number of values being transferred (see previous item).
6024(For calls of Lua functions,
6025this value is always equal to <code>nparams</code>.)
6026</li>
6027
6028</ul>
6029
6030
6031
6032
6033<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
6034<span class="apii">[-0, +0, &ndash;]</span>
6035<pre>lua_Hook lua_gethook (lua_State *L);</pre>
6036
6037<p>
6038Returns the current hook function.
6039
6040
6041
6042
6043
6044<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
6045<span class="apii">[-0, +0, &ndash;]</span>
6046<pre>int lua_gethookcount (lua_State *L);</pre>
6047
6048<p>
6049Returns the current hook count.
6050
6051
6052
6053
6054
6055<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
6056<span class="apii">[-0, +0, &ndash;]</span>
6057<pre>int lua_gethookmask (lua_State *L);</pre>
6058
6059<p>
6060Returns the current hook mask.
6061
6062
6063
6064
6065
6066<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
6067<span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
6068<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
6069
6070<p>
6071Gets information about a specific function or function invocation.
6072
6073
6074<p>
6075To get information about a function invocation,
6076the parameter <code>ar</code> must be a valid activation record that was
6077filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6078given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6079
6080
6081<p>
6082To get information about a function, you push it onto the stack
6083and start the <code>what</code> string with the character '<code>&gt;</code>'.
6084(In that case,
6085<code>lua_getinfo</code> pops the function from the top of the stack.)
6086For instance, to know in which line a function <code>f</code> was defined,
6087you can write the following code:
6088
6089<pre>
6090     lua_Debug ar;
6091     lua_getglobal(L, "f");  /* get global 'f' */
6092     lua_getinfo(L, "&gt;S", &amp;ar);
6093     printf("%d\n", ar.linedefined);
6094</pre>
6095
6096<p>
6097Each character in the string <code>what</code>
6098selects some fields of the structure <code>ar</code> to be filled or
6099a value to be pushed on the stack:
6100
6101<ul>
6102
6103<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
6104</li>
6105
6106<li><b>'<code>S</code>': </b>
6107fills in the fields <code>source</code>, <code>short_src</code>,
6108<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
6109</li>
6110
6111<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
6112</li>
6113
6114<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
6115</li>
6116
6117<li><b>'<code>u</code>': </b> fills in the fields
6118<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
6119</li>
6120
6121<li><b>'<code>f</code>': </b>
6122pushes onto the stack the function that is
6123running at the given level;
6124</li>
6125
6126<li><b>'<code>L</code>': </b>
6127pushes onto the stack a table whose indices are the
6128numbers of the lines that are valid on the function.
6129(A <em>valid line</em> is a line with some associated code,
6130that is, a line where you can put a break point.
6131Non-valid lines include empty lines and comments.)
6132
6133
6134<p>
6135If this option is given together with option '<code>f</code>',
6136its table is pushed after the function.
6137
6138
6139<p>
6140This is the only option that can raise a memory error.
6141</li>
6142
6143</ul>
6144
6145<p>
6146This function returns 0 to signal an invalid option in <code>what</code>;
6147even then the valid options are handled correctly.
6148
6149
6150
6151
6152
6153<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
6154<span class="apii">[-0, +(0|1), &ndash;]</span>
6155<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6156
6157<p>
6158Gets information about a local variable or a temporary value
6159of a given activation record or a given function.
6160
6161
6162<p>
6163In the first case,
6164the parameter <code>ar</code> must be a valid activation record that was
6165filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6166given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6167The index <code>n</code> selects which local variable to inspect;
6168see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
6169and names.
6170
6171
6172<p>
6173<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
6174and returns its name.
6175
6176
6177<p>
6178In the second case, <code>ar</code> must be <code>NULL</code> and the function
6179to be inspected must be on the top of the stack.
6180In this case, only parameters of Lua functions are visible
6181(as there is no information about what variables are active)
6182and no values are pushed onto the stack.
6183
6184
6185<p>
6186Returns <code>NULL</code> (and pushes nothing)
6187when the index is greater than
6188the number of active local variables.
6189
6190
6191
6192
6193
6194<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
6195<span class="apii">[-0, +0, &ndash;]</span>
6196<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
6197
6198<p>
6199Gets information about the interpreter runtime stack.
6200
6201
6202<p>
6203This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
6204an identification of the <em>activation record</em>
6205of the function executing at a given level.
6206Level&nbsp;0 is the current running function,
6207whereas level <em>n+1</em> is the function that has called level <em>n</em>
6208(except for tail calls, which do not count in the stack).
6209When called with a level greater than the stack depth,
6210<a href="#lua_getstack"><code>lua_getstack</code></a> returns 0;
6211otherwise it returns 1.
6212
6213
6214
6215
6216
6217<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
6218<span class="apii">[-0, +(0|1), &ndash;]</span>
6219<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
6220
6221<p>
6222Gets information about the <code>n</code>-th upvalue
6223of the closure at index <code>funcindex</code>.
6224It pushes the upvalue's value onto the stack
6225and returns its name.
6226Returns <code>NULL</code> (and pushes nothing)
6227when the index <code>n</code> is greater than the number of upvalues.
6228
6229
6230<p>
6231See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
6232
6233
6234
6235
6236
6237<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
6238<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
6239
6240<p>
6241Type for debugging hook functions.
6242
6243
6244<p>
6245Whenever a hook is called, its <code>ar</code> argument has its field
6246<code>event</code> set to the specific event that triggered the hook.
6247Lua identifies these events with the following constants:
6248<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
6249<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
6250and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
6251Moreover, for line events, the field <code>currentline</code> is also set.
6252To get the value of any other field in <code>ar</code>,
6253the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
6254
6255
6256<p>
6257For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
6258the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
6259in this case, there will be no corresponding return event.
6260
6261
6262<p>
6263While Lua is running a hook, it disables other calls to hooks.
6264Therefore, if a hook calls back Lua to execute a function or a chunk,
6265this execution occurs without any calls to hooks.
6266
6267
6268<p>
6269Hook functions cannot have continuations,
6270that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
6271<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>.
6272
6273
6274<p>
6275Hook functions can yield under the following conditions:
6276Only count and line events can yield;
6277to yield, a hook function must finish its execution
6278calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
6279(that is, with no values).
6280
6281
6282
6283
6284
6285<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
6286<span class="apii">[-0, +0, &ndash;]</span>
6287<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
6288
6289<p>
6290Sets the debugging hook function.
6291
6292
6293<p>
6294Argument <code>f</code> is the hook function.
6295<code>mask</code> specifies on which events the hook will be called:
6296it is formed by a bitwise OR of the constants
6297<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
6298<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
6299<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
6300and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
6301The <code>count</code> argument is only meaningful when the mask
6302includes <code>LUA_MASKCOUNT</code>.
6303For each event, the hook is called as explained below:
6304
6305<ul>
6306
6307<li><b>The call hook: </b> is called when the interpreter calls a function.
6308The hook is called just after Lua enters the new function.
6309</li>
6310
6311<li><b>The return hook: </b> is called when the interpreter returns from a function.
6312The hook is called just before Lua leaves the function.
6313</li>
6314
6315<li><b>The line hook: </b> is called when the interpreter is about to
6316start the execution of a new line of code,
6317or when it jumps back in the code (even to the same line).
6318This event only happens while Lua is executing a Lua function.
6319</li>
6320
6321<li><b>The count hook: </b> is called after the interpreter executes every
6322<code>count</code> instructions.
6323This event only happens while Lua is executing a Lua function.
6324</li>
6325
6326</ul>
6327
6328<p>
6329Hooks are disabled by setting <code>mask</code> to zero.
6330
6331
6332
6333
6334
6335<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
6336<span class="apii">[-(0|1), +0, &ndash;]</span>
6337<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6338
6339<p>
6340Sets the value of a local variable of a given activation record.
6341It assigns the value on the top of the stack
6342to the variable and returns its name.
6343It also pops the value from the stack.
6344
6345
6346<p>
6347Returns <code>NULL</code> (and pops nothing)
6348when the index is greater than
6349the number of active local variables.
6350
6351
6352<p>
6353Parameters <code>ar</code> and <code>n</code> are as in the function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
6354
6355
6356
6357
6358
6359<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
6360<span class="apii">[-(0|1), +0, &ndash;]</span>
6361<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
6362
6363<p>
6364Sets the value of a closure's upvalue.
6365It assigns the value on the top of the stack
6366to the upvalue and returns its name.
6367It also pops the value from the stack.
6368
6369
6370<p>
6371Returns <code>NULL</code> (and pops nothing)
6372when the index <code>n</code> is greater than the number of upvalues.
6373
6374
6375<p>
6376Parameters <code>funcindex</code> and <code>n</code> are as in
6377the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
6378
6379
6380
6381
6382
6383<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
6384<span class="apii">[-0, +0, &ndash;]</span>
6385<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
6386
6387<p>
6388Returns a unique identifier for the upvalue numbered <code>n</code>
6389from the closure at index <code>funcindex</code>.
6390
6391
6392<p>
6393These unique identifiers allow a program to check whether different
6394closures share upvalues.
6395Lua closures that share an upvalue
6396(that is, that access a same external local variable)
6397will return identical ids for those upvalue indices.
6398
6399
6400<p>
6401Parameters <code>funcindex</code> and <code>n</code> are as in
6402the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
6403but <code>n</code> cannot be greater than the number of upvalues.
6404
6405
6406
6407
6408
6409<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
6410<span class="apii">[-0, +0, &ndash;]</span>
6411<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
6412                                    int funcindex2, int n2);</pre>
6413
6414<p>
6415Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
6416refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
6417
6418
6419
6420
6421
6422
6423
6424<h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
6425
6426
6427
6428<p>
6429
6430The <em>auxiliary library</em> provides several convenient functions
6431to interface C with Lua.
6432While the basic API provides the primitive functions for all
6433interactions between C and Lua,
6434the auxiliary library provides higher-level functions for some
6435common tasks.
6436
6437
6438<p>
6439All functions and types from the auxiliary library
6440are defined in header file <code>lauxlib.h</code> and
6441have a prefix <code>luaL_</code>.
6442
6443
6444<p>
6445All functions in the auxiliary library are built on
6446top of the basic API,
6447and so they provide nothing that cannot be done with that API.
6448Nevertheless, the use of the auxiliary library ensures
6449more consistency to your code.
6450
6451
6452<p>
6453Several functions in the auxiliary library use internally some
6454extra stack slots.
6455When a function in the auxiliary library uses less than five slots,
6456it does not check the stack size;
6457it simply assumes that there are enough slots.
6458
6459
6460<p>
6461Several functions in the auxiliary library are used to
6462check C&nbsp;function arguments.
6463Because the error message is formatted for arguments
6464(e.g., "<code>bad argument #1</code>"),
6465you should not use these functions for other stack values.
6466
6467
6468<p>
6469Functions called <code>luaL_check*</code>
6470always raise an error if the check is not satisfied.
6471
6472
6473
6474
6475
6476<h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
6477
6478<p>
6479Here we list all functions and types from the auxiliary library
6480in alphabetical order.
6481
6482
6483
6484<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
6485<span class="apii">[-?, +?, <em>m</em>]</span>
6486<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
6487
6488<p>
6489Adds the byte <code>c</code> to the buffer <code>B</code>
6490(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6491
6492
6493
6494
6495
6496<hr><h3><a name="luaL_addgsub"><code>luaL_addgsub</code></a></h3><p>
6497<span class="apii">[-0, +0, <em>m</em>]</span>
6498<pre>const void luaL_addgsub (luaL_Buffer *B, const char *s,
6499                         const char *p, const char *r);</pre>
6500
6501<p>
6502Adds a copy of the string <code>s</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>),
6503replacing any occurrence of the string <code>p</code>
6504with the string <code>r</code>.
6505
6506
6507
6508
6509
6510<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
6511<span class="apii">[-?, +?, <em>m</em>]</span>
6512<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
6513
6514<p>
6515Adds the string pointed to by <code>s</code> with length <code>l</code> to
6516the buffer <code>B</code>
6517(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6518The string can contain embedded zeros.
6519
6520
6521
6522
6523
6524<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
6525<span class="apii">[-?, +?, &ndash;]</span>
6526<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
6527
6528<p>
6529Adds to the buffer <code>B</code>
6530a string of length <code>n</code> previously copied to the
6531buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
6532
6533
6534
6535
6536
6537<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
6538<span class="apii">[-?, +?, <em>m</em>]</span>
6539<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
6540
6541<p>
6542Adds the zero-terminated string pointed to by <code>s</code>
6543to the buffer <code>B</code>
6544(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6545
6546
6547
6548
6549
6550<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
6551<span class="apii">[-1, +?, <em>m</em>]</span>
6552<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
6553
6554<p>
6555Adds the value on the top of the stack
6556to the buffer <code>B</code>
6557(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6558Pops the value.
6559
6560
6561<p>
6562This is the only function on string buffers that can (and must)
6563be called with an extra element on the stack,
6564which is the value to be added to the buffer.
6565
6566
6567
6568
6569
6570<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
6571<span class="apii">[-0, +0, <em>v</em>]</span>
6572<pre>void luaL_argcheck (lua_State *L,
6573                    int cond,
6574                    int arg,
6575                    const char *extramsg);</pre>
6576
6577<p>
6578Checks whether <code>cond</code> is true.
6579If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
6580
6581
6582
6583
6584
6585<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
6586<span class="apii">[-0, +0, <em>v</em>]</span>
6587<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
6588
6589<p>
6590Raises an error reporting a problem with argument <code>arg</code>
6591of the C&nbsp;function that called it,
6592using a standard message
6593that includes <code>extramsg</code> as a comment:
6594
6595<pre>
6596     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
6597</pre><p>
6598This function never returns.
6599
6600
6601
6602
6603
6604<hr><h3><a name="luaL_argexpected"><code>luaL_argexpected</code></a></h3><p>
6605<span class="apii">[-0, +0, <em>v</em>]</span>
6606<pre>void luaL_argexpected (lua_State *L,
6607                       int cond,
6608                       int arg,
6609                       const char *tname);</pre>
6610
6611<p>
6612Checks whether <code>cond</code> is true.
6613If it is not, raises an error about the type of the argument <code>arg</code>
6614with a standard message (see <a href="#luaL_typeerror"><code>luaL_typeerror</code></a>).
6615
6616
6617
6618
6619
6620<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
6621<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
6622
6623<p>
6624Type for a <em>string buffer</em>.
6625
6626
6627<p>
6628A string buffer allows C&nbsp;code to build Lua strings piecemeal.
6629Its pattern of use is as follows:
6630
6631<ul>
6632
6633<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6634
6635<li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6636
6637<li>
6638Then add string pieces to the buffer calling any of
6639the <code>luaL_add*</code> functions.
6640</li>
6641
6642<li>
6643Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6644This call leaves the final string on the top of the stack.
6645</li>
6646
6647</ul>
6648
6649<p>
6650If you know beforehand the maximum size of the resulting string,
6651you can use the buffer like this:
6652
6653<ul>
6654
6655<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6656
6657<li>Then initialize it and preallocate a space of
6658size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6659
6660<li>Then produce the string into that space.</li>
6661
6662<li>
6663Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6664where <code>sz</code> is the total size of the resulting string
6665copied into that space (which may be less than or
6666equal to the preallocated size).
6667</li>
6668
6669</ul>
6670
6671<p>
6672During its normal operation,
6673a string buffer uses a variable number of stack slots.
6674So, while using a buffer, you cannot assume that you know where
6675the top of the stack is.
6676You can use the stack between successive calls to buffer operations
6677as long as that use is balanced;
6678that is,
6679when you call a buffer operation,
6680the stack is at the same level
6681it was immediately after the previous buffer operation.
6682(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6683After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>,
6684the stack is back to its level when the buffer was initialized,
6685plus the final string on its top.
6686
6687
6688
6689
6690
6691<hr><h3><a name="luaL_buffaddr"><code>luaL_buffaddr</code></a></h3><p>
6692<span class="apii">[-0, +0, &ndash;]</span>
6693<pre>char *luaL_buffaddr (luaL_Buffer *B);</pre>
6694
6695<p>
6696Returns the address of the current content of buffer <code>B</code>
6697(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6698Note that any addition to the buffer may invalidate this address.
6699
6700
6701
6702
6703
6704<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6705<span class="apii">[-0, +0, &ndash;]</span>
6706<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6707
6708<p>
6709Initializes a buffer <code>B</code>
6710(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6711This function does not allocate any space;
6712the buffer must be declared as a variable.
6713
6714
6715
6716
6717
6718<hr><h3><a name="luaL_bufflen"><code>luaL_bufflen</code></a></h3><p>
6719<span class="apii">[-0, +0, &ndash;]</span>
6720<pre>size_t luaL_bufflen (luaL_Buffer *B);</pre>
6721
6722<p>
6723Returns the length of the current content of buffer <code>B</code>
6724(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6725
6726
6727
6728
6729
6730<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6731<span class="apii">[-?, +?, <em>m</em>]</span>
6732<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6733
6734<p>
6735Equivalent to the sequence
6736<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6737
6738
6739
6740
6741
6742<hr><h3><a name="luaL_buffsub"><code>luaL_buffsub</code></a></h3><p>
6743<span class="apii">[-0, +0, &ndash;]</span>
6744<pre>void luaL_buffsub (luaL_Buffer *B, int n);</pre>
6745
6746<p>
6747Removes <code>n</code> bytes from the the buffer <code>B</code>
6748(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6749The buffer must have at least that many bytes.
6750
6751
6752
6753
6754
6755<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6756<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6757<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6758
6759<p>
6760Calls a metamethod.
6761
6762
6763<p>
6764If the object at index <code>obj</code> has a metatable and this
6765metatable has a field <code>e</code>,
6766this function calls this field passing the object as its only argument.
6767In this case this function returns true and pushes onto the
6768stack the value returned by the call.
6769If there is no metatable or no metamethod,
6770this function returns false without pushing any value on the stack.
6771
6772
6773
6774
6775
6776<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6777<span class="apii">[-0, +0, <em>v</em>]</span>
6778<pre>void luaL_checkany (lua_State *L, int arg);</pre>
6779
6780<p>
6781Checks whether the function has an argument
6782of any type (including <b>nil</b>) at position <code>arg</code>.
6783
6784
6785
6786
6787
6788<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6789<span class="apii">[-0, +0, <em>v</em>]</span>
6790<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6791
6792<p>
6793Checks whether the function argument <code>arg</code> is an integer
6794(or can be converted to an integer)
6795and returns this integer.
6796
6797
6798
6799
6800
6801<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6802<span class="apii">[-0, +0, <em>v</em>]</span>
6803<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6804
6805<p>
6806Checks whether the function argument <code>arg</code> is a string
6807and returns this string;
6808if <code>l</code> is not <code>NULL</code> fills its referent
6809with the string's length.
6810
6811
6812<p>
6813This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6814so all conversions and caveats of that function apply here.
6815
6816
6817
6818
6819
6820<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6821<span class="apii">[-0, +0, <em>v</em>]</span>
6822<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6823
6824<p>
6825Checks whether the function argument <code>arg</code> is a number
6826and returns this number converted to a <code>lua_Number</code>.
6827
6828
6829
6830
6831
6832<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6833<span class="apii">[-0, +0, <em>v</em>]</span>
6834<pre>int luaL_checkoption (lua_State *L,
6835                      int arg,
6836                      const char *def,
6837                      const char *const lst[]);</pre>
6838
6839<p>
6840Checks whether the function argument <code>arg</code> is a string and
6841searches for this string in the array <code>lst</code>
6842(which must be NULL-terminated).
6843Returns the index in the array where the string was found.
6844Raises an error if the argument is not a string or
6845if the string cannot be found.
6846
6847
6848<p>
6849If <code>def</code> is not <code>NULL</code>,
6850the function uses <code>def</code> as a default value when
6851there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6852
6853
6854<p>
6855This is a useful function for mapping strings to C&nbsp;enums.
6856(The usual convention in Lua libraries is
6857to use strings instead of numbers to select options.)
6858
6859
6860
6861
6862
6863<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6864<span class="apii">[-0, +0, <em>v</em>]</span>
6865<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6866
6867<p>
6868Grows the stack size to <code>top + sz</code> elements,
6869raising an error if the stack cannot grow to that size.
6870<code>msg</code> is an additional text to go into the error message
6871(or <code>NULL</code> for no additional text).
6872
6873
6874
6875
6876
6877<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6878<span class="apii">[-0, +0, <em>v</em>]</span>
6879<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6880
6881<p>
6882Checks whether the function argument <code>arg</code> is a string
6883and returns this string.
6884
6885
6886<p>
6887This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6888so all conversions and caveats of that function apply here.
6889
6890
6891
6892
6893
6894<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6895<span class="apii">[-0, +0, <em>v</em>]</span>
6896<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6897
6898<p>
6899Checks whether the function argument <code>arg</code> has type <code>t</code>.
6900See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6901
6902
6903
6904
6905
6906<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6907<span class="apii">[-0, +0, <em>v</em>]</span>
6908<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6909
6910<p>
6911Checks whether the function argument <code>arg</code> is a userdata
6912of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6913returns the userdata's memory-block address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6914
6915
6916
6917
6918
6919<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6920<span class="apii">[-0, +0, <em>v</em>]</span>
6921<pre>void luaL_checkversion (lua_State *L);</pre>
6922
6923<p>
6924Checks whether the code making the call and the Lua library being called
6925are using the same version of Lua and the same numeric types.
6926
6927
6928
6929
6930
6931<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6932<span class="apii">[-0, +?, <em>m</em>]</span>
6933<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6934
6935<p>
6936Loads and runs the given file.
6937It is defined as the following macro:
6938
6939<pre>
6940     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6941</pre><p>
6942It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6943or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6944
6945
6946
6947
6948
6949<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6950<span class="apii">[-0, +?, &ndash;]</span>
6951<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6952
6953<p>
6954Loads and runs the given string.
6955It is defined as the following macro:
6956
6957<pre>
6958     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6959</pre><p>
6960It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6961or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6962
6963
6964
6965
6966
6967<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6968<span class="apii">[-0, +0, <em>v</em>]</span>
6969<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6970
6971<p>
6972Raises an error.
6973The error message format is given by <code>fmt</code>
6974plus any extra arguments,
6975following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6976It also adds at the beginning of the message the file name and
6977the line number where the error occurred,
6978if this information is available.
6979
6980
6981<p>
6982This function never returns,
6983but it is an idiom to use it in C&nbsp;functions
6984as <code>return luaL_error(<em>args</em>)</code>.
6985
6986
6987
6988
6989
6990<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
6991<span class="apii">[-0, +3, <em>m</em>]</span>
6992<pre>int luaL_execresult (lua_State *L, int stat);</pre>
6993
6994<p>
6995This function produces the return values for
6996process-related functions in the standard library
6997(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
6998
6999
7000
7001
7002
7003<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
7004<span class="apii">[-0, +(1|3), <em>m</em>]</span>
7005<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
7006
7007<p>
7008This function produces the return values for
7009file-related functions in the standard library
7010(<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.).
7011
7012
7013
7014
7015
7016<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
7017<span class="apii">[-0, +(0|1), <em>m</em>]</span>
7018<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
7019
7020<p>
7021Pushes onto the stack the field <code>e</code> from the metatable
7022of the object at index <code>obj</code> and returns the type of the pushed value.
7023If the object does not have a metatable,
7024or if the metatable does not have this field,
7025pushes nothing and returns <code>LUA_TNIL</code>.
7026
7027
7028
7029
7030
7031<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
7032<span class="apii">[-0, +1, <em>m</em>]</span>
7033<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
7034
7035<p>
7036Pushes onto the stack the metatable associated with the name <code>tname</code>
7037in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>),
7038or <b>nil</b> if there is no metatable associated with that name.
7039Returns the type of the pushed value.
7040
7041
7042
7043
7044
7045<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
7046<span class="apii">[-0, +1, <em>e</em>]</span>
7047<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
7048
7049<p>
7050Ensures that the value <code>t[fname]</code>,
7051where <code>t</code> is the value at index <code>idx</code>,
7052is a table,
7053and pushes that table onto the stack.
7054Returns true if it finds a previous table there
7055and false if it creates a new table.
7056
7057
7058
7059
7060
7061<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
7062<span class="apii">[-0, +1, <em>m</em>]</span>
7063<pre>const char *luaL_gsub (lua_State *L,
7064                       const char *s,
7065                       const char *p,
7066                       const char *r);</pre>
7067
7068<p>
7069Creates a copy of string <code>s</code>,
7070replacing any occurrence of the string <code>p</code>
7071with the string <code>r</code>.
7072Pushes the resulting string on the stack and returns it.
7073
7074
7075
7076
7077
7078<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
7079<span class="apii">[-0, +0, <em>e</em>]</span>
7080<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
7081
7082<p>
7083Returns the "length" of the value at the given index
7084as a number;
7085it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
7086Raises an error if the result of the operation is not an integer.
7087(This case can only happen through metamethods.)
7088
7089
7090
7091
7092
7093<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
7094<span class="apii">[-0, +1, &ndash;]</span>
7095<pre>int luaL_loadbuffer (lua_State *L,
7096                     const char *buff,
7097                     size_t sz,
7098                     const char *name);</pre>
7099
7100<p>
7101Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
7102
7103
7104
7105
7106
7107<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
7108<span class="apii">[-0, +1, &ndash;]</span>
7109<pre>int luaL_loadbufferx (lua_State *L,
7110                      const char *buff,
7111                      size_t sz,
7112                      const char *name,
7113                      const char *mode);</pre>
7114
7115<p>
7116Loads a buffer as a Lua chunk.
7117This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
7118buffer pointed to by <code>buff</code> with size <code>sz</code>.
7119
7120
7121<p>
7122This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7123<code>name</code> is the chunk name,
7124used for debug information and error messages.
7125The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7126
7127
7128
7129
7130
7131<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
7132<span class="apii">[-0, +1, <em>m</em>]</span>
7133<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
7134
7135<p>
7136Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
7137
7138
7139
7140
7141
7142<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
7143<span class="apii">[-0, +1, <em>m</em>]</span>
7144<pre>int luaL_loadfilex (lua_State *L, const char *filename,
7145                                            const char *mode);</pre>
7146
7147<p>
7148Loads a file as a Lua chunk.
7149This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
7150named <code>filename</code>.
7151If <code>filename</code> is <code>NULL</code>,
7152then it loads from the standard input.
7153The first line in the file is ignored if it starts with a <code>#</code>.
7154
7155
7156<p>
7157The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7158
7159
7160<p>
7161This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>
7162or <a href="#pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> for file-related errors.
7163
7164
7165<p>
7166As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7167it does not run it.
7168
7169
7170
7171
7172
7173<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
7174<span class="apii">[-0, +1, &ndash;]</span>
7175<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
7176
7177<p>
7178Loads a string as a Lua chunk.
7179This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
7180the zero-terminated string <code>s</code>.
7181
7182
7183<p>
7184This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7185
7186
7187<p>
7188Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7189it does not run it.
7190
7191
7192
7193
7194
7195<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
7196<span class="apii">[-0, +1, <em>m</em>]</span>
7197<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
7198
7199<p>
7200Creates a new table and registers there
7201the functions in the list <code>l</code>.
7202
7203
7204<p>
7205It is implemented as the following macro:
7206
7207<pre>
7208     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
7209</pre><p>
7210The array <code>l</code> must be the actual array,
7211not a pointer to it.
7212
7213
7214
7215
7216
7217<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
7218<span class="apii">[-0, +1, <em>m</em>]</span>
7219<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
7220
7221<p>
7222Creates a new table with a size optimized
7223to store all entries in the array <code>l</code>
7224(but does not actually store them).
7225It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
7226(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
7227
7228
7229<p>
7230It is implemented as a macro.
7231The array <code>l</code> must be the actual array,
7232not a pointer to it.
7233
7234
7235
7236
7237
7238<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
7239<span class="apii">[-0, +1, <em>m</em>]</span>
7240<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
7241
7242<p>
7243If the registry already has the key <code>tname</code>,
7244returns 0.
7245Otherwise,
7246creates a new table to be used as a metatable for userdata,
7247adds to this new table the pair <code>__name = tname</code>,
7248adds to the registry the pair <code>[tname] = new table</code>,
7249and returns 1.
7250
7251
7252<p>
7253In both cases,
7254the function pushes onto the stack the final value associated
7255with <code>tname</code> in the registry.
7256
7257
7258
7259
7260
7261<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
7262<span class="apii">[-0, +0, &ndash;]</span>
7263<pre>lua_State *luaL_newstate (void);</pre>
7264
7265<p>
7266Creates a new Lua state.
7267It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
7268allocator based on the standard&nbsp;C allocation functions
7269and then sets a warning function and a panic function (see <a href="#4.4">&sect;4.4</a>)
7270that print messages to the standard error output.
7271
7272
7273<p>
7274Returns the new state,
7275or <code>NULL</code> if there is a memory allocation error.
7276
7277
7278
7279
7280
7281<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
7282<span class="apii">[-0, +0, <em>e</em>]</span>
7283<pre>void luaL_openlibs (lua_State *L);</pre>
7284
7285<p>
7286Opens all standard Lua libraries into the given state.
7287
7288
7289
7290
7291
7292<hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
7293<span class="apii">[-0, +0, &ndash;]</span>
7294<pre>T luaL_opt (L, func, arg, dflt);</pre>
7295
7296<p>
7297This macro is defined as follows:
7298
7299<pre>
7300     (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
7301</pre><p>
7302In words, if the argument <code>arg</code> is nil or absent,
7303the macro results in the default <code>dflt</code>.
7304Otherwise, it results in the result of calling <code>func</code>
7305with the state <code>L</code> and the argument index <code>arg</code> as
7306arguments.
7307Note that it evaluates the expression <code>dflt</code> only if needed.
7308
7309
7310
7311
7312
7313<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
7314<span class="apii">[-0, +0, <em>v</em>]</span>
7315<pre>lua_Integer luaL_optinteger (lua_State *L,
7316                             int arg,
7317                             lua_Integer d);</pre>
7318
7319<p>
7320If the function argument <code>arg</code> is an integer
7321(or it is convertible to an integer),
7322returns this integer.
7323If this argument is absent or is <b>nil</b>,
7324returns <code>d</code>.
7325Otherwise, raises an error.
7326
7327
7328
7329
7330
7331<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
7332<span class="apii">[-0, +0, <em>v</em>]</span>
7333<pre>const char *luaL_optlstring (lua_State *L,
7334                             int arg,
7335                             const char *d,
7336                             size_t *l);</pre>
7337
7338<p>
7339If the function argument <code>arg</code> is a string,
7340returns this string.
7341If this argument is absent or is <b>nil</b>,
7342returns <code>d</code>.
7343Otherwise, raises an error.
7344
7345
7346<p>
7347If <code>l</code> is not <code>NULL</code>,
7348fills its referent with the result's length.
7349If the result is <code>NULL</code>
7350(only possible when returning <code>d</code> and <code>d == NULL</code>),
7351its length is considered zero.
7352
7353
7354<p>
7355This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
7356so all conversions and caveats of that function apply here.
7357
7358
7359
7360
7361
7362<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
7363<span class="apii">[-0, +0, <em>v</em>]</span>
7364<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
7365
7366<p>
7367If the function argument <code>arg</code> is a number,
7368returns this number as a <code>lua_Number</code>.
7369If this argument is absent or is <b>nil</b>,
7370returns <code>d</code>.
7371Otherwise, raises an error.
7372
7373
7374
7375
7376
7377<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
7378<span class="apii">[-0, +0, <em>v</em>]</span>
7379<pre>const char *luaL_optstring (lua_State *L,
7380                            int arg,
7381                            const char *d);</pre>
7382
7383<p>
7384If the function argument <code>arg</code> is a string,
7385returns this string.
7386If this argument is absent or is <b>nil</b>,
7387returns <code>d</code>.
7388Otherwise, raises an error.
7389
7390
7391
7392
7393
7394<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
7395<span class="apii">[-?, +?, <em>m</em>]</span>
7396<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
7397
7398<p>
7399Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
7400with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
7401
7402
7403
7404
7405
7406<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
7407<span class="apii">[-?, +?, <em>m</em>]</span>
7408<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
7409
7410<p>
7411Returns an address to a space of size <code>sz</code>
7412where you can copy a string to be added to buffer <code>B</code>
7413(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
7414After copying the string into this space you must call
7415<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
7416it to the buffer.
7417
7418
7419
7420
7421
7422<hr><h3><a name="luaL_pushfail"><code>luaL_pushfail</code></a></h3><p>
7423<span class="apii">[-0, +1, &ndash;]</span>
7424<pre>void luaL_pushfail (lua_State *L);</pre>
7425
7426<p>
7427Pushes the <b>fail</b> value onto the stack (see <a href="#6">&sect;6</a>).
7428
7429
7430
7431
7432
7433<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
7434<span class="apii">[-?, +1, <em>m</em>]</span>
7435<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
7436
7437<p>
7438Finishes the use of buffer <code>B</code> leaving the final string on
7439the top of the stack.
7440
7441
7442
7443
7444
7445<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
7446<span class="apii">[-?, +1, <em>m</em>]</span>
7447<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
7448
7449<p>
7450Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
7451
7452
7453
7454
7455
7456<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
7457<span class="apii">[-1, +0, <em>m</em>]</span>
7458<pre>int luaL_ref (lua_State *L, int t);</pre>
7459
7460<p>
7461Creates and returns a <em>reference</em>,
7462in the table at index <code>t</code>,
7463for the object on the top of the stack (and pops the object).
7464
7465
7466<p>
7467A reference is a unique integer key.
7468As long as you do not manually add integer keys into the table <code>t</code>,
7469<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
7470You can retrieve an object referred by the reference <code>r</code>
7471by calling <code>lua_rawgeti(L, t, r)</code>.
7472The function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference.
7473
7474
7475<p>
7476If the object on the top of the stack is <b>nil</b>,
7477<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
7478The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
7479from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
7480
7481
7482
7483
7484
7485<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
7486<pre>typedef struct luaL_Reg {
7487  const char *name;
7488  lua_CFunction func;
7489} luaL_Reg;</pre>
7490
7491<p>
7492Type for arrays of functions to be registered by
7493<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
7494<code>name</code> is the function name and <code>func</code> is a pointer to
7495the function.
7496Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
7497in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
7498
7499
7500
7501
7502
7503<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
7504<span class="apii">[-0, +1, <em>e</em>]</span>
7505<pre>void luaL_requiref (lua_State *L, const char *modname,
7506                    lua_CFunction openf, int glb);</pre>
7507
7508<p>
7509If <code>package.loaded[modname]</code> is not true,
7510calls the function <code>openf</code> with the string <code>modname</code> as an argument
7511and sets the call result to <code>package.loaded[modname]</code>,
7512as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
7513
7514
7515<p>
7516If <code>glb</code> is true,
7517also stores the module into the global <code>modname</code>.
7518
7519
7520<p>
7521Leaves a copy of the module on the stack.
7522
7523
7524
7525
7526
7527<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
7528<span class="apii">[-nup, +0, <em>m</em>]</span>
7529<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
7530
7531<p>
7532Registers all functions in the array <code>l</code>
7533(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
7534(below optional upvalues, see next).
7535
7536
7537<p>
7538When <code>nup</code> is not zero,
7539all functions are created with <code>nup</code> upvalues,
7540initialized with copies of the <code>nup</code> values
7541previously pushed on the stack
7542on top of the library table.
7543These values are popped from the stack after the registration.
7544
7545
7546
7547
7548
7549<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
7550<span class="apii">[-0, +0, &ndash;]</span>
7551<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
7552
7553<p>
7554Sets the metatable of the object on the top of the stack
7555as the metatable associated with name <code>tname</code>
7556in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7557
7558
7559
7560
7561
7562<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
7563<pre>typedef struct luaL_Stream {
7564  FILE *f;
7565  lua_CFunction closef;
7566} luaL_Stream;</pre>
7567
7568<p>
7569The standard representation for file handles
7570used by the standard I/O library.
7571
7572
7573<p>
7574A file handle is implemented as a full userdata,
7575with a metatable called <code>LUA_FILEHANDLE</code>
7576(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
7577The metatable is created by the I/O library
7578(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7579
7580
7581<p>
7582This userdata must start with the structure <code>luaL_Stream</code>;
7583it can contain other data after this initial structure.
7584The field <code>f</code> points to the corresponding C stream
7585(or it can be <code>NULL</code> to indicate an incompletely created handle).
7586The field <code>closef</code> points to a Lua function
7587that will be called to close the stream
7588when the handle is closed or collected;
7589this function receives the file handle as its sole argument and
7590must return either a true value, in case of success,
7591or a false value plus an error message, in case of error.
7592Once Lua calls this field,
7593it changes the field value to <code>NULL</code>
7594to signal that the handle is closed.
7595
7596
7597
7598
7599
7600<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
7601<span class="apii">[-0, +0, <em>m</em>]</span>
7602<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
7603
7604<p>
7605This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
7606except that, when the test fails,
7607it returns <code>NULL</code> instead of raising an error.
7608
7609
7610
7611
7612
7613<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
7614<span class="apii">[-0, +1, <em>e</em>]</span>
7615<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
7616
7617<p>
7618Converts any Lua value at the given index to a C&nbsp;string
7619in a reasonable format.
7620The resulting string is pushed onto the stack and also
7621returned by the function (see <a href="#4.1.3">&sect;4.1.3</a>).
7622If <code>len</code> is not <code>NULL</code>,
7623the function also sets <code>*len</code> with the string length.
7624
7625
7626<p>
7627If the value has a metatable with a <code>__tostring</code> field,
7628then <code>luaL_tolstring</code> calls the corresponding metamethod
7629with the value as argument,
7630and uses the result of the call as its result.
7631
7632
7633
7634
7635
7636<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
7637<span class="apii">[-0, +1, <em>m</em>]</span>
7638<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
7639                     int level);</pre>
7640
7641<p>
7642Creates and pushes a traceback of the stack <code>L1</code>.
7643If <code>msg</code> is not <code>NULL</code>, it is appended
7644at the beginning of the traceback.
7645The <code>level</code> parameter tells at which level
7646to start the traceback.
7647
7648
7649
7650
7651
7652<hr><h3><a name="luaL_typeerror"><code>luaL_typeerror</code></a></h3><p>
7653<span class="apii">[-0, +0, <em>v</em>]</span>
7654<pre>const char *luaL_typeerror (lua_State *L,
7655                                      int arg,
7656                                      const char *tname);</pre>
7657
7658<p>
7659Raises a type error for the argument <code>arg</code>
7660of the C&nbsp;function that called it,
7661using a standard message;
7662<code>tname</code> is a "name" for the expected type.
7663This function never returns.
7664
7665
7666
7667
7668
7669<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
7670<span class="apii">[-0, +0, &ndash;]</span>
7671<pre>const char *luaL_typename (lua_State *L, int index);</pre>
7672
7673<p>
7674Returns the name of the type of the value at the given index.
7675
7676
7677
7678
7679
7680<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
7681<span class="apii">[-0, +0, &ndash;]</span>
7682<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
7683
7684<p>
7685Releases the reference <code>ref</code> from the table at index <code>t</code>
7686(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
7687The entry is removed from the table,
7688so that the referred object can be collected.
7689The reference <code>ref</code> is also freed to be used again.
7690
7691
7692<p>
7693If <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>,
7694<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
7695
7696
7697
7698
7699
7700<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
7701<span class="apii">[-0, +1, <em>m</em>]</span>
7702<pre>void luaL_where (lua_State *L, int lvl);</pre>
7703
7704<p>
7705Pushes onto the stack a string identifying the current position
7706of the control at level <code>lvl</code> in the call stack.
7707Typically this string has the following format:
7708
7709<pre>
7710     <em>chunkname</em>:<em>currentline</em>:
7711</pre><p>
7712Level&nbsp;0 is the running function,
7713level&nbsp;1 is the function that called the running function,
7714etc.
7715
7716
7717<p>
7718This function is used to build a prefix for error messages.
7719
7720
7721
7722
7723
7724
7725
7726<h1>6 &ndash; <a name="6">The Standard Libraries</a></h1>
7727
7728
7729
7730<p>
7731The standard Lua libraries provide useful functions
7732that are implemented in&nbsp;C through the C&nbsp;API.
7733Some of these functions provide essential services to the language
7734(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7735others provide access to outside services (e.g., I/O);
7736and others could be implemented in Lua itself,
7737but that for different reasons
7738deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7739
7740
7741<p>
7742All libraries are implemented through the official C&nbsp;API
7743and are provided as separate C&nbsp;modules.
7744Unless otherwise noted,
7745these library functions do not adjust its number of arguments
7746to its expected parameters.
7747For instance, a function documented as <code>foo(arg)</code>
7748should not be called without an argument.
7749
7750
7751<p>
7752The notation <b>fail</b> means a false value representing
7753some kind of failure.
7754(Currently, <b>fail</b> is equal to <b>nil</b>,
7755but that may change in future versions.
7756The recommendation is to always test the success of these functions
7757with <code>(not status)</code>, instead of <code>(status == nil)</code>.)
7758
7759
7760<p>
7761Currently, Lua has the following standard libraries:
7762
7763<ul>
7764
7765<li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7766
7767<li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7768
7769<li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7770
7771<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7772
7773<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7774
7775<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7776
7777<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7778
7779<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7780
7781<li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7782
7783<li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7784
7785</ul><p>
7786Except for the basic and the package libraries,
7787each library provides all its functions as fields of a global table
7788or as methods of its objects.
7789
7790
7791<p>
7792To have access to these libraries,
7793the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7794which opens all standard libraries.
7795Alternatively,
7796the host program can open them individually by using
7797<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7798<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7799<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7800<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7801<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7802<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF-8 library),
7803<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7804<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7805<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7806<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7807and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7808These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7809
7810
7811
7812
7813
7814<h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7815
7816<p>
7817The basic library provides core functions to Lua.
7818If you do not include this library in your application,
7819you should check carefully whether you need to provide
7820implementations for some of its facilities.
7821
7822
7823<p>
7824<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7825
7826
7827<p>
7828Raises an error if
7829the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7830otherwise, returns all its arguments.
7831In case of error,
7832<code>message</code> is the error object;
7833when absent, it defaults to "<code>assertion failed!</code>"
7834
7835
7836
7837
7838<p>
7839<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7840
7841
7842<p>
7843This function is a generic interface to the garbage collector.
7844It performs different functions according to its first argument, <code>opt</code>:
7845
7846<ul>
7847
7848<li><b>"<code>collect</code>": </b>
7849Performs a full garbage-collection cycle.
7850This is the default option.
7851</li>
7852
7853<li><b>"<code>stop</code>": </b>
7854Stops automatic execution of the garbage collector.
7855The collector will run only when explicitly invoked,
7856until a call to restart it.
7857</li>
7858
7859<li><b>"<code>restart</code>": </b>
7860Restarts automatic execution of the garbage collector.
7861</li>
7862
7863<li><b>"<code>count</code>": </b>
7864Returns the total memory in use by Lua in Kbytes.
7865The value has a fractional part,
7866so that it multiplied by 1024
7867gives the exact number of bytes in use by Lua.
7868</li>
7869
7870<li><b>"<code>step</code>": </b>
7871Performs a garbage-collection step.
7872The step "size" is controlled by <code>arg</code>.
7873With a zero value,
7874the collector will perform one basic (indivisible) step.
7875For non-zero values,
7876the collector will perform as if that amount of memory
7877(in Kbytes) had been allocated by Lua.
7878Returns <b>true</b> if the step finished a collection cycle.
7879</li>
7880
7881<li><b>"<code>isrunning</code>": </b>
7882Returns a boolean that tells whether the collector is running
7883(i.e., not stopped).
7884</li>
7885
7886<li><b>"<code>incremental</code>": </b>
7887Change the collector mode to incremental.
7888This option can be followed by three numbers:
7889the garbage-collector pause,
7890the step multiplier,
7891and the step size (see <a href="#2.5.1">&sect;2.5.1</a>).
7892A zero means to not change that value.
7893</li>
7894
7895<li><b>"<code>generational</code>": </b>
7896Change the collector mode to generational.
7897This option can be followed by two numbers:
7898the garbage-collector minor multiplier
7899and the major multiplier (see <a href="#2.5.2">&sect;2.5.2</a>).
7900A zero means to not change that value.
7901</li>
7902
7903</ul><p>
7904See <a href="#2.5">&sect;2.5</a> for more details about garbage collection
7905and some of these options.
7906
7907
7908
7909
7910<p>
7911<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7912Opens the named file and executes its content as a Lua chunk.
7913When called without arguments,
7914<code>dofile</code> executes the content of the standard input (<code>stdin</code>).
7915Returns all values returned by the chunk.
7916In case of errors, <code>dofile</code> propagates the error
7917to its caller.
7918(That is, <code>dofile</code> does not run in protected mode.)
7919
7920
7921
7922
7923<p>
7924<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7925Raises an error (see <a href="#2.3">&sect;2.3</a>) with @{message} as the error object.
7926This function never returns.
7927
7928
7929<p>
7930Usually, <code>error</code> adds some information about the error position
7931at the beginning of the message, if the message is a string.
7932The <code>level</code> argument specifies how to get the error position.
7933With level&nbsp;1 (the default), the error position is where the
7934<code>error</code> function was called.
7935Level&nbsp;2 points the error to where the function
7936that called <code>error</code> was called; and so on.
7937Passing a level&nbsp;0 avoids the addition of error position information
7938to the message.
7939
7940
7941
7942
7943<p>
7944<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7945A global variable (not a function) that
7946holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7947Lua itself does not use this variable;
7948changing its value does not affect any environment,
7949nor vice versa.
7950
7951
7952
7953
7954<p>
7955<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7956
7957
7958<p>
7959If <code>object</code> does not have a metatable, returns <b>nil</b>.
7960Otherwise,
7961if the object's metatable has a <code>__metatable</code> field,
7962returns the associated value.
7963Otherwise, returns the metatable of the given object.
7964
7965
7966
7967
7968<p>
7969<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7970
7971
7972<p>
7973Returns three values (an iterator function, the table <code>t</code>, and 0)
7974so that the construction
7975
7976<pre>
7977     for i,v in ipairs(t) do <em>body</em> end
7978</pre><p>
7979will iterate over the key&ndash;value pairs
7980(<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7981up to the first absent index.
7982
7983
7984
7985
7986<p>
7987<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
7988
7989
7990<p>
7991Loads a chunk.
7992
7993
7994<p>
7995If <code>chunk</code> is a string, the chunk is this string.
7996If <code>chunk</code> is a function,
7997<code>load</code> calls it repeatedly to get the chunk pieces.
7998Each call to <code>chunk</code> must return a string that concatenates
7999with previous results.
8000A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
8001
8002
8003<p>
8004If there are no syntactic errors,
8005<code>load</code> returns the compiled chunk as a function;
8006otherwise, it returns <b>fail</b> plus the error message.
8007
8008
8009<p>
8010When you load a main chunk,
8011the resulting function will always have exactly one upvalue,
8012the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
8013However,
8014when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
8015the resulting function can have an arbitrary number of upvalues,
8016and there is no guarantee that its first upvalue will be
8017the <code>_ENV</code> variable.
8018(A non-main function may not even have an <code>_ENV</code> upvalue.)
8019
8020
8021<p>
8022Regardless, if the resulting function has any upvalues,
8023its first upvalue is set to the value of <code>env</code>,
8024if that parameter is given,
8025or to the value of the global environment.
8026Other upvalues are initialized with <b>nil</b>.
8027All upvalues are fresh, that is,
8028they are not shared with any other function.
8029
8030
8031<p>
8032<code>chunkname</code> is used as the name of the chunk for error messages
8033and debug information (see <a href="#4.7">&sect;4.7</a>).
8034When absent,
8035it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
8036or to "<code>=(load)</code>" otherwise.
8037
8038
8039<p>
8040The string <code>mode</code> controls whether the chunk can be text or binary
8041(that is, a precompiled chunk).
8042It may be the string "<code>b</code>" (only binary chunks),
8043"<code>t</code>" (only text chunks),
8044or "<code>bt</code>" (both binary and text).
8045The default is "<code>bt</code>".
8046
8047
8048<p>
8049It is safe to load malformed binary chunks;
8050<code>load</code> signals an appropriate error.
8051However,
8052Lua does not check the consistency of the code inside binary chunks;
8053running maliciously crafted bytecode can crash the interpreter.
8054
8055
8056
8057
8058<p>
8059<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
8060
8061
8062<p>
8063Similar to <a href="#pdf-load"><code>load</code></a>,
8064but gets the chunk from file <code>filename</code>
8065or from the standard input,
8066if no file name is given.
8067
8068
8069
8070
8071<p>
8072<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
8073
8074
8075<p>
8076Allows a program to traverse all fields of a table.
8077Its first argument is a table and its second argument
8078is an index in this table.
8079A call to <code>next</code> returns the next index of the table
8080and its associated value.
8081When called with <b>nil</b> as its second argument,
8082<code>next</code> returns an initial index
8083and its associated value.
8084When called with the last index,
8085or with <b>nil</b> in an empty table,
8086<code>next</code> returns <b>nil</b>.
8087If the second argument is absent, then it is interpreted as <b>nil</b>.
8088In particular,
8089you can use <code>next(t)</code> to check whether a table is empty.
8090
8091
8092<p>
8093The order in which the indices are enumerated is not specified,
8094<em>even for numeric indices</em>.
8095(To traverse a table in numerical order,
8096use a numerical <b>for</b>.)
8097
8098
8099<p>
8100The behavior of <code>next</code> is undefined if,
8101during the traversal,
8102you assign any value to a non-existent field in the table.
8103You may however modify existing fields.
8104In particular, you may set existing fields to nil.
8105
8106
8107
8108
8109<p>
8110<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
8111
8112
8113<p>
8114If <code>t</code> has a metamethod <code>__pairs</code>,
8115calls it with <code>t</code> as argument and returns the first three
8116results from the call.
8117
8118
8119<p>
8120Otherwise,
8121returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
8122so that the construction
8123
8124<pre>
8125     for k,v in pairs(t) do <em>body</em> end
8126</pre><p>
8127will iterate over all key&ndash;value pairs of table <code>t</code>.
8128
8129
8130<p>
8131See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
8132the table during its traversal.
8133
8134
8135
8136
8137<p>
8138<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
8139
8140
8141<p>
8142Calls the function <code>f</code> with
8143the given arguments in <em>protected mode</em>.
8144This means that any error inside&nbsp;<code>f</code> is not propagated;
8145instead, <code>pcall</code> catches the error
8146and returns a status code.
8147Its first result is the status code (a boolean),
8148which is true if the call succeeds without errors.
8149In such case, <code>pcall</code> also returns all results from the call,
8150after this first result.
8151In case of any error, <code>pcall</code> returns <b>false</b> plus the error object.
8152Note that errors caught by <code>pcall</code> do not call a message handler.
8153
8154
8155
8156
8157<p>
8158<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
8159Receives any number of arguments
8160and prints their values to <code>stdout</code>,
8161converting each argument to a string
8162following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8163
8164
8165<p>
8166The function <code>print</code> is not intended for formatted output,
8167but only as a quick way to show a value,
8168for instance for debugging.
8169For complete control over the output,
8170use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
8171
8172
8173
8174
8175<p>
8176<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
8177Checks whether <code>v1</code> is equal to <code>v2</code>,
8178without invoking the <code>__eq</code> metamethod.
8179Returns a boolean.
8180
8181
8182
8183
8184<p>
8185<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
8186Gets the real value of <code>table[index]</code>,
8187without using the <code>__index</code> metavalue.
8188<code>table</code> must be a table;
8189<code>index</code> may be any value.
8190
8191
8192
8193
8194<p>
8195<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
8196Returns the length of the object <code>v</code>,
8197which must be a table or a string,
8198without invoking the <code>__len</code> metamethod.
8199Returns an integer.
8200
8201
8202
8203
8204<p>
8205<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
8206Sets the real value of <code>table[index]</code> to <code>value</code>,
8207without using the <code>__newindex</code> metavalue.
8208<code>table</code> must be a table,
8209<code>index</code> any value different from <b>nil</b> and NaN,
8210and <code>value</code> any Lua value.
8211
8212
8213<p>
8214This function returns <code>table</code>.
8215
8216
8217
8218
8219<p>
8220<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
8221
8222
8223<p>
8224If <code>index</code> is a number,
8225returns all arguments after argument number <code>index</code>;
8226a negative number indexes from the end (-1 is the last argument).
8227Otherwise, <code>index</code> must be the string <code>"#"</code>,
8228and <code>select</code> returns the total number of extra arguments it received.
8229
8230
8231
8232
8233<p>
8234<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
8235
8236
8237<p>
8238Sets the metatable for the given table.
8239If <code>metatable</code> is <b>nil</b>,
8240removes the metatable of the given table.
8241If the original metatable has a <code>__metatable</code> field,
8242raises an error.
8243
8244
8245<p>
8246This function returns <code>table</code>.
8247
8248
8249<p>
8250To change the metatable of other types from Lua code,
8251you must use the debug library (<a href="#6.10">&sect;6.10</a>).
8252
8253
8254
8255
8256<p>
8257<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
8258
8259
8260<p>
8261When called with no <code>base</code>,
8262<code>tonumber</code> tries to convert its argument to a number.
8263If the argument is already a number or
8264a string convertible to a number,
8265then <code>tonumber</code> returns this number;
8266otherwise, it returns <b>fail</b>.
8267
8268
8269<p>
8270The conversion of strings can result in integers or floats,
8271according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
8272The string may have leading and trailing spaces and a sign.
8273
8274
8275<p>
8276When called with <code>base</code>,
8277then <code>e</code> must be a string to be interpreted as
8278an integer numeral in that base.
8279The base may be any integer between 2 and 36, inclusive.
8280In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
8281represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
8282with '<code>Z</code>' representing 35.
8283If the string <code>e</code> is not a valid numeral in the given base,
8284the function returns <b>fail</b>.
8285
8286
8287
8288
8289<p>
8290<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
8291
8292
8293<p>
8294Receives a value of any type and
8295converts it to a string in a human-readable format.
8296
8297
8298<p>
8299If the metatable of <code>v</code> has a <code>__tostring</code> field,
8300then <code>tostring</code> calls the corresponding value
8301with <code>v</code> as argument,
8302and uses the result of the call as its result.
8303Otherwise, if the metatable of <code>v</code> has a <code>__name</code> field
8304with a string value,
8305<code>tostring</code> may use that string in its final result.
8306
8307
8308<p>
8309For complete control of how numbers are converted,
8310use <a href="#pdf-string.format"><code>string.format</code></a>.
8311
8312
8313
8314
8315<p>
8316<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
8317
8318
8319<p>
8320Returns the type of its only argument, coded as a string.
8321The possible results of this function are
8322"<code>nil</code>" (a string, not the value <b>nil</b>),
8323"<code>number</code>",
8324"<code>string</code>",
8325"<code>boolean</code>",
8326"<code>table</code>",
8327"<code>function</code>",
8328"<code>thread</code>",
8329and "<code>userdata</code>".
8330
8331
8332
8333
8334<p>
8335<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
8336
8337
8338<p>
8339A global variable (not a function) that
8340holds a string containing the running Lua version.
8341The current value of this variable is "<code>Lua 5.4</code>".
8342
8343
8344
8345
8346<p>
8347<hr><h3><a name="pdf-warn"><code>warn (msg1, &middot;&middot;&middot;)</code></a></h3>
8348
8349
8350<p>
8351Emits a warning with a message composed by the concatenation
8352of all its arguments (which should be strings).
8353
8354
8355<p>
8356By convention,
8357a one-piece message starting with '<code>@</code>'
8358is intended to be a <em>control message</em>,
8359which is a message to the warning system itself.
8360In particular, the standard warning function in Lua
8361recognizes the control messages "<code>@off</code>",
8362to stop the emission of warnings,
8363and "<code>@on</code>", to (re)start the emission;
8364it ignores unknown control messages.
8365
8366
8367
8368
8369<p>
8370<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
8371
8372
8373<p>
8374This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
8375except that it sets a new message handler <code>msgh</code>.
8376
8377
8378
8379
8380
8381
8382
8383<h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
8384
8385<p>
8386This library comprises the operations to manipulate coroutines,
8387which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
8388See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
8389
8390
8391<p>
8392<hr><h3><a name="pdf-coroutine.close"><code>coroutine.close (co)</code></a></h3>
8393
8394
8395<p>
8396Closes coroutine <code>co</code>,
8397that is,
8398closes all its pending to-be-closed variables
8399and puts the coroutine in a dead state.
8400The given coroutine must be dead or suspended.
8401In case of error closing some variable,
8402returns <b>false</b> plus the error object;
8403otherwise returns <b>true</b>.
8404
8405
8406
8407
8408<p>
8409<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
8410
8411
8412<p>
8413Creates a new coroutine, with body <code>f</code>.
8414<code>f</code> must be a function.
8415Returns this new coroutine,
8416an object with type <code>"thread"</code>.
8417
8418
8419
8420
8421<p>
8422<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ([co])</code></a></h3>
8423
8424
8425<p>
8426Returns true when the coroutine <code>co</code> can yield.
8427The default for <code>co</code> is the running coroutine.
8428
8429
8430<p>
8431A coroutine is yieldable if it is not the main thread and
8432it is not inside a non-yieldable C&nbsp;function.
8433
8434
8435
8436
8437<p>
8438<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
8439
8440
8441<p>
8442Starts or continues the execution of coroutine <code>co</code>.
8443The first time you resume a coroutine,
8444it starts running its body.
8445The values <code>val1</code>, ... are passed
8446as the arguments to the body function.
8447If the coroutine has yielded,
8448<code>resume</code> restarts it;
8449the values <code>val1</code>, ... are passed
8450as the results from the yield.
8451
8452
8453<p>
8454If the coroutine runs without any errors,
8455<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
8456(when the coroutine yields) or any values returned by the body function
8457(when the coroutine terminates).
8458If there is any error,
8459<code>resume</code> returns <b>false</b> plus the error message.
8460
8461
8462
8463
8464<p>
8465<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
8466
8467
8468<p>
8469Returns the running coroutine plus a boolean,
8470true when the running coroutine is the main one.
8471
8472
8473
8474
8475<p>
8476<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
8477
8478
8479<p>
8480Returns the status of the coroutine <code>co</code>, as a string:
8481<code>"running"</code>,
8482if the coroutine is running
8483(that is, it is the one that called <code>status</code>);
8484<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
8485or if it has not started running yet;
8486<code>"normal"</code> if the coroutine is active but not running
8487(that is, it has resumed another coroutine);
8488and <code>"dead"</code> if the coroutine has finished its body function,
8489or if it has stopped with an error.
8490
8491
8492
8493
8494<p>
8495<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
8496
8497
8498<p>
8499Creates a new coroutine, with body <code>f</code>;
8500<code>f</code> must be a function.
8501Returns a function that resumes the coroutine each time it is called.
8502Any arguments passed to this function behave as the
8503extra arguments to <code>resume</code>.
8504The function returns the same values returned by <code>resume</code>,
8505except the first boolean.
8506In case of error,
8507the function closes the coroutine and propagates the error.
8508
8509
8510
8511
8512<p>
8513<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
8514
8515
8516<p>
8517Suspends the execution of the calling coroutine.
8518Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
8519
8520
8521
8522
8523
8524
8525
8526<h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
8527
8528<p>
8529The package library provides basic
8530facilities for loading modules in Lua.
8531It exports one function directly in the global environment:
8532<a href="#pdf-require"><code>require</code></a>.
8533Everything else is exported in the table <a name="pdf-package"><code>package</code></a>.
8534
8535
8536<p>
8537<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
8538
8539
8540<p>
8541Loads the given module.
8542The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
8543to determine whether <code>modname</code> is already loaded.
8544If it is, then <code>require</code> returns the value stored
8545at <code>package.loaded[modname]</code>.
8546(The absence of a second result in this case
8547signals that this call did not have to load the module.)
8548Otherwise, it tries to find a <em>loader</em> for the module.
8549
8550
8551<p>
8552To find a loader,
8553<code>require</code> is guided by the table <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8554Each item in this table is a search function,
8555that searches for the module in a particular way.
8556By changing this table,
8557we can change how <code>require</code> looks for a module.
8558The following explanation is based on the default configuration
8559for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8560
8561
8562<p>
8563First <code>require</code> queries <code>package.preload[modname]</code>.
8564If it has a value,
8565this value (which must be a function) is the loader.
8566Otherwise <code>require</code> searches for a Lua loader using the
8567path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
8568If that also fails, it searches for a C&nbsp;loader using the
8569path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8570If that also fails,
8571it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
8572
8573
8574<p>
8575Once a loader is found,
8576<code>require</code> calls the loader with two arguments:
8577<code>modname</code> and an extra value,
8578a <em>loader data</em>,
8579also returned by the searcher.
8580The loader data can be any value useful to the module;
8581for the default searchers,
8582it indicates where the loader was found.
8583(For instance, if the loader came from a file,
8584this extra value is the file path.)
8585If the loader returns any non-nil value,
8586<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
8587If the loader does not return a non-nil value and
8588has not assigned any value to <code>package.loaded[modname]</code>,
8589then <code>require</code> assigns <b>true</b> to this entry.
8590In any case, <code>require</code> returns the
8591final value of <code>package.loaded[modname]</code>.
8592Besides that value, <code>require</code> also returns as a second result
8593the loader data returned by the searcher,
8594which indicates how <code>require</code> found the module.
8595
8596
8597<p>
8598If there is any error loading or running the module,
8599or if it cannot find any loader for the module,
8600then <code>require</code> raises an error.
8601
8602
8603
8604
8605<p>
8606<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
8607
8608
8609<p>
8610A string describing some compile-time configurations for packages.
8611This string is a sequence of lines:
8612
8613<ul>
8614
8615<li>The first line is the directory separator string.
8616Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
8617
8618<li>The second line is the character that separates templates in a path.
8619Default is '<code>;</code>'.</li>
8620
8621<li>The third line is the string that marks the
8622substitution points in a template.
8623Default is '<code>?</code>'.</li>
8624
8625<li>The fourth line is a string that, in a path in Windows,
8626is replaced by the executable's directory.
8627Default is '<code>!</code>'.</li>
8628
8629<li>The fifth line is a mark to ignore all text after it
8630when building the <code>luaopen_</code> function name.
8631Default is '<code>-</code>'.</li>
8632
8633</ul>
8634
8635
8636
8637<p>
8638<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
8639
8640
8641<p>
8642A string with the path used by <a href="#pdf-require"><code>require</code></a>
8643to search for a C&nbsp;loader.
8644
8645
8646<p>
8647Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
8648it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
8649using the environment variable <a name="pdf-LUA_CPATH_5_4"><code>LUA_CPATH_5_4</code></a>,
8650or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
8651or a default path defined in <code>luaconf.h</code>.
8652
8653
8654
8655
8656<p>
8657<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
8658
8659
8660<p>
8661A table used by <a href="#pdf-require"><code>require</code></a> to control which
8662modules are already loaded.
8663When you require a module <code>modname</code> and
8664<code>package.loaded[modname]</code> is not false,
8665<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
8666
8667
8668<p>
8669This variable is only a reference to the real table;
8670assignments to this variable do not change the
8671table used by <a href="#pdf-require"><code>require</code></a>.
8672
8673
8674
8675
8676<p>
8677<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
8678
8679
8680<p>
8681Dynamically links the host program with the C&nbsp;library <code>libname</code>.
8682
8683
8684<p>
8685If <code>funcname</code> is "<code>*</code>",
8686then it only links with the library,
8687making the symbols exported by the library
8688available to other dynamically linked libraries.
8689Otherwise,
8690it looks for a function <code>funcname</code> inside the library
8691and returns this function as a C&nbsp;function.
8692So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
8693(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8694
8695
8696<p>
8697This is a low-level function.
8698It completely bypasses the package and module system.
8699Unlike <a href="#pdf-require"><code>require</code></a>,
8700it does not perform any path searching and
8701does not automatically adds extensions.
8702<code>libname</code> must be the complete file name of the C&nbsp;library,
8703including if necessary a path and an extension.
8704<code>funcname</code> must be the exact name exported by the C&nbsp;library
8705(which may depend on the C&nbsp;compiler and linker used).
8706
8707
8708<p>
8709This function is not supported by Standard&nbsp;C.
8710As such, it is only available on some platforms
8711(Windows, Linux, Mac OS X, Solaris, BSD,
8712plus other Unix systems that support the <code>dlfcn</code> standard).
8713
8714
8715<p>
8716This function is inherently insecure,
8717as it allows Lua to call any function in any readable dynamic
8718library in the system.
8719(Lua calls any function assuming the function
8720has a proper prototype and respects a proper protocol
8721(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8722Therefore,
8723calling an arbitrary function in an arbitrary dynamic library
8724more often than not results in an access violation.)
8725
8726
8727
8728
8729<p>
8730<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
8731
8732
8733<p>
8734A string with the path used by <a href="#pdf-require"><code>require</code></a>
8735to search for a Lua loader.
8736
8737
8738<p>
8739At start-up, Lua initializes this variable with
8740the value of the environment variable <a name="pdf-LUA_PATH_5_4"><code>LUA_PATH_5_4</code></a> or
8741the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
8742with a default path defined in <code>luaconf.h</code>,
8743if those environment variables are not defined.
8744A "<code>;;</code>" in the value of the environment variable
8745is replaced by the default path.
8746
8747
8748
8749
8750<p>
8751<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
8752
8753
8754<p>
8755A table to store loaders for specific modules
8756(see <a href="#pdf-require"><code>require</code></a>).
8757
8758
8759<p>
8760This variable is only a reference to the real table;
8761assignments to this variable do not change the
8762table used by <a href="#pdf-require"><code>require</code></a>.
8763
8764
8765
8766
8767<p>
8768<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
8769
8770
8771<p>
8772A table used by <a href="#pdf-require"><code>require</code></a> to control how to find modules.
8773
8774
8775<p>
8776Each entry in this table is a <em>searcher function</em>.
8777When looking for a module,
8778<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
8779with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
8780sole argument.
8781If the searcher finds the module,
8782it returns another function, the module <em>loader</em>,
8783plus an extra value, a <em>loader data</em>,
8784that will be passed to that loader and
8785returned as a second result by <a href="#pdf-require"><code>require</code></a>.
8786If it cannot find the module,
8787it returns a string explaining why
8788(or <b>nil</b> if it has nothing to say).
8789
8790
8791<p>
8792Lua initializes this table with four searcher functions.
8793
8794
8795<p>
8796The first searcher simply looks for a loader in the
8797<a href="#pdf-package.preload"><code>package.preload</code></a> table.
8798
8799
8800<p>
8801The second searcher looks for a loader as a Lua library,
8802using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
8803The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8804
8805
8806<p>
8807The third searcher looks for a loader as a C&nbsp;library,
8808using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8809Again,
8810the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8811For instance,
8812if the C&nbsp;path is the string
8813
8814<pre>
8815     "./?.so;./?.dll;/usr/local/?/init.so"
8816</pre><p>
8817the searcher for module <code>foo</code>
8818will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
8819and <code>/usr/local/foo/init.so</code>, in that order.
8820Once it finds a C&nbsp;library,
8821this searcher first uses a dynamic link facility to link the
8822application with the library.
8823Then it tries to find a C&nbsp;function inside the library to
8824be used as the loader.
8825The name of this C&nbsp;function is the string "<code>luaopen_</code>"
8826concatenated with a copy of the module name where each dot
8827is replaced by an underscore.
8828Moreover, if the module name has a hyphen,
8829its suffix after (and including) the first hyphen is removed.
8830For instance, if the module name is <code>a.b.c-v2.1</code>,
8831the function name will be <code>luaopen_a_b_c</code>.
8832
8833
8834<p>
8835The fourth searcher tries an <em>all-in-one loader</em>.
8836It searches the C&nbsp;path for a library for
8837the root name of the given module.
8838For instance, when requiring <code>a.b.c</code>,
8839it will search for a C&nbsp;library for <code>a</code>.
8840If found, it looks into it for an open function for
8841the submodule;
8842in our example, that would be <code>luaopen_a_b_c</code>.
8843With this facility, a package can pack several C&nbsp;submodules
8844into one single library,
8845with each submodule keeping its original open function.
8846
8847
8848<p>
8849All searchers except the first one (preload) return as the extra value
8850the file path where the module was found,
8851as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8852The first searcher always returns the string "<code>:preload:</code>".
8853
8854
8855<p>
8856Searchers should raise no errors and have no side effects in Lua.
8857(They may have side effects in C,
8858for instance by linking the application with a library.)
8859
8860
8861
8862
8863<p>
8864<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8865
8866
8867<p>
8868Searches for the given <code>name</code> in the given <code>path</code>.
8869
8870
8871<p>
8872A path is a string containing a sequence of
8873<em>templates</em> separated by semicolons.
8874For each template,
8875the function replaces each interrogation mark (if any)
8876in the template with a copy of <code>name</code>
8877wherein all occurrences of <code>sep</code>
8878(a dot, by default)
8879were replaced by <code>rep</code>
8880(the system's directory separator, by default),
8881and then tries to open the resulting file name.
8882
8883
8884<p>
8885For instance, if the path is the string
8886
8887<pre>
8888     "./?.lua;./?.lc;/usr/local/?/init.lua"
8889</pre><p>
8890the search for the name <code>foo.a</code>
8891will try to open the files
8892<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8893<code>/usr/local/foo/a/init.lua</code>, in that order.
8894
8895
8896<p>
8897Returns the resulting name of the first file that it can
8898open in read mode (after closing the file),
8899or <b>fail</b> plus an error message if none succeeds.
8900(This error message lists all file names it tried to open.)
8901
8902
8903
8904
8905
8906
8907
8908<h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8909
8910
8911
8912<p>
8913This library provides generic functions for string manipulation,
8914such as finding and extracting substrings, and pattern matching.
8915When indexing a string in Lua, the first character is at position&nbsp;1
8916(not at&nbsp;0, as in C).
8917Indices are allowed to be negative and are interpreted as indexing backwards,
8918from the end of the string.
8919Thus, the last character is at position -1, and so on.
8920
8921
8922<p>
8923The string library provides all its functions inside the table
8924<a name="pdf-string"><code>string</code></a>.
8925It also sets a metatable for strings
8926where the <code>__index</code> field points to the <code>string</code> table.
8927Therefore, you can use the string functions in object-oriented style.
8928For instance, <code>string.byte(s,i)</code>
8929can be written as <code>s:byte(i)</code>.
8930
8931
8932<p>
8933The string library assumes one-byte character encodings.
8934
8935
8936<p>
8937<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8938Returns the internal numeric codes of the characters <code>s[i]</code>,
8939<code>s[i+1]</code>, ..., <code>s[j]</code>.
8940The default value for <code>i</code> is&nbsp;1;
8941the default value for <code>j</code> is&nbsp;<code>i</code>.
8942These indices are corrected
8943following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8944
8945
8946<p>
8947Numeric codes are not necessarily portable across platforms.
8948
8949
8950
8951
8952<p>
8953<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8954Receives zero or more integers.
8955Returns a string with length equal to the number of arguments,
8956in which each character has the internal numeric code equal
8957to its corresponding argument.
8958
8959
8960<p>
8961Numeric codes are not necessarily portable across platforms.
8962
8963
8964
8965
8966<p>
8967<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8968
8969
8970<p>
8971Returns a string containing a binary representation
8972(a <em>binary chunk</em>)
8973of the given function,
8974so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8975a copy of the function (but with new upvalues).
8976If <code>strip</code> is a true value,
8977the binary representation may not include all debug information
8978about the function,
8979to save space.
8980
8981
8982<p>
8983Functions with upvalues have only their number of upvalues saved.
8984When (re)loaded,
8985those upvalues receive fresh instances.
8986(See the <a href="#pdf-load"><code>load</code></a> function for details about
8987how these upvalues are initialized.
8988You can use the debug library to serialize
8989and reload the upvalues of a function
8990in a way adequate to your needs.)
8991
8992
8993
8994
8995<p>
8996<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
8997
8998
8999<p>
9000Looks for the first match of
9001<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9002If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
9003where this occurrence starts and ends;
9004otherwise, it returns <b>fail</b>.
9005A third, optional numeric argument <code>init</code> specifies
9006where to start the search;
9007its default value is&nbsp;1 and can be negative.
9008A value of <b>true</b> as a fourth, optional argument <code>plain</code>
9009turns off the pattern matching facilities,
9010so the function does a plain "find substring" operation,
9011with no characters in <code>pattern</code> being considered magic.
9012
9013
9014<p>
9015If the pattern has captures,
9016then in a successful match
9017the captured values are also returned,
9018after the two indices.
9019
9020
9021
9022
9023<p>
9024<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
9025
9026
9027<p>
9028Returns a formatted version of its variable number of arguments
9029following the description given in its first argument,
9030which must be a string.
9031The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
9032The only differences are that the conversion specifiers and modifiers
9033<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, and <code>n</code> are not supported
9034and that there is an extra specifier, <code>q</code>.
9035
9036
9037<p>
9038The specifier <code>q</code> formats booleans, nil, numbers, and strings
9039in a way that the result is a valid constant in Lua source code.
9040Booleans and nil are written in the obvious way
9041(<code>true</code>, <code>false</code>, <code>nil</code>).
9042Floats are written in hexadecimal,
9043to preserve full precision.
9044A string is written between double quotes,
9045using escape sequences when necessary to ensure that
9046it can safely be read back by the Lua interpreter.
9047For instance, the call
9048
9049<pre>
9050     string.format('%q', 'a string with "quotes" and \n new line')
9051</pre><p>
9052may produce the string:
9053
9054<pre>
9055     "a string with \"quotes\" and \
9056      new line"
9057</pre><p>
9058This specifier does not support modifiers (flags, width, length).
9059
9060
9061<p>
9062The conversion specifiers
9063<code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
9064<code>G</code>, and <code>g</code> all expect a number as argument.
9065The specifiers <code>c</code>, <code>d</code>,
9066<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
9067expect an integer.
9068When Lua is compiled with a C89 compiler,
9069the specifiers <code>A</code> and <code>a</code> (hexadecimal floats)
9070do not support modifiers.
9071
9072
9073<p>
9074The specifier <code>s</code> expects a string;
9075if its argument is not a string,
9076it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
9077If the specifier has any modifier,
9078the corresponding string argument should not contain embedded zeros.
9079
9080
9081<p>
9082The specifier <code>p</code> formats the pointer
9083returned by <a href="#lua_topointer"><code>lua_topointer</code></a>.
9084That gives a unique string identifier for tables, userdata,
9085threads, strings, and functions.
9086For other values (numbers, nil, booleans),
9087this specifier results in a string representing
9088the pointer <code>NULL</code>.
9089
9090
9091
9092
9093<p>
9094<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern [, init])</code></a></h3>
9095Returns an iterator function that,
9096each time it is called,
9097returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
9098over the string <code>s</code>.
9099If <code>pattern</code> specifies no captures,
9100then the whole match is produced in each call.
9101A third, optional numeric argument <code>init</code> specifies
9102where to start the search;
9103its default value is&nbsp;1 and can be negative.
9104
9105
9106<p>
9107As an example, the following loop
9108will iterate over all the words from string <code>s</code>,
9109printing one per line:
9110
9111<pre>
9112     s = "hello world from Lua"
9113     for w in string.gmatch(s, "%a+") do
9114       print(w)
9115     end
9116</pre><p>
9117The next example collects all pairs <code>key=value</code> from the
9118given string into a table:
9119
9120<pre>
9121     t = {}
9122     s = "from=world, to=Lua"
9123     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
9124       t[k] = v
9125     end
9126</pre>
9127
9128<p>
9129For this function, a caret '<code>^</code>' at the start of a pattern does not
9130work as an anchor, as this would prevent the iteration.
9131
9132
9133
9134
9135<p>
9136<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
9137Returns a copy of <code>s</code>
9138in which all (or the first <code>n</code>, if given)
9139occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
9140replaced by a replacement string specified by <code>repl</code>,
9141which can be a string, a table, or a function.
9142<code>gsub</code> also returns, as its second value,
9143the total number of matches that occurred.
9144The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
9145
9146
9147<p>
9148If <code>repl</code> is a string, then its value is used for replacement.
9149The character&nbsp;<code>%</code> works as an escape character:
9150any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
9151with <em>d</em> between 1 and 9,
9152stands for the value of the <em>d</em>-th captured substring;
9153the sequence <code>%0</code> stands for the whole match;
9154the sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
9155
9156
9157<p>
9158If <code>repl</code> is a table, then the table is queried for every match,
9159using the first capture as the key.
9160
9161
9162<p>
9163If <code>repl</code> is a function, then this function is called every time a
9164match occurs, with all captured substrings passed as arguments,
9165in order.
9166
9167
9168<p>
9169In any case,
9170if the pattern specifies no captures,
9171then it behaves as if the whole pattern was inside a capture.
9172
9173
9174<p>
9175If the value returned by the table query or by the function call
9176is a string or a number,
9177then it is used as the replacement string;
9178otherwise, if it is <b>false</b> or <b>nil</b>,
9179then there is no replacement
9180(that is, the original match is kept in the string).
9181
9182
9183<p>
9184Here are some examples:
9185
9186<pre>
9187     x = string.gsub("hello world", "(%w+)", "%1 %1")
9188     --&gt; x="hello hello world world"
9189     
9190     x = string.gsub("hello world", "%w+", "%0 %0", 1)
9191     --&gt; x="hello hello world"
9192     
9193     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
9194     --&gt; x="world hello Lua from"
9195     
9196     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
9197     --&gt; x="home = /home/roberto, user = roberto"
9198     
9199     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
9200           return load(s)()
9201         end)
9202     --&gt; x="4+5 = 9"
9203     
9204     local t = {name="lua", version="5.4"}
9205     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
9206     --&gt; x="lua-5.4.tar.gz"
9207</pre>
9208
9209
9210
9211<p>
9212<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
9213
9214
9215<p>
9216Receives a string and returns its length.
9217The empty string <code>""</code> has length 0.
9218Embedded zeros are counted,
9219so <code>"a\000bc\000"</code> has length 5.
9220
9221
9222
9223
9224<p>
9225<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
9226
9227
9228<p>
9229Receives a string and returns a copy of this string with all
9230uppercase letters changed to lowercase.
9231All other characters are left unchanged.
9232The definition of what an uppercase letter is depends on the current locale.
9233
9234
9235
9236
9237<p>
9238<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
9239
9240
9241<p>
9242Looks for the first <em>match</em> of
9243the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9244If it finds one, then <code>match</code> returns
9245the captures from the pattern;
9246otherwise it returns <b>fail</b>.
9247If <code>pattern</code> specifies no captures,
9248then the whole match is returned.
9249A third, optional numeric argument <code>init</code> specifies
9250where to start the search;
9251its default value is&nbsp;1 and can be negative.
9252
9253
9254
9255
9256<p>
9257<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
9258
9259
9260<p>
9261Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
9262serialized in binary form (packed)
9263according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9264
9265
9266
9267
9268<p>
9269<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
9270
9271
9272<p>
9273Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
9274with the given format.
9275The format string cannot have the variable-length options
9276'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
9277
9278
9279
9280
9281<p>
9282<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
9283
9284
9285<p>
9286Returns a string that is the concatenation of <code>n</code> copies of
9287the string <code>s</code> separated by the string <code>sep</code>.
9288The default value for <code>sep</code> is the empty string
9289(that is, no separator).
9290Returns the empty string if <code>n</code> is not positive.
9291
9292
9293<p>
9294(Note that it is very easy to exhaust the memory of your machine
9295with a single call to this function.)
9296
9297
9298
9299
9300<p>
9301<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
9302
9303
9304<p>
9305Returns a string that is the string <code>s</code> reversed.
9306
9307
9308
9309
9310<p>
9311<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
9312
9313
9314<p>
9315Returns the substring of <code>s</code> that
9316starts at <code>i</code>  and continues until <code>j</code>;
9317<code>i</code> and <code>j</code> can be negative.
9318If <code>j</code> is absent, then it is assumed to be equal to -1
9319(which is the same as the string length).
9320In particular,
9321the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
9322with length <code>j</code>,
9323and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
9324returns a suffix of <code>s</code>
9325with length <code>i</code>.
9326
9327
9328<p>
9329If, after the translation of negative indices,
9330<code>i</code> is less than 1,
9331it is corrected to 1.
9332If <code>j</code> is greater than the string length,
9333it is corrected to that length.
9334If, after these corrections,
9335<code>i</code> is greater than <code>j</code>,
9336the function returns the empty string.
9337
9338
9339
9340
9341<p>
9342<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
9343
9344
9345<p>
9346Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
9347according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9348An optional <code>pos</code> marks where
9349to start reading in <code>s</code> (default is 1).
9350After the read values,
9351this function also returns the index of the first unread byte in <code>s</code>.
9352
9353
9354
9355
9356<p>
9357<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
9358
9359
9360<p>
9361Receives a string and returns a copy of this string with all
9362lowercase letters changed to uppercase.
9363All other characters are left unchanged.
9364The definition of what a lowercase letter is depends on the current locale.
9365
9366
9367
9368
9369
9370
9371
9372<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
9373
9374
9375
9376<p>
9377Patterns in Lua are described by regular strings,
9378which are interpreted as patterns by the pattern-matching functions
9379<a href="#pdf-string.find"><code>string.find</code></a>,
9380<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
9381<a href="#pdf-string.gsub"><code>string.gsub</code></a>,
9382and <a href="#pdf-string.match"><code>string.match</code></a>.
9383This section describes the syntax and the meaning
9384(that is, what they match) of these strings.
9385
9386
9387
9388
9389
9390<h4>Character Class:</h4><p>
9391A <em>character class</em> is used to represent a set of characters.
9392The following combinations are allowed in describing a character class:
9393
9394<ul>
9395
9396<li><b><em>x</em>: </b>
9397(where <em>x</em> is not one of the <em>magic characters</em>
9398<code>^$()%.[]*+-?</code>)
9399represents the character <em>x</em> itself.
9400</li>
9401
9402<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
9403
9404<li><b><code>%a</code>: </b> represents all letters.</li>
9405
9406<li><b><code>%c</code>: </b> represents all control characters.</li>
9407
9408<li><b><code>%d</code>: </b> represents all digits.</li>
9409
9410<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
9411
9412<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
9413
9414<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
9415
9416<li><b><code>%s</code>: </b> represents all space characters.</li>
9417
9418<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
9419
9420<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
9421
9422<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
9423
9424<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
9425represents the character <em>x</em>.
9426This is the standard way to escape the magic characters.
9427Any non-alphanumeric character
9428(including all punctuation characters, even the non-magical)
9429can be preceded by a '<code>%</code>' to represent itself in a pattern.
9430</li>
9431
9432<li><b><code>[<em>set</em>]</code>: </b>
9433represents the class which is the union of all
9434characters in <em>set</em>.
9435A range of characters can be specified by
9436separating the end characters of the range,
9437in ascending order, with a '<code>-</code>'.
9438All classes <code>%</code><em>x</em> described above can also be used as
9439components in <em>set</em>.
9440All other characters in <em>set</em> represent themselves.
9441For example, <code>[%w_]</code> (or <code>[_%w]</code>)
9442represents all alphanumeric characters plus the underscore,
9443<code>[0-7]</code> represents the octal digits,
9444and <code>[0-7%l%-]</code> represents the octal digits plus
9445the lowercase letters plus the '<code>-</code>' character.
9446
9447
9448<p>
9449You can put a closing square bracket in a set
9450by positioning it as the first character in the set.
9451You can put a hyphen in a set
9452by positioning it as the first or the last character in the set.
9453(You can also use an escape for both cases.)
9454
9455
9456<p>
9457The interaction between ranges and classes is not defined.
9458Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
9459have no meaning.
9460</li>
9461
9462<li><b><code>[^<em>set</em>]</code>: </b>
9463represents the complement of <em>set</em>,
9464where <em>set</em> is interpreted as above.
9465</li>
9466
9467</ul><p>
9468For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
9469the corresponding uppercase letter represents the complement of the class.
9470For instance, <code>%S</code> represents all non-space characters.
9471
9472
9473<p>
9474The definitions of letter, space, and other character groups
9475depend on the current locale.
9476In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
9477
9478
9479
9480
9481
9482<h4>Pattern Item:</h4><p>
9483A <em>pattern item</em> can be
9484
9485<ul>
9486
9487<li>
9488a single character class,
9489which matches any single character in the class;
9490</li>
9491
9492<li>
9493a single character class followed by '<code>*</code>',
9494which matches sequences of zero or more characters in the class.
9495These repetition items will always match the longest possible sequence;
9496</li>
9497
9498<li>
9499a single character class followed by '<code>+</code>',
9500which matches sequences of one or more characters in the class.
9501These repetition items will always match the longest possible sequence;
9502</li>
9503
9504<li>
9505a single character class followed by '<code>-</code>',
9506which also matches sequences of zero or more characters in the class.
9507Unlike '<code>*</code>',
9508these repetition items will always match the shortest possible sequence;
9509</li>
9510
9511<li>
9512a single character class followed by '<code>?</code>',
9513which matches zero or one occurrence of a character in the class.
9514It always matches one occurrence if possible;
9515</li>
9516
9517<li>
9518<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
9519such item matches a substring equal to the <em>n</em>-th captured string
9520(see below);
9521</li>
9522
9523<li>
9524<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
9525such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
9526and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
9527This means that, if one reads the string from left to right,
9528counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
9529the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
9530For instance, the item <code>%b()</code> matches expressions with
9531balanced parentheses.
9532</li>
9533
9534<li>
9535<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
9536such item matches an empty string at any position such that
9537the next character belongs to <em>set</em>
9538and the previous character does not belong to <em>set</em>.
9539The set <em>set</em> is interpreted as previously described.
9540The beginning and the end of the subject are handled as if
9541they were the character '<code>\0</code>'.
9542</li>
9543
9544</ul>
9545
9546
9547
9548
9549<h4>Pattern:</h4><p>
9550A <em>pattern</em> is a sequence of pattern items.
9551A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
9552beginning of the subject string.
9553A '<code>$</code>' at the end of a pattern anchors the match at the
9554end of the subject string.
9555At other positions,
9556'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
9557
9558
9559
9560
9561
9562<h4>Captures:</h4><p>
9563A pattern can contain sub-patterns enclosed in parentheses;
9564they describe <em>captures</em>.
9565When a match succeeds, the substrings of the subject string
9566that match captures are stored (<em>captured</em>) for future use.
9567Captures are numbered according to their left parentheses.
9568For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
9569the part of the string matching <code>"a*(.)%w(%s*)"</code> is
9570stored as the first capture, and therefore has number&nbsp;1;
9571the character matching "<code>.</code>" is captured with number&nbsp;2,
9572and the part matching "<code>%s*</code>" has number&nbsp;3.
9573
9574
9575<p>
9576As a special case, the capture <code>()</code> captures
9577the current string position (a number).
9578For instance, if we apply the pattern <code>"()aa()"</code> on the
9579string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
9580
9581
9582
9583
9584
9585<h4>Multiple matches:</h4><p>
9586The function <a href="#pdf-string.gsub"><code>string.gsub</code></a> and the iterator <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>
9587match multiple occurrences of the given pattern in the subject.
9588For these functions,
9589a new match is considered valid only
9590if it ends at least one byte after the end of the previous match.
9591In other words, the pattern machine never accepts the
9592empty string as a match immediately after another match.
9593As an example,
9594consider the results of the following code:
9595
9596<pre>
9597     &gt; string.gsub("abc", "()a*()", print);
9598     --&gt; 1   2
9599     --&gt; 3   3
9600     --&gt; 4   4
9601</pre><p>
9602The second and third results come from Lua matching an empty
9603string after '<code>b</code>' and another one after '<code>c</code>'.
9604Lua does not match an empty string after '<code>a</code>',
9605because it would end at the same position of the previous match.
9606
9607
9608
9609
9610
9611
9612
9613<h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
9614
9615<p>
9616The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
9617<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
9618is a format string,
9619which describes the layout of the structure being created or read.
9620
9621
9622<p>
9623A format string is a sequence of conversion options.
9624The conversion options are as follows:
9625
9626<ul>
9627<li><b><code>&lt;</code>: </b>sets little endian</li>
9628<li><b><code>&gt;</code>: </b>sets big endian</li>
9629<li><b><code>=</code>: </b>sets native endian</li>
9630<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
9631(default is native alignment)</li>
9632<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
9633<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
9634<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
9635<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
9636<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
9637<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
9638<li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
9639<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
9640<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
9641<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
9642(default is native size)</li>
9643<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
9644(default is native size)</li>
9645<li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
9646<li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
9647<li><b><code>n</code>: </b>a <code>lua_Number</code></li>
9648<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
9649<li><b><code>z</code>: </b>a zero-terminated string</li>
9650<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
9651coded as an unsigned integer with <code>n</code> bytes
9652(default is a <code>size_t</code>)</li>
9653<li><b><code>x</code>: </b>one byte of padding</li>
9654<li><b><code>X<em>op</em></code>: </b>an empty item that aligns
9655according to option <code>op</code>
9656(which is otherwise ignored)</li>
9657<li><b>'<code> </code>': </b>(space) ignored</li>
9658</ul><p>
9659(A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
9660Except for padding, spaces, and configurations
9661(options "<code>xX &lt;=&gt;!</code>"),
9662each option corresponds to an argument in <a href="#pdf-string.pack"><code>string.pack</code></a>
9663or a result in <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9664
9665
9666<p>
9667For 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>",
9668<code>n</code> can be any integer between 1 and 16.
9669All integral options check overflows;
9670<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
9671<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
9672For the unsigned options,
9673Lua integers are treated as unsigned values too.
9674
9675
9676<p>
9677Any format string starts as if prefixed by "<code>!1=</code>",
9678that is,
9679with maximum alignment of 1 (no alignment)
9680and native endianness.
9681
9682
9683<p>
9684Native endianness assumes that the whole system is
9685either big or little endian.
9686The packing functions will not emulate correctly the behavior
9687of mixed-endian formats.
9688
9689
9690<p>
9691Alignment works as follows:
9692For each option,
9693the format gets extra padding until the data starts
9694at an offset that is a multiple of the minimum between the
9695option size and the maximum alignment;
9696this minimum must be a power of 2.
9697Options "<code>c</code>" and "<code>z</code>" are not aligned;
9698option "<code>s</code>" follows the alignment of its starting integer.
9699
9700
9701<p>
9702All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
9703and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9704
9705
9706
9707
9708
9709
9710
9711<h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
9712
9713<p>
9714This library provides basic support for UTF-8 encoding.
9715It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
9716This library does not provide any support for Unicode other
9717than the handling of the encoding.
9718Any operation that needs the meaning of a character,
9719such as character classification, is outside its scope.
9720
9721
9722<p>
9723Unless stated otherwise,
9724all functions that expect a byte position as a parameter
9725assume that the given position is either the start of a byte sequence
9726or one plus the length of the subject string.
9727As in the string library,
9728negative indices count from the end of the string.
9729
9730
9731<p>
9732Functions that create byte sequences
9733accept all values up to <code>0x7FFFFFFF</code>,
9734as defined in the original UTF-8 specification;
9735that implies byte sequences of up to six bytes.
9736
9737
9738<p>
9739Functions that interpret byte sequences only accept
9740valid sequences (well formed and not overlong).
9741By default, they only accept byte sequences
9742that result in valid Unicode code points,
9743rejecting values greater than <code>10FFFF</code> and surrogates.
9744A boolean argument <code>lax</code>, when available,
9745lifts these checks,
9746so that all values up to <code>0x7FFFFFFF</code> are accepted.
9747(Not well formed and overlong sequences are still rejected.)
9748
9749
9750<p>
9751<hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
9752
9753
9754<p>
9755Receives zero or more integers,
9756converts each one to its corresponding UTF-8 byte sequence
9757and returns a string with the concatenation of all these sequences.
9758
9759
9760
9761
9762<p>
9763<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
9764
9765
9766<p>
9767The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xFD][\x80-\xBF]*</code>"
9768(see <a href="#6.4.1">&sect;6.4.1</a>),
9769which matches exactly one UTF-8 byte sequence,
9770assuming that the subject is a valid UTF-8 string.
9771
9772
9773
9774
9775<p>
9776<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s [, lax])</code></a></h3>
9777
9778
9779<p>
9780Returns values so that the construction
9781
9782<pre>
9783     for p, c in utf8.codes(s) do <em>body</em> end
9784</pre><p>
9785will iterate over all UTF-8 characters in string <code>s</code>,
9786with <code>p</code> being the position (in bytes) and <code>c</code> the code point
9787of each character.
9788It raises an error if it meets any invalid byte sequence.
9789
9790
9791
9792
9793<p>
9794<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j [, lax]]])</code></a></h3>
9795
9796
9797<p>
9798Returns the code points (as integers) from all characters in <code>s</code>
9799that start between byte position <code>i</code> and <code>j</code> (both included).
9800The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
9801It raises an error if it meets any invalid byte sequence.
9802
9803
9804
9805
9806<p>
9807<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j [, lax]]])</code></a></h3>
9808
9809
9810<p>
9811Returns the number of UTF-8 characters in string <code>s</code>
9812that start between positions <code>i</code> and <code>j</code> (both inclusive).
9813The default for <code>i</code> is 1 and for <code>j</code> is -1.
9814If it finds any invalid byte sequence,
9815returns <b>fail</b> plus the position of the first invalid byte.
9816
9817
9818
9819
9820<p>
9821<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
9822
9823
9824<p>
9825Returns the position (in bytes) where the encoding of the
9826<code>n</code>-th character of <code>s</code>
9827(counting from position <code>i</code>) starts.
9828A negative <code>n</code> gets characters before position <code>i</code>.
9829The default for <code>i</code> is 1 when <code>n</code> is non-negative
9830and <code>#s + 1</code> otherwise,
9831so that <code>utf8.offset(s, -n)</code> gets the offset of the
9832<code>n</code>-th character from the end of the string.
9833If the specified character is neither in the subject
9834nor right after its end,
9835the function returns <b>fail</b>.
9836
9837
9838<p>
9839As a special case,
9840when <code>n</code> is 0 the function returns the start of the encoding
9841of the character that contains the <code>i</code>-th byte of <code>s</code>.
9842
9843
9844<p>
9845This function assumes that <code>s</code> is a valid UTF-8 string.
9846
9847
9848
9849
9850
9851
9852
9853<h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
9854
9855<p>
9856This library provides generic functions for table manipulation.
9857It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
9858
9859
9860<p>
9861Remember that, whenever an operation needs the length of a table,
9862all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>).
9863All functions ignore non-numeric keys
9864in the tables given as arguments.
9865
9866
9867<p>
9868<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
9869
9870
9871<p>
9872Given a list where all elements are strings or numbers,
9873returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
9874The default value for <code>sep</code> is the empty string,
9875the default for <code>i</code> is 1,
9876and the default for <code>j</code> is <code>#list</code>.
9877If <code>i</code> is greater than <code>j</code>, returns the empty string.
9878
9879
9880
9881
9882<p>
9883<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
9884
9885
9886<p>
9887Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
9888shifting up the elements
9889<code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
9890The default value for <code>pos</code> is <code>#list+1</code>,
9891so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
9892of the list <code>t</code>.
9893
9894
9895
9896
9897<p>
9898<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
9899
9900
9901<p>
9902Moves elements from the table <code>a1</code> to the table <code>a2</code>,
9903performing the equivalent to the following
9904multiple assignment:
9905<code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
9906The default for <code>a2</code> is <code>a1</code>.
9907The destination range can overlap with the source range.
9908The number of elements to be moved must fit in a Lua integer.
9909
9910
9911<p>
9912Returns the destination table <code>a2</code>.
9913
9914
9915
9916
9917<p>
9918<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
9919
9920
9921<p>
9922Returns a new table with all arguments stored into keys 1, 2, etc.
9923and with a field "<code>n</code>" with the total number of arguments.
9924Note that the resulting table may not be a sequence,
9925if some arguments are <b>nil</b>.
9926
9927
9928
9929
9930<p>
9931<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
9932
9933
9934<p>
9935Removes from <code>list</code> the element at position <code>pos</code>,
9936returning the value of the removed element.
9937When <code>pos</code> is an integer between 1 and <code>#list</code>,
9938it shifts down the elements
9939<code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
9940and erases element <code>list[#list]</code>;
9941The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
9942or <code>#list + 1</code>.
9943
9944
9945<p>
9946The default value for <code>pos</code> is <code>#list</code>,
9947so that a call <code>table.remove(l)</code> removes the last element
9948of the list <code>l</code>.
9949
9950
9951
9952
9953<p>
9954<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
9955
9956
9957<p>
9958Sorts the list elements in a given order, <em>in-place</em>,
9959from <code>list[1]</code> to <code>list[#list]</code>.
9960If <code>comp</code> is given,
9961then it must be a function that receives two list elements
9962and returns true when the first element must come
9963before the second in the final order
9964(so that, after the sort,
9965<code>i &lt; j</code> implies <code>not comp(list[j],list[i])</code>).
9966If <code>comp</code> is not given,
9967then the standard Lua operator <code>&lt;</code> is used instead.
9968
9969
9970<p>
9971Note that the <code>comp</code> function must define
9972a strict partial order over the elements in the list;
9973that is, it must be asymmetric and transitive.
9974Otherwise, no valid sort may be possible.
9975
9976
9977<p>
9978The sort algorithm is not stable:
9979elements considered equal by the given order
9980may have their relative positions changed by the sort.
9981
9982
9983
9984
9985<p>
9986<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
9987
9988
9989<p>
9990Returns the elements from the given list.
9991This function is equivalent to
9992
9993<pre>
9994     return list[i], list[i+1], &middot;&middot;&middot;, list[j]
9995</pre><p>
9996By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
9997
9998
9999
10000
10001
10002
10003
10004<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
10005
10006<p>
10007This library provides basic mathematical functions.
10008It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
10009Functions with the annotation "<code>integer/float</code>" give
10010integer results for integer arguments
10011and float results for non-integer arguments.
10012The rounding functions
10013<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>
10014return an integer when the result fits in the range of an integer,
10015or a float otherwise.
10016
10017
10018<p>
10019<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
10020
10021
10022<p>
10023Returns the maximum value between <code>x</code> and <code>-x</code>. (integer/float)
10024
10025
10026
10027
10028<p>
10029<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
10030
10031
10032<p>
10033Returns the arc cosine of <code>x</code> (in radians).
10034
10035
10036
10037
10038<p>
10039<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
10040
10041
10042<p>
10043Returns the arc sine of <code>x</code> (in radians).
10044
10045
10046
10047
10048<p>
10049<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
10050
10051
10052<p>
10053
10054Returns the arc tangent of <code>y/x</code> (in radians),
10055but uses the signs of both arguments to find the
10056quadrant of the result.
10057It also handles correctly the case of <code>x</code> being zero.
10058
10059
10060<p>
10061The default value for <code>x</code> is 1,
10062so that the call <code>math.atan(y)</code>
10063returns the arc tangent of <code>y</code>.
10064
10065
10066
10067
10068<p>
10069<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
10070
10071
10072<p>
10073Returns the smallest integral value greater than or equal to <code>x</code>.
10074
10075
10076
10077
10078<p>
10079<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
10080
10081
10082<p>
10083Returns the cosine of <code>x</code> (assumed to be in radians).
10084
10085
10086
10087
10088<p>
10089<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
10090
10091
10092<p>
10093Converts the angle <code>x</code> from radians to degrees.
10094
10095
10096
10097
10098<p>
10099<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
10100
10101
10102<p>
10103Returns the value <em>e<sup>x</sup></em>
10104(where <code>e</code> is the base of natural logarithms).
10105
10106
10107
10108
10109<p>
10110<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
10111
10112
10113<p>
10114Returns the largest integral value less than or equal to <code>x</code>.
10115
10116
10117
10118
10119<p>
10120<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
10121
10122
10123<p>
10124Returns the remainder of the division of <code>x</code> by <code>y</code>
10125that rounds the quotient towards zero. (integer/float)
10126
10127
10128
10129
10130<p>
10131<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
10132
10133
10134<p>
10135The float value <code>HUGE_VAL</code>,
10136a value greater than any other numeric value.
10137
10138
10139
10140
10141<p>
10142<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
10143
10144
10145<p>
10146Returns the logarithm of <code>x</code> in the given base.
10147The default for <code>base</code> is <em>e</em>
10148(so that the function returns the natural logarithm of <code>x</code>).
10149
10150
10151
10152
10153<p>
10154<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
10155
10156
10157<p>
10158Returns the argument with the maximum value,
10159according to the Lua operator <code>&lt;</code>.
10160
10161
10162
10163
10164<p>
10165<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
10166An integer with the maximum value for an integer.
10167
10168
10169
10170
10171<p>
10172<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
10173
10174
10175<p>
10176Returns the argument with the minimum value,
10177according to the Lua operator <code>&lt;</code>.
10178
10179
10180
10181
10182<p>
10183<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
10184An integer with the minimum value for an integer.
10185
10186
10187
10188
10189<p>
10190<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
10191
10192
10193<p>
10194Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
10195Its second result is always a float.
10196
10197
10198
10199
10200<p>
10201<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
10202
10203
10204<p>
10205The value of <em>&pi;</em>.
10206
10207
10208
10209
10210<p>
10211<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
10212
10213
10214<p>
10215Converts the angle <code>x</code> from degrees to radians.
10216
10217
10218
10219
10220<p>
10221<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
10222
10223
10224<p>
10225When called without arguments,
10226returns a pseudo-random float with uniform distribution
10227in the range  <em>[0,1)</em>.  
10228When called with two integers <code>m</code> and <code>n</code>,
10229<code>math.random</code> returns a pseudo-random integer
10230with uniform distribution in the range <em>[m, n]</em>.
10231The call <code>math.random(n)</code>, for a positive <code>n</code>,
10232is equivalent to <code>math.random(1,n)</code>.
10233The call <code>math.random(0)</code> produces an integer with
10234all bits (pseudo)random.
10235
10236
10237<p>
10238This function uses the <code>xoshiro256**</code> algorithm to produce
10239pseudo-random 64-bit integers,
10240which are the results of calls with argument&nbsp;0.
10241Other results (ranges and floats)
10242are unbiased extracted from these integers.
10243
10244
10245<p>
10246Lua initializes its pseudo-random generator with the equivalent of
10247a call to <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with no arguments,
10248so that <code>math.random</code> should generate
10249different sequences of results each time the program runs.
10250
10251
10252
10253
10254<p>
10255<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed ([x [, y]])</code></a></h3>
10256
10257
10258<p>
10259When called with at least one argument,
10260the integer parameters <code>x</code> and <code>y</code> are
10261joined into a 128-bit <em>seed</em> that
10262is used to reinitialize the pseudo-random generator;
10263equal seeds produce equal sequences of numbers.
10264The default for <code>y</code> is zero.
10265
10266
10267<p>
10268When called with no arguments,
10269Lua generates a seed with
10270a weak attempt for randomness.
10271
10272
10273<p>
10274This function returns the two seed components
10275that were effectively used,
10276so that setting them again repeats the sequence.
10277
10278
10279<p>
10280To ensure a required level of randomness to the initial state
10281(or contrarily, to have a deterministic sequence,
10282for instance when debugging a program),
10283you should call <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with explicit arguments.
10284
10285
10286
10287
10288<p>
10289<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
10290
10291
10292<p>
10293Returns the sine of <code>x</code> (assumed to be in radians).
10294
10295
10296
10297
10298<p>
10299<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
10300
10301
10302<p>
10303Returns the square root of <code>x</code>.
10304(You can also use the expression <code>x^0.5</code> to compute this value.)
10305
10306
10307
10308
10309<p>
10310<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
10311
10312
10313<p>
10314Returns the tangent of <code>x</code> (assumed to be in radians).
10315
10316
10317
10318
10319<p>
10320<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
10321
10322
10323<p>
10324If the value <code>x</code> is convertible to an integer,
10325returns that integer.
10326Otherwise, returns <b>fail</b>.
10327
10328
10329
10330
10331<p>
10332<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
10333
10334
10335<p>
10336Returns "<code>integer</code>" if <code>x</code> is an integer,
10337"<code>float</code>" if it is a float,
10338or <b>fail</b> if <code>x</code> is not a number.
10339
10340
10341
10342
10343<p>
10344<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
10345
10346
10347<p>
10348Returns a boolean,
10349true if and only if integer <code>m</code> is below integer <code>n</code> when
10350they are compared as unsigned integers.
10351
10352
10353
10354
10355
10356
10357
10358<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
10359
10360<p>
10361The I/O library provides two different styles for file manipulation.
10362The first one uses implicit file handles;
10363that is, there are operations to set a default input file and a
10364default output file,
10365and all input/output operations are done over these default files.
10366The second style uses explicit file handles.
10367
10368
10369<p>
10370When using implicit file handles,
10371all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
10372When using explicit file handles,
10373the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
10374and then all operations are supplied as methods of the file handle.
10375
10376
10377<p>
10378The metatable for file handles provides metamethods
10379for <code>__gc</code> and <code>__close</code> that try
10380to close the file when called.
10381
10382
10383<p>
10384The table <code>io</code> also provides
10385three predefined file handles with their usual meanings from C:
10386<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>.
10387The I/O library never closes these files.
10388
10389
10390<p>
10391Unless otherwise stated,
10392all I/O functions return <b>fail</b> on failure,
10393plus an error message as a second result and
10394a system-dependent error code as a third result,
10395and some non-false value on success.
10396On non-POSIX systems,
10397the computation of the error message and error code
10398in case of errors
10399may be not thread safe,
10400because they rely on the global C variable <code>errno</code>.
10401
10402
10403<p>
10404<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
10405
10406
10407<p>
10408Equivalent to <code>file:close()</code>.
10409Without a <code>file</code>, closes the default output file.
10410
10411
10412
10413
10414<p>
10415<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
10416
10417
10418<p>
10419Equivalent to <code>io.output():flush()</code>.
10420
10421
10422
10423
10424<p>
10425<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
10426
10427
10428<p>
10429When called with a file name, it opens the named file (in text mode),
10430and sets its handle as the default input file.
10431When called with a file handle,
10432it simply sets this file handle as the default input file.
10433When called without arguments,
10434it returns the current default input file.
10435
10436
10437<p>
10438In case of errors this function raises the error,
10439instead of returning an error code.
10440
10441
10442
10443
10444<p>
10445<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3>
10446
10447
10448<p>
10449Opens the given file name in read mode
10450and returns an iterator function that
10451works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
10452When the iterator function fails to read any value,
10453it automatically closes the file.
10454Besides the iterator function,
10455<code>io.lines</code> returns three other values:
10456two <b>nil</b> values as placeholders,
10457plus the created file handle.
10458Therefore, when used in a generic <b>for</b> loop,
10459the file is closed also if the loop is interrupted by an
10460error or a <b>break</b>.
10461
10462
10463<p>
10464The call <code>io.lines()</code> (with no file name) is equivalent
10465to <code>io.input():lines("l")</code>;
10466that is, it iterates over the lines of the default input file.
10467In this case, the iterator does not close the file when the loop ends.
10468
10469
10470<p>
10471In case of errors opening the file,
10472this function raises the error,
10473instead of returning an error code.
10474
10475
10476
10477
10478<p>
10479<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
10480
10481
10482<p>
10483This function opens a file,
10484in the mode specified in the string <code>mode</code>.
10485In case of success,
10486it returns a new file handle.
10487
10488
10489<p>
10490The <code>mode</code> string can be any of the following:
10491
10492<ul>
10493<li><b>"<code>r</code>": </b> read mode (the default);</li>
10494<li><b>"<code>w</code>": </b> write mode;</li>
10495<li><b>"<code>a</code>": </b> append mode;</li>
10496<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
10497<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
10498<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
10499  writing is only allowed at the end of file.</li>
10500</ul><p>
10501The <code>mode</code> string can also have a '<code>b</code>' at the end,
10502which is needed in some systems to open the file in binary mode.
10503
10504
10505
10506
10507<p>
10508<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
10509
10510
10511<p>
10512Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
10513
10514
10515
10516
10517<p>
10518<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
10519
10520
10521<p>
10522This function is system dependent and is not available
10523on all platforms.
10524
10525
10526<p>
10527Starts the program <code>prog</code> in a separated process and returns
10528a file handle that you can use to read data from this program
10529(if <code>mode</code> is <code>"r"</code>, the default)
10530or to write data to this program
10531(if <code>mode</code> is <code>"w"</code>).
10532
10533
10534
10535
10536<p>
10537<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
10538
10539
10540<p>
10541Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
10542
10543
10544
10545
10546<p>
10547<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
10548
10549
10550<p>
10551In case of success,
10552returns a handle for a temporary file.
10553This file is opened in update mode
10554and it is automatically removed when the program ends.
10555
10556
10557
10558
10559<p>
10560<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
10561
10562
10563<p>
10564Checks whether <code>obj</code> is a valid file handle.
10565Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
10566<code>"closed file"</code> if <code>obj</code> is a closed file handle,
10567or <b>fail</b> if <code>obj</code> is not a file handle.
10568
10569
10570
10571
10572<p>
10573<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
10574
10575
10576<p>
10577Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
10578
10579
10580
10581
10582<p>
10583<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
10584
10585
10586<p>
10587Closes <code>file</code>.
10588Note that files are automatically closed when
10589their handles are garbage collected,
10590but that takes an unpredictable amount of time to happen.
10591
10592
10593<p>
10594When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
10595<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
10596returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
10597
10598
10599
10600
10601<p>
10602<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
10603
10604
10605<p>
10606Saves any written data to <code>file</code>.
10607
10608
10609
10610
10611<p>
10612<hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
10613
10614
10615<p>
10616Returns an iterator function that,
10617each time it is called,
10618reads the file according to the given formats.
10619When no format is given,
10620uses "<code>l</code>" as a default.
10621As an example, the construction
10622
10623<pre>
10624     for c in file:lines(1) do <em>body</em> end
10625</pre><p>
10626will iterate over all characters of the file,
10627starting at the current position.
10628Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
10629when the loop ends.
10630
10631
10632
10633
10634<p>
10635<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
10636
10637
10638<p>
10639Reads the file <code>file</code>,
10640according to the given formats, which specify what to read.
10641For each format,
10642the function returns a string or a number with the characters read,
10643or <b>fail</b> if it cannot read data with the specified format.
10644(In this latter case,
10645the function does not read subsequent formats.)
10646When called without arguments,
10647it uses a default format that reads the next line
10648(see below).
10649
10650
10651<p>
10652The available formats are
10653
10654<ul>
10655
10656<li><b>"<code>n</code>": </b>
10657reads a numeral and returns it as a float or an integer,
10658following the lexical conventions of Lua.
10659(The numeral may have leading whitespaces and a sign.)
10660This format always reads the longest input sequence that
10661is a valid prefix for a numeral;
10662if that prefix does not form a valid numeral
10663(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>")
10664or it is too long (more than 200 characters),
10665it is discarded and the format returns <b>fail</b>.
10666</li>
10667
10668<li><b>"<code>a</code>": </b>
10669reads the whole file, starting at the current position.
10670On end of file, it returns the empty string;
10671this format never fails.
10672</li>
10673
10674<li><b>"<code>l</code>": </b>
10675reads the next line skipping the end of line,
10676returning <b>fail</b> on end of file.
10677This is the default format.
10678</li>
10679
10680<li><b>"<code>L</code>": </b>
10681reads the next line keeping the end-of-line character (if present),
10682returning <b>fail</b> on end of file.
10683</li>
10684
10685<li><b><em>number</em>: </b>
10686reads a string with up to this number of bytes,
10687returning <b>fail</b> on end of file.
10688If <code>number</code> is zero,
10689it reads nothing and returns an empty string,
10690or <b>fail</b> on end of file.
10691</li>
10692
10693</ul><p>
10694The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
10695
10696
10697
10698
10699<p>
10700<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
10701
10702
10703<p>
10704Sets and gets the file position,
10705measured from the beginning of the file,
10706to the position given by <code>offset</code> plus a base
10707specified by the string <code>whence</code>, as follows:
10708
10709<ul>
10710<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
10711<li><b>"<code>cur</code>": </b> base is current position;</li>
10712<li><b>"<code>end</code>": </b> base is end of file;</li>
10713</ul><p>
10714In case of success, <code>seek</code> returns the final file position,
10715measured in bytes from the beginning of the file.
10716If <code>seek</code> fails, it returns <b>fail</b>,
10717plus a string describing the error.
10718
10719
10720<p>
10721The default value for <code>whence</code> is <code>"cur"</code>,
10722and for <code>offset</code> is 0.
10723Therefore, the call <code>file:seek()</code> returns the current
10724file position, without changing it;
10725the call <code>file:seek("set")</code> sets the position to the
10726beginning of the file (and returns 0);
10727and the call <code>file:seek("end")</code> sets the position to the
10728end of the file, and returns its size.
10729
10730
10731
10732
10733<p>
10734<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
10735
10736
10737<p>
10738Sets the buffering mode for a file.
10739There are three available modes:
10740
10741<ul>
10742<li><b>"<code>no</code>": </b> no buffering.</li>
10743<li><b>"<code>full</code>": </b> full buffering.</li>
10744<li><b>"<code>line</code>": </b> line buffering.</li>
10745</ul>
10746
10747<p>
10748For the last two cases,
10749<code>size</code> is a hint for the size of the buffer, in bytes.
10750The default is an appropriate size.
10751
10752
10753<p>
10754The specific behavior of each mode is non portable;
10755check the underlying ISO&nbsp;C function <code>setvbuf</code> in your platform for
10756more details.
10757
10758
10759
10760
10761<p>
10762<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
10763
10764
10765<p>
10766Writes the value of each of its arguments to <code>file</code>.
10767The arguments must be strings or numbers.
10768
10769
10770<p>
10771In case of success, this function returns <code>file</code>.
10772
10773
10774
10775
10776
10777
10778
10779<h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
10780
10781<p>
10782This library is implemented through table <a name="pdf-os"><code>os</code></a>.
10783
10784
10785<p>
10786<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
10787
10788
10789<p>
10790Returns an approximation of the amount in seconds of CPU time
10791used by the program,
10792as returned by the underlying ISO&nbsp;C function <code>clock</code>.
10793
10794
10795
10796
10797<p>
10798<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
10799
10800
10801<p>
10802Returns a string or a table containing date and time,
10803formatted according to the given string <code>format</code>.
10804
10805
10806<p>
10807If the <code>time</code> argument is present,
10808this is the time to be formatted
10809(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
10810Otherwise, <code>date</code> formats the current time.
10811
10812
10813<p>
10814If <code>format</code> starts with '<code>!</code>',
10815then the date is formatted in Coordinated Universal Time.
10816After this optional character,
10817if <code>format</code> is the string "<code>*t</code>",
10818then <code>date</code> returns a table with the following fields:
10819<code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
10820<code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59),
10821<code>sec</code> (0&ndash;61, due to leap seconds),
10822<code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1),
10823<code>yday</code> (day of the year, 1&ndash;366),
10824and <code>isdst</code> (daylight saving flag, a boolean).
10825This last field may be absent
10826if the information is not available.
10827
10828
10829<p>
10830If <code>format</code> is not "<code>*t</code>",
10831then <code>date</code> returns the date as a string,
10832formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
10833
10834
10835<p>
10836If <code>format</code> is absent, it defaults to "<code>%c</code>",
10837which gives a human-readable date and time representation
10838using the current locale.
10839
10840
10841<p>
10842On non-POSIX systems,
10843this function may be not thread safe
10844because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
10845
10846
10847
10848
10849<p>
10850<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
10851
10852
10853<p>
10854Returns the difference, in seconds,
10855from time <code>t1</code> to time <code>t2</code>
10856(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
10857In POSIX, Windows, and some other systems,
10858this value is exactly <code>t2</code><em>-</em><code>t1</code>.
10859
10860
10861
10862
10863<p>
10864<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
10865
10866
10867<p>
10868This function is equivalent to the ISO&nbsp;C function <code>system</code>.
10869It passes <code>command</code> to be executed by an operating system shell.
10870Its first result is <b>true</b>
10871if the command terminated successfully,
10872or <b>fail</b> otherwise.
10873After this first result
10874the function returns a string plus a number,
10875as follows:
10876
10877<ul>
10878
10879<li><b>"<code>exit</code>": </b>
10880the command terminated normally;
10881the following number is the exit status of the command.
10882</li>
10883
10884<li><b>"<code>signal</code>": </b>
10885the command was terminated by a signal;
10886the following number is the signal that terminated the command.
10887</li>
10888
10889</ul>
10890
10891<p>
10892When called without a <code>command</code>,
10893<code>os.execute</code> returns a boolean that is true if a shell is available.
10894
10895
10896
10897
10898<p>
10899<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
10900
10901
10902<p>
10903Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
10904If <code>code</code> is <b>true</b>,
10905the returned status is <code>EXIT_SUCCESS</code>;
10906if <code>code</code> is <b>false</b>,
10907the returned status is <code>EXIT_FAILURE</code>;
10908if <code>code</code> is a number,
10909the returned status is this number.
10910The default value for <code>code</code> is <b>true</b>.
10911
10912
10913<p>
10914If the optional second argument <code>close</code> is true,
10915closes the Lua state before exiting.
10916
10917
10918
10919
10920<p>
10921<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
10922
10923
10924<p>
10925Returns the value of the process environment variable <code>varname</code>
10926or <b>fail</b> if the variable is not defined.
10927
10928
10929
10930
10931<p>
10932<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
10933
10934
10935<p>
10936Deletes the file (or empty directory, on POSIX systems)
10937with the given name.
10938If this function fails, it returns <b>fail</b>
10939plus a string describing the error and the error code.
10940Otherwise, it returns true.
10941
10942
10943
10944
10945<p>
10946<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
10947
10948
10949<p>
10950Renames the file or directory named <code>oldname</code> to <code>newname</code>.
10951If this function fails, it returns <b>fail</b>,
10952plus a string describing the error and the error code.
10953Otherwise, it returns true.
10954
10955
10956
10957
10958<p>
10959<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
10960
10961
10962<p>
10963Sets the current locale of the program.
10964<code>locale</code> is a system-dependent string specifying a locale;
10965<code>category</code> is an optional string describing which category to change:
10966<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
10967<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
10968the default category is <code>"all"</code>.
10969The function returns the name of the new locale,
10970or <b>fail</b> if the request cannot be honored.
10971
10972
10973<p>
10974If <code>locale</code> is the empty string,
10975the current locale is set to an implementation-defined native locale.
10976If <code>locale</code> is the string "<code>C</code>",
10977the current locale is set to the standard C locale.
10978
10979
10980<p>
10981When called with <b>nil</b> as the first argument,
10982this function only returns the name of the current locale
10983for the given category.
10984
10985
10986<p>
10987This function may be not thread safe
10988because of its reliance on C&nbsp;function <code>setlocale</code>.
10989
10990
10991
10992
10993<p>
10994<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
10995
10996
10997<p>
10998Returns the current time when called without arguments,
10999or a time representing the local date and time specified by the given table.
11000This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
11001and may have fields
11002<code>hour</code> (default is 12),
11003<code>min</code> (default is 0),
11004<code>sec</code> (default is 0),
11005and <code>isdst</code> (default is <b>nil</b>).
11006Other fields are ignored.
11007For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
11008
11009
11010<p>
11011When the function is called,
11012the values in these fields do not need to be inside their valid ranges.
11013For instance, if <code>sec</code> is -10,
11014it means 10 seconds before the time specified by the other fields;
11015if <code>hour</code> is 1000,
11016it means 1000 hours after the time specified by the other fields.
11017
11018
11019<p>
11020The returned value is a number, whose meaning depends on your system.
11021In POSIX, Windows, and some other systems,
11022this number counts the number
11023of seconds since some given start time (the "epoch").
11024In other systems, the meaning is not specified,
11025and the number returned by <code>time</code> can be used only as an argument to
11026<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
11027
11028
11029<p>
11030When called with a table,
11031<code>os.time</code> also normalizes all the fields
11032documented in the <a href="#pdf-os.date"><code>os.date</code></a> function,
11033so that they represent the same time as before the call
11034but with values inside their valid ranges.
11035
11036
11037
11038
11039<p>
11040<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
11041
11042
11043<p>
11044Returns a string with a file name that can
11045be used for a temporary file.
11046The file must be explicitly opened before its use
11047and explicitly removed when no longer needed.
11048
11049
11050<p>
11051In POSIX systems,
11052this function also creates a file with that name,
11053to avoid security risks.
11054(Someone else might create the file with wrong permissions
11055in the time between getting the name and creating the file.)
11056You still have to open the file to use it
11057and to remove it (even if you do not use it).
11058
11059
11060<p>
11061When possible,
11062you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
11063which automatically removes the file when the program ends.
11064
11065
11066
11067
11068
11069
11070
11071<h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
11072
11073<p>
11074This library provides
11075the functionality of the debug interface (<a href="#4.7">&sect;4.7</a>) to Lua programs.
11076You should exert care when using this library.
11077Several of its functions
11078violate basic assumptions about Lua code
11079(e.g., that variables local to a function
11080cannot be accessed from outside;
11081that userdata metatables cannot be changed by Lua code;
11082that Lua programs do not crash)
11083and therefore can compromise otherwise secure code.
11084Moreover, some functions in this library may be slow.
11085
11086
11087<p>
11088All functions in this library are provided
11089inside the <a name="pdf-debug"><code>debug</code></a> table.
11090All functions that operate over a thread
11091have an optional first argument which is the
11092thread to operate over.
11093The default is always the current thread.
11094
11095
11096<p>
11097<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
11098
11099
11100<p>
11101Enters an interactive mode with the user,
11102running each string that the user enters.
11103Using simple commands and other debug facilities,
11104the user can inspect global and local variables,
11105change their values, evaluate expressions, and so on.
11106A line containing only the word <code>cont</code> finishes this function,
11107so that the caller continues its execution.
11108
11109
11110<p>
11111Note that commands for <code>debug.debug</code> are not lexically nested
11112within any function and so have no direct access to local variables.
11113
11114
11115
11116
11117<p>
11118<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
11119
11120
11121<p>
11122Returns the current hook settings of the thread, as three values:
11123the current hook function, the current hook mask,
11124and the current hook count,
11125as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function.
11126
11127
11128<p>
11129Returns <b>fail</b> if there is no active hook.
11130
11131
11132
11133
11134<p>
11135<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
11136
11137
11138<p>
11139Returns a table with information about a function.
11140You can give the function directly
11141or you can give a number as the value of <code>f</code>,
11142which means the function running at level <code>f</code> of the call stack
11143of the given thread:
11144level&nbsp;0 is the current function (<code>getinfo</code> itself);
11145level&nbsp;1 is the function that called <code>getinfo</code>
11146(except for tail calls, which do not count in the stack);
11147and so on.
11148If <code>f</code> is a number greater than the number of active functions,
11149then <code>getinfo</code> returns <b>fail</b>.
11150
11151
11152<p>
11153The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
11154with the string <code>what</code> describing which fields to fill in.
11155The default for <code>what</code> is to get all information available,
11156except the table of valid lines.
11157If present,
11158the option '<code>f</code>'
11159adds a field named <code>func</code> with the function itself.
11160If present,
11161the option '<code>L</code>'
11162adds a field named <code>activelines</code> with the table of
11163valid lines.
11164
11165
11166<p>
11167For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
11168a name for the current function,
11169if a reasonable name can be found,
11170and the expression <code>debug.getinfo(print)</code>
11171returns a table with all available information
11172about the <a href="#pdf-print"><code>print</code></a> function.
11173
11174
11175
11176
11177<p>
11178<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
11179
11180
11181<p>
11182This function returns the name and the value of the local variable
11183with index <code>local</code> of the function at level <code>f</code> of the stack.
11184This function accesses not only explicit local variables,
11185but also parameters and temporary values.
11186
11187
11188<p>
11189The first parameter or local variable has index&nbsp;1, and so on,
11190following the order that they are declared in the code,
11191counting only the variables that are active
11192in the current scope of the function.
11193Compile-time constants may not appear in this listing,
11194if they were optimized away by the compiler.
11195Negative indices refer to vararg arguments;
11196-1 is the first vararg argument.
11197The function returns <b>fail</b>
11198if there is no variable with the given index,
11199and raises an error when called with a level out of range.
11200(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
11201
11202
11203<p>
11204Variable names starting with '<code>(</code>' (open parenthesis) 
11205represent variables with no known names
11206(internal variables such as loop control variables,
11207and variables from chunks saved without debug information).
11208
11209
11210<p>
11211The parameter <code>f</code> may also be a function.
11212In that case, <code>getlocal</code> returns only the name of function parameters.
11213
11214
11215
11216
11217<p>
11218<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
11219
11220
11221<p>
11222Returns the metatable of the given <code>value</code>
11223or <b>nil</b> if it does not have a metatable.
11224
11225
11226
11227
11228<p>
11229<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
11230
11231
11232<p>
11233Returns the registry table (see <a href="#4.3">&sect;4.3</a>).
11234
11235
11236
11237
11238<p>
11239<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
11240
11241
11242<p>
11243This function returns the name and the value of the upvalue
11244with index <code>up</code> of the function <code>f</code>.
11245The function returns <b>fail</b>
11246if there is no upvalue with the given index.
11247
11248
11249<p>
11250(For Lua functions,
11251upvalues are the external local variables that the function uses,
11252and that are consequently included in its closure.)
11253
11254
11255<p>
11256For C&nbsp;functions, this function uses the empty string <code>""</code>
11257as a name for all upvalues.
11258
11259
11260<p>
11261Variable name '<code>?</code>' (interrogation mark)
11262represents variables with no known names
11263(variables from chunks saved without debug information).
11264
11265
11266
11267
11268<p>
11269<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u, n)</code></a></h3>
11270
11271
11272<p>
11273Returns the <code>n</code>-th user value associated
11274to the userdata <code>u</code> plus a boolean,
11275<b>false</b> if the userdata does not have that value.
11276
11277
11278
11279
11280<p>
11281<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
11282
11283
11284<p>
11285Sets the given function as the debug hook.
11286The string <code>mask</code> and the number <code>count</code> describe
11287when the hook will be called.
11288The string mask may have any combination of the following characters,
11289with the given meaning:
11290
11291<ul>
11292<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
11293<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
11294<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
11295</ul><p>
11296Moreover,
11297with a <code>count</code> different from zero,
11298the hook is called also after every <code>count</code> instructions.
11299
11300
11301<p>
11302When called without arguments,
11303<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
11304
11305
11306<p>
11307When the hook is called, its first parameter is a string
11308describing the event that has triggered its call:
11309<code>"call"</code>, <code>"tail call"</code>, <code>"return"</code>,
11310<code>"line"</code>, and <code>"count"</code>.
11311For line events,
11312the hook also gets the new line number as its second parameter.
11313Inside a hook,
11314you can call <code>getinfo</code> with level&nbsp;2 to get more information about
11315the running function.
11316(Level&nbsp;0 is the <code>getinfo</code> function,
11317and level&nbsp;1 is the hook function.)
11318
11319
11320
11321
11322<p>
11323<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
11324
11325
11326<p>
11327This function assigns the value <code>value</code> to the local variable
11328with index <code>local</code> of the function at level <code>level</code> of the stack.
11329The function returns <b>fail</b> if there is no local
11330variable with the given index,
11331and raises an error when called with a <code>level</code> out of range.
11332(You can call <code>getinfo</code> to check whether the level is valid.)
11333Otherwise, it returns the name of the local variable.
11334
11335
11336<p>
11337See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
11338variable indices and names.
11339
11340
11341
11342
11343<p>
11344<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
11345
11346
11347<p>
11348Sets the metatable for the given <code>value</code> to the given <code>table</code>
11349(which can be <b>nil</b>).
11350Returns <code>value</code>.
11351
11352
11353
11354
11355<p>
11356<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
11357
11358
11359<p>
11360This function assigns the value <code>value</code> to the upvalue
11361with index <code>up</code> of the function <code>f</code>.
11362The function returns <b>fail</b> if there is no upvalue
11363with the given index.
11364Otherwise, it returns the name of the upvalue.
11365
11366
11367<p>
11368See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
11369
11370
11371
11372
11373<p>
11374<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value, n)</code></a></h3>
11375
11376
11377<p>
11378Sets the given <code>value</code> as
11379the <code>n</code>-th user value associated to the given <code>udata</code>.
11380<code>udata</code> must be a full userdata.
11381
11382
11383<p>
11384Returns <code>udata</code>,
11385or <b>fail</b> if the userdata does not have that value.
11386
11387
11388
11389
11390<p>
11391<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
11392
11393
11394<p>
11395If <code>message</code> is present but is neither a string nor <b>nil</b>,
11396this function returns <code>message</code> without further processing.
11397Otherwise,
11398it returns a string with a traceback of the call stack.
11399The optional <code>message</code> string is appended
11400at the beginning of the traceback.
11401An optional <code>level</code> number tells at which level
11402to start the traceback
11403(default is 1, the function calling <code>traceback</code>).
11404
11405
11406
11407
11408<p>
11409<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
11410
11411
11412<p>
11413Returns a unique identifier (as a light userdata)
11414for the upvalue numbered <code>n</code>
11415from the given function.
11416
11417
11418<p>
11419These unique identifiers allow a program to check whether different
11420closures share upvalues.
11421Lua closures that share an upvalue
11422(that is, that access a same external local variable)
11423will return identical ids for those upvalue indices.
11424
11425
11426
11427
11428<p>
11429<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
11430
11431
11432<p>
11433Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
11434refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
11435
11436
11437
11438
11439
11440
11441
11442<h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
11443
11444<p>
11445Although Lua has been designed as an extension language,
11446to be embedded in a host C&nbsp;program,
11447it is also frequently used as a standalone language.
11448An interpreter for Lua as a standalone language,
11449called simply <code>lua</code>,
11450is provided with the standard distribution.
11451The standalone interpreter includes
11452all standard libraries.
11453Its usage is:
11454
11455<pre>
11456     lua [options] [script [args]]
11457</pre><p>
11458The options are:
11459
11460<ul>
11461<li><b><code>-e <em>stat</em></code>: </b> execute string <em>stat</em>;</li>
11462<li><b><code>-i</code>: </b> enter interactive mode after running <em>script</em>;</li>
11463<li><b><code>-l <em>mod</em></code>: </b> "require" <em>mod</em> and assign the
11464  result to global <em>mod</em>;</li>
11465<li><b><code>-v</code>: </b> print version information;</li>
11466<li><b><code>-E</code>: </b> ignore environment variables;</li>
11467<li><b><code>-W</code>: </b> turn warnings on;</li>
11468<li><b><code>--</code>: </b> stop handling options;</li>
11469<li><b><code>-</code>: </b> execute <code>stdin</code> as a file and stop handling options.</li>
11470</ul><p>
11471After handling its options, <code>lua</code> runs the given <em>script</em>.
11472When called without arguments,
11473<code>lua</code> behaves as <code>lua -v -i</code>
11474when the standard input (<code>stdin</code>) is a terminal,
11475and as <code>lua -</code> otherwise.
11476
11477
11478<p>
11479When called without the option <code>-E</code>,
11480the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_4"><code>LUA_INIT_5_4</code></a>
11481(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
11482before running any argument.
11483If the variable content has the format <code>@<em>filename</em></code>,
11484then <code>lua</code> executes the file.
11485Otherwise, <code>lua</code> executes the string itself.
11486
11487
11488<p>
11489When called with the option <code>-E</code>,
11490Lua does not consult any environment variables.
11491In particular,
11492the values of <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
11493are set with the default paths defined in <code>luaconf.h</code>.
11494
11495
11496<p>
11497The options <code>-e</code>, <code>-l</code>, and <code>-W</code> are handled in
11498the order they appear.
11499For instance, an invocation like
11500
11501<pre>
11502     $ lua -e 'a=1' -llib1 script.lua
11503</pre><p>
11504will first set <code>a</code> to 1, then require the library <code>lib1</code>,
11505and finally run the file <code>script.lua</code> with no arguments.
11506(Here <code>$</code> is the shell prompt. Your prompt may be different.)
11507
11508
11509<p>
11510Before running any code,
11511<code>lua</code> collects all command-line arguments
11512in a global table called <code>arg</code>.
11513The script name goes to index 0,
11514the first argument after the script name goes to index 1,
11515and so on.
11516Any arguments before the script name
11517(that is, the interpreter name plus its options)
11518go to negative indices.
11519For instance, in the call
11520
11521<pre>
11522     $ lua -la b.lua t1 t2
11523</pre><p>
11524the table is like this:
11525
11526<pre>
11527     arg = { [-2] = "lua", [-1] = "-la",
11528             [0] = "b.lua",
11529             [1] = "t1", [2] = "t2" }
11530</pre><p>
11531If there is no script in the call,
11532the interpreter name goes to index 0,
11533followed by the other arguments.
11534For instance, the call
11535
11536<pre>
11537     $ lua -e "print(arg[1])"
11538</pre><p>
11539will print "<code>-e</code>".
11540If there is a script,
11541the script is called with arguments
11542<code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
11543Like all chunks in Lua,
11544the script is compiled as a vararg function.
11545
11546
11547<p>
11548In interactive mode,
11549Lua repeatedly prompts and waits for a line.
11550After reading a line,
11551Lua first try to interpret the line as an expression.
11552If it succeeds, it prints its value.
11553Otherwise, it interprets the line as a statement.
11554If you write an incomplete statement,
11555the interpreter waits for its completion
11556by issuing a different prompt.
11557
11558
11559<p>
11560If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
11561then its value is used as the prompt.
11562Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
11563its value is used as the secondary prompt
11564(issued during incomplete statements).
11565
11566
11567<p>
11568In case of unprotected errors in the script,
11569the interpreter reports the error to the standard error stream.
11570If the error object is not a string but
11571has a metamethod <code>__tostring</code>,
11572the interpreter calls this metamethod to produce the final message.
11573Otherwise, the interpreter converts the error object to a string
11574and adds a stack traceback to it.
11575When warnings are on,
11576they are simply printed in the standard error output.
11577
11578
11579<p>
11580When finishing normally,
11581the interpreter closes its main Lua state
11582(see <a href="#lua_close"><code>lua_close</code></a>).
11583The script can avoid this step by
11584calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
11585
11586
11587<p>
11588To allow the use of Lua as a
11589script interpreter in Unix systems,
11590Lua skips the first line of a file chunk if it starts with <code>#</code>.
11591Therefore, Lua scripts can be made into executable programs
11592by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
11593as in
11594
11595<pre>
11596     #!/usr/local/bin/lua
11597</pre><p>
11598Of course,
11599the location of the Lua interpreter may be different in your machine.
11600If <code>lua</code> is in your <code>PATH</code>,
11601then
11602
11603<pre>
11604     #!/usr/bin/env lua
11605</pre><p>
11606is a more portable solution.
11607
11608
11609
11610<h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
11611
11612
11613
11614<p>
11615Here we list the incompatibilities that you may find when moving a program
11616from Lua&nbsp;5.3 to Lua&nbsp;5.4.
11617
11618
11619<p>
11620You can avoid some incompatibilities by compiling Lua with
11621appropriate options (see file <code>luaconf.h</code>).
11622However,
11623all these compatibility options will be removed in the future.
11624More often than not,
11625compatibility issues arise when these compatibility options
11626are removed.
11627So, whenever you have the chance,
11628you should try to test your code with a version of Lua compiled
11629with all compatibility options turned off.
11630That will ease transitions to newer versions of Lua.
11631
11632
11633<p>
11634Lua versions can always change the C API in ways that
11635do not imply source-code changes in a program,
11636such as the numeric values for constants
11637or the implementation of functions as macros.
11638Therefore,
11639you should never assume that binaries are compatible between
11640different Lua versions.
11641Always recompile clients of the Lua API when
11642using a new version.
11643
11644
11645<p>
11646Similarly, Lua versions can always change the internal representation
11647of precompiled chunks;
11648precompiled chunks are not compatible between different Lua versions.
11649
11650
11651<p>
11652The standard paths in the official distribution may
11653change between versions.
11654
11655
11656
11657
11658
11659<h2>8.1 &ndash; <a name="8.1">Incompatibilities in the Language</a></h2>
11660<ul>
11661
11662<li>
11663The coercion of strings to numbers in
11664arithmetic and bitwise operations
11665has been removed from the core language.
11666The string library does a similar job
11667for arithmetic (but not for bitwise) operations
11668using the string metamethods.
11669However, unlike in previous versions,
11670the new implementation preserves the implicit type of the numeral
11671in the string.
11672For instance, the result of <code>"1" + "2"</code> now is an integer,
11673not a float.
11674</li>
11675
11676<li>
11677Literal decimal integer constants that overflow are read as floats,
11678instead of wrapping around.
11679You can use hexadecimal notation for such constants if you
11680want the old behavior
11681(reading them as integers with wrap around).
11682</li>
11683
11684<li>
11685The use of the <code>__lt</code> metamethod to emulate <code>__le</code>
11686has been removed.
11687When needed, this metamethod must be explicitly defined.
11688</li>
11689
11690<li>
11691The semantics of the numerical <b>for</b> loop
11692over integers changed in some details.
11693In particular, the control variable never wraps around.
11694</li>
11695
11696<li>
11697A label for a <b>goto</b> cannot be declared where a label with the same
11698name is visible, even if this other label is declared in an enclosing
11699block.
11700</li>
11701
11702<li>
11703When finalizing an object,
11704Lua does not ignore <code>__gc</code> metamethods that are not functions.
11705Any value will be called, if present.
11706(Non-callable values will generate a warning,
11707like any other error when calling a finalizer.)
11708</li>
11709
11710</ul>
11711
11712
11713
11714
11715<h2>8.2 &ndash; <a name="8.2">Incompatibilities in the Libraries</a></h2>
11716<ul>
11717
11718<li>
11719The function <a href="#pdf-print"><code>print</code></a> does not call <a href="#pdf-tostring"><code>tostring</code></a>
11720to format its arguments;
11721instead, it has this functionality hardwired.
11722You should use <code>__tostring</code> to modify how values are printed.
11723</li>
11724
11725<li>
11726The pseudo-random number generator used by the function <a href="#pdf-math.random"><code>math.random</code></a>
11727now starts with a somewhat random seed.
11728Moreover, it uses a different algorithm.
11729</li>
11730
11731<li>
11732By default, the decoding functions in the <a href="#pdf-utf8"><code>utf8</code></a> library
11733do not accept surrogates as valid code points.
11734An extra parameter in these functions makes them more permissive.
11735</li>
11736
11737<li>
11738The options "<code>setpause</code>" and "<code>setstepmul</code>"
11739of the function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> are deprecated.
11740You should use the new option "<code>incremental</code>" to set them.
11741</li>
11742
11743<li>
11744The function <a href="#pdf-io.lines"><code>io.lines</code></a> now returns four values,
11745instead of just one.
11746That can be a problem when it is used as the sole
11747argument to another function that has optional parameters,
11748such as in <code>load(io.lines(filename, "L"))</code>.
11749To fix that issue,
11750you can wrap the call into parentheses,
11751to adjust its number of results to one.
11752</li>
11753
11754</ul>
11755
11756
11757
11758
11759<h2>8.3 &ndash; <a name="8.3">Incompatibilities in the API</a></h2>
11760
11761
11762<ul>
11763
11764<li>
11765Full userdata now has an arbitrary number of associated user values.
11766Therefore, the functions <code>lua_newuserdata</code>,
11767<code>lua_setuservalue</code>, and <code>lua_getuservalue</code> were
11768replaced by <a href="#lua_newuserdatauv"><code>lua_newuserdatauv</code></a>,
11769<a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a>, and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>,
11770which have an extra argument.
11771
11772
11773<p>
11774For compatibility, the old names still work as macros assuming
11775one single user value.
11776Note, however, that userdata with zero user values
11777are more efficient memory-wise.
11778</li>
11779
11780<li>
11781The function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter.
11782This out parameter returns the number of values on
11783the top of the stack that were yielded or returned by the coroutine.
11784(In previous versions,
11785those values were the entire stack.)
11786</li>
11787
11788<li>
11789The function <a href="#lua_version"><code>lua_version</code></a> returns the version number,
11790instead of an address of the version number.
11791The Lua core should work correctly with libraries using their
11792own static copies of the same core,
11793so there is no need to check whether they are using the same
11794address space.
11795</li>
11796
11797<li>
11798The constant <code>LUA_ERRGCMM</code> was removed.
11799Errors in finalizers are never propagated;
11800instead, they generate a warning.
11801</li>
11802
11803<li>
11804The options <code>LUA_GCSETPAUSE</code> and <code>LUA_GCSETSTEPMUL</code>
11805of the function <a href="#lua_gc"><code>lua_gc</code></a> are deprecated.
11806You should use the new option <code>LUA_GCINC</code> to set them.
11807</li>
11808
11809</ul>
11810
11811
11812
11813
11814<h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
11815
11816<p>
11817Here is the complete syntax of Lua in extended BNF.
11818As usual in extended BNF,
11819{A} means 0 or more As,
11820and [A] means an optional A.
11821(For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
11822for a description of the terminals
11823Name, Numeral,
11824and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
11825
11826
11827
11828
11829<pre>
11830
11831	chunk ::= block
11832
11833	block ::= {stat} [retstat]
11834
11835	stat ::=  &lsquo;<b>;</b>&rsquo; | 
11836		 varlist &lsquo;<b>=</b>&rsquo; explist | 
11837		 functioncall | 
11838		 label | 
11839		 <b>break</b> | 
11840		 <b>goto</b> Name | 
11841		 <b>do</b> block <b>end</b> | 
11842		 <b>while</b> exp <b>do</b> block <b>end</b> | 
11843		 <b>repeat</b> block <b>until</b> exp | 
11844		 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | 
11845		 <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> | 
11846		 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> | 
11847		 <b>function</b> funcname funcbody | 
11848		 <b>local</b> <b>function</b> Name funcbody | 
11849		 <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist] 
11850
11851	attnamelist ::=  Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
11852
11853	attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
11854
11855	retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
11856
11857	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
11858
11859	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
11860
11861	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
11862
11863	var ::=  Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name 
11864
11865	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
11866
11867	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
11868
11869	exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef | 
11870		 prefixexp | tableconstructor | exp binop exp | unop exp 
11871
11872	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
11873
11874	functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args 
11875
11876	args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString 
11877
11878	functiondef ::= <b>function</b> funcbody
11879
11880	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
11881
11882	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
11883
11884	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
11885
11886	fieldlist ::= field {fieldsep field} [fieldsep]
11887
11888	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
11889
11890	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
11891
11892	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; | 
11893		 &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; | 
11894		 &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; | 
11895		 <b>and</b> | <b>or</b>
11896
11897	unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
11898
11899</pre>
11900
11901<p>
11902
11903
11904
11905
11906
11907
11908
11909<P CLASS="footer">
11910Last update:
11911Fri Nov 13 15:35:22 UTC 2020
11912</P>
11913<!--
11914Last change: revised for Lua 5.4.2
11915-->
11916
11917</body></html>
11918
11919