]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - doc/manual.html
Import lua 5.3.5
[FreeBSD/FreeBSD.git] / doc / manual.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <HTML>
3 <HEAD>
4 <TITLE>Lua 5.3 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>
14 Lua 5.3 Reference Manual
15 </H1>
16
17 <P>
18 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
19
20 <P>
21 <SMALL>
22 Copyright &copy; 2015&ndash;2018 Lua.org, PUC-Rio.
23 Freely 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,v 1.167.1.2 2018/06/26 15:49:07 roberto Exp $ -->
39
40
41
42
43 <h1>1 &ndash; <a name="1">Introduction</a></h1>
44
45 <p>
46 Lua is a powerful, efficient, lightweight, embeddable scripting language.
47 It supports procedural programming,
48 object-oriented programming, functional programming,
49 data-driven programming, and data description.
50
51
52 <p>
53 Lua combines simple procedural syntax with powerful data description
54 constructs based on associative arrays and extensible semantics.
55 Lua is dynamically typed,
56 runs by interpreting bytecode with a register-based
57 virtual machine,
58 and has automatic memory management with
59 incremental garbage collection,
60 making it ideal for configuration, scripting,
61 and rapid prototyping.
62
63
64 <p>
65 Lua is implemented as a library, written in <em>clean C</em>,
66 the common subset of Standard&nbsp;C and C++.
67 The Lua distribution includes a host program called <code>lua</code>,
68 which uses the Lua library to offer a complete,
69 standalone Lua interpreter,
70 for interactive or batch use.
71 Lua is intended to be used both as a powerful, lightweight,
72 embeddable scripting language for any program that needs one,
73 and as a powerful but lightweight and efficient stand-alone language.
74
75
76 <p>
77 As an extension language, Lua has no notion of a "main" program:
78 it works <em>embedded</em> in a host client,
79 called the <em>embedding program</em> or simply the <em>host</em>.
80 (Frequently, this host is the stand-alone <code>lua</code> program.)
81 The host program can invoke functions to execute a piece of Lua code,
82 can write and read Lua variables,
83 and can register C&nbsp;functions to be called by Lua code.
84 Through the use of C&nbsp;functions, Lua can be augmented to cope with
85 a wide range of different domains,
86 thus creating customized programming languages sharing a syntactical framework.
87
88
89 <p>
90 Lua is free software,
91 and is provided as usual with no guarantees,
92 as stated in its license.
93 The implementation described in this manual is available
94 at Lua's official web site, <code>www.lua.org</code>.
95
96
97 <p>
98 Like any other reference manual,
99 this document is dry in places.
100 For a discussion of the decisions behind the design of Lua,
101 see the technical papers available at Lua's web site.
102 For a detailed introduction to programming in Lua,
103 see Roberto's book, <em>Programming in Lua</em>.
104
105
106
107 <h1>2 &ndash; <a name="2">Basic Concepts</a></h1>
108
109 <p>
110 This section describes the basic concepts of the language.
111
112
113
114 <h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
115
116 <p>
117 Lua is a <em>dynamically typed language</em>.
118 This means that
119 variables do not have types; only values do.
120 There are no type definitions in the language.
121 All values carry their own type.
122
123
124 <p>
125 All values in Lua are <em>first-class values</em>.
126 This means that all values can be stored in variables,
127 passed as arguments to other functions, and returned as results.
128
129
130 <p>
131 There are eight basic types in Lua:
132 <em>nil</em>, <em>boolean</em>, <em>number</em>,
133 <em>string</em>, <em>function</em>, <em>userdata</em>,
134 <em>thread</em>, and <em>table</em>.
135 The type <em>nil</em> has one single value, <b>nil</b>,
136 whose main property is to be different from any other value;
137 it usually represents the absence of a useful value.
138 The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>.
139 Both <b>nil</b> and <b>false</b> make a condition false;
140 any other value makes it true.
141 The type <em>number</em> represents both
142 integer numbers and real (floating-point) numbers.
143 The type <em>string</em> represents immutable sequences of bytes.
144
145 Lua is 8-bit clean:
146 strings can contain any 8-bit value,
147 including embedded zeros ('<code>\0</code>').
148 Lua is also encoding-agnostic;
149 it makes no assumptions about the contents of a string.
150
151
152 <p>
153 The type <em>number</em> uses two internal representations,
154 or two subtypes,
155 one called <em>integer</em> and the other called <em>float</em>.
156 Lua has explicit rules about when each representation is used,
157 but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
158 Therefore,
159 the programmer may choose to mostly ignore the difference
160 between integers and floats
161 or to assume complete control over the representation of each number.
162 Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
163 but you can also compile Lua so that it
164 uses 32-bit integers and/or single-precision (32-bit) floats.
165 The option with 32 bits for both integers and floats
166 is particularly attractive
167 for small machines and embedded systems.
168 (See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
169
170
171 <p>
172 Lua can call (and manipulate) functions written in Lua and
173 functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
174 Both are represented by the type <em>function</em>.
175
176
177 <p>
178 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
179 be stored in Lua variables.
180 A userdata value represents a block of raw memory.
181 There are two kinds of userdata:
182 <em>full userdata</em>,
183 which is an object with a block of memory managed by Lua,
184 and <em>light userdata</em>,
185 which is simply a C&nbsp;pointer value.
186 Userdata has no predefined operations in Lua,
187 except assignment and identity test.
188 By using <em>metatables</em>,
189 the programmer can define operations for full userdata values
190 (see <a href="#2.4">&sect;2.4</a>).
191 Userdata values cannot be created or modified in Lua,
192 only through the C&nbsp;API.
193 This guarantees the integrity of data owned by the host program.
194
195
196 <p>
197 The type <em>thread</em> represents independent threads of execution
198 and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
199 Lua threads are not related to operating-system threads.
200 Lua supports coroutines on all systems,
201 even those that do not support threads natively.
202
203
204 <p>
205 The type <em>table</em> implements associative arrays,
206 that is, arrays that can have as indices not only numbers,
207 but any Lua value except <b>nil</b> and NaN.
208 (<em>Not a Number</em> is a special value used to represent
209 undefined or unrepresentable numerical results, such as <code>0/0</code>.)
210 Tables can be <em>heterogeneous</em>;
211 that is, they can contain values of all types (except <b>nil</b>).
212 Any key with value <b>nil</b> is not considered part of the table.
213 Conversely, any key that is not part of a table has
214 an associated value <b>nil</b>.
215
216
217 <p>
218 Tables are the sole data-structuring mechanism in Lua;
219 they can be used to represent ordinary arrays, lists,
220 symbol tables, sets, records, graphs, trees, etc.
221 To represent records, Lua uses the field name as an index.
222 The language supports this representation by
223 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
224 There are several convenient ways to create tables in Lua
225 (see <a href="#3.4.9">&sect;3.4.9</a>).
226
227
228 <p>
229 Like indices,
230 the values of table fields can be of any type.
231 In particular,
232 because functions are first-class values,
233 table fields can contain functions.
234 Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
235
236
237 <p>
238 The indexing of tables follows
239 the definition of raw equality in the language.
240 The expressions <code>a[i]</code> and <code>a[j]</code>
241 denote the same table element
242 if and only if <code>i</code> and <code>j</code> are raw equal
243 (that is, equal without metamethods).
244 In particular, floats with integral values
245 are equal to their respective integers
246 (e.g., <code>1.0 == 1</code>).
247 To avoid ambiguities,
248 any float with integral value used as a key
249 is converted to its respective integer.
250 For instance, if you write <code>a[2.0] = true</code>,
251 the actual key inserted into the table will be the
252 integer <code>2</code>.
253 (On the other hand,
254 2 and "<code>2</code>" are different Lua values and therefore
255 denote different table entries.)
256
257
258 <p>
259 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
260 variables do not actually <em>contain</em> these values,
261 only <em>references</em> to them.
262 Assignment, parameter passing, and function returns
263 always manipulate references to such values;
264 these operations do not imply any kind of copy.
265
266
267 <p>
268 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
269 of a given value (see <a href="#6.1">&sect;6.1</a>).
270
271
272
273
274
275 <h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
276
277 <p>
278 As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
279 any reference to a free name
280 (that is, a name not bound to any declaration) <code>var</code>
281 is syntactically translated to <code>_ENV.var</code>.
282 Moreover, every chunk is compiled in the scope of
283 an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
284 so <code>_ENV</code> itself is never a free name in a chunk.
285
286
287 <p>
288 Despite the existence of this external <code>_ENV</code> variable and
289 the translation of free names,
290 <code>_ENV</code> is a completely regular name.
291 In particular,
292 you can define new variables and parameters with that name.
293 Each reference to a free name uses the <code>_ENV</code> that is
294 visible at that point in the program,
295 following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
296
297
298 <p>
299 Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
300
301
302 <p>
303 Lua keeps a distinguished environment called the <em>global environment</em>.
304 This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
305 In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
306 (<a href="#pdf-_G"><code>_G</code></a> is never used internally.)
307
308
309 <p>
310 When Lua loads a chunk,
311 the default value for its <code>_ENV</code> upvalue
312 is the global environment (see <a href="#pdf-load"><code>load</code></a>).
313 Therefore, by default,
314 free names in Lua code refer to entries in the global environment
315 (and, therefore, they are also called <em>global variables</em>).
316 Moreover, all standard libraries are loaded in the global environment
317 and some functions there operate on that environment.
318 You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
319 to load a chunk with a different environment.
320 (In C, you have to load the chunk and then change the value
321 of its first upvalue.)
322
323
324
325
326
327 <h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
328
329 <p>
330 Because Lua is an embedded extension language,
331 all Lua actions start from C&nbsp;code in the host program
332 calling a function from the Lua library.
333 (When you use Lua standalone,
334 the <code>lua</code> application is the host program.)
335 Whenever an error occurs during
336 the compilation or execution of a Lua chunk,
337 control returns to the host,
338 which can take appropriate measures
339 (such as printing an error message).
340
341
342 <p>
343 Lua code can explicitly generate an error by calling the
344 <a href="#pdf-error"><code>error</code></a> function.
345 If you need to catch errors in Lua,
346 you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
347 to call a given function in <em>protected mode</em>.
348
349
350 <p>
351 Whenever there is an error,
352 an <em>error object</em> (also called an <em>error message</em>)
353 is propagated with information about the error.
354 Lua itself only generates errors whose error object is a string,
355 but programs may generate errors with
356 any value as the error object.
357 It is up to the Lua program or its host to handle such error objects.
358
359
360 <p>
361 When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
362 you may give a <em>message handler</em>
363 to be called in case of errors.
364 This function is called with the original error object
365 and returns a new error object.
366 It is called before the error unwinds the stack,
367 so that it can gather more information about the error,
368 for instance by inspecting the stack and creating a stack traceback.
369 This message handler is still protected by the protected call;
370 so, an error inside the message handler
371 will call the message handler again.
372 If this loop goes on for too long,
373 Lua breaks it and returns an appropriate message.
374 (The message handler is called only for regular runtime errors.
375 It is not called for memory-allocation errors
376 nor for errors while running finalizers.)
377
378
379
380
381
382 <h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
383
384 <p>
385 Every value in Lua can have a <em>metatable</em>.
386 This <em>metatable</em> is an ordinary Lua table
387 that defines the behavior of the original value
388 under certain special operations.
389 You can change several aspects of the behavior
390 of operations over a value by setting specific fields in its metatable.
391 For instance, when a non-numeric value is the operand of an addition,
392 Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
393 If it finds one,
394 Lua calls this function to perform the addition.
395
396
397 <p>
398 The key for each event in a metatable is a string
399 with the event name prefixed by two underscores;
400 the corresponding values are called <em>metamethods</em>.
401 In the previous example, the key is "<code>__add</code>"
402 and the metamethod is the function that performs the addition.
403 Unless stated otherwise,
404 metamethods should be function values.
405
406
407 <p>
408 You can query the metatable of any value
409 using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
410 Lua queries metamethods in metatables using a raw access (see <a href="#pdf-rawget"><code>rawget</code></a>).
411 So, to retrieve the metamethod for event <code>ev</code> in object <code>o</code>,
412 Lua does the equivalent to the following code:
413
414 <pre>
415      rawget(getmetatable(<em>o</em>) or {}, "__<em>ev</em>")
416 </pre>
417
418 <p>
419 You can replace the metatable of tables
420 using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
421 You cannot change the metatable of other types from Lua code
422 (except by using the debug library (<a href="#6.10">&sect;6.10</a>));
423 you should use the C&nbsp;API for that.
424
425
426 <p>
427 Tables and full userdata have individual metatables
428 (although multiple tables and userdata can share their metatables).
429 Values of all other types share one single metatable per type;
430 that is, there is one single metatable for all numbers,
431 one for all strings, etc.
432 By default, a value has no metatable,
433 but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
434
435
436 <p>
437 A metatable controls how an object behaves in
438 arithmetic operations, bitwise operations,
439 order comparisons, concatenation, length operation, calls, and indexing.
440 A metatable also can define a function to be called
441 when a userdata or a table is garbage collected (<a href="#2.5">&sect;2.5</a>).
442
443
444 <p>
445 For the unary operators (negation, length, and bitwise NOT),
446 the metamethod is computed and called with a dummy second operand,
447 equal to the first one.
448 This extra operand is only to simplify Lua's internals
449 (by making these operators behave like a binary operation)
450 and may be removed in future versions.
451 (For most uses this extra operand is irrelevant.)
452
453
454 <p>
455 A detailed list of events controlled by metatables is given next.
456 Each operation is identified by its corresponding key.
457
458
459
460 <ul>
461
462 <li><b><code>__add</code>: </b>
463 the addition (<code>+</code>) operation.
464 If any operand for an addition is not a number
465 (nor a string coercible to a number),
466 Lua will try to call a metamethod.
467 First, Lua will check the first operand (even if it is valid).
468 If that operand does not define a metamethod for <code>__add</code>,
469 then Lua will check the second operand.
470 If Lua can find a metamethod,
471 it calls the metamethod with the two operands as arguments,
472 and the result of the call
473 (adjusted to one value)
474 is the result of the operation.
475 Otherwise,
476 it raises an error.
477 </li>
478
479 <li><b><code>__sub</code>: </b>
480 the subtraction (<code>-</code>) operation.
481 Behavior similar to the addition operation.
482 </li>
483
484 <li><b><code>__mul</code>: </b>
485 the multiplication (<code>*</code>) operation.
486 Behavior similar to the addition operation.
487 </li>
488
489 <li><b><code>__div</code>: </b>
490 the division (<code>/</code>) operation.
491 Behavior similar to the addition operation.
492 </li>
493
494 <li><b><code>__mod</code>: </b>
495 the modulo (<code>%</code>) operation.
496 Behavior similar to the addition operation.
497 </li>
498
499 <li><b><code>__pow</code>: </b>
500 the exponentiation (<code>^</code>) operation.
501 Behavior similar to the addition operation.
502 </li>
503
504 <li><b><code>__unm</code>: </b>
505 the negation (unary <code>-</code>) operation.
506 Behavior similar to the addition operation.
507 </li>
508
509 <li><b><code>__idiv</code>: </b>
510 the floor division (<code>//</code>) operation.
511 Behavior similar to the addition operation.
512 </li>
513
514 <li><b><code>__band</code>: </b>
515 the bitwise AND (<code>&amp;</code>) operation.
516 Behavior similar to the addition operation,
517 except that Lua will try a metamethod
518 if any operand is neither an integer
519 nor a value coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
520 </li>
521
522 <li><b><code>__bor</code>: </b>
523 the bitwise OR (<code>|</code>) operation.
524 Behavior similar to the bitwise AND operation.
525 </li>
526
527 <li><b><code>__bxor</code>: </b>
528 the bitwise exclusive OR (binary <code>~</code>) operation.
529 Behavior similar to the bitwise AND operation.
530 </li>
531
532 <li><b><code>__bnot</code>: </b>
533 the bitwise NOT (unary <code>~</code>) operation.
534 Behavior similar to the bitwise AND operation.
535 </li>
536
537 <li><b><code>__shl</code>: </b>
538 the bitwise left shift (<code>&lt;&lt;</code>) operation.
539 Behavior similar to the bitwise AND operation.
540 </li>
541
542 <li><b><code>__shr</code>: </b>
543 the bitwise right shift (<code>&gt;&gt;</code>) operation.
544 Behavior similar to the bitwise AND operation.
545 </li>
546
547 <li><b><code>__concat</code>: </b>
548 the concatenation (<code>..</code>) operation.
549 Behavior similar to the addition operation,
550 except that Lua will try a metamethod
551 if any operand is neither a string nor a number
552 (which is always coercible to a string).
553 </li>
554
555 <li><b><code>__len</code>: </b>
556 the length (<code>#</code>) operation.
557 If the object is not a string,
558 Lua will try its metamethod.
559 If there is a metamethod,
560 Lua calls it with the object as argument,
561 and the result of the call
562 (always adjusted to one value)
563 is the result of the operation.
564 If there is no metamethod but the object is a table,
565 then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
566 Otherwise, Lua raises an error.
567 </li>
568
569 <li><b><code>__eq</code>: </b>
570 the equal (<code>==</code>) operation.
571 Behavior similar to the addition operation,
572 except that Lua will try a metamethod only when the values
573 being compared are either both tables or both full userdata
574 and they are not primitively equal.
575 The result of the call is always converted to a boolean.
576 </li>
577
578 <li><b><code>__lt</code>: </b>
579 the less than (<code>&lt;</code>) operation.
580 Behavior similar to the addition operation,
581 except that Lua will try a metamethod only when the values
582 being compared are neither both numbers nor both strings.
583 The result of the call is always converted to a boolean.
584 </li>
585
586 <li><b><code>__le</code>: </b>
587 the less equal (<code>&lt;=</code>) operation.
588 Unlike other operations,
589 the less-equal operation can use two different events.
590 First, Lua looks for the <code>__le</code> metamethod in both operands,
591 like in the less than operation.
592 If it cannot find such a metamethod,
593 then it will try the <code>__lt</code> metamethod,
594 assuming that <code>a &lt;= b</code> is equivalent to <code>not (b &lt; a)</code>.
595 As with the other comparison operators,
596 the result is always a boolean.
597 (This use of the <code>__lt</code> event can be removed in future versions;
598 it is also slower than a real <code>__le</code> metamethod.)
599 </li>
600
601 <li><b><code>__index</code>: </b>
602 The indexing access operation <code>table[key]</code>.
603 This event happens when <code>table</code> is not a table or
604 when <code>key</code> is not present in <code>table</code>.
605 The metamethod is looked up in <code>table</code>.
606
607
608 <p>
609 Despite the name,
610 the metamethod for this event can be either a function or a table.
611 If it is a function,
612 it is called with <code>table</code> and <code>key</code> as arguments,
613 and the result of the call
614 (adjusted to one value)
615 is the result of the operation.
616 If it is a table,
617 the final result is the result of indexing this table with <code>key</code>.
618 (This indexing is regular, not raw,
619 and therefore can trigger another metamethod.)
620 </li>
621
622 <li><b><code>__newindex</code>: </b>
623 The indexing assignment <code>table[key] = value</code>.
624 Like the index event,
625 this event happens when <code>table</code> is not a table or
626 when <code>key</code> is not present in <code>table</code>.
627 The metamethod is looked up in <code>table</code>.
628
629
630 <p>
631 Like with indexing,
632 the metamethod for this event can be either a function or a table.
633 If it is a function,
634 it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
635 If it is a table,
636 Lua does an indexing assignment to this table with the same key and value.
637 (This assignment is regular, not raw,
638 and therefore can trigger another metamethod.)
639
640
641 <p>
642 Whenever there is a <code>__newindex</code> metamethod,
643 Lua does not perform the primitive assignment.
644 (If necessary,
645 the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
646 to do the assignment.)
647 </li>
648
649 <li><b><code>__call</code>: </b>
650 The call operation <code>func(args)</code>.
651 This event happens when Lua tries to call a non-function value
652 (that is, <code>func</code> is not a function).
653 The metamethod is looked up in <code>func</code>.
654 If present,
655 the metamethod is called with <code>func</code> as its first argument,
656 followed by the arguments of the original call (<code>args</code>).
657 All results of the call
658 are the result of the operation.
659 (This is the only metamethod that allows multiple results.)
660 </li>
661
662 </ul>
663
664 <p>
665 It is a good practice to add all needed metamethods to a table
666 before setting it as a metatable of some object.
667 In particular, the <code>__gc</code> metamethod works only when this order
668 is followed (see <a href="#2.5.1">&sect;2.5.1</a>).
669
670
671 <p>
672 Because metatables are regular tables,
673 they can contain arbitrary fields,
674 not only the event names defined above.
675 Some functions in the standard library
676 (e.g., <a href="#pdf-tostring"><code>tostring</code></a>)
677 use other fields in metatables for their own purposes.
678
679
680
681
682
683 <h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
684
685 <p>
686 Lua performs automatic memory management.
687 This means that
688 you do not have to worry about allocating memory for new objects
689 or freeing it when the objects are no longer needed.
690 Lua manages memory automatically by running
691 a <em>garbage collector</em> to collect all <em>dead objects</em>
692 (that is, objects that are no longer accessible from Lua).
693 All memory used by Lua is subject to automatic management:
694 strings, tables, userdata, functions, threads, internal structures, etc.
695
696
697 <p>
698 Lua implements an incremental mark-and-sweep collector.
699 It uses two numbers to control its garbage-collection cycles:
700 the <em>garbage-collector pause</em> and
701 the <em>garbage-collector step multiplier</em>.
702 Both use percentage points as units
703 (e.g., a value of 100 means an internal value of 1).
704
705
706 <p>
707 The garbage-collector pause
708 controls how long the collector waits before starting a new cycle.
709 Larger values make the collector less aggressive.
710 Values smaller than 100 mean the collector will not wait to
711 start a new cycle.
712 A value of 200 means that the collector waits for the total memory in use
713 to double before starting a new cycle.
714
715
716 <p>
717 The garbage-collector step multiplier
718 controls the relative speed of the collector relative to
719 memory allocation.
720 Larger values make the collector more aggressive but also increase
721 the size of each incremental step.
722 You should not use values smaller than 100,
723 because they make the collector too slow and
724 can result in the collector never finishing a cycle.
725 The default is 200,
726 which means that the collector runs at "twice"
727 the speed of memory allocation.
728
729
730 <p>
731 If you set the step multiplier to a very large number
732 (larger than 10% of the maximum number of
733 bytes that the program may use),
734 the collector behaves like a stop-the-world collector.
735 If you then set the pause to 200,
736 the collector behaves as in old Lua versions,
737 doing a complete collection every time Lua doubles its
738 memory usage.
739
740
741 <p>
742 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
743 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
744 You can also use these functions to control
745 the collector directly (e.g., stop and restart it).
746
747
748
749 <h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
750
751 <p>
752 You can set garbage-collector metamethods for tables
753 and, using the C&nbsp;API,
754 for full userdata (see <a href="#2.4">&sect;2.4</a>).
755 These metamethods are also called <em>finalizers</em>.
756 Finalizers allow you to coordinate Lua's garbage collection
757 with external resource management
758 (such as closing files, network or database connections,
759 or freeing your own memory).
760
761
762 <p>
763 For an object (table or userdata) to be finalized when collected,
764 you must <em>mark</em> it for finalization.
765
766 You mark an object for finalization when you set its metatable
767 and the metatable has a field indexed by the string "<code>__gc</code>".
768 Note that if you set a metatable without a <code>__gc</code> field
769 and later create that field in the metatable,
770 the object will not be marked for finalization.
771
772
773 <p>
774 When a marked object becomes garbage,
775 it is not collected immediately by the garbage collector.
776 Instead, Lua puts it in a list.
777 After the collection,
778 Lua goes through that list.
779 For each object in the list,
780 it checks the object's <code>__gc</code> metamethod:
781 If it is a function,
782 Lua calls it with the object as its single argument;
783 if the metamethod is not a function,
784 Lua simply ignores it.
785
786
787 <p>
788 At the end of each garbage-collection cycle,
789 the finalizers for objects are called in
790 the reverse order that the objects were marked for finalization,
791 among those collected in that cycle;
792 that is, the first finalizer to be called is the one associated
793 with the object marked last in the program.
794 The execution of each finalizer may occur at any point during
795 the execution of the regular code.
796
797
798 <p>
799 Because the object being collected must still be used by the finalizer,
800 that object (and other objects accessible only through it)
801 must be <em>resurrected</em> by Lua.
802 Usually, this resurrection is transient,
803 and the object memory is freed in the next garbage-collection cycle.
804 However, if the finalizer stores the object in some global place
805 (e.g., a global variable),
806 then the resurrection is permanent.
807 Moreover, if the finalizer marks a finalizing object for finalization again,
808 its finalizer will be called again in the next cycle where the
809 object is unreachable.
810 In any case,
811 the object memory is freed only in a GC cycle where
812 the object is unreachable and not marked for finalization.
813
814
815 <p>
816 When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
817 Lua calls the finalizers of all objects marked for finalization,
818 following the reverse order that they were marked.
819 If any finalizer marks objects for collection during that phase,
820 these marks have no effect.
821
822
823
824
825
826 <h3>2.5.2 &ndash; <a name="2.5.2">Weak Tables</a></h3>
827
828 <p>
829 A <em>weak table</em> is a table whose elements are
830 <em>weak references</em>.
831 A weak reference is ignored by the garbage collector.
832 In other words,
833 if the only references to an object are weak references,
834 then the garbage collector will collect that object.
835
836
837 <p>
838 A weak table can have weak keys, weak values, or both.
839 A table with weak values allows the collection of its values,
840 but prevents the collection of its keys.
841 A table with both weak keys and weak values allows the collection of
842 both keys and values.
843 In any case, if either the key or the value is collected,
844 the whole pair is removed from the table.
845 The weakness of a table is controlled by the
846 <code>__mode</code> field of its metatable.
847 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
848 the keys in the table are weak.
849 If <code>__mode</code> contains '<code>v</code>',
850 the values in the table are weak.
851
852
853 <p>
854 A table with weak keys and strong values
855 is also called an <em>ephemeron table</em>.
856 In an ephemeron table,
857 a value is considered reachable only if its key is reachable.
858 In particular,
859 if the only reference to a key comes through its value,
860 the pair is removed.
861
862
863 <p>
864 Any change in the weakness of a table may take effect only
865 at the next collect cycle.
866 In particular, if you change the weakness to a stronger mode,
867 Lua may still collect some items from that table
868 before the change takes effect.
869
870
871 <p>
872 Only objects that have an explicit construction
873 are removed from weak tables.
874 Values, such as numbers and light C&nbsp;functions,
875 are not subject to garbage collection,
876 and therefore are not removed from weak tables
877 (unless their associated values are collected).
878 Although strings are subject to garbage collection,
879 they do not have an explicit construction,
880 and therefore are not removed from weak tables.
881
882
883 <p>
884 Resurrected objects
885 (that is, objects being finalized
886 and objects accessible only through objects being finalized)
887 have a special behavior in weak tables.
888 They are removed from weak values before running their finalizers,
889 but are removed from weak keys only in the next collection
890 after running their finalizers, when such objects are actually freed.
891 This behavior allows the finalizer to access properties
892 associated with the object through weak tables.
893
894
895 <p>
896 If a weak table is among the resurrected objects in a collection cycle,
897 it may not be properly cleared until the next cycle.
898
899
900
901
902
903
904
905 <h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
906
907 <p>
908 Lua supports coroutines,
909 also called <em>collaborative multithreading</em>.
910 A coroutine in Lua represents an independent thread of execution.
911 Unlike threads in multithread systems, however,
912 a coroutine only suspends its execution by explicitly calling
913 a yield function.
914
915
916 <p>
917 You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
918 Its sole argument is a function
919 that is the main function of the coroutine.
920 The <code>create</code> function only creates a new coroutine and
921 returns a handle to it (an object of type <em>thread</em>);
922 it does not start the coroutine.
923
924
925 <p>
926 You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
927 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
928 passing as its first argument
929 a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
930 the coroutine starts its execution by
931 calling its main function.
932 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
933 as arguments to that function.
934 After the coroutine starts running,
935 it runs until it terminates or <em>yields</em>.
936
937
938 <p>
939 A coroutine can terminate its execution in two ways:
940 normally, when its main function returns
941 (explicitly or implicitly, after the last instruction);
942 and abnormally, if there is an unprotected error.
943 In case of normal termination,
944 <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
945 plus any values returned by the coroutine main function.
946 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
947 plus an error object.
948
949
950 <p>
951 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
952 When a coroutine yields,
953 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
954 even if the yield happens inside nested function calls
955 (that is, not in the main function,
956 but in a function directly or indirectly called by the main function).
957 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
958 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
959 The next time you resume the same coroutine,
960 it continues its execution from the point where it yielded,
961 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
962 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
963
964
965 <p>
966 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
967 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
968 but instead of returning the coroutine itself,
969 it returns a function that, when called, resumes the coroutine.
970 Any arguments passed to this function
971 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
972 <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>,
973 except the first one (the boolean error code).
974 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
975 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
976 any error is propagated to the caller.
977
978
979 <p>
980 As an example of how coroutines work,
981 consider the following code:
982
983 <pre>
984      function foo (a)
985        print("foo", a)
986        return coroutine.yield(2*a)
987      end
988      
989      co = coroutine.create(function (a,b)
990            print("co-body", a, b)
991            local r = foo(a+1)
992            print("co-body", r)
993            local r, s = coroutine.yield(a+b, a-b)
994            print("co-body", r, s)
995            return b, "end"
996      end)
997      
998      print("main", coroutine.resume(co, 1, 10))
999      print("main", coroutine.resume(co, "r"))
1000      print("main", coroutine.resume(co, "x", "y"))
1001      print("main", coroutine.resume(co, "x", "y"))
1002 </pre><p>
1003 When you run it, it produces the following output:
1004
1005 <pre>
1006      co-body 1       10
1007      foo     2
1008      main    true    4
1009      co-body r
1010      main    true    11      -9
1011      co-body x       y
1012      main    true    10      end
1013      main    false   cannot resume dead coroutine
1014 </pre>
1015
1016 <p>
1017 You can also create and manipulate coroutines through the C API:
1018 see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1019 and <a href="#lua_yield"><code>lua_yield</code></a>.
1020
1021
1022
1023
1024
1025 <h1>3 &ndash; <a name="3">The Language</a></h1>
1026
1027 <p>
1028 This section describes the lexis, the syntax, and the semantics of Lua.
1029 In other words,
1030 this section describes
1031 which tokens are valid,
1032 how they can be combined,
1033 and what their combinations mean.
1034
1035
1036 <p>
1037 Language constructs will be explained using the usual extended BNF notation,
1038 in which
1039 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1040 [<em>a</em>]&nbsp;means an optional <em>a</em>.
1041 Non-terminals are shown like non-terminal,
1042 keywords are shown like <b>kword</b>,
1043 and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1044 The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1045 at the end of this manual.
1046
1047
1048
1049 <h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1050
1051 <p>
1052 Lua is a free-form language.
1053 It ignores spaces (including new lines) and comments
1054 between lexical elements (tokens),
1055 except as delimiters between names and keywords.
1056
1057
1058 <p>
1059 <em>Names</em>
1060 (also called <em>identifiers</em>)
1061 in Lua can be any string of letters,
1062 digits, and underscores,
1063 not beginning with a digit and
1064 not being a reserved word.
1065 Identifiers are used to name variables, table fields, and labels.
1066
1067
1068 <p>
1069 The following <em>keywords</em> are reserved
1070 and cannot be used as names:
1071
1072
1073 <pre>
1074      and       break     do        else      elseif    end
1075      false     for       function  goto      if        in
1076      local     nil       not       or        repeat    return
1077      then      true      until     while
1078 </pre>
1079
1080 <p>
1081 Lua is a case-sensitive language:
1082 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1083 are two different, valid names.
1084 As a convention,
1085 programs should avoid creating
1086 names that start with an underscore followed by
1087 one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1088
1089
1090 <p>
1091 The following strings denote other tokens:
1092
1093 <pre>
1094      +     -     *     /     %     ^     #
1095      &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
1096      ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
1097      (     )     {     }     [     ]     ::
1098      ;     :     ,     .     ..    ...
1099 </pre>
1100
1101 <p>
1102 A <em>short literal string</em>
1103 can be delimited by matching single or double quotes,
1104 and can contain the following C-like escape sequences:
1105 '<code>\a</code>' (bell),
1106 '<code>\b</code>' (backspace),
1107 '<code>\f</code>' (form feed),
1108 '<code>\n</code>' (newline),
1109 '<code>\r</code>' (carriage return),
1110 '<code>\t</code>' (horizontal tab),
1111 '<code>\v</code>' (vertical tab),
1112 '<code>\\</code>' (backslash),
1113 '<code>\"</code>' (quotation mark [double quote]),
1114 and '<code>\'</code>' (apostrophe [single quote]).
1115 A backslash followed by a line break
1116 results in a newline in the string.
1117 The escape sequence '<code>\z</code>' skips the following span
1118 of white-space characters,
1119 including line breaks;
1120 it is particularly useful to break and indent a long literal string
1121 into multiple lines without adding the newlines and spaces
1122 into the string contents.
1123 A short literal string cannot contain unescaped line breaks
1124 nor escapes not forming a valid escape sequence.
1125
1126
1127 <p>
1128 We can specify any byte in a short literal string by its numeric value
1129 (including embedded zeros).
1130 This can be done
1131 with the escape sequence <code>\x<em>XX</em></code>,
1132 where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1133 or with the escape sequence <code>\<em>ddd</em></code>,
1134 where <em>ddd</em> is a sequence of up to three decimal digits.
1135 (Note that if a decimal escape sequence is to be followed by a digit,
1136 it must be expressed using exactly three digits.)
1137
1138
1139 <p>
1140 The UTF-8 encoding of a Unicode character
1141 can be inserted in a literal string with
1142 the escape sequence <code>\u{<em>XXX</em>}</code>
1143 (note the mandatory enclosing brackets),
1144 where <em>XXX</em> is a sequence of one or more hexadecimal digits
1145 representing the character code point.
1146
1147
1148 <p>
1149 Literal strings can also be defined using a long format
1150 enclosed by <em>long brackets</em>.
1151 We define an <em>opening long bracket of level <em>n</em></em> as an opening
1152 square bracket followed by <em>n</em> equal signs followed by another
1153 opening square bracket.
1154 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>, 
1155 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>, 
1156 and so on.
1157 A <em>closing long bracket</em> is defined similarly;
1158 for instance,
1159 a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
1160 A <em>long literal</em> starts with an opening long bracket of any level and
1161 ends at the first closing long bracket of the same level.
1162 It can contain any text except a closing bracket of the same level.
1163 Literals in this bracketed form can run for several lines,
1164 do not interpret any escape sequences,
1165 and ignore long brackets of any other level.
1166 Any kind of end-of-line sequence
1167 (carriage return, newline, carriage return followed by newline,
1168 or newline followed by carriage return)
1169 is converted to a simple newline.
1170
1171
1172 <p>
1173 For convenience,
1174 when the opening long bracket is immediately followed by a newline,
1175 the newline is not included in the string.
1176 As an example, in a system using ASCII
1177 (in which '<code>a</code>' is coded as&nbsp;97,
1178 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1179 the five literal strings below denote the same string:
1180
1181 <pre>
1182      a = 'alo\n123"'
1183      a = "alo\n123\""
1184      a = '\97lo\10\04923"'
1185      a = [[alo
1186      123"]]
1187      a = [==[
1188      alo
1189      123"]==]
1190 </pre>
1191
1192 <p>
1193 Any byte in a literal string not
1194 explicitly affected by the previous rules represents itself.
1195 However, Lua opens files for parsing in text mode,
1196 and the system file functions may have problems with
1197 some control characters.
1198 So, it is safer to represent
1199 non-text data as a quoted literal with
1200 explicit escape sequences for the non-text characters.
1201
1202
1203 <p>
1204 A <em>numeric constant</em> (or <em>numeral</em>)
1205 can be written with an optional fractional part
1206 and an optional decimal exponent,
1207 marked by a letter '<code>e</code>' or '<code>E</code>'.
1208 Lua also accepts hexadecimal constants,
1209 which start with <code>0x</code> or <code>0X</code>.
1210 Hexadecimal constants also accept an optional fractional part
1211 plus an optional binary exponent,
1212 marked by a letter '<code>p</code>' or '<code>P</code>'.
1213 A numeric constant with a radix point or an exponent
1214 denotes a float;
1215 otherwise,
1216 if its value fits in an integer,
1217 it denotes an integer.
1218 Examples of valid integer constants are
1219
1220 <pre>
1221      3   345   0xff   0xBEBADA
1222 </pre><p>
1223 Examples of valid float constants are
1224
1225 <pre>
1226      3.0     3.1416     314.16e-2     0.31416E1     34e1
1227      0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
1228 </pre>
1229
1230 <p>
1231 A <em>comment</em> starts with a double hyphen (<code>--</code>)
1232 anywhere outside a string.
1233 If the text immediately after <code>--</code> is not an opening long bracket,
1234 the comment is a <em>short comment</em>,
1235 which runs until the end of the line.
1236 Otherwise, it is a <em>long comment</em>,
1237 which runs until the corresponding closing long bracket.
1238 Long comments are frequently used to disable code temporarily.
1239
1240
1241
1242
1243
1244 <h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1245
1246 <p>
1247 Variables are places that store values.
1248 There are three kinds of variables in Lua:
1249 global variables, local variables, and table fields.
1250
1251
1252 <p>
1253 A single name can denote a global variable or a local variable
1254 (or a function's formal parameter,
1255 which is a particular kind of local variable):
1256
1257 <pre>
1258         var ::= Name
1259 </pre><p>
1260 Name denotes identifiers, as defined in <a href="#3.1">&sect;3.1</a>.
1261
1262
1263 <p>
1264 Any variable name is assumed to be global unless explicitly declared
1265 as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1266 Local variables are <em>lexically scoped</em>:
1267 local variables can be freely accessed by functions
1268 defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1269
1270
1271 <p>
1272 Before the first assignment to a variable, its value is <b>nil</b>.
1273
1274
1275 <p>
1276 Square brackets are used to index a table:
1277
1278 <pre>
1279         var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1280 </pre><p>
1281 The meaning of accesses to table fields can be changed via metatables
1282 (see <a href="#2.4">&sect;2.4</a>).
1283
1284
1285 <p>
1286 The syntax <code>var.Name</code> is just syntactic sugar for
1287 <code>var["Name"]</code>:
1288
1289 <pre>
1290         var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1291 </pre>
1292
1293 <p>
1294 An access to a global variable <code>x</code>
1295 is equivalent to <code>_ENV.x</code>.
1296 Due to the way that chunks are compiled,
1297 <code>_ENV</code> is never a global name (see <a href="#2.2">&sect;2.2</a>).
1298
1299
1300
1301
1302
1303 <h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1304
1305 <p>
1306 Lua supports an almost conventional set of statements,
1307 similar to those in Pascal or C.
1308 This set includes
1309 assignments, control structures, function calls,
1310 and variable declarations.
1311
1312
1313
1314 <h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1315
1316 <p>
1317 A block is a list of statements,
1318 which are executed sequentially:
1319
1320 <pre>
1321         block ::= {stat}
1322 </pre><p>
1323 Lua has <em>empty statements</em>
1324 that allow you to separate statements with semicolons,
1325 start a block with a semicolon
1326 or write two semicolons in sequence:
1327
1328 <pre>
1329         stat ::= &lsquo;<b>;</b>&rsquo;
1330 </pre>
1331
1332 <p>
1333 Function calls and assignments
1334 can start with an open parenthesis.
1335 This possibility leads to an ambiguity in Lua's grammar.
1336 Consider the following fragment:
1337
1338 <pre>
1339      a = b + c
1340      (print or io.write)('done')
1341 </pre><p>
1342 The grammar could see it in two ways:
1343
1344 <pre>
1345      a = b + c(print or io.write)('done')
1346      
1347      a = b + c; (print or io.write)('done')
1348 </pre><p>
1349 The current parser always sees such constructions
1350 in the first way,
1351 interpreting the open parenthesis
1352 as the start of the arguments to a call.
1353 To avoid this ambiguity,
1354 it is a good practice to always precede with a semicolon
1355 statements that start with a parenthesis:
1356
1357 <pre>
1358      ;(print or io.write)('done')
1359 </pre>
1360
1361 <p>
1362 A block can be explicitly delimited to produce a single statement:
1363
1364 <pre>
1365         stat ::= <b>do</b> block <b>end</b>
1366 </pre><p>
1367 Explicit blocks are useful
1368 to control the scope of variable declarations.
1369 Explicit blocks are also sometimes used to
1370 add a <b>return</b> statement in the middle
1371 of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1372
1373
1374
1375
1376
1377 <h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1378
1379 <p>
1380 The unit of compilation of Lua is called a <em>chunk</em>.
1381 Syntactically,
1382 a chunk is simply a block:
1383
1384 <pre>
1385         chunk ::= block
1386 </pre>
1387
1388 <p>
1389 Lua handles a chunk as the body of an anonymous function
1390 with a variable number of arguments
1391 (see <a href="#3.4.11">&sect;3.4.11</a>).
1392 As such, chunks can define local variables,
1393 receive arguments, and return values.
1394 Moreover, such anonymous function is compiled as in the
1395 scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1396 The resulting function always has <code>_ENV</code> as its only upvalue,
1397 even if it does not use that variable.
1398
1399
1400 <p>
1401 A chunk can be stored in a file or in a string inside the host program.
1402 To execute a chunk,
1403 Lua first <em>loads</em> it,
1404 precompiling the chunk's code into instructions for a virtual machine,
1405 and then Lua executes the compiled code
1406 with an interpreter for the virtual machine.
1407
1408
1409 <p>
1410 Chunks can also be precompiled into binary form;
1411 see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1412 Programs in source and compiled forms are interchangeable;
1413 Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1414
1415
1416
1417
1418
1419 <h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1420
1421 <p>
1422 Lua allows multiple assignments.
1423 Therefore, the syntax for assignment
1424 defines a list of variables on the left side
1425 and a list of expressions on the right side.
1426 The elements in both lists are separated by commas:
1427
1428 <pre>
1429         stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1430         varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1431         explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1432 </pre><p>
1433 Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1434
1435
1436 <p>
1437 Before the assignment,
1438 the list of values is <em>adjusted</em> to the length of
1439 the list of variables.
1440 If there are more values than needed,
1441 the excess values are thrown away.
1442 If there are fewer values than needed,
1443 the list is extended with as many  <b>nil</b>'s as needed.
1444 If the list of expressions ends with a function call,
1445 then all values returned by that call enter the list of values,
1446 before the adjustment
1447 (except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1448
1449
1450 <p>
1451 The assignment statement first evaluates all its expressions
1452 and only then the assignments are performed.
1453 Thus the code
1454
1455 <pre>
1456      i = 3
1457      i, a[i] = i+1, 20
1458 </pre><p>
1459 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1460 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1461 before it is assigned&nbsp;4.
1462 Similarly, the line
1463
1464 <pre>
1465      x, y = y, x
1466 </pre><p>
1467 exchanges the values of <code>x</code> and <code>y</code>,
1468 and
1469
1470 <pre>
1471      x, y, z = y, z, x
1472 </pre><p>
1473 cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1474
1475
1476 <p>
1477 An assignment to a global name <code>x = val</code>
1478 is equivalent to the assignment
1479 <code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1480
1481
1482 <p>
1483 The meaning of assignments to table fields and
1484 global variables (which are actually table fields, too)
1485 can be changed via metatables (see <a href="#2.4">&sect;2.4</a>).
1486
1487
1488
1489
1490
1491 <h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1492 The control structures
1493 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1494 familiar syntax:
1495
1496
1497
1498
1499 <pre>
1500         stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1501         stat ::= <b>repeat</b> block <b>until</b> exp
1502         stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1503 </pre><p>
1504 Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1505
1506
1507 <p>
1508 The condition expression of a
1509 control structure can return any value.
1510 Both <b>false</b> and <b>nil</b> are considered false.
1511 All values different from <b>nil</b> and <b>false</b> are considered true
1512 (in particular, the number 0 and the empty string are also true).
1513
1514
1515 <p>
1516 In the <b>repeat</b>&ndash;<b>until</b> loop,
1517 the inner block does not end at the <b>until</b> keyword,
1518 but only after the condition.
1519 So, the condition can refer to local variables
1520 declared inside the loop block.
1521
1522
1523 <p>
1524 The <b>goto</b> statement transfers the program control to a label.
1525 For syntactical reasons,
1526 labels in Lua are considered statements too:
1527
1528
1529
1530 <pre>
1531         stat ::= <b>goto</b> Name
1532         stat ::= label
1533         label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1534 </pre>
1535
1536 <p>
1537 A label is visible in the entire block where it is defined,
1538 except
1539 inside nested blocks where a label with the same name is defined and
1540 inside nested functions.
1541 A goto may jump to any visible label as long as it does not
1542 enter into the scope of a local variable.
1543
1544
1545 <p>
1546 Labels and empty statements are called <em>void statements</em>,
1547 as they perform no actions.
1548
1549
1550 <p>
1551 The <b>break</b> statement terminates the execution of a
1552 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1553 skipping to the next statement after the loop:
1554
1555
1556 <pre>
1557         stat ::= <b>break</b>
1558 </pre><p>
1559 A <b>break</b> ends the innermost enclosing loop.
1560
1561
1562 <p>
1563 The <b>return</b> statement is used to return values
1564 from a function or a chunk
1565 (which is an anonymous function).
1566
1567 Functions can return more than one value,
1568 so the syntax for the <b>return</b> statement is
1569
1570 <pre>
1571         stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1572 </pre>
1573
1574 <p>
1575 The <b>return</b> statement can only be written
1576 as the last statement of a block.
1577 If it is really necessary to <b>return</b> in the middle of a block,
1578 then an explicit inner block can be used,
1579 as in the idiom <code>do return end</code>,
1580 because now <b>return</b> is the last statement in its (inner) block.
1581
1582
1583
1584
1585
1586 <h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1587
1588 <p>
1589
1590 The <b>for</b> statement has two forms:
1591 one numerical and one generic.
1592
1593
1594 <p>
1595 The numerical <b>for</b> loop repeats a block of code while a
1596 control variable runs through an arithmetic progression.
1597 It has the following syntax:
1598
1599 <pre>
1600         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>
1601 </pre><p>
1602 The <em>block</em> is repeated for <em>name</em> starting at the value of
1603 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
1604 third <em>exp</em>.
1605 More precisely, a <b>for</b> statement like
1606
1607 <pre>
1608      for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
1609 </pre><p>
1610 is equivalent to the code:
1611
1612 <pre>
1613      do
1614        local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
1615        if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
1616        <em>var</em> = <em>var</em> - <em>step</em>
1617        while true do
1618          <em>var</em> = <em>var</em> + <em>step</em>
1619          if (<em>step</em> &gt;= 0 and <em>var</em> &gt; <em>limit</em>) or (<em>step</em> &lt; 0 and <em>var</em> &lt; <em>limit</em>) then
1620            break
1621          end
1622          local v = <em>var</em>
1623          <em>block</em>
1624        end
1625      end
1626 </pre>
1627
1628 <p>
1629 Note the following:
1630
1631 <ul>
1632
1633 <li>
1634 All three control expressions are evaluated only once,
1635 before the loop starts.
1636 They must all result in numbers.
1637 </li>
1638
1639 <li>
1640 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
1641 The names shown here are for explanatory purposes only.
1642 </li>
1643
1644 <li>
1645 If the third expression (the step) is absent,
1646 then a step of&nbsp;1 is used.
1647 </li>
1648
1649 <li>
1650 You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop.
1651 </li>
1652
1653 <li>
1654 The loop variable <code>v</code> is local to the loop body.
1655 If you need its value after the loop,
1656 assign it to another variable before exiting the loop.
1657 </li>
1658
1659 </ul>
1660
1661 <p>
1662 The generic <b>for</b> statement works over functions,
1663 called <em>iterators</em>.
1664 On each iteration, the iterator function is called to produce a new value,
1665 stopping when this new value is <b>nil</b>.
1666 The generic <b>for</b> loop has the following syntax:
1667
1668 <pre>
1669         stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1670         namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1671 </pre><p>
1672 A <b>for</b> statement like
1673
1674 <pre>
1675      for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
1676 </pre><p>
1677 is equivalent to the code:
1678
1679 <pre>
1680      do
1681        local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
1682        while true do
1683          local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
1684          if <em>var_1</em> == nil then break end
1685          <em>var</em> = <em>var_1</em>
1686          <em>block</em>
1687        end
1688      end
1689 </pre><p>
1690 Note the following:
1691
1692 <ul>
1693
1694 <li>
1695 <code><em>explist</em></code> is evaluated only once.
1696 Its results are an <em>iterator</em> function,
1697 a <em>state</em>,
1698 and an initial value for the first <em>iterator variable</em>.
1699 </li>
1700
1701 <li>
1702 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
1703 The names are here for explanatory purposes only.
1704 </li>
1705
1706 <li>
1707 You can use <b>break</b> to exit a <b>for</b> loop.
1708 </li>
1709
1710 <li>
1711 The loop variables <code><em>var_i</em></code> are local to the loop;
1712 you cannot use their values after the <b>for</b> ends.
1713 If you need these values,
1714 then assign them to other variables before breaking or exiting the loop.
1715 </li>
1716
1717 </ul>
1718
1719
1720
1721
1722 <h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1723 To allow possible side-effects,
1724 function calls can be executed as statements:
1725
1726 <pre>
1727         stat ::= functioncall
1728 </pre><p>
1729 In this case, all returned values are thrown away.
1730 Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1731
1732
1733
1734
1735
1736 <h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1737 Local variables can be declared anywhere inside a block.
1738 The declaration can include an initial assignment:
1739
1740 <pre>
1741         stat ::= <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
1742 </pre><p>
1743 If present, an initial assignment has the same semantics
1744 of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1745 Otherwise, all variables are initialized with <b>nil</b>.
1746
1747
1748 <p>
1749 A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1750 and so local variables can be declared in a chunk outside any explicit block.
1751
1752
1753 <p>
1754 The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1755
1756
1757
1758
1759
1760
1761
1762 <h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
1763
1764 <p>
1765 The basic expressions in Lua are the following:
1766
1767 <pre>
1768         exp ::= prefixexp
1769         exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1770         exp ::= Numeral
1771         exp ::= LiteralString
1772         exp ::= functiondef
1773         exp ::= tableconstructor
1774         exp ::= &lsquo;<b>...</b>&rsquo;
1775         exp ::= exp binop exp
1776         exp ::= unop exp
1777         prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1778 </pre>
1779
1780 <p>
1781 Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1782 variables are explained in <a href="#3.2">&sect;3.2</a>;
1783 function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
1784 function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1785 table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
1786 Vararg expressions,
1787 denoted by three dots ('<code>...</code>'), can only be used when
1788 directly inside a vararg function;
1789 they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
1790
1791
1792 <p>
1793 Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
1794 bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
1795 relational 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>),
1796 and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
1797 Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
1798 the unary bitwise NOT (see <a href="#3.4.2">&sect;3.4.2</a>),
1799 the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
1800 and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
1801
1802
1803 <p>
1804 Both function calls and vararg expressions can result in multiple values.
1805 If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
1806 then its return list is adjusted to zero elements,
1807 thus discarding all returned values.
1808 If an expression is used as the last (or the only) element
1809 of a list of expressions,
1810 then no adjustment is made
1811 (unless the expression is enclosed in parentheses).
1812 In all other contexts,
1813 Lua adjusts the result list to one element,
1814 either discarding all values except the first one
1815 or adding a single <b>nil</b> if there are no values.
1816
1817
1818 <p>
1819 Here are some examples:
1820
1821 <pre>
1822      f()                -- adjusted to 0 results
1823      g(f(), x)          -- f() is adjusted to 1 result
1824      g(x, f())          -- g gets x plus all results from f()
1825      a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
1826      a,b = ...          -- a gets the first vararg argument, b gets
1827                         -- the second (both a and b can get nil if there
1828                         -- is no corresponding vararg argument)
1829      
1830      a,b,c = x, f()     -- f() is adjusted to 2 results
1831      a,b,c = f()        -- f() is adjusted to 3 results
1832      return f()         -- returns all results from f()
1833      return ...         -- returns all received vararg arguments
1834      return x,y,f()     -- returns x, y, and all results from f()
1835      {f()}              -- creates a list with all results from f()
1836      {...}              -- creates a list with all vararg arguments
1837      {f(), nil}         -- f() is adjusted to 1 result
1838 </pre>
1839
1840 <p>
1841 Any expression enclosed in parentheses always results in only one value.
1842 Thus,
1843 <code>(f(x,y,z))</code> is always a single value,
1844 even if <code>f</code> returns several values.
1845 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
1846 or <b>nil</b> if <code>f</code> does not return any values.)
1847
1848
1849
1850 <h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1851 Lua supports the following arithmetic operators:
1852
1853 <ul>
1854 <li><b><code>+</code>: </b>addition</li>
1855 <li><b><code>-</code>: </b>subtraction</li>
1856 <li><b><code>*</code>: </b>multiplication</li>
1857 <li><b><code>/</code>: </b>float division</li>
1858 <li><b><code>//</code>: </b>floor division</li>
1859 <li><b><code>%</code>: </b>modulo</li>
1860 <li><b><code>^</code>: </b>exponentiation</li>
1861 <li><b><code>-</code>: </b>unary minus</li>
1862 </ul>
1863
1864 <p>
1865 With the exception of exponentiation and float division,
1866 the arithmetic operators work as follows:
1867 If both operands are integers,
1868 the operation is performed over integers and the result is an integer.
1869 Otherwise, if both operands are numbers
1870 or strings that can be converted to
1871 numbers (see <a href="#3.4.3">&sect;3.4.3</a>),
1872 then they are converted to floats,
1873 the operation is performed following the usual rules
1874 for floating-point arithmetic
1875 (usually the IEEE 754 standard),
1876 and the result is a float.
1877
1878
1879 <p>
1880 Exponentiation and float division (<code>/</code>)
1881 always convert their operands to floats
1882 and the result is always a float.
1883 Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
1884 so that it works for non-integer exponents too.
1885
1886
1887 <p>
1888 Floor division (<code>//</code>) is a division
1889 that rounds the quotient towards minus infinity,
1890 that is, the floor of the division of its operands.
1891
1892
1893 <p>
1894 Modulo is defined as the remainder of a division
1895 that rounds the quotient towards minus infinity (floor division).
1896
1897
1898 <p>
1899 In case of overflows in integer arithmetic,
1900 all operations <em>wrap around</em>,
1901 according to the usual rules of two-complement arithmetic.
1902 (In other words,
1903 they return the unique representable integer
1904 that is equal modulo <em>2<sup>64</sup></em> to the mathematical result.)
1905
1906
1907
1908 <h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
1909 Lua supports the following bitwise operators:
1910
1911 <ul>
1912 <li><b><code>&amp;</code>: </b>bitwise AND</li>
1913 <li><b><code>&#124;</code>: </b>bitwise OR</li>
1914 <li><b><code>~</code>: </b>bitwise exclusive OR</li>
1915 <li><b><code>&gt;&gt;</code>: </b>right shift</li>
1916 <li><b><code>&lt;&lt;</code>: </b>left shift</li>
1917 <li><b><code>~</code>: </b>unary bitwise NOT</li>
1918 </ul>
1919
1920 <p>
1921 All bitwise operations convert its operands to integers
1922 (see <a href="#3.4.3">&sect;3.4.3</a>),
1923 operate on all bits of those integers,
1924 and result in an integer.
1925
1926
1927 <p>
1928 Both right and left shifts fill the vacant bits with zeros.
1929 Negative displacements shift to the other direction;
1930 displacements with absolute values equal to or higher than
1931 the number of bits in an integer
1932 result in zero (as all bits are shifted out).
1933
1934
1935
1936
1937
1938 <h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
1939 Lua provides some automatic conversions between some
1940 types and representations at run time.
1941 Bitwise operators always convert float operands to integers.
1942 Exponentiation and float division
1943 always convert integer operands to floats.
1944 All other arithmetic operations applied to mixed numbers
1945 (integers and floats) convert the integer operand to a float;
1946 this is called the <em>usual rule</em>.
1947 The C API also converts both integers to floats and
1948 floats to integers, as needed.
1949 Moreover, string concatenation accepts numbers as arguments,
1950 besides strings.
1951
1952
1953 <p>
1954 Lua also converts strings to numbers,
1955 whenever a number is expected.
1956
1957
1958 <p>
1959 In a conversion from integer to float,
1960 if the integer value has an exact representation as a float,
1961 that is the result.
1962 Otherwise,
1963 the conversion gets the nearest higher or
1964 the nearest lower representable value.
1965 This kind of conversion never fails.
1966
1967
1968 <p>
1969 The conversion from float to integer
1970 checks whether the float has an exact representation as an integer
1971 (that is, the float has an integral value and
1972 it is in the range of integer representation).
1973 If it does, that representation is the result.
1974 Otherwise, the conversion fails.
1975
1976
1977 <p>
1978 The conversion from strings to numbers goes as follows:
1979 First, the string is converted to an integer or a float,
1980 following its syntax and the rules of the Lua lexer.
1981 (The string may have also leading and trailing spaces and a sign.)
1982 Then, the resulting number (float or integer)
1983 is converted to the type (float or integer) required by the context
1984 (e.g., the operation that forced the conversion).
1985
1986
1987 <p>
1988 All conversions from strings to numbers
1989 accept both a dot and the current locale mark
1990 as the radix character.
1991 (The Lua lexer, however, accepts only a dot.)
1992
1993
1994 <p>
1995 The conversion from numbers to strings uses a
1996 non-specified human-readable format.
1997 For complete control over how numbers are converted to strings,
1998 use the <code>format</code> function from the string library
1999 (see <a href="#pdf-string.format"><code>string.format</code></a>).
2000
2001
2002
2003
2004
2005 <h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
2006 Lua supports the following relational operators:
2007
2008 <ul>
2009 <li><b><code>==</code>: </b>equality</li>
2010 <li><b><code>~=</code>: </b>inequality</li>
2011 <li><b><code>&lt;</code>: </b>less than</li>
2012 <li><b><code>&gt;</code>: </b>greater than</li>
2013 <li><b><code>&lt;=</code>: </b>less or equal</li>
2014 <li><b><code>&gt;=</code>: </b>greater or equal</li>
2015 </ul><p>
2016 These operators always result in <b>false</b> or <b>true</b>.
2017
2018
2019 <p>
2020 Equality (<code>==</code>) first compares the type of its operands.
2021 If the types are different, then the result is <b>false</b>.
2022 Otherwise, the values of the operands are compared.
2023 Strings are compared in the obvious way.
2024 Numbers are equal if they denote the same mathematical value.
2025
2026
2027 <p>
2028 Tables, userdata, and threads
2029 are compared by reference:
2030 two objects are considered equal only if they are the same object.
2031 Every time you create a new object
2032 (a table, userdata, or thread),
2033 this new object is different from any previously existing object.
2034 A closure is always equal to itself.
2035 Closures with any detectable difference
2036 (different behavior, different definition) are always different.
2037 Closures created at different times but with no detectable differences
2038 may be classified as equal or not
2039 (depending on internal caching details).
2040
2041
2042 <p>
2043 You can change the way that Lua compares tables and userdata
2044 by using the "eq" metamethod (see <a href="#2.4">&sect;2.4</a>).
2045
2046
2047 <p>
2048 Equality comparisons do not convert strings to numbers
2049 or vice versa.
2050 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2051 and <code>t[0]</code> and <code>t["0"]</code> denote different
2052 entries in a table.
2053
2054
2055 <p>
2056 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2057
2058
2059 <p>
2060 The order operators work as follows.
2061 If both arguments are numbers,
2062 then they are compared according to their mathematical values
2063 (regardless of their subtypes).
2064 Otherwise, if both arguments are strings,
2065 then their values are compared according to the current locale.
2066 Otherwise, Lua tries to call the "lt" or the "le"
2067 metamethod (see <a href="#2.4">&sect;2.4</a>).
2068 A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2069 and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2070
2071
2072 <p>
2073 Following the IEEE 754 standard,
2074 NaN is considered neither smaller than,
2075 nor equal to, nor greater than any value (including itself).
2076
2077
2078
2079
2080
2081 <h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2082 The logical operators in Lua are
2083 <b>and</b>, <b>or</b>, and <b>not</b>.
2084 Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2085 all logical operators consider both <b>false</b> and <b>nil</b> as false
2086 and anything else as true.
2087
2088
2089 <p>
2090 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2091 The conjunction operator <b>and</b> returns its first argument
2092 if this value is <b>false</b> or <b>nil</b>;
2093 otherwise, <b>and</b> returns its second argument.
2094 The disjunction operator <b>or</b> returns its first argument
2095 if this value is different from <b>nil</b> and <b>false</b>;
2096 otherwise, <b>or</b> returns its second argument.
2097 Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2098 that is,
2099 the second operand is evaluated only if necessary.
2100 Here are some examples:
2101
2102 <pre>
2103      10 or 20            --&gt; 10
2104      10 or error()       --&gt; 10
2105      nil or "a"          --&gt; "a"
2106      nil and 10          --&gt; nil
2107      false and error()   --&gt; false
2108      false and nil       --&gt; false
2109      false or nil        --&gt; nil
2110      10 and 20           --&gt; 20
2111 </pre><p>
2112 (In this manual,
2113 <code>--&gt;</code> indicates the result of the preceding expression.)
2114
2115
2116
2117
2118
2119 <h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2120 The string concatenation operator in Lua is
2121 denoted by two dots ('<code>..</code>').
2122 If both operands are strings or numbers, then they are converted to
2123 strings according to the rules described in <a href="#3.4.3">&sect;3.4.3</a>.
2124 Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2125
2126
2127
2128
2129
2130 <h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2131
2132 <p>
2133 The length operator is denoted by the unary prefix operator <code>#</code>.
2134
2135
2136 <p>
2137 The length of a string is its number of bytes
2138 (that is, the usual meaning of string length when each
2139 character is one byte).
2140
2141
2142 <p>
2143 The length operator applied on a table
2144 returns a border in that table.
2145 A <em>border</em> in a table <code>t</code> is any natural number
2146 that satisfies the following condition:
2147
2148 <pre>
2149      (border == 0 or t[border] ~= nil) and t[border + 1] == nil
2150 </pre><p>
2151 In words,
2152 a border is any (natural) index in a table
2153 where a non-nil value is followed by a nil value
2154 (or zero, when index 1 is nil).
2155
2156
2157 <p>
2158 A table with exactly one border is called a <em>sequence</em>.
2159 For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence,
2160 as it has only one border (5).
2161 The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5),
2162 and therefore it is not a sequence.
2163 The table <code>{nil, 20, 30, nil, nil, 60, nil}</code>
2164 has three borders (0, 3, and 6),
2165 so it is not a sequence, too.
2166 The table <code>{}</code> is a sequence with border 0.
2167 Note that non-natural keys do not interfere
2168 with whether a table is a sequence.
2169
2170
2171 <p>
2172 When <code>t</code> is a sequence,
2173 <code>#t</code> returns its only border,
2174 which corresponds to the intuitive notion of the length of the sequence.
2175 When <code>t</code> is not a sequence,
2176 <code>#t</code> can return any of its borders.
2177 (The exact one depends on details of
2178 the internal representation of the table,
2179 which in turn can depend on how the table was populated and
2180 the memory addresses of its non-numeric keys.)
2181
2182
2183 <p>
2184 The computation of the length of a table
2185 has a guaranteed worst time of <em>O(log n)</em>,
2186 where <em>n</em> is the largest natural key in the table.
2187
2188
2189 <p>
2190 A program can modify the behavior of the length operator for
2191 any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2192
2193
2194
2195
2196
2197 <h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2198 Operator precedence in Lua follows the table below,
2199 from lower to higher priority:
2200
2201 <pre>
2202      or
2203      and
2204      &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2205      |
2206      ~
2207      &amp;
2208      &lt;&lt;    &gt;&gt;
2209      ..
2210      +     -
2211      *     /     //    %
2212      unary operators (not   #     -     ~)
2213      ^
2214 </pre><p>
2215 As usual,
2216 you can use parentheses to change the precedences of an expression.
2217 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2218 operators are right associative.
2219 All other binary operators are left associative.
2220
2221
2222
2223
2224
2225 <h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2226 Table constructors are expressions that create tables.
2227 Every time a constructor is evaluated, a new table is created.
2228 A constructor can be used to create an empty table
2229 or to create a table and initialize some of its fields.
2230 The general syntax for constructors is
2231
2232 <pre>
2233         tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2234         fieldlist ::= field {fieldsep field} [fieldsep]
2235         field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2236         fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2237 </pre>
2238
2239 <p>
2240 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2241 with key <code>exp1</code> and value <code>exp2</code>.
2242 A field of the form <code>name = exp</code> is equivalent to
2243 <code>["name"] = exp</code>.
2244 Finally, fields of the form <code>exp</code> are equivalent to
2245 <code>[i] = exp</code>, where <code>i</code> are consecutive integers
2246 starting with 1.
2247 Fields in the other formats do not affect this counting.
2248 For example,
2249
2250 <pre>
2251      a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2252 </pre><p>
2253 is equivalent to
2254
2255 <pre>
2256      do
2257        local t = {}
2258        t[f(1)] = g
2259        t[1] = "x"         -- 1st exp
2260        t[2] = "y"         -- 2nd exp
2261        t.x = 1            -- t["x"] = 1
2262        t[3] = f(x)        -- 3rd exp
2263        t[30] = 23
2264        t[4] = 45          -- 4th exp
2265        a = t
2266      end
2267 </pre>
2268
2269 <p>
2270 The order of the assignments in a constructor is undefined.
2271 (This order would be relevant only when there are repeated keys.)
2272
2273
2274 <p>
2275 If the last field in the list has the form <code>exp</code>
2276 and the expression is a function call or a vararg expression,
2277 then all values returned by this expression enter the list consecutively
2278 (see <a href="#3.4.10">&sect;3.4.10</a>).
2279
2280
2281 <p>
2282 The field list can have an optional trailing separator,
2283 as a convenience for machine-generated code.
2284
2285
2286
2287
2288
2289 <h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2290 A function call in Lua has the following syntax:
2291
2292 <pre>
2293         functioncall ::= prefixexp args
2294 </pre><p>
2295 In a function call,
2296 first prefixexp and args are evaluated.
2297 If the value of prefixexp has type <em>function</em>,
2298 then this function is called
2299 with the given arguments.
2300 Otherwise, the prefixexp "call" metamethod is called,
2301 having as first argument the value of prefixexp,
2302 followed by the original call arguments
2303 (see <a href="#2.4">&sect;2.4</a>).
2304
2305
2306 <p>
2307 The form
2308
2309 <pre>
2310         functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2311 </pre><p>
2312 can be used to call "methods".
2313 A call <code>v:name(<em>args</em>)</code>
2314 is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2315 except that <code>v</code> is evaluated only once.
2316
2317
2318 <p>
2319 Arguments have the following syntax:
2320
2321 <pre>
2322         args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2323         args ::= tableconstructor
2324         args ::= LiteralString
2325 </pre><p>
2326 All argument expressions are evaluated before the call.
2327 A call of the form <code>f{<em>fields</em>}</code> is
2328 syntactic sugar for <code>f({<em>fields</em>})</code>;
2329 that is, the argument list is a single new table.
2330 A call of the form <code>f'<em>string</em>'</code>
2331 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2332 is syntactic sugar for <code>f('<em>string</em>')</code>;
2333 that is, the argument list is a single literal string.
2334
2335
2336 <p>
2337 A call of the form <code>return <em>functioncall</em></code> is called
2338 a <em>tail call</em>.
2339 Lua implements <em>proper tail calls</em>
2340 (or <em>proper tail recursion</em>):
2341 in a tail call,
2342 the called function reuses the stack entry of the calling function.
2343 Therefore, there is no limit on the number of nested tail calls that
2344 a program can execute.
2345 However, a tail call erases any debug information about the
2346 calling function.
2347 Note that a tail call only happens with a particular syntax,
2348 where the <b>return</b> has one single function call as argument;
2349 this syntax makes the calling function return exactly
2350 the returns of the called function.
2351 So, none of the following examples are tail calls:
2352
2353 <pre>
2354      return (f(x))        -- results adjusted to 1
2355      return 2 * f(x)
2356      return x, f(x)       -- additional results
2357      f(x); return         -- results discarded
2358      return x or f(x)     -- results adjusted to 1
2359 </pre>
2360
2361
2362
2363
2364 <h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2365
2366 <p>
2367 The syntax for function definition is
2368
2369 <pre>
2370         functiondef ::= <b>function</b> funcbody
2371         funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2372 </pre>
2373
2374 <p>
2375 The following syntactic sugar simplifies function definitions:
2376
2377 <pre>
2378         stat ::= <b>function</b> funcname funcbody
2379         stat ::= <b>local</b> <b>function</b> Name funcbody
2380         funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2381 </pre><p>
2382 The statement
2383
2384 <pre>
2385      function f () <em>body</em> end
2386 </pre><p>
2387 translates to
2388
2389 <pre>
2390      f = function () <em>body</em> end
2391 </pre><p>
2392 The statement
2393
2394 <pre>
2395      function t.a.b.c.f () <em>body</em> end
2396 </pre><p>
2397 translates to
2398
2399 <pre>
2400      t.a.b.c.f = function () <em>body</em> end
2401 </pre><p>
2402 The statement
2403
2404 <pre>
2405      local function f () <em>body</em> end
2406 </pre><p>
2407 translates to
2408
2409 <pre>
2410      local f; f = function () <em>body</em> end
2411 </pre><p>
2412 not to
2413
2414 <pre>
2415      local f = function () <em>body</em> end
2416 </pre><p>
2417 (This only makes a difference when the body of the function
2418 contains references to <code>f</code>.)
2419
2420
2421 <p>
2422 A function definition is an executable expression,
2423 whose value has type <em>function</em>.
2424 When Lua precompiles a chunk,
2425 all its function bodies are precompiled too.
2426 Then, whenever Lua executes the function definition,
2427 the function is <em>instantiated</em> (or <em>closed</em>).
2428 This function instance (or <em>closure</em>)
2429 is the final value of the expression.
2430
2431
2432 <p>
2433 Parameters act as local variables that are
2434 initialized with the argument values:
2435
2436 <pre>
2437         parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2438 </pre><p>
2439 When a function is called,
2440 the list of arguments is adjusted to
2441 the length of the list of parameters,
2442 unless the function is a <em>vararg function</em>,
2443 which is indicated by three dots ('<code>...</code>')
2444 at the end of its parameter list.
2445 A vararg function does not adjust its argument list;
2446 instead, it collects all extra arguments and supplies them
2447 to the function through a <em>vararg expression</em>,
2448 which is also written as three dots.
2449 The value of this expression is a list of all actual extra arguments,
2450 similar to a function with multiple results.
2451 If a vararg expression is used inside another expression
2452 or in the middle of a list of expressions,
2453 then its return list is adjusted to one element.
2454 If the expression is used as the last element of a list of expressions,
2455 then no adjustment is made
2456 (unless that last expression is enclosed in parentheses).
2457
2458
2459 <p>
2460 As an example, consider the following definitions:
2461
2462 <pre>
2463      function f(a, b) end
2464      function g(a, b, ...) end
2465      function r() return 1,2,3 end
2466 </pre><p>
2467 Then, we have the following mapping from arguments to parameters and
2468 to the vararg expression:
2469
2470 <pre>
2471      CALL            PARAMETERS
2472      
2473      f(3)             a=3, b=nil
2474      f(3, 4)          a=3, b=4
2475      f(3, 4, 5)       a=3, b=4
2476      f(r(), 10)       a=1, b=10
2477      f(r())           a=1, b=2
2478      
2479      g(3)             a=3, b=nil, ... --&gt;  (nothing)
2480      g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
2481      g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
2482      g(5, r())        a=5, b=1,   ... --&gt;  2  3
2483 </pre>
2484
2485 <p>
2486 Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2487 If control reaches the end of a function
2488 without encountering a <b>return</b> statement,
2489 then the function returns with no results.
2490
2491
2492 <p>
2493
2494 There is a system-dependent limit on the number of values
2495 that a function may return.
2496 This limit is guaranteed to be larger than 1000.
2497
2498
2499 <p>
2500 The <em>colon</em> syntax
2501 is used for defining <em>methods</em>,
2502 that is, functions that have an implicit extra parameter <code>self</code>.
2503 Thus, the statement
2504
2505 <pre>
2506      function t.a.b.c:f (<em>params</em>) <em>body</em> end
2507 </pre><p>
2508 is syntactic sugar for
2509
2510 <pre>
2511      t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2512 </pre>
2513
2514
2515
2516
2517
2518
2519 <h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2520
2521 <p>
2522
2523 Lua is a lexically scoped language.
2524 The scope of a local variable begins at the first statement after
2525 its declaration and lasts until the last non-void statement
2526 of the innermost block that includes the declaration.
2527 Consider the following example:
2528
2529 <pre>
2530      x = 10                -- global variable
2531      do                    -- new block
2532        local x = x         -- new 'x', with value 10
2533        print(x)            --&gt; 10
2534        x = x+1
2535        do                  -- another block
2536          local x = x+1     -- another 'x'
2537          print(x)          --&gt; 12
2538        end
2539        print(x)            --&gt; 11
2540      end
2541      print(x)              --&gt; 10  (the global one)
2542 </pre>
2543
2544 <p>
2545 Notice that, in a declaration like <code>local x = x</code>,
2546 the new <code>x</code> being declared is not in scope yet,
2547 and so the second <code>x</code> refers to the outside variable.
2548
2549
2550 <p>
2551 Because of the lexical scoping rules,
2552 local variables can be freely accessed by functions
2553 defined inside their scope.
2554 A local variable used by an inner function is called
2555 an <em>upvalue</em>, or <em>external local variable</em>,
2556 inside the inner function.
2557
2558
2559 <p>
2560 Notice that each execution of a <b>local</b> statement
2561 defines new local variables.
2562 Consider the following example:
2563
2564 <pre>
2565      a = {}
2566      local x = 20
2567      for i=1,10 do
2568        local y = 0
2569        a[i] = function () y=y+1; return x+y end
2570      end
2571 </pre><p>
2572 The loop creates ten closures
2573 (that is, ten instances of the anonymous function).
2574 Each of these closures uses a different <code>y</code> variable,
2575 while all of them share the same <code>x</code>.
2576
2577
2578
2579
2580
2581 <h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2582
2583 <p>
2584
2585 This section describes the C&nbsp;API for Lua, that is,
2586 the set of C&nbsp;functions available to the host program to communicate
2587 with Lua.
2588 All API functions and related types and constants
2589 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2590
2591
2592 <p>
2593 Even when we use the term "function",
2594 any facility in the API may be provided as a macro instead.
2595 Except where stated otherwise,
2596 all such macros use each of their arguments exactly once
2597 (except for the first argument, which is always a Lua state),
2598 and so do not generate any hidden side-effects.
2599
2600
2601 <p>
2602 As in most C&nbsp;libraries,
2603 the Lua API functions do not check their arguments for validity or consistency.
2604 However, you can change this behavior by compiling Lua
2605 with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2606
2607
2608 <p>
2609 The Lua library is fully reentrant:
2610 it has no global variables.
2611 It keeps all information it needs in a dynamic structure,
2612 called the <em>Lua state</em>.
2613
2614
2615 <p>
2616 Each Lua state has one or more threads,
2617 which correspond to independent, cooperative lines of execution.
2618 The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread.
2619 (Indirectly, through the thread, it also refers to the
2620 Lua state associated to the thread.)
2621
2622
2623 <p>
2624 A pointer to a thread must be passed as the first argument to
2625 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
2626 which creates a Lua state from scratch and returns a pointer
2627 to the <em>main thread</em> in the new state.
2628
2629
2630
2631 <h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2632
2633 <p>
2634 Lua uses a <em>virtual stack</em> to pass values to and from C.
2635 Each element in this stack represents a Lua value
2636 (<b>nil</b>, number, string, etc.).
2637 Functions in the API can access this stack through the
2638 Lua state parameter that they receive.
2639
2640
2641 <p>
2642 Whenever Lua calls C, the called function gets a new stack,
2643 which is independent of previous stacks and of stacks of
2644 C&nbsp;functions that are still active.
2645 This stack initially contains any arguments to the C&nbsp;function
2646 and it is where the C&nbsp;function can store temporary
2647 Lua values and must push its results
2648 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2649
2650
2651 <p>
2652 For convenience,
2653 most query operations in the API do not follow a strict stack discipline.
2654 Instead, they can refer to any element in the stack
2655 by using an <em>index</em>:
2656 A positive index represents an absolute stack position
2657 (starting at&nbsp;1);
2658 a negative index represents an offset relative to the top of the stack.
2659 More specifically, if the stack has <em>n</em> elements,
2660 then index&nbsp;1 represents the first element
2661 (that is, the element that was pushed onto the stack first)
2662 and
2663 index&nbsp;<em>n</em> represents the last element;
2664 index&nbsp;-1 also represents the last element
2665 (that is, the element at the&nbsp;top)
2666 and index <em>-n</em> represents the first element.
2667
2668
2669
2670
2671
2672 <h2>4.2 &ndash; <a name="4.2">Stack Size</a></h2>
2673
2674 <p>
2675 When you interact with the Lua API,
2676 you are responsible for ensuring consistency.
2677 In particular,
2678 <em>you are responsible for controlling stack overflow</em>.
2679 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2680 to ensure that the stack has enough space for pushing new elements.
2681
2682
2683 <p>
2684 Whenever Lua calls C,
2685 it ensures that the stack has space for
2686 at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2687 <code>LUA_MINSTACK</code> is defined as 20,
2688 so that usually you do not have to worry about stack space
2689 unless your code has loops pushing elements onto the stack.
2690
2691
2692 <p>
2693 When you call a Lua function
2694 without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2695 Lua ensures that the stack has enough space for all results,
2696 but it does not ensure any extra space.
2697 So, before pushing anything in the stack after such a call
2698 you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2699
2700
2701
2702
2703
2704 <h2>4.3 &ndash; <a name="4.3">Valid and Acceptable Indices</a></h2>
2705
2706 <p>
2707 Any function in the API that receives stack indices
2708 works only with <em>valid indices</em> or <em>acceptable indices</em>.
2709
2710
2711 <p>
2712 A <em>valid index</em> is an index that refers to a
2713 position that stores a modifiable Lua value.
2714 It comprises stack indices between&nbsp;1 and the stack top
2715 (<code>1 &le; abs(index) &le; top</code>)
2716
2717 plus <em>pseudo-indices</em>,
2718 which represent some positions that are accessible to C&nbsp;code
2719 but that are not in the stack.
2720 Pseudo-indices are used to access the registry (see <a href="#4.5">&sect;4.5</a>)
2721 and the upvalues of a C&nbsp;function (see <a href="#4.4">&sect;4.4</a>).
2722
2723
2724 <p>
2725 Functions that do not need a specific mutable position,
2726 but only a value (e.g., query functions),
2727 can be called with acceptable indices.
2728 An <em>acceptable index</em> can be any valid index,
2729 but it also can be any positive index after the stack top
2730 within the space allocated for the stack,
2731 that is, indices up to the stack size.
2732 (Note that 0 is never an acceptable index.)
2733 Except when noted otherwise,
2734 functions in the API work with acceptable indices.
2735
2736
2737 <p>
2738 Acceptable indices serve to avoid extra tests
2739 against the stack top when querying the stack.
2740 For instance, a C&nbsp;function can query its third argument
2741 without the need to first check whether there is a third argument,
2742 that is, without the need to check whether 3 is a valid index.
2743
2744
2745 <p>
2746 For functions that can be called with acceptable indices,
2747 any non-valid index is treated as if it
2748 contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
2749 which behaves like a nil value.
2750
2751
2752
2753
2754
2755 <h2>4.4 &ndash; <a name="4.4">C Closures</a></h2>
2756
2757 <p>
2758 When a C&nbsp;function is created,
2759 it is possible to associate some values with it,
2760 thus creating a <em>C&nbsp;closure</em>
2761 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
2762 these values are called <em>upvalues</em> and are
2763 accessible to the function whenever it is called.
2764
2765
2766 <p>
2767 Whenever a C&nbsp;function is called,
2768 its upvalues are located at specific pseudo-indices.
2769 These pseudo-indices are produced by the macro
2770 <a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2771 The first upvalue associated with a function is at index
2772 <code>lua_upvalueindex(1)</code>, and so on.
2773 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2774 where <em>n</em> is greater than the number of upvalues of the
2775 current function
2776 (but not greater than 256,
2777 which is one plus the maximum number of upvalues in a closure),
2778 produces an acceptable but invalid index.
2779
2780
2781
2782
2783
2784 <h2>4.5 &ndash; <a name="4.5">Registry</a></h2>
2785
2786 <p>
2787 Lua provides a <em>registry</em>,
2788 a predefined table that can be used by any C&nbsp;code to
2789 store whatever Lua values it needs to store.
2790 The registry table is always located at pseudo-index
2791 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
2792 Any C&nbsp;library can store data into this table,
2793 but it must take care to choose keys
2794 that are different from those used
2795 by other libraries, to avoid collisions.
2796 Typically, you should use as key a string containing your library name,
2797 or a light userdata with the address of a C&nbsp;object in your code,
2798 or any Lua object created by your code.
2799 As with variable names,
2800 string keys starting with an underscore followed by
2801 uppercase letters are reserved for Lua.
2802
2803
2804 <p>
2805 The integer keys in the registry are used
2806 by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
2807 and by some predefined values.
2808 Therefore, integer keys must not be used for other purposes.
2809
2810
2811 <p>
2812 When you create a new Lua state,
2813 its registry comes with some predefined values.
2814 These predefined values are indexed with integer keys
2815 defined as constants in <code>lua.h</code>.
2816 The following constants are defined:
2817
2818 <ul>
2819 <li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
2820 the main thread of the state.
2821 (The main thread is the one created together with the state.)
2822 </li>
2823
2824 <li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
2825 the global environment.
2826 </li>
2827 </ul>
2828
2829
2830
2831
2832 <h2>4.6 &ndash; <a name="4.6">Error Handling in C</a></h2>
2833
2834 <p>
2835 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2836 (Lua will use exceptions if you compile it as C++;
2837 search for <code>LUAI_THROW</code> in the source code for details.)
2838 When Lua faces any error
2839 (such as a memory allocation error or a type error)
2840 it <em>raises</em> an error;
2841 that is, it does a long jump.
2842 A <em>protected environment</em> uses <code>setjmp</code>
2843 to set a recovery point;
2844 any error jumps to the most recent active recovery point.
2845
2846
2847 <p>
2848 Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2849
2850
2851 <p>
2852 Most functions in the API can raise an error,
2853 for instance due to a memory allocation error.
2854 The documentation for each function indicates whether
2855 it can raise errors.
2856
2857
2858 <p>
2859 If an error happens outside any protected environment,
2860 Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
2861 and then calls <code>abort</code>,
2862 thus exiting the host application.
2863 Your panic function can avoid this exit by
2864 never returning
2865 (e.g., doing a long jump to your own recovery point outside Lua).
2866
2867
2868 <p>
2869 The panic function,
2870 as its name implies,
2871 is a mechanism of last resort.
2872 Programs should avoid it.
2873 As a general rule,
2874 when a C&nbsp;function is called by Lua with a Lua state,
2875 it can do whatever it wants on that Lua state,
2876 as it should be already protected.
2877 However,
2878 when C code operates on other Lua states
2879 (e.g., a Lua argument to the function,
2880 a Lua state stored in the registry, or
2881 the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
2882 it should use them only in API calls that cannot raise errors.
2883
2884
2885 <p>
2886 The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
2887 in particular, the error object is at the top of the stack.
2888 However, there is no guarantee about stack space.
2889 To push anything on the stack,
2890 the panic function must first check the available space (see <a href="#4.2">&sect;4.2</a>).
2891
2892
2893
2894
2895
2896 <h2>4.7 &ndash; <a name="4.7">Handling Yields in C</a></h2>
2897
2898 <p>
2899 Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2900 Therefore, if a C&nbsp;function <code>foo</code> calls an API function
2901 and this API function yields
2902 (directly or indirectly by calling another function that yields),
2903 Lua cannot return to <code>foo</code> any more,
2904 because the <code>longjmp</code> removes its frame from the C stack.
2905
2906
2907 <p>
2908 To avoid this kind of problem,
2909 Lua raises an error whenever it tries to yield across an API call,
2910 except for three functions:
2911 <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>.
2912 All those functions receive a <em>continuation function</em>
2913 (as a parameter named <code>k</code>) to continue execution after a yield.
2914
2915
2916 <p>
2917 We need to set some terminology to explain continuations.
2918 We have a C&nbsp;function called from Lua which we will call
2919 the <em>original function</em>.
2920 This original function then calls one of those three functions in the C API,
2921 which we will call the <em>callee function</em>,
2922 that then yields the current thread.
2923 (This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
2924 or 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>
2925 and the function called by them yields.)
2926
2927
2928 <p>
2929 Suppose the running thread yields while executing the callee function.
2930 After the thread resumes,
2931 it eventually will finish running the callee function.
2932 However,
2933 the callee function cannot return to the original function,
2934 because its frame in the C stack was destroyed by the yield.
2935 Instead, Lua calls a <em>continuation function</em>,
2936 which was given as an argument to the callee function.
2937 As the name implies,
2938 the continuation function should continue the task
2939 of the original function.
2940
2941
2942 <p>
2943 As an illustration, consider the following function:
2944
2945 <pre>
2946      int original_function (lua_State *L) {
2947        ...     /* code 1 */
2948        status = lua_pcall(L, n, m, h);  /* calls Lua */
2949        ...     /* code 2 */
2950      }
2951 </pre><p>
2952 Now we want to allow
2953 the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
2954 First, we can rewrite our function like here:
2955
2956 <pre>
2957      int k (lua_State *L, int status, lua_KContext ctx) {
2958        ...  /* code 2 */
2959      }
2960      
2961      int original_function (lua_State *L) {
2962        ...     /* code 1 */
2963        return k(L, lua_pcall(L, n, m, h), ctx);
2964      }
2965 </pre><p>
2966 In the above code,
2967 the new function <code>k</code> is a
2968 <em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
2969 which should do all the work that the original function
2970 was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
2971 Now, we must inform Lua that it must call <code>k</code> if the Lua code
2972 being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
2973 (errors or yielding),
2974 so we rewrite the code as here,
2975 replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
2976
2977 <pre>
2978      int original_function (lua_State *L) {
2979        ...     /* code 1 */
2980        return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
2981      }
2982 </pre><p>
2983 Note the external, explicit call to the continuation:
2984 Lua will call the continuation only if needed, that is,
2985 in case of errors or resuming after a yield.
2986 If the called function returns normally without ever yielding,
2987 <a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
2988 (Of course, instead of calling the continuation in that case,
2989 you can do the equivalent work directly inside the original function.)
2990
2991
2992 <p>
2993 Besides the Lua state,
2994 the continuation function has two other parameters:
2995 the final status of the call plus the context value (<code>ctx</code>) that
2996 was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
2997 (Lua does not use this context value;
2998 it only passes this value from the original function to the
2999 continuation function.)
3000 For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3001 the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3002 except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
3003 (instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
3004 For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
3005 the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
3006 (For these two functions,
3007 Lua will not call the continuation in case of errors,
3008 because they do not handle errors.)
3009 Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
3010 you should call the continuation function
3011 with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
3012 (For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
3013 directly the continuation function,
3014 because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
3015
3016
3017 <p>
3018 Lua treats the continuation function as if it were the original function.
3019 The continuation function receives the same Lua stack
3020 from the original function,
3021 in the same state it would be if the callee function had returned.
3022 (For instance,
3023 after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
3024 removed from the stack and replaced by the results from the call.)
3025 It also has the same upvalues.
3026 Whatever it returns is handled by Lua as if it were the return
3027 of the original function.
3028
3029
3030
3031
3032
3033 <h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
3034
3035 <p>
3036 Here we list all functions and types from the C&nbsp;API in
3037 alphabetical order.
3038 Each function has an indicator like this:
3039 <span class="apii">[-o, +p, <em>x</em>]</span>
3040
3041
3042 <p>
3043 The first field, <code>o</code>,
3044 is how many elements the function pops from the stack.
3045 The second field, <code>p</code>,
3046 is how many elements the function pushes onto the stack.
3047 (Any function always pushes its results after popping its arguments.)
3048 A field in the form <code>x|y</code> means the function can push (or pop)
3049 <code>x</code> or <code>y</code> elements,
3050 depending on the situation;
3051 an interrogation mark '<code>?</code>' means that
3052 we cannot know how many elements the function pops/pushes
3053 by looking only at its arguments
3054 (e.g., they may depend on what is on the stack).
3055 The third field, <code>x</code>,
3056 tells whether the function may raise errors:
3057 '<code>-</code>' means the function never raises any error;
3058 '<code>m</code>' means the function may raise out-of-memory errors
3059 and errors running a <code>__gc</code> metamethod;
3060 '<code>e</code>' means the function may raise any errors
3061 (it can run arbitrary Lua code,
3062 either directly or through metamethods);
3063 '<code>v</code>' means the function may raise an error on purpose.
3064
3065
3066
3067 <hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
3068 <span class="apii">[-0, +0, &ndash;]</span>
3069 <pre>int lua_absindex (lua_State *L, int idx);</pre>
3070
3071 <p>
3072 Converts the acceptable index <code>idx</code>
3073 into an equivalent absolute index
3074 (that is, one that does not depend on the stack top).
3075
3076
3077
3078
3079
3080 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
3081 <pre>typedef void * (*lua_Alloc) (void *ud,
3082                              void *ptr,
3083                              size_t osize,
3084                              size_t nsize);</pre>
3085
3086 <p>
3087 The type of the memory-allocation function used by Lua states.
3088 The allocator function must provide a
3089 functionality similar to <code>realloc</code>,
3090 but not exactly the same.
3091 Its arguments are
3092 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3093 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3094 <code>osize</code>, the original size of the block or some code about what
3095 is being allocated;
3096 and <code>nsize</code>, the new size of the block.
3097
3098
3099 <p>
3100 When <code>ptr</code> is not <code>NULL</code>,
3101 <code>osize</code> is the size of the block pointed by <code>ptr</code>,
3102 that is, the size given when it was allocated or reallocated.
3103
3104
3105 <p>
3106 When <code>ptr</code> is <code>NULL</code>,
3107 <code>osize</code> encodes the kind of object that Lua is allocating.
3108 <code>osize</code> is any of
3109 <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>,
3110 <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)
3111 Lua is creating a new object of that type.
3112 When <code>osize</code> is some other value,
3113 Lua is allocating memory for something else.
3114
3115
3116 <p>
3117 Lua assumes the following behavior from the allocator function:
3118
3119
3120 <p>
3121 When <code>nsize</code> is zero,
3122 the allocator must behave like <code>free</code>
3123 and return <code>NULL</code>.
3124
3125
3126 <p>
3127 When <code>nsize</code> is not zero,
3128 the allocator must behave like <code>realloc</code>.
3129 The allocator returns <code>NULL</code>
3130 if and only if it cannot fulfill the request.
3131 Lua assumes that the allocator never fails when
3132 <code>osize &gt;= nsize</code>.
3133
3134
3135 <p>
3136 Here is a simple implementation for the allocator function.
3137 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3138
3139 <pre>
3140      static void *l_alloc (void *ud, void *ptr, size_t osize,
3141                                                 size_t nsize) {
3142        (void)ud;  (void)osize;  /* not used */
3143        if (nsize == 0) {
3144          free(ptr);
3145          return NULL;
3146        }
3147        else
3148          return realloc(ptr, nsize);
3149      }
3150 </pre><p>
3151 Note that Standard&nbsp;C ensures
3152 that <code>free(NULL)</code> has no effect and that
3153 <code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3154 This code assumes that <code>realloc</code> does not fail when shrinking a block.
3155 (Although Standard&nbsp;C does not ensure this behavior,
3156 it seems to be a safe assumption.)
3157
3158
3159
3160
3161
3162 <hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3163 <span class="apii">[-(2|1), +1, <em>e</em>]</span>
3164 <pre>void lua_arith (lua_State *L, int op);</pre>
3165
3166 <p>
3167 Performs an arithmetic or bitwise operation over the two values
3168 (or one, in the case of negations)
3169 at the top of the stack,
3170 with the value at the top being the second operand,
3171 pops these values, and pushes the result of the operation.
3172 The function follows the semantics of the corresponding Lua operator
3173 (that is, it may call metamethods).
3174
3175
3176 <p>
3177 The value of <code>op</code> must be one of the following constants:
3178
3179 <ul>
3180
3181 <li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3182 <li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3183 <li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3184 <li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3185 <li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3186 <li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3187 <li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3188 <li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3189 <li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
3190 <li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li>
3191 <li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
3192 <li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
3193 <li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3194 <li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3195
3196 </ul>
3197
3198
3199
3200
3201 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3202 <span class="apii">[-0, +0, &ndash;]</span>
3203 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3204
3205 <p>
3206 Sets a new panic function and returns the old one (see <a href="#4.6">&sect;4.6</a>).
3207
3208
3209
3210
3211
3212 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3213 <span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3214 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3215
3216 <p>
3217 Calls a function.
3218
3219
3220 <p>
3221 To call a function you must use the following protocol:
3222 first, the function to be called is pushed onto the stack;
3223 then, the arguments to the function are pushed
3224 in direct order;
3225 that is, the first argument is pushed first.
3226 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3227 <code>nargs</code> is the number of arguments that you pushed onto the stack.
3228 All arguments and the function value are popped from the stack
3229 when the function is called.
3230 The function results are pushed onto the stack when the function returns.
3231 The number of results is adjusted to <code>nresults</code>,
3232 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3233 In this case, all results from the function are pushed;
3234 Lua takes care that the returned values fit into the stack space,
3235 but it does not ensure any extra space in the stack.
3236 The function results are pushed onto the stack in direct order
3237 (the first result is pushed first),
3238 so that after the call the last result is on the top of the stack.
3239
3240
3241 <p>
3242 Any error inside the called function is propagated upwards
3243 (with a <code>longjmp</code>).
3244
3245
3246 <p>
3247 The following example shows how the host program can do the
3248 equivalent to this Lua code:
3249
3250 <pre>
3251      a = f("how", t.x, 14)
3252 </pre><p>
3253 Here it is in&nbsp;C:
3254
3255 <pre>
3256      lua_getglobal(L, "f");                  /* function to be called */
3257      lua_pushliteral(L, "how");                       /* 1st argument */
3258      lua_getglobal(L, "t");                    /* table to be indexed */
3259      lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
3260      lua_remove(L, -2);                  /* remove 't' from the stack */
3261      lua_pushinteger(L, 14);                          /* 3rd argument */
3262      lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
3263      lua_setglobal(L, "a");                         /* set global 'a' */
3264 </pre><p>
3265 Note that the code above is <em>balanced</em>:
3266 at its end, the stack is back to its original configuration.
3267 This is considered good programming practice.
3268
3269
3270
3271
3272
3273 <hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3274 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3275 <pre>void lua_callk (lua_State *L,
3276                 int nargs,
3277                 int nresults,
3278                 lua_KContext ctx,
3279                 lua_KFunction k);</pre>
3280
3281 <p>
3282 This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3283 but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
3284
3285
3286
3287
3288
3289 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3290 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3291
3292 <p>
3293 Type for C&nbsp;functions.
3294
3295
3296 <p>
3297 In order to communicate properly with Lua,
3298 a C&nbsp;function must use the following protocol,
3299 which defines the way parameters and results are passed:
3300 a C&nbsp;function receives its arguments from Lua in its stack
3301 in direct order (the first argument is pushed first).
3302 So, when the function starts,
3303 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
3304 The first argument (if any) is at index 1
3305 and its last argument is at index <code>lua_gettop(L)</code>.
3306 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3307 in direct order (the first result is pushed first),
3308 and returns the number of results.
3309 Any other value in the stack below the results will be properly
3310 discarded by Lua.
3311 Like a Lua function, a C&nbsp;function called by Lua can also return
3312 many results.
3313
3314
3315 <p>
3316 As an example, the following function receives a variable number
3317 of numeric arguments and returns their average and their sum:
3318
3319 <pre>
3320      static int foo (lua_State *L) {
3321        int n = lua_gettop(L);    /* number of arguments */
3322        lua_Number sum = 0.0;
3323        int i;
3324        for (i = 1; i &lt;= n; i++) {
3325          if (!lua_isnumber(L, i)) {
3326            lua_pushliteral(L, "incorrect argument");
3327            lua_error(L);
3328          }
3329          sum += lua_tonumber(L, i);
3330        }
3331        lua_pushnumber(L, sum/n);        /* first result */
3332        lua_pushnumber(L, sum);         /* second result */
3333        return 2;                   /* number of results */
3334      }
3335 </pre>
3336
3337
3338
3339
3340 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3341 <span class="apii">[-0, +0, &ndash;]</span>
3342 <pre>int lua_checkstack (lua_State *L, int n);</pre>
3343
3344 <p>
3345 Ensures that the stack has space for at least <code>n</code> extra slots
3346 (that is, that you can safely push up to <code>n</code> values into it).
3347 It returns false if it cannot fulfill the request,
3348 either because it would cause the stack
3349 to be larger than a fixed maximum size
3350 (typically at least several thousand elements) or
3351 because it cannot allocate memory for the extra space.
3352 This function never shrinks the stack;
3353 if the stack already has space for the extra slots,
3354 it is left unchanged.
3355
3356
3357
3358
3359
3360 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3361 <span class="apii">[-0, +0, &ndash;]</span>
3362 <pre>void lua_close (lua_State *L);</pre>
3363
3364 <p>
3365 Destroys all objects in the given Lua state
3366 (calling the corresponding garbage-collection metamethods, if any)
3367 and frees all dynamic memory used by this state.
3368 In several platforms, you may not need to call this function,
3369 because all resources are naturally released when the host program ends.
3370 On the other hand, long-running programs that create multiple states,
3371 such as daemons or web servers,
3372 will probably need to close states as soon as they are not needed.
3373
3374
3375
3376
3377
3378 <hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3379 <span class="apii">[-0, +0, <em>e</em>]</span>
3380 <pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3381
3382 <p>
3383 Compares two Lua values.
3384 Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3385 when compared with the value at index <code>index2</code>,
3386 following the semantics of the corresponding Lua operator
3387 (that is, it may call metamethods).
3388 Otherwise returns&nbsp;0.
3389 Also returns&nbsp;0 if any of the indices is not valid.
3390
3391
3392 <p>
3393 The value of <code>op</code> must be one of the following constants:
3394
3395 <ul>
3396
3397 <li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3398 <li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3399 <li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3400
3401 </ul>
3402
3403
3404
3405
3406 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3407 <span class="apii">[-n, +1, <em>e</em>]</span>
3408 <pre>void lua_concat (lua_State *L, int n);</pre>
3409
3410 <p>
3411 Concatenates the <code>n</code> values at the top of the stack,
3412 pops them, and leaves the result at the top.
3413 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3414 (that is, the function does nothing);
3415 if <code>n</code> is 0, the result is the empty string.
3416 Concatenation is performed following the usual semantics of Lua
3417 (see <a href="#3.4.6">&sect;3.4.6</a>).
3418
3419
3420
3421
3422
3423 <hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3424 <span class="apii">[-0, +0, &ndash;]</span>
3425 <pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3426
3427 <p>
3428 Copies the element at index <code>fromidx</code>
3429 into the valid index <code>toidx</code>,
3430 replacing the value at that position.
3431 Values at other positions are not affected.
3432
3433
3434
3435
3436
3437 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3438 <span class="apii">[-0, +1, <em>m</em>]</span>
3439 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3440
3441 <p>
3442 Creates a new empty table and pushes it onto the stack.
3443 Parameter <code>narr</code> is a hint for how many elements the table
3444 will have as a sequence;
3445 parameter <code>nrec</code> is a hint for how many other elements
3446 the table will have.
3447 Lua may use these hints to preallocate memory for the new table.
3448 This preallocation is useful for performance when you know in advance
3449 how many elements the table will have.
3450 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3451
3452
3453
3454
3455
3456 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3457 <span class="apii">[-0, +0, &ndash;]</span>
3458 <pre>int lua_dump (lua_State *L,
3459                         lua_Writer writer,
3460                         void *data,
3461                         int strip);</pre>
3462
3463 <p>
3464 Dumps a function as a binary chunk.
3465 Receives a Lua function on the top of the stack
3466 and produces a binary chunk that,
3467 if loaded again,
3468 results in a function equivalent to the one dumped.
3469 As it produces parts of the chunk,
3470 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3471 with the given <code>data</code>
3472 to write them.
3473
3474
3475 <p>
3476 If <code>strip</code> is true,
3477 the binary representation may not include all debug information
3478 about the function,
3479 to save space.
3480
3481
3482 <p>
3483 The value returned is the error code returned by the last
3484 call to the writer;
3485 0&nbsp;means no errors.
3486
3487
3488 <p>
3489 This function does not pop the Lua function from the stack.
3490
3491
3492
3493
3494
3495 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3496 <span class="apii">[-1, +0, <em>v</em>]</span>
3497 <pre>int lua_error (lua_State *L);</pre>
3498
3499 <p>
3500 Generates a Lua error,
3501 using the value at the top of the stack as the error object.
3502 This function does a long jump,
3503 and therefore never returns
3504 (see <a href="#luaL_error"><code>luaL_error</code></a>).
3505
3506
3507
3508
3509
3510 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3511 <span class="apii">[-0, +0, <em>m</em>]</span>
3512 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
3513
3514 <p>
3515 Controls the garbage collector.
3516
3517
3518 <p>
3519 This function performs several tasks,
3520 according to the value of the parameter <code>what</code>:
3521
3522 <ul>
3523
3524 <li><b><code>LUA_GCSTOP</code>: </b>
3525 stops the garbage collector.
3526 </li>
3527
3528 <li><b><code>LUA_GCRESTART</code>: </b>
3529 restarts the garbage collector.
3530 </li>
3531
3532 <li><b><code>LUA_GCCOLLECT</code>: </b>
3533 performs a full garbage-collection cycle.
3534 </li>
3535
3536 <li><b><code>LUA_GCCOUNT</code>: </b>
3537 returns the current amount of memory (in Kbytes) in use by Lua.
3538 </li>
3539
3540 <li><b><code>LUA_GCCOUNTB</code>: </b>
3541 returns the remainder of dividing the current amount of bytes of
3542 memory in use by Lua by 1024.
3543 </li>
3544
3545 <li><b><code>LUA_GCSTEP</code>: </b>
3546 performs an incremental step of garbage collection.
3547 </li>
3548
3549 <li><b><code>LUA_GCSETPAUSE</code>: </b>
3550 sets <code>data</code> as the new value
3551 for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>)
3552 and returns the previous value of the pause.
3553 </li>
3554
3555 <li><b><code>LUA_GCSETSTEPMUL</code>: </b>
3556 sets <code>data</code> as the new value for the <em>step multiplier</em> of
3557 the collector (see <a href="#2.5">&sect;2.5</a>)
3558 and returns the previous value of the step multiplier.
3559 </li>
3560
3561 <li><b><code>LUA_GCISRUNNING</code>: </b>
3562 returns a boolean that tells whether the collector is running
3563 (i.e., not stopped).
3564 </li>
3565
3566 </ul>
3567
3568 <p>
3569 For more details about these options,
3570 see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3571
3572
3573
3574
3575
3576 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3577 <span class="apii">[-0, +0, &ndash;]</span>
3578 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3579
3580 <p>
3581 Returns the memory-allocation function of a given state.
3582 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3583 opaque pointer given when the memory-allocator function was set.
3584
3585
3586
3587
3588
3589 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3590 <span class="apii">[-0, +1, <em>e</em>]</span>
3591 <pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
3592
3593 <p>
3594 Pushes onto the stack the value <code>t[k]</code>,
3595 where <code>t</code> is the value at the given index.
3596 As in Lua, this function may trigger a metamethod
3597 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3598
3599
3600 <p>
3601 Returns the type of the pushed value.
3602
3603
3604
3605
3606
3607 <hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
3608 <span class="apii">[-0, +0, &ndash;]</span>
3609 <pre>void *lua_getextraspace (lua_State *L);</pre>
3610
3611 <p>
3612 Returns a pointer to a raw memory area associated with the
3613 given Lua state.
3614 The application can use this area for any purpose;
3615 Lua does not use it for anything.
3616
3617
3618 <p>
3619 Each new thread has this area initialized with a copy
3620 of the area of the main thread.
3621
3622
3623 <p>
3624 By default, this area has the size of a pointer to void,
3625 but you can recompile Lua with a different size for this area.
3626 (See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
3627
3628
3629
3630
3631
3632 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3633 <span class="apii">[-0, +1, <em>e</em>]</span>
3634 <pre>int lua_getglobal (lua_State *L, const char *name);</pre>
3635
3636 <p>
3637 Pushes onto the stack the value of the global <code>name</code>.
3638 Returns the type of that value.
3639
3640
3641
3642
3643
3644 <hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
3645 <span class="apii">[-0, +1, <em>e</em>]</span>
3646 <pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
3647
3648 <p>
3649 Pushes onto the stack the value <code>t[i]</code>,
3650 where <code>t</code> is the value at the given index.
3651 As in Lua, this function may trigger a metamethod
3652 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3653
3654
3655 <p>
3656 Returns the type of the pushed value.
3657
3658
3659
3660
3661
3662 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
3663 <span class="apii">[-0, +(0|1), &ndash;]</span>
3664 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
3665
3666 <p>
3667 If the value at the given index has a metatable,
3668 the function pushes that metatable onto the stack and returns&nbsp;1.
3669 Otherwise,
3670 the function returns&nbsp;0 and pushes nothing on the stack.
3671
3672
3673
3674
3675
3676 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
3677 <span class="apii">[-1, +1, <em>e</em>]</span>
3678 <pre>int lua_gettable (lua_State *L, int index);</pre>
3679
3680 <p>
3681 Pushes onto the stack the value <code>t[k]</code>,
3682 where <code>t</code> is the value at the given index
3683 and <code>k</code> is the value at the top of the stack.
3684
3685
3686 <p>
3687 This function pops the key from the stack,
3688 pushing the resulting value in its place.
3689 As in Lua, this function may trigger a metamethod
3690 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3691
3692
3693 <p>
3694 Returns the type of the pushed value.
3695
3696
3697
3698
3699
3700 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
3701 <span class="apii">[-0, +0, &ndash;]</span>
3702 <pre>int lua_gettop (lua_State *L);</pre>
3703
3704 <p>
3705 Returns the index of the top element in the stack.
3706 Because indices start at&nbsp;1,
3707 this result is equal to the number of elements in the stack;
3708 in particular, 0&nbsp;means an empty stack.
3709
3710
3711
3712
3713
3714 <hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
3715 <span class="apii">[-0, +1, &ndash;]</span>
3716 <pre>int lua_getuservalue (lua_State *L, int index);</pre>
3717
3718 <p>
3719 Pushes onto the stack the Lua value associated with the full userdata
3720 at the given index.
3721
3722
3723 <p>
3724 Returns the type of the pushed value.
3725
3726
3727
3728
3729
3730 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
3731 <span class="apii">[-1, +1, &ndash;]</span>
3732 <pre>void lua_insert (lua_State *L, int index);</pre>
3733
3734 <p>
3735 Moves the top element into the given valid index,
3736 shifting up the elements above this index to open space.
3737 This function cannot be called with a pseudo-index,
3738 because a pseudo-index is not an actual stack position.
3739
3740
3741
3742
3743
3744 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3745 <pre>typedef ... lua_Integer;</pre>
3746
3747 <p>
3748 The type of integers in Lua.
3749
3750
3751 <p>
3752 By default this type is <code>long long</code>,
3753 (usually a 64-bit two-complement integer),
3754 but that can be changed to <code>long</code> or <code>int</code>
3755 (usually a 32-bit two-complement integer).
3756 (See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
3757
3758
3759 <p>
3760 Lua also defines the constants
3761 <a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
3762 with the minimum and the maximum values that fit in this type.
3763
3764
3765
3766
3767
3768 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3769 <span class="apii">[-0, +0, &ndash;]</span>
3770 <pre>int lua_isboolean (lua_State *L, int index);</pre>
3771
3772 <p>
3773 Returns 1 if the value at the given index is a boolean,
3774 and 0&nbsp;otherwise.
3775
3776
3777
3778
3779
3780 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3781 <span class="apii">[-0, +0, &ndash;]</span>
3782 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
3783
3784 <p>
3785 Returns 1 if the value at the given index is a C&nbsp;function,
3786 and 0&nbsp;otherwise.
3787
3788
3789
3790
3791
3792 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3793 <span class="apii">[-0, +0, &ndash;]</span>
3794 <pre>int lua_isfunction (lua_State *L, int index);</pre>
3795
3796 <p>
3797 Returns 1 if the value at the given index is a function
3798 (either C or Lua), and 0&nbsp;otherwise.
3799
3800
3801
3802
3803
3804 <hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
3805 <span class="apii">[-0, +0, &ndash;]</span>
3806 <pre>int lua_isinteger (lua_State *L, int index);</pre>
3807
3808 <p>
3809 Returns 1 if the value at the given index is an integer
3810 (that is, the value is a number and is represented as an integer),
3811 and 0&nbsp;otherwise.
3812
3813
3814
3815
3816
3817 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3818 <span class="apii">[-0, +0, &ndash;]</span>
3819 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3820
3821 <p>
3822 Returns 1 if the value at the given index is a light userdata,
3823 and 0&nbsp;otherwise.
3824
3825
3826
3827
3828
3829 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3830 <span class="apii">[-0, +0, &ndash;]</span>
3831 <pre>int lua_isnil (lua_State *L, int index);</pre>
3832
3833 <p>
3834 Returns 1 if the value at the given index is <b>nil</b>,
3835 and 0&nbsp;otherwise.
3836
3837
3838
3839
3840
3841 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3842 <span class="apii">[-0, +0, &ndash;]</span>
3843 <pre>int lua_isnone (lua_State *L, int index);</pre>
3844
3845 <p>
3846 Returns 1 if the given index is not valid,
3847 and 0&nbsp;otherwise.
3848
3849
3850
3851
3852
3853 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3854 <span class="apii">[-0, +0, &ndash;]</span>
3855 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3856
3857 <p>
3858 Returns 1 if the given index is not valid
3859 or if the value at this index is <b>nil</b>,
3860 and 0&nbsp;otherwise.
3861
3862
3863
3864
3865
3866 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3867 <span class="apii">[-0, +0, &ndash;]</span>
3868 <pre>int lua_isnumber (lua_State *L, int index);</pre>
3869
3870 <p>
3871 Returns 1 if the value at the given index is a number
3872 or a string convertible to a number,
3873 and 0&nbsp;otherwise.
3874
3875
3876
3877
3878
3879 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3880 <span class="apii">[-0, +0, &ndash;]</span>
3881 <pre>int lua_isstring (lua_State *L, int index);</pre>
3882
3883 <p>
3884 Returns 1 if the value at the given index is a string
3885 or a number (which is always convertible to a string),
3886 and 0&nbsp;otherwise.
3887
3888
3889
3890
3891
3892 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3893 <span class="apii">[-0, +0, &ndash;]</span>
3894 <pre>int lua_istable (lua_State *L, int index);</pre>
3895
3896 <p>
3897 Returns 1 if the value at the given index is a table,
3898 and 0&nbsp;otherwise.
3899
3900
3901
3902
3903
3904 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3905 <span class="apii">[-0, +0, &ndash;]</span>
3906 <pre>int lua_isthread (lua_State *L, int index);</pre>
3907
3908 <p>
3909 Returns 1 if the value at the given index is a thread,
3910 and 0&nbsp;otherwise.
3911
3912
3913
3914
3915
3916 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3917 <span class="apii">[-0, +0, &ndash;]</span>
3918 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
3919
3920 <p>
3921 Returns 1 if the value at the given index is a userdata
3922 (either full or light), and 0&nbsp;otherwise.
3923
3924
3925
3926
3927
3928 <hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
3929 <span class="apii">[-0, +0, &ndash;]</span>
3930 <pre>int lua_isyieldable (lua_State *L);</pre>
3931
3932 <p>
3933 Returns 1 if the given coroutine can yield,
3934 and 0&nbsp;otherwise.
3935
3936
3937
3938
3939
3940 <hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
3941 <pre>typedef ... lua_KContext;</pre>
3942
3943 <p>
3944 The type for continuation-function contexts.
3945 It must be a numeric type.
3946 This type is defined as <code>intptr_t</code>
3947 when <code>intptr_t</code> is available,
3948 so that it can store pointers too.
3949 Otherwise, it is defined as <code>ptrdiff_t</code>.
3950
3951
3952
3953
3954
3955 <hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
3956 <pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
3957
3958 <p>
3959 Type for continuation functions (see <a href="#4.7">&sect;4.7</a>).
3960
3961
3962
3963
3964
3965 <hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
3966 <span class="apii">[-0, +1, <em>e</em>]</span>
3967 <pre>void lua_len (lua_State *L, int index);</pre>
3968
3969 <p>
3970 Returns the length of the value at the given index.
3971 It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
3972 may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
3973 The result is pushed on the stack.
3974
3975
3976
3977
3978
3979 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3980 <span class="apii">[-0, +1, &ndash;]</span>
3981 <pre>int lua_load (lua_State *L,
3982               lua_Reader reader,
3983               void *data,
3984               const char *chunkname,
3985               const char *mode);</pre>
3986
3987 <p>
3988 Loads a Lua chunk without running it.
3989 If there are no errors,
3990 <code>lua_load</code> pushes the compiled chunk as a Lua
3991 function on top of the stack.
3992 Otherwise, it pushes an error message.
3993
3994
3995 <p>
3996 The return values of <code>lua_load</code> are:
3997
3998 <ul>
3999
4000 <li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li>
4001
4002 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b>
4003 syntax error during precompilation;</li>
4004
4005 <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
4006 memory allocation (out-of-memory) error;</li>
4007
4008 <li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
4009 error while running a <code>__gc</code> metamethod.
4010 (This error has no relation with the chunk being loaded.
4011 It is generated by the garbage collector.)
4012 </li>
4013
4014 </ul>
4015
4016 <p>
4017 The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
4018 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
4019 The <code>data</code> argument is an opaque value passed to the reader function.
4020
4021
4022 <p>
4023 The <code>chunkname</code> argument gives a name to the chunk,
4024 which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>).
4025
4026
4027 <p>
4028 <code>lua_load</code> automatically detects whether the chunk is text or binary
4029 and loads it accordingly (see program <code>luac</code>).
4030 The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
4031 with the addition that
4032 a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
4033
4034
4035 <p>
4036 <code>lua_load</code> uses the stack internally,
4037 so the reader function must always leave the stack
4038 unmodified when returning.
4039
4040
4041 <p>
4042 If the resulting function has upvalues,
4043 its first upvalue is set to the value of the global environment
4044 stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>).
4045 When loading main chunks,
4046 this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
4047 Other upvalues are initialized with <b>nil</b>.
4048
4049
4050
4051
4052
4053 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
4054 <span class="apii">[-0, +0, &ndash;]</span>
4055 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
4056
4057 <p>
4058 Creates a new thread running in a new, independent state.
4059 Returns <code>NULL</code> if it cannot create the thread or the state
4060 (due to lack of memory).
4061 The argument <code>f</code> is the allocator function;
4062 Lua does all memory allocation for this state
4063 through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
4064 The second argument, <code>ud</code>, is an opaque pointer that Lua
4065 passes to the allocator in every call.
4066
4067
4068
4069
4070
4071 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
4072 <span class="apii">[-0, +1, <em>m</em>]</span>
4073 <pre>void lua_newtable (lua_State *L);</pre>
4074
4075 <p>
4076 Creates a new empty table and pushes it onto the stack.
4077 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
4078
4079
4080
4081
4082
4083 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
4084 <span class="apii">[-0, +1, <em>m</em>]</span>
4085 <pre>lua_State *lua_newthread (lua_State *L);</pre>
4086
4087 <p>
4088 Creates a new thread, pushes it on the stack,
4089 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
4090 The new thread returned by this function shares with the original thread
4091 its global environment,
4092 but has an independent execution stack.
4093
4094
4095 <p>
4096 There is no explicit function to close or to destroy a thread.
4097 Threads are subject to garbage collection,
4098 like any Lua object.
4099
4100
4101
4102
4103
4104 <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
4105 <span class="apii">[-0, +1, <em>m</em>]</span>
4106 <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
4107
4108 <p>
4109 This function allocates a new block of memory with the given size,
4110 pushes onto the stack a new full userdata with the block address,
4111 and returns this address.
4112 The host program can freely use this memory.
4113
4114
4115
4116
4117
4118 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4119 <span class="apii">[-1, +(2|0), <em>e</em>]</span>
4120 <pre>int lua_next (lua_State *L, int index);</pre>
4121
4122 <p>
4123 Pops a key from the stack,
4124 and pushes a key&ndash;value pair from the table at the given index
4125 (the "next" pair after the given key).
4126 If there are no more elements in the table,
4127 then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
4128
4129
4130 <p>
4131 A typical traversal looks like this:
4132
4133 <pre>
4134      /* table is in the stack at index 't' */
4135      lua_pushnil(L);  /* first key */
4136      while (lua_next(L, t) != 0) {
4137        /* uses 'key' (at index -2) and 'value' (at index -1) */
4138        printf("%s - %s\n",
4139               lua_typename(L, lua_type(L, -2)),
4140               lua_typename(L, lua_type(L, -1)));
4141        /* removes 'value'; keeps 'key' for next iteration */
4142        lua_pop(L, 1);
4143      }
4144 </pre>
4145
4146 <p>
4147 While traversing a table,
4148 do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4149 unless you know that the key is actually a string.
4150 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4151 the value at the given index;
4152 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4153
4154
4155 <p>
4156 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4157 the table during its traversal.
4158
4159
4160
4161
4162
4163 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4164 <pre>typedef ... lua_Number;</pre>
4165
4166 <p>
4167 The type of floats in Lua.
4168
4169
4170 <p>
4171 By default this type is double,
4172 but that can be changed to a single float or a long double.
4173 (See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
4174
4175
4176
4177
4178
4179 <hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4180 <pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4181
4182 <p>
4183 Converts a Lua float to a Lua integer.
4184 This macro assumes that <code>n</code> has an integral value.
4185 If that value is within the range of Lua integers,
4186 it is converted to an integer and assigned to <code>*p</code>.
4187 The macro results in a boolean indicating whether the
4188 conversion was successful.
4189 (Note that this range test can be tricky to do
4190 correctly without this macro,
4191 due to roundings.)
4192
4193
4194 <p>
4195 This macro may evaluate its arguments more than once.
4196
4197
4198
4199
4200
4201 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4202 <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4203 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4204
4205 <p>
4206 Calls a function in protected mode.
4207
4208
4209 <p>
4210 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4211 in <a href="#lua_call"><code>lua_call</code></a>.
4212 If there are no errors during the call,
4213 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4214 However, if there is any error,
4215 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4216 pushes a single value on the stack (the error object),
4217 and returns an error code.
4218 Like <a href="#lua_call"><code>lua_call</code></a>,
4219 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4220 and its arguments from the stack.
4221
4222
4223 <p>
4224 If <code>msgh</code> is 0,
4225 then the error object returned on the stack
4226 is exactly the original error object.
4227 Otherwise, <code>msgh</code> is the stack index of a
4228 <em>message handler</em>.
4229 (This index cannot be a pseudo-index.)
4230 In case of runtime errors,
4231 this function will be called with the error object
4232 and its return value will be the object
4233 returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4234
4235
4236 <p>
4237 Typically, the message handler is used to add more debug
4238 information to the error object, such as a stack traceback.
4239 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4240 since by then the stack has unwound.
4241
4242
4243 <p>
4244 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants
4245 (defined in <code>lua.h</code>):
4246
4247 <ul>
4248
4249 <li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b>
4250 success.</li>
4251
4252 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b>
4253 a runtime error.
4254 </li>
4255
4256 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
4257 memory allocation error.
4258 For such errors, Lua does not call the message handler.
4259 </li>
4260
4261 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b>
4262 error while running the message handler.
4263 </li>
4264
4265 <li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
4266 error while running a <code>__gc</code> metamethod.
4267 For such errors, Lua does not call the message handler
4268 (as this kind of error typically has no relation
4269 with the function being called).
4270 </li>
4271
4272 </ul>
4273
4274
4275
4276
4277 <hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4278 <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4279 <pre>int lua_pcallk (lua_State *L,
4280                 int nargs,
4281                 int nresults,
4282                 int msgh,
4283                 lua_KContext ctx,
4284                 lua_KFunction k);</pre>
4285
4286 <p>
4287 This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4288 but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
4289
4290
4291
4292
4293
4294 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4295 <span class="apii">[-n, +0, &ndash;]</span>
4296 <pre>void lua_pop (lua_State *L, int n);</pre>
4297
4298 <p>
4299 Pops <code>n</code> elements from the stack.
4300
4301
4302
4303
4304
4305 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4306 <span class="apii">[-0, +1, &ndash;]</span>
4307 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
4308
4309 <p>
4310 Pushes a boolean value with value <code>b</code> onto the stack.
4311
4312
4313
4314
4315
4316 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4317 <span class="apii">[-n, +1, <em>m</em>]</span>
4318 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4319
4320 <p>
4321 Pushes a new C&nbsp;closure onto the stack.
4322
4323
4324 <p>
4325 When a C&nbsp;function is created,
4326 it is possible to associate some values with it,
4327 thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>);
4328 these values are then accessible to the function whenever it is called.
4329 To associate values with a C&nbsp;function,
4330 first these values must be pushed onto the stack
4331 (when there are multiple values, the first value is pushed first).
4332 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4333 is called to create and push the C&nbsp;function onto the stack,
4334 with the argument <code>n</code> telling how many values will be
4335 associated with the function.
4336 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4337
4338
4339 <p>
4340 The maximum value for <code>n</code> is 255.
4341
4342
4343 <p>
4344 When <code>n</code> is zero,
4345 this function creates a <em>light C&nbsp;function</em>,
4346 which is just a pointer to the C&nbsp;function.
4347 In that case, it never raises a memory error.
4348
4349
4350
4351
4352
4353 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4354 <span class="apii">[-0, +1, &ndash;]</span>
4355 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4356
4357 <p>
4358 Pushes a C&nbsp;function onto the stack.
4359 This function receives a pointer to a C&nbsp;function
4360 and pushes onto the stack a Lua value of type <code>function</code> that,
4361 when called, invokes the corresponding C&nbsp;function.
4362
4363
4364 <p>
4365 Any function to be callable by Lua must
4366 follow the correct protocol to receive its parameters
4367 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4368
4369
4370
4371
4372
4373 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4374 <span class="apii">[-0, +1, <em>e</em>]</span>
4375 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4376
4377 <p>
4378 Pushes onto the stack a formatted string
4379 and returns a pointer to this string.
4380 It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4381 but has some important differences:
4382
4383 <ul>
4384
4385 <li>
4386 You do not have to allocate space for the result:
4387 the result is a Lua string and Lua takes care of memory allocation
4388 (and deallocation, through garbage collection).
4389 </li>
4390
4391 <li>
4392 The conversion specifiers are quite restricted.
4393 There are no flags, widths, or precisions.
4394 The conversion specifiers can only be
4395 '<code>%%</code>' (inserts the character '<code>%</code>'),
4396 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4397 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4398 '<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4399 '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
4400 '<code>%d</code>' (inserts an <code>int</code>),
4401 '<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4402 '<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4403 </li>
4404
4405 </ul>
4406
4407 <p>
4408 Unlike other push functions,
4409 this function checks for the stack space it needs,
4410 including the slot for its result.
4411
4412
4413
4414
4415
4416 <hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4417 <span class="apii">[-0, +1, &ndash;]</span>
4418 <pre>void lua_pushglobaltable (lua_State *L);</pre>
4419
4420 <p>
4421 Pushes the global environment onto the stack.
4422
4423
4424
4425
4426
4427 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4428 <span class="apii">[-0, +1, &ndash;]</span>
4429 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4430
4431 <p>
4432 Pushes an integer with value <code>n</code> onto the stack.
4433
4434
4435
4436
4437
4438 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4439 <span class="apii">[-0, +1, &ndash;]</span>
4440 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4441
4442 <p>
4443 Pushes a light userdata onto the stack.
4444
4445
4446 <p>
4447 Userdata represent C&nbsp;values in Lua.
4448 A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4449 It is a value (like a number):
4450 you do not create it, it has no individual metatable,
4451 and it is not collected (as it was never created).
4452 A light userdata is equal to "any"
4453 light userdata with the same C&nbsp;address.
4454
4455
4456
4457
4458
4459 <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4460 <span class="apii">[-0, +1, <em>m</em>]</span>
4461 <pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4462
4463 <p>
4464 This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
4465 but should be used only when <code>s</code> is a literal string.
4466
4467
4468
4469
4470
4471 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4472 <span class="apii">[-0, +1, <em>m</em>]</span>
4473 <pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4474
4475 <p>
4476 Pushes the string pointed to by <code>s</code> with size <code>len</code>
4477 onto the stack.
4478 Lua makes (or reuses) an internal copy of the given string,
4479 so the memory at <code>s</code> can be freed or reused immediately after
4480 the function returns.
4481 The string can contain any binary data,
4482 including embedded zeros.
4483
4484
4485 <p>
4486 Returns a pointer to the internal copy of the string.
4487
4488
4489
4490
4491
4492 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4493 <span class="apii">[-0, +1, &ndash;]</span>
4494 <pre>void lua_pushnil (lua_State *L);</pre>
4495
4496 <p>
4497 Pushes a nil value onto the stack.
4498
4499
4500
4501
4502
4503 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4504 <span class="apii">[-0, +1, &ndash;]</span>
4505 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4506
4507 <p>
4508 Pushes a float with value <code>n</code> onto the stack.
4509
4510
4511
4512
4513
4514 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4515 <span class="apii">[-0, +1, <em>m</em>]</span>
4516 <pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4517
4518 <p>
4519 Pushes the zero-terminated string pointed to by <code>s</code>
4520 onto the stack.
4521 Lua makes (or reuses) an internal copy of the given string,
4522 so the memory at <code>s</code> can be freed or reused immediately after
4523 the function returns.
4524
4525
4526 <p>
4527 Returns a pointer to the internal copy of the string.
4528
4529
4530 <p>
4531 If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4532
4533
4534
4535
4536
4537 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4538 <span class="apii">[-0, +1, &ndash;]</span>
4539 <pre>int lua_pushthread (lua_State *L);</pre>
4540
4541 <p>
4542 Pushes the thread represented by <code>L</code> onto the stack.
4543 Returns 1 if this thread is the main thread of its state.
4544
4545
4546
4547
4548
4549 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4550 <span class="apii">[-0, +1, &ndash;]</span>
4551 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
4552
4553 <p>
4554 Pushes a copy of the element at the given index
4555 onto the stack.
4556
4557
4558
4559
4560
4561 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4562 <span class="apii">[-0, +1, <em>m</em>]</span>
4563 <pre>const char *lua_pushvfstring (lua_State *L,
4564                               const char *fmt,
4565                               va_list argp);</pre>
4566
4567 <p>
4568 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4569 instead of a variable number of arguments.
4570
4571
4572
4573
4574
4575 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4576 <span class="apii">[-0, +0, &ndash;]</span>
4577 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4578
4579 <p>
4580 Returns 1 if the two values in indices <code>index1</code> and
4581 <code>index2</code> are primitively equal
4582 (that is, without calling the <code>__eq</code> metamethod).
4583 Otherwise returns&nbsp;0.
4584 Also returns&nbsp;0 if any of the indices are not valid.
4585
4586
4587
4588
4589
4590 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4591 <span class="apii">[-1, +1, &ndash;]</span>
4592 <pre>int lua_rawget (lua_State *L, int index);</pre>
4593
4594 <p>
4595 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4596 (i.e., without metamethods).
4597
4598
4599
4600
4601
4602 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4603 <span class="apii">[-0, +1, &ndash;]</span>
4604 <pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4605
4606 <p>
4607 Pushes onto the stack the value <code>t[n]</code>,
4608 where <code>t</code> is the table at the given index.
4609 The access is raw,
4610 that is, it does not invoke the <code>__index</code> metamethod.
4611
4612
4613 <p>
4614 Returns the type of the pushed value.
4615
4616
4617
4618
4619
4620 <hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4621 <span class="apii">[-0, +1, &ndash;]</span>
4622 <pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4623
4624 <p>
4625 Pushes onto the stack the value <code>t[k]</code>,
4626 where <code>t</code> is the table at the given index and
4627 <code>k</code> is the pointer <code>p</code> represented as a light userdata.
4628 The access is raw;
4629 that is, it does not invoke the <code>__index</code> metamethod.
4630
4631
4632 <p>
4633 Returns the type of the pushed value.
4634
4635
4636
4637
4638
4639 <hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
4640 <span class="apii">[-0, +0, &ndash;]</span>
4641 <pre>size_t lua_rawlen (lua_State *L, int index);</pre>
4642
4643 <p>
4644 Returns the raw "length" of the value at the given index:
4645 for strings, this is the string length;
4646 for tables, this is the result of the length operator ('<code>#</code>')
4647 with no metamethods;
4648 for userdata, this is the size of the block of memory allocated
4649 for the userdata;
4650 for other values, it is&nbsp;0.
4651
4652
4653
4654
4655
4656 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
4657 <span class="apii">[-2, +0, <em>m</em>]</span>
4658 <pre>void lua_rawset (lua_State *L, int index);</pre>
4659
4660 <p>
4661 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
4662 (i.e., without metamethods).
4663
4664
4665
4666
4667
4668 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
4669 <span class="apii">[-1, +0, <em>m</em>]</span>
4670 <pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
4671
4672 <p>
4673 Does the equivalent of <code>t[i] = v</code>,
4674 where <code>t</code> is the table at the given index
4675 and <code>v</code> is the value at the top of the stack.
4676
4677
4678 <p>
4679 This function pops the value from the stack.
4680 The assignment is raw,
4681 that is, it does not invoke the <code>__newindex</code> metamethod.
4682
4683
4684
4685
4686
4687 <hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
4688 <span class="apii">[-1, +0, <em>m</em>]</span>
4689 <pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
4690
4691 <p>
4692 Does the equivalent of <code>t[p] = v</code>,
4693 where <code>t</code> is the table at the given index,
4694 <code>p</code> is encoded as a light userdata,
4695 and <code>v</code> is the value at the top of the stack.
4696
4697
4698 <p>
4699 This function pops the value from the stack.
4700 The assignment is raw,
4701 that is, it does not invoke <code>__newindex</code> metamethod.
4702
4703
4704
4705
4706
4707 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
4708 <pre>typedef const char * (*lua_Reader) (lua_State *L,
4709                                     void *data,
4710                                     size_t *size);</pre>
4711
4712 <p>
4713 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
4714 Every time it needs another piece of the chunk,
4715 <a href="#lua_load"><code>lua_load</code></a> calls the reader,
4716 passing along its <code>data</code> parameter.
4717 The reader must return a pointer to a block of memory
4718 with a new piece of the chunk
4719 and set <code>size</code> to the block size.
4720 The block must exist until the reader function is called again.
4721 To signal the end of the chunk,
4722 the reader must return <code>NULL</code> or set <code>size</code> to zero.
4723 The reader function may return pieces of any size greater than zero.
4724
4725
4726
4727
4728
4729 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
4730 <span class="apii">[-0, +0, <em>e</em>]</span>
4731 <pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
4732
4733 <p>
4734 Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>.
4735 It is defined as a macro:
4736
4737 <pre>
4738      #define lua_register(L,n,f) \
4739             (lua_pushcfunction(L, f), lua_setglobal(L, n))
4740 </pre>
4741
4742
4743
4744
4745 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
4746 <span class="apii">[-1, +0, &ndash;]</span>
4747 <pre>void lua_remove (lua_State *L, int index);</pre>
4748
4749 <p>
4750 Removes the element at the given valid index,
4751 shifting down the elements above this index to fill the gap.
4752 This function cannot be called with a pseudo-index,
4753 because a pseudo-index is not an actual stack position.
4754
4755
4756
4757
4758
4759 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
4760 <span class="apii">[-1, +0, &ndash;]</span>
4761 <pre>void lua_replace (lua_State *L, int index);</pre>
4762
4763 <p>
4764 Moves the top element into the given valid index
4765 without shifting any element
4766 (therefore replacing the value at that given index),
4767 and then pops the top element.
4768
4769
4770
4771
4772
4773 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
4774 <span class="apii">[-?, +?, &ndash;]</span>
4775 <pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre>
4776
4777 <p>
4778 Starts and resumes a coroutine in the given thread <code>L</code>.
4779
4780
4781 <p>
4782 To start a coroutine,
4783 you push onto the thread stack the main function plus any arguments;
4784 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
4785 with <code>nargs</code> being the number of arguments.
4786 This call returns when the coroutine suspends or finishes its execution.
4787 When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
4788 or all values returned by the body function.
4789 <a href="#lua_resume"><code>lua_resume</code></a> returns
4790 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
4791 <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
4792 without errors,
4793 or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
4794
4795
4796 <p>
4797 In case of errors,
4798 the stack is not unwound,
4799 so you can use the debug API over it.
4800 The error object is on the top of the stack.
4801
4802
4803 <p>
4804 To resume a coroutine,
4805 you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>,
4806 put on its stack only the values to
4807 be passed as results from <code>yield</code>,
4808 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
4809
4810
4811 <p>
4812 The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
4813 If there is no such coroutine,
4814 this parameter can be <code>NULL</code>.
4815
4816
4817
4818
4819
4820 <hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
4821 <span class="apii">[-0, +0, &ndash;]</span>
4822 <pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
4823
4824 <p>
4825 Rotates the stack elements between the valid index <code>idx</code>
4826 and the top of the stack.
4827 The elements are rotated <code>n</code> positions in the direction of the top,
4828 for a positive <code>n</code>,
4829 or <code>-n</code> positions in the direction of the bottom,
4830 for a negative <code>n</code>.
4831 The absolute value of <code>n</code> must not be greater than the size
4832 of the slice being rotated.
4833 This function cannot be called with a pseudo-index,
4834 because a pseudo-index is not an actual stack position.
4835
4836
4837
4838
4839
4840 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
4841 <span class="apii">[-0, +0, &ndash;]</span>
4842 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
4843
4844 <p>
4845 Changes the allocator function of a given state to <code>f</code>
4846 with user data <code>ud</code>.
4847
4848
4849
4850
4851
4852 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
4853 <span class="apii">[-1, +0, <em>e</em>]</span>
4854 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
4855
4856 <p>
4857 Does the equivalent to <code>t[k] = v</code>,
4858 where <code>t</code> is the value at the given index
4859 and <code>v</code> is the value at the top of the stack.
4860
4861
4862 <p>
4863 This function pops the value from the stack.
4864 As in Lua, this function may trigger a metamethod
4865 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4866
4867
4868
4869
4870
4871 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
4872 <span class="apii">[-1, +0, <em>e</em>]</span>
4873 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
4874
4875 <p>
4876 Pops a value from the stack and
4877 sets it as the new value of global <code>name</code>.
4878
4879
4880
4881
4882
4883 <hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
4884 <span class="apii">[-1, +0, <em>e</em>]</span>
4885 <pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
4886
4887 <p>
4888 Does the equivalent to <code>t[n] = v</code>,
4889 where <code>t</code> is the value at the given index
4890 and <code>v</code> is the value at the top of the stack.
4891
4892
4893 <p>
4894 This function pops the value from the stack.
4895 As in Lua, this function may trigger a metamethod
4896 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4897
4898
4899
4900
4901
4902 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
4903 <span class="apii">[-1, +0, &ndash;]</span>
4904 <pre>void lua_setmetatable (lua_State *L, int index);</pre>
4905
4906 <p>
4907 Pops a table from the stack and
4908 sets it as the new metatable for the value at the given index.
4909
4910
4911
4912
4913
4914 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
4915 <span class="apii">[-2, +0, <em>e</em>]</span>
4916 <pre>void lua_settable (lua_State *L, int index);</pre>
4917
4918 <p>
4919 Does the equivalent to <code>t[k] = v</code>,
4920 where <code>t</code> is the value at the given index,
4921 <code>v</code> is the value at the top of the stack,
4922 and <code>k</code> is the value just below the top.
4923
4924
4925 <p>
4926 This function pops both the key and the value from the stack.
4927 As in Lua, this function may trigger a metamethod
4928 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4929
4930
4931
4932
4933
4934 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
4935 <span class="apii">[-?, +?, &ndash;]</span>
4936 <pre>void lua_settop (lua_State *L, int index);</pre>
4937
4938 <p>
4939 Accepts any index, or&nbsp;0,
4940 and sets the stack top to this index.
4941 If the new top is larger than the old one,
4942 then the new elements are filled with <b>nil</b>.
4943 If <code>index</code> is&nbsp;0, then all stack elements are removed.
4944
4945
4946
4947
4948
4949 <hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p>
4950 <span class="apii">[-1, +0, &ndash;]</span>
4951 <pre>void lua_setuservalue (lua_State *L, int index);</pre>
4952
4953 <p>
4954 Pops a value from the stack and sets it as
4955 the new value associated to the full userdata at the given index.
4956
4957
4958
4959
4960
4961 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
4962 <pre>typedef struct lua_State lua_State;</pre>
4963
4964 <p>
4965 An opaque structure that points to a thread and indirectly
4966 (through the thread) to the whole state of a Lua interpreter.
4967 The Lua library is fully reentrant:
4968 it has no global variables.
4969 All information about a state is accessible through this structure.
4970
4971
4972 <p>
4973 A pointer to this structure must be passed as the first argument to
4974 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4975 which creates a Lua state from scratch.
4976
4977
4978
4979
4980
4981 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4982 <span class="apii">[-0, +0, &ndash;]</span>
4983 <pre>int lua_status (lua_State *L);</pre>
4984
4985 <p>
4986 Returns the status of the thread <code>L</code>.
4987
4988
4989 <p>
4990 The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread,
4991 an error code if the thread finished the execution
4992 of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
4993 or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4994
4995
4996 <p>
4997 You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
4998 You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
4999 (to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
5000 (to resume a coroutine).
5001
5002
5003
5004
5005
5006 <hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
5007 <span class="apii">[-0, +1, &ndash;]</span>
5008 <pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
5009
5010 <p>
5011 Converts the zero-terminated string <code>s</code> to a number,
5012 pushes that number into the stack,
5013 and returns the total size of the string,
5014 that is, its length plus one.
5015 The conversion can result in an integer or a float,
5016 according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
5017 The string may have leading and trailing spaces and a sign.
5018 If the string is not a valid numeral,
5019 returns 0 and pushes nothing.
5020 (Note that the result can be used as a boolean,
5021 true if the conversion succeeds.)
5022
5023
5024
5025
5026
5027 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
5028 <span class="apii">[-0, +0, &ndash;]</span>
5029 <pre>int lua_toboolean (lua_State *L, int index);</pre>
5030
5031 <p>
5032 Converts the Lua value at the given index to a C&nbsp;boolean
5033 value (0&nbsp;or&nbsp;1).
5034 Like all tests in Lua,
5035 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
5036 different from <b>false</b> and <b>nil</b>;
5037 otherwise it returns false.
5038 (If you want to accept only actual boolean values,
5039 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
5040
5041
5042
5043
5044
5045 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
5046 <span class="apii">[-0, +0, &ndash;]</span>
5047 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
5048
5049 <p>
5050 Converts a value at the given index to a C&nbsp;function.
5051 That value must be a C&nbsp;function;
5052 otherwise, returns <code>NULL</code>.
5053
5054
5055
5056
5057
5058 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
5059 <span class="apii">[-0, +0, &ndash;]</span>
5060 <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
5061
5062 <p>
5063 Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5064
5065
5066
5067
5068
5069 <hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
5070 <span class="apii">[-0, +0, &ndash;]</span>
5071 <pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
5072
5073 <p>
5074 Converts the Lua value at the given index
5075 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
5076 The Lua value must be an integer,
5077 or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
5078 otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
5079
5080
5081 <p>
5082 If <code>isnum</code> is not <code>NULL</code>,
5083 its referent is assigned a boolean value that
5084 indicates whether the operation succeeded.
5085
5086
5087
5088
5089
5090 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
5091 <span class="apii">[-0, +0, <em>m</em>]</span>
5092 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5093
5094 <p>
5095 Converts the Lua value at the given index to a C&nbsp;string.
5096 If <code>len</code> is not <code>NULL</code>,
5097 it sets <code>*len</code> with the string length.
5098 The Lua value must be a string or a number;
5099 otherwise, the function returns <code>NULL</code>.
5100 If the value is a number,
5101 then <code>lua_tolstring</code> also
5102 <em>changes the actual value in the stack to a string</em>.
5103 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
5104 when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5105
5106
5107 <p>
5108 <code>lua_tolstring</code> returns a pointer
5109 to a string inside the Lua state.
5110 This string always has a zero ('<code>\0</code>')
5111 after its last character (as in&nbsp;C),
5112 but can contain other zeros in its body.
5113
5114
5115 <p>
5116 Because Lua has garbage collection,
5117 there is no guarantee that the pointer returned by <code>lua_tolstring</code>
5118 will be valid after the corresponding Lua value is removed from the stack.
5119
5120
5121
5122
5123
5124 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5125 <span class="apii">[-0, +0, &ndash;]</span>
5126 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5127
5128 <p>
5129 Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5130
5131
5132
5133
5134
5135 <hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5136 <span class="apii">[-0, +0, &ndash;]</span>
5137 <pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5138
5139 <p>
5140 Converts the Lua value at the given index
5141 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5142 The Lua value must be a number or a string convertible to a number
5143 (see <a href="#3.4.3">&sect;3.4.3</a>);
5144 otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5145
5146
5147 <p>
5148 If <code>isnum</code> is not <code>NULL</code>,
5149 its referent is assigned a boolean value that
5150 indicates whether the operation succeeded.
5151
5152
5153
5154
5155
5156 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5157 <span class="apii">[-0, +0, &ndash;]</span>
5158 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
5159
5160 <p>
5161 Converts the value at the given index to a generic
5162 C&nbsp;pointer (<code>void*</code>).
5163 The value can be a userdata, a table, a thread, or a function;
5164 otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5165 Different objects will give different pointers.
5166 There is no way to convert the pointer back to its original value.
5167
5168
5169 <p>
5170 Typically this function is used only for hashing and debug information.
5171
5172
5173
5174
5175
5176 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5177 <span class="apii">[-0, +0, <em>m</em>]</span>
5178 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
5179
5180 <p>
5181 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5182
5183
5184
5185
5186
5187 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5188 <span class="apii">[-0, +0, &ndash;]</span>
5189 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5190
5191 <p>
5192 Converts the value at the given index to a Lua thread
5193 (represented as <code>lua_State*</code>).
5194 This value must be a thread;
5195 otherwise, the function returns <code>NULL</code>.
5196
5197
5198
5199
5200
5201 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5202 <span class="apii">[-0, +0, &ndash;]</span>
5203 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
5204
5205 <p>
5206 If the value at the given index is a full userdata,
5207 returns its block address.
5208 If the value is a light userdata,
5209 returns its pointer.
5210 Otherwise, returns <code>NULL</code>.
5211
5212
5213
5214
5215
5216 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5217 <span class="apii">[-0, +0, &ndash;]</span>
5218 <pre>int lua_type (lua_State *L, int index);</pre>
5219
5220 <p>
5221 Returns the type of the value in the given valid index,
5222 or <code>LUA_TNONE</code> for a non-valid (but acceptable) index.
5223 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5224 defined in <code>lua.h</code>:
5225 <a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a> (0),
5226 <a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5227 <a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5228 <a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5229 <a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5230 <a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5231 <a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5232 <a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5233 and
5234 <a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5235
5236
5237
5238
5239
5240 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5241 <span class="apii">[-0, +0, &ndash;]</span>
5242 <pre>const char *lua_typename (lua_State *L, int tp);</pre>
5243
5244 <p>
5245 Returns the name of the type encoded by the value <code>tp</code>,
5246 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5247
5248
5249
5250
5251
5252 <hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5253 <pre>typedef ... lua_Unsigned;</pre>
5254
5255 <p>
5256 The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5257
5258
5259
5260
5261
5262 <hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5263 <span class="apii">[-0, +0, &ndash;]</span>
5264 <pre>int lua_upvalueindex (int i);</pre>
5265
5266 <p>
5267 Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5268 the running function (see <a href="#4.4">&sect;4.4</a>).
5269
5270
5271
5272
5273
5274 <hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5275 <span class="apii">[-0, +0, &ndash;]</span>
5276 <pre>const lua_Number *lua_version (lua_State *L);</pre>
5277
5278 <p>
5279 Returns the address of the version number
5280 (a C static variable)
5281 stored in the Lua core.
5282 When called with a valid <a href="#lua_State"><code>lua_State</code></a>,
5283 returns the address of the version used to create that state.
5284 When called with <code>NULL</code>,
5285 returns the address of the version running the call.
5286
5287
5288
5289
5290
5291 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5292 <pre>typedef int (*lua_Writer) (lua_State *L,
5293                            const void* p,
5294                            size_t sz,
5295                            void* ud);</pre>
5296
5297 <p>
5298 The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5299 Every time it produces another piece of chunk,
5300 <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
5301 passing along the buffer to be written (<code>p</code>),
5302 its size (<code>sz</code>),
5303 and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5304
5305
5306 <p>
5307 The writer returns an error code:
5308 0&nbsp;means no errors;
5309 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5310 calling the writer again.
5311
5312
5313
5314
5315
5316 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5317 <span class="apii">[-?, +?, &ndash;]</span>
5318 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5319
5320 <p>
5321 Exchange values between different threads of the same state.
5322
5323
5324 <p>
5325 This function pops <code>n</code> values from the stack <code>from</code>,
5326 and pushes them onto the stack <code>to</code>.
5327
5328
5329
5330
5331
5332 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5333 <span class="apii">[-?, +?, <em>e</em>]</span>
5334 <pre>int lua_yield (lua_State *L, int nresults);</pre>
5335
5336 <p>
5337 This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5338 but it has no continuation (see <a href="#4.7">&sect;4.7</a>).
5339 Therefore, when the thread resumes,
5340 it continues the function that called
5341 the function calling <code>lua_yield</code>.
5342
5343
5344
5345
5346
5347 <hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5348 <span class="apii">[-?, +?, <em>e</em>]</span>
5349 <pre>int lua_yieldk (lua_State *L,
5350                 int nresults,
5351                 lua_KContext ctx,
5352                 lua_KFunction k);</pre>
5353
5354 <p>
5355 Yields a coroutine (thread).
5356
5357
5358 <p>
5359 When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5360 the running coroutine suspends its execution,
5361 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5362 The parameter <code>nresults</code> is the number of values from the stack
5363 that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5364
5365
5366 <p>
5367 When the coroutine is resumed again,
5368 Lua calls the given continuation function <code>k</code> to continue
5369 the execution of the C&nbsp;function that yielded (see <a href="#4.7">&sect;4.7</a>).
5370 This continuation function receives the same stack
5371 from the previous function,
5372 with the <code>n</code> results removed and
5373 replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5374 Moreover,
5375 the continuation function receives the value <code>ctx</code>
5376 that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5377
5378
5379 <p>
5380 Usually, this function does not return;
5381 when the coroutine eventually resumes,
5382 it continues executing the continuation function.
5383 However, there is one special case,
5384 which is when this function is called
5385 from inside a line or a count hook (see <a href="#4.9">&sect;4.9</a>).
5386 In that case, <code>lua_yieldk</code> should be called with no continuation
5387 (probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
5388 and the hook should return immediately after the call.
5389 Lua will yield and,
5390 when the coroutine resumes again,
5391 it will continue the normal execution
5392 of the (Lua) function that triggered the hook.
5393
5394
5395 <p>
5396 This function can raise an error if it is called from a thread
5397 with a pending C call with no continuation function,
5398 or it is called from a thread that is not running inside a resume
5399 (e.g., the main thread).
5400
5401
5402
5403
5404
5405
5406
5407 <h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2>
5408
5409 <p>
5410 Lua has no built-in debugging facilities.
5411 Instead, it offers a special interface
5412 by means of functions and <em>hooks</em>.
5413 This interface allows the construction of different
5414 kinds of debuggers, profilers, and other tools
5415 that need "inside information" from the interpreter.
5416
5417
5418
5419 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5420 <pre>typedef struct lua_Debug {
5421   int event;
5422   const char *name;           /* (n) */
5423   const char *namewhat;       /* (n) */
5424   const char *what;           /* (S) */
5425   const char *source;         /* (S) */
5426   int currentline;            /* (l) */
5427   int linedefined;            /* (S) */
5428   int lastlinedefined;        /* (S) */
5429   unsigned char nups;         /* (u) number of upvalues */
5430   unsigned char nparams;      /* (u) number of parameters */
5431   char isvararg;              /* (u) */
5432   char istailcall;            /* (t) */
5433   char short_src[LUA_IDSIZE]; /* (S) */
5434   /* private part */
5435   <em>other fields</em>
5436 } lua_Debug;</pre>
5437
5438 <p>
5439 A structure used to carry different pieces of
5440 information about a function or an activation record.
5441 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5442 of this structure, for later use.
5443 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5444 call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5445
5446
5447 <p>
5448 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5449
5450 <ul>
5451
5452 <li><b><code>source</code>: </b>
5453 the name of the chunk that created the function.
5454 If <code>source</code> starts with a '<code>@</code>',
5455 it means that the function was defined in a file where
5456 the file name follows the '<code>@</code>'.
5457 If <code>source</code> starts with a '<code>=</code>',
5458 the remainder of its contents describe the source in a user-dependent manner.
5459 Otherwise,
5460 the function was defined in a string where
5461 <code>source</code> is that string.
5462 </li>
5463
5464 <li><b><code>short_src</code>: </b>
5465 a "printable" version of <code>source</code>, to be used in error messages.
5466 </li>
5467
5468 <li><b><code>linedefined</code>: </b>
5469 the line number where the definition of the function starts.
5470 </li>
5471
5472 <li><b><code>lastlinedefined</code>: </b>
5473 the line number where the definition of the function ends.
5474 </li>
5475
5476 <li><b><code>what</code>: </b>
5477 the string <code>"Lua"</code> if the function is a Lua function,
5478 <code>"C"</code> if it is a C&nbsp;function,
5479 <code>"main"</code> if it is the main part of a chunk.
5480 </li>
5481
5482 <li><b><code>currentline</code>: </b>
5483 the current line where the given function is executing.
5484 When no line information is available,
5485 <code>currentline</code> is set to -1.
5486 </li>
5487
5488 <li><b><code>name</code>: </b>
5489 a reasonable name for the given function.
5490 Because functions in Lua are first-class values,
5491 they do not have a fixed name:
5492 some functions can be the value of multiple global variables,
5493 while others can be stored only in a table field.
5494 The <code>lua_getinfo</code> function checks how the function was
5495 called to find a suitable name.
5496 If it cannot find a name,
5497 then <code>name</code> is set to <code>NULL</code>.
5498 </li>
5499
5500 <li><b><code>namewhat</code>: </b>
5501 explains the <code>name</code> field.
5502 The value of <code>namewhat</code> can be
5503 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
5504 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
5505 according to how the function was called.
5506 (Lua uses the empty string when no other option seems to apply.)
5507 </li>
5508
5509 <li><b><code>istailcall</code>: </b>
5510 true if this function invocation was called by a tail call.
5511 In this case, the caller of this level is not in the stack.
5512 </li>
5513
5514 <li><b><code>nups</code>: </b>
5515 the number of upvalues of the function.
5516 </li>
5517
5518 <li><b><code>nparams</code>: </b>
5519 the number of fixed parameters of the function
5520 (always 0&nbsp;for C&nbsp;functions).
5521 </li>
5522
5523 <li><b><code>isvararg</code>: </b>
5524 true if the function is a vararg function
5525 (always true for C&nbsp;functions).
5526 </li>
5527
5528 </ul>
5529
5530
5531
5532
5533 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
5534 <span class="apii">[-0, +0, &ndash;]</span>
5535 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
5536
5537 <p>
5538 Returns the current hook function.
5539
5540
5541
5542
5543
5544 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
5545 <span class="apii">[-0, +0, &ndash;]</span>
5546 <pre>int lua_gethookcount (lua_State *L);</pre>
5547
5548 <p>
5549 Returns the current hook count.
5550
5551
5552
5553
5554
5555 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
5556 <span class="apii">[-0, +0, &ndash;]</span>
5557 <pre>int lua_gethookmask (lua_State *L);</pre>
5558
5559 <p>
5560 Returns the current hook mask.
5561
5562
5563
5564
5565
5566 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
5567 <span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span>
5568 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
5569
5570 <p>
5571 Gets information about a specific function or function invocation.
5572
5573
5574 <p>
5575 To get information about a function invocation,
5576 the parameter <code>ar</code> must be a valid activation record that was
5577 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5578 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5579
5580
5581 <p>
5582 To get information about a function, you push it onto the stack
5583 and start the <code>what</code> string with the character '<code>&gt;</code>'.
5584 (In that case,
5585 <code>lua_getinfo</code> pops the function from the top of the stack.)
5586 For instance, to know in which line a function <code>f</code> was defined,
5587 you can write the following code:
5588
5589 <pre>
5590      lua_Debug ar;
5591      lua_getglobal(L, "f");  /* get global 'f' */
5592      lua_getinfo(L, "&gt;S", &amp;ar);
5593      printf("%d\n", ar.linedefined);
5594 </pre>
5595
5596 <p>
5597 Each character in the string <code>what</code>
5598 selects some fields of the structure <code>ar</code> to be filled or
5599 a value to be pushed on the stack:
5600
5601 <ul>
5602
5603 <li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
5604 </li>
5605
5606 <li><b>'<code>S</code>': </b>
5607 fills in the fields <code>source</code>, <code>short_src</code>,
5608 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
5609 </li>
5610
5611 <li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
5612 </li>
5613
5614 <li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
5615 </li>
5616
5617 <li><b>'<code>u</code>': </b> fills in the fields
5618 <code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
5619 </li>
5620
5621 <li><b>'<code>f</code>': </b>
5622 pushes onto the stack the function that is
5623 running at the given level;
5624 </li>
5625
5626 <li><b>'<code>L</code>': </b>
5627 pushes onto the stack a table whose indices are the
5628 numbers of the lines that are valid on the function.
5629 (A <em>valid line</em> is a line with some associated code,
5630 that is, a line where you can put a break point.
5631 Non-valid lines include empty lines and comments.)
5632
5633
5634 <p>
5635 If this option is given together with option '<code>f</code>',
5636 its table is pushed after the function.
5637 </li>
5638
5639 </ul>
5640
5641 <p>
5642 This function returns 0 on error
5643 (for instance, an invalid option in <code>what</code>).
5644
5645
5646
5647
5648
5649 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
5650 <span class="apii">[-0, +(0|1), &ndash;]</span>
5651 <pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
5652
5653 <p>
5654 Gets information about a local variable of
5655 a given activation record or a given function.
5656
5657
5658 <p>
5659 In the first case,
5660 the parameter <code>ar</code> must be a valid activation record that was
5661 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5662 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5663 The index <code>n</code> selects which local variable to inspect;
5664 see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
5665 and names.
5666
5667
5668 <p>
5669 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
5670 and returns its name.
5671
5672
5673 <p>
5674 In the second case, <code>ar</code> must be <code>NULL</code> and the function
5675 to be inspected must be at the top of the stack.
5676 In this case, only parameters of Lua functions are visible
5677 (as there is no information about what variables are active)
5678 and no values are pushed onto the stack.
5679
5680
5681 <p>
5682 Returns <code>NULL</code> (and pushes nothing)
5683 when the index is greater than
5684 the number of active local variables.
5685
5686
5687
5688
5689
5690 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
5691 <span class="apii">[-0, +0, &ndash;]</span>
5692 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
5693
5694 <p>
5695 Gets information about the interpreter runtime stack.
5696
5697
5698 <p>
5699 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
5700 an identification of the <em>activation record</em>
5701 of the function executing at a given level.
5702 Level&nbsp;0 is the current running function,
5703 whereas level <em>n+1</em> is the function that has called level <em>n</em>
5704 (except for tail calls, which do not count on the stack).
5705 When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
5706 when called with a level greater than the stack depth,
5707 it returns 0.
5708
5709
5710
5711
5712
5713 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
5714 <span class="apii">[-0, +(0|1), &ndash;]</span>
5715 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
5716
5717 <p>
5718 Gets information about the <code>n</code>-th upvalue
5719 of the closure at index <code>funcindex</code>.
5720 It pushes the upvalue's value onto the stack
5721 and returns its name.
5722 Returns <code>NULL</code> (and pushes nothing)
5723 when the index <code>n</code> is greater than the number of upvalues.
5724
5725
5726 <p>
5727 For C&nbsp;functions, this function uses the empty string <code>""</code>
5728 as a name for all upvalues.
5729 (For Lua functions,
5730 upvalues are the external local variables that the function uses,
5731 and that are consequently included in its closure.)
5732
5733
5734 <p>
5735 Upvalues have no particular order,
5736 as they are active through the whole function.
5737 They are numbered in an arbitrary order.
5738
5739
5740
5741
5742
5743 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
5744 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
5745
5746 <p>
5747 Type for debugging hook functions.
5748
5749
5750 <p>
5751 Whenever a hook is called, its <code>ar</code> argument has its field
5752 <code>event</code> set to the specific event that triggered the hook.
5753 Lua identifies these events with the following constants:
5754 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
5755 <a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
5756 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
5757 Moreover, for line events, the field <code>currentline</code> is also set.
5758 To get the value of any other field in <code>ar</code>,
5759 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5760
5761
5762 <p>
5763 For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
5764 the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
5765 in this case, there will be no corresponding return event.
5766
5767
5768 <p>
5769 While Lua is running a hook, it disables other calls to hooks.
5770 Therefore, if a hook calls back Lua to execute a function or a chunk,
5771 this execution occurs without any calls to hooks.
5772
5773
5774 <p>
5775 Hook functions cannot have continuations,
5776 that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5777 <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>.
5778
5779
5780 <p>
5781 Hook functions can yield under the following conditions:
5782 Only count and line events can yield;
5783 to yield, a hook function must finish its execution
5784 calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
5785 (that is, with no values).
5786
5787
5788
5789
5790
5791 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
5792 <span class="apii">[-0, +0, &ndash;]</span>
5793 <pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5794
5795 <p>
5796 Sets the debugging hook function.
5797
5798
5799 <p>
5800 Argument <code>f</code> is the hook function.
5801 <code>mask</code> specifies on which events the hook will be called:
5802 it is formed by a bitwise OR of the constants
5803 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
5804 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
5805 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
5806 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
5807 The <code>count</code> argument is only meaningful when the mask
5808 includes <code>LUA_MASKCOUNT</code>.
5809 For each event, the hook is called as explained below:
5810
5811 <ul>
5812
5813 <li><b>The call hook: </b> is called when the interpreter calls a function.
5814 The hook is called just after Lua enters the new function,
5815 before the function gets its arguments.
5816 </li>
5817
5818 <li><b>The return hook: </b> is called when the interpreter returns from a function.
5819 The hook is called just before Lua leaves the function.
5820 There is no standard way to access the values
5821 to be returned by the function.
5822 </li>
5823
5824 <li><b>The line hook: </b> is called when the interpreter is about to
5825 start the execution of a new line of code,
5826 or when it jumps back in the code (even to the same line).
5827 (This event only happens while Lua is executing a Lua function.)
5828 </li>
5829
5830 <li><b>The count hook: </b> is called after the interpreter executes every
5831 <code>count</code> instructions.
5832 (This event only happens while Lua is executing a Lua function.)
5833 </li>
5834
5835 </ul>
5836
5837 <p>
5838 A hook is disabled by setting <code>mask</code> to zero.
5839
5840
5841
5842
5843
5844 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
5845 <span class="apii">[-(0|1), +0, &ndash;]</span>
5846 <pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
5847
5848 <p>
5849 Sets the value of a local variable of a given activation record.
5850 It assigns the value at the top of the stack
5851 to the variable and returns its name.
5852 It also pops the value from the stack.
5853
5854
5855 <p>
5856 Returns <code>NULL</code> (and pops nothing)
5857 when the index is greater than
5858 the number of active local variables.
5859
5860
5861 <p>
5862 Parameters <code>ar</code> and <code>n</code> are as in function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
5863
5864
5865
5866
5867
5868 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
5869 <span class="apii">[-(0|1), +0, &ndash;]</span>
5870 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
5871
5872 <p>
5873 Sets the value of a closure's upvalue.
5874 It assigns the value at the top of the stack
5875 to the upvalue and returns its name.
5876 It also pops the value from the stack.
5877
5878
5879 <p>
5880 Returns <code>NULL</code> (and pops nothing)
5881 when the index <code>n</code> is greater than the number of upvalues.
5882
5883
5884 <p>
5885 Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
5886
5887
5888
5889
5890
5891 <hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
5892 <span class="apii">[-0, +0, &ndash;]</span>
5893 <pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
5894
5895 <p>
5896 Returns a unique identifier for the upvalue numbered <code>n</code>
5897 from the closure at index <code>funcindex</code>.
5898
5899
5900 <p>
5901 These unique identifiers allow a program to check whether different
5902 closures share upvalues.
5903 Lua closures that share an upvalue
5904 (that is, that access a same external local variable)
5905 will return identical ids for those upvalue indices.
5906
5907
5908 <p>
5909 Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
5910 but <code>n</code> cannot be greater than the number of upvalues.
5911
5912
5913
5914
5915
5916 <hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
5917 <span class="apii">[-0, +0, &ndash;]</span>
5918 <pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
5919                                     int funcindex2, int n2);</pre>
5920
5921 <p>
5922 Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
5923 refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
5924
5925
5926
5927
5928
5929
5930
5931 <h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
5932
5933 <p>
5934
5935 The <em>auxiliary library</em> provides several convenient functions
5936 to interface C with Lua.
5937 While the basic API provides the primitive functions for all
5938 interactions between C and Lua,
5939 the auxiliary library provides higher-level functions for some
5940 common tasks.
5941
5942
5943 <p>
5944 All functions and types from the auxiliary library
5945 are defined in header file <code>lauxlib.h</code> and
5946 have a prefix <code>luaL_</code>.
5947
5948
5949 <p>
5950 All functions in the auxiliary library are built on
5951 top of the basic API,
5952 and so they provide nothing that cannot be done with that API.
5953 Nevertheless, the use of the auxiliary library ensures
5954 more consistency to your code.
5955
5956
5957 <p>
5958 Several functions in the auxiliary library use internally some
5959 extra stack slots.
5960 When a function in the auxiliary library uses less than five slots,
5961 it does not check the stack size;
5962 it simply assumes that there are enough slots.
5963
5964
5965 <p>
5966 Several functions in the auxiliary library are used to
5967 check C&nbsp;function arguments.
5968 Because the error message is formatted for arguments
5969 (e.g., "<code>bad argument #1</code>"),
5970 you should not use these functions for other stack values.
5971
5972
5973 <p>
5974 Functions called <code>luaL_check*</code>
5975 always raise an error if the check is not satisfied.
5976
5977
5978
5979 <h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
5980
5981 <p>
5982 Here we list all functions and types from the auxiliary library
5983 in alphabetical order.
5984
5985
5986
5987 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
5988 <span class="apii">[-?, +?, <em>m</em>]</span>
5989 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
5990
5991 <p>
5992 Adds the byte <code>c</code> to the buffer <code>B</code>
5993 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5994
5995
5996
5997
5998
5999 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
6000 <span class="apii">[-?, +?, <em>m</em>]</span>
6001 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
6002
6003 <p>
6004 Adds the string pointed to by <code>s</code> with length <code>l</code> to
6005 the buffer <code>B</code>
6006 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6007 The string can contain embedded zeros.
6008
6009
6010
6011
6012
6013 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
6014 <span class="apii">[-?, +?, &ndash;]</span>
6015 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
6016
6017 <p>
6018 Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
6019 a string of length <code>n</code> previously copied to the
6020 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
6021
6022
6023
6024
6025
6026 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
6027 <span class="apii">[-?, +?, <em>m</em>]</span>
6028 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
6029
6030 <p>
6031 Adds the zero-terminated string pointed to by <code>s</code>
6032 to the buffer <code>B</code>
6033 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6034
6035
6036
6037
6038
6039 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
6040 <span class="apii">[-1, +?, <em>m</em>]</span>
6041 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
6042
6043 <p>
6044 Adds the value at the top of the stack
6045 to the buffer <code>B</code>
6046 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6047 Pops the value.
6048
6049
6050 <p>
6051 This is the only function on string buffers that can (and must)
6052 be called with an extra element on the stack,
6053 which is the value to be added to the buffer.
6054
6055
6056
6057
6058
6059 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
6060 <span class="apii">[-0, +0, <em>v</em>]</span>
6061 <pre>void luaL_argcheck (lua_State *L,
6062                     int cond,
6063                     int arg,
6064                     const char *extramsg);</pre>
6065
6066 <p>
6067 Checks whether <code>cond</code> is true.
6068 If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
6069
6070
6071
6072
6073
6074 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
6075 <span class="apii">[-0, +0, <em>v</em>]</span>
6076 <pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
6077
6078 <p>
6079 Raises an error reporting a problem with argument <code>arg</code>
6080 of the C&nbsp;function that called it,
6081 using a standard message
6082 that includes <code>extramsg</code> as a comment:
6083
6084 <pre>
6085      bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
6086 </pre><p>
6087 This function never returns.
6088
6089
6090
6091
6092
6093 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
6094 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
6095
6096 <p>
6097 Type for a <em>string buffer</em>.
6098
6099
6100 <p>
6101 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
6102 Its pattern of use is as follows:
6103
6104 <ul>
6105
6106 <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6107
6108 <li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6109
6110 <li>
6111 Then add string pieces to the buffer calling any of
6112 the <code>luaL_add*</code> functions.
6113 </li>
6114
6115 <li>
6116 Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6117 This call leaves the final string on the top of the stack.
6118 </li>
6119
6120 </ul>
6121
6122 <p>
6123 If you know beforehand the total size of the resulting string,
6124 you can use the buffer like this:
6125
6126 <ul>
6127
6128 <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6129
6130 <li>Then initialize it and preallocate a space of
6131 size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6132
6133 <li>Then copy the string into that space.</li>
6134
6135 <li>
6136 Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6137 where <code>sz</code> is the total size of the resulting string
6138 copied into that space.
6139 </li>
6140
6141 </ul>
6142
6143 <p>
6144 During its normal operation,
6145 a string buffer uses a variable number of stack slots.
6146 So, while using a buffer, you cannot assume that you know where
6147 the top of the stack is.
6148 You can use the stack between successive calls to buffer operations
6149 as long as that use is balanced;
6150 that is,
6151 when you call a buffer operation,
6152 the stack is at the same level
6153 it was immediately after the previous buffer operation.
6154 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6155 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
6156 level when the buffer was initialized,
6157 plus the final string on its top.
6158
6159
6160
6161
6162
6163 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6164 <span class="apii">[-0, +0, &ndash;]</span>
6165 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6166
6167 <p>
6168 Initializes a buffer <code>B</code>.
6169 This function does not allocate any space;
6170 the buffer must be declared as a variable
6171 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6172
6173
6174
6175
6176
6177 <hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6178 <span class="apii">[-?, +?, <em>m</em>]</span>
6179 <pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6180
6181 <p>
6182 Equivalent to the sequence
6183 <a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6184
6185
6186
6187
6188
6189 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6190 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
6191 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6192
6193 <p>
6194 Calls a metamethod.
6195
6196
6197 <p>
6198 If the object at index <code>obj</code> has a metatable and this
6199 metatable has a field <code>e</code>,
6200 this function calls this field passing the object as its only argument.
6201 In this case this function returns true and pushes onto the
6202 stack the value returned by the call.
6203 If there is no metatable or no metamethod,
6204 this function returns false (without pushing any value on the stack).
6205
6206
6207
6208
6209
6210 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6211 <span class="apii">[-0, +0, <em>v</em>]</span>
6212 <pre>void luaL_checkany (lua_State *L, int arg);</pre>
6213
6214 <p>
6215 Checks whether the function has an argument
6216 of any type (including <b>nil</b>) at position <code>arg</code>.
6217
6218
6219
6220
6221
6222 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6223 <span class="apii">[-0, +0, <em>v</em>]</span>
6224 <pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6225
6226 <p>
6227 Checks whether the function argument <code>arg</code> is an integer
6228 (or can be converted to an integer)
6229 and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6230
6231
6232
6233
6234
6235 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6236 <span class="apii">[-0, +0, <em>v</em>]</span>
6237 <pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6238
6239 <p>
6240 Checks whether the function argument <code>arg</code> is a string
6241 and returns this string;
6242 if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
6243 with the string's length.
6244
6245
6246 <p>
6247 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6248 so all conversions and caveats of that function apply here.
6249
6250
6251
6252
6253
6254 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6255 <span class="apii">[-0, +0, <em>v</em>]</span>
6256 <pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6257
6258 <p>
6259 Checks whether the function argument <code>arg</code> is a number
6260 and returns this number.
6261
6262
6263
6264
6265
6266 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6267 <span class="apii">[-0, +0, <em>v</em>]</span>
6268 <pre>int luaL_checkoption (lua_State *L,
6269                       int arg,
6270                       const char *def,
6271                       const char *const lst[]);</pre>
6272
6273 <p>
6274 Checks whether the function argument <code>arg</code> is a string and
6275 searches for this string in the array <code>lst</code>
6276 (which must be NULL-terminated).
6277 Returns the index in the array where the string was found.
6278 Raises an error if the argument is not a string or
6279 if the string cannot be found.
6280
6281
6282 <p>
6283 If <code>def</code> is not <code>NULL</code>,
6284 the function uses <code>def</code> as a default value when
6285 there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6286
6287
6288 <p>
6289 This is a useful function for mapping strings to C&nbsp;enums.
6290 (The usual convention in Lua libraries is
6291 to use strings instead of numbers to select options.)
6292
6293
6294
6295
6296
6297 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6298 <span class="apii">[-0, +0, <em>v</em>]</span>
6299 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6300
6301 <p>
6302 Grows the stack size to <code>top + sz</code> elements,
6303 raising an error if the stack cannot grow to that size.
6304 <code>msg</code> is an additional text to go into the error message
6305 (or <code>NULL</code> for no additional text).
6306
6307
6308
6309
6310
6311 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6312 <span class="apii">[-0, +0, <em>v</em>]</span>
6313 <pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6314
6315 <p>
6316 Checks whether the function argument <code>arg</code> is a string
6317 and returns this string.
6318
6319
6320 <p>
6321 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6322 so all conversions and caveats of that function apply here.
6323
6324
6325
6326
6327
6328 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6329 <span class="apii">[-0, +0, <em>v</em>]</span>
6330 <pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6331
6332 <p>
6333 Checks whether the function argument <code>arg</code> has type <code>t</code>.
6334 See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6335
6336
6337
6338
6339
6340 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6341 <span class="apii">[-0, +0, <em>v</em>]</span>
6342 <pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6343
6344 <p>
6345 Checks whether the function argument <code>arg</code> is a userdata
6346 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6347 returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6348
6349
6350
6351
6352
6353 <hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6354 <span class="apii">[-0, +0, <em>v</em>]</span>
6355 <pre>void luaL_checkversion (lua_State *L);</pre>
6356
6357 <p>
6358 Checks whether the core running the call,
6359 the core that created the Lua state,
6360 and the code making the call are all using the same version of Lua.
6361 Also checks whether the core running the call
6362 and the core that created the Lua state
6363 are using the same address space.
6364
6365
6366
6367
6368
6369 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6370 <span class="apii">[-0, +?, <em>e</em>]</span>
6371 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6372
6373 <p>
6374 Loads and runs the given file.
6375 It is defined as the following macro:
6376
6377 <pre>
6378      (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6379 </pre><p>
6380 It returns false if there are no errors
6381 or true in case of errors.
6382
6383
6384
6385
6386
6387 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6388 <span class="apii">[-0, +?, &ndash;]</span>
6389 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6390
6391 <p>
6392 Loads and runs the given string.
6393 It is defined as the following macro:
6394
6395 <pre>
6396      (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6397 </pre><p>
6398 It returns false if there are no errors
6399 or true in case of errors.
6400
6401
6402
6403
6404
6405 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6406 <span class="apii">[-0, +0, <em>v</em>]</span>
6407 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6408
6409 <p>
6410 Raises an error.
6411 The error message format is given by <code>fmt</code>
6412 plus any extra arguments,
6413 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6414 It also adds at the beginning of the message the file name and
6415 the line number where the error occurred,
6416 if this information is available.
6417
6418
6419 <p>
6420 This function never returns,
6421 but it is an idiom to use it in C&nbsp;functions
6422 as <code>return luaL_error(<em>args</em>)</code>.
6423
6424
6425
6426
6427
6428 <hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
6429 <span class="apii">[-0, +3, <em>m</em>]</span>
6430 <pre>int luaL_execresult (lua_State *L, int stat);</pre>
6431
6432 <p>
6433 This function produces the return values for
6434 process-related functions in the standard library
6435 (<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
6436
6437
6438
6439
6440
6441 <hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
6442 <span class="apii">[-0, +(1|3), <em>m</em>]</span>
6443 <pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
6444
6445 <p>
6446 This function produces the return values for
6447 file-related functions in the standard library
6448 (<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.).
6449
6450
6451
6452
6453
6454 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
6455 <span class="apii">[-0, +(0|1), <em>m</em>]</span>
6456 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
6457
6458 <p>
6459 Pushes onto the stack the field <code>e</code> from the metatable
6460 of the object at index <code>obj</code> and returns the type of the pushed value.
6461 If the object does not have a metatable,
6462 or if the metatable does not have this field,
6463 pushes nothing and returns <code>LUA_TNIL</code>.
6464
6465
6466
6467
6468
6469 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
6470 <span class="apii">[-0, +1, <em>m</em>]</span>
6471 <pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
6472
6473 <p>
6474 Pushes onto the stack the metatable associated with name <code>tname</code>
6475 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>)
6476 (<b>nil</b> if there is no metatable associated with that name).
6477 Returns the type of the pushed value.
6478
6479
6480
6481
6482
6483 <hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
6484 <span class="apii">[-0, +1, <em>e</em>]</span>
6485 <pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
6486
6487 <p>
6488 Ensures that the value <code>t[fname]</code>,
6489 where <code>t</code> is the value at index <code>idx</code>,
6490 is a table,
6491 and pushes that table onto the stack.
6492 Returns true if it finds a previous table there
6493 and false if it creates a new table.
6494
6495
6496
6497
6498
6499 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
6500 <span class="apii">[-0, +1, <em>m</em>]</span>
6501 <pre>const char *luaL_gsub (lua_State *L,
6502                        const char *s,
6503                        const char *p,
6504                        const char *r);</pre>
6505
6506 <p>
6507 Creates a copy of string <code>s</code> by replacing
6508 any occurrence of the string <code>p</code>
6509 with the string <code>r</code>.
6510 Pushes the resulting string on the stack and returns it.
6511
6512
6513
6514
6515
6516 <hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
6517 <span class="apii">[-0, +0, <em>e</em>]</span>
6518 <pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
6519
6520 <p>
6521 Returns the "length" of the value at the given index
6522 as a number;
6523 it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
6524 Raises an error if the result of the operation is not an integer.
6525 (This case only can happen through metamethods.)
6526
6527
6528
6529
6530
6531 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
6532 <span class="apii">[-0, +1, &ndash;]</span>
6533 <pre>int luaL_loadbuffer (lua_State *L,
6534                      const char *buff,
6535                      size_t sz,
6536                      const char *name);</pre>
6537
6538 <p>
6539 Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
6540
6541
6542
6543
6544
6545 <hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
6546 <span class="apii">[-0, +1, &ndash;]</span>
6547 <pre>int luaL_loadbufferx (lua_State *L,
6548                       const char *buff,
6549                       size_t sz,
6550                       const char *name,
6551                       const char *mode);</pre>
6552
6553 <p>
6554 Loads a buffer as a Lua chunk.
6555 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
6556 buffer pointed to by <code>buff</code> with size <code>sz</code>.
6557
6558
6559 <p>
6560 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6561 <code>name</code> is the chunk name,
6562 used for debug information and error messages.
6563 The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6564
6565
6566
6567
6568
6569 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
6570 <span class="apii">[-0, +1, <em>m</em>]</span>
6571 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
6572
6573 <p>
6574 Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
6575
6576
6577
6578
6579
6580 <hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
6581 <span class="apii">[-0, +1, <em>m</em>]</span>
6582 <pre>int luaL_loadfilex (lua_State *L, const char *filename,
6583                                             const char *mode);</pre>
6584
6585 <p>
6586 Loads a file as a Lua chunk.
6587 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
6588 named <code>filename</code>.
6589 If <code>filename</code> is <code>NULL</code>,
6590 then it loads from the standard input.
6591 The first line in the file is ignored if it starts with a <code>#</code>.
6592
6593
6594 <p>
6595 The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6596
6597
6598 <p>
6599 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
6600 but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
6601 for file-related errors
6602 (e.g., it cannot open or read the file).
6603
6604
6605 <p>
6606 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6607 it does not run it.
6608
6609
6610
6611
6612
6613 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
6614 <span class="apii">[-0, +1, &ndash;]</span>
6615 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
6616
6617 <p>
6618 Loads a string as a Lua chunk.
6619 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
6620 the zero-terminated string <code>s</code>.
6621
6622
6623 <p>
6624 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6625
6626
6627 <p>
6628 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6629 it does not run it.
6630
6631
6632
6633
6634
6635 <hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
6636 <span class="apii">[-0, +1, <em>m</em>]</span>
6637 <pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
6638
6639 <p>
6640 Creates a new table and registers there
6641 the functions in list <code>l</code>.
6642
6643
6644 <p>
6645 It is implemented as the following macro:
6646
6647 <pre>
6648      (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
6649 </pre><p>
6650 The array <code>l</code> must be the actual array,
6651 not a pointer to it.
6652
6653
6654
6655
6656
6657 <hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
6658 <span class="apii">[-0, +1, <em>m</em>]</span>
6659 <pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
6660
6661 <p>
6662 Creates a new table with a size optimized
6663 to store all entries in the array <code>l</code>
6664 (but does not actually store them).
6665 It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
6666 (see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
6667
6668
6669 <p>
6670 It is implemented as a macro.
6671 The array <code>l</code> must be the actual array,
6672 not a pointer to it.
6673
6674
6675
6676
6677
6678 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
6679 <span class="apii">[-0, +1, <em>m</em>]</span>
6680 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
6681
6682 <p>
6683 If the registry already has the key <code>tname</code>,
6684 returns 0.
6685 Otherwise,
6686 creates a new table to be used as a metatable for userdata,
6687 adds to this new table the pair <code>__name = tname</code>,
6688 adds to the registry the pair <code>[tname] = new table</code>,
6689 and returns 1.
6690 (The entry <code>__name</code> is used by some error-reporting functions.)
6691
6692
6693 <p>
6694 In both cases pushes onto the stack the final value associated
6695 with <code>tname</code> in the registry.
6696
6697
6698
6699
6700
6701 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
6702 <span class="apii">[-0, +0, &ndash;]</span>
6703 <pre>lua_State *luaL_newstate (void);</pre>
6704
6705 <p>
6706 Creates a new Lua state.
6707 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
6708 allocator based on the standard&nbsp;C <code>realloc</code> function
6709 and then sets a panic function (see <a href="#4.6">&sect;4.6</a>) that prints
6710 an error message to the standard error output in case of fatal
6711 errors.
6712
6713
6714 <p>
6715 Returns the new state,
6716 or <code>NULL</code> if there is a memory allocation error.
6717
6718
6719
6720
6721
6722 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
6723 <span class="apii">[-0, +0, <em>e</em>]</span>
6724 <pre>void luaL_openlibs (lua_State *L);</pre>
6725
6726 <p>
6727 Opens all standard Lua libraries into the given state.
6728
6729
6730
6731
6732
6733 <hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
6734 <span class="apii">[-0, +0, <em>e</em>]</span>
6735 <pre>T luaL_opt (L, func, arg, dflt);</pre>
6736
6737 <p>
6738 This macro is defined as follows:
6739
6740 <pre>
6741      (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
6742 </pre><p>
6743 In words, if the argument <code>arg</code> is nil or absent,
6744 the macro results in the default <code>dflt</code>.
6745 Otherwise, it results in the result of calling <code>func</code>
6746 with the state <code>L</code> and the argument index <code>arg</code> as
6747 arguments.
6748 Note that it evaluates the expression <code>dflt</code> only if needed.
6749
6750
6751
6752
6753
6754 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
6755 <span class="apii">[-0, +0, <em>v</em>]</span>
6756 <pre>lua_Integer luaL_optinteger (lua_State *L,
6757                              int arg,
6758                              lua_Integer d);</pre>
6759
6760 <p>
6761 If the function argument <code>arg</code> is an integer
6762 (or convertible to an integer),
6763 returns this integer.
6764 If this argument is absent or is <b>nil</b>,
6765 returns <code>d</code>.
6766 Otherwise, raises an error.
6767
6768
6769
6770
6771
6772 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
6773 <span class="apii">[-0, +0, <em>v</em>]</span>
6774 <pre>const char *luaL_optlstring (lua_State *L,
6775                              int arg,
6776                              const char *d,
6777                              size_t *l);</pre>
6778
6779 <p>
6780 If the function argument <code>arg</code> is a string,
6781 returns this string.
6782 If this argument is absent or is <b>nil</b>,
6783 returns <code>d</code>.
6784 Otherwise, raises an error.
6785
6786
6787 <p>
6788 If <code>l</code> is not <code>NULL</code>,
6789 fills the position <code>*l</code> with the result's length.
6790 If the result is <code>NULL</code>
6791 (only possible when returning <code>d</code> and <code>d == NULL</code>),
6792 its length is considered zero.
6793
6794
6795 <p>
6796 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6797 so all conversions and caveats of that function apply here.
6798
6799
6800
6801
6802
6803 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
6804 <span class="apii">[-0, +0, <em>v</em>]</span>
6805 <pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
6806
6807 <p>
6808 If the function argument <code>arg</code> is a number,
6809 returns this number.
6810 If this argument is absent or is <b>nil</b>,
6811 returns <code>d</code>.
6812 Otherwise, raises an error.
6813
6814
6815
6816
6817
6818 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
6819 <span class="apii">[-0, +0, <em>v</em>]</span>
6820 <pre>const char *luaL_optstring (lua_State *L,
6821                             int arg,
6822                             const char *d);</pre>
6823
6824 <p>
6825 If the function argument <code>arg</code> is a string,
6826 returns this string.
6827 If this argument is absent or is <b>nil</b>,
6828 returns <code>d</code>.
6829 Otherwise, raises an error.
6830
6831
6832
6833
6834
6835 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
6836 <span class="apii">[-?, +?, <em>m</em>]</span>
6837 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
6838
6839 <p>
6840 Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
6841 with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
6842
6843
6844
6845
6846
6847 <hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
6848 <span class="apii">[-?, +?, <em>m</em>]</span>
6849 <pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
6850
6851 <p>
6852 Returns an address to a space of size <code>sz</code>
6853 where you can copy a string to be added to buffer <code>B</code>
6854 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6855 After copying the string into this space you must call
6856 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
6857 it to the buffer.
6858
6859
6860
6861
6862
6863 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
6864 <span class="apii">[-?, +1, <em>m</em>]</span>
6865 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
6866
6867 <p>
6868 Finishes the use of buffer <code>B</code> leaving the final string on
6869 the top of the stack.
6870
6871
6872
6873
6874
6875 <hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
6876 <span class="apii">[-?, +1, <em>m</em>]</span>
6877 <pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
6878
6879 <p>
6880 Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
6881
6882
6883
6884
6885
6886 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
6887 <span class="apii">[-1, +0, <em>m</em>]</span>
6888 <pre>int luaL_ref (lua_State *L, int t);</pre>
6889
6890 <p>
6891 Creates and returns a <em>reference</em>,
6892 in the table at index <code>t</code>,
6893 for the object at the top of the stack (and pops the object).
6894
6895
6896 <p>
6897 A reference is a unique integer key.
6898 As long as you do not manually add integer keys into table <code>t</code>,
6899 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
6900 You can retrieve an object referred by reference <code>r</code>
6901 by calling <code>lua_rawgeti(L, t, r)</code>.
6902 Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
6903
6904
6905 <p>
6906 If the object at the top of the stack is <b>nil</b>,
6907 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
6908 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
6909 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
6910
6911
6912
6913
6914
6915 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
6916 <pre>typedef struct luaL_Reg {
6917   const char *name;
6918   lua_CFunction func;
6919 } luaL_Reg;</pre>
6920
6921 <p>
6922 Type for arrays of functions to be registered by
6923 <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
6924 <code>name</code> is the function name and <code>func</code> is a pointer to
6925 the function.
6926 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
6927 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
6928
6929
6930
6931
6932
6933 <hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
6934 <span class="apii">[-0, +1, <em>e</em>]</span>
6935 <pre>void luaL_requiref (lua_State *L, const char *modname,
6936                     lua_CFunction openf, int glb);</pre>
6937
6938 <p>
6939 If <code>modname</code> is not already present in <a href="#pdf-package.loaded"><code>package.loaded</code></a>,
6940 calls function <code>openf</code> with string <code>modname</code> as an argument
6941 and sets the call result in <code>package.loaded[modname]</code>,
6942 as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
6943
6944
6945 <p>
6946 If <code>glb</code> is true,
6947 also stores the module into global <code>modname</code>.
6948
6949
6950 <p>
6951 Leaves a copy of the module on the stack.
6952
6953
6954
6955
6956
6957 <hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
6958 <span class="apii">[-nup, +0, <em>m</em>]</span>
6959 <pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
6960
6961 <p>
6962 Registers all functions in the array <code>l</code>
6963 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
6964 (below optional upvalues, see next).
6965
6966
6967 <p>
6968 When <code>nup</code> is not zero,
6969 all functions are created sharing <code>nup</code> upvalues,
6970 which must be previously pushed on the stack
6971 on top of the library table.
6972 These values are popped from the stack after the registration.
6973
6974
6975
6976
6977
6978 <hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
6979 <span class="apii">[-0, +0, &ndash;]</span>
6980 <pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
6981
6982 <p>
6983 Sets the metatable of the object at the top of the stack
6984 as the metatable associated with name <code>tname</code>
6985 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6986
6987
6988
6989
6990
6991 <hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
6992 <pre>typedef struct luaL_Stream {
6993   FILE *f;
6994   lua_CFunction closef;
6995 } luaL_Stream;</pre>
6996
6997 <p>
6998 The standard representation for file handles,
6999 which is used by the standard I/O library.
7000
7001
7002 <p>
7003 A file handle is implemented as a full userdata,
7004 with a metatable called <code>LUA_FILEHANDLE</code>
7005 (where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
7006 The metatable is created by the I/O library
7007 (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7008
7009
7010 <p>
7011 This userdata must start with the structure <code>luaL_Stream</code>;
7012 it can contain other data after this initial structure.
7013 Field <code>f</code> points to the corresponding C stream
7014 (or it can be <code>NULL</code> to indicate an incompletely created handle).
7015 Field <code>closef</code> points to a Lua function
7016 that will be called to close the stream
7017 when the handle is closed or collected;
7018 this function receives the file handle as its sole argument and
7019 must return either <b>true</b> (in case of success)
7020 or <b>nil</b> plus an error message (in case of error).
7021 Once Lua calls this field,
7022 it changes the field value to <code>NULL</code>
7023 to signal that the handle is closed.
7024
7025
7026
7027
7028
7029 <hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
7030 <span class="apii">[-0, +0, <em>m</em>]</span>
7031 <pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
7032
7033 <p>
7034 This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
7035 except that, when the test fails,
7036 it returns <code>NULL</code> instead of raising an error.
7037
7038
7039
7040
7041
7042 <hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
7043 <span class="apii">[-0, +1, <em>e</em>]</span>
7044 <pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
7045
7046 <p>
7047 Converts any Lua value at the given index to a C&nbsp;string
7048 in a reasonable format.
7049 The resulting string is pushed onto the stack and also
7050 returned by the function.
7051 If <code>len</code> is not <code>NULL</code>,
7052 the function also sets <code>*len</code> with the string length.
7053
7054
7055 <p>
7056 If the value has a metatable with a <code>__tostring</code> field,
7057 then <code>luaL_tolstring</code> calls the corresponding metamethod
7058 with the value as argument,
7059 and uses the result of the call as its result.
7060
7061
7062
7063
7064
7065 <hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
7066 <span class="apii">[-0, +1, <em>m</em>]</span>
7067 <pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
7068                      int level);</pre>
7069
7070 <p>
7071 Creates and pushes a traceback of the stack <code>L1</code>.
7072 If <code>msg</code> is not <code>NULL</code> it is appended
7073 at the beginning of the traceback.
7074 The <code>level</code> parameter tells at which level
7075 to start the traceback.
7076
7077
7078
7079
7080
7081 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
7082 <span class="apii">[-0, +0, &ndash;]</span>
7083 <pre>const char *luaL_typename (lua_State *L, int index);</pre>
7084
7085 <p>
7086 Returns the name of the type of the value at the given index.
7087
7088
7089
7090
7091
7092 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
7093 <span class="apii">[-0, +0, &ndash;]</span>
7094 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
7095
7096 <p>
7097 Releases reference <code>ref</code> from the table at index <code>t</code>
7098 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
7099 The entry is removed from the table,
7100 so that the referred object can be collected.
7101 The reference <code>ref</code> is also freed to be used again.
7102
7103
7104 <p>
7105 If <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>,
7106 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
7107
7108
7109
7110
7111
7112 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
7113 <span class="apii">[-0, +1, <em>m</em>]</span>
7114 <pre>void luaL_where (lua_State *L, int lvl);</pre>
7115
7116 <p>
7117 Pushes onto the stack a string identifying the current position
7118 of the control at level <code>lvl</code> in the call stack.
7119 Typically this string has the following format:
7120
7121 <pre>
7122      <em>chunkname</em>:<em>currentline</em>:
7123 </pre><p>
7124 Level&nbsp;0 is the running function,
7125 level&nbsp;1 is the function that called the running function,
7126 etc.
7127
7128
7129 <p>
7130 This function is used to build a prefix for error messages.
7131
7132
7133
7134
7135
7136
7137
7138 <h1>6 &ndash; <a name="6">Standard Libraries</a></h1>
7139
7140 <p>
7141 The standard Lua libraries provide useful functions
7142 that are implemented directly through the C&nbsp;API.
7143 Some of these functions provide essential services to the language
7144 (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7145 others provide access to "outside" services (e.g., I/O);
7146 and others could be implemented in Lua itself,
7147 but are quite useful or have critical performance requirements that
7148 deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7149
7150
7151 <p>
7152 All libraries are implemented through the official C&nbsp;API
7153 and are provided as separate C&nbsp;modules.
7154 Currently, Lua has the following standard libraries:
7155
7156 <ul>
7157
7158 <li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7159
7160 <li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7161
7162 <li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7163
7164 <li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7165
7166 <li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7167
7168 <li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7169
7170 <li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7171
7172 <li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7173
7174 <li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7175
7176 <li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7177
7178 </ul><p>
7179 Except for the basic and the package libraries,
7180 each library provides all its functions as fields of a global table
7181 or as methods of its objects.
7182
7183
7184 <p>
7185 To have access to these libraries,
7186 the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7187 which opens all standard libraries.
7188 Alternatively,
7189 the host program can open them individually by using
7190 <a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7191 <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7192 <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7193 <a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7194 <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7195 <a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF8 library),
7196 <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7197 <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7198 <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7199 <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7200 and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7201 These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7202
7203
7204
7205 <h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7206
7207 <p>
7208 The basic library provides core functions to Lua.
7209 If you do not include this library in your application,
7210 you should check carefully whether you need to provide
7211 implementations for some of its facilities.
7212
7213
7214 <p>
7215 <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7216
7217
7218 <p>
7219 Calls <a href="#pdf-error"><code>error</code></a> if
7220 the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7221 otherwise, returns all its arguments.
7222 In case of error,
7223 <code>message</code> is the error object;
7224 when absent, it defaults to "<code>assertion failed!</code>"
7225
7226
7227
7228
7229 <p>
7230 <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7231
7232
7233 <p>
7234 This function is a generic interface to the garbage collector.
7235 It performs different functions according to its first argument, <code>opt</code>:
7236
7237 <ul>
7238
7239 <li><b>"<code>collect</code>": </b>
7240 performs a full garbage-collection cycle.
7241 This is the default option.
7242 </li>
7243
7244 <li><b>"<code>stop</code>": </b>
7245 stops automatic execution of the garbage collector.
7246 The collector will run only when explicitly invoked,
7247 until a call to restart it.
7248 </li>
7249
7250 <li><b>"<code>restart</code>": </b>
7251 restarts automatic execution of the garbage collector.
7252 </li>
7253
7254 <li><b>"<code>count</code>": </b>
7255 returns the total memory in use by Lua in Kbytes.
7256 The value has a fractional part,
7257 so that it multiplied by 1024
7258 gives the exact number of bytes in use by Lua
7259 (except for overflows).
7260 </li>
7261
7262 <li><b>"<code>step</code>": </b>
7263 performs a garbage-collection step.
7264 The step "size" is controlled by <code>arg</code>.
7265 With a zero value,
7266 the collector will perform one basic (indivisible) step.
7267 For non-zero values,
7268 the collector will perform as if that amount of memory
7269 (in KBytes) had been allocated by Lua.
7270 Returns <b>true</b> if the step finished a collection cycle.
7271 </li>
7272
7273 <li><b>"<code>setpause</code>": </b>
7274 sets <code>arg</code> as the new value for the <em>pause</em> of
7275 the collector (see <a href="#2.5">&sect;2.5</a>).
7276 Returns the previous value for <em>pause</em>.
7277 </li>
7278
7279 <li><b>"<code>setstepmul</code>": </b>
7280 sets <code>arg</code> as the new value for the <em>step multiplier</em> of
7281 the collector (see <a href="#2.5">&sect;2.5</a>).
7282 Returns the previous value for <em>step</em>.
7283 </li>
7284
7285 <li><b>"<code>isrunning</code>": </b>
7286 returns a boolean that tells whether the collector is running
7287 (i.e., not stopped).
7288 </li>
7289
7290 </ul>
7291
7292
7293
7294 <p>
7295 <hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7296 Opens the named file and executes its contents as a Lua chunk.
7297 When called without arguments,
7298 <code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
7299 Returns all values returned by the chunk.
7300 In case of errors, <code>dofile</code> propagates the error
7301 to its caller (that is, <code>dofile</code> does not run in protected mode).
7302
7303
7304
7305
7306 <p>
7307 <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7308 Terminates the last protected function called
7309 and returns <code>message</code> as the error object.
7310 Function <code>error</code> never returns.
7311
7312
7313 <p>
7314 Usually, <code>error</code> adds some information about the error position
7315 at the beginning of the message, if the message is a string.
7316 The <code>level</code> argument specifies how to get the error position.
7317 With level&nbsp;1 (the default), the error position is where the
7318 <code>error</code> function was called.
7319 Level&nbsp;2 points the error to where the function
7320 that called <code>error</code> was called; and so on.
7321 Passing a level&nbsp;0 avoids the addition of error position information
7322 to the message.
7323
7324
7325
7326
7327 <p>
7328 <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7329 A global variable (not a function) that
7330 holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7331 Lua itself does not use this variable;
7332 changing its value does not affect any environment,
7333 nor vice versa.
7334
7335
7336
7337
7338 <p>
7339 <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7340
7341
7342 <p>
7343 If <code>object</code> does not have a metatable, returns <b>nil</b>.
7344 Otherwise,
7345 if the object's metatable has a <code>__metatable</code> field,
7346 returns the associated value.
7347 Otherwise, returns the metatable of the given object.
7348
7349
7350
7351
7352 <p>
7353 <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7354
7355
7356 <p>
7357 Returns three values (an iterator function, the table <code>t</code>, and 0)
7358 so that the construction
7359
7360 <pre>
7361      for i,v in ipairs(t) do <em>body</em> end
7362 </pre><p>
7363 will iterate over the key&ndash;value pairs
7364 (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7365 up to the first nil value.
7366
7367
7368
7369
7370 <p>
7371 <hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
7372
7373
7374 <p>
7375 Loads a chunk.
7376
7377
7378 <p>
7379 If <code>chunk</code> is a string, the chunk is this string.
7380 If <code>chunk</code> is a function,
7381 <code>load</code> calls it repeatedly to get the chunk pieces.
7382 Each call to <code>chunk</code> must return a string that concatenates
7383 with previous results.
7384 A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
7385
7386
7387 <p>
7388 If there are no syntactic errors,
7389 returns the compiled chunk as a function;
7390 otherwise, returns <b>nil</b> plus the error message.
7391
7392
7393 <p>
7394 If the resulting function has upvalues,
7395 the first upvalue is set to the value of <code>env</code>,
7396 if that parameter is given,
7397 or to the value of the global environment.
7398 Other upvalues are initialized with <b>nil</b>.
7399 (When you load a main chunk,
7400 the resulting function will always have exactly one upvalue,
7401 the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
7402 However,
7403 when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7404 the resulting function can have an arbitrary number of upvalues.)
7405 All upvalues are fresh, that is,
7406 they are not shared with any other function.
7407
7408
7409 <p>
7410 <code>chunkname</code> is used as the name of the chunk for error messages
7411 and debug information (see <a href="#4.9">&sect;4.9</a>).
7412 When absent,
7413 it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
7414 or to "<code>=(load)</code>" otherwise.
7415
7416
7417 <p>
7418 The string <code>mode</code> controls whether the chunk can be text or binary
7419 (that is, a precompiled chunk).
7420 It may be the string "<code>b</code>" (only binary chunks),
7421 "<code>t</code>" (only text chunks),
7422 or "<code>bt</code>" (both binary and text).
7423 The default is "<code>bt</code>".
7424
7425
7426 <p>
7427 Lua does not check the consistency of binary chunks.
7428 Maliciously crafted binary chunks can crash
7429 the interpreter.
7430
7431
7432
7433
7434 <p>
7435 <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
7436
7437
7438 <p>
7439 Similar to <a href="#pdf-load"><code>load</code></a>,
7440 but gets the chunk from file <code>filename</code>
7441 or from the standard input,
7442 if no file name is given.
7443
7444
7445
7446
7447 <p>
7448 <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
7449
7450
7451 <p>
7452 Allows a program to traverse all fields of a table.
7453 Its first argument is a table and its second argument
7454 is an index in this table.
7455 <code>next</code> returns the next index of the table
7456 and its associated value.
7457 When called with <b>nil</b> as its second argument,
7458 <code>next</code> returns an initial index
7459 and its associated value.
7460 When called with the last index,
7461 or with <b>nil</b> in an empty table,
7462 <code>next</code> returns <b>nil</b>.
7463 If the second argument is absent, then it is interpreted as <b>nil</b>.
7464 In particular,
7465 you can use <code>next(t)</code> to check whether a table is empty.
7466
7467
7468 <p>
7469 The order in which the indices are enumerated is not specified,
7470 <em>even for numeric indices</em>.
7471 (To traverse a table in numerical order,
7472 use a numerical <b>for</b>.)
7473
7474
7475 <p>
7476 The behavior of <code>next</code> is undefined if,
7477 during the traversal,
7478 you assign any value to a non-existent field in the table.
7479 You may however modify existing fields.
7480 In particular, you may clear existing fields.
7481
7482
7483
7484
7485 <p>
7486 <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
7487
7488
7489 <p>
7490 If <code>t</code> has a metamethod <code>__pairs</code>,
7491 calls it with <code>t</code> as argument and returns the first three
7492 results from the call.
7493
7494
7495 <p>
7496 Otherwise,
7497 returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
7498 so that the construction
7499
7500 <pre>
7501      for k,v in pairs(t) do <em>body</em> end
7502 </pre><p>
7503 will iterate over all key&ndash;value pairs of table <code>t</code>.
7504
7505
7506 <p>
7507 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
7508 the table during its traversal.
7509
7510
7511
7512
7513 <p>
7514 <hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
7515
7516
7517 <p>
7518 Calls function <code>f</code> with
7519 the given arguments in <em>protected mode</em>.
7520 This means that any error inside&nbsp;<code>f</code> is not propagated;
7521 instead, <code>pcall</code> catches the error
7522 and returns a status code.
7523 Its first result is the status code (a boolean),
7524 which is true if the call succeeds without errors.
7525 In such case, <code>pcall</code> also returns all results from the call,
7526 after this first result.
7527 In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
7528
7529
7530
7531
7532 <p>
7533 <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
7534 Receives any number of arguments
7535 and prints their values to <code>stdout</code>,
7536 using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string.
7537 <code>print</code> is not intended for formatted output,
7538 but only as a quick way to show a value,
7539 for instance for debugging.
7540 For complete control over the output,
7541 use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
7542
7543
7544
7545
7546 <p>
7547 <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
7548 Checks whether <code>v1</code> is equal to <code>v2</code>,
7549 without invoking the <code>__eq</code> metamethod.
7550 Returns a boolean.
7551
7552
7553
7554
7555 <p>
7556 <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
7557 Gets the real value of <code>table[index]</code>,
7558 without invoking the <code>__index</code> metamethod.
7559 <code>table</code> must be a table;
7560 <code>index</code> may be any value.
7561
7562
7563
7564
7565 <p>
7566 <hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
7567 Returns the length of the object <code>v</code>,
7568 which must be a table or a string,
7569 without invoking the <code>__len</code> metamethod.
7570 Returns an integer.
7571
7572
7573
7574
7575 <p>
7576 <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
7577 Sets the real value of <code>table[index]</code> to <code>value</code>,
7578 without invoking the <code>__newindex</code> metamethod.
7579 <code>table</code> must be a table,
7580 <code>index</code> any value different from <b>nil</b> and NaN,
7581 and <code>value</code> any Lua value.
7582
7583
7584 <p>
7585 This function returns <code>table</code>.
7586
7587
7588
7589
7590 <p>
7591 <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
7592
7593
7594 <p>
7595 If <code>index</code> is a number,
7596 returns all arguments after argument number <code>index</code>;
7597 a negative number indexes from the end (-1 is the last argument).
7598 Otherwise, <code>index</code> must be the string <code>"#"</code>,
7599 and <code>select</code> returns the total number of extra arguments it received.
7600
7601
7602
7603
7604 <p>
7605 <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
7606
7607
7608 <p>
7609 Sets the metatable for the given table.
7610 (To change the metatable of other types from Lua code,
7611 you must use the debug library (<a href="#6.10">&sect;6.10</a>).)
7612 If <code>metatable</code> is <b>nil</b>,
7613 removes the metatable of the given table.
7614 If the original metatable has a <code>__metatable</code> field,
7615 raises an error.
7616
7617
7618 <p>
7619 This function returns <code>table</code>.
7620
7621
7622
7623
7624 <p>
7625 <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
7626
7627
7628 <p>
7629 When called with no <code>base</code>,
7630 <code>tonumber</code> tries to convert its argument to a number.
7631 If the argument is already a number or
7632 a string convertible to a number,
7633 then <code>tonumber</code> returns this number;
7634 otherwise, it returns <b>nil</b>.
7635
7636
7637 <p>
7638 The conversion of strings can result in integers or floats,
7639 according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
7640 (The string may have leading and trailing spaces and a sign.)
7641
7642
7643 <p>
7644 When called with <code>base</code>,
7645 then <code>e</code> must be a string to be interpreted as
7646 an integer numeral in that base.
7647 The base may be any integer between 2 and 36, inclusive.
7648 In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
7649 represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
7650 with '<code>Z</code>' representing 35.
7651 If the string <code>e</code> is not a valid numeral in the given base,
7652 the function returns <b>nil</b>.
7653
7654
7655
7656
7657 <p>
7658 <hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
7659 Receives a value of any type and
7660 converts it to a string in a human-readable format.
7661 (For complete control of how numbers are converted,
7662 use <a href="#pdf-string.format"><code>string.format</code></a>.)
7663
7664
7665 <p>
7666 If the metatable of <code>v</code> has a <code>__tostring</code> field,
7667 then <code>tostring</code> calls the corresponding value
7668 with <code>v</code> as argument,
7669 and uses the result of the call as its result.
7670
7671
7672
7673
7674 <p>
7675 <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
7676 Returns the type of its only argument, coded as a string.
7677 The possible results of this function are
7678 "<code>nil</code>" (a string, not the value <b>nil</b>),
7679 "<code>number</code>",
7680 "<code>string</code>",
7681 "<code>boolean</code>",
7682 "<code>table</code>",
7683 "<code>function</code>",
7684 "<code>thread</code>",
7685 and "<code>userdata</code>".
7686
7687
7688
7689
7690 <p>
7691 <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
7692
7693
7694 <p>
7695 A global variable (not a function) that
7696 holds a string containing the running Lua version.
7697 The current value of this variable is "<code>Lua 5.3</code>".
7698
7699
7700
7701
7702 <p>
7703 <hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
7704
7705
7706 <p>
7707 This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
7708 except that it sets a new message handler <code>msgh</code>.
7709
7710
7711
7712
7713
7714
7715
7716 <h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
7717
7718 <p>
7719 This library comprises the operations to manipulate coroutines,
7720 which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
7721 See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
7722
7723
7724 <p>
7725 <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
7726
7727
7728 <p>
7729 Creates a new coroutine, with body <code>f</code>.
7730 <code>f</code> must be a function.
7731 Returns this new coroutine,
7732 an object with type <code>"thread"</code>.
7733
7734
7735
7736
7737 <p>
7738 <hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3>
7739
7740
7741 <p>
7742 Returns true when the running coroutine can yield.
7743
7744
7745 <p>
7746 A running coroutine is yieldable if it is not the main thread and
7747 it is not inside a non-yieldable C&nbsp;function.
7748
7749
7750
7751
7752 <p>
7753 <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
7754
7755
7756 <p>
7757 Starts or continues the execution of coroutine <code>co</code>.
7758 The first time you resume a coroutine,
7759 it starts running its body.
7760 The values <code>val1</code>, ... are passed
7761 as the arguments to the body function.
7762 If the coroutine has yielded,
7763 <code>resume</code> restarts it;
7764 the values <code>val1</code>, ... are passed
7765 as the results from the yield.
7766
7767
7768 <p>
7769 If the coroutine runs without any errors,
7770 <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
7771 (when the coroutine yields) or any values returned by the body function
7772 (when the coroutine terminates).
7773 If there is any error,
7774 <code>resume</code> returns <b>false</b> plus the error message.
7775
7776
7777
7778
7779 <p>
7780 <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
7781
7782
7783 <p>
7784 Returns the running coroutine plus a boolean,
7785 true when the running coroutine is the main one.
7786
7787
7788
7789
7790 <p>
7791 <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
7792
7793
7794 <p>
7795 Returns the status of coroutine <code>co</code>, as a string:
7796 <code>"running"</code>,
7797 if the coroutine is running (that is, it called <code>status</code>);
7798 <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
7799 or if it has not started running yet;
7800 <code>"normal"</code> if the coroutine is active but not running
7801 (that is, it has resumed another coroutine);
7802 and <code>"dead"</code> if the coroutine has finished its body function,
7803 or if it has stopped with an error.
7804
7805
7806
7807
7808 <p>
7809 <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
7810
7811
7812 <p>
7813 Creates a new coroutine, with body <code>f</code>.
7814 <code>f</code> must be a function.
7815 Returns a function that resumes the coroutine each time it is called.
7816 Any arguments passed to the function behave as the
7817 extra arguments to <code>resume</code>.
7818 Returns the same values returned by <code>resume</code>,
7819 except the first boolean.
7820 In case of error, propagates the error.
7821
7822
7823
7824
7825 <p>
7826 <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
7827
7828
7829 <p>
7830 Suspends the execution of the calling coroutine.
7831 Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
7832
7833
7834
7835
7836
7837
7838
7839 <h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
7840
7841 <p>
7842 The package library provides basic
7843 facilities for loading modules in Lua.
7844 It exports one function directly in the global environment:
7845 <a href="#pdf-require"><code>require</code></a>.
7846 Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
7847
7848
7849 <p>
7850 <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
7851
7852
7853 <p>
7854 Loads the given module.
7855 The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
7856 to determine whether <code>modname</code> is already loaded.
7857 If it is, then <code>require</code> returns the value stored
7858 at <code>package.loaded[modname]</code>.
7859 Otherwise, it tries to find a <em>loader</em> for the module.
7860
7861
7862 <p>
7863 To find a loader,
7864 <code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence.
7865 By changing this sequence,
7866 we can change how <code>require</code> looks for a module.
7867 The following explanation is based on the default configuration
7868 for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
7869
7870
7871 <p>
7872 First <code>require</code> queries <code>package.preload[modname]</code>.
7873 If it has a value,
7874 this value (which must be a function) is the loader.
7875 Otherwise <code>require</code> searches for a Lua loader using the
7876 path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
7877 If that also fails, it searches for a C&nbsp;loader using the
7878 path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7879 If that also fails,
7880 it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
7881
7882
7883 <p>
7884 Once a loader is found,
7885 <code>require</code> calls the loader with two arguments:
7886 <code>modname</code> and an extra value dependent on how it got the loader.
7887 (If the loader came from a file,
7888 this extra value is the file name.)
7889 If the loader returns any non-nil value,
7890 <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
7891 If the loader does not return a non-nil value and
7892 has not assigned any value to <code>package.loaded[modname]</code>,
7893 then <code>require</code> assigns <b>true</b> to this entry.
7894 In any case, <code>require</code> returns the
7895 final value of <code>package.loaded[modname]</code>.
7896
7897
7898 <p>
7899 If there is any error loading or running the module,
7900 or if it cannot find any loader for the module,
7901 then <code>require</code> raises an error.
7902
7903
7904
7905
7906 <p>
7907 <hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
7908
7909
7910 <p>
7911 A string describing some compile-time configurations for packages.
7912 This string is a sequence of lines:
7913
7914 <ul>
7915
7916 <li>The first line is the directory separator string.
7917 Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
7918
7919 <li>The second line is the character that separates templates in a path.
7920 Default is '<code>;</code>'.</li>
7921
7922 <li>The third line is the string that marks the
7923 substitution points in a template.
7924 Default is '<code>?</code>'.</li>
7925
7926 <li>The fourth line is a string that, in a path in Windows,
7927 is replaced by the executable's directory.
7928 Default is '<code>!</code>'.</li>
7929
7930 <li>The fifth line is a mark to ignore all text after it
7931 when building the <code>luaopen_</code> function name.
7932 Default is '<code>-</code>'.</li>
7933
7934 </ul>
7935
7936
7937
7938 <p>
7939 <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
7940
7941
7942 <p>
7943 The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
7944
7945
7946 <p>
7947 Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
7948 it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7949 using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a>,
7950 or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
7951 or a default path defined in <code>luaconf.h</code>.
7952
7953
7954
7955
7956 <p>
7957 <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
7958
7959
7960 <p>
7961 A table used by <a href="#pdf-require"><code>require</code></a> to control which
7962 modules are already loaded.
7963 When you require a module <code>modname</code> and
7964 <code>package.loaded[modname]</code> is not false,
7965 <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
7966
7967
7968 <p>
7969 This variable is only a reference to the real table;
7970 assignments to this variable do not change the
7971 table used by <a href="#pdf-require"><code>require</code></a>.
7972
7973
7974
7975
7976 <p>
7977 <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
7978
7979
7980 <p>
7981 Dynamically links the host program with the C&nbsp;library <code>libname</code>.
7982
7983
7984 <p>
7985 If <code>funcname</code> is "<code>*</code>",
7986 then it only links with the library,
7987 making the symbols exported by the library
7988 available to other dynamically linked libraries.
7989 Otherwise,
7990 it looks for a function <code>funcname</code> inside the library
7991 and returns this function as a C&nbsp;function.
7992 So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
7993 (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
7994
7995
7996 <p>
7997 This is a low-level function.
7998 It completely bypasses the package and module system.
7999 Unlike <a href="#pdf-require"><code>require</code></a>,
8000 it does not perform any path searching and
8001 does not automatically adds extensions.
8002 <code>libname</code> must be the complete file name of the C&nbsp;library,
8003 including if necessary a path and an extension.
8004 <code>funcname</code> must be the exact name exported by the C&nbsp;library
8005 (which may depend on the C&nbsp;compiler and linker used).
8006
8007
8008 <p>
8009 This function is not supported by Standard&nbsp;C.
8010 As such, it is only available on some platforms
8011 (Windows, Linux, Mac OS X, Solaris, BSD,
8012 plus other Unix systems that support the <code>dlfcn</code> standard).
8013
8014
8015
8016
8017 <p>
8018 <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
8019
8020
8021 <p>
8022 The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
8023
8024
8025 <p>
8026 At start-up, Lua initializes this variable with
8027 the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or
8028 the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
8029 with a default path defined in <code>luaconf.h</code>,
8030 if those environment variables are not defined.
8031 Any "<code>;;</code>" in the value of the environment variable
8032 is replaced by the default path.
8033
8034
8035
8036
8037 <p>
8038 <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
8039
8040
8041 <p>
8042 A table to store loaders for specific modules
8043 (see <a href="#pdf-require"><code>require</code></a>).
8044
8045
8046 <p>
8047 This variable is only a reference to the real table;
8048 assignments to this variable do not change the
8049 table used by <a href="#pdf-require"><code>require</code></a>.
8050
8051
8052
8053
8054 <p>
8055 <hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
8056
8057
8058 <p>
8059 A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
8060
8061
8062 <p>
8063 Each entry in this table is a <em>searcher function</em>.
8064 When looking for a module,
8065 <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
8066 with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
8067 sole parameter.
8068 The function can return another function (the module <em>loader</em>)
8069 plus an extra value that will be passed to that loader,
8070 or a string explaining why it did not find that module
8071 (or <b>nil</b> if it has nothing to say).
8072
8073
8074 <p>
8075 Lua initializes this table with four searcher functions.
8076
8077
8078 <p>
8079 The first searcher simply looks for a loader in the
8080 <a href="#pdf-package.preload"><code>package.preload</code></a> table.
8081
8082
8083 <p>
8084 The second searcher looks for a loader as a Lua library,
8085 using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
8086 The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8087
8088
8089 <p>
8090 The third searcher looks for a loader as a C&nbsp;library,
8091 using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8092 Again,
8093 the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8094 For instance,
8095 if the C&nbsp;path is the string
8096
8097 <pre>
8098      "./?.so;./?.dll;/usr/local/?/init.so"
8099 </pre><p>
8100 the searcher for module <code>foo</code>
8101 will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
8102 and <code>/usr/local/foo/init.so</code>, in that order.
8103 Once it finds a C&nbsp;library,
8104 this searcher first uses a dynamic link facility to link the
8105 application with the library.
8106 Then it tries to find a C&nbsp;function inside the library to
8107 be used as the loader.
8108 The name of this C&nbsp;function is the string "<code>luaopen_</code>"
8109 concatenated with a copy of the module name where each dot
8110 is replaced by an underscore.
8111 Moreover, if the module name has a hyphen,
8112 its suffix after (and including) the first hyphen is removed.
8113 For instance, if the module name is <code>a.b.c-v2.1</code>,
8114 the function name will be <code>luaopen_a_b_c</code>.
8115
8116
8117 <p>
8118 The fourth searcher tries an <em>all-in-one loader</em>.
8119 It searches the C&nbsp;path for a library for
8120 the root name of the given module.
8121 For instance, when requiring <code>a.b.c</code>,
8122 it will search for a C&nbsp;library for <code>a</code>.
8123 If found, it looks into it for an open function for
8124 the submodule;
8125 in our example, that would be <code>luaopen_a_b_c</code>.
8126 With this facility, a package can pack several C&nbsp;submodules
8127 into one single library,
8128 with each submodule keeping its original open function.
8129
8130
8131 <p>
8132 All searchers except the first one (preload) return as the extra value
8133 the file name where the module was found,
8134 as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8135 The first searcher returns no extra value.
8136
8137
8138
8139
8140 <p>
8141 <hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8142
8143
8144 <p>
8145 Searches for the given <code>name</code> in the given <code>path</code>.
8146
8147
8148 <p>
8149 A path is a string containing a sequence of
8150 <em>templates</em> separated by semicolons.
8151 For each template,
8152 the function replaces each interrogation mark (if any)
8153 in the template with a copy of <code>name</code>
8154 wherein all occurrences of <code>sep</code>
8155 (a dot, by default)
8156 were replaced by <code>rep</code>
8157 (the system's directory separator, by default),
8158 and then tries to open the resulting file name.
8159
8160
8161 <p>
8162 For instance, if the path is the string
8163
8164 <pre>
8165      "./?.lua;./?.lc;/usr/local/?/init.lua"
8166 </pre><p>
8167 the search for the name <code>foo.a</code>
8168 will try to open the files
8169 <code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8170 <code>/usr/local/foo/a/init.lua</code>, in that order.
8171
8172
8173 <p>
8174 Returns the resulting name of the first file that it can
8175 open in read mode (after closing the file),
8176 or <b>nil</b> plus an error message if none succeeds.
8177 (This error message lists all file names it tried to open.)
8178
8179
8180
8181
8182
8183
8184
8185 <h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8186
8187 <p>
8188 This library provides generic functions for string manipulation,
8189 such as finding and extracting substrings, and pattern matching.
8190 When indexing a string in Lua, the first character is at position&nbsp;1
8191 (not at&nbsp;0, as in C).
8192 Indices are allowed to be negative and are interpreted as indexing backwards,
8193 from the end of the string.
8194 Thus, the last character is at position -1, and so on.
8195
8196
8197 <p>
8198 The string library provides all its functions inside the table
8199 <a name="pdf-string"><code>string</code></a>.
8200 It also sets a metatable for strings
8201 where the <code>__index</code> field points to the <code>string</code> table.
8202 Therefore, you can use the string functions in object-oriented style.
8203 For instance, <code>string.byte(s,i)</code>
8204 can be written as <code>s:byte(i)</code>.
8205
8206
8207 <p>
8208 The string library assumes one-byte character encodings.
8209
8210
8211 <p>
8212 <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8213 Returns the internal numeric codes of the characters <code>s[i]</code>,
8214 <code>s[i+1]</code>, ..., <code>s[j]</code>.
8215 The default value for <code>i</code> is&nbsp;1;
8216 the default value for <code>j</code> is&nbsp;<code>i</code>.
8217 These indices are corrected
8218 following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8219
8220
8221 <p>
8222 Numeric codes are not necessarily portable across platforms.
8223
8224
8225
8226
8227 <p>
8228 <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8229 Receives zero or more integers.
8230 Returns a string with length equal to the number of arguments,
8231 in which each character has the internal numeric code equal
8232 to its corresponding argument.
8233
8234
8235 <p>
8236 Numeric codes are not necessarily portable across platforms.
8237
8238
8239
8240
8241 <p>
8242 <hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8243
8244
8245 <p>
8246 Returns a string containing a binary representation
8247 (a <em>binary chunk</em>)
8248 of the given function,
8249 so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8250 a copy of the function (but with new upvalues).
8251 If <code>strip</code> is a true value,
8252 the binary representation may not include all debug information
8253 about the function,
8254 to save space.
8255
8256
8257 <p>
8258 Functions with upvalues have only their number of upvalues saved.
8259 When (re)loaded,
8260 those upvalues receive fresh instances containing <b>nil</b>.
8261 (You can use the debug library to serialize
8262 and reload the upvalues of a function
8263 in a way adequate to your needs.)
8264
8265
8266
8267
8268 <p>
8269 <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
8270
8271
8272 <p>
8273 Looks for the first match of
8274 <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
8275 If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
8276 where this occurrence starts and ends;
8277 otherwise, it returns <b>nil</b>.
8278 A third, optional numeric argument <code>init</code> specifies
8279 where to start the search;
8280 its default value is&nbsp;1 and can be negative.
8281 A value of <b>true</b> as a fourth, optional argument <code>plain</code>
8282 turns off the pattern matching facilities,
8283 so the function does a plain "find substring" operation,
8284 with no characters in <code>pattern</code> being considered magic.
8285 Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
8286
8287
8288 <p>
8289 If the pattern has captures,
8290 then in a successful match
8291 the captured values are also returned,
8292 after the two indices.
8293
8294
8295
8296
8297 <p>
8298 <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
8299
8300
8301 <p>
8302 Returns a formatted version of its variable number of arguments
8303 following the description given in its first argument (which must be a string).
8304 The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
8305 The only differences are that the options/modifiers
8306 <code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
8307 and <code>p</code> are not supported
8308 and that there is an extra option, <code>q</code>.
8309
8310
8311 <p>
8312 The <code>q</code> option formats a string between double quotes,
8313 using escape sequences when necessary to ensure that
8314 it can safely be read back by the Lua interpreter.
8315 For instance, the call
8316
8317 <pre>
8318      string.format('%q', 'a string with "quotes" and \n new line')
8319 </pre><p>
8320 may produce the string:
8321
8322 <pre>
8323      "a string with \"quotes\" and \
8324       new line"
8325 </pre>
8326
8327 <p>
8328 Options
8329 <code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
8330 <code>G</code>, and <code>g</code> all expect a number as argument.
8331 Options <code>c</code>, <code>d</code>,
8332 <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
8333 expect an integer.
8334 When Lua is compiled with a C89 compiler,
8335 options <code>A</code> and <code>a</code> (hexadecimal floats)
8336 do not support any modifier (flags, width, length).
8337
8338
8339 <p>
8340 Option <code>s</code> expects a string;
8341 if its argument is not a string,
8342 it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8343 If the option has any modifier (flags, width, length),
8344 the string argument should not contain embedded zeros.
8345
8346
8347
8348
8349 <p>
8350 <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
8351 Returns an iterator function that,
8352 each time it is called,
8353 returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
8354 over the string <code>s</code>.
8355 If <code>pattern</code> specifies no captures,
8356 then the whole match is produced in each call.
8357
8358
8359 <p>
8360 As an example, the following loop
8361 will iterate over all the words from string <code>s</code>,
8362 printing one per line:
8363
8364 <pre>
8365      s = "hello world from Lua"
8366      for w in string.gmatch(s, "%a+") do
8367        print(w)
8368      end
8369 </pre><p>
8370 The next example collects all pairs <code>key=value</code> from the
8371 given string into a table:
8372
8373 <pre>
8374      t = {}
8375      s = "from=world, to=Lua"
8376      for k, v in string.gmatch(s, "(%w+)=(%w+)") do
8377        t[k] = v
8378      end
8379 </pre>
8380
8381 <p>
8382 For this function, a caret '<code>^</code>' at the start of a pattern does not
8383 work as an anchor, as this would prevent the iteration.
8384
8385
8386
8387
8388 <p>
8389 <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
8390 Returns a copy of <code>s</code>
8391 in which all (or the first <code>n</code>, if given)
8392 occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
8393 replaced by a replacement string specified by <code>repl</code>,
8394 which can be a string, a table, or a function.
8395 <code>gsub</code> also returns, as its second value,
8396 the total number of matches that occurred.
8397 The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
8398
8399
8400 <p>
8401 If <code>repl</code> is a string, then its value is used for replacement.
8402 The character&nbsp;<code>%</code> works as an escape character:
8403 any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
8404 with <em>d</em> between 1 and 9,
8405 stands for the value of the <em>d</em>-th captured substring.
8406 The sequence <code>%0</code> stands for the whole match.
8407 The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
8408
8409
8410 <p>
8411 If <code>repl</code> is a table, then the table is queried for every match,
8412 using the first capture as the key.
8413
8414
8415 <p>
8416 If <code>repl</code> is a function, then this function is called every time a
8417 match occurs, with all captured substrings passed as arguments,
8418 in order.
8419
8420
8421 <p>
8422 In any case,
8423 if the pattern specifies no captures,
8424 then it behaves as if the whole pattern was inside a capture.
8425
8426
8427 <p>
8428 If the value returned by the table query or by the function call
8429 is a string or a number,
8430 then it is used as the replacement string;
8431 otherwise, if it is <b>false</b> or <b>nil</b>,
8432 then there is no replacement
8433 (that is, the original match is kept in the string).
8434
8435
8436 <p>
8437 Here are some examples:
8438
8439 <pre>
8440      x = string.gsub("hello world", "(%w+)", "%1 %1")
8441      --&gt; x="hello hello world world"
8442      
8443      x = string.gsub("hello world", "%w+", "%0 %0", 1)
8444      --&gt; x="hello hello world"
8445      
8446      x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
8447      --&gt; x="world hello Lua from"
8448      
8449      x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
8450      --&gt; x="home = /home/roberto, user = roberto"
8451      
8452      x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
8453            return load(s)()
8454          end)
8455      --&gt; x="4+5 = 9"
8456      
8457      local t = {name="lua", version="5.3"}
8458      x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8459      --&gt; x="lua-5.3.tar.gz"
8460 </pre>
8461
8462
8463
8464 <p>
8465 <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
8466 Receives a string and returns its length.
8467 The empty string <code>""</code> has length 0.
8468 Embedded zeros are counted,
8469 so <code>"a\000bc\000"</code> has length 5.
8470
8471
8472
8473
8474 <p>
8475 <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
8476 Receives a string and returns a copy of this string with all
8477 uppercase letters changed to lowercase.
8478 All other characters are left unchanged.
8479 The definition of what an uppercase letter is depends on the current locale.
8480
8481
8482
8483
8484 <p>
8485 <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
8486 Looks for the first <em>match</em> of
8487 <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
8488 If it finds one, then <code>match</code> returns
8489 the captures from the pattern;
8490 otherwise it returns <b>nil</b>.
8491 If <code>pattern</code> specifies no captures,
8492 then the whole match is returned.
8493 A third, optional numeric argument <code>init</code> specifies
8494 where to start the search;
8495 its default value is&nbsp;1 and can be negative.
8496
8497
8498
8499
8500 <p>
8501 <hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
8502
8503
8504 <p>
8505 Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
8506 packed (that is, serialized in binary form)
8507 according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
8508
8509
8510
8511
8512 <p>
8513 <hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
8514
8515
8516 <p>
8517 Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
8518 with the given format.
8519 The format string cannot have the variable-length options
8520 '<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
8521
8522
8523
8524
8525 <p>
8526 <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
8527 Returns a string that is the concatenation of <code>n</code> copies of
8528 the string <code>s</code> separated by the string <code>sep</code>.
8529 The default value for <code>sep</code> is the empty string
8530 (that is, no separator).
8531 Returns the empty string if <code>n</code> is not positive.
8532
8533
8534 <p>
8535 (Note that it is very easy to exhaust the memory of your machine
8536 with a single call to this function.)
8537
8538
8539
8540
8541 <p>
8542 <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
8543 Returns a string that is the string <code>s</code> reversed.
8544
8545
8546
8547
8548 <p>
8549 <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
8550 Returns the substring of <code>s</code> that
8551 starts at <code>i</code>  and continues until <code>j</code>;
8552 <code>i</code> and <code>j</code> can be negative.
8553 If <code>j</code> is absent, then it is assumed to be equal to -1
8554 (which is the same as the string length).
8555 In particular,
8556 the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
8557 with length <code>j</code>,
8558 and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
8559 returns a suffix of <code>s</code>
8560 with length <code>i</code>.
8561
8562
8563 <p>
8564 If, after the translation of negative indices,
8565 <code>i</code> is less than 1,
8566 it is corrected to 1.
8567 If <code>j</code> is greater than the string length,
8568 it is corrected to that length.
8569 If, after these corrections,
8570 <code>i</code> is greater than <code>j</code>,
8571 the function returns the empty string.
8572
8573
8574
8575
8576 <p>
8577 <hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
8578
8579
8580 <p>
8581 Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
8582 according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
8583 An optional <code>pos</code> marks where
8584 to start reading in <code>s</code> (default is 1).
8585 After the read values,
8586 this function also returns the index of the first unread byte in <code>s</code>.
8587
8588
8589
8590
8591 <p>
8592 <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
8593 Receives a string and returns a copy of this string with all
8594 lowercase letters changed to uppercase.
8595 All other characters are left unchanged.
8596 The definition of what a lowercase letter is depends on the current locale.
8597
8598
8599
8600
8601
8602 <h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
8603
8604 <p>
8605 Patterns in Lua are described by regular strings,
8606 which are interpreted as patterns by the pattern-matching functions
8607 <a href="#pdf-string.find"><code>string.find</code></a>,
8608 <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
8609 <a href="#pdf-string.gsub"><code>string.gsub</code></a>,
8610 and <a href="#pdf-string.match"><code>string.match</code></a>.
8611 This section describes the syntax and the meaning
8612 (that is, what they match) of these strings.
8613
8614
8615
8616 <h4>Character Class:</h4><p>
8617 A <em>character class</em> is used to represent a set of characters.
8618 The following combinations are allowed in describing a character class:
8619
8620 <ul>
8621
8622 <li><b><em>x</em>: </b>
8623 (where <em>x</em> is not one of the <em>magic characters</em>
8624 <code>^$()%.[]*+-?</code>)
8625 represents the character <em>x</em> itself.
8626 </li>
8627
8628 <li><b><code>.</code>: </b> (a dot) represents all characters.</li>
8629
8630 <li><b><code>%a</code>: </b> represents all letters.</li>
8631
8632 <li><b><code>%c</code>: </b> represents all control characters.</li>
8633
8634 <li><b><code>%d</code>: </b> represents all digits.</li>
8635
8636 <li><b><code>%g</code>: </b> represents all printable characters except space.</li>
8637
8638 <li><b><code>%l</code>: </b> represents all lowercase letters.</li>
8639
8640 <li><b><code>%p</code>: </b> represents all punctuation characters.</li>
8641
8642 <li><b><code>%s</code>: </b> represents all space characters.</li>
8643
8644 <li><b><code>%u</code>: </b> represents all uppercase letters.</li>
8645
8646 <li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
8647
8648 <li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
8649
8650 <li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
8651 represents the character <em>x</em>.
8652 This is the standard way to escape the magic characters.
8653 Any non-alphanumeric character
8654 (including all punctuation characters, even the non-magical)
8655 can be preceded by a '<code>%</code>'
8656 when used to represent itself in a pattern.
8657 </li>
8658
8659 <li><b><code>[<em>set</em>]</code>: </b>
8660 represents the class which is the union of all
8661 characters in <em>set</em>.
8662 A range of characters can be specified by
8663 separating the end characters of the range,
8664 in ascending order, with a '<code>-</code>'.
8665 All classes <code>%</code><em>x</em> described above can also be used as
8666 components in <em>set</em>.
8667 All other characters in <em>set</em> represent themselves.
8668 For example, <code>[%w_]</code> (or <code>[_%w]</code>)
8669 represents all alphanumeric characters plus the underscore,
8670 <code>[0-7]</code> represents the octal digits,
8671 and <code>[0-7%l%-]</code> represents the octal digits plus
8672 the lowercase letters plus the '<code>-</code>' character.
8673
8674
8675 <p>
8676 You can put a closing square bracket in a set
8677 by positioning it as the first character in the set.
8678 You can put a hyphen in a set
8679 by positioning it as the first or the last character in the set.
8680 (You can also use an escape for both cases.)
8681
8682
8683 <p>
8684 The interaction between ranges and classes is not defined.
8685 Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
8686 have no meaning.
8687 </li>
8688
8689 <li><b><code>[^<em>set</em>]</code>: </b>
8690 represents the complement of <em>set</em>,
8691 where <em>set</em> is interpreted as above.
8692 </li>
8693
8694 </ul><p>
8695 For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
8696 the corresponding uppercase letter represents the complement of the class.
8697 For instance, <code>%S</code> represents all non-space characters.
8698
8699
8700 <p>
8701 The definitions of letter, space, and other character groups
8702 depend on the current locale.
8703 In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
8704
8705
8706
8707
8708
8709 <h4>Pattern Item:</h4><p>
8710 A <em>pattern item</em> can be
8711
8712 <ul>
8713
8714 <li>
8715 a single character class,
8716 which matches any single character in the class;
8717 </li>
8718
8719 <li>
8720 a single character class followed by '<code>*</code>',
8721 which matches zero or more repetitions of characters in the class.
8722 These repetition items will always match the longest possible sequence;
8723 </li>
8724
8725 <li>
8726 a single character class followed by '<code>+</code>',
8727 which matches one or more repetitions of characters in the class.
8728 These repetition items will always match the longest possible sequence;
8729 </li>
8730
8731 <li>
8732 a single character class followed by '<code>-</code>',
8733 which also matches zero or more repetitions of characters in the class.
8734 Unlike '<code>*</code>',
8735 these repetition items will always match the shortest possible sequence;
8736 </li>
8737
8738 <li>
8739 a single character class followed by '<code>?</code>',
8740 which matches zero or one occurrence of a character in the class.
8741 It always matches one occurrence if possible;
8742 </li>
8743
8744 <li>
8745 <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
8746 such item matches a substring equal to the <em>n</em>-th captured string
8747 (see below);
8748 </li>
8749
8750 <li>
8751 <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
8752 such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
8753 and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
8754 This means that, if one reads the string from left to right,
8755 counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
8756 the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
8757 For instance, the item <code>%b()</code> matches expressions with
8758 balanced parentheses.
8759 </li>
8760
8761 <li>
8762 <code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
8763 such item matches an empty string at any position such that
8764 the next character belongs to <em>set</em>
8765 and the previous character does not belong to <em>set</em>.
8766 The set <em>set</em> is interpreted as previously described.
8767 The beginning and the end of the subject are handled as if
8768 they were the character '<code>\0</code>'.
8769 </li>
8770
8771 </ul>
8772
8773
8774
8775
8776 <h4>Pattern:</h4><p>
8777 A <em>pattern</em> is a sequence of pattern items.
8778 A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
8779 beginning of the subject string.
8780 A '<code>$</code>' at the end of a pattern anchors the match at the
8781 end of the subject string.
8782 At other positions,
8783 '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
8784
8785
8786
8787
8788
8789 <h4>Captures:</h4><p>
8790 A pattern can contain sub-patterns enclosed in parentheses;
8791 they describe <em>captures</em>.
8792 When a match succeeds, the substrings of the subject string
8793 that match captures are stored (<em>captured</em>) for future use.
8794 Captures are numbered according to their left parentheses.
8795 For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
8796 the part of the string matching <code>"a*(.)%w(%s*)"</code> is
8797 stored as the first capture (and therefore has number&nbsp;1);
8798 the character matching "<code>.</code>" is captured with number&nbsp;2,
8799 and the part matching "<code>%s*</code>" has number&nbsp;3.
8800
8801
8802 <p>
8803 As a special case, the empty capture <code>()</code> captures
8804 the current string position (a number).
8805 For instance, if we apply the pattern <code>"()aa()"</code> on the
8806 string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
8807
8808
8809
8810
8811
8812
8813
8814 <h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
8815
8816 <p>
8817 The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
8818 <a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
8819 is a format string,
8820 which describes the layout of the structure being created or read.
8821
8822
8823 <p>
8824 A format string is a sequence of conversion options.
8825 The conversion options are as follows:
8826
8827 <ul>
8828 <li><b><code>&lt;</code>: </b>sets little endian</li>
8829 <li><b><code>&gt;</code>: </b>sets big endian</li>
8830 <li><b><code>=</code>: </b>sets native endian</li>
8831 <li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
8832 (default is native alignment)</li>
8833 <li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
8834 <li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
8835 <li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
8836 <li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
8837 <li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
8838 <li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
8839 <li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
8840 <li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
8841 <li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
8842 <li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
8843 (default is native size)</li>
8844 <li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
8845 (default is native size)</li>
8846 <li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
8847 <li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
8848 <li><b><code>n</code>: </b>a <code>lua_Number</code></li>
8849 <li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
8850 <li><b><code>z</code>: </b>a zero-terminated string</li>
8851 <li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
8852 coded as an unsigned integer with <code>n</code> bytes
8853 (default is a <code>size_t</code>)</li>
8854 <li><b><code>x</code>: </b>one byte of padding</li>
8855 <li><b><code>X<em>op</em></code>: </b>an empty item that aligns
8856 according to option <code>op</code>
8857 (which is otherwise ignored)</li>
8858 <li><b>'<code> </code>': </b>(empty space) ignored</li>
8859 </ul><p>
8860 (A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
8861 Except for padding, spaces, and configurations
8862 (options "<code>xX &lt;=&gt;!</code>"),
8863 each option corresponds to an argument (in <a href="#pdf-string.pack"><code>string.pack</code></a>)
8864 or a result (in <a href="#pdf-string.unpack"><code>string.unpack</code></a>).
8865
8866
8867 <p>
8868 For 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>",
8869 <code>n</code> can be any integer between 1 and 16.
8870 All integral options check overflows;
8871 <a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
8872 <a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
8873
8874
8875 <p>
8876 Any format string starts as if prefixed by "<code>!1=</code>",
8877 that is,
8878 with maximum alignment of 1 (no alignment)
8879 and native endianness.
8880
8881
8882 <p>
8883 Alignment works as follows:
8884 For each option,
8885 the format gets extra padding until the data starts
8886 at an offset that is a multiple of the minimum between the
8887 option size and the maximum alignment;
8888 this minimum must be a power of 2.
8889 Options "<code>c</code>" and "<code>z</code>" are not aligned;
8890 option "<code>s</code>" follows the alignment of its starting integer.
8891
8892
8893 <p>
8894 All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
8895 (and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>).
8896
8897
8898
8899
8900
8901
8902
8903 <h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
8904
8905 <p>
8906 This library provides basic support for UTF-8 encoding.
8907 It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
8908 This library does not provide any support for Unicode other
8909 than the handling of the encoding.
8910 Any operation that needs the meaning of a character,
8911 such as character classification, is outside its scope.
8912
8913
8914 <p>
8915 Unless stated otherwise,
8916 all functions that expect a byte position as a parameter
8917 assume that the given position is either the start of a byte sequence
8918 or one plus the length of the subject string.
8919 As in the string library,
8920 negative indices count from the end of the string.
8921
8922
8923 <p>
8924 <hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
8925 Receives zero or more integers,
8926 converts each one to its corresponding UTF-8 byte sequence
8927 and returns a string with the concatenation of all these sequences.
8928
8929
8930
8931
8932 <p>
8933 <hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
8934 The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>"
8935 (see <a href="#6.4.1">&sect;6.4.1</a>),
8936 which matches exactly one UTF-8 byte sequence,
8937 assuming that the subject is a valid UTF-8 string.
8938
8939
8940
8941
8942 <p>
8943 <hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3>
8944
8945
8946 <p>
8947 Returns values so that the construction
8948
8949 <pre>
8950      for p, c in utf8.codes(s) do <em>body</em> end
8951 </pre><p>
8952 will iterate over all characters in string <code>s</code>,
8953 with <code>p</code> being the position (in bytes) and <code>c</code> the code point
8954 of each character.
8955 It raises an error if it meets any invalid byte sequence.
8956
8957
8958
8959
8960 <p>
8961 <hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3>
8962 Returns the codepoints (as integers) from all characters in <code>s</code>
8963 that start between byte position <code>i</code> and <code>j</code> (both included).
8964 The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
8965 It raises an error if it meets any invalid byte sequence.
8966
8967
8968
8969
8970 <p>
8971 <hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3>
8972 Returns the number of UTF-8 characters in string <code>s</code>
8973 that start between positions <code>i</code> and <code>j</code> (both inclusive).
8974 The default for <code>i</code> is 1 and for <code>j</code> is -1.
8975 If it finds any invalid byte sequence,
8976 returns a false value plus the position of the first invalid byte.
8977
8978
8979
8980
8981 <p>
8982 <hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
8983 Returns the position (in bytes) where the encoding of the
8984 <code>n</code>-th character of <code>s</code>
8985 (counting from position <code>i</code>) starts.
8986 A negative <code>n</code> gets characters before position <code>i</code>.
8987 The default for <code>i</code> is 1 when <code>n</code> is non-negative
8988 and <code>#s + 1</code> otherwise,
8989 so that <code>utf8.offset(s, -n)</code> gets the offset of the
8990 <code>n</code>-th character from the end of the string.
8991 If the specified character is neither in the subject
8992 nor right after its end,
8993 the function returns <b>nil</b>.
8994
8995
8996 <p>
8997 As a special case,
8998 when <code>n</code> is 0 the function returns the start of the encoding
8999 of the character that contains the <code>i</code>-th byte of <code>s</code>.
9000
9001
9002 <p>
9003 This function assumes that <code>s</code> is a valid UTF-8 string.
9004
9005
9006
9007
9008
9009
9010
9011 <h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
9012
9013 <p>
9014 This library provides generic functions for table manipulation.
9015 It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
9016
9017
9018 <p>
9019 Remember that, whenever an operation needs the length of a table,
9020 all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>).
9021 All functions ignore non-numeric keys
9022 in the tables given as arguments.
9023
9024
9025 <p>
9026 <hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
9027
9028
9029 <p>
9030 Given a list where all elements are strings or numbers,
9031 returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
9032 The default value for <code>sep</code> is the empty string,
9033 the default for <code>i</code> is 1,
9034 and the default for <code>j</code> is <code>#list</code>.
9035 If <code>i</code> is greater than <code>j</code>, returns the empty string.
9036
9037
9038
9039
9040 <p>
9041 <hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
9042
9043
9044 <p>
9045 Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
9046 shifting up the elements
9047 <code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
9048 The default value for <code>pos</code> is <code>#list+1</code>,
9049 so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
9050 of list <code>t</code>.
9051
9052
9053
9054
9055 <p>
9056 <hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
9057
9058
9059 <p>
9060 Moves elements from table <code>a1</code> to table <code>a2</code>,
9061 performing the equivalent to the following
9062 multiple assignment:
9063 <code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
9064 The default for <code>a2</code> is <code>a1</code>.
9065 The destination range can overlap with the source range.
9066 The number of elements to be moved must fit in a Lua integer.
9067
9068
9069 <p>
9070 Returns the destination table <code>a2</code>.
9071
9072
9073
9074
9075 <p>
9076 <hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
9077
9078
9079 <p>
9080 Returns a new table with all arguments stored into keys 1, 2, etc.
9081 and with a field "<code>n</code>" with the total number of arguments.
9082 Note that the resulting table may not be a sequence.
9083
9084
9085
9086
9087 <p>
9088 <hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
9089
9090
9091 <p>
9092 Removes from <code>list</code> the element at position <code>pos</code>,
9093 returning the value of the removed element.
9094 When <code>pos</code> is an integer between 1 and <code>#list</code>,
9095 it shifts down the elements
9096 <code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
9097 and erases element <code>list[#list]</code>;
9098 The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
9099 or <code>#list + 1</code>;
9100 in those cases, the function erases the element <code>list[pos]</code>.
9101
9102
9103 <p>
9104 The default value for <code>pos</code> is <code>#list</code>,
9105 so that a call <code>table.remove(l)</code> removes the last element
9106 of list <code>l</code>.
9107
9108
9109
9110
9111 <p>
9112 <hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
9113
9114
9115 <p>
9116 Sorts list elements in a given order, <em>in-place</em>,
9117 from <code>list[1]</code> to <code>list[#list]</code>.
9118 If <code>comp</code> is given,
9119 then it must be a function that receives two list elements
9120 and returns true when the first element must come
9121 before the second in the final order
9122 (so that, after the sort,
9123 <code>i &lt; j</code> implies <code>not comp(list[j],list[i])</code>).
9124 If <code>comp</code> is not given,
9125 then the standard Lua operator <code>&lt;</code> is used instead.
9126
9127
9128 <p>
9129 Note that the <code>comp</code> function must define
9130 a strict partial order over the elements in the list;
9131 that is, it must be asymmetric and transitive.
9132 Otherwise, no valid sort may be possible.
9133
9134
9135 <p>
9136 The sort algorithm is not stable:
9137 elements considered equal by the given order
9138 may have their relative positions changed by the sort.
9139
9140
9141
9142
9143 <p>
9144 <hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
9145
9146
9147 <p>
9148 Returns the elements from the given list.
9149 This function is equivalent to
9150
9151 <pre>
9152      return list[i], list[i+1], &middot;&middot;&middot;, list[j]
9153 </pre><p>
9154 By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
9155
9156
9157
9158
9159
9160
9161
9162 <h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
9163
9164 <p>
9165 This library provides basic mathematical functions.
9166 It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
9167 Functions with the annotation "<code>integer/float</code>" give
9168 integer results for integer arguments
9169 and float results for float (or mixed) arguments.
9170 Rounding functions
9171 (<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>)
9172 return an integer when the result fits in the range of an integer,
9173 or a float otherwise.
9174
9175
9176 <p>
9177 <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
9178
9179
9180 <p>
9181 Returns the absolute value of <code>x</code>. (integer/float)
9182
9183
9184
9185
9186 <p>
9187 <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
9188
9189
9190 <p>
9191 Returns the arc cosine of <code>x</code> (in radians).
9192
9193
9194
9195
9196 <p>
9197 <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
9198
9199
9200 <p>
9201 Returns the arc sine of <code>x</code> (in radians).
9202
9203
9204
9205
9206 <p>
9207 <hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
9208
9209
9210 <p>
9211
9212 Returns the arc tangent of <code>y/x</code> (in radians),
9213 but uses the signs of both arguments to find the
9214 quadrant of the result.
9215 (It also handles correctly the case of <code>x</code> being zero.)
9216
9217
9218 <p>
9219 The default value for <code>x</code> is 1,
9220 so that the call <code>math.atan(y)</code>
9221 returns the arc tangent of <code>y</code>.
9222
9223
9224
9225
9226 <p>
9227 <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
9228
9229
9230 <p>
9231 Returns the smallest integral value larger than or equal to <code>x</code>.
9232
9233
9234
9235
9236 <p>
9237 <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
9238
9239
9240 <p>
9241 Returns the cosine of <code>x</code> (assumed to be in radians).
9242
9243
9244
9245
9246 <p>
9247 <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
9248
9249
9250 <p>
9251 Converts the angle <code>x</code> from radians to degrees.
9252
9253
9254
9255
9256 <p>
9257 <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
9258
9259
9260 <p>
9261 Returns the value <em>e<sup>x</sup></em>
9262 (where <code>e</code> is the base of natural logarithms).
9263
9264
9265
9266
9267 <p>
9268 <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
9269
9270
9271 <p>
9272 Returns the largest integral value smaller than or equal to <code>x</code>.
9273
9274
9275
9276
9277 <p>
9278 <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
9279
9280
9281 <p>
9282 Returns the remainder of the division of <code>x</code> by <code>y</code>
9283 that rounds the quotient towards zero. (integer/float)
9284
9285
9286
9287
9288 <p>
9289 <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
9290
9291
9292 <p>
9293 The float value <code>HUGE_VAL</code>,
9294 a value larger than any other numeric value.
9295
9296
9297
9298
9299 <p>
9300 <hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
9301
9302
9303 <p>
9304 Returns the logarithm of <code>x</code> in the given base.
9305 The default for <code>base</code> is <em>e</em>
9306 (so that the function returns the natural logarithm of <code>x</code>).
9307
9308
9309
9310
9311 <p>
9312 <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
9313
9314
9315 <p>
9316 Returns the argument with the maximum value,
9317 according to the Lua operator <code>&lt;</code>. (integer/float)
9318
9319
9320
9321
9322 <p>
9323 <hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
9324 An integer with the maximum value for an integer.
9325
9326
9327
9328
9329 <p>
9330 <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
9331
9332
9333 <p>
9334 Returns the argument with the minimum value,
9335 according to the Lua operator <code>&lt;</code>. (integer/float)
9336
9337
9338
9339
9340 <p>
9341 <hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
9342 An integer with the minimum value for an integer.
9343
9344
9345
9346
9347 <p>
9348 <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
9349
9350
9351 <p>
9352 Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
9353 Its second result is always a float.
9354
9355
9356
9357
9358 <p>
9359 <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
9360
9361
9362 <p>
9363 The value of <em>&pi;</em>.
9364
9365
9366
9367
9368 <p>
9369 <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
9370
9371
9372 <p>
9373 Converts the angle <code>x</code> from degrees to radians.
9374
9375
9376
9377
9378 <p>
9379 <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
9380
9381
9382 <p>
9383 When called without arguments,
9384 returns a pseudo-random float with uniform distribution
9385 in the range  <em>[0,1)</em>.  
9386 When called with two integers <code>m</code> and <code>n</code>,
9387 <code>math.random</code> returns a pseudo-random integer
9388 with uniform distribution in the range <em>[m, n]</em>.
9389 (The value <em>n-m</em> cannot be negative and must fit in a Lua integer.)
9390 The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>.
9391
9392
9393 <p>
9394 This function is an interface to the underling
9395 pseudo-random generator function provided by C.
9396
9397
9398
9399
9400 <p>
9401 <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
9402
9403
9404 <p>
9405 Sets <code>x</code> as the "seed"
9406 for the pseudo-random generator:
9407 equal seeds produce equal sequences of numbers.
9408
9409
9410
9411
9412 <p>
9413 <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
9414
9415
9416 <p>
9417 Returns the sine of <code>x</code> (assumed to be in radians).
9418
9419
9420
9421
9422 <p>
9423 <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
9424
9425
9426 <p>
9427 Returns the square root of <code>x</code>.
9428 (You can also use the expression <code>x^0.5</code> to compute this value.)
9429
9430
9431
9432
9433 <p>
9434 <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
9435
9436
9437 <p>
9438 Returns the tangent of <code>x</code> (assumed to be in radians).
9439
9440
9441
9442
9443 <p>
9444 <hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
9445
9446
9447 <p>
9448 If the value <code>x</code> is convertible to an integer,
9449 returns that integer.
9450 Otherwise, returns <b>nil</b>.
9451
9452
9453
9454
9455 <p>
9456 <hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
9457
9458
9459 <p>
9460 Returns "<code>integer</code>" if <code>x</code> is an integer,
9461 "<code>float</code>" if it is a float,
9462 or <b>nil</b> if <code>x</code> is not a number.
9463
9464
9465
9466
9467 <p>
9468 <hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
9469
9470
9471 <p>
9472 Returns a boolean,
9473 true if and only if integer <code>m</code> is below integer <code>n</code> when
9474 they are compared as unsigned integers.
9475
9476
9477
9478
9479
9480
9481
9482 <h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
9483
9484 <p>
9485 The I/O library provides two different styles for file manipulation.
9486 The first one uses implicit file handles;
9487 that is, there are operations to set a default input file and a
9488 default output file,
9489 and all input/output operations are over these default files.
9490 The second style uses explicit file handles.
9491
9492
9493 <p>
9494 When using implicit file handles,
9495 all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
9496 When using explicit file handles,
9497 the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
9498 and then all operations are supplied as methods of the file handle.
9499
9500
9501 <p>
9502 The table <code>io</code> also provides
9503 three predefined file handles with their usual meanings from C:
9504 <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>.
9505 The I/O library never closes these files.
9506
9507
9508 <p>
9509 Unless otherwise stated,
9510 all I/O functions return <b>nil</b> on failure
9511 (plus an error message as a second result and
9512 a system-dependent error code as a third result)
9513 and some value different from <b>nil</b> on success.
9514 In non-POSIX systems,
9515 the computation of the error message and error code
9516 in case of errors
9517 may be not thread safe,
9518 because they rely on the global C variable <code>errno</code>.
9519
9520
9521 <p>
9522 <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
9523
9524
9525 <p>
9526 Equivalent to <code>file:close()</code>.
9527 Without a <code>file</code>, closes the default output file.
9528
9529
9530
9531
9532 <p>
9533 <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
9534
9535
9536 <p>
9537 Equivalent to <code>io.output():flush()</code>.
9538
9539
9540
9541
9542 <p>
9543 <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
9544
9545
9546 <p>
9547 When called with a file name, it opens the named file (in text mode),
9548 and sets its handle as the default input file.
9549 When called with a file handle,
9550 it simply sets this file handle as the default input file.
9551 When called without arguments,
9552 it returns the current default input file.
9553
9554
9555 <p>
9556 In case of errors this function raises the error,
9557 instead of returning an error code.
9558
9559
9560
9561
9562 <p>
9563 <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3>
9564
9565
9566 <p>
9567 Opens the given file name in read mode
9568 and returns an iterator function that
9569 works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
9570 When the iterator function detects the end of file,
9571 it returns no values (to finish the loop) and automatically closes the file.
9572
9573
9574 <p>
9575 The call <code>io.lines()</code> (with no file name) is equivalent
9576 to <code>io.input():lines("*l")</code>;
9577 that is, it iterates over the lines of the default input file.
9578 In this case, the iterator does not close the file when the loop ends.
9579
9580
9581 <p>
9582 In case of errors this function raises the error,
9583 instead of returning an error code.
9584
9585
9586
9587
9588 <p>
9589 <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
9590
9591
9592 <p>
9593 This function opens a file,
9594 in the mode specified in the string <code>mode</code>.
9595 In case of success,
9596 it returns a new file handle.
9597
9598
9599 <p>
9600 The <code>mode</code> string can be any of the following:
9601
9602 <ul>
9603 <li><b>"<code>r</code>": </b> read mode (the default);</li>
9604 <li><b>"<code>w</code>": </b> write mode;</li>
9605 <li><b>"<code>a</code>": </b> append mode;</li>
9606 <li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
9607 <li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
9608 <li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
9609   writing is only allowed at the end of file.</li>
9610 </ul><p>
9611 The <code>mode</code> string can also have a '<code>b</code>' at the end,
9612 which is needed in some systems to open the file in binary mode.
9613
9614
9615
9616
9617 <p>
9618 <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
9619
9620
9621 <p>
9622 Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
9623
9624
9625
9626
9627 <p>
9628 <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
9629
9630
9631 <p>
9632 This function is system dependent and is not available
9633 on all platforms.
9634
9635
9636 <p>
9637 Starts program <code>prog</code> in a separated process and returns
9638 a file handle that you can use to read data from this program
9639 (if <code>mode</code> is <code>"r"</code>, the default)
9640 or to write data to this program
9641 (if <code>mode</code> is <code>"w"</code>).
9642
9643
9644
9645
9646 <p>
9647 <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
9648
9649
9650 <p>
9651 Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
9652
9653
9654
9655
9656 <p>
9657 <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
9658
9659
9660 <p>
9661 In case of success,
9662 returns a handle for a temporary file.
9663 This file is opened in update mode
9664 and it is automatically removed when the program ends.
9665
9666
9667
9668
9669 <p>
9670 <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
9671
9672
9673 <p>
9674 Checks whether <code>obj</code> is a valid file handle.
9675 Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
9676 <code>"closed file"</code> if <code>obj</code> is a closed file handle,
9677 or <b>nil</b> if <code>obj</code> is not a file handle.
9678
9679
9680
9681
9682 <p>
9683 <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
9684
9685
9686 <p>
9687 Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
9688
9689
9690
9691
9692 <p>
9693 <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
9694
9695
9696 <p>
9697 Closes <code>file</code>.
9698 Note that files are automatically closed when
9699 their handles are garbage collected,
9700 but that takes an unpredictable amount of time to happen.
9701
9702
9703 <p>
9704 When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
9705 <a href="#pdf-file:close"><code>file:close</code></a> returns the same values
9706 returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
9707
9708
9709
9710
9711 <p>
9712 <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
9713
9714
9715 <p>
9716 Saves any written data to <code>file</code>.
9717
9718
9719
9720
9721 <p>
9722 <hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
9723
9724
9725 <p>
9726 Returns an iterator function that,
9727 each time it is called,
9728 reads the file according to the given formats.
9729 When no format is given,
9730 uses "<code>l</code>" as a default.
9731 As an example, the construction
9732
9733 <pre>
9734      for c in file:lines(1) do <em>body</em> end
9735 </pre><p>
9736 will iterate over all characters of the file,
9737 starting at the current position.
9738 Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
9739 when the loop ends.
9740
9741
9742 <p>
9743 In case of errors this function raises the error,
9744 instead of returning an error code.
9745
9746
9747
9748
9749 <p>
9750 <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
9751
9752
9753 <p>
9754 Reads the file <code>file</code>,
9755 according to the given formats, which specify what to read.
9756 For each format,
9757 the function returns a string or a number with the characters read,
9758 or <b>nil</b> if it cannot read data with the specified format.
9759 (In this latter case,
9760 the function does not read subsequent formats.)
9761 When called without formats,
9762 it uses a default format that reads the next line
9763 (see below).
9764
9765
9766 <p>
9767 The available formats are
9768
9769 <ul>
9770
9771 <li><b>"<code>n</code>": </b>
9772 reads a numeral and returns it as a float or an integer,
9773 following the lexical conventions of Lua.
9774 (The numeral may have leading spaces and a sign.)
9775 This format always reads the longest input sequence that
9776 is a valid prefix for a numeral;
9777 if that prefix does not form a valid numeral
9778 (e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"),
9779 it is discarded and the function returns <b>nil</b>.
9780 </li>
9781
9782 <li><b>"<code>a</code>": </b>
9783 reads the whole file, starting at the current position.
9784 On end of file, it returns the empty string.
9785 </li>
9786
9787 <li><b>"<code>l</code>": </b>
9788 reads the next line skipping the end of line,
9789 returning <b>nil</b> on end of file.
9790 This is the default format.
9791 </li>
9792
9793 <li><b>"<code>L</code>": </b>
9794 reads the next line keeping the end-of-line character (if present),
9795 returning <b>nil</b> on end of file.
9796 </li>
9797
9798 <li><b><em>number</em>: </b>
9799 reads a string with up to this number of bytes,
9800 returning <b>nil</b> on end of file.
9801 If <code>number</code> is zero,
9802 it reads nothing and returns an empty string,
9803 or <b>nil</b> on end of file.
9804 </li>
9805
9806 </ul><p>
9807 The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
9808
9809
9810
9811
9812 <p>
9813 <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
9814
9815
9816 <p>
9817 Sets and gets the file position,
9818 measured from the beginning of the file,
9819 to the position given by <code>offset</code> plus a base
9820 specified by the string <code>whence</code>, as follows:
9821
9822 <ul>
9823 <li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
9824 <li><b>"<code>cur</code>": </b> base is current position;</li>
9825 <li><b>"<code>end</code>": </b> base is end of file;</li>
9826 </ul><p>
9827 In case of success, <code>seek</code> returns the final file position,
9828 measured in bytes from the beginning of the file.
9829 If <code>seek</code> fails, it returns <b>nil</b>,
9830 plus a string describing the error.
9831
9832
9833 <p>
9834 The default value for <code>whence</code> is <code>"cur"</code>,
9835 and for <code>offset</code> is 0.
9836 Therefore, the call <code>file:seek()</code> returns the current
9837 file position, without changing it;
9838 the call <code>file:seek("set")</code> sets the position to the
9839 beginning of the file (and returns 0);
9840 and the call <code>file:seek("end")</code> sets the position to the
9841 end of the file, and returns its size.
9842
9843
9844
9845
9846 <p>
9847 <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
9848
9849
9850 <p>
9851 Sets the buffering mode for an output file.
9852 There are three available modes:
9853
9854 <ul>
9855
9856 <li><b>"<code>no</code>": </b>
9857 no buffering; the result of any output operation appears immediately.
9858 </li>
9859
9860 <li><b>"<code>full</code>": </b>
9861 full buffering; output operation is performed only
9862 when the buffer is full or when
9863 you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>).
9864 </li>
9865
9866 <li><b>"<code>line</code>": </b>
9867 line buffering; output is buffered until a newline is output
9868 or there is any input from some special files
9869 (such as a terminal device).
9870 </li>
9871
9872 </ul><p>
9873 For the last two cases, <code>size</code>
9874 specifies the size of the buffer, in bytes.
9875 The default is an appropriate size.
9876
9877
9878
9879
9880 <p>
9881 <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
9882
9883
9884 <p>
9885 Writes the value of each of its arguments to <code>file</code>.
9886 The arguments must be strings or numbers.
9887
9888
9889 <p>
9890 In case of success, this function returns <code>file</code>.
9891 Otherwise it returns <b>nil</b> plus a string describing the error.
9892
9893
9894
9895
9896
9897
9898
9899 <h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
9900
9901 <p>
9902 This library is implemented through table <a name="pdf-os"><code>os</code></a>.
9903
9904
9905 <p>
9906 <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
9907
9908
9909 <p>
9910 Returns an approximation of the amount in seconds of CPU time
9911 used by the program.
9912
9913
9914
9915
9916 <p>
9917 <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
9918
9919
9920 <p>
9921 Returns a string or a table containing date and time,
9922 formatted according to the given string <code>format</code>.
9923
9924
9925 <p>
9926 If the <code>time</code> argument is present,
9927 this is the time to be formatted
9928 (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
9929 Otherwise, <code>date</code> formats the current time.
9930
9931
9932 <p>
9933 If <code>format</code> starts with '<code>!</code>',
9934 then the date is formatted in Coordinated Universal Time.
9935 After this optional character,
9936 if <code>format</code> is the string "<code>*t</code>",
9937 then <code>date</code> returns a table with the following fields:
9938 <code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
9939 <code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59), <code>sec</code> (0&ndash;61),
9940 <code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1),
9941 <code>yday</code> (day of the year, 1&ndash;366),
9942 and <code>isdst</code> (daylight saving flag, a boolean).
9943 This last field may be absent
9944 if the information is not available.
9945
9946
9947 <p>
9948 If <code>format</code> is not "<code>*t</code>",
9949 then <code>date</code> returns the date as a string,
9950 formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
9951
9952
9953 <p>
9954 When called without arguments,
9955 <code>date</code> returns a reasonable date and time representation that depends on
9956 the host system and on the current locale.
9957 (More specifically, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>.)
9958
9959
9960 <p>
9961 In non-POSIX systems,
9962 this function may be not thread safe
9963 because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
9964
9965
9966
9967
9968 <p>
9969 <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
9970
9971
9972 <p>
9973 Returns the difference, in seconds,
9974 from time <code>t1</code> to time <code>t2</code>
9975 (where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
9976 In POSIX, Windows, and some other systems,
9977 this value is exactly <code>t2</code><em>-</em><code>t1</code>.
9978
9979
9980
9981
9982 <p>
9983 <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
9984
9985
9986 <p>
9987 This function is equivalent to the ISO&nbsp;C function <code>system</code>.
9988 It passes <code>command</code> to be executed by an operating system shell.
9989 Its first result is <b>true</b>
9990 if the command terminated successfully,
9991 or <b>nil</b> otherwise.
9992 After this first result
9993 the function returns a string plus a number,
9994 as follows:
9995
9996 <ul>
9997
9998 <li><b>"<code>exit</code>": </b>
9999 the command terminated normally;
10000 the following number is the exit status of the command.
10001 </li>
10002
10003 <li><b>"<code>signal</code>": </b>
10004 the command was terminated by a signal;
10005 the following number is the signal that terminated the command.
10006 </li>
10007
10008 </ul>
10009
10010 <p>
10011 When called without a <code>command</code>,
10012 <code>os.execute</code> returns a boolean that is true if a shell is available.
10013
10014
10015
10016
10017 <p>
10018 <hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
10019
10020
10021 <p>
10022 Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
10023 If <code>code</code> is <b>true</b>,
10024 the returned status is <code>EXIT_SUCCESS</code>;
10025 if <code>code</code> is <b>false</b>,
10026 the returned status is <code>EXIT_FAILURE</code>;
10027 if <code>code</code> is a number,
10028 the returned status is this number.
10029 The default value for <code>code</code> is <b>true</b>.
10030
10031
10032 <p>
10033 If the optional second argument <code>close</code> is true,
10034 closes the Lua state before exiting.
10035
10036
10037
10038
10039 <p>
10040 <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
10041
10042
10043 <p>
10044 Returns the value of the process environment variable <code>varname</code>,
10045 or <b>nil</b> if the variable is not defined.
10046
10047
10048
10049
10050 <p>
10051 <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
10052
10053
10054 <p>
10055 Deletes the file (or empty directory, on POSIX systems)
10056 with the given name.
10057 If this function fails, it returns <b>nil</b>,
10058 plus a string describing the error and the error code.
10059 Otherwise, it returns true.
10060
10061
10062
10063
10064 <p>
10065 <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
10066
10067
10068 <p>
10069 Renames the file or directory named <code>oldname</code> to <code>newname</code>.
10070 If this function fails, it returns <b>nil</b>,
10071 plus a string describing the error and the error code.
10072 Otherwise, it returns true.
10073
10074
10075
10076
10077 <p>
10078 <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
10079
10080
10081 <p>
10082 Sets the current locale of the program.
10083 <code>locale</code> is a system-dependent string specifying a locale;
10084 <code>category</code> is an optional string describing which category to change:
10085 <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
10086 <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
10087 the default category is <code>"all"</code>.
10088 The function returns the name of the new locale,
10089 or <b>nil</b> if the request cannot be honored.
10090
10091
10092 <p>
10093 If <code>locale</code> is the empty string,
10094 the current locale is set to an implementation-defined native locale.
10095 If <code>locale</code> is the string "<code>C</code>",
10096 the current locale is set to the standard C locale.
10097
10098
10099 <p>
10100 When called with <b>nil</b> as the first argument,
10101 this function only returns the name of the current locale
10102 for the given category.
10103
10104
10105 <p>
10106 This function may be not thread safe
10107 because of its reliance on C&nbsp;function <code>setlocale</code>.
10108
10109
10110
10111
10112 <p>
10113 <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
10114
10115
10116 <p>
10117 Returns the current time when called without arguments,
10118 or a time representing the local date and time specified by the given table.
10119 This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
10120 and may have fields
10121 <code>hour</code> (default is 12),
10122 <code>min</code> (default is 0),
10123 <code>sec</code> (default is 0),
10124 and <code>isdst</code> (default is <b>nil</b>).
10125 Other fields are ignored.
10126 For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
10127
10128
10129 <p>
10130 The values in these fields do not need to be inside their valid ranges.
10131 For instance, if <code>sec</code> is -10,
10132 it means -10 seconds from the time specified by the other fields;
10133 if <code>hour</code> is 1000,
10134 it means +1000 hours from the time specified by the other fields.
10135
10136
10137 <p>
10138 The returned value is a number, whose meaning depends on your system.
10139 In POSIX, Windows, and some other systems,
10140 this number counts the number
10141 of seconds since some given start time (the "epoch").
10142 In other systems, the meaning is not specified,
10143 and the number returned by <code>time</code> can be used only as an argument to
10144 <a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
10145
10146
10147
10148
10149 <p>
10150 <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
10151
10152
10153 <p>
10154 Returns a string with a file name that can
10155 be used for a temporary file.
10156 The file must be explicitly opened before its use
10157 and explicitly removed when no longer needed.
10158
10159
10160 <p>
10161 In POSIX systems,
10162 this function also creates a file with that name,
10163 to avoid security risks.
10164 (Someone else might create the file with wrong permissions
10165 in the time between getting the name and creating the file.)
10166 You still have to open the file to use it
10167 and to remove it (even if you do not use it).
10168
10169
10170 <p>
10171 When possible,
10172 you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
10173 which automatically removes the file when the program ends.
10174
10175
10176
10177
10178
10179
10180
10181 <h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
10182
10183 <p>
10184 This library provides
10185 the functionality of the debug interface (<a href="#4.9">&sect;4.9</a>) to Lua programs.
10186 You should exert care when using this library.
10187 Several of its functions
10188 violate basic assumptions about Lua code
10189 (e.g., that variables local to a function
10190 cannot be accessed from outside;
10191 that userdata metatables cannot be changed by Lua code;
10192 that Lua programs do not crash)
10193 and therefore can compromise otherwise secure code.
10194 Moreover, some functions in this library may be slow.
10195
10196
10197 <p>
10198 All functions in this library are provided
10199 inside the <a name="pdf-debug"><code>debug</code></a> table.
10200 All functions that operate over a thread
10201 have an optional first argument which is the
10202 thread to operate over.
10203 The default is always the current thread.
10204
10205
10206 <p>
10207 <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
10208
10209
10210 <p>
10211 Enters an interactive mode with the user,
10212 running each string that the user enters.
10213 Using simple commands and other debug facilities,
10214 the user can inspect global and local variables,
10215 change their values, evaluate expressions, and so on.
10216 A line containing only the word <code>cont</code> finishes this function,
10217 so that the caller continues its execution.
10218
10219
10220 <p>
10221 Note that commands for <code>debug.debug</code> are not lexically nested
10222 within any function and so have no direct access to local variables.
10223
10224
10225
10226
10227 <p>
10228 <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
10229
10230
10231 <p>
10232 Returns the current hook settings of the thread, as three values:
10233 the current hook function, the current hook mask,
10234 and the current hook count
10235 (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
10236
10237
10238
10239
10240 <p>
10241 <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
10242
10243
10244 <p>
10245 Returns a table with information about a function.
10246 You can give the function directly
10247 or you can give a number as the value of <code>f</code>,
10248 which means the function running at level <code>f</code> of the call stack
10249 of the given thread:
10250 level&nbsp;0 is the current function (<code>getinfo</code> itself);
10251 level&nbsp;1 is the function that called <code>getinfo</code>
10252 (except for tail calls, which do not count on the stack);
10253 and so on.
10254 If <code>f</code> is a number larger than the number of active functions,
10255 then <code>getinfo</code> returns <b>nil</b>.
10256
10257
10258 <p>
10259 The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
10260 with the string <code>what</code> describing which fields to fill in.
10261 The default for <code>what</code> is to get all information available,
10262 except the table of valid lines.
10263 If present,
10264 the option '<code>f</code>'
10265 adds a field named <code>func</code> with the function itself.
10266 If present,
10267 the option '<code>L</code>'
10268 adds a field named <code>activelines</code> with the table of
10269 valid lines.
10270
10271
10272 <p>
10273 For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
10274 a name for the current function,
10275 if a reasonable name can be found,
10276 and the expression <code>debug.getinfo(print)</code>
10277 returns a table with all available information
10278 about the <a href="#pdf-print"><code>print</code></a> function.
10279
10280
10281
10282
10283 <p>
10284 <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
10285
10286
10287 <p>
10288 This function returns the name and the value of the local variable
10289 with index <code>local</code> of the function at level <code>f</code> of the stack.
10290 This function accesses not only explicit local variables,
10291 but also parameters, temporaries, etc.
10292
10293
10294 <p>
10295 The first parameter or local variable has index&nbsp;1, and so on,
10296 following the order that they are declared in the code,
10297 counting only the variables that are active
10298 in the current scope of the function.
10299 Negative indices refer to vararg arguments;
10300 -1 is the first vararg argument.
10301 The function returns <b>nil</b> if there is no variable with the given index,
10302 and raises an error when called with a level out of range.
10303 (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
10304
10305
10306 <p>
10307 Variable names starting with '<code>(</code>' (open parenthesis) 
10308 represent variables with no known names
10309 (internal variables such as loop control variables,
10310 and variables from chunks saved without debug information).
10311
10312
10313 <p>
10314 The parameter <code>f</code> may also be a function.
10315 In that case, <code>getlocal</code> returns only the name of function parameters.
10316
10317
10318
10319
10320 <p>
10321 <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
10322
10323
10324 <p>
10325 Returns the metatable of the given <code>value</code>
10326 or <b>nil</b> if it does not have a metatable.
10327
10328
10329
10330
10331 <p>
10332 <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
10333
10334
10335 <p>
10336 Returns the registry table (see <a href="#4.5">&sect;4.5</a>).
10337
10338
10339
10340
10341 <p>
10342 <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
10343
10344
10345 <p>
10346 This function returns the name and the value of the upvalue
10347 with index <code>up</code> of the function <code>f</code>.
10348 The function returns <b>nil</b> if there is no upvalue with the given index.
10349
10350
10351 <p>
10352 Variable names starting with '<code>(</code>' (open parenthesis) 
10353 represent variables with no known names
10354 (variables from chunks saved without debug information).
10355
10356
10357
10358
10359 <p>
10360 <hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
10361
10362
10363 <p>
10364 Returns the Lua value associated to <code>u</code>.
10365 If <code>u</code> is not a full userdata,
10366 returns <b>nil</b>.
10367
10368
10369
10370
10371 <p>
10372 <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
10373
10374
10375 <p>
10376 Sets the given function as a hook.
10377 The string <code>mask</code> and the number <code>count</code> describe
10378 when the hook will be called.
10379 The string mask may have any combination of the following characters,
10380 with the given meaning:
10381
10382 <ul>
10383 <li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
10384 <li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
10385 <li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
10386 </ul><p>
10387 Moreover,
10388 with a <code>count</code> different from zero,
10389 the hook is called also after every <code>count</code> instructions.
10390
10391
10392 <p>
10393 When called without arguments,
10394 <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
10395
10396
10397 <p>
10398 When the hook is called, its first argument is a string
10399 describing the event that has triggered its call:
10400 <code>"call"</code> (or <code>"tail call"</code>),
10401 <code>"return"</code>,
10402 <code>"line"</code>, and <code>"count"</code>.
10403 For line events,
10404 the hook also gets the new line number as its second parameter.
10405 Inside a hook,
10406 you can call <code>getinfo</code> with level&nbsp;2 to get more information about
10407 the running function
10408 (level&nbsp;0 is the <code>getinfo</code> function,
10409 and level&nbsp;1 is the hook function).
10410
10411
10412
10413
10414 <p>
10415 <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
10416
10417
10418 <p>
10419 This function assigns the value <code>value</code> to the local variable
10420 with index <code>local</code> of the function at level <code>level</code> of the stack.
10421 The function returns <b>nil</b> if there is no local
10422 variable with the given index,
10423 and raises an error when called with a <code>level</code> out of range.
10424 (You can call <code>getinfo</code> to check whether the level is valid.)
10425 Otherwise, it returns the name of the local variable.
10426
10427
10428 <p>
10429 See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
10430 variable indices and names.
10431
10432
10433
10434
10435 <p>
10436 <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
10437
10438
10439 <p>
10440 Sets the metatable for the given <code>value</code> to the given <code>table</code>
10441 (which can be <b>nil</b>).
10442 Returns <code>value</code>.
10443
10444
10445
10446
10447 <p>
10448 <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
10449
10450
10451 <p>
10452 This function assigns the value <code>value</code> to the upvalue
10453 with index <code>up</code> of the function <code>f</code>.
10454 The function returns <b>nil</b> if there is no upvalue
10455 with the given index.
10456 Otherwise, it returns the name of the upvalue.
10457
10458
10459
10460
10461 <p>
10462 <hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3>
10463
10464
10465 <p>
10466 Sets the given <code>value</code> as
10467 the Lua value associated to the given <code>udata</code>.
10468 <code>udata</code> must be a full userdata.
10469
10470
10471 <p>
10472 Returns <code>udata</code>.
10473
10474
10475
10476
10477 <p>
10478 <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
10479
10480
10481 <p>
10482 If <code>message</code> is present but is neither a string nor <b>nil</b>,
10483 this function returns <code>message</code> without further processing.
10484 Otherwise,
10485 it returns a string with a traceback of the call stack.
10486 The optional <code>message</code> string is appended
10487 at the beginning of the traceback.
10488 An optional <code>level</code> number tells at which level
10489 to start the traceback
10490 (default is 1, the function calling <code>traceback</code>).
10491
10492
10493
10494
10495 <p>
10496 <hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
10497
10498
10499 <p>
10500 Returns a unique identifier (as a light userdata)
10501 for the upvalue numbered <code>n</code>
10502 from the given function.
10503
10504
10505 <p>
10506 These unique identifiers allow a program to check whether different
10507 closures share upvalues.
10508 Lua closures that share an upvalue
10509 (that is, that access a same external local variable)
10510 will return identical ids for those upvalue indices.
10511
10512
10513
10514
10515 <p>
10516 <hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
10517
10518
10519 <p>
10520 Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
10521 refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
10522
10523
10524
10525
10526
10527
10528
10529 <h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
10530
10531 <p>
10532 Although Lua has been designed as an extension language,
10533 to be embedded in a host C&nbsp;program,
10534 it is also frequently used as a standalone language.
10535 An interpreter for Lua as a standalone language,
10536 called simply <code>lua</code>,
10537 is provided with the standard distribution.
10538 The standalone interpreter includes
10539 all standard libraries, including the debug library.
10540 Its usage is:
10541
10542 <pre>
10543      lua [options] [script [args]]
10544 </pre><p>
10545 The options are:
10546
10547 <ul>
10548 <li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li>
10549 <li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em> and assigns the
10550   result to global @<em>mod</em>;</li>
10551 <li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li>
10552 <li><b><code>-v</code>: </b> prints version information;</li>
10553 <li><b><code>-E</code>: </b> ignores environment variables;</li>
10554 <li><b><code>--</code>: </b> stops handling options;</li>
10555 <li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
10556 </ul><p>
10557 After handling its options, <code>lua</code> runs the given <em>script</em>.
10558 When called without arguments,
10559 <code>lua</code> behaves as <code>lua -v -i</code>
10560 when the standard input (<code>stdin</code>) is a terminal,
10561 and as <code>lua -</code> otherwise.
10562
10563
10564 <p>
10565 When called without option <code>-E</code>,
10566 the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a>
10567 (or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
10568 before running any argument.
10569 If the variable content has the format <code>@<em>filename</em></code>,
10570 then <code>lua</code> executes the file.
10571 Otherwise, <code>lua</code> executes the string itself.
10572
10573
10574 <p>
10575 When called with option <code>-E</code>,
10576 besides ignoring <code>LUA_INIT</code>,
10577 Lua also ignores
10578 the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>,
10579 setting the values of
10580 <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
10581 with the default paths defined in <code>luaconf.h</code>.
10582
10583
10584 <p>
10585 All options are handled in order, except <code>-i</code> and <code>-E</code>.
10586 For instance, an invocation like
10587
10588 <pre>
10589      $ lua -e'a=1' -e 'print(a)' script.lua
10590 </pre><p>
10591 will first set <code>a</code> to 1, then print the value of <code>a</code>,
10592 and finally run the file <code>script.lua</code> with no arguments.
10593 (Here <code>$</code> is the shell prompt. Your prompt may be different.)
10594
10595
10596 <p>
10597 Before running any code,
10598 <code>lua</code> collects all command-line arguments
10599 in a global table called <code>arg</code>.
10600 The script name goes to index 0,
10601 the first argument after the script name goes to index 1,
10602 and so on.
10603 Any arguments before the script name
10604 (that is, the interpreter name plus its options)
10605 go to negative indices.
10606 For instance, in the call
10607
10608 <pre>
10609      $ lua -la b.lua t1 t2
10610 </pre><p>
10611 the table is like this:
10612
10613 <pre>
10614      arg = { [-2] = "lua", [-1] = "-la",
10615              [0] = "b.lua",
10616              [1] = "t1", [2] = "t2" }
10617 </pre><p>
10618 If there is no script in the call,
10619 the interpreter name goes to index 0,
10620 followed by the other arguments.
10621 For instance, the call
10622
10623 <pre>
10624      $ lua -e "print(arg[1])"
10625 </pre><p>
10626 will print "<code>-e</code>".
10627 If there is a script,
10628 the script is called with arguments
10629 <code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
10630 (Like all chunks in Lua,
10631 the script is compiled as a vararg function.)
10632
10633
10634 <p>
10635 In interactive mode,
10636 Lua repeatedly prompts and waits for a line.
10637 After reading a line,
10638 Lua first try to interpret the line as an expression.
10639 If it succeeds, it prints its value.
10640 Otherwise, it interprets the line as a statement.
10641 If you write an incomplete statement,
10642 the interpreter waits for its completion
10643 by issuing a different prompt.
10644
10645
10646 <p>
10647 If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
10648 then its value is used as the prompt.
10649 Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
10650 its value is used as the secondary prompt
10651 (issued during incomplete statements).
10652
10653
10654 <p>
10655 In case of unprotected errors in the script,
10656 the interpreter reports the error to the standard error stream.
10657 If the error object is not a string but
10658 has a metamethod <code>__tostring</code>,
10659 the interpreter calls this metamethod to produce the final message.
10660 Otherwise, the interpreter converts the error object to a string
10661 and adds a stack traceback to it.
10662
10663
10664 <p>
10665 When finishing normally,
10666 the interpreter closes its main Lua state
10667 (see <a href="#lua_close"><code>lua_close</code></a>).
10668 The script can avoid this step by
10669 calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
10670
10671
10672 <p>
10673 To allow the use of Lua as a
10674 script interpreter in Unix systems,
10675 the standalone interpreter skips
10676 the first line of a chunk if it starts with <code>#</code>.
10677 Therefore, Lua scripts can be made into executable programs
10678 by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
10679 as in
10680
10681 <pre>
10682      #!/usr/local/bin/lua
10683 </pre><p>
10684 (Of course,
10685 the location of the Lua interpreter may be different in your machine.
10686 If <code>lua</code> is in your <code>PATH</code>,
10687 then
10688
10689 <pre>
10690      #!/usr/bin/env lua
10691 </pre><p>
10692 is a more portable solution.)
10693
10694
10695
10696 <h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
10697
10698 <p>
10699 Here we list the incompatibilities that you may find when moving a program
10700 from Lua&nbsp;5.2 to Lua&nbsp;5.3.
10701 You can avoid some incompatibilities by compiling Lua with
10702 appropriate options (see file <code>luaconf.h</code>).
10703 However,
10704 all these compatibility options will be removed in the future.
10705
10706
10707 <p>
10708 Lua versions can always change the C API in ways that
10709 do not imply source-code changes in a program,
10710 such as the numeric values for constants
10711 or the implementation of functions as macros.
10712 Therefore,
10713 you should not assume that binaries are compatible between
10714 different Lua versions.
10715 Always recompile clients of the Lua API when
10716 using a new version.
10717
10718
10719 <p>
10720 Similarly, Lua versions can always change the internal representation
10721 of precompiled chunks;
10722 precompiled chunks are not compatible between different Lua versions.
10723
10724
10725 <p>
10726 The standard paths in the official distribution may
10727 change between versions.
10728
10729
10730
10731 <h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10732 <ul>
10733
10734 <li>
10735 The main difference between Lua&nbsp;5.2 and Lua&nbsp;5.3 is the
10736 introduction of an integer subtype for numbers.
10737 Although this change should not affect "normal" computations,
10738 some computations
10739 (mainly those that involve some kind of overflow)
10740 can give different results.
10741
10742
10743 <p>
10744 You can fix these differences by forcing a number to be a float
10745 (in Lua&nbsp;5.2 all numbers were float),
10746 in particular writing constants with an ending <code>.0</code>
10747 or using <code>x = x + 0.0</code> to convert a variable.
10748 (This recommendation is only for a quick fix
10749 for an occasional incompatibility;
10750 it is not a general guideline for good programming.
10751 For good programming,
10752 use floats where you need floats
10753 and integers where you need integers.)
10754 </li>
10755
10756 <li>
10757 The conversion of a float to a string now adds a <code>.0</code> suffix
10758 to the result if it looks like an integer.
10759 (For instance, the float 2.0 will be printed as <code>2.0</code>,
10760 not as <code>2</code>.)
10761 You should always use an explicit format
10762 when you need a specific format for numbers.
10763
10764
10765 <p>
10766 (Formally this is not an incompatibility,
10767 because Lua does not specify how numbers are formatted as strings,
10768 but some programs assumed a specific format.)
10769 </li>
10770
10771 <li>
10772 The generational mode for the garbage collector was removed.
10773 (It was an experimental feature in Lua&nbsp;5.2.)
10774 </li>
10775
10776 </ul>
10777
10778
10779
10780
10781 <h2>8.2 &ndash; <a name="8.2">Changes in the Libraries</a></h2>
10782 <ul>
10783
10784 <li>
10785 The <code>bit32</code> library has been deprecated.
10786 It is easy to require a compatible external library or,
10787 better yet, to replace its functions with appropriate bitwise operations.
10788 (Keep in mind that <code>bit32</code> operates on 32-bit integers,
10789 while the bitwise operators in Lua&nbsp;5.3 operate on Lua integers,
10790 which by default have 64&nbsp;bits.)
10791 </li>
10792
10793 <li>
10794 The Table library now respects metamethods
10795 for setting and getting elements.
10796 </li>
10797
10798 <li>
10799 The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and
10800 its <code>__ipairs</code> metamethod has been deprecated.
10801 </li>
10802
10803 <li>
10804 Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore.
10805 For compatibility, Lua will continue to accept (and ignore) this character.
10806 </li>
10807
10808 <li>
10809 The following functions were deprecated in the mathematical library:
10810 <code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>,
10811 <code>frexp</code>, and <code>ldexp</code>.
10812 You can replace <code>math.pow(x,y)</code> with <code>x^y</code>;
10813 you can replace <code>math.atan2</code> with <code>math.atan</code>,
10814 which now accepts one or two arguments;
10815 you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>.
10816 For the other operations,
10817 you can either use an external library or
10818 implement them in Lua.
10819 </li>
10820
10821 <li>
10822 The searcher for C loaders used by <a href="#pdf-require"><code>require</code></a>
10823 changed the way it handles versioned names.
10824 Now, the version should come after the module name
10825 (as is usual in most other tools).
10826 For compatibility, that searcher still tries the old format
10827 if it cannot find an open function according to the new style.
10828 (Lua&nbsp;5.2 already worked that way,
10829 but it did not document the change.)
10830 </li>
10831
10832 <li>
10833 The call <code>collectgarbage("count")</code> now returns only one result.
10834 (You can compute that second result from the fractional part
10835 of the first result.)
10836 </li>
10837
10838 </ul>
10839
10840
10841
10842
10843 <h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2>
10844
10845
10846 <ul>
10847
10848 <li>
10849 Continuation functions now receive as arguments what they needed
10850 to get through <code>lua_getctx</code>,
10851 so <code>lua_getctx</code> has been removed.
10852 Adapt your code accordingly.
10853 </li>
10854
10855 <li>
10856 Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>.
10857 Use 0 as the value of this parameter to get the old behavior.
10858 </li>
10859
10860 <li>
10861 Functions to inject/project unsigned integers
10862 (<code>lua_pushunsigned</code>, <code>lua_tounsigned</code>, <code>lua_tounsignedx</code>,
10863 <code>luaL_checkunsigned</code>, <code>luaL_optunsigned</code>)
10864 were deprecated.
10865 Use their signed equivalents with a type cast.
10866 </li>
10867
10868 <li>
10869 Macros to project non-default integer types
10870 (<code>luaL_checkint</code>, <code>luaL_optint</code>, <code>luaL_checklong</code>, <code>luaL_optlong</code>)
10871 were deprecated.
10872 Use their equivalent over <a href="#lua_Integer"><code>lua_Integer</code></a> with a type cast
10873 (or, when possible, use <a href="#lua_Integer"><code>lua_Integer</code></a> in your code).
10874 </li>
10875
10876 </ul>
10877
10878
10879
10880
10881 <h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
10882
10883 <p>
10884 Here is the complete syntax of Lua in extended BNF.
10885 As usual in extended BNF,
10886 {A} means 0 or more As,
10887 and [A] means an optional A.
10888 (For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
10889 for a description of the terminals
10890 Name, Numeral,
10891 and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
10892
10893
10894
10895
10896 <pre>
10897
10898         chunk ::= block
10899
10900         block ::= {stat} [retstat]
10901
10902         stat ::=  &lsquo;<b>;</b>&rsquo; | 
10903                  varlist &lsquo;<b>=</b>&rsquo; explist | 
10904                  functioncall | 
10905                  label | 
10906                  <b>break</b> | 
10907                  <b>goto</b> Name | 
10908                  <b>do</b> block <b>end</b> | 
10909                  <b>while</b> exp <b>do</b> block <b>end</b> | 
10910                  <b>repeat</b> block <b>until</b> exp | 
10911                  <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | 
10912                  <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> | 
10913                  <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> | 
10914                  <b>function</b> funcname funcbody | 
10915                  <b>local</b> <b>function</b> Name funcbody | 
10916                  <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist] 
10917
10918         retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
10919
10920         label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
10921
10922         funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
10923
10924         varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
10925
10926         var ::=  Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name 
10927
10928         namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
10929
10930         explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
10931
10932         exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef | 
10933                  prefixexp | tableconstructor | exp binop exp | unop exp 
10934
10935         prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
10936
10937         functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args 
10938
10939         args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString 
10940
10941         functiondef ::= <b>function</b> funcbody
10942
10943         funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
10944
10945         parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
10946
10947         tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
10948
10949         fieldlist ::= field {fieldsep field} [fieldsep]
10950
10951         field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
10952
10953         fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
10954
10955         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; | 
10956                  &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; | 
10957                  &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; | 
10958                  <b>and</b> | <b>or</b>
10959
10960         unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
10961
10962 </pre>
10963
10964 <p>
10965
10966
10967
10968
10969
10970
10971
10972
10973 <P CLASS="footer">
10974 Last update:
10975 Tue Jun 26 13:16:37 -03 2018
10976 </P>
10977 <!--
10978 Last change: revised for Lua 5.3.5
10979 -->
10980
10981 </body></html>
10982