Debian Codegraph @

vendor/lua/doc/manual.html

raw
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <HTML>
3 <HEAD>
4 <TITLE>Lua 5.4 Reference Manual</TITLE>
5 <LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
6 <LINK REL="stylesheet" TYPE="text/css" HREF="manual.css">
7 <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
8 </HEAD>
9
10 <BODY>
11
12 <H1>
13 <A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A>
14 Lua 5.4 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; 2020&ndash;2021 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 $ -->
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 a generational 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
110
111 <p>
112 This section describes the basic concepts of the language.
113
114
115
116
117
118 <h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
119
120 <p>
121 Lua is a dynamically typed language.
122 This means that
123 variables do not have types; only values do.
124 There are no type definitions in the language.
125 All values carry their own type.
126
127
128 <p>
129 All values in Lua are first-class values.
130 This means that all values can be stored in variables,
131 passed as arguments to other functions, and returned as results.
132
133
134 <p>
135 There are eight basic types in Lua:
136 <em>nil</em>, <em>boolean</em>, <em>number</em>,
137 <em>string</em>, <em>function</em>, <em>userdata</em>,
138 <em>thread</em>, and <em>table</em>.
139 The type <em>nil</em> has one single value, <b>nil</b>,
140 whose main property is to be different from any other value;
141 it often represents the absence of a useful value.
142 The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>.
143 Both <b>nil</b> and <b>false</b> make a condition false;
144 they are collectively called <em>false values</em>.
145 Any other value makes a condition true.
146 Despite its name,
147 <b>false</b> is frequently used as an alternative to <b>nil</b>,
148 with the key difference that <b>false</b> behaves
149 like a regular value in a table,
150 while a <b>nil</b> in a table represents an absent key.
151
152
153 <p>
154 The type <em>number</em> represents both
155 integer numbers and real (floating-point) numbers,
156 using two subtypes: <em>integer</em> and <em>float</em>.
157 Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
158 but you can also compile Lua so that it
159 uses 32-bit integers and/or single-precision (32-bit) floats.
160 The option with 32 bits for both integers and floats
161 is particularly attractive
162 for small machines and embedded systems.
163 (See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
164
165
166 <p>
167 Unless stated otherwise,
168 any overflow when manipulating integer values <em>wrap around</em>,
169 according to the usual rules of two-complement arithmetic.
170 (In other words,
171 the actual result is the unique representable integer
172 that is equal modulo <em>2<sup>n</sup></em> to the mathematical result,
173 where <em>n</em> is the number of bits of the integer type.)
174
175
176 <p>
177 Lua has explicit rules about when each subtype is used,
178 but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
179 Therefore,
180 the programmer may choose to mostly ignore the difference
181 between integers and floats
182 or to assume complete control over the representation of each number.
183
184
185 <p>
186 The type <em>string</em> represents immutable sequences of bytes.
187
188 Lua is 8-bit clean:
189 strings can contain any 8-bit value,
190 including embedded zeros ('<code>\0</code>').
191 Lua is also encoding-agnostic;
192 it makes no assumptions about the contents of a string.
193 The length of any string in Lua must fit in a Lua integer.
194
195
196 <p>
197 Lua can call (and manipulate) functions written in Lua and
198 functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
199 Both are represented by the type <em>function</em>.
200
201
202 <p>
203 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
204 be stored in Lua variables.
205 A userdata value represents a block of raw memory.
206 There are two kinds of userdata:
207 <em>full userdata</em>,
208 which is an object with a block of memory managed by Lua,
209 and <em>light userdata</em>,
210 which is simply a C&nbsp;pointer value.
211 Userdata has no predefined operations in Lua,
212 except assignment and identity test.
213 By using <em>metatables</em>,
214 the programmer can define operations for full userdata values
215 (see <a href="#2.4">&sect;2.4</a>).
216 Userdata values cannot be created or modified in Lua,
217 only through the C&nbsp;API.
218 This guarantees the integrity of data owned by
219 the host program and C&nbsp;libraries.
220
221
222 <p>
223 The type <em>thread</em> represents independent threads of execution
224 and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
225 Lua threads are not related to operating-system threads.
226 Lua supports coroutines on all systems,
227 even those that do not support threads natively.
228
229
230 <p>
231 The type <em>table</em> implements associative arrays,
232 that is, arrays that can have as indices not only numbers,
233 but any Lua value except <b>nil</b> and NaN.
234 (<em>Not a Number</em> is a special floating-point value
235 used by the IEEE 754 standard to represent
236 undefined numerical results, such as <code>0/0</code>.)
237 Tables can be <em>heterogeneous</em>;
238 that is, they can contain values of all types (except <b>nil</b>).
239 Any key associated to the value <b>nil</b> is not considered part of the table.
240 Conversely, any key that is not part of a table has
241 an associated value <b>nil</b>.
242
243
244 <p>
245 Tables are the sole data-structuring mechanism in Lua;
246 they can be used to represent ordinary arrays, lists,
247 symbol tables, sets, records, graphs, trees, etc.
248 To represent records, Lua uses the field name as an index.
249 The language supports this representation by
250 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
251 There are several convenient ways to create tables in Lua
252 (see <a href="#3.4.9">&sect;3.4.9</a>).
253
254
255 <p>
256 Like indices,
257 the values of table fields can be of any type.
258 In particular,
259 because functions are first-class values,
260 table fields can contain functions.
261 Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
262
263
264 <p>
265 The indexing of tables follows
266 the definition of raw equality in the language.
267 The expressions <code>a[i]</code> and <code>a[j]</code>
268 denote the same table element
269 if and only if <code>i</code> and <code>j</code> are raw equal
270 (that is, equal without metamethods).
271 In particular, floats with integral values
272 are equal to their respective integers
273 (e.g., <code>1.0 == 1</code>).
274 To avoid ambiguities,
275 any float used as a key that is equal to an integer
276 is converted to that integer.
277 For instance, if you write <code>a[2.0] = true</code>,
278 the actual key inserted into the table will be the integer <code>2</code>.
279
280
281 <p>
282 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
283 variables do not actually <em>contain</em> these values,
284 only <em>references</em> to them.
285 Assignment, parameter passing, and function returns
286 always manipulate references to such values;
287 these operations do not imply any kind of copy.
288
289
290 <p>
291 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
292 of a given value (see <a href="#pdf-type"><code>type</code></a>).
293
294
295
296
297
298 <h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
299
300 <p>
301 As we will discuss further in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
302 any reference to a free name
303 (that is, a name not bound to any declaration) <code>var</code>
304 is syntactically translated to <code>_ENV.var</code>.
305 Moreover, every chunk is compiled in the scope of
306 an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
307 so <code>_ENV</code> itself is never a free name in a chunk.
308
309
310 <p>
311 Despite the existence of this external <code>_ENV</code> variable and
312 the translation of free names,
313 <code>_ENV</code> is a completely regular name.
314 In particular,
315 you can define new variables and parameters with that name.
316 Each reference to a free name uses the <code>_ENV</code> that is
317 visible at that point in the program,
318 following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
319
320
321 <p>
322 Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
323
324
325 <p>
326 Lua keeps a distinguished environment called the <em>global environment</em>.
327 This value is kept at a special index in the C registry (see <a href="#4.3">&sect;4.3</a>).
328 In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
329 (<a href="#pdf-_G"><code>_G</code></a> is never used internally,
330 so changing its value will affect only your own code.)
331
332
333 <p>
334 When Lua loads a chunk,
335 the default value for its <code>_ENV</code> variable
336 is the global environment (see <a href="#pdf-load"><code>load</code></a>).
337 Therefore, by default,
338 free names in Lua code refer to entries in the global environment
339 and, therefore, they are also called <em>global variables</em>.
340 Moreover, all standard libraries are loaded in the global environment
341 and some functions there operate on that environment.
342 You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
343 to load a chunk with a different environment.
344 (In C, you have to load the chunk and then change the value
345 of its first upvalue; see <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.)
346
347
348
349
350
351 <h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
352
353 <p>
354 Several operations in Lua can <em>raise</em> an error.
355 An error interrupts the normal flow of the program,
356 which can continue by <em>catching</em> the error.
357
358
359 <p>
360 Lua code can explicitly raise an error by calling the
361 <a href="#pdf-error"><code>error</code></a> function.
362 (This function never returns.)
363
364
365 <p>
366 To catch errors in Lua,
367 you can do a <em>protected call</em>,
368 using <a href="#pdf-pcall"><code>pcall</code></a> (or <a href="#pdf-xpcall"><code>xpcall</code></a>).
369 The function <a href="#pdf-pcall"><code>pcall</code></a> calls a given function in <em>protected mode</em>.
370 Any error while running the function stops its execution,
371 and control returns immediately to <code>pcall</code>,
372 which returns a status code.
373
374
375 <p>
376 Because Lua is an embedded extension language,
377 Lua code starts running by a call
378 from C&nbsp;code in the host program.
379 (When you use Lua standalone,
380 the <code>lua</code> application is the host program.)
381 Usually, this call is protected;
382 so, when an otherwise unprotected error occurs during
383 the compilation or execution of a Lua chunk,
384 control returns to the host,
385 which can take appropriate measures,
386 such as printing an error message.
387
388
389 <p>
390 Whenever there is an error,
391 an <em>error object</em>
392 is propagated with information about the error.
393 Lua itself only generates errors whose error object is a string,
394 but programs may generate errors with
395 any value as the error object.
396 It is up to the Lua program or its host to handle such error objects.
397 For historical reasons,
398 an error object is often called an <em>error message</em>,
399 even though it does not have to be a string.
400
401
402 <p>
403 When you use <a href="#pdf-xpcall"><code>xpcall</code></a> (or <a href="#lua_pcall"><code>lua_pcall</code></a>, in C)
404 you may give a <em>message handler</em>
405 to be called in case of errors.
406 This function is called with the original error object
407 and returns a new error object.
408 It is called before the error unwinds the stack,
409 so that it can gather more information about the error,
410 for instance by inspecting the stack and creating a stack traceback.
411 This message handler is still protected by the protected call;
412 so, an error inside the message handler
413 will call the message handler again.
414 If this loop goes on for too long,
415 Lua breaks it and returns an appropriate message.
416 The message handler is called only for regular runtime errors.
417 It is not called for memory-allocation errors
418 nor for errors while running finalizers or other message handlers.
419
420
421 <p>
422 Lua also offers a system of <em>warnings</em> (see <a href="#pdf-warn"><code>warn</code></a>).
423 Unlike errors, warnings do not interfere
424 in any way with program execution.
425 They typically only generate a message to the user,
426 although this behavior can be adapted from C (see <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>).
427
428
429
430
431
432 <h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
433
434 <p>
435 Every value in Lua can have a <em>metatable</em>.
436 This <em>metatable</em> is an ordinary Lua table
437 that defines the behavior of the original value
438 under certain events.
439 You can change several aspects of the behavior
440 of a value by setting specific fields in its metatable.
441 For instance, when a non-numeric value is the operand of an addition,
442 Lua checks for a function in the field <code>__add</code> of the value's metatable.
443 If it finds one,
444 Lua calls this function to perform the addition.
445
446
447 <p>
448 The key for each event in a metatable is a string
449 with the event name prefixed by two underscores;
450 the corresponding value is called a <em>metavalue</em>.
451 For most events, the metavalue must be a function,
452 which is then called a <em>metamethod</em>.
453 In the previous example, the key is the string "<code>__add</code>"
454 and the metamethod is the function that performs the addition.
455 Unless stated otherwise,
456 a metamethod may in fact be any callable value,
457 which is either a function or a value with a <code>__call</code> metamethod.
458
459
460 <p>
461 You can query the metatable of any value
462 using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
463 Lua queries metamethods in metatables using a raw access (see <a href="#pdf-rawget"><code>rawget</code></a>).
464
465
466 <p>
467 You can replace the metatable of tables
468 using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
469 You cannot change the metatable of other types from Lua code,
470 except by using the debug library (<a href="#6.10">&sect;6.10</a>).
471
472
473 <p>
474 Tables and full userdata have individual metatables,
475 although multiple tables and userdata can share their metatables.
476 Values of all other types share one single metatable per type;
477 that is, there is one single metatable for all numbers,
478 one for all strings, etc.
479 By default, a value has no metatable,
480 but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
481
482
483 <p>
484 A detailed list of operations controlled by metatables is given next.
485 Each event is identified by its corresponding key.
486 By convention, all metatable keys used by Lua are composed by
487 two underscores followed by lowercase Latin letters.
488
489
490
491 <ul>
492
493 <li><b><code>__add</code>: </b>
494 the addition (<code>+</code>) operation.
495 If any operand for an addition is not a number,
496 Lua will try to call a metamethod.
497 It starts by checking the first operand (even if it is a number);
498 if that operand does not define a metamethod for <code>__add</code>,
499 then Lua will check the second operand.
500 If Lua can find a metamethod,
501 it calls the metamethod with the two operands as arguments,
502 and the result of the call
503 (adjusted to one value)
504 is the result of the operation.
505 Otherwise, if no metamethod is found,
506 Lua raises an error.
507 </li>
508
509 <li><b><code>__sub</code>: </b>
510 the subtraction (<code>-</code>) operation.
511 Behavior similar to the addition operation.
512 </li>
513
514 <li><b><code>__mul</code>: </b>
515 the multiplication (<code>*</code>) operation.
516 Behavior similar to the addition operation.
517 </li>
518
519 <li><b><code>__div</code>: </b>
520 the division (<code>/</code>) operation.
521 Behavior similar to the addition operation.
522 </li>
523
524 <li><b><code>__mod</code>: </b>
525 the modulo (<code>%</code>) operation.
526 Behavior similar to the addition operation.
527 </li>
528
529 <li><b><code>__pow</code>: </b>
530 the exponentiation (<code>^</code>) operation.
531 Behavior similar to the addition operation.
532 </li>
533
534 <li><b><code>__unm</code>: </b>
535 the negation (unary <code>-</code>) operation.
536 Behavior similar to the addition operation.
537 </li>
538
539 <li><b><code>__idiv</code>: </b>
540 the floor division (<code>//</code>) operation.
541 Behavior similar to the addition operation.
542 </li>
543
544 <li><b><code>__band</code>: </b>
545 the bitwise AND (<code>&amp;</code>) operation.
546 Behavior similar to the addition operation,
547 except that Lua will try a metamethod
548 if any operand is neither an integer
549 nor a float coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
550 </li>
551
552 <li><b><code>__bor</code>: </b>
553 the bitwise OR (<code>|</code>) operation.
554 Behavior similar to the bitwise AND operation.
555 </li>
556
557 <li><b><code>__bxor</code>: </b>
558 the bitwise exclusive OR (binary <code>~</code>) operation.
559 Behavior similar to the bitwise AND operation.
560 </li>
561
562 <li><b><code>__bnot</code>: </b>
563 the bitwise NOT (unary <code>~</code>) operation.
564 Behavior similar to the bitwise AND operation.
565 </li>
566
567 <li><b><code>__shl</code>: </b>
568 the bitwise left shift (<code>&lt;&lt;</code>) operation.
569 Behavior similar to the bitwise AND operation.
570 </li>
571
572 <li><b><code>__shr</code>: </b>
573 the bitwise right shift (<code>&gt;&gt;</code>) operation.
574 Behavior similar to the bitwise AND operation.
575 </li>
576
577 <li><b><code>__concat</code>: </b>
578 the concatenation (<code>..</code>) operation.
579 Behavior similar to the addition operation,
580 except that Lua will try a metamethod
581 if any operand is neither a string nor a number
582 (which is always coercible to a string).
583 </li>
584
585 <li><b><code>__len</code>: </b>
586 the length (<code>#</code>) operation.
587 If the object is not a string,
588 Lua will try its metamethod.
589 If there is a metamethod,
590 Lua calls it with the object as argument,
591 and the result of the call
592 (always adjusted to one value)
593 is the result of the operation.
594 If there is no metamethod but the object is a table,
595 then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
596 Otherwise, Lua raises an error.
597 </li>
598
599 <li><b><code>__eq</code>: </b>
600 the equal (<code>==</code>) operation.
601 Behavior similar to the addition operation,
602 except that Lua will try a metamethod only when the values
603 being compared are either both tables or both full userdata
604 and they are not primitively equal.
605 The result of the call is always converted to a boolean.
606 </li>
607
608 <li><b><code>__lt</code>: </b>
609 the less than (<code>&lt;</code>) operation.
610 Behavior similar to the addition operation,
611 except that Lua will try a metamethod only when the values
612 being compared are neither both numbers nor both strings.
613 Moreover, the result of the call is always converted to a boolean.
614 </li>
615
616 <li><b><code>__le</code>: </b>
617 the less equal (<code>&lt;=</code>) operation.
618 Behavior similar to the less than operation.
619 </li>
620
621 <li><b><code>__index</code>: </b>
622 The indexing access operation <code>table[key]</code>.
623 This event happens when <code>table</code> is not a table or
624 when <code>key</code> is not present in <code>table</code>.
625 The metavalue is looked up in the metatable of <code>table</code>.
626
627
628 <p>
629 The metavalue for this event can be either a function, a table,
630 or any value with an <code>__index</code> metavalue.
631 If it is a function,
632 it is called with <code>table</code> and <code>key</code> as arguments,
633 and the result of the call
634 (adjusted to one value)
635 is the result of the operation.
636 Otherwise,
637 the final result is the result of indexing this metavalue with <code>key</code>.
638 This indexing is regular, not raw,
639 and therefore can trigger another <code>__index</code> metavalue.
640 </li>
641
642 <li><b><code>__newindex</code>: </b>
643 The indexing assignment <code>table[key] = value</code>.
644 Like the index event,
645 this event happens when <code>table</code> is not a table or
646 when <code>key</code> is not present in <code>table</code>.
647 The metavalue is looked up in the metatable of <code>table</code>.
648
649
650 <p>
651 Like with indexing,
652 the metavalue for this event can be either a function, a table,
653 or any value with an <code>__newindex</code> metavalue.
654 If it is a function,
655 it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
656 Otherwise,
657 Lua repeats the indexing assignment over this metavalue
658 with the same key and value.
659 This assignment is regular, not raw,
660 and therefore can trigger another <code>__newindex</code> metavalue.
661
662
663 <p>
664 Whenever a <code>__newindex</code> metavalue is invoked,
665 Lua does not perform the primitive assignment.
666 If needed,
667 the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
668 to do the assignment.
669 </li>
670
671 <li><b><code>__call</code>: </b>
672 The call operation <code>func(args)</code>.
673 This event happens when Lua tries to call a non-function value
674 (that is, <code>func</code> is not a function).
675 The metamethod is looked up in <code>func</code>.
676 If present,
677 the metamethod is called with <code>func</code> as its first argument,
678 followed by the arguments of the original call (<code>args</code>).
679 All results of the call
680 are the results of the operation.
681 This is the only metamethod that allows multiple results.
682 </li>
683
684 </ul>
685
686 <p>
687 In addition to the previous list,
688 the interpreter also respects the following keys in metatables:
689 <code>__gc</code> (see <a href="#2.5.3">&sect;2.5.3</a>),
690 <code>__close</code> (see <a href="#3.3.8">&sect;3.3.8</a>),
691 <code>__mode</code> (see <a href="#2.5.4">&sect;2.5.4</a>),
692 and <code>__name</code>.
693 (The entry <code>__name</code>,
694 when it contains a string,
695 may be used by <a href="#pdf-tostring"><code>tostring</code></a> and in error messages.)
696
697
698 <p>
699 For the unary operators (negation, length, and bitwise NOT),
700 the metamethod is computed and called with a dummy second operand,
701 equal to the first one.
702 This extra operand is only to simplify Lua's internals
703 (by making these operators behave like a binary operation)
704 and may be removed in future versions.
705 For most uses this extra operand is irrelevant.
706
707
708 <p>
709 Because metatables are regular tables,
710 they can contain arbitrary fields,
711 not only the event names defined above.
712 Some functions in the standard library
713 (e.g., <a href="#pdf-tostring"><code>tostring</code></a>)
714 use other fields in metatables for their own purposes.
715
716
717 <p>
718 It is a good practice to add all needed metamethods to a table
719 before setting it as a metatable of some object.
720 In particular, the <code>__gc</code> metamethod works only when this order
721 is followed (see <a href="#2.5.3">&sect;2.5.3</a>).
722 It is also a good practice to set the metatable of an object
723 right after its creation.
724
725
726
727
728
729 <h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
730
731
732
733 <p>
734 Lua performs automatic memory management.
735 This means that
736 you do not have to worry about allocating memory for new objects
737 or freeing it when the objects are no longer needed.
738 Lua manages memory automatically by running
739 a <em>garbage collector</em> to collect all <em>dead</em> objects.
740 All memory used by Lua is subject to automatic management:
741 strings, tables, userdata, functions, threads, internal structures, etc.
742
743
744 <p>
745 An object is considered <em>dead</em>
746 as soon as the collector can be sure the object
747 will not be accessed again in the normal execution of the program.
748 ("Normal execution" here excludes finalizers,
749 which can resurrect dead objects (see <a href="#2.5.3">&sect;2.5.3</a>),
750 and excludes also operations using the debug library.)
751 Note that the time when the collector can be sure that an object
752 is dead may not coincide with the programmer's expectations.
753 The only guarantees are that Lua will not collect an object
754 that may still be accessed in the normal execution of the program,
755 and it will eventually collect an object
756 that is inaccessible from Lua.
757 (Here,
758 <em>inaccessible from Lua</em> means that neither a variable nor
759 another live object refer to the object.)
760 Because Lua has no knowledge about C&nbsp;code,
761 it never collects objects accessible through the registry (see <a href="#4.3">&sect;4.3</a>),
762 which includes the global environment (see <a href="#2.2">&sect;2.2</a>).
763
764
765 <p>
766 The garbage collector (GC) in Lua can work in two modes:
767 incremental and generational.
768
769
770 <p>
771 The default GC mode with the default parameters
772 are adequate for most uses.
773 However, programs that waste a large proportion of their time
774 allocating and freeing memory can benefit from other settings.
775 Keep in mind that the GC behavior is non-portable
776 both across platforms and across different Lua releases;
777 therefore, optimal settings are also non-portable.
778
779
780 <p>
781 You can change the GC mode and parameters by calling
782 <a href="#lua_gc"><code>lua_gc</code></a> in&nbsp;C
783 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
784 You can also use these functions to control
785 the collector directly (e.g., to stop and restart it).
786
787
788
789
790
791 <h3>2.5.1 &ndash; <a name="2.5.1">Incremental Garbage Collection</a></h3>
792
793 <p>
794 In incremental mode,
795 each GC cycle performs a mark-and-sweep collection in small steps
796 interleaved with the program's execution.
797 In this mode,
798 the collector uses three numbers to control its garbage-collection cycles:
799 the <em>garbage-collector pause</em>,
800 the <em>garbage-collector step multiplier</em>,
801 and the <em>garbage-collector step size</em>.
802
803
804 <p>
805 The garbage-collector pause
806 controls how long the collector waits before starting a new cycle.
807 The collector starts a new cycle when the use of memory
808 hits <em>n%</em> of the use after the previous collection.
809 Larger values make the collector less aggressive.
810 Values equal to or less than 100 mean the collector will not wait to
811 start a new cycle.
812 A value of 200 means that the collector waits for the total memory in use
813 to double before starting a new cycle.
814 The default value is 200; the maximum value is 1000.
815
816
817 <p>
818 The garbage-collector step multiplier
819 controls the speed of the collector relative to
820 memory allocation,
821 that is,
822 how many elements it marks or sweeps for each
823 kilobyte of memory allocated.
824 Larger values make the collector more aggressive but also increase
825 the size of each incremental step.
826 You should not use values less than 100,
827 because they make the collector too slow and
828 can result in the collector never finishing a cycle.
829 The default value is 100; the maximum value is 1000.
830
831
832 <p>
833 The garbage-collector step size controls the
834 size of each incremental step,
835 specifically how many bytes the interpreter allocates
836 before performing a step.
837 This parameter is logarithmic:
838 A value of <em>n</em> means the interpreter will allocate <em>2<sup>n</sup></em>
839 bytes between steps and perform equivalent work during the step.
840 A large value (e.g., 60) makes the collector a stop-the-world
841 (non-incremental) collector.
842 The default value is 13,
843 which means steps of approximately 8&nbsp;Kbytes.
844
845
846
847
848
849 <h3>2.5.2 &ndash; <a name="2.5.2">Generational Garbage Collection</a></h3>
850
851 <p>
852 In generational mode,
853 the collector does frequent <em>minor</em> collections,
854 which traverses only objects recently created.
855 If after a minor collection the use of memory is still above a limit,
856 the collector does a stop-the-world <em>major</em> collection,
857 which traverses all objects.
858 The generational mode uses two parameters:
859 the <em>minor multiplier</em> and the <em>the major multiplier</em>.
860
861
862 <p>
863 The minor multiplier controls the frequency of minor collections.
864 For a minor multiplier <em>x</em>,
865 a new minor collection will be done when memory
866 grows <em>x%</em> larger than the memory in use after the previous major
867 collection.
868 For instance, for a multiplier of 20,
869 the collector will do a minor collection when the use of memory
870 gets 20% larger than the use after the previous major collection.
871 The default value is 20; the maximum value is 200.
872
873
874 <p>
875 The major multiplier controls the frequency of major collections.
876 For a major multiplier <em>x</em>,
877 a new major collection will be done when memory
878 grows <em>x%</em> larger than the memory in use after the previous major
879 collection.
880 For instance, for a multiplier of 100,
881 the collector will do a major collection when the use of memory
882 gets larger than twice the use after the previous collection.
883 The default value is 100; the maximum value is 1000.
884
885
886
887
888
889 <h3>2.5.3 &ndash; <a name="2.5.3">Garbage-Collection Metamethods</a></h3>
890
891 <p>
892 You can set garbage-collector metamethods for tables
893 and, using the C&nbsp;API,
894 for full userdata (see <a href="#2.4">&sect;2.4</a>).
895 These metamethods, called <em>finalizers</em>,
896 are called when the garbage collector detects that the
897 corresponding table or userdata is dead.
898 Finalizers allow you to coordinate Lua's garbage collection
899 with external resource management such as closing files,
900 network or database connections,
901 or freeing your own memory.
902
903
904 <p>
905 For an object (table or userdata) to be finalized when collected,
906 you must <em>mark</em> it for finalization.
907
908 You mark an object for finalization when you set its metatable
909 and the metatable has a <code>__gc</code> metamethod.
910 Note that if you set a metatable without a <code>__gc</code> field
911 and later create that field in the metatable,
912 the object will not be marked for finalization.
913
914
915 <p>
916 When a marked object becomes dead,
917 it is not collected immediately by the garbage collector.
918 Instead, Lua puts it in a list.
919 After the collection,
920 Lua goes through that list.
921 For each object in the list,
922 it checks the object's <code>__gc</code> metamethod:
923 If it is present,
924 Lua calls it with the object as its single argument.
925
926
927 <p>
928 At the end of each garbage-collection cycle,
929 the finalizers are called in
930 the reverse order that the objects were marked for finalization,
931 among those collected in that cycle;
932 that is, the first finalizer to be called is the one associated
933 with the object marked last in the program.
934 The execution of each finalizer may occur at any point during
935 the execution of the regular code.
936
937
938 <p>
939 Because the object being collected must still be used by the finalizer,
940 that object (and other objects accessible only through it)
941 must be <em>resurrected</em> by Lua.
942 Usually, this resurrection is transient,
943 and the object memory is freed in the next garbage-collection cycle.
944 However, if the finalizer stores the object in some global place
945 (e.g., a global variable),
946 then the resurrection is permanent.
947 Moreover, if the finalizer marks a finalizing object for finalization again,
948 its finalizer will be called again in the next cycle where the
949 object is dead.
950 In any case,
951 the object memory is freed only in a GC cycle where
952 the object is dead and not marked for finalization.
953
954
955 <p>
956 When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
957 Lua calls the finalizers of all objects marked for finalization,
958 following the reverse order that they were marked.
959 If any finalizer marks objects for collection during that phase,
960 these marks have no effect.
961
962
963 <p>
964 Finalizers cannot yield.
965 Except for that, they can do anything,
966 such as raise errors, create new objects,
967 or even run the garbage collector.
968 However, because they can run in unpredictable times,
969 it is good practice to restrict each finalizer
970 to the minimum necessary to properly release
971 its associated resource.
972
973
974 <p>
975 Any error while running a finalizer generates a warning;
976 the error is not propagated.
977
978
979
980
981
982 <h3>2.5.4 &ndash; <a name="2.5.4">Weak Tables</a></h3>
983
984 <p>
985 A <em>weak table</em> is a table whose elements are
986 <em>weak references</em>.
987 A weak reference is ignored by the garbage collector.
988 In other words,
989 if the only references to an object are weak references,
990 then the garbage collector will collect that object.
991
992
993 <p>
994 A weak table can have weak keys, weak values, or both.
995 A table with weak values allows the collection of its values,
996 but prevents the collection of its keys.
997 A table with both weak keys and weak values allows the collection of
998 both keys and values.
999 In any case, if either the key or the value is collected,
1000 the whole pair is removed from the table.
1001 The weakness of a table is controlled by the
1002 <code>__mode</code> field of its metatable.
1003 This metavalue, if present, must be one of the following strings:
1004 "<code>k</code>", for a table with weak keys;
1005 "<code>v</code>", for a table with weak values;
1006 or "<code>kv</code>", for a table with both weak keys and values.
1007
1008
1009 <p>
1010 A table with weak keys and strong values
1011 is also called an <em>ephemeron table</em>.
1012 In an ephemeron table,
1013 a value is considered reachable only if its key is reachable.
1014 In particular,
1015 if the only reference to a key comes through its value,
1016 the pair is removed.
1017
1018
1019 <p>
1020 Any change in the weakness of a table may take effect only
1021 at the next collect cycle.
1022 In particular, if you change the weakness to a stronger mode,
1023 Lua may still collect some items from that table
1024 before the change takes effect.
1025
1026
1027 <p>
1028 Only objects that have an explicit construction
1029 are removed from weak tables.
1030 Values, such as numbers and light C&nbsp;functions,
1031 are not subject to garbage collection,
1032 and therefore are not removed from weak tables
1033 (unless their associated values are collected).
1034 Although strings are subject to garbage collection,
1035 they do not have an explicit construction and
1036 their equality is by value;
1037 they behave more like values than like objects.
1038 Therefore, they are not removed from weak tables.
1039
1040
1041 <p>
1042 Resurrected objects
1043 (that is, objects being finalized
1044 and objects accessible only through objects being finalized)
1045 have a special behavior in weak tables.
1046 They are removed from weak values before running their finalizers,
1047 but are removed from weak keys only in the next collection
1048 after running their finalizers, when such objects are actually freed.
1049 This behavior allows the finalizer to access properties
1050 associated with the object through weak tables.
1051
1052
1053 <p>
1054 If a weak table is among the resurrected objects in a collection cycle,
1055 it may not be properly cleared until the next cycle.
1056
1057
1058
1059
1060
1061
1062
1063 <h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
1064
1065 <p>
1066 Lua supports coroutines,
1067 also called <em>collaborative multithreading</em>.
1068 A coroutine in Lua represents an independent thread of execution.
1069 Unlike threads in multithread systems, however,
1070 a coroutine only suspends its execution by explicitly calling
1071 a yield function.
1072
1073
1074 <p>
1075 You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1076 Its sole argument is a function
1077 that is the main function of the coroutine.
1078 The <code>create</code> function only creates a new coroutine and
1079 returns a handle to it (an object of type <em>thread</em>);
1080 it does not start the coroutine.
1081
1082
1083 <p>
1084 You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1085 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1086 passing as its first argument
1087 a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1088 the coroutine starts its execution by
1089 calling its main function.
1090 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
1091 as arguments to that function.
1092 After the coroutine starts running,
1093 it runs until it terminates or <em>yields</em>.
1094
1095
1096 <p>
1097 A coroutine can terminate its execution in two ways:
1098 normally, when its main function returns
1099 (explicitly or implicitly, after the last instruction);
1100 and abnormally, if there is an unprotected error.
1101 In case of normal termination,
1102 <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1103 plus any values returned by the coroutine main function.
1104 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1105 plus the error object.
1106 In this case, the coroutine does not unwind its stack,
1107 so that it is possible to inspect it after the error
1108 with the debug API.
1109
1110
1111 <p>
1112 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1113 When a coroutine yields,
1114 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1115 even if the yield happens inside nested function calls
1116 (that is, not in the main function,
1117 but in a function directly or indirectly called by the main function).
1118 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1119 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1120 The next time you resume the same coroutine,
1121 it continues its execution from the point where it yielded,
1122 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1123 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1124
1125
1126 <p>
1127 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1128 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1129 but instead of returning the coroutine itself,
1130 it returns a function that, when called, resumes the coroutine.
1131 Any arguments passed to this function
1132 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1133 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1134 except the first one (the boolean error code).
1135 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1136 the function created by <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>
1137 propagates any error to the caller.
1138 In this case,
1139 the function also closes the coroutine (see <a href="#pdf-coroutine.close"><code>coroutine.close</code></a>).
1140
1141
1142 <p>
1143 As an example of how coroutines work,
1144 consider the following code:
1145
1146 <pre>
1147 function foo (a)
1148 print("foo", a)
1149 return coroutine.yield(2*a)
1150 end
1151
1152 co = coroutine.create(function (a,b)
1153 print("co-body", a, b)
1154 local r = foo(a+1)
1155 print("co-body", r)
1156 local r, s = coroutine.yield(a+b, a-b)
1157 print("co-body", r, s)
1158 return b, "end"
1159 end)
1160
1161 print("main", coroutine.resume(co, 1, 10))
1162 print("main", coroutine.resume(co, "r"))
1163 print("main", coroutine.resume(co, "x", "y"))
1164 print("main", coroutine.resume(co, "x", "y"))
1165 </pre><p>
1166 When you run it, it produces the following output:
1167
1168 <pre>
1169 co-body 1 10
1170 foo 2
1171 main true 4
1172 co-body r
1173 main true 11 -9
1174 co-body x y
1175 main true 10 end
1176 main false cannot resume dead coroutine
1177 </pre>
1178
1179 <p>
1180 You can also create and manipulate coroutines through the C API:
1181 see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1182 and <a href="#lua_yield"><code>lua_yield</code></a>.
1183
1184
1185
1186
1187
1188 <h1>3 &ndash; <a name="3">The Language</a></h1>
1189
1190
1191
1192 <p>
1193 This section describes the lexis, the syntax, and the semantics of Lua.
1194 In other words,
1195 this section describes
1196 which tokens are valid,
1197 how they can be combined,
1198 and what their combinations mean.
1199
1200
1201 <p>
1202 Language constructs will be explained using the usual extended BNF notation,
1203 in which
1204 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1205 [<em>a</em>]&nbsp;means an optional <em>a</em>.
1206 Non-terminals are shown like non-terminal,
1207 keywords are shown like <b>kword</b>,
1208 and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1209 The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1210 at the end of this manual.
1211
1212
1213
1214
1215
1216 <h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1217
1218 <p>
1219 Lua is a free-form language.
1220 It ignores spaces and comments between lexical elements (tokens),
1221 except as delimiters between two tokens.
1222 In source code,
1223 Lua recognizes as spaces the standard ASCII whitespace
1224 characters space, form feed, newline,
1225 carriage return, horizontal tab, and vertical tab.
1226
1227
1228 <p>
1229 <em>Names</em>
1230 (also called <em>identifiers</em>)
1231 in Lua can be any string of Latin letters,
1232 Arabic-Indic digits, and underscores,
1233 not beginning with a digit and
1234 not being a reserved word.
1235 Identifiers are used to name variables, table fields, and labels.
1236
1237
1238 <p>
1239 The following <em>keywords</em> are reserved
1240 and cannot be used as names:
1241
1242
1243 <pre>
1244 and break do else elseif end
1245 false for function goto if in
1246 local nil not or repeat return
1247 then true until while
1248 </pre>
1249
1250 <p>
1251 Lua is a case-sensitive language:
1252 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1253 are two different, valid names.
1254 As a convention,
1255 programs should avoid creating
1256 names that start with an underscore followed by
1257 one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1258
1259
1260 <p>
1261 The following strings denote other tokens:
1262
1263 <pre>
1264 + - * / % ^ #
1265 &amp; ~ | &lt;&lt; &gt;&gt; //
1266 == ~= &lt;= &gt;= &lt; &gt; =
1267 ( ) { } [ ] ::
1268 ; : , . .. ...
1269 </pre>
1270
1271 <p>
1272 A <em>short literal string</em>
1273 can be delimited by matching single or double quotes,
1274 and can contain the following C-like escape sequences:
1275 '<code>\a</code>' (bell),
1276 '<code>\b</code>' (backspace),
1277 '<code>\f</code>' (form feed),
1278 '<code>\n</code>' (newline),
1279 '<code>\r</code>' (carriage return),
1280 '<code>\t</code>' (horizontal tab),
1281 '<code>\v</code>' (vertical tab),
1282 '<code>\\</code>' (backslash),
1283 '<code>\"</code>' (quotation mark [double quote]),
1284 and '<code>\'</code>' (apostrophe [single quote]).
1285 A backslash followed by a line break
1286 results in a newline in the string.
1287 The escape sequence '<code>\z</code>' skips the following span
1288 of whitespace characters,
1289 including line breaks;
1290 it is particularly useful to break and indent a long literal string
1291 into multiple lines without adding the newlines and spaces
1292 into the string contents.
1293 A short literal string cannot contain unescaped line breaks
1294 nor escapes not forming a valid escape sequence.
1295
1296
1297 <p>
1298 We can specify any byte in a short literal string,
1299 including embedded zeros,
1300 by its numeric value.
1301 This can be done
1302 with the escape sequence <code>\x<em>XX</em></code>,
1303 where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1304 or with the escape sequence <code>\<em>ddd</em></code>,
1305 where <em>ddd</em> is a sequence of up to three decimal digits.
1306 (Note that if a decimal escape sequence is to be followed by a digit,
1307 it must be expressed using exactly three digits.)
1308
1309
1310 <p>
1311 The UTF-8 encoding of a Unicode character
1312 can be inserted in a literal string with
1313 the escape sequence <code>\u{<em>XXX</em>}</code>
1314 (with mandatory enclosing braces),
1315 where <em>XXX</em> is a sequence of one or more hexadecimal digits
1316 representing the character code point.
1317 This code point can be any value less than <em>2<sup>31</sup></em>.
1318 (Lua uses the original UTF-8 specification here,
1319 which is not restricted to valid Unicode code points.)
1320
1321
1322 <p>
1323 Literal strings can also be defined using a long format
1324 enclosed by <em>long brackets</em>.
1325 We define an <em>opening long bracket of level <em>n</em></em> as an opening
1326 square bracket followed by <em>n</em> equal signs followed by another
1327 opening square bracket.
1328 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1329 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1330 and so on.
1331 A <em>closing long bracket</em> is defined similarly;
1332 for instance,
1333 a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
1334 A <em>long literal</em> starts with an opening long bracket of any level and
1335 ends at the first closing long bracket of the same level.
1336 It can contain any text except a closing bracket of the same level.
1337 Literals in this bracketed form can run for several lines,
1338 do not interpret any escape sequences,
1339 and ignore long brackets of any other level.
1340 Any kind of end-of-line sequence
1341 (carriage return, newline, carriage return followed by newline,
1342 or newline followed by carriage return)
1343 is converted to a simple newline.
1344 When the opening long bracket is immediately followed by a newline,
1345 the newline is not included in the string.
1346
1347
1348 <p>
1349 As an example, in a system using ASCII
1350 (in which '<code>a</code>' is coded as&nbsp;97,
1351 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1352 the five literal strings below denote the same string:
1353
1354 <pre>
1355 a = 'alo\n123"'
1356 a = "alo\n123\""
1357 a = '\97lo\10\04923"'
1358 a = [[alo
1359 123"]]
1360 a = [==[
1361 alo
1362 123"]==]
1363 </pre>
1364
1365 <p>
1366 Any byte in a literal string not
1367 explicitly affected by the previous rules represents itself.
1368 However, Lua opens files for parsing in text mode,
1369 and the system's file functions may have problems with
1370 some control characters.
1371 So, it is safer to represent
1372 binary data as a quoted literal with
1373 explicit escape sequences for the non-text characters.
1374
1375
1376 <p>
1377 A <em>numeric constant</em> (or <em>numeral</em>)
1378 can be written with an optional fractional part
1379 and an optional decimal exponent,
1380 marked by a letter '<code>e</code>' or '<code>E</code>'.
1381 Lua also accepts hexadecimal constants,
1382 which start with <code>0x</code> or <code>0X</code>.
1383 Hexadecimal constants also accept an optional fractional part
1384 plus an optional binary exponent,
1385 marked by a letter '<code>p</code>' or '<code>P</code>'.
1386
1387
1388 <p>
1389 A numeric constant with a radix point or an exponent
1390 denotes a float;
1391 otherwise,
1392 if its value fits in an integer or it is a hexadecimal constant,
1393 it denotes an integer;
1394 otherwise (that is, a decimal integer numeral that overflows),
1395 it denotes a float.
1396 Hexadecimal numerals with neither a radix point nor an exponent
1397 always denote an integer value;
1398 if the value overflows, it <em>wraps around</em>
1399 to fit into a valid integer.
1400
1401
1402 <p>
1403 Examples of valid integer constants are
1404
1405 <pre>
1406 3 345 0xff 0xBEBADA
1407 </pre><p>
1408 Examples of valid float constants are
1409
1410 <pre>
1411 3.0 3.1416 314.16e-2 0.31416E1 34e1
1412 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1413 </pre>
1414
1415 <p>
1416 A <em>comment</em> starts with a double hyphen (<code>--</code>)
1417 anywhere outside a string.
1418 If the text immediately after <code>--</code> is not an opening long bracket,
1419 the comment is a <em>short comment</em>,
1420 which runs until the end of the line.
1421 Otherwise, it is a <em>long comment</em>,
1422 which runs until the corresponding closing long bracket.
1423
1424
1425
1426
1427
1428 <h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1429
1430 <p>
1431 Variables are places that store values.
1432 There are three kinds of variables in Lua:
1433 global variables, local variables, and table fields.
1434
1435
1436 <p>
1437 A single name can denote a global variable or a local variable
1438 (or a function's formal parameter,
1439 which is a particular kind of local variable):
1440
1441 <pre>
1442 var ::= Name
1443 </pre><p>
1444 Name denotes identifiers (see <a href="#3.1">&sect;3.1</a>).
1445
1446
1447 <p>
1448 Any variable name is assumed to be global unless explicitly declared
1449 as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1450 Local variables are <em>lexically scoped</em>:
1451 local variables can be freely accessed by functions
1452 defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1453
1454
1455 <p>
1456 Before the first assignment to a variable, its value is <b>nil</b>.
1457
1458
1459 <p>
1460 Square brackets are used to index a table:
1461
1462 <pre>
1463 var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1464 </pre><p>
1465 The meaning of accesses to table fields can be changed via metatables
1466 (see <a href="#2.4">&sect;2.4</a>).
1467
1468
1469 <p>
1470 The syntax <code>var.Name</code> is just syntactic sugar for
1471 <code>var["Name"]</code>:
1472
1473 <pre>
1474 var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1475 </pre>
1476
1477 <p>
1478 An access to a global variable <code>x</code>
1479 is equivalent to <code>_ENV.x</code>.
1480 Due to the way that chunks are compiled,
1481 the variable <code>_ENV</code> itself is never global (see <a href="#2.2">&sect;2.2</a>).
1482
1483
1484
1485
1486
1487 <h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1488
1489
1490
1491 <p>
1492 Lua supports an almost conventional set of statements,
1493 similar to those in other conventional languages.
1494 This set includes
1495 blocks, assignments, control structures, function calls,
1496 and variable declarations.
1497
1498
1499
1500
1501
1502 <h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1503
1504 <p>
1505 A block is a list of statements,
1506 which are executed sequentially:
1507
1508 <pre>
1509 block ::= {stat}
1510 </pre><p>
1511 Lua has <em>empty statements</em>
1512 that allow you to separate statements with semicolons,
1513 start a block with a semicolon
1514 or write two semicolons in sequence:
1515
1516 <pre>
1517 stat ::= &lsquo;<b>;</b>&rsquo;
1518 </pre>
1519
1520 <p>
1521 Both function calls and assignments
1522 can start with an open parenthesis.
1523 This possibility leads to an ambiguity in Lua's grammar.
1524 Consider the following fragment:
1525
1526 <pre>
1527 a = b + c
1528 (print or io.write)('done')
1529 </pre><p>
1530 The grammar could see this fragment in two ways:
1531
1532 <pre>
1533 a = b + c(print or io.write)('done')
1534
1535 a = b + c; (print or io.write)('done')
1536 </pre><p>
1537 The current parser always sees such constructions
1538 in the first way,
1539 interpreting the open parenthesis
1540 as the start of the arguments to a call.
1541 To avoid this ambiguity,
1542 it is a good practice to always precede with a semicolon
1543 statements that start with a parenthesis:
1544
1545 <pre>
1546 ;(print or io.write)('done')
1547 </pre>
1548
1549 <p>
1550 A block can be explicitly delimited to produce a single statement:
1551
1552 <pre>
1553 stat ::= <b>do</b> block <b>end</b>
1554 </pre><p>
1555 Explicit blocks are useful
1556 to control the scope of variable declarations.
1557 Explicit blocks are also sometimes used to
1558 add a <b>return</b> statement in the middle
1559 of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1560
1561
1562
1563
1564
1565 <h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1566
1567 <p>
1568 The unit of compilation of Lua is called a <em>chunk</em>.
1569 Syntactically,
1570 a chunk is simply a block:
1571
1572 <pre>
1573 chunk ::= block
1574 </pre>
1575
1576 <p>
1577 Lua handles a chunk as the body of an anonymous function
1578 with a variable number of arguments
1579 (see <a href="#3.4.11">&sect;3.4.11</a>).
1580 As such, chunks can define local variables,
1581 receive arguments, and return values.
1582 Moreover, such anonymous function is compiled as in the
1583 scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1584 The resulting function always has <code>_ENV</code> as its only external variable,
1585 even if it does not use that variable.
1586
1587
1588 <p>
1589 A chunk can be stored in a file or in a string inside the host program.
1590 To execute a chunk,
1591 Lua first <em>loads</em> it,
1592 precompiling the chunk's code into instructions for a virtual machine,
1593 and then Lua executes the compiled code
1594 with an interpreter for the virtual machine.
1595
1596
1597 <p>
1598 Chunks can also be precompiled into binary form;
1599 see the program <code>luac</code> and the function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1600 Programs in source and compiled forms are interchangeable;
1601 Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1602
1603
1604
1605
1606
1607 <h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1608
1609 <p>
1610 Lua allows multiple assignments.
1611 Therefore, the syntax for assignment
1612 defines a list of variables on the left side
1613 and a list of expressions on the right side.
1614 The elements in both lists are separated by commas:
1615
1616 <pre>
1617 stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1618 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1619 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1620 </pre><p>
1621 Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1622
1623
1624 <p>
1625 Before the assignment,
1626 the list of values is <em>adjusted</em> to the length of
1627 the list of variables.
1628 If there are more values than needed,
1629 the excess values are thrown away.
1630 If there are fewer values than needed,
1631 the list is extended with <b>nil</b>'s.
1632 If the list of expressions ends with a function call,
1633 then all values returned by that call enter the list of values,
1634 before the adjustment
1635 (except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1636
1637
1638 <p>
1639 The assignment statement first evaluates all its expressions
1640 and only then the assignments are performed.
1641 Thus the code
1642
1643 <pre>
1644 i = 3
1645 i, a[i] = i+1, 20
1646 </pre><p>
1647 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1648 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1649 before it is assigned&nbsp;4.
1650 Similarly, the line
1651
1652 <pre>
1653 x, y = y, x
1654 </pre><p>
1655 exchanges the values of <code>x</code> and <code>y</code>,
1656 and
1657
1658 <pre>
1659 x, y, z = y, z, x
1660 </pre><p>
1661 cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1662
1663
1664 <p>
1665 An assignment to a global name <code>x = val</code>
1666 is equivalent to the assignment
1667 <code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1668
1669
1670 <p>
1671 The meaning of assignments to table fields and
1672 global variables (which are actually table fields, too)
1673 can be changed via metatables (see <a href="#2.4">&sect;2.4</a>).
1674
1675
1676
1677
1678
1679 <h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1680 The control structures
1681 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1682 familiar syntax:
1683
1684
1685
1686
1687 <pre>
1688 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1689 stat ::= <b>repeat</b> block <b>until</b> exp
1690 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1691 </pre><p>
1692 Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1693
1694
1695 <p>
1696 The condition expression of a
1697 control structure can return any value.
1698 Both <b>false</b> and <b>nil</b> test false.
1699 All values different from <b>nil</b> and <b>false</b> test true.
1700 In particular, the number 0 and the empty string also test true.
1701
1702
1703 <p>
1704 In the <b>repeat</b>&ndash;<b>until</b> loop,
1705 the inner block does not end at the <b>until</b> keyword,
1706 but only after the condition.
1707 So, the condition can refer to local variables
1708 declared inside the loop block.
1709
1710
1711 <p>
1712 The <b>goto</b> statement transfers the program control to a label.
1713 For syntactical reasons,
1714 labels in Lua are considered statements too:
1715
1716
1717
1718 <pre>
1719 stat ::= <b>goto</b> Name
1720 stat ::= label
1721 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1722 </pre>
1723
1724 <p>
1725 A label is visible in the entire block where it is defined,
1726 except inside nested functions.
1727 A goto may jump to any visible label as long as it does not
1728 enter into the scope of a local variable.
1729 A label should not be declared
1730 where a label with the same name is visible,
1731 even if this other label has been declared in an enclosing block.
1732
1733
1734 <p>
1735 Labels and empty statements are called <em>void statements</em>,
1736 as they perform no actions.
1737
1738
1739 <p>
1740 The <b>break</b> statement terminates the execution of a
1741 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1742 skipping to the next statement after the loop:
1743
1744
1745 <pre>
1746 stat ::= <b>break</b>
1747 </pre><p>
1748 A <b>break</b> ends the innermost enclosing loop.
1749
1750
1751 <p>
1752 The <b>return</b> statement is used to return values
1753 from a function or a chunk
1754 (which is handled as an anonymous function).
1755
1756 Functions can return more than one value,
1757 so the syntax for the <b>return</b> statement is
1758
1759 <pre>
1760 stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1761 </pre>
1762
1763 <p>
1764 The <b>return</b> statement can only be written
1765 as the last statement of a block.
1766 If it is necessary to <b>return</b> in the middle of a block,
1767 then an explicit inner block can be used,
1768 as in the idiom <code>do return end</code>,
1769 because now <b>return</b> is the last statement in its (inner) block.
1770
1771
1772
1773
1774
1775 <h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1776
1777 <p>
1778
1779 The <b>for</b> statement has two forms:
1780 one numerical and one generic.
1781
1782
1783
1784 <h4>The numerical <b>for</b> loop</h4>
1785
1786 <p>
1787 The numerical <b>for</b> loop repeats a block of code while a
1788 control variable goes through an arithmetic progression.
1789 It has the following syntax:
1790
1791 <pre>
1792 stat ::= <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b>
1793 </pre><p>
1794 The given identifier (Name) defines the control variable,
1795 which is a new variable local to the loop body (<em>block</em>).
1796
1797
1798 <p>
1799 The loop starts by evaluating once the three control expressions.
1800 Their values are called respectively
1801 the <em>initial value</em>, the <em>limit</em>, and the <em>step</em>.
1802 If the step is absent, it defaults to&nbsp;1.
1803
1804
1805 <p>
1806 If both the initial value and the step are integers,
1807 the loop is done with integers;
1808 note that the limit may not be an integer.
1809 Otherwise, the three values are converted to
1810 floats and the loop is done with floats.
1811 Beware of floating-point accuracy in this case.
1812
1813
1814 <p>
1815 After that initialization,
1816 the loop body is repeated with the value of the control variable
1817 going through an arithmetic progression,
1818 starting at the initial value,
1819 with a common difference given by the step.
1820 A negative step makes a decreasing sequence;
1821 a step equal to zero raises an error.
1822 The loop continues while the value is less than
1823 or equal to the limit
1824 (greater than or equal to for a negative step).
1825 If the initial value is already greater than the limit
1826 (or less than, if the step is negative),
1827 the body is not executed.
1828
1829
1830 <p>
1831 For integer loops,
1832 the control variable never wraps around;
1833 instead, the loop ends in case of an overflow.
1834
1835
1836 <p>
1837 You should not change the value of the control variable
1838 during the loop.
1839 If you need its value after the loop,
1840 assign it to another variable before exiting the loop.
1841
1842
1843
1844
1845
1846 <h4>The generic <b>for</b> loop</h4>
1847
1848 <p>
1849 The generic <b>for</b> statement works over functions,
1850 called <em>iterators</em>.
1851 On each iteration, the iterator function is called to produce a new value,
1852 stopping when this new value is <b>nil</b>.
1853 The generic <b>for</b> loop has the following syntax:
1854
1855 <pre>
1856 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1857 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1858 </pre><p>
1859 A <b>for</b> statement like
1860
1861 <pre>
1862 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>body</em> end
1863 </pre><p>
1864 works as follows.
1865
1866
1867 <p>
1868 The names <em>var_i</em> declare loop variables local to the loop body.
1869 The first of these variables is the <em>control variable</em>.
1870
1871
1872 <p>
1873 The loop starts by evaluating <em>explist</em>
1874 to produce four values:
1875 an <em>iterator function</em>,
1876 a <em>state</em>,
1877 an initial value for the control variable,
1878 and a <em>closing value</em>.
1879
1880
1881 <p>
1882 Then, at each iteration,
1883 Lua calls the iterator function with two arguments:
1884 the state and the control variable.
1885 The results from this call are then assigned to the loop variables,
1886 following the rules of multiple assignments (see <a href="#3.3.3">&sect;3.3.3</a>).
1887 If the control variable becomes <b>nil</b>,
1888 the loop terminates.
1889 Otherwise, the body is executed and the loop goes
1890 to the next iteration.
1891
1892
1893 <p>
1894 The closing value behaves like a
1895 to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>),
1896 which can be used to release resources when the loop ends.
1897 Otherwise, it does not interfere with the loop.
1898
1899
1900 <p>
1901 You should not change the value of the control variable
1902 during the loop.
1903
1904
1905
1906
1907
1908
1909
1910 <h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1911 To allow possible side-effects,
1912 function calls can be executed as statements:
1913
1914 <pre>
1915 stat ::= functioncall
1916 </pre><p>
1917 In this case, all returned values are thrown away.
1918 Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1919
1920
1921
1922
1923
1924 <h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1925 Local variables can be declared anywhere inside a block.
1926 The declaration can include an initialization:
1927
1928 <pre>
1929 stat ::= <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
1930 attnamelist ::= Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
1931 </pre><p>
1932 If present, an initial assignment has the same semantics
1933 of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1934 Otherwise, all variables are initialized with <b>nil</b>.
1935
1936
1937 <p>
1938 Each variable name may be postfixed by an attribute
1939 (a name between angle brackets):
1940
1941 <pre>
1942 attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
1943 </pre><p>
1944 There are two possible attributes:
1945 <code>const</code>, which declares a constant variable,
1946 that is, a variable that cannot be assigned to
1947 after its initialization;
1948 and <code>close</code>, which declares a to-be-closed variable (see <a href="#3.3.8">&sect;3.3.8</a>).
1949 A list of variables can contain at most one to-be-closed variable.
1950
1951
1952 <p>
1953 A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1954 and so local variables can be declared in a chunk outside any explicit block.
1955
1956
1957 <p>
1958 The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1959
1960
1961
1962
1963
1964 <h3>3.3.8 &ndash; <a name="3.3.8">To-be-closed Variables</a></h3>
1965
1966 <p>
1967 A to-be-closed variable behaves like a constant local variable,
1968 except that its value is <em>closed</em> whenever the variable
1969 goes out of scope, including normal block termination,
1970 exiting its block by <b>break</b>/<b>goto</b>/<b>return</b>,
1971 or exiting by an error.
1972
1973
1974 <p>
1975 Here, to <em>close</em> a value means
1976 to call its <code>__close</code> metamethod.
1977 When calling the metamethod,
1978 the value itself is passed as the first argument
1979 and the error object that caused the exit (if any)
1980 is passed as a second argument;
1981 if there was no error, the second argument is <b>nil</b>.
1982
1983
1984 <p>
1985 The value assigned to a to-be-closed variable
1986 must have a <code>__close</code> metamethod
1987 or be a false value.
1988 (<b>nil</b> and <b>false</b> are ignored as to-be-closed values.)
1989
1990
1991 <p>
1992 If several to-be-closed variables go out of scope at the same event,
1993 they are closed in the reverse order that they were declared.
1994
1995
1996 <p>
1997 If there is any error while running a closing method,
1998 that error is handled like an error in the regular code
1999 where the variable was defined.
2000 After an error,
2001 the other pending closing methods will still be called.
2002
2003
2004 <p>
2005 If a coroutine yields and is never resumed again,
2006 some variables may never go out of scope,
2007 and therefore they will never be closed.
2008 (These variables are the ones created inside the coroutine
2009 and in scope at the point where the coroutine yielded.)
2010 Similarly, if a coroutine ends with an error,
2011 it does not unwind its stack,
2012 so it does not close any variable.
2013 In both cases,
2014 you can either use finalizers
2015 or call <a href="#pdf-coroutine.close"><code>coroutine.close</code></a> to close the variables.
2016 However, if the coroutine was created
2017 through <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a>,
2018 then its corresponding function will close the coroutine
2019 in case of errors.
2020
2021
2022
2023
2024
2025
2026
2027 <h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
2028
2029
2030
2031 <p>
2032 The basic expressions in Lua are the following:
2033
2034 <pre>
2035 exp ::= prefixexp
2036 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
2037 exp ::= Numeral
2038 exp ::= LiteralString
2039 exp ::= functiondef
2040 exp ::= tableconstructor
2041 exp ::= &lsquo;<b>...</b>&rsquo;
2042 exp ::= exp binop exp
2043 exp ::= unop exp
2044 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
2045 </pre>
2046
2047 <p>
2048 Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
2049 variables are explained in <a href="#3.2">&sect;3.2</a>;
2050 function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
2051 function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
2052 table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
2053 Vararg expressions,
2054 denoted by three dots ('<code>...</code>'), can only be used when
2055 directly inside a vararg function;
2056 they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
2057
2058
2059 <p>
2060 Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
2061 bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
2062 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>),
2063 and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
2064 Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
2065 the unary bitwise NOT (see <a href="#3.4.2">&sect;3.4.2</a>),
2066 the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
2067 and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
2068
2069
2070 <p>
2071 Both function calls and vararg expressions can result in multiple values.
2072 If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
2073 then its return list is adjusted to zero elements,
2074 thus discarding all returned values.
2075 If an expression is used as the last (or the only) element
2076 of a list of expressions,
2077 then no adjustment is made
2078 (unless the expression is enclosed in parentheses).
2079 In all other contexts,
2080 Lua adjusts the result list to one element,
2081 either discarding all values except the first one
2082 or adding a single <b>nil</b> if there are no values.
2083
2084
2085 <p>
2086 Here are some examples:
2087
2088 <pre>
2089 f() -- adjusted to 0 results
2090 g(f(), x) -- f() is adjusted to 1 result
2091 g(x, f()) -- g gets x plus all results from f()
2092 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
2093 a,b = ... -- a gets the first vararg argument, b gets
2094 -- the second (both a and b can get nil if there
2095 -- is no corresponding vararg argument)
2096
2097 a,b,c = x, f() -- f() is adjusted to 2 results
2098 a,b,c = f() -- f() is adjusted to 3 results
2099 return f() -- returns all results from f()
2100 return ... -- returns all received vararg arguments
2101 return x,y,f() -- returns x, y, and all results from f()
2102 {f()} -- creates a list with all results from f()
2103 {...} -- creates a list with all vararg arguments
2104 {f(), nil} -- f() is adjusted to 1 result
2105 </pre>
2106
2107 <p>
2108 Any expression enclosed in parentheses always results in only one value.
2109 Thus,
2110 <code>(f(x,y,z))</code> is always a single value,
2111 even if <code>f</code> returns several values.
2112 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
2113 or <b>nil</b> if <code>f</code> does not return any values.)
2114
2115
2116
2117
2118
2119 <h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
2120 Lua supports the following arithmetic operators:
2121
2122 <ul>
2123 <li><b><code>+</code>: </b>addition</li>
2124 <li><b><code>-</code>: </b>subtraction</li>
2125 <li><b><code>*</code>: </b>multiplication</li>
2126 <li><b><code>/</code>: </b>float division</li>
2127 <li><b><code>//</code>: </b>floor division</li>
2128 <li><b><code>%</code>: </b>modulo</li>
2129 <li><b><code>^</code>: </b>exponentiation</li>
2130 <li><b><code>-</code>: </b>unary minus</li>
2131 </ul>
2132
2133 <p>
2134 With the exception of exponentiation and float division,
2135 the arithmetic operators work as follows:
2136 If both operands are integers,
2137 the operation is performed over integers and the result is an integer.
2138 Otherwise, if both operands are numbers,
2139 then they are converted to floats,
2140 the operation is performed following the machine's rules
2141 for floating-point arithmetic
2142 (usually the IEEE 754 standard),
2143 and the result is a float.
2144 (The string library coerces strings to numbers in
2145 arithmetic operations; see <a href="#3.4.3">&sect;3.4.3</a> for details.)
2146
2147
2148 <p>
2149 Exponentiation and float division (<code>/</code>)
2150 always convert their operands to floats
2151 and the result is always a float.
2152 Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
2153 so that it works for non-integer exponents too.
2154
2155
2156 <p>
2157 Floor division (<code>//</code>) is a division
2158 that rounds the quotient towards minus infinity,
2159 resulting in the floor of the division of its operands.
2160
2161
2162 <p>
2163 Modulo is defined as the remainder of a division
2164 that rounds the quotient towards minus infinity (floor division).
2165
2166
2167 <p>
2168 In case of overflows in integer arithmetic,
2169 all operations <em>wrap around</em>.
2170
2171
2172
2173 <h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
2174 Lua supports the following bitwise operators:
2175
2176 <ul>
2177 <li><b><code>&amp;</code>: </b>bitwise AND</li>
2178 <li><b><code>&#124;</code>: </b>bitwise OR</li>
2179 <li><b><code>~</code>: </b>bitwise exclusive OR</li>
2180 <li><b><code>&gt;&gt;</code>: </b>right shift</li>
2181 <li><b><code>&lt;&lt;</code>: </b>left shift</li>
2182 <li><b><code>~</code>: </b>unary bitwise NOT</li>
2183 </ul>
2184
2185 <p>
2186 All bitwise operations convert its operands to integers
2187 (see <a href="#3.4.3">&sect;3.4.3</a>),
2188 operate on all bits of those integers,
2189 and result in an integer.
2190
2191
2192 <p>
2193 Both right and left shifts fill the vacant bits with zeros.
2194 Negative displacements shift to the other direction;
2195 displacements with absolute values equal to or higher than
2196 the number of bits in an integer
2197 result in zero (as all bits are shifted out).
2198
2199
2200
2201
2202
2203 <h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
2204 Lua provides some automatic conversions between some
2205 types and representations at run time.
2206 Bitwise operators always convert float operands to integers.
2207 Exponentiation and float division
2208 always convert integer operands to floats.
2209 All other arithmetic operations applied to mixed numbers
2210 (integers and floats) convert the integer operand to a float.
2211 The C API also converts both integers to floats and
2212 floats to integers, as needed.
2213 Moreover, string concatenation accepts numbers as arguments,
2214 besides strings.
2215
2216
2217 <p>
2218 In a conversion from integer to float,
2219 if the integer value has an exact representation as a float,
2220 that is the result.
2221 Otherwise,
2222 the conversion gets the nearest higher or
2223 the nearest lower representable value.
2224 This kind of conversion never fails.
2225
2226
2227 <p>
2228 The conversion from float to integer
2229 checks whether the float has an exact representation as an integer
2230 (that is, the float has an integral value and
2231 it is in the range of integer representation).
2232 If it does, that representation is the result.
2233 Otherwise, the conversion fails.
2234
2235
2236 <p>
2237 Several places in Lua coerce strings to numbers when necessary.
2238 In particular,
2239 the string library sets metamethods that try to coerce
2240 strings to numbers in all arithmetic operations.
2241 If the conversion fails,
2242 the library calls the metamethod of the other operand
2243 (if present) or it raises an error.
2244 Note that bitwise operators do not do this coercion.
2245
2246
2247 <p>
2248 Nonetheless, it is always a good practice not to rely on these
2249 implicit coercions, as they are not always applied;
2250 in particular, <code>"1"==1</code> is false and <code>"1"&lt;1</code> raises an error
2251 (see <a href="#3.4.4">&sect;3.4.4</a>).
2252 These coercions exist mainly for compatibility and may be removed
2253 in future versions of the language.
2254
2255
2256 <p>
2257 A string is converted to an integer or a float
2258 following its syntax and the rules of the Lua lexer.
2259 The string may have also leading and trailing whitespaces and a sign.
2260 All conversions from strings to numbers
2261 accept both a dot and the current locale mark
2262 as the radix character.
2263 (The Lua lexer, however, accepts only a dot.)
2264 If the string is not a valid numeral,
2265 the conversion fails.
2266 If necessary, the result of this first step is then converted
2267 to a specific number subtype following the previous rules
2268 for conversions between floats and integers.
2269
2270
2271 <p>
2272 The conversion from numbers to strings uses a
2273 non-specified human-readable format.
2274 To convert numbers to strings in any specific way,
2275 use the function <a href="#pdf-string.format"><code>string.format</code></a>.
2276
2277
2278
2279
2280
2281 <h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
2282 Lua supports the following relational operators:
2283
2284 <ul>
2285 <li><b><code>==</code>: </b>equality</li>
2286 <li><b><code>~=</code>: </b>inequality</li>
2287 <li><b><code>&lt;</code>: </b>less than</li>
2288 <li><b><code>&gt;</code>: </b>greater than</li>
2289 <li><b><code>&lt;=</code>: </b>less or equal</li>
2290 <li><b><code>&gt;=</code>: </b>greater or equal</li>
2291 </ul><p>
2292 These operators always result in <b>false</b> or <b>true</b>.
2293
2294
2295 <p>
2296 Equality (<code>==</code>) first compares the type of its operands.
2297 If the types are different, then the result is <b>false</b>.
2298 Otherwise, the values of the operands are compared.
2299 Strings are equal if they have the same byte content.
2300 Numbers are equal if they denote the same mathematical value.
2301
2302
2303 <p>
2304 Tables, userdata, and threads
2305 are compared by reference:
2306 two objects are considered equal only if they are the same object.
2307 Every time you create a new object
2308 (a table, a userdata, or a thread),
2309 this new object is different from any previously existing object.
2310 A function is always equal to itself.
2311 Functions with any detectable difference
2312 (different behavior, different definition) are always different.
2313 Functions created at different times but with no detectable differences
2314 may be classified as equal or not
2315 (depending on internal caching details).
2316
2317
2318 <p>
2319 You can change the way that Lua compares tables and userdata
2320 by using the <code>__eq</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2321
2322
2323 <p>
2324 Equality comparisons do not convert strings to numbers
2325 or vice versa.
2326 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2327 and <code>t[0]</code> and <code>t["0"]</code> denote different
2328 entries in a table.
2329
2330
2331 <p>
2332 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2333
2334
2335 <p>
2336 The order operators work as follows.
2337 If both arguments are numbers,
2338 then they are compared according to their mathematical values,
2339 regardless of their subtypes.
2340 Otherwise, if both arguments are strings,
2341 then their values are compared according to the current locale.
2342 Otherwise, Lua tries to call the <code>__lt</code> or the <code>__le</code>
2343 metamethod (see <a href="#2.4">&sect;2.4</a>).
2344 A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2345 and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2346
2347
2348 <p>
2349 Following the IEEE 754 standard,
2350 the special value NaN is considered neither less than,
2351 nor equal to, nor greater than any value, including itself.
2352
2353
2354
2355
2356
2357 <h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2358 The logical operators in Lua are
2359 <b>and</b>, <b>or</b>, and <b>not</b>.
2360 Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2361 all logical operators consider both <b>false</b> and <b>nil</b> as false
2362 and anything else as true.
2363
2364
2365 <p>
2366 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2367 The conjunction operator <b>and</b> returns its first argument
2368 if this value is <b>false</b> or <b>nil</b>;
2369 otherwise, <b>and</b> returns its second argument.
2370 The disjunction operator <b>or</b> returns its first argument
2371 if this value is different from <b>nil</b> and <b>false</b>;
2372 otherwise, <b>or</b> returns its second argument.
2373 Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2374 that is,
2375 the second operand is evaluated only if necessary.
2376 Here are some examples:
2377
2378 <pre>
2379 10 or 20 --&gt; 10
2380 10 or error() --&gt; 10
2381 nil or "a" --&gt; "a"
2382 nil and 10 --&gt; nil
2383 false and error() --&gt; false
2384 false and nil --&gt; false
2385 false or nil --&gt; nil
2386 10 and 20 --&gt; 20
2387 </pre>
2388
2389
2390
2391
2392 <h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2393 The string concatenation operator in Lua is
2394 denoted by two dots ('<code>..</code>').
2395 If both operands are strings or numbers,
2396 then the numbers are converted to strings
2397 in a non-specified format (see <a href="#3.4.3">&sect;3.4.3</a>).
2398 Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2399
2400
2401
2402
2403
2404 <h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2405
2406 <p>
2407 The length operator is denoted by the unary prefix operator <code>#</code>.
2408
2409
2410 <p>
2411 The length of a string is its number of bytes.
2412 (That is the usual meaning of string length when each
2413 character is one byte.)
2414
2415
2416 <p>
2417 The length operator applied on a table
2418 returns a border in that table.
2419 A <em>border</em> in a table <code>t</code> is any natural number
2420 that satisfies the following condition:
2421
2422 <pre>
2423 (border == 0 or t[border] ~= nil) and t[border + 1] == nil
2424 </pre><p>
2425 In words,
2426 a border is any (natural) index present in the table
2427 that is followed by an absent index
2428 (or zero, when index 1 is absent).
2429
2430
2431 <p>
2432 A table with exactly one border is called a <em>sequence</em>.
2433 For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence,
2434 as it has only one border (5).
2435 The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5),
2436 and therefore it is not a sequence.
2437 (The <b>nil</b> at index 4 is called a <em>hole</em>.)
2438 The table <code>{nil, 20, 30, nil, nil, 60, nil}</code>
2439 has three borders (0, 3, and 6) and three holes
2440 (at indices 1, 4, and 5),
2441 so it is not a sequence, too.
2442 The table <code>{}</code> is a sequence with border 0.
2443 Note that non-natural keys do not interfere
2444 with whether a table is a sequence.
2445
2446
2447 <p>
2448 When <code>t</code> is a sequence,
2449 <code>#t</code> returns its only border,
2450 which corresponds to the intuitive notion of the length of the sequence.
2451 When <code>t</code> is not a sequence,
2452 <code>#t</code> can return any of its borders.
2453 (The exact one depends on details of
2454 the internal representation of the table,
2455 which in turn can depend on how the table was populated and
2456 the memory addresses of its non-numeric keys.)
2457
2458
2459 <p>
2460 The computation of the length of a table
2461 has a guaranteed worst time of <em>O(log n)</em>,
2462 where <em>n</em> is the largest natural key in the table.
2463
2464
2465 <p>
2466 A program can modify the behavior of the length operator for
2467 any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2468
2469
2470
2471
2472
2473 <h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2474 Operator precedence in Lua follows the table below,
2475 from lower to higher priority:
2476
2477 <pre>
2478 or
2479 and
2480 &lt; &gt; &lt;= &gt;= ~= ==
2481 |
2482 ~
2483 &amp;
2484 &lt;&lt; &gt;&gt;
2485 ..
2486 + -
2487 * / // %
2488 unary operators (not # - ~)
2489 ^
2490 </pre><p>
2491 As usual,
2492 you can use parentheses to change the precedences of an expression.
2493 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2494 operators are right associative.
2495 All other binary operators are left associative.
2496
2497
2498
2499
2500
2501 <h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2502 Table constructors are expressions that create tables.
2503 Every time a constructor is evaluated, a new table is created.
2504 A constructor can be used to create an empty table
2505 or to create a table and initialize some of its fields.
2506 The general syntax for constructors is
2507
2508 <pre>
2509 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2510 fieldlist ::= field {fieldsep field} [fieldsep]
2511 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2512 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2513 </pre>
2514
2515 <p>
2516 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2517 with key <code>exp1</code> and value <code>exp2</code>.
2518 A field of the form <code>name = exp</code> is equivalent to
2519 <code>["name"] = exp</code>.
2520 Fields of the form <code>exp</code> are equivalent to
2521 <code>[i] = exp</code>, where <code>i</code> are consecutive integers
2522 starting with 1;
2523 fields in the other formats do not affect this counting.
2524 For example,
2525
2526 <pre>
2527 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2528 </pre><p>
2529 is equivalent to
2530
2531 <pre>
2532 do
2533 local t = {}
2534 t[f(1)] = g
2535 t[1] = "x" -- 1st exp
2536 t[2] = "y" -- 2nd exp
2537 t.x = 1 -- t["x"] = 1
2538 t[3] = f(x) -- 3rd exp
2539 t[30] = 23
2540 t[4] = 45 -- 4th exp
2541 a = t
2542 end
2543 </pre>
2544
2545 <p>
2546 The order of the assignments in a constructor is undefined.
2547 (This order would be relevant only when there are repeated keys.)
2548
2549
2550 <p>
2551 If the last field in the list has the form <code>exp</code>
2552 and the expression is a function call or a vararg expression,
2553 then all values returned by this expression enter the list consecutively
2554 (see <a href="#3.4.10">&sect;3.4.10</a>).
2555
2556
2557 <p>
2558 The field list can have an optional trailing separator,
2559 as a convenience for machine-generated code.
2560
2561
2562
2563
2564
2565 <h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2566 A function call in Lua has the following syntax:
2567
2568 <pre>
2569 functioncall ::= prefixexp args
2570 </pre><p>
2571 In a function call,
2572 first prefixexp and args are evaluated.
2573 If the value of prefixexp has type <em>function</em>,
2574 then this function is called
2575 with the given arguments.
2576 Otherwise, if present,
2577 the prefixexp <code>__call</code> metamethod is called:
2578 its first argument is the value of prefixexp,
2579 followed by the original call arguments
2580 (see <a href="#2.4">&sect;2.4</a>).
2581
2582
2583 <p>
2584 The form
2585
2586 <pre>
2587 functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2588 </pre><p>
2589 can be used to emulate methods.
2590 A call <code>v:name(<em>args</em>)</code>
2591 is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2592 except that <code>v</code> is evaluated only once.
2593
2594
2595 <p>
2596 Arguments have the following syntax:
2597
2598 <pre>
2599 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2600 args ::= tableconstructor
2601 args ::= LiteralString
2602 </pre><p>
2603 All argument expressions are evaluated before the call.
2604 A call of the form <code>f{<em>fields</em>}</code> is
2605 syntactic sugar for <code>f({<em>fields</em>})</code>;
2606 that is, the argument list is a single new table.
2607 A call of the form <code>f'<em>string</em>'</code>
2608 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2609 is syntactic sugar for <code>f('<em>string</em>')</code>;
2610 that is, the argument list is a single literal string.
2611
2612
2613 <p>
2614 A call of the form <code>return <em>functioncall</em></code> not in the
2615 scope of a to-be-closed variable is called a <em>tail call</em>.
2616 Lua implements <em>proper tail calls</em>
2617 (or <em>proper tail recursion</em>):
2618 in a tail call,
2619 the called function reuses the stack entry of the calling function.
2620 Therefore, there is no limit on the number of nested tail calls that
2621 a program can execute.
2622 However, a tail call erases any debug information about the
2623 calling function.
2624 Note that a tail call only happens with a particular syntax,
2625 where the <b>return</b> has one single function call as argument,
2626 and it is outside the scope of any to-be-closed variable.
2627 This syntax makes the calling function return exactly
2628 the returns of the called function,
2629 without any intervening action.
2630 So, none of the following examples are tail calls:
2631
2632 <pre>
2633 return (f(x)) -- results adjusted to 1
2634 return 2 * f(x) -- result multiplied by 2
2635 return x, f(x) -- additional results
2636 f(x); return -- results discarded
2637 return x or f(x) -- results adjusted to 1
2638 </pre>
2639
2640
2641
2642
2643 <h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2644
2645 <p>
2646 The syntax for function definition is
2647
2648 <pre>
2649 functiondef ::= <b>function</b> funcbody
2650 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2651 </pre>
2652
2653 <p>
2654 The following syntactic sugar simplifies function definitions:
2655
2656 <pre>
2657 stat ::= <b>function</b> funcname funcbody
2658 stat ::= <b>local</b> <b>function</b> Name funcbody
2659 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2660 </pre><p>
2661 The statement
2662
2663 <pre>
2664 function f () <em>body</em> end
2665 </pre><p>
2666 translates to
2667
2668 <pre>
2669 f = function () <em>body</em> end
2670 </pre><p>
2671 The statement
2672
2673 <pre>
2674 function t.a.b.c.f () <em>body</em> end
2675 </pre><p>
2676 translates to
2677
2678 <pre>
2679 t.a.b.c.f = function () <em>body</em> end
2680 </pre><p>
2681 The statement
2682
2683 <pre>
2684 local function f () <em>body</em> end
2685 </pre><p>
2686 translates to
2687
2688 <pre>
2689 local f; f = function () <em>body</em> end
2690 </pre><p>
2691 not to
2692
2693 <pre>
2694 local f = function () <em>body</em> end
2695 </pre><p>
2696 (This only makes a difference when the body of the function
2697 contains references to <code>f</code>.)
2698
2699
2700 <p>
2701 A function definition is an executable expression,
2702 whose value has type <em>function</em>.
2703 When Lua precompiles a chunk,
2704 all its function bodies are precompiled too,
2705 but they are not created yet.
2706 Then, whenever Lua executes the function definition,
2707 the function is <em>instantiated</em> (or <em>closed</em>).
2708 This function instance, or <em>closure</em>,
2709 is the final value of the expression.
2710
2711
2712 <p>
2713 Parameters act as local variables that are
2714 initialized with the argument values:
2715
2716 <pre>
2717 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2718 </pre><p>
2719 When a Lua function is called,
2720 it adjusts its list of arguments to
2721 the length of its list of parameters,
2722 unless the function is a <em>vararg function</em>,
2723 which is indicated by three dots ('<code>...</code>')
2724 at the end of its parameter list.
2725 A vararg function does not adjust its argument list;
2726 instead, it collects all extra arguments and supplies them
2727 to the function through a <em>vararg expression</em>,
2728 which is also written as three dots.
2729 The value of this expression is a list of all actual extra arguments,
2730 similar to a function with multiple results.
2731 If a vararg expression is used inside another expression
2732 or in the middle of a list of expressions,
2733 then its return list is adjusted to one element.
2734 If the expression is used as the last element of a list of expressions,
2735 then no adjustment is made
2736 (unless that last expression is enclosed in parentheses).
2737
2738
2739 <p>
2740 As an example, consider the following definitions:
2741
2742 <pre>
2743 function f(a, b) end
2744 function g(a, b, ...) end
2745 function r() return 1,2,3 end
2746 </pre><p>
2747 Then, we have the following mapping from arguments to parameters and
2748 to the vararg expression:
2749
2750 <pre>
2751 CALL PARAMETERS
2752
2753 f(3) a=3, b=nil
2754 f(3, 4) a=3, b=4
2755 f(3, 4, 5) a=3, b=4
2756 f(r(), 10) a=1, b=10
2757 f(r()) a=1, b=2
2758
2759 g(3) a=3, b=nil, ... --&gt; (nothing)
2760 g(3, 4) a=3, b=4, ... --&gt; (nothing)
2761 g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
2762 g(5, r()) a=5, b=1, ... --&gt; 2 3
2763 </pre>
2764
2765 <p>
2766 Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2767 If control reaches the end of a function
2768 without encountering a <b>return</b> statement,
2769 then the function returns with no results.
2770
2771
2772 <p>
2773
2774 There is a system-dependent limit on the number of values
2775 that a function may return.
2776 This limit is guaranteed to be greater than 1000.
2777
2778
2779 <p>
2780 The <em>colon</em> syntax
2781 is used to emulate <em>methods</em>,
2782 adding an implicit extra parameter <code>self</code> to the function.
2783 Thus, the statement
2784
2785 <pre>
2786 function t.a.b.c:f (<em>params</em>) <em>body</em> end
2787 </pre><p>
2788 is syntactic sugar for
2789
2790 <pre>
2791 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2792 </pre>
2793
2794
2795
2796
2797
2798
2799 <h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2800
2801 <p>
2802
2803 Lua is a lexically scoped language.
2804 The scope of a local variable begins at the first statement after
2805 its declaration and lasts until the last non-void statement
2806 of the innermost block that includes the declaration.
2807 Consider the following example:
2808
2809 <pre>
2810 x = 10 -- global variable
2811 do -- new block
2812 local x = x -- new 'x', with value 10
2813 print(x) --&gt; 10
2814 x = x+1
2815 do -- another block
2816 local x = x+1 -- another 'x'
2817 print(x) --&gt; 12
2818 end
2819 print(x) --&gt; 11
2820 end
2821 print(x) --&gt; 10 (the global one)
2822 </pre>
2823
2824 <p>
2825 Notice that, in a declaration like <code>local x = x</code>,
2826 the new <code>x</code> being declared is not in scope yet,
2827 and so the second <code>x</code> refers to the outside variable.
2828
2829
2830 <p>
2831 Because of the lexical scoping rules,
2832 local variables can be freely accessed by functions
2833 defined inside their scope.
2834 A local variable used by an inner function is called an <em>upvalue</em>
2835 (or <em>external local variable</em>, or simply <em>external variable</em>)
2836 inside the inner function.
2837
2838
2839 <p>
2840 Notice that each execution of a <b>local</b> statement
2841 defines new local variables.
2842 Consider the following example:
2843
2844 <pre>
2845 a = {}
2846 local x = 20
2847 for i = 1, 10 do
2848 local y = 0
2849 a[i] = function () y = y + 1; return x + y end
2850 end
2851 </pre><p>
2852 The loop creates ten closures
2853 (that is, ten instances of the anonymous function).
2854 Each of these closures uses a different <code>y</code> variable,
2855 while all of them share the same <code>x</code>.
2856
2857
2858
2859
2860
2861 <h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2862
2863
2864
2865 <p>
2866
2867 This section describes the C&nbsp;API for Lua, that is,
2868 the set of C&nbsp;functions available to the host program to communicate
2869 with Lua.
2870 All API functions and related types and constants
2871 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2872
2873
2874 <p>
2875 Even when we use the term "function",
2876 any facility in the API may be provided as a macro instead.
2877 Except where stated otherwise,
2878 all such macros use each of their arguments exactly once
2879 (except for the first argument, which is always a Lua state),
2880 and so do not generate any hidden side-effects.
2881
2882
2883 <p>
2884 As in most C&nbsp;libraries,
2885 the Lua API functions do not check their arguments
2886 for validity or consistency.
2887 However, you can change this behavior by compiling Lua
2888 with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2889
2890
2891 <p>
2892 The Lua library is fully reentrant:
2893 it has no global variables.
2894 It keeps all information it needs in a dynamic structure,
2895 called the <em>Lua state</em>.
2896
2897
2898 <p>
2899 Each Lua state has one or more threads,
2900 which correspond to independent, cooperative lines of execution.
2901 The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread.
2902 (Indirectly, through the thread, it also refers to the
2903 Lua state associated to the thread.)
2904
2905
2906 <p>
2907 A pointer to a thread must be passed as the first argument to
2908 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
2909 which creates a Lua state from scratch and returns a pointer
2910 to the <em>main thread</em> in the new state.
2911
2912
2913
2914
2915
2916 <h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2917
2918
2919
2920 <p>
2921 Lua uses a <em>virtual stack</em> to pass values to and from C.
2922 Each element in this stack represents a Lua value
2923 (<b>nil</b>, number, string, etc.).
2924 Functions in the API can access this stack through the
2925 Lua state parameter that they receive.
2926
2927
2928 <p>
2929 Whenever Lua calls C, the called function gets a new stack,
2930 which is independent of previous stacks and of stacks of
2931 C&nbsp;functions that are still active.
2932 This stack initially contains any arguments to the C&nbsp;function
2933 and it is where the C&nbsp;function can store temporary
2934 Lua values and must push its results
2935 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2936
2937
2938 <p>
2939 For convenience,
2940 most query operations in the API do not follow a strict stack discipline.
2941 Instead, they can refer to any element in the stack
2942 by using an <em>index</em>:
2943 A positive index represents an absolute stack position,
2944 starting at&nbsp;1 as the bottom of the stack;
2945 a negative index represents an offset relative to the top of the stack.
2946 More specifically, if the stack has <em>n</em> elements,
2947 then index&nbsp;1 represents the first element
2948 (that is, the element that was pushed onto the stack first)
2949 and
2950 index&nbsp;<em>n</em> represents the last element;
2951 index&nbsp;-1 also represents the last element
2952 (that is, the element at the&nbsp;top)
2953 and index <em>-n</em> represents the first element.
2954
2955
2956
2957
2958
2959 <h3>4.1.1 &ndash; <a name="4.1.1">Stack Size</a></h3>
2960
2961 <p>
2962 When you interact with the Lua API,
2963 you are responsible for ensuring consistency.
2964 In particular,
2965 <em>you are responsible for controlling stack overflow</em>.
2966 When you call any API function,
2967 you must ensure the stack has enough room to accommodate the results.
2968
2969
2970 <p>
2971 There is one exception to the above rule:
2972 When you call a Lua function
2973 without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2974 Lua ensures that the stack has enough space for all results.
2975 However, it does not ensure any extra space.
2976 So, before pushing anything on the stack after such a call
2977 you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2978
2979
2980 <p>
2981 Whenever Lua calls C,
2982 it ensures that the stack has space for
2983 at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra elements;
2984 that is, you can safely push up to <code>LUA_MINSTACK</code> values into it.
2985 <code>LUA_MINSTACK</code> is defined as 20,
2986 so that usually you do not have to worry about stack space
2987 unless your code has loops pushing elements onto the stack.
2988 Whenever necessary,
2989 you can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2990 to ensure that the stack has enough space for pushing new elements.
2991
2992
2993
2994
2995
2996 <h3>4.1.2 &ndash; <a name="4.1.2">Valid and Acceptable Indices</a></h3>
2997
2998 <p>
2999 Any function in the API that receives stack indices
3000 works only with <em>valid indices</em> or <em>acceptable indices</em>.
3001
3002
3003 <p>
3004 A <em>valid index</em> is an index that refers to a
3005 position that stores a modifiable Lua value.
3006 It comprises stack indices between&nbsp;1 and the stack top
3007 (<code>1 &le; abs(index) &le; top</code>)
3008
3009 plus <em>pseudo-indices</em>,
3010 which represent some positions that are accessible to C&nbsp;code
3011 but that are not in the stack.
3012 Pseudo-indices are used to access the registry (see <a href="#4.3">&sect;4.3</a>)
3013 and the upvalues of a C&nbsp;function (see <a href="#4.2">&sect;4.2</a>).
3014
3015
3016 <p>
3017 Functions that do not need a specific mutable position,
3018 but only a value (e.g., query functions),
3019 can be called with acceptable indices.
3020 An <em>acceptable index</em> can be any valid index,
3021 but it also can be any positive index after the stack top
3022 within the space allocated for the stack,
3023 that is, indices up to the stack size.
3024 (Note that 0 is never an acceptable index.)
3025 Indices to upvalues (see <a href="#4.2">&sect;4.2</a>) greater than the real number
3026 of upvalues in the current C&nbsp;function are also acceptable (but invalid).
3027 Except when noted otherwise,
3028 functions in the API work with acceptable indices.
3029
3030
3031 <p>
3032 Acceptable indices serve to avoid extra tests
3033 against the stack top when querying the stack.
3034 For instance, a C&nbsp;function can query its third argument
3035 without the need to check whether there is a third argument,
3036 that is, without the need to check whether 3 is a valid index.
3037
3038
3039 <p>
3040 For functions that can be called with acceptable indices,
3041 any non-valid index is treated as if it
3042 contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
3043 which behaves like a nil value.
3044
3045
3046
3047
3048
3049 <h3>4.1.3 &ndash; <a name="4.1.3">Pointers to strings</a></h3>
3050
3051 <p>
3052 Several functions in the API return pointers (<code>const char*</code>)
3053 to Lua strings in the stack.
3054 (See <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
3055 <a href="#lua_pushstring"><code>lua_pushstring</code></a>, and <a href="#lua_tolstring"><code>lua_tolstring</code></a>.
3056 See also <a href="#luaL_checklstring"><code>luaL_checklstring</code></a>, <a href="#luaL_checkstring"><code>luaL_checkstring</code></a>,
3057 and <a href="#luaL_tolstring"><code>luaL_tolstring</code></a> in the auxiliary library.)
3058
3059
3060 <p>
3061 In general,
3062 Lua's garbage collection can free or move internal memory
3063 and then invalidate pointers to internal strings.
3064 To allow a safe use of these pointers,
3065 The API guarantees that any pointer to a string in a stack index
3066 is valid while the string value at that index is not removed from the stack.
3067 (It can be moved to another index, though.)
3068 When the index is a pseudo-index (referring to an upvalue),
3069 the pointer is valid while the corresponding call is active and
3070 the corresponding upvalue is not modified.
3071
3072
3073 <p>
3074 Some functions in the debug interface
3075 also return pointers to strings,
3076 namely <a href="#lua_getlocal"><code>lua_getlocal</code></a>, <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
3077 <a href="#lua_setlocal"><code>lua_setlocal</code></a>, and <a href="#lua_setupvalue"><code>lua_setupvalue</code></a>.
3078 For these functions, the pointer is guaranteed to
3079 be valid while the caller function is active and
3080 the given closure (if one was given) is in the stack.
3081
3082
3083 <p>
3084 Except for these guarantees,
3085 the garbage collector is free to invalidate
3086 any pointer to internal strings.
3087
3088
3089
3090
3091
3092
3093
3094 <h2>4.2 &ndash; <a name="4.2">C Closures</a></h2>
3095
3096 <p>
3097 When a C&nbsp;function is created,
3098 it is possible to associate some values with it,
3099 thus creating a <em>C&nbsp;closure</em>
3100 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
3101 these values are called <em>upvalues</em> and are
3102 accessible to the function whenever it is called.
3103
3104
3105 <p>
3106 Whenever a C&nbsp;function is called,
3107 its upvalues are located at specific pseudo-indices.
3108 These pseudo-indices are produced by the macro
3109 <a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
3110 The first upvalue associated with a function is at index
3111 <code>lua_upvalueindex(1)</code>, and so on.
3112 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
3113 where <em>n</em> is greater than the number of upvalues of the
3114 current function
3115 (but not greater than 256,
3116 which is one plus the maximum number of upvalues in a closure),
3117 produces an acceptable but invalid index.
3118
3119
3120 <p>
3121 A C&nbsp;closure can also change the values
3122 of its corresponding upvalues.
3123
3124
3125
3126
3127
3128 <h2>4.3 &ndash; <a name="4.3">Registry</a></h2>
3129
3130 <p>
3131 Lua provides a <em>registry</em>,
3132 a predefined table that can be used by any C&nbsp;code to
3133 store whatever Lua values it needs to store.
3134 The registry table is always accessible at pseudo-index
3135 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
3136 Any C&nbsp;library can store data into this table,
3137 but it must take care to choose keys
3138 that are different from those used
3139 by other libraries, to avoid collisions.
3140 Typically, you should use as key a string containing your library name,
3141 or a light userdata with the address of a C&nbsp;object in your code,
3142 or any Lua object created by your code.
3143 As with variable names,
3144 string keys starting with an underscore followed by
3145 uppercase letters are reserved for Lua.
3146
3147
3148 <p>
3149 The integer keys in the registry are used
3150 by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
3151 and by some predefined values.
3152 Therefore, integer keys in the registry
3153 must not be used for other purposes.
3154
3155
3156 <p>
3157 When you create a new Lua state,
3158 its registry comes with some predefined values.
3159 These predefined values are indexed with integer keys
3160 defined as constants in <code>lua.h</code>.
3161 The following constants are defined:
3162
3163 <ul>
3164 <li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
3165 the main thread of the state.
3166 (The main thread is the one created together with the state.)
3167 </li>
3168
3169 <li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
3170 the global environment.
3171 </li>
3172 </ul>
3173
3174
3175
3176
3177 <h2>4.4 &ndash; <a name="4.4">Error Handling in C</a></h2>
3178
3179
3180
3181 <p>
3182 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
3183 (Lua will use exceptions if you compile it as C++;
3184 search for <code>LUAI_THROW</code> in the source code for details.)
3185 When Lua faces any error,
3186 such as a memory allocation error or a type error,
3187 it <em>raises</em> an error;
3188 that is, it does a long jump.
3189 A <em>protected environment</em> uses <code>setjmp</code>
3190 to set a recovery point;
3191 any error jumps to the most recent active recovery point.
3192
3193
3194 <p>
3195 Inside a C&nbsp;function you can raise an error explicitly
3196 by calling <a href="#lua_error"><code>lua_error</code></a>.
3197
3198
3199 <p>
3200 Most functions in the API can raise an error,
3201 for instance due to a memory allocation error.
3202 The documentation for each function indicates whether
3203 it can raise errors.
3204
3205
3206 <p>
3207 If an error happens outside any protected environment,
3208 Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
3209 and then calls <code>abort</code>,
3210 thus exiting the host application.
3211 Your panic function can avoid this exit by
3212 never returning
3213 (e.g., doing a long jump to your own recovery point outside Lua).
3214
3215
3216 <p>
3217 The panic function,
3218 as its name implies,
3219 is a mechanism of last resort.
3220 Programs should avoid it.
3221 As a general rule,
3222 when a C&nbsp;function is called by Lua with a Lua state,
3223 it can do whatever it wants on that Lua state,
3224 as it should be already protected.
3225 However,
3226 when C code operates on other Lua states
3227 (e.g., a Lua-state argument to the function,
3228 a Lua state stored in the registry, or
3229 the result of <a href="#lua_newthread"><code>lua_newthread</code></a>),
3230 it should use them only in API calls that cannot raise errors.
3231
3232
3233 <p>
3234 The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
3235 in particular, the error object is on the top of the stack.
3236 However, there is no guarantee about stack space.
3237 To push anything on the stack,
3238 the panic function must first check the available space (see <a href="#4.1.1">&sect;4.1.1</a>).
3239
3240
3241
3242
3243
3244 <h3>4.4.1 &ndash; <a name="4.4.1">Status Codes</a></h3>
3245
3246 <p>
3247 Several functions that report errors in the API use the following
3248 status codes to indicate different kinds of errors or other conditions:
3249
3250 <ul>
3251
3252 <li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> no errors.</li>
3253
3254 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> a runtime error.</li>
3255
3256 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3257 memory allocation error.
3258 For such errors, Lua does not call the message handler.
3259 </li>
3260
3261 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> error while running the message handler.</li>
3262
3263 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> syntax error during precompilation.</li>
3264
3265 <li><b><a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a>: </b> the thread (coroutine) yields.</li>
3266
3267 <li><b><a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>: </b> a file-related error;
3268 e.g., it cannot open or read the file.</li>
3269
3270 </ul><p>
3271 These constants are defined in the header file <code>lua.h</code>.
3272
3273
3274
3275
3276
3277
3278
3279 <h2>4.5 &ndash; <a name="4.5">Handling Yields in C</a></h2>
3280
3281 <p>
3282 Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
3283 Therefore, if a C&nbsp;function <code>foo</code> calls an API function
3284 and this API function yields
3285 (directly or indirectly by calling another function that yields),
3286 Lua cannot return to <code>foo</code> any more,
3287 because the <code>longjmp</code> removes its frame from the C&nbsp;stack.
3288
3289
3290 <p>
3291 To avoid this kind of problem,
3292 Lua raises an error whenever it tries to yield across an API call,
3293 except for three functions:
3294 <a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3295 All those functions receive a <em>continuation function</em>
3296 (as a parameter named <code>k</code>) to continue execution after a yield.
3297
3298
3299 <p>
3300 We need to set some terminology to explain continuations.
3301 We have a C&nbsp;function called from Lua which we will call
3302 the <em>original function</em>.
3303 This original function then calls one of those three functions in the C API,
3304 which we will call the <em>callee function</em>,
3305 that then yields the current thread.
3306 This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
3307 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>
3308 and the function called by them yields.
3309
3310
3311 <p>
3312 Suppose the running thread yields while executing the callee function.
3313 After the thread resumes,
3314 it eventually will finish running the callee function.
3315 However,
3316 the callee function cannot return to the original function,
3317 because its frame in the C&nbsp;stack was destroyed by the yield.
3318 Instead, Lua calls a <em>continuation function</em>,
3319 which was given as an argument to the callee function.
3320 As the name implies,
3321 the continuation function should continue the task
3322 of the original function.
3323
3324
3325 <p>
3326 As an illustration, consider the following function:
3327
3328 <pre>
3329 int original_function (lua_State *L) {
3330 ... /* code 1 */
3331 status = lua_pcall(L, n, m, h); /* calls Lua */
3332 ... /* code 2 */
3333 }
3334 </pre><p>
3335 Now we want to allow
3336 the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
3337 First, we can rewrite our function like here:
3338
3339 <pre>
3340 int k (lua_State *L, int status, lua_KContext ctx) {
3341 ... /* code 2 */
3342 }
3343
3344 int original_function (lua_State *L) {
3345 ... /* code 1 */
3346 return k(L, lua_pcall(L, n, m, h), ctx);
3347 }
3348 </pre><p>
3349 In the above code,
3350 the new function <code>k</code> is a
3351 <em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
3352 which should do all the work that the original function
3353 was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
3354 Now, we must inform Lua that it must call <code>k</code> if the Lua code
3355 being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
3356 (errors or yielding),
3357 so we rewrite the code as here,
3358 replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
3359
3360 <pre>
3361 int original_function (lua_State *L) {
3362 ... /* code 1 */
3363 return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
3364 }
3365 </pre><p>
3366 Note the external, explicit call to the continuation:
3367 Lua will call the continuation only if needed, that is,
3368 in case of errors or resuming after a yield.
3369 If the called function returns normally without ever yielding,
3370 <a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
3371 (Of course, instead of calling the continuation in that case,
3372 you can do the equivalent work directly inside the original function.)
3373
3374
3375 <p>
3376 Besides the Lua state,
3377 the continuation function has two other parameters:
3378 the final status of the call and the context value (<code>ctx</code>) that
3379 was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
3380 Lua does not use this context value;
3381 it only passes this value from the original function to the
3382 continuation function.
3383 For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3384 the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3385 except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
3386 (instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
3387 For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
3388 the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
3389 (For these two functions,
3390 Lua will not call the continuation in case of errors,
3391 because they do not handle errors.)
3392 Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
3393 you should call the continuation function
3394 with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
3395 (For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
3396 directly the continuation function,
3397 because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
3398
3399
3400 <p>
3401 Lua treats the continuation function as if it were the original function.
3402 The continuation function receives the same Lua stack
3403 from the original function,
3404 in the same state it would be if the callee function had returned.
3405 (For instance,
3406 after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
3407 removed from the stack and replaced by the results from the call.)
3408 It also has the same upvalues.
3409 Whatever it returns is handled by Lua as if it were the return
3410 of the original function.
3411
3412
3413
3414
3415
3416 <h2>4.6 &ndash; <a name="4.6">Functions and Types</a></h2>
3417
3418 <p>
3419 Here we list all functions and types from the C&nbsp;API in
3420 alphabetical order.
3421 Each function has an indicator like this:
3422 <span class="apii">[-o, +p, <em>x</em>]</span>
3423
3424
3425 <p>
3426 The first field, <code>o</code>,
3427 is how many elements the function pops from the stack.
3428 The second field, <code>p</code>,
3429 is how many elements the function pushes onto the stack.
3430 (Any function always pushes its results after popping its arguments.)
3431 A field in the form <code>x|y</code> means the function can push (or pop)
3432 <code>x</code> or <code>y</code> elements,
3433 depending on the situation;
3434 an interrogation mark '<code>?</code>' means that
3435 we cannot know how many elements the function pops/pushes
3436 by looking only at its arguments.
3437 (For instance, they may depend on what is in the stack.)
3438 The third field, <code>x</code>,
3439 tells whether the function may raise errors:
3440 '<code>-</code>' means the function never raises any error;
3441 '<code>m</code>' means the function may raise only out-of-memory errors;
3442 '<code>v</code>' means the function may raise the errors explained in the text;
3443 '<code>e</code>' means the function can run arbitrary Lua code,
3444 either directly or through metamethods,
3445 and therefore may raise any errors.
3446
3447
3448
3449 <hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
3450 <span class="apii">[-0, +0, &ndash;]</span>
3451 <pre>int lua_absindex (lua_State *L, int idx);</pre>
3452
3453 <p>
3454 Converts the acceptable index <code>idx</code>
3455 into an equivalent absolute index
3456 (that is, one that does not depend on the stack size).
3457
3458
3459
3460
3461
3462 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
3463 <pre>typedef void * (*lua_Alloc) (void *ud,
3464 void *ptr,
3465 size_t osize,
3466 size_t nsize);</pre>
3467
3468 <p>
3469 The type of the memory-allocation function used by Lua states.
3470 The allocator function must provide a
3471 functionality similar to <code>realloc</code>,
3472 but not exactly the same.
3473 Its arguments are
3474 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3475 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3476 <code>osize</code>, the original size of the block or some code about what
3477 is being allocated;
3478 and <code>nsize</code>, the new size of the block.
3479
3480
3481 <p>
3482 When <code>ptr</code> is not <code>NULL</code>,
3483 <code>osize</code> is the size of the block pointed by <code>ptr</code>,
3484 that is, the size given when it was allocated or reallocated.
3485
3486
3487 <p>
3488 When <code>ptr</code> is <code>NULL</code>,
3489 <code>osize</code> encodes the kind of object that Lua is allocating.
3490 <code>osize</code> is any of
3491 <a href="#pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a href="#pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a href="#pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
3492 <a href="#pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, or <a href="#pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a> when (and only when)
3493 Lua is creating a new object of that type.
3494 When <code>osize</code> is some other value,
3495 Lua is allocating memory for something else.
3496
3497
3498 <p>
3499 Lua assumes the following behavior from the allocator function:
3500
3501
3502 <p>
3503 When <code>nsize</code> is zero,
3504 the allocator must behave like <code>free</code>
3505 and then return <code>NULL</code>.
3506
3507
3508 <p>
3509 When <code>nsize</code> is not zero,
3510 the allocator must behave like <code>realloc</code>.
3511 In particular, the allocator returns <code>NULL</code>
3512 if and only if it cannot fulfill the request.
3513
3514
3515 <p>
3516 Here is a simple implementation for the allocator function.
3517 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3518
3519 <pre>
3520 static void *l_alloc (void *ud, void *ptr, size_t osize,
3521 size_t nsize) {
3522 (void)ud; (void)osize; /* not used */
3523 if (nsize == 0) {
3524 free(ptr);
3525 return NULL;
3526 }
3527 else
3528 return realloc(ptr, nsize);
3529 }
3530 </pre><p>
3531 Note that Standard&nbsp;C ensures
3532 that <code>free(NULL)</code> has no effect and that
3533 <code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3534
3535
3536
3537
3538
3539 <hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3540 <span class="apii">[-(2|1), +1, <em>e</em>]</span>
3541 <pre>void lua_arith (lua_State *L, int op);</pre>
3542
3543 <p>
3544 Performs an arithmetic or bitwise operation over the two values
3545 (or one, in the case of negations)
3546 at the top of the stack,
3547 with the value on the top being the second operand,
3548 pops these values, and pushes the result of the operation.
3549 The function follows the semantics of the corresponding Lua operator
3550 (that is, it may call metamethods).
3551
3552
3553 <p>
3554 The value of <code>op</code> must be one of the following constants:
3555
3556 <ul>
3557
3558 <li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3559 <li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3560 <li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3561 <li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3562 <li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3563 <li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3564 <li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3565 <li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3566 <li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li>
3567 <li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li>
3568 <li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li>
3569 <li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li>
3570 <li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3571 <li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3572
3573 </ul>
3574
3575
3576
3577
3578 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3579 <span class="apii">[-0, +0, &ndash;]</span>
3580 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3581
3582 <p>
3583 Sets a new panic function and returns the old one (see <a href="#4.4">&sect;4.4</a>).
3584
3585
3586
3587
3588
3589 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3590 <span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3591 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3592
3593 <p>
3594 Calls a function.
3595 Like regular Lua calls,
3596 <code>lua_call</code> respects the <code>__call</code> metamethod.
3597 So, here the word "function"
3598 means any callable value.
3599
3600
3601 <p>
3602 To do a call you must use the following protocol:
3603 first, the function to be called is pushed onto the stack;
3604 then, the arguments to the call are pushed
3605 in direct order;
3606 that is, the first argument is pushed first.
3607 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3608 <code>nargs</code> is the number of arguments that you pushed onto the stack.
3609 When the function returns,
3610 all arguments and the function value are popped
3611 and the call results are pushed onto the stack.
3612 The number of results is adjusted to <code>nresults</code>,
3613 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3614 In this case, all results from the function are pushed;
3615 Lua takes care that the returned values fit into the stack space,
3616 but it does not ensure any extra space in the stack.
3617 The function results are pushed onto the stack in direct order
3618 (the first result is pushed first),
3619 so that after the call the last result is on the top of the stack.
3620
3621
3622 <p>
3623 Any error while calling and running the function is propagated upwards
3624 (with a <code>longjmp</code>).
3625
3626
3627 <p>
3628 The following example shows how the host program can do the
3629 equivalent to this Lua code:
3630
3631 <pre>
3632 a = f("how", t.x, 14)
3633 </pre><p>
3634 Here it is in&nbsp;C:
3635
3636 <pre>
3637 lua_getglobal(L, "f"); /* function to be called */
3638 lua_pushliteral(L, "how"); /* 1st argument */
3639 lua_getglobal(L, "t"); /* table to be indexed */
3640 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
3641 lua_remove(L, -2); /* remove 't' from the stack */
3642 lua_pushinteger(L, 14); /* 3rd argument */
3643 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
3644 lua_setglobal(L, "a"); /* set global 'a' */
3645 </pre><p>
3646 Note that the code above is <em>balanced</em>:
3647 at its end, the stack is back to its original configuration.
3648 This is considered good programming practice.
3649
3650
3651
3652
3653
3654 <hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3655 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3656 <pre>void lua_callk (lua_State *L,
3657 int nargs,
3658 int nresults,
3659 lua_KContext ctx,
3660 lua_KFunction k);</pre>
3661
3662 <p>
3663 This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3664 but allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
3665
3666
3667
3668
3669
3670 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3671 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3672
3673 <p>
3674 Type for C&nbsp;functions.
3675
3676
3677 <p>
3678 In order to communicate properly with Lua,
3679 a C&nbsp;function must use the following protocol,
3680 which defines the way parameters and results are passed:
3681 a C&nbsp;function receives its arguments from Lua in its stack
3682 in direct order (the first argument is pushed first).
3683 So, when the function starts,
3684 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
3685 The first argument (if any) is at index 1
3686 and its last argument is at index <code>lua_gettop(L)</code>.
3687 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3688 in direct order (the first result is pushed first),
3689 and returns in C the number of results.
3690 Any other value in the stack below the results will be properly
3691 discarded by Lua.
3692 Like a Lua function, a C&nbsp;function called by Lua can also return
3693 many results.
3694
3695
3696 <p>
3697 As an example, the following function receives a variable number
3698 of numeric arguments and returns their average and their sum:
3699
3700 <pre>
3701 static int foo (lua_State *L) {
3702 int n = lua_gettop(L); /* number of arguments */
3703 lua_Number sum = 0.0;
3704 int i;
3705 for (i = 1; i &lt;= n; i++) {
3706 if (!lua_isnumber(L, i)) {
3707 lua_pushliteral(L, "incorrect argument");
3708 lua_error(L);
3709 }
3710 sum += lua_tonumber(L, i);
3711 }
3712 lua_pushnumber(L, sum/n); /* first result */
3713 lua_pushnumber(L, sum); /* second result */
3714 return 2; /* number of results */
3715 }
3716 </pre>
3717
3718
3719
3720
3721 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3722 <span class="apii">[-0, +0, &ndash;]</span>
3723 <pre>int lua_checkstack (lua_State *L, int n);</pre>
3724
3725 <p>
3726 Ensures that the stack has space for at least <code>n</code> extra elements,
3727 that is, that you can safely push up to <code>n</code> values into it.
3728 It returns false if it cannot fulfill the request,
3729 either because it would cause the stack
3730 to be greater than a fixed maximum size
3731 (typically at least several thousand elements) or
3732 because it cannot allocate memory for the extra space.
3733 This function never shrinks the stack;
3734 if the stack already has space for the extra elements,
3735 it is left unchanged.
3736
3737
3738
3739
3740
3741 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3742 <span class="apii">[-0, +0, &ndash;]</span>
3743 <pre>void lua_close (lua_State *L);</pre>
3744
3745 <p>
3746 Close all active to-be-closed variables in the main thread,
3747 release all objects in the given Lua state
3748 (calling the corresponding garbage-collection metamethods, if any),
3749 and frees all dynamic memory used by this state.
3750
3751
3752 <p>
3753 On several platforms, you may not need to call this function,
3754 because all resources are naturally released when the host program ends.
3755 On the other hand, long-running programs that create multiple states,
3756 such as daemons or web servers,
3757 will probably need to close states as soon as they are not needed.
3758
3759
3760
3761
3762
3763 <hr><h3><a name="lua_closeslot"><code>lua_closeslot</code></a></h3><p>
3764 <span class="apii">[-0, +0, <em>e</em>]</span>
3765 <pre>void lua_closeslot (lua_State *L, int index);</pre>
3766
3767 <p>
3768 Close the to-be-closed slot at the given index and set its value to <b>nil</b>.
3769 The index must be the last index previously marked to be closed
3770 (see <a href="#lua_toclose"><code>lua_toclose</code></a>) that is still active (that is, not closed yet).
3771
3772
3773 <p>
3774 A <code>__close</code> metamethod cannot yield
3775 when called through this function.
3776
3777
3778 <p>
3779 (Exceptionally, this function was introduced in release 5.4.3.
3780 It is not present in previous 5.4 releases.)
3781
3782
3783
3784
3785
3786 <hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3787 <span class="apii">[-0, +0, <em>e</em>]</span>
3788 <pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3789
3790 <p>
3791 Compares two Lua values.
3792 Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3793 when compared with the value at index <code>index2</code>,
3794 following the semantics of the corresponding Lua operator
3795 (that is, it may call metamethods).
3796 Otherwise returns&nbsp;0.
3797 Also returns&nbsp;0 if any of the indices is not valid.
3798
3799
3800 <p>
3801 The value of <code>op</code> must be one of the following constants:
3802
3803 <ul>
3804
3805 <li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3806 <li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3807 <li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3808
3809 </ul>
3810
3811
3812
3813
3814 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3815 <span class="apii">[-n, +1, <em>e</em>]</span>
3816 <pre>void lua_concat (lua_State *L, int n);</pre>
3817
3818 <p>
3819 Concatenates the <code>n</code> values at the top of the stack,
3820 pops them, and leaves the result on the top.
3821 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3822 (that is, the function does nothing);
3823 if <code>n</code> is 0, the result is the empty string.
3824 Concatenation is performed following the usual semantics of Lua
3825 (see <a href="#3.4.6">&sect;3.4.6</a>).
3826
3827
3828
3829
3830
3831 <hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3832 <span class="apii">[-0, +0, &ndash;]</span>
3833 <pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3834
3835 <p>
3836 Copies the element at index <code>fromidx</code>
3837 into the valid index <code>toidx</code>,
3838 replacing the value at that position.
3839 Values at other positions are not affected.
3840
3841
3842
3843
3844
3845 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3846 <span class="apii">[-0, +1, <em>m</em>]</span>
3847 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3848
3849 <p>
3850 Creates a new empty table and pushes it onto the stack.
3851 Parameter <code>narr</code> is a hint for how many elements the table
3852 will have as a sequence;
3853 parameter <code>nrec</code> is a hint for how many other elements
3854 the table will have.
3855 Lua may use these hints to preallocate memory for the new table.
3856 This preallocation may help performance when you know in advance
3857 how many elements the table will have.
3858 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3859
3860
3861
3862
3863
3864 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3865 <span class="apii">[-0, +0, &ndash;]</span>
3866 <pre>int lua_dump (lua_State *L,
3867 lua_Writer writer,
3868 void *data,
3869 int strip);</pre>
3870
3871 <p>
3872 Dumps a function as a binary chunk.
3873 Receives a Lua function on the top of the stack
3874 and produces a binary chunk that,
3875 if loaded again,
3876 results in a function equivalent to the one dumped.
3877 As it produces parts of the chunk,
3878 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3879 with the given <code>data</code>
3880 to write them.
3881
3882
3883 <p>
3884 If <code>strip</code> is true,
3885 the binary representation may not include all debug information
3886 about the function,
3887 to save space.
3888
3889
3890 <p>
3891 The value returned is the error code returned by the last
3892 call to the writer;
3893 0&nbsp;means no errors.
3894
3895
3896 <p>
3897 This function does not pop the Lua function from the stack.
3898
3899
3900
3901
3902
3903 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3904 <span class="apii">[-1, +0, <em>v</em>]</span>
3905 <pre>int lua_error (lua_State *L);</pre>
3906
3907 <p>
3908 Raises a Lua error,
3909 using the value on the top of the stack as the error object.
3910 This function does a long jump,
3911 and therefore never returns
3912 (see <a href="#luaL_error"><code>luaL_error</code></a>).
3913
3914
3915
3916
3917
3918 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3919 <span class="apii">[-0, +0, &ndash;]</span>
3920 <pre>int lua_gc (lua_State *L, int what, ...);</pre>
3921
3922 <p>
3923 Controls the garbage collector.
3924
3925
3926 <p>
3927 This function performs several tasks,
3928 according to the value of the parameter <code>what</code>.
3929 For options that need extra arguments,
3930 they are listed after the option.
3931
3932 <ul>
3933
3934 <li><b><code>LUA_GCCOLLECT</code>: </b>
3935 Performs a full garbage-collection cycle.
3936 </li>
3937
3938 <li><b><code>LUA_GCSTOP</code>: </b>
3939 Stops the garbage collector.
3940 </li>
3941
3942 <li><b><code>LUA_GCRESTART</code>: </b>
3943 Restarts the garbage collector.
3944 </li>
3945
3946 <li><b><code>LUA_GCCOUNT</code>: </b>
3947 Returns the current amount of memory (in Kbytes) in use by Lua.
3948 </li>
3949
3950 <li><b><code>LUA_GCCOUNTB</code>: </b>
3951 Returns the remainder of dividing the current amount of bytes of
3952 memory in use by Lua by 1024.
3953 </li>
3954
3955 <li><b><code>LUA_GCSTEP</code> <code>(int stepsize)</code>: </b>
3956 Performs an incremental step of garbage collection,
3957 corresponding to the allocation of <code>stepsize</code> Kbytes.
3958 </li>
3959
3960 <li><b><code>LUA_GCISRUNNING</code>: </b>
3961 Returns a boolean that tells whether the collector is running
3962 (i.e., not stopped).
3963 </li>
3964
3965 <li><b><code>LUA_GCINC</code> (int pause, int stepmul, stepsize): </b>
3966 Changes the collector to incremental mode
3967 with the given parameters (see <a href="#2.5.1">&sect;2.5.1</a>).
3968 Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3969 </li>
3970
3971 <li><b><code>LUA_GCGEN</code> (int minormul, int majormul): </b>
3972 Changes the collector to generational mode
3973 with the given parameters (see <a href="#2.5.2">&sect;2.5.2</a>).
3974 Returns the previous mode (<code>LUA_GCGEN</code> or <code>LUA_GCINC</code>).
3975 </li>
3976
3977 </ul><p>
3978 For more details about these options,
3979 see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3980
3981
3982
3983
3984
3985 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3986 <span class="apii">[-0, +0, &ndash;]</span>
3987 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3988
3989 <p>
3990 Returns the memory-allocation function of a given state.
3991 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3992 opaque pointer given when the memory-allocator function was set.
3993
3994
3995
3996
3997
3998 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3999 <span class="apii">[-0, +1, <em>e</em>]</span>
4000 <pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
4001
4002 <p>
4003 Pushes onto the stack the value <code>t[k]</code>,
4004 where <code>t</code> is the value at the given index.
4005 As in Lua, this function may trigger a metamethod
4006 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4007
4008
4009 <p>
4010 Returns the type of the pushed value.
4011
4012
4013
4014
4015
4016 <hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
4017 <span class="apii">[-0, +0, &ndash;]</span>
4018 <pre>void *lua_getextraspace (lua_State *L);</pre>
4019
4020 <p>
4021 Returns a pointer to a raw memory area associated with the
4022 given Lua state.
4023 The application can use this area for any purpose;
4024 Lua does not use it for anything.
4025
4026
4027 <p>
4028 Each new thread has this area initialized with a copy
4029 of the area of the main thread.
4030
4031
4032 <p>
4033 By default, this area has the size of a pointer to void,
4034 but you can recompile Lua with a different size for this area.
4035 (See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
4036
4037
4038
4039
4040
4041 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
4042 <span class="apii">[-0, +1, <em>e</em>]</span>
4043 <pre>int lua_getglobal (lua_State *L, const char *name);</pre>
4044
4045 <p>
4046 Pushes onto the stack the value of the global <code>name</code>.
4047 Returns the type of that value.
4048
4049
4050
4051
4052
4053 <hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
4054 <span class="apii">[-0, +1, <em>e</em>]</span>
4055 <pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
4056
4057 <p>
4058 Pushes onto the stack the value <code>t[i]</code>,
4059 where <code>t</code> is the value at the given index.
4060 As in Lua, this function may trigger a metamethod
4061 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4062
4063
4064 <p>
4065 Returns the type of the pushed value.
4066
4067
4068
4069
4070
4071 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
4072 <span class="apii">[-0, +(0|1), &ndash;]</span>
4073 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
4074
4075 <p>
4076 If the value at the given index has a metatable,
4077 the function pushes that metatable onto the stack and returns&nbsp;1.
4078 Otherwise,
4079 the function returns&nbsp;0 and pushes nothing on the stack.
4080
4081
4082
4083
4084
4085 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
4086 <span class="apii">[-1, +1, <em>e</em>]</span>
4087 <pre>int lua_gettable (lua_State *L, int index);</pre>
4088
4089 <p>
4090 Pushes onto the stack the value <code>t[k]</code>,
4091 where <code>t</code> is the value at the given index
4092 and <code>k</code> is the value on the top of the stack.
4093
4094
4095 <p>
4096 This function pops the key from the stack,
4097 pushing the resulting value in its place.
4098 As in Lua, this function may trigger a metamethod
4099 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
4100
4101
4102 <p>
4103 Returns the type of the pushed value.
4104
4105
4106
4107
4108
4109 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
4110 <span class="apii">[-0, +0, &ndash;]</span>
4111 <pre>int lua_gettop (lua_State *L);</pre>
4112
4113 <p>
4114 Returns the index of the top element in the stack.
4115 Because indices start at&nbsp;1,
4116 this result is equal to the number of elements in the stack;
4117 in particular, 0&nbsp;means an empty stack.
4118
4119
4120
4121
4122
4123 <hr><h3><a name="lua_getiuservalue"><code>lua_getiuservalue</code></a></h3><p>
4124 <span class="apii">[-0, +1, &ndash;]</span>
4125 <pre>int lua_getiuservalue (lua_State *L, int index, int n);</pre>
4126
4127 <p>
4128 Pushes onto the stack the <code>n</code>-th user value associated with the
4129 full userdata at the given index and
4130 returns the type of the pushed value.
4131
4132
4133 <p>
4134 If the userdata does not have that value,
4135 pushes <b>nil</b> and returns <a href="#pdf-LUA_TNONE"><code>LUA_TNONE</code></a>.
4136
4137
4138
4139
4140
4141 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
4142 <span class="apii">[-1, +1, &ndash;]</span>
4143 <pre>void lua_insert (lua_State *L, int index);</pre>
4144
4145 <p>
4146 Moves the top element into the given valid index,
4147 shifting up the elements above this index to open space.
4148 This function cannot be called with a pseudo-index,
4149 because a pseudo-index is not an actual stack position.
4150
4151
4152
4153
4154
4155 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
4156 <pre>typedef ... lua_Integer;</pre>
4157
4158 <p>
4159 The type of integers in Lua.
4160
4161
4162 <p>
4163 By default this type is <code>long long</code>,
4164 (usually a 64-bit two-complement integer),
4165 but that can be changed to <code>long</code> or <code>int</code>
4166 (usually a 32-bit two-complement integer).
4167 (See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.)
4168
4169
4170 <p>
4171 Lua also defines the constants
4172 <a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
4173 with the minimum and the maximum values that fit in this type.
4174
4175
4176
4177
4178
4179 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
4180 <span class="apii">[-0, +0, &ndash;]</span>
4181 <pre>int lua_isboolean (lua_State *L, int index);</pre>
4182
4183 <p>
4184 Returns 1 if the value at the given index is a boolean,
4185 and 0&nbsp;otherwise.
4186
4187
4188
4189
4190
4191 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
4192 <span class="apii">[-0, +0, &ndash;]</span>
4193 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
4194
4195 <p>
4196 Returns 1 if the value at the given index is a C&nbsp;function,
4197 and 0&nbsp;otherwise.
4198
4199
4200
4201
4202
4203 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
4204 <span class="apii">[-0, +0, &ndash;]</span>
4205 <pre>int lua_isfunction (lua_State *L, int index);</pre>
4206
4207 <p>
4208 Returns 1 if the value at the given index is a function
4209 (either C or Lua), and 0&nbsp;otherwise.
4210
4211
4212
4213
4214
4215 <hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
4216 <span class="apii">[-0, +0, &ndash;]</span>
4217 <pre>int lua_isinteger (lua_State *L, int index);</pre>
4218
4219 <p>
4220 Returns 1 if the value at the given index is an integer
4221 (that is, the value is a number and is represented as an integer),
4222 and 0&nbsp;otherwise.
4223
4224
4225
4226
4227
4228 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
4229 <span class="apii">[-0, +0, &ndash;]</span>
4230 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
4231
4232 <p>
4233 Returns 1 if the value at the given index is a light userdata,
4234 and 0&nbsp;otherwise.
4235
4236
4237
4238
4239
4240 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
4241 <span class="apii">[-0, +0, &ndash;]</span>
4242 <pre>int lua_isnil (lua_State *L, int index);</pre>
4243
4244 <p>
4245 Returns 1 if the value at the given index is <b>nil</b>,
4246 and 0&nbsp;otherwise.
4247
4248
4249
4250
4251
4252 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
4253 <span class="apii">[-0, +0, &ndash;]</span>
4254 <pre>int lua_isnone (lua_State *L, int index);</pre>
4255
4256 <p>
4257 Returns 1 if the given index is not valid,
4258 and 0&nbsp;otherwise.
4259
4260
4261
4262
4263
4264 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
4265 <span class="apii">[-0, +0, &ndash;]</span>
4266 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
4267
4268 <p>
4269 Returns 1 if the given index is not valid
4270 or if the value at this index is <b>nil</b>,
4271 and 0&nbsp;otherwise.
4272
4273
4274
4275
4276
4277 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
4278 <span class="apii">[-0, +0, &ndash;]</span>
4279 <pre>int lua_isnumber (lua_State *L, int index);</pre>
4280
4281 <p>
4282 Returns 1 if the value at the given index is a number
4283 or a string convertible to a number,
4284 and 0&nbsp;otherwise.
4285
4286
4287
4288
4289
4290 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
4291 <span class="apii">[-0, +0, &ndash;]</span>
4292 <pre>int lua_isstring (lua_State *L, int index);</pre>
4293
4294 <p>
4295 Returns 1 if the value at the given index is a string
4296 or a number (which is always convertible to a string),
4297 and 0&nbsp;otherwise.
4298
4299
4300
4301
4302
4303 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
4304 <span class="apii">[-0, +0, &ndash;]</span>
4305 <pre>int lua_istable (lua_State *L, int index);</pre>
4306
4307 <p>
4308 Returns 1 if the value at the given index is a table,
4309 and 0&nbsp;otherwise.
4310
4311
4312
4313
4314
4315 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
4316 <span class="apii">[-0, +0, &ndash;]</span>
4317 <pre>int lua_isthread (lua_State *L, int index);</pre>
4318
4319 <p>
4320 Returns 1 if the value at the given index is a thread,
4321 and 0&nbsp;otherwise.
4322
4323
4324
4325
4326
4327 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
4328 <span class="apii">[-0, +0, &ndash;]</span>
4329 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
4330
4331 <p>
4332 Returns 1 if the value at the given index is a userdata
4333 (either full or light), and 0&nbsp;otherwise.
4334
4335
4336
4337
4338
4339 <hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
4340 <span class="apii">[-0, +0, &ndash;]</span>
4341 <pre>int lua_isyieldable (lua_State *L);</pre>
4342
4343 <p>
4344 Returns 1 if the given coroutine can yield,
4345 and 0&nbsp;otherwise.
4346
4347
4348
4349
4350
4351 <hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
4352 <pre>typedef ... lua_KContext;</pre>
4353
4354 <p>
4355 The type for continuation-function contexts.
4356 It must be a numeric type.
4357 This type is defined as <code>intptr_t</code>
4358 when <code>intptr_t</code> is available,
4359 so that it can store pointers too.
4360 Otherwise, it is defined as <code>ptrdiff_t</code>.
4361
4362
4363
4364
4365
4366 <hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
4367 <pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
4368
4369 <p>
4370 Type for continuation functions (see <a href="#4.5">&sect;4.5</a>).
4371
4372
4373
4374
4375
4376 <hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
4377 <span class="apii">[-0, +1, <em>e</em>]</span>
4378 <pre>void lua_len (lua_State *L, int index);</pre>
4379
4380 <p>
4381 Returns the length of the value at the given index.
4382 It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
4383 may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
4384 The result is pushed on the stack.
4385
4386
4387
4388
4389
4390 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
4391 <span class="apii">[-0, +1, &ndash;]</span>
4392 <pre>int lua_load (lua_State *L,
4393 lua_Reader reader,
4394 void *data,
4395 const char *chunkname,
4396 const char *mode);</pre>
4397
4398 <p>
4399 Loads a Lua chunk without running it.
4400 If there are no errors,
4401 <code>lua_load</code> pushes the compiled chunk as a Lua
4402 function on top of the stack.
4403 Otherwise, it pushes an error message.
4404
4405
4406 <p>
4407 The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
4408 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
4409 The <code>data</code> argument is an opaque value passed to the reader function.
4410
4411
4412 <p>
4413 The <code>chunkname</code> argument gives a name to the chunk,
4414 which is used for error messages and in debug information (see <a href="#4.7">&sect;4.7</a>).
4415
4416
4417 <p>
4418 <code>lua_load</code> automatically detects whether the chunk is text or binary
4419 and loads it accordingly (see program <code>luac</code>).
4420 The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
4421 with the addition that
4422 a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
4423
4424
4425 <p>
4426 <code>lua_load</code> uses the stack internally,
4427 so the reader function must always leave the stack
4428 unmodified when returning.
4429
4430
4431 <p>
4432 <code>lua_load</code> can return
4433 <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>, <a href="#pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>, or <a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>.
4434 The function may also return other values corresponding to
4435 errors raised by the read function (see <a href="#4.4.1">&sect;4.4.1</a>).
4436
4437
4438 <p>
4439 If the resulting function has upvalues,
4440 its first upvalue is set to the value of the global environment
4441 stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.3">&sect;4.3</a>).
4442 When loading main chunks,
4443 this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
4444 Other upvalues are initialized with <b>nil</b>.
4445
4446
4447
4448
4449
4450 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
4451 <span class="apii">[-0, +0, &ndash;]</span>
4452 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
4453
4454 <p>
4455 Creates a new independent state and returns its main thread.
4456 Returns <code>NULL</code> if it cannot create the state
4457 (due to lack of memory).
4458 The argument <code>f</code> is the allocator function;
4459 Lua will do all memory allocation for this state
4460 through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
4461 The second argument, <code>ud</code>, is an opaque pointer that Lua
4462 passes to the allocator in every call.
4463
4464
4465
4466
4467
4468 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
4469 <span class="apii">[-0, +1, <em>m</em>]</span>
4470 <pre>void lua_newtable (lua_State *L);</pre>
4471
4472 <p>
4473 Creates a new empty table and pushes it onto the stack.
4474 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
4475
4476
4477
4478
4479
4480 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
4481 <span class="apii">[-0, +1, <em>m</em>]</span>
4482 <pre>lua_State *lua_newthread (lua_State *L);</pre>
4483
4484 <p>
4485 Creates a new thread, pushes it on the stack,
4486 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
4487 The new thread returned by this function shares with the original thread
4488 its global environment,
4489 but has an independent execution stack.
4490
4491
4492 <p>
4493 Threads are subject to garbage collection,
4494 like any Lua object.
4495
4496
4497
4498
4499
4500 <hr><h3><a name="lua_newuserdatauv"><code>lua_newuserdatauv</code></a></h3><p>
4501 <span class="apii">[-0, +1, <em>m</em>]</span>
4502 <pre>void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);</pre>
4503
4504 <p>
4505 This function creates and pushes on the stack a new full userdata,
4506 with <code>nuvalue</code> associated Lua values, called <code>user values</code>,
4507 plus an associated block of raw memory with <code>size</code> bytes.
4508 (The user values can be set and read with the functions
4509 <a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a> and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>.)
4510
4511
4512 <p>
4513 The function returns the address of the block of memory.
4514 Lua ensures that this address is valid as long as
4515 the corresponding userdata is alive (see <a href="#2.5">&sect;2.5</a>).
4516 Moreover, if the userdata is marked for finalization (see <a href="#2.5.3">&sect;2.5.3</a>),
4517 its address is valid at least until the call to its finalizer.
4518
4519
4520
4521
4522
4523 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4524 <span class="apii">[-1, +(2|0), <em>v</em>]</span>
4525 <pre>int lua_next (lua_State *L, int index);</pre>
4526
4527 <p>
4528 Pops a key from the stack,
4529 and pushes a key&ndash;value pair from the table at the given index,
4530 the "next" pair after the given key.
4531 If there are no more elements in the table,
4532 then <a href="#lua_next"><code>lua_next</code></a> returns 0 and pushes nothing.
4533
4534
4535 <p>
4536 A typical table traversal looks like this:
4537
4538 <pre>
4539 /* table is in the stack at index 't' */
4540 lua_pushnil(L); /* first key */
4541 while (lua_next(L, t) != 0) {
4542 /* uses 'key' (at index -2) and 'value' (at index -1) */
4543 printf("%s - %s\n",
4544 lua_typename(L, lua_type(L, -2)),
4545 lua_typename(L, lua_type(L, -1)));
4546 /* removes 'value'; keeps 'key' for next iteration */
4547 lua_pop(L, 1);
4548 }
4549 </pre>
4550
4551 <p>
4552 While traversing a table,
4553 avoid calling <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4554 unless you know that the key is actually a string.
4555 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4556 the value at the given index;
4557 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4558
4559
4560 <p>
4561 This function may raise an error if the given key
4562 is neither <b>nil</b> nor present in the table.
4563 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4564 the table during its traversal.
4565
4566
4567
4568
4569
4570 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4571 <pre>typedef ... lua_Number;</pre>
4572
4573 <p>
4574 The type of floats in Lua.
4575
4576
4577 <p>
4578 By default this type is double,
4579 but that can be changed to a single float or a long double.
4580 (See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.)
4581
4582
4583
4584
4585
4586 <hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4587 <pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4588
4589 <p>
4590 Tries to convert a Lua float to a Lua integer;
4591 the float <code>n</code> must have an integral value.
4592 If that value is within the range of Lua integers,
4593 it is converted to an integer and assigned to <code>*p</code>.
4594 The macro results in a boolean indicating whether the
4595 conversion was successful.
4596 (Note that this range test can be tricky to do
4597 correctly without this macro, due to rounding.)
4598
4599
4600 <p>
4601 This macro may evaluate its arguments more than once.
4602
4603
4604
4605
4606
4607 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4608 <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4609 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4610
4611 <p>
4612 Calls a function (or a callable object) in protected mode.
4613
4614
4615 <p>
4616 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4617 in <a href="#lua_call"><code>lua_call</code></a>.
4618 If there are no errors during the call,
4619 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4620 However, if there is any error,
4621 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4622 pushes a single value on the stack (the error object),
4623 and returns an error code.
4624 Like <a href="#lua_call"><code>lua_call</code></a>,
4625 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4626 and its arguments from the stack.
4627
4628
4629 <p>
4630 If <code>msgh</code> is 0,
4631 then the error object returned on the stack
4632 is exactly the original error object.
4633 Otherwise, <code>msgh</code> is the stack index of a
4634 <em>message handler</em>.
4635 (This index cannot be a pseudo-index.)
4636 In case of runtime errors,
4637 this handler will be called with the error object
4638 and its return value will be the object
4639 returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4640
4641
4642 <p>
4643 Typically, the message handler is used to add more debug
4644 information to the error object, such as a stack traceback.
4645 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4646 since by then the stack has unwound.
4647
4648
4649 <p>
4650 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following status codes:
4651 <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>, <a href="#pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>, <a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>, or <a href="#pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>.
4652
4653
4654
4655
4656
4657 <hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4658 <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4659 <pre>int lua_pcallk (lua_State *L,
4660 int nargs,
4661 int nresults,
4662 int msgh,
4663 lua_KContext ctx,
4664 lua_KFunction k);</pre>
4665
4666 <p>
4667 This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4668 except that it allows the called function to yield (see <a href="#4.5">&sect;4.5</a>).
4669
4670
4671
4672
4673
4674 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4675 <span class="apii">[-n, +0, <em>e</em>]</span>
4676 <pre>void lua_pop (lua_State *L, int n);</pre>
4677
4678 <p>
4679 Pops <code>n</code> elements from the stack.
4680 It is implemented as a macro over <a href="#lua_settop"><code>lua_settop</code></a>.
4681
4682
4683
4684
4685
4686 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4687 <span class="apii">[-0, +1, &ndash;]</span>
4688 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
4689
4690 <p>
4691 Pushes a boolean value with value <code>b</code> onto the stack.
4692
4693
4694
4695
4696
4697 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4698 <span class="apii">[-n, +1, <em>m</em>]</span>
4699 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4700
4701 <p>
4702 Pushes a new C&nbsp;closure onto the stack.
4703 This function receives a pointer to a C&nbsp;function
4704 and pushes onto the stack a Lua value of type <code>function</code> that,
4705 when called, invokes the corresponding C&nbsp;function.
4706 The parameter <code>n</code> tells how many upvalues this function will have
4707 (see <a href="#4.2">&sect;4.2</a>).
4708
4709
4710 <p>
4711 Any function to be callable by Lua must
4712 follow the correct protocol to receive its parameters
4713 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4714
4715
4716 <p>
4717 When a C&nbsp;function is created,
4718 it is possible to associate some values with it,
4719 the so called upvalues;
4720 these upvalues are then accessible to the function whenever it is called.
4721 This association is called a C&nbsp;closure (see <a href="#4.2">&sect;4.2</a>).
4722 To create a C&nbsp;closure,
4723 first the initial values for its upvalues must be pushed onto the stack.
4724 (When there are multiple upvalues, the first value is pushed first.)
4725 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4726 is called to create and push the C&nbsp;function onto the stack,
4727 with the argument <code>n</code> telling how many values will be
4728 associated with the function.
4729 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4730
4731
4732 <p>
4733 The maximum value for <code>n</code> is 255.
4734
4735
4736 <p>
4737 When <code>n</code> is zero,
4738 this function creates a <em>light C&nbsp;function</em>,
4739 which is just a pointer to the C&nbsp;function.
4740 In that case, it never raises a memory error.
4741
4742
4743
4744
4745
4746 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4747 <span class="apii">[-0, +1, &ndash;]</span>
4748 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4749
4750 <p>
4751 Pushes a C&nbsp;function onto the stack.
4752 This function is equivalent to <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> with no upvalues.
4753
4754
4755
4756
4757
4758 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4759 <span class="apii">[-0, +1, <em>v</em>]</span>
4760 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4761
4762 <p>
4763 Pushes onto the stack a formatted string
4764 and returns a pointer to this string (see <a href="#4.1.3">&sect;4.1.3</a>).
4765 It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4766 but has two important differences.
4767 First,
4768 you do not have to allocate space for the result;
4769 the result is a Lua string and Lua takes care of memory allocation
4770 (and deallocation, through garbage collection).
4771 Second,
4772 the conversion specifiers are quite restricted.
4773 There are no flags, widths, or precisions.
4774 The conversion specifiers can only be
4775 '<code>%%</code>' (inserts the character '<code>%</code>'),
4776 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4777 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4778 '<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4779 '<code>%p</code>' (inserts a pointer),
4780 '<code>%d</code>' (inserts an <code>int</code>),
4781 '<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4782 '<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4783
4784
4785 <p>
4786 This function may raise errors due to memory overflow
4787 or an invalid conversion specifier.
4788
4789
4790
4791
4792
4793 <hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4794 <span class="apii">[-0, +1, &ndash;]</span>
4795 <pre>void lua_pushglobaltable (lua_State *L);</pre>
4796
4797 <p>
4798 Pushes the global environment onto the stack.
4799
4800
4801
4802
4803
4804 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4805 <span class="apii">[-0, +1, &ndash;]</span>
4806 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4807
4808 <p>
4809 Pushes an integer with value <code>n</code> onto the stack.
4810
4811
4812
4813
4814
4815 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4816 <span class="apii">[-0, +1, &ndash;]</span>
4817 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4818
4819 <p>
4820 Pushes a light userdata onto the stack.
4821
4822
4823 <p>
4824 Userdata represent C&nbsp;values in Lua.
4825 A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4826 It is a value (like a number):
4827 you do not create it, it has no individual metatable,
4828 and it is not collected (as it was never created).
4829 A light userdata is equal to "any"
4830 light userdata with the same C&nbsp;address.
4831
4832
4833
4834
4835
4836 <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4837 <span class="apii">[-0, +1, <em>m</em>]</span>
4838 <pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4839
4840 <p>
4841 This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>,
4842 but should be used only when <code>s</code> is a literal string.
4843 (Lua may optimize this case.)
4844
4845
4846
4847
4848
4849 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4850 <span class="apii">[-0, +1, <em>m</em>]</span>
4851 <pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4852
4853 <p>
4854 Pushes the string pointed to by <code>s</code> with size <code>len</code>
4855 onto the stack.
4856 Lua will make or reuse an internal copy of the given string,
4857 so the memory at <code>s</code> can be freed or reused immediately after
4858 the function returns.
4859 The string can contain any binary data,
4860 including embedded zeros.
4861
4862
4863 <p>
4864 Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4865
4866
4867
4868
4869
4870 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4871 <span class="apii">[-0, +1, &ndash;]</span>
4872 <pre>void lua_pushnil (lua_State *L);</pre>
4873
4874 <p>
4875 Pushes a nil value onto the stack.
4876
4877
4878
4879
4880
4881 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4882 <span class="apii">[-0, +1, &ndash;]</span>
4883 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4884
4885 <p>
4886 Pushes a float with value <code>n</code> onto the stack.
4887
4888
4889
4890
4891
4892 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4893 <span class="apii">[-0, +1, <em>m</em>]</span>
4894 <pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4895
4896 <p>
4897 Pushes the zero-terminated string pointed to by <code>s</code>
4898 onto the stack.
4899 Lua will make or reuse an internal copy of the given string,
4900 so the memory at <code>s</code> can be freed or reused immediately after
4901 the function returns.
4902
4903
4904 <p>
4905 Returns a pointer to the internal copy of the string (see <a href="#4.1.3">&sect;4.1.3</a>).
4906
4907
4908 <p>
4909 If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4910
4911
4912
4913
4914
4915 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4916 <span class="apii">[-0, +1, &ndash;]</span>
4917 <pre>int lua_pushthread (lua_State *L);</pre>
4918
4919 <p>
4920 Pushes the thread represented by <code>L</code> onto the stack.
4921 Returns 1 if this thread is the main thread of its state.
4922
4923
4924
4925
4926
4927 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4928 <span class="apii">[-0, +1, &ndash;]</span>
4929 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
4930
4931 <p>
4932 Pushes a copy of the element at the given index
4933 onto the stack.
4934
4935
4936
4937
4938
4939 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4940 <span class="apii">[-0, +1, <em>v</em>]</span>
4941 <pre>const char *lua_pushvfstring (lua_State *L,
4942 const char *fmt,
4943 va_list argp);</pre>
4944
4945 <p>
4946 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4947 instead of a variable number of arguments.
4948
4949
4950
4951
4952
4953 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4954 <span class="apii">[-0, +0, &ndash;]</span>
4955 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4956
4957 <p>
4958 Returns 1 if the two values in indices <code>index1</code> and
4959 <code>index2</code> are primitively equal
4960 (that is, equal without calling the <code>__eq</code> metamethod).
4961 Otherwise returns&nbsp;0.
4962 Also returns&nbsp;0 if any of the indices are not valid.
4963
4964
4965
4966
4967
4968 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4969 <span class="apii">[-1, +1, &ndash;]</span>
4970 <pre>int lua_rawget (lua_State *L, int index);</pre>
4971
4972 <p>
4973 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4974 (i.e., without metamethods).
4975
4976
4977
4978
4979
4980 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4981 <span class="apii">[-0, +1, &ndash;]</span>
4982 <pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4983
4984 <p>
4985 Pushes onto the stack the value <code>t[n]</code>,
4986 where <code>t</code> is the table at the given index.
4987 The access is raw,
4988 that is, it does not use the <code>__index</code> metavalue.
4989
4990
4991 <p>
4992 Returns the type of the pushed value.
4993
4994
4995
4996
4997
4998 <hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4999 <span class="apii">[-0, +1, &ndash;]</span>
5000 <pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
5001
5002 <p>
5003 Pushes onto the stack the value <code>t[k]</code>,
5004 where <code>t</code> is the table at the given index and
5005 <code>k</code> is the pointer <code>p</code> represented as a light userdata.
5006 The access is raw;
5007 that is, it does not use the <code>__index</code> metavalue.
5008
5009
5010 <p>
5011 Returns the type of the pushed value.
5012
5013
5014
5015
5016
5017 <hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
5018 <span class="apii">[-0, +0, &ndash;]</span>
5019 <pre>lua_Unsigned lua_rawlen (lua_State *L, int index);</pre>
5020
5021 <p>
5022 Returns the raw "length" of the value at the given index:
5023 for strings, this is the string length;
5024 for tables, this is the result of the length operator ('<code>#</code>')
5025 with no metamethods;
5026 for userdata, this is the size of the block of memory allocated
5027 for the userdata.
5028 For other values, this call returns&nbsp;0.
5029
5030
5031
5032
5033
5034 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
5035 <span class="apii">[-2, +0, <em>m</em>]</span>
5036 <pre>void lua_rawset (lua_State *L, int index);</pre>
5037
5038 <p>
5039 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
5040 (i.e., without metamethods).
5041
5042
5043
5044
5045
5046 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
5047 <span class="apii">[-1, +0, <em>m</em>]</span>
5048 <pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
5049
5050 <p>
5051 Does the equivalent of <code>t[i] = v</code>,
5052 where <code>t</code> is the table at the given index
5053 and <code>v</code> is the value on the top of the stack.
5054
5055
5056 <p>
5057 This function pops the value from the stack.
5058 The assignment is raw,
5059 that is, it does not use the <code>__newindex</code> metavalue.
5060
5061
5062
5063
5064
5065 <hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
5066 <span class="apii">[-1, +0, <em>m</em>]</span>
5067 <pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
5068
5069 <p>
5070 Does the equivalent of <code>t[p] = v</code>,
5071 where <code>t</code> is the table at the given index,
5072 <code>p</code> is encoded as a light userdata,
5073 and <code>v</code> is the value on the top of the stack.
5074
5075
5076 <p>
5077 This function pops the value from the stack.
5078 The assignment is raw,
5079 that is, it does not use the <code>__newindex</code> metavalue.
5080
5081
5082
5083
5084
5085 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
5086 <pre>typedef const char * (*lua_Reader) (lua_State *L,
5087 void *data,
5088 size_t *size);</pre>
5089
5090 <p>
5091 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
5092 Every time <a href="#lua_load"><code>lua_load</code></a> needs another piece of the chunk,
5093 it calls the reader,
5094 passing along its <code>data</code> parameter.
5095 The reader must return a pointer to a block of memory
5096 with a new piece of the chunk
5097 and set <code>size</code> to the block size.
5098 The block must exist until the reader function is called again.
5099 To signal the end of the chunk,
5100 the reader must return <code>NULL</code> or set <code>size</code> to zero.
5101 The reader function may return pieces of any size greater than zero.
5102
5103
5104
5105
5106
5107 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
5108 <span class="apii">[-0, +0, <em>e</em>]</span>
5109 <pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
5110
5111 <p>
5112 Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>.
5113 It is defined as a macro:
5114
5115 <pre>
5116 #define lua_register(L,n,f) \
5117 (lua_pushcfunction(L, f), lua_setglobal(L, n))
5118 </pre>
5119
5120
5121
5122
5123 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
5124 <span class="apii">[-1, +0, &ndash;]</span>
5125 <pre>void lua_remove (lua_State *L, int index);</pre>
5126
5127 <p>
5128 Removes the element at the given valid index,
5129 shifting down the elements above this index to fill the gap.
5130 This function cannot be called with a pseudo-index,
5131 because a pseudo-index is not an actual stack position.
5132
5133
5134
5135
5136
5137 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
5138 <span class="apii">[-1, +0, &ndash;]</span>
5139 <pre>void lua_replace (lua_State *L, int index);</pre>
5140
5141 <p>
5142 Moves the top element into the given valid index
5143 without shifting any element
5144 (therefore replacing the value at that given index),
5145 and then pops the top element.
5146
5147
5148
5149
5150
5151 <hr><h3><a name="lua_resetthread"><code>lua_resetthread</code></a></h3><p>
5152 <span class="apii">[-0, +?, &ndash;]</span>
5153 <pre>int lua_resetthread (lua_State *L);</pre>
5154
5155 <p>
5156 Resets a thread, cleaning its call stack and closing all pending
5157 to-be-closed variables.
5158 Returns a status code:
5159 <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for no errors in the thread
5160 (either the original error that stopped the thread or
5161 errors in closing methods),
5162 or an error status otherwise.
5163 In case of error,
5164 leaves the error object on the top of the stack.
5165
5166
5167
5168
5169
5170 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
5171 <span class="apii">[-?, +?, &ndash;]</span>
5172 <pre>int lua_resume (lua_State *L, lua_State *from, int nargs,
5173 int *nresults);</pre>
5174
5175 <p>
5176 Starts and resumes a coroutine in the given thread <code>L</code>.
5177
5178
5179 <p>
5180 To start a coroutine,
5181 you push the main function plus any arguments
5182 onto the empty stack of the thread.
5183 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
5184 with <code>nargs</code> being the number of arguments.
5185 This call returns when the coroutine suspends or finishes its execution.
5186 When it returns,
5187 <code>*nresults</code> is updated and
5188 the top of the stack contains
5189 the <code>*nresults</code> values passed to <a href="#lua_yield"><code>lua_yield</code></a>
5190 or returned by the body function.
5191 <a href="#lua_resume"><code>lua_resume</code></a> returns
5192 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
5193 <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
5194 without errors,
5195 or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
5196 In case of errors,
5197 the error object is on the top of the stack.
5198
5199
5200 <p>
5201 To resume a coroutine,
5202 you remove the <code>*nresults</code> yielded values from its stack,
5203 push the values to be passed as results from <code>yield</code>,
5204 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
5205
5206
5207 <p>
5208 The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
5209 If there is no such coroutine,
5210 this parameter can be <code>NULL</code>.
5211
5212
5213
5214
5215
5216 <hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
5217 <span class="apii">[-0, +0, &ndash;]</span>
5218 <pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
5219
5220 <p>
5221 Rotates the stack elements between the valid index <code>idx</code>
5222 and the top of the stack.
5223 The elements are rotated <code>n</code> positions in the direction of the top,
5224 for a positive <code>n</code>,
5225 or <code>-n</code> positions in the direction of the bottom,
5226 for a negative <code>n</code>.
5227 The absolute value of <code>n</code> must not be greater than the size
5228 of the slice being rotated.
5229 This function cannot be called with a pseudo-index,
5230 because a pseudo-index is not an actual stack position.
5231
5232
5233
5234
5235
5236 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
5237 <span class="apii">[-0, +0, &ndash;]</span>
5238 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
5239
5240 <p>
5241 Changes the allocator function of a given state to <code>f</code>
5242 with user data <code>ud</code>.
5243
5244
5245
5246
5247
5248 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
5249 <span class="apii">[-1, +0, <em>e</em>]</span>
5250 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
5251
5252 <p>
5253 Does the equivalent to <code>t[k] = v</code>,
5254 where <code>t</code> is the value at the given index
5255 and <code>v</code> is the value on the top of the stack.
5256
5257
5258 <p>
5259 This function pops the value from the stack.
5260 As in Lua, this function may trigger a metamethod
5261 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5262
5263
5264
5265
5266
5267 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
5268 <span class="apii">[-1, +0, <em>e</em>]</span>
5269 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
5270
5271 <p>
5272 Pops a value from the stack and
5273 sets it as the new value of global <code>name</code>.
5274
5275
5276
5277
5278
5279 <hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
5280 <span class="apii">[-1, +0, <em>e</em>]</span>
5281 <pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
5282
5283 <p>
5284 Does the equivalent to <code>t[n] = v</code>,
5285 where <code>t</code> is the value at the given index
5286 and <code>v</code> is the value on the top of the stack.
5287
5288
5289 <p>
5290 This function pops the value from the stack.
5291 As in Lua, this function may trigger a metamethod
5292 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5293
5294
5295
5296
5297
5298 <hr><h3><a name="lua_setiuservalue"><code>lua_setiuservalue</code></a></h3><p>
5299 <span class="apii">[-1, +0, &ndash;]</span>
5300 <pre>int lua_setiuservalue (lua_State *L, int index, int n);</pre>
5301
5302 <p>
5303 Pops a value from the stack and sets it as
5304 the new <code>n</code>-th user value associated to the
5305 full userdata at the given index.
5306 Returns 0 if the userdata does not have that value.
5307
5308
5309
5310
5311
5312 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
5313 <span class="apii">[-1, +0, &ndash;]</span>
5314 <pre>int lua_setmetatable (lua_State *L, int index);</pre>
5315
5316 <p>
5317 Pops a table or <b>nil</b> from the stack and
5318 sets that value as the new metatable for the value at the given index.
5319 (<b>nil</b> means no metatable.)
5320
5321
5322 <p>
5323 (For historical reasons, this function returns an <code>int</code>,
5324 which now is always 1.)
5325
5326
5327
5328
5329
5330 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
5331 <span class="apii">[-2, +0, <em>e</em>]</span>
5332 <pre>void lua_settable (lua_State *L, int index);</pre>
5333
5334 <p>
5335 Does the equivalent to <code>t[k] = v</code>,
5336 where <code>t</code> is the value at the given index,
5337 <code>v</code> is the value on the top of the stack,
5338 and <code>k</code> is the value just below the top.
5339
5340
5341 <p>
5342 This function pops both the key and the value from the stack.
5343 As in Lua, this function may trigger a metamethod
5344 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
5345
5346
5347
5348
5349
5350 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
5351 <span class="apii">[-?, +?, <em>e</em>]</span>
5352 <pre>void lua_settop (lua_State *L, int index);</pre>
5353
5354 <p>
5355 Accepts any index, or&nbsp;0,
5356 and sets the stack top to this index.
5357 If the new top is greater than the old one,
5358 then the new elements are filled with <b>nil</b>.
5359 If <code>index</code> is&nbsp;0, then all stack elements are removed.
5360
5361
5362 <p>
5363 This function can run arbitrary code when removing an index
5364 marked as to-be-closed from the stack.
5365
5366
5367
5368
5369
5370 <hr><h3><a name="lua_setwarnf"><code>lua_setwarnf</code></a></h3><p>
5371 <span class="apii">[-0, +0, &ndash;]</span>
5372 <pre>void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);</pre>
5373
5374 <p>
5375 Sets the warning function to be used by Lua to emit warnings
5376 (see <a href="#lua_WarnFunction"><code>lua_WarnFunction</code></a>).
5377 The <code>ud</code> parameter sets the value <code>ud</code> passed to
5378 the warning function.
5379
5380
5381
5382
5383
5384 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
5385 <pre>typedef struct lua_State lua_State;</pre>
5386
5387 <p>
5388 An opaque structure that points to a thread and indirectly
5389 (through the thread) to the whole state of a Lua interpreter.
5390 The Lua library is fully reentrant:
5391 it has no global variables.
5392 All information about a state is accessible through this structure.
5393
5394
5395 <p>
5396 A pointer to this structure must be passed as the first argument to
5397 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
5398 which creates a Lua state from scratch.
5399
5400
5401
5402
5403
5404 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
5405 <span class="apii">[-0, +0, &ndash;]</span>
5406 <pre>int lua_status (lua_State *L);</pre>
5407
5408 <p>
5409 Returns the status of the thread <code>L</code>.
5410
5411
5412 <p>
5413 The status can be <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> for a normal thread,
5414 an error code if the thread finished the execution
5415 of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
5416 or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
5417
5418
5419 <p>
5420 You can call functions only in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
5421 You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
5422 (to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
5423 (to resume a coroutine).
5424
5425
5426
5427
5428
5429 <hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
5430 <span class="apii">[-0, +1, &ndash;]</span>
5431 <pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
5432
5433 <p>
5434 Converts the zero-terminated string <code>s</code> to a number,
5435 pushes that number into the stack,
5436 and returns the total size of the string,
5437 that is, its length plus one.
5438 The conversion can result in an integer or a float,
5439 according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
5440 The string may have leading and trailing whitespaces and a sign.
5441 If the string is not a valid numeral,
5442 returns 0 and pushes nothing.
5443 (Note that the result can be used as a boolean,
5444 true if the conversion succeeds.)
5445
5446
5447
5448
5449
5450 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
5451 <span class="apii">[-0, +0, &ndash;]</span>
5452 <pre>int lua_toboolean (lua_State *L, int index);</pre>
5453
5454 <p>
5455 Converts the Lua value at the given index to a C&nbsp;boolean
5456 value (0&nbsp;or&nbsp;1).
5457 Like all tests in Lua,
5458 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
5459 different from <b>false</b> and <b>nil</b>;
5460 otherwise it returns false.
5461 (If you want to accept only actual boolean values,
5462 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
5463
5464
5465
5466
5467
5468 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
5469 <span class="apii">[-0, +0, &ndash;]</span>
5470 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
5471
5472 <p>
5473 Converts a value at the given index to a C&nbsp;function.
5474 That value must be a C&nbsp;function;
5475 otherwise, returns <code>NULL</code>.
5476
5477
5478
5479
5480
5481 <hr><h3><a name="lua_toclose"><code>lua_toclose</code></a></h3><p>
5482 <span class="apii">[-0, +0, <em>m</em>]</span>
5483 <pre>void lua_toclose (lua_State *L, int index);</pre>
5484
5485 <p>
5486 Marks the given index in the stack as a
5487 to-be-closed slot (see <a href="#3.3.8">&sect;3.3.8</a>).
5488 Like a to-be-closed variable in Lua,
5489 the value at that slot in the stack will be closed
5490 when it goes out of scope.
5491 Here, in the context of a C function,
5492 to go out of scope means that the running function returns to Lua,
5493 or there is an error,
5494 or the slot is removed from the stack through
5495 <a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>,
5496 or there is a call to <a href="#lua_closeslot"><code>lua_closeslot</code></a>.
5497 A slot marked as to-be-closed should not be removed from the stack
5498 by any other function in the API except <a href="#lua_settop"><code>lua_settop</code></a> or <a href="#lua_pop"><code>lua_pop</code></a>,
5499 unless previously deactivated by <a href="#lua_closeslot"><code>lua_closeslot</code></a>.
5500
5501
5502 <p>
5503 This function should not be called for an index
5504 that is equal to or below an active to-be-closed slot.
5505
5506
5507 <p>
5508 Note that, both in case of errors and of a regular return,
5509 by the time the <code>__close</code> metamethod runs,
5510 the C&nbsp;stack was already unwound,
5511 so that any automatic C&nbsp;variable declared in the calling function
5512 (e.g., a buffer) will be out of scope.
5513
5514
5515
5516
5517
5518 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
5519 <span class="apii">[-0, +0, &ndash;]</span>
5520 <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
5521
5522 <p>
5523 Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5524
5525
5526
5527
5528
5529 <hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
5530 <span class="apii">[-0, +0, &ndash;]</span>
5531 <pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
5532
5533 <p>
5534 Converts the Lua value at the given index
5535 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
5536 The Lua value must be an integer,
5537 or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
5538 otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
5539
5540
5541 <p>
5542 If <code>isnum</code> is not <code>NULL</code>,
5543 its referent is assigned a boolean value that
5544 indicates whether the operation succeeded.
5545
5546
5547
5548
5549
5550 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
5551 <span class="apii">[-0, +0, <em>m</em>]</span>
5552 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5553
5554 <p>
5555 Converts the Lua value at the given index to a C&nbsp;string.
5556 If <code>len</code> is not <code>NULL</code>,
5557 it sets <code>*len</code> with the string length.
5558 The Lua value must be a string or a number;
5559 otherwise, the function returns <code>NULL</code>.
5560 If the value is a number,
5561 then <code>lua_tolstring</code> also
5562 <em>changes the actual value in the stack to a string</em>.
5563 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
5564 when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5565
5566
5567 <p>
5568 <code>lua_tolstring</code> returns a pointer
5569 to a string inside the Lua state (see <a href="#4.1.3">&sect;4.1.3</a>).
5570 This string always has a zero ('<code>\0</code>')
5571 after its last character (as in&nbsp;C),
5572 but can contain other zeros in its body.
5573
5574
5575
5576
5577
5578 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5579 <span class="apii">[-0, +0, &ndash;]</span>
5580 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5581
5582 <p>
5583 Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5584
5585
5586
5587
5588
5589 <hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5590 <span class="apii">[-0, +0, &ndash;]</span>
5591 <pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5592
5593 <p>
5594 Converts the Lua value at the given index
5595 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5596 The Lua value must be a number or a string convertible to a number
5597 (see <a href="#3.4.3">&sect;3.4.3</a>);
5598 otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5599
5600
5601 <p>
5602 If <code>isnum</code> is not <code>NULL</code>,
5603 its referent is assigned a boolean value that
5604 indicates whether the operation succeeded.
5605
5606
5607
5608
5609
5610 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5611 <span class="apii">[-0, +0, &ndash;]</span>
5612 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
5613
5614 <p>
5615 Converts the value at the given index to a generic
5616 C&nbsp;pointer (<code>void*</code>).
5617 The value can be a userdata, a table, a thread, a string, or a function;
5618 otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5619 Different objects will give different pointers.
5620 There is no way to convert the pointer back to its original value.
5621
5622
5623 <p>
5624 Typically this function is used only for hashing and debug information.
5625
5626
5627
5628
5629
5630 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5631 <span class="apii">[-0, +0, <em>m</em>]</span>
5632 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
5633
5634 <p>
5635 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5636
5637
5638
5639
5640
5641 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5642 <span class="apii">[-0, +0, &ndash;]</span>
5643 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5644
5645 <p>
5646 Converts the value at the given index to a Lua thread
5647 (represented as <code>lua_State*</code>).
5648 This value must be a thread;
5649 otherwise, the function returns <code>NULL</code>.
5650
5651
5652
5653
5654
5655 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5656 <span class="apii">[-0, +0, &ndash;]</span>
5657 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
5658
5659 <p>
5660 If the value at the given index is a full userdata,
5661 returns its memory-block address.
5662 If the value is a light userdata,
5663 returns its value (a pointer).
5664 Otherwise, returns <code>NULL</code>.
5665
5666
5667
5668
5669
5670 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5671 <span class="apii">[-0, +0, &ndash;]</span>
5672 <pre>int lua_type (lua_State *L, int index);</pre>
5673
5674 <p>
5675 Returns the type of the value in the given valid index,
5676 or <code>LUA_TNONE</code> for a non-valid but acceptable index.
5677 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5678 defined in <code>lua.h</code>:
5679 <a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5680 <a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5681 <a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5682 <a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5683 <a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5684 <a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5685 <a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5686 <a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5687 and
5688 <a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5689
5690
5691
5692
5693
5694 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5695 <span class="apii">[-0, +0, &ndash;]</span>
5696 <pre>const char *lua_typename (lua_State *L, int tp);</pre>
5697
5698 <p>
5699 Returns the name of the type encoded by the value <code>tp</code>,
5700 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5701
5702
5703
5704
5705
5706 <hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5707 <pre>typedef ... lua_Unsigned;</pre>
5708
5709 <p>
5710 The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5711
5712
5713
5714
5715
5716 <hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5717 <span class="apii">[-0, +0, &ndash;]</span>
5718 <pre>int lua_upvalueindex (int i);</pre>
5719
5720 <p>
5721 Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5722 the running function (see <a href="#4.2">&sect;4.2</a>).
5723 <code>i</code> must be in the range <em>[1,256]</em>.
5724
5725
5726
5727
5728
5729 <hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5730 <span class="apii">[-0, +0, &ndash;]</span>
5731 <pre>lua_Number lua_version (lua_State *L);</pre>
5732
5733 <p>
5734 Returns the version number of this core.
5735
5736
5737
5738
5739
5740 <hr><h3><a name="lua_WarnFunction"><code>lua_WarnFunction</code></a></h3>
5741 <pre>typedef void (*lua_WarnFunction) (void *ud, const char *msg, int tocont);</pre>
5742
5743 <p>
5744 The type of warning functions, called by Lua to emit warnings.
5745 The first parameter is an opaque pointer
5746 set by <a href="#lua_setwarnf"><code>lua_setwarnf</code></a>.
5747 The second parameter is the warning message.
5748 The third parameter is a boolean that
5749 indicates whether the message is
5750 to be continued by the message in the next call.
5751
5752
5753 <p>
5754 See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5755
5756
5757
5758
5759
5760 <hr><h3><a name="lua_warning"><code>lua_warning</code></a></h3><p>
5761 <span class="apii">[-0, +0, &ndash;]</span>
5762 <pre>void lua_warning (lua_State *L, const char *msg, int tocont);</pre>
5763
5764 <p>
5765 Emits a warning with the given message.
5766 A message in a call with <code>tocont</code> true should be
5767 continued in another call to this function.
5768
5769
5770 <p>
5771 See <a href="#pdf-warn"><code>warn</code></a> for more details about warnings.
5772
5773
5774
5775
5776
5777 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5778 <pre>typedef int (*lua_Writer) (lua_State *L,
5779 const void* p,
5780 size_t sz,
5781 void* ud);</pre>
5782
5783 <p>
5784 The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5785 Every time <a href="#lua_dump"><code>lua_dump</code></a> produces another piece of chunk,
5786 it calls the writer,
5787 passing along the buffer to be written (<code>p</code>),
5788 its size (<code>sz</code>),
5789 and the <code>ud</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5790
5791
5792 <p>
5793 The writer returns an error code:
5794 0&nbsp;means no errors;
5795 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5796 calling the writer again.
5797
5798
5799
5800
5801
5802 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5803 <span class="apii">[-?, +?, &ndash;]</span>
5804 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5805
5806 <p>
5807 Exchange values between different threads of the same state.
5808
5809
5810 <p>
5811 This function pops <code>n</code> values from the stack <code>from</code>,
5812 and pushes them onto the stack <code>to</code>.
5813
5814
5815
5816
5817
5818 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5819 <span class="apii">[-?, +?, <em>v</em>]</span>
5820 <pre>int lua_yield (lua_State *L, int nresults);</pre>
5821
5822 <p>
5823 This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5824 but it has no continuation (see <a href="#4.5">&sect;4.5</a>).
5825 Therefore, when the thread resumes,
5826 it continues the function that called
5827 the function calling <code>lua_yield</code>.
5828 To avoid surprises,
5829 this function should be called only in a tail call.
5830
5831
5832
5833
5834
5835 <hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5836 <span class="apii">[-?, +?, <em>v</em>]</span>
5837 <pre>int lua_yieldk (lua_State *L,
5838 int nresults,
5839 lua_KContext ctx,
5840 lua_KFunction k);</pre>
5841
5842 <p>
5843 Yields a coroutine (thread).
5844
5845
5846 <p>
5847 When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5848 the running coroutine suspends its execution,
5849 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5850 The parameter <code>nresults</code> is the number of values from the stack
5851 that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5852
5853
5854 <p>
5855 When the coroutine is resumed again,
5856 Lua calls the given continuation function <code>k</code> to continue
5857 the execution of the C&nbsp;function that yielded (see <a href="#4.5">&sect;4.5</a>).
5858 This continuation function receives the same stack
5859 from the previous function,
5860 with the <code>n</code> results removed and
5861 replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5862 Moreover,
5863 the continuation function receives the value <code>ctx</code>
5864 that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5865
5866
5867 <p>
5868 Usually, this function does not return;
5869 when the coroutine eventually resumes,
5870 it continues executing the continuation function.
5871 However, there is one special case,
5872 which is when this function is called
5873 from inside a line or a count hook (see <a href="#4.7">&sect;4.7</a>).
5874 In that case, <code>lua_yieldk</code> should be called with no continuation
5875 (probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results,
5876 and the hook should return immediately after the call.
5877 Lua will yield and,
5878 when the coroutine resumes again,
5879 it will continue the normal execution
5880 of the (Lua) function that triggered the hook.
5881
5882
5883 <p>
5884 This function can raise an error if it is called from a thread
5885 with a pending C call with no continuation function
5886 (what is called a <em>C-call boundary</em>),
5887 or it is called from a thread that is not running inside a resume
5888 (typically the main thread).
5889
5890
5891
5892
5893
5894
5895
5896 <h2>4.7 &ndash; <a name="4.7">The Debug Interface</a></h2>
5897
5898 <p>
5899 Lua has no built-in debugging facilities.
5900 Instead, it offers a special interface
5901 by means of functions and <em>hooks</em>.
5902 This interface allows the construction of different
5903 kinds of debuggers, profilers, and other tools
5904 that need "inside information" from the interpreter.
5905
5906
5907
5908 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5909 <pre>typedef struct lua_Debug {
5910 int event;
5911 const char *name; /* (n) */
5912 const char *namewhat; /* (n) */
5913 const char *what; /* (S) */
5914 const char *source; /* (S) */
5915 size_t srclen; /* (S) */
5916 int currentline; /* (l) */
5917 int linedefined; /* (S) */
5918 int lastlinedefined; /* (S) */
5919 unsigned char nups; /* (u) number of upvalues */
5920 unsigned char nparams; /* (u) number of parameters */
5921 char isvararg; /* (u) */
5922 char istailcall; /* (t) */
5923 unsigned short ftransfer; /* (r) index of first value transferred */
5924 unsigned short ntransfer; /* (r) number of transferred values */
5925 char short_src[LUA_IDSIZE]; /* (S) */
5926 /* private part */
5927 <em>other fields</em>
5928 } lua_Debug;</pre>
5929
5930 <p>
5931 A structure used to carry different pieces of
5932 information about a function or an activation record.
5933 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5934 of this structure, for later use.
5935 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5936 you must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5937
5938
5939 <p>
5940 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5941
5942 <ul>
5943
5944 <li><b><code>source</code>: </b>
5945 the source of the chunk that created the function.
5946 If <code>source</code> starts with a '<code>@</code>',
5947 it means that the function was defined in a file where
5948 the file name follows the '<code>@</code>'.
5949 If <code>source</code> starts with a '<code>=</code>',
5950 the remainder of its contents describes the source in a user-dependent manner.
5951 Otherwise,
5952 the function was defined in a string where
5953 <code>source</code> is that string.
5954 </li>
5955
5956 <li><b><code>srclen</code>: </b>
5957 The length of the string <code>source</code>.
5958 </li>
5959
5960 <li><b><code>short_src</code>: </b>
5961 a "printable" version of <code>source</code>, to be used in error messages.
5962 </li>
5963
5964 <li><b><code>linedefined</code>: </b>
5965 the line number where the definition of the function starts.
5966 </li>
5967
5968 <li><b><code>lastlinedefined</code>: </b>
5969 the line number where the definition of the function ends.
5970 </li>
5971
5972 <li><b><code>what</code>: </b>
5973 the string <code>"Lua"</code> if the function is a Lua function,
5974 <code>"C"</code> if it is a C&nbsp;function,
5975 <code>"main"</code> if it is the main part of a chunk.
5976 </li>
5977
5978 <li><b><code>currentline</code>: </b>
5979 the current line where the given function is executing.
5980 When no line information is available,
5981 <code>currentline</code> is set to -1.
5982 </li>
5983
5984 <li><b><code>name</code>: </b>
5985 a reasonable name for the given function.
5986 Because functions in Lua are first-class values,
5987 they do not have a fixed name:
5988 some functions can be the value of multiple global variables,
5989 while others can be stored only in a table field.
5990 The <code>lua_getinfo</code> function checks how the function was
5991 called to find a suitable name.
5992 If it cannot find a name,
5993 then <code>name</code> is set to <code>NULL</code>.
5994 </li>
5995
5996 <li><b><code>namewhat</code>: </b>
5997 explains the <code>name</code> field.
5998 The value of <code>namewhat</code> can be
5999 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
6000 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
6001 according to how the function was called.
6002 (Lua uses the empty string when no other option seems to apply.)
6003 </li>
6004
6005 <li><b><code>istailcall</code>: </b>
6006 true if this function invocation was called by a tail call.
6007 In this case, the caller of this level is not in the stack.
6008 </li>
6009
6010 <li><b><code>nups</code>: </b>
6011 the number of upvalues of the function.
6012 </li>
6013
6014 <li><b><code>nparams</code>: </b>
6015 the number of parameters of the function
6016 (always 0&nbsp;for C&nbsp;functions).
6017 </li>
6018
6019 <li><b><code>isvararg</code>: </b>
6020 true if the function is a vararg function
6021 (always true for C&nbsp;functions).
6022 </li>
6023
6024 <li><b><code>ftransfer</code>: </b>
6025 the index in the stack of the first value being "transferred",
6026 that is, parameters in a call or return values in a return.
6027 (The other values are in consecutive indices.)
6028 Using this index, you can access and modify these values
6029 through <a href="#lua_getlocal"><code>lua_getlocal</code></a> and <a href="#lua_setlocal"><code>lua_setlocal</code></a>.
6030 This field is only meaningful during a
6031 call hook, denoting the first parameter,
6032 or a return hook, denoting the first value being returned.
6033 (For call hooks, this value is always 1.)
6034 </li>
6035
6036 <li><b><code>ntransfer</code>: </b>
6037 The number of values being transferred (see previous item).
6038 (For calls of Lua functions,
6039 this value is always equal to <code>nparams</code>.)
6040 </li>
6041
6042 </ul>
6043
6044
6045
6046
6047 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
6048 <span class="apii">[-0, +0, &ndash;]</span>
6049 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
6050
6051 <p>
6052 Returns the current hook function.
6053
6054
6055
6056
6057
6058 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
6059 <span class="apii">[-0, +0, &ndash;]</span>
6060 <pre>int lua_gethookcount (lua_State *L);</pre>
6061
6062 <p>
6063 Returns the current hook count.
6064
6065
6066
6067
6068
6069 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
6070 <span class="apii">[-0, +0, &ndash;]</span>
6071 <pre>int lua_gethookmask (lua_State *L);</pre>
6072
6073 <p>
6074 Returns the current hook mask.
6075
6076
6077
6078
6079
6080 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
6081 <span class="apii">[-(0|1), +(0|1|2), <em>m</em>]</span>
6082 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
6083
6084 <p>
6085 Gets information about a specific function or function invocation.
6086
6087
6088 <p>
6089 To get information about a function invocation,
6090 the parameter <code>ar</code> must be a valid activation record that was
6091 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6092 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6093
6094
6095 <p>
6096 To get information about a function, you push it onto the stack
6097 and start the <code>what</code> string with the character '<code>&gt;</code>'.
6098 (In that case,
6099 <code>lua_getinfo</code> pops the function from the top of the stack.)
6100 For instance, to know in which line a function <code>f</code> was defined,
6101 you can write the following code:
6102
6103 <pre>
6104 lua_Debug ar;
6105 lua_getglobal(L, "f"); /* get global 'f' */
6106 lua_getinfo(L, "&gt;S", &amp;ar);
6107 printf("%d\n", ar.linedefined);
6108 </pre>
6109
6110 <p>
6111 Each character in the string <code>what</code>
6112 selects some fields of the structure <code>ar</code> to be filled or
6113 a value to be pushed on the stack:
6114
6115 <ul>
6116
6117 <li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
6118 </li>
6119
6120 <li><b>'<code>S</code>': </b>
6121 fills in the fields <code>source</code>, <code>short_src</code>,
6122 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
6123 </li>
6124
6125 <li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
6126 </li>
6127
6128 <li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
6129 </li>
6130
6131 <li><b>'<code>u</code>': </b> fills in the fields
6132 <code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
6133 </li>
6134
6135 <li><b>'<code>f</code>': </b>
6136 pushes onto the stack the function that is
6137 running at the given level;
6138 </li>
6139
6140 <li><b>'<code>L</code>': </b>
6141 pushes onto the stack a table whose indices are the
6142 numbers of the lines that are valid on the function.
6143 (A <em>valid line</em> is a line with some associated code,
6144 that is, a line where you can put a break point.
6145 Non-valid lines include empty lines and comments.)
6146
6147
6148 <p>
6149 If this option is given together with option '<code>f</code>',
6150 its table is pushed after the function.
6151
6152
6153 <p>
6154 This is the only option that can raise a memory error.
6155 </li>
6156
6157 </ul>
6158
6159 <p>
6160 This function returns 0 to signal an invalid option in <code>what</code>;
6161 even then the valid options are handled correctly.
6162
6163
6164
6165
6166
6167 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
6168 <span class="apii">[-0, +(0|1), &ndash;]</span>
6169 <pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6170
6171 <p>
6172 Gets information about a local variable or a temporary value
6173 of a given activation record or a given function.
6174
6175
6176 <p>
6177 In the first case,
6178 the parameter <code>ar</code> must be a valid activation record that was
6179 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
6180 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
6181 The index <code>n</code> selects which local variable to inspect;
6182 see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
6183 and names.
6184
6185
6186 <p>
6187 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
6188 and returns its name.
6189
6190
6191 <p>
6192 In the second case, <code>ar</code> must be <code>NULL</code> and the function
6193 to be inspected must be on the top of the stack.
6194 In this case, only parameters of Lua functions are visible
6195 (as there is no information about what variables are active)
6196 and no values are pushed onto the stack.
6197
6198
6199 <p>
6200 Returns <code>NULL</code> (and pushes nothing)
6201 when the index is greater than
6202 the number of active local variables.
6203
6204
6205
6206
6207
6208 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
6209 <span class="apii">[-0, +0, &ndash;]</span>
6210 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
6211
6212 <p>
6213 Gets information about the interpreter runtime stack.
6214
6215
6216 <p>
6217 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
6218 an identification of the <em>activation record</em>
6219 of the function executing at a given level.
6220 Level&nbsp;0 is the current running function,
6221 whereas level <em>n+1</em> is the function that has called level <em>n</em>
6222 (except for tail calls, which do not count in the stack).
6223 When called with a level greater than the stack depth,
6224 <a href="#lua_getstack"><code>lua_getstack</code></a> returns 0;
6225 otherwise it returns 1.
6226
6227
6228
6229
6230
6231 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
6232 <span class="apii">[-0, +(0|1), &ndash;]</span>
6233 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
6234
6235 <p>
6236 Gets information about the <code>n</code>-th upvalue
6237 of the closure at index <code>funcindex</code>.
6238 It pushes the upvalue's value onto the stack
6239 and returns its name.
6240 Returns <code>NULL</code> (and pushes nothing)
6241 when the index <code>n</code> is greater than the number of upvalues.
6242
6243
6244 <p>
6245 See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
6246
6247
6248
6249
6250
6251 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
6252 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
6253
6254 <p>
6255 Type for debugging hook functions.
6256
6257
6258 <p>
6259 Whenever a hook is called, its <code>ar</code> argument has its field
6260 <code>event</code> set to the specific event that triggered the hook.
6261 Lua identifies these events with the following constants:
6262 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
6263 <a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
6264 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
6265 Moreover, for line events, the field <code>currentline</code> is also set.
6266 To get the value of any other field in <code>ar</code>,
6267 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
6268
6269
6270 <p>
6271 For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
6272 the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
6273 in this case, there will be no corresponding return event.
6274
6275
6276 <p>
6277 While Lua is running a hook, it disables other calls to hooks.
6278 Therefore, if a hook calls back Lua to execute a function or a chunk,
6279 this execution occurs without any calls to hooks.
6280
6281
6282 <p>
6283 Hook functions cannot have continuations,
6284 that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
6285 <a href="#lua_pcallk"><code>lua_pcallk</code></a>, or <a href="#lua_callk"><code>lua_callk</code></a> with a non-null <code>k</code>.
6286
6287
6288 <p>
6289 Hook functions can yield under the following conditions:
6290 Only count and line events can yield;
6291 to yield, a hook function must finish its execution
6292 calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero
6293 (that is, with no values).
6294
6295
6296
6297
6298
6299 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
6300 <span class="apii">[-0, +0, &ndash;]</span>
6301 <pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
6302
6303 <p>
6304 Sets the debugging hook function.
6305
6306
6307 <p>
6308 Argument <code>f</code> is the hook function.
6309 <code>mask</code> specifies on which events the hook will be called:
6310 it is formed by a bitwise OR of the constants
6311 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
6312 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
6313 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
6314 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
6315 The <code>count</code> argument is only meaningful when the mask
6316 includes <code>LUA_MASKCOUNT</code>.
6317 For each event, the hook is called as explained below:
6318
6319 <ul>
6320
6321 <li><b>The call hook: </b> is called when the interpreter calls a function.
6322 The hook is called just after Lua enters the new function.
6323 </li>
6324
6325 <li><b>The return hook: </b> is called when the interpreter returns from a function.
6326 The hook is called just before Lua leaves the function.
6327 </li>
6328
6329 <li><b>The line hook: </b> is called when the interpreter is about to
6330 start the execution of a new line of code,
6331 or when it jumps back in the code (even to the same line).
6332 This event only happens while Lua is executing a Lua function.
6333 </li>
6334
6335 <li><b>The count hook: </b> is called after the interpreter executes every
6336 <code>count</code> instructions.
6337 This event only happens while Lua is executing a Lua function.
6338 </li>
6339
6340 </ul>
6341
6342 <p>
6343 Hooks are disabled by setting <code>mask</code> to zero.
6344
6345
6346
6347
6348
6349 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
6350 <span class="apii">[-(0|1), +0, &ndash;]</span>
6351 <pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
6352
6353 <p>
6354 Sets the value of a local variable of a given activation record.
6355 It assigns the value on the top of the stack
6356 to the variable and returns its name.
6357 It also pops the value from the stack.
6358
6359
6360 <p>
6361 Returns <code>NULL</code> (and pops nothing)
6362 when the index is greater than
6363 the number of active local variables.
6364
6365
6366 <p>
6367 Parameters <code>ar</code> and <code>n</code> are as in the function <a href="#lua_getlocal"><code>lua_getlocal</code></a>.
6368
6369
6370
6371
6372
6373 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
6374 <span class="apii">[-(0|1), +0, &ndash;]</span>
6375 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
6376
6377 <p>
6378 Sets the value of a closure's upvalue.
6379 It assigns the value on the top of the stack
6380 to the upvalue and returns its name.
6381 It also pops the value from the stack.
6382
6383
6384 <p>
6385 Returns <code>NULL</code> (and pops nothing)
6386 when the index <code>n</code> is greater than the number of upvalues.
6387
6388
6389 <p>
6390 Parameters <code>funcindex</code> and <code>n</code> are as in
6391 the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>.
6392
6393
6394
6395
6396
6397 <hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
6398 <span class="apii">[-0, +0, &ndash;]</span>
6399 <pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
6400
6401 <p>
6402 Returns a unique identifier for the upvalue numbered <code>n</code>
6403 from the closure at index <code>funcindex</code>.
6404
6405
6406 <p>
6407 These unique identifiers allow a program to check whether different
6408 closures share upvalues.
6409 Lua closures that share an upvalue
6410 (that is, that access a same external local variable)
6411 will return identical ids for those upvalue indices.
6412
6413
6414 <p>
6415 Parameters <code>funcindex</code> and <code>n</code> are as in
6416 the function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>,
6417 but <code>n</code> cannot be greater than the number of upvalues.
6418
6419
6420
6421
6422
6423 <hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
6424 <span class="apii">[-0, +0, &ndash;]</span>
6425 <pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
6426 int funcindex2, int n2);</pre>
6427
6428 <p>
6429 Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
6430 refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
6431
6432
6433
6434
6435
6436
6437
6438 <h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
6439
6440
6441
6442 <p>
6443
6444 The <em>auxiliary library</em> provides several convenient functions
6445 to interface C with Lua.
6446 While the basic API provides the primitive functions for all
6447 interactions between C and Lua,
6448 the auxiliary library provides higher-level functions for some
6449 common tasks.
6450
6451
6452 <p>
6453 All functions and types from the auxiliary library
6454 are defined in header file <code>lauxlib.h</code> and
6455 have a prefix <code>luaL_</code>.
6456
6457
6458 <p>
6459 All functions in the auxiliary library are built on
6460 top of the basic API,
6461 and so they provide nothing that cannot be done with that API.
6462 Nevertheless, the use of the auxiliary library ensures
6463 more consistency to your code.
6464
6465
6466 <p>
6467 Several functions in the auxiliary library use internally some
6468 extra stack slots.
6469 When a function in the auxiliary library uses less than five slots,
6470 it does not check the stack size;
6471 it simply assumes that there are enough slots.
6472
6473
6474 <p>
6475 Several functions in the auxiliary library are used to
6476 check C&nbsp;function arguments.
6477 Because the error message is formatted for arguments
6478 (e.g., "<code>bad argument #1</code>"),
6479 you should not use these functions for other stack values.
6480
6481
6482 <p>
6483 Functions called <code>luaL_check*</code>
6484 always raise an error if the check is not satisfied.
6485
6486
6487
6488
6489
6490 <h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
6491
6492 <p>
6493 Here we list all functions and types from the auxiliary library
6494 in alphabetical order.
6495
6496
6497
6498 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
6499 <span class="apii">[-?, +?, <em>m</em>]</span>
6500 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
6501
6502 <p>
6503 Adds the byte <code>c</code> to the buffer <code>B</code>
6504 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6505
6506
6507
6508
6509
6510 <hr><h3><a name="luaL_addgsub"><code>luaL_addgsub</code></a></h3><p>
6511 <span class="apii">[-0, +0, <em>m</em>]</span>
6512 <pre>const void luaL_addgsub (luaL_Buffer *B, const char *s,
6513 const char *p, const char *r);</pre>
6514
6515 <p>
6516 Adds a copy of the string <code>s</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>),
6517 replacing any occurrence of the string <code>p</code>
6518 with the string <code>r</code>.
6519
6520
6521
6522
6523
6524 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
6525 <span class="apii">[-?, +?, <em>m</em>]</span>
6526 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
6527
6528 <p>
6529 Adds the string pointed to by <code>s</code> with length <code>l</code> to
6530 the buffer <code>B</code>
6531 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6532 The string can contain embedded zeros.
6533
6534
6535
6536
6537
6538 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
6539 <span class="apii">[-?, +?, &ndash;]</span>
6540 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
6541
6542 <p>
6543 Adds to the buffer <code>B</code>
6544 a string of length <code>n</code> previously copied to the
6545 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
6546
6547
6548
6549
6550
6551 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
6552 <span class="apii">[-?, +?, <em>m</em>]</span>
6553 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
6554
6555 <p>
6556 Adds the zero-terminated string pointed to by <code>s</code>
6557 to the buffer <code>B</code>
6558 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6559
6560
6561
6562
6563
6564 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
6565 <span class="apii">[-1, +?, <em>m</em>]</span>
6566 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
6567
6568 <p>
6569 Adds the value on the top of the stack
6570 to the buffer <code>B</code>
6571 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6572 Pops the value.
6573
6574
6575 <p>
6576 This is the only function on string buffers that can (and must)
6577 be called with an extra element on the stack,
6578 which is the value to be added to the buffer.
6579
6580
6581
6582
6583
6584 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
6585 <span class="apii">[-0, +0, <em>v</em>]</span>
6586 <pre>void luaL_argcheck (lua_State *L,
6587 int cond,
6588 int arg,
6589 const char *extramsg);</pre>
6590
6591 <p>
6592 Checks whether <code>cond</code> is true.
6593 If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
6594
6595
6596
6597
6598
6599 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
6600 <span class="apii">[-0, +0, <em>v</em>]</span>
6601 <pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
6602
6603 <p>
6604 Raises an error reporting a problem with argument <code>arg</code>
6605 of the C&nbsp;function that called it,
6606 using a standard message
6607 that includes <code>extramsg</code> as a comment:
6608
6609 <pre>
6610 bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
6611 </pre><p>
6612 This function never returns.
6613
6614
6615
6616
6617
6618 <hr><h3><a name="luaL_argexpected"><code>luaL_argexpected</code></a></h3><p>
6619 <span class="apii">[-0, +0, <em>v</em>]</span>
6620 <pre>void luaL_argexpected (lua_State *L,
6621 int cond,
6622 int arg,
6623 const char *tname);</pre>
6624
6625 <p>
6626 Checks whether <code>cond</code> is true.
6627 If it is not, raises an error about the type of the argument <code>arg</code>
6628 with a standard message (see <a href="#luaL_typeerror"><code>luaL_typeerror</code></a>).
6629
6630
6631
6632
6633
6634 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
6635 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
6636
6637 <p>
6638 Type for a <em>string buffer</em>.
6639
6640
6641 <p>
6642 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
6643 Its pattern of use is as follows:
6644
6645 <ul>
6646
6647 <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6648
6649 <li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6650
6651 <li>
6652 Then add string pieces to the buffer calling any of
6653 the <code>luaL_add*</code> functions.
6654 </li>
6655
6656 <li>
6657 Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6658 This call leaves the final string on the top of the stack.
6659 </li>
6660
6661 </ul>
6662
6663 <p>
6664 If you know beforehand the maximum size of the resulting string,
6665 you can use the buffer like this:
6666
6667 <ul>
6668
6669 <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6670
6671 <li>Then initialize it and preallocate a space of
6672 size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6673
6674 <li>Then produce the string into that space.</li>
6675
6676 <li>
6677 Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6678 where <code>sz</code> is the total size of the resulting string
6679 copied into that space (which may be less than or
6680 equal to the preallocated size).
6681 </li>
6682
6683 </ul>
6684
6685 <p>
6686 During its normal operation,
6687 a string buffer uses a variable number of stack slots.
6688 So, while using a buffer, you cannot assume that you know where
6689 the top of the stack is.
6690 You can use the stack between successive calls to buffer operations
6691 as long as that use is balanced;
6692 that is,
6693 when you call a buffer operation,
6694 the stack is at the same level
6695 it was immediately after the previous buffer operation.
6696 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6697 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>,
6698 the stack is back to its level when the buffer was initialized,
6699 plus the final string on its top.
6700
6701
6702
6703
6704
6705 <hr><h3><a name="luaL_buffaddr"><code>luaL_buffaddr</code></a></h3><p>
6706 <span class="apii">[-0, +0, &ndash;]</span>
6707 <pre>char *luaL_buffaddr (luaL_Buffer *B);</pre>
6708
6709 <p>
6710 Returns the address of the current content of buffer <code>B</code>
6711 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6712 Note that any addition to the buffer may invalidate this address.
6713
6714
6715
6716
6717
6718 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6719 <span class="apii">[-0, +0, &ndash;]</span>
6720 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6721
6722 <p>
6723 Initializes a buffer <code>B</code>
6724 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6725 This function does not allocate any space;
6726 the buffer must be declared as a variable.
6727
6728
6729
6730
6731
6732 <hr><h3><a name="luaL_bufflen"><code>luaL_bufflen</code></a></h3><p>
6733 <span class="apii">[-0, +0, &ndash;]</span>
6734 <pre>size_t luaL_bufflen (luaL_Buffer *B);</pre>
6735
6736 <p>
6737 Returns the length of the current content of buffer <code>B</code>
6738 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6739
6740
6741
6742
6743
6744 <hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6745 <span class="apii">[-?, +?, <em>m</em>]</span>
6746 <pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6747
6748 <p>
6749 Equivalent to the sequence
6750 <a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6751
6752
6753
6754
6755
6756 <hr><h3><a name="luaL_buffsub"><code>luaL_buffsub</code></a></h3><p>
6757 <span class="apii">[-0, +0, &ndash;]</span>
6758 <pre>void luaL_buffsub (luaL_Buffer *B, int n);</pre>
6759
6760 <p>
6761 Removes <code>n</code> bytes from the the buffer <code>B</code>
6762 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6763 The buffer must have at least that many bytes.
6764
6765
6766
6767
6768
6769 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6770 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
6771 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6772
6773 <p>
6774 Calls a metamethod.
6775
6776
6777 <p>
6778 If the object at index <code>obj</code> has a metatable and this
6779 metatable has a field <code>e</code>,
6780 this function calls this field passing the object as its only argument.
6781 In this case this function returns true and pushes onto the
6782 stack the value returned by the call.
6783 If there is no metatable or no metamethod,
6784 this function returns false without pushing any value on the stack.
6785
6786
6787
6788
6789
6790 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6791 <span class="apii">[-0, +0, <em>v</em>]</span>
6792 <pre>void luaL_checkany (lua_State *L, int arg);</pre>
6793
6794 <p>
6795 Checks whether the function has an argument
6796 of any type (including <b>nil</b>) at position <code>arg</code>.
6797
6798
6799
6800
6801
6802 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6803 <span class="apii">[-0, +0, <em>v</em>]</span>
6804 <pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6805
6806 <p>
6807 Checks whether the function argument <code>arg</code> is an integer
6808 (or can be converted to an integer)
6809 and returns this integer.
6810
6811
6812
6813
6814
6815 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6816 <span class="apii">[-0, +0, <em>v</em>]</span>
6817 <pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6818
6819 <p>
6820 Checks whether the function argument <code>arg</code> is a string
6821 and returns this string;
6822 if <code>l</code> is not <code>NULL</code> fills its referent
6823 with the string's length.
6824
6825
6826 <p>
6827 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6828 so all conversions and caveats of that function apply here.
6829
6830
6831
6832
6833
6834 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6835 <span class="apii">[-0, +0, <em>v</em>]</span>
6836 <pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6837
6838 <p>
6839 Checks whether the function argument <code>arg</code> is a number
6840 and returns this number converted to a <code>lua_Number</code>.
6841
6842
6843
6844
6845
6846 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6847 <span class="apii">[-0, +0, <em>v</em>]</span>
6848 <pre>int luaL_checkoption (lua_State *L,
6849 int arg,
6850 const char *def,
6851 const char *const lst[]);</pre>
6852
6853 <p>
6854 Checks whether the function argument <code>arg</code> is a string and
6855 searches for this string in the array <code>lst</code>
6856 (which must be NULL-terminated).
6857 Returns the index in the array where the string was found.
6858 Raises an error if the argument is not a string or
6859 if the string cannot be found.
6860
6861
6862 <p>
6863 If <code>def</code> is not <code>NULL</code>,
6864 the function uses <code>def</code> as a default value when
6865 there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6866
6867
6868 <p>
6869 This is a useful function for mapping strings to C&nbsp;enums.
6870 (The usual convention in Lua libraries is
6871 to use strings instead of numbers to select options.)
6872
6873
6874
6875
6876
6877 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6878 <span class="apii">[-0, +0, <em>v</em>]</span>
6879 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6880
6881 <p>
6882 Grows the stack size to <code>top + sz</code> elements,
6883 raising an error if the stack cannot grow to that size.
6884 <code>msg</code> is an additional text to go into the error message
6885 (or <code>NULL</code> for no additional text).
6886
6887
6888
6889
6890
6891 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6892 <span class="apii">[-0, +0, <em>v</em>]</span>
6893 <pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6894
6895 <p>
6896 Checks whether the function argument <code>arg</code> is a string
6897 and returns this string.
6898
6899
6900 <p>
6901 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6902 so all conversions and caveats of that function apply here.
6903
6904
6905
6906
6907
6908 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6909 <span class="apii">[-0, +0, <em>v</em>]</span>
6910 <pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6911
6912 <p>
6913 Checks whether the function argument <code>arg</code> has type <code>t</code>.
6914 See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6915
6916
6917
6918
6919
6920 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6921 <span class="apii">[-0, +0, <em>v</em>]</span>
6922 <pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6923
6924 <p>
6925 Checks whether the function argument <code>arg</code> is a userdata
6926 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6927 returns the userdata's memory-block address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6928
6929
6930
6931
6932
6933 <hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6934 <span class="apii">[-0, +0, <em>v</em>]</span>
6935 <pre>void luaL_checkversion (lua_State *L);</pre>
6936
6937 <p>
6938 Checks whether the code making the call and the Lua library being called
6939 are using the same version of Lua and the same numeric types.
6940
6941
6942
6943
6944
6945 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6946 <span class="apii">[-0, +?, <em>m</em>]</span>
6947 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6948
6949 <p>
6950 Loads and runs the given file.
6951 It is defined as the following macro:
6952
6953 <pre>
6954 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6955 </pre><p>
6956 It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6957 or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6958
6959
6960
6961
6962
6963 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6964 <span class="apii">[-0, +?, &ndash;]</span>
6965 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6966
6967 <p>
6968 Loads and runs the given string.
6969 It is defined as the following macro:
6970
6971 <pre>
6972 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6973 </pre><p>
6974 It returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if there are no errors,
6975 or an error code in case of errors (see <a href="#4.4.1">&sect;4.4.1</a>).
6976
6977
6978
6979
6980
6981 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6982 <span class="apii">[-0, +0, <em>v</em>]</span>
6983 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6984
6985 <p>
6986 Raises an error.
6987 The error message format is given by <code>fmt</code>
6988 plus any extra arguments,
6989 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6990 It also adds at the beginning of the message the file name and
6991 the line number where the error occurred,
6992 if this information is available.
6993
6994
6995 <p>
6996 This function never returns,
6997 but it is an idiom to use it in C&nbsp;functions
6998 as <code>return luaL_error(<em>args</em>)</code>.
6999
7000
7001
7002
7003
7004 <hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
7005 <span class="apii">[-0, +3, <em>m</em>]</span>
7006 <pre>int luaL_execresult (lua_State *L, int stat);</pre>
7007
7008 <p>
7009 This function produces the return values for
7010 process-related functions in the standard library
7011 (<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
7012
7013
7014
7015
7016
7017 <hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
7018 <span class="apii">[-0, +(1|3), <em>m</em>]</span>
7019 <pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
7020
7021 <p>
7022 This function produces the return values for
7023 file-related functions in the standard library
7024 (<a href="#pdf-io.open"><code>io.open</code></a>, <a href="#pdf-os.rename"><code>os.rename</code></a>, <a href="#pdf-file:seek"><code>file:seek</code></a>, etc.).
7025
7026
7027
7028
7029
7030 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
7031 <span class="apii">[-0, +(0|1), <em>m</em>]</span>
7032 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
7033
7034 <p>
7035 Pushes onto the stack the field <code>e</code> from the metatable
7036 of the object at index <code>obj</code> and returns the type of the pushed value.
7037 If the object does not have a metatable,
7038 or if the metatable does not have this field,
7039 pushes nothing and returns <code>LUA_TNIL</code>.
7040
7041
7042
7043
7044
7045 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
7046 <span class="apii">[-0, +1, <em>m</em>]</span>
7047 <pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
7048
7049 <p>
7050 Pushes onto the stack the metatable associated with the name <code>tname</code>
7051 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>),
7052 or <b>nil</b> if there is no metatable associated with that name.
7053 Returns the type of the pushed value.
7054
7055
7056
7057
7058
7059 <hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
7060 <span class="apii">[-0, +1, <em>e</em>]</span>
7061 <pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
7062
7063 <p>
7064 Ensures that the value <code>t[fname]</code>,
7065 where <code>t</code> is the value at index <code>idx</code>,
7066 is a table,
7067 and pushes that table onto the stack.
7068 Returns true if it finds a previous table there
7069 and false if it creates a new table.
7070
7071
7072
7073
7074
7075 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
7076 <span class="apii">[-0, +1, <em>m</em>]</span>
7077 <pre>const char *luaL_gsub (lua_State *L,
7078 const char *s,
7079 const char *p,
7080 const char *r);</pre>
7081
7082 <p>
7083 Creates a copy of string <code>s</code>,
7084 replacing any occurrence of the string <code>p</code>
7085 with the string <code>r</code>.
7086 Pushes the resulting string on the stack and returns it.
7087
7088
7089
7090
7091
7092 <hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
7093 <span class="apii">[-0, +0, <em>e</em>]</span>
7094 <pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
7095
7096 <p>
7097 Returns the "length" of the value at the given index
7098 as a number;
7099 it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
7100 Raises an error if the result of the operation is not an integer.
7101 (This case can only happen through metamethods.)
7102
7103
7104
7105
7106
7107 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
7108 <span class="apii">[-0, +1, &ndash;]</span>
7109 <pre>int luaL_loadbuffer (lua_State *L,
7110 const char *buff,
7111 size_t sz,
7112 const char *name);</pre>
7113
7114 <p>
7115 Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
7116
7117
7118
7119
7120
7121 <hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
7122 <span class="apii">[-0, +1, &ndash;]</span>
7123 <pre>int luaL_loadbufferx (lua_State *L,
7124 const char *buff,
7125 size_t sz,
7126 const char *name,
7127 const char *mode);</pre>
7128
7129 <p>
7130 Loads a buffer as a Lua chunk.
7131 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
7132 buffer pointed to by <code>buff</code> with size <code>sz</code>.
7133
7134
7135 <p>
7136 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7137 <code>name</code> is the chunk name,
7138 used for debug information and error messages.
7139 The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7140
7141
7142
7143
7144
7145 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
7146 <span class="apii">[-0, +1, <em>m</em>]</span>
7147 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
7148
7149 <p>
7150 Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
7151
7152
7153
7154
7155
7156 <hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
7157 <span class="apii">[-0, +1, <em>m</em>]</span>
7158 <pre>int luaL_loadfilex (lua_State *L, const char *filename,
7159 const char *mode);</pre>
7160
7161 <p>
7162 Loads a file as a Lua chunk.
7163 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
7164 named <code>filename</code>.
7165 If <code>filename</code> is <code>NULL</code>,
7166 then it loads from the standard input.
7167 The first line in the file is ignored if it starts with a <code>#</code>.
7168
7169
7170 <p>
7171 The string <code>mode</code> works as in the function <a href="#lua_load"><code>lua_load</code></a>.
7172
7173
7174 <p>
7175 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>
7176 or <a href="#pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> for file-related errors.
7177
7178
7179 <p>
7180 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7181 it does not run it.
7182
7183
7184
7185
7186
7187 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
7188 <span class="apii">[-0, +1, &ndash;]</span>
7189 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
7190
7191 <p>
7192 Loads a string as a Lua chunk.
7193 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
7194 the zero-terminated string <code>s</code>.
7195
7196
7197 <p>
7198 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
7199
7200
7201 <p>
7202 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
7203 it does not run it.
7204
7205
7206
7207
7208
7209 <hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
7210 <span class="apii">[-0, +1, <em>m</em>]</span>
7211 <pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
7212
7213 <p>
7214 Creates a new table and registers there
7215 the functions in the list <code>l</code>.
7216
7217
7218 <p>
7219 It is implemented as the following macro:
7220
7221 <pre>
7222 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
7223 </pre><p>
7224 The array <code>l</code> must be the actual array,
7225 not a pointer to it.
7226
7227
7228
7229
7230
7231 <hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
7232 <span class="apii">[-0, +1, <em>m</em>]</span>
7233 <pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
7234
7235 <p>
7236 Creates a new table with a size optimized
7237 to store all entries in the array <code>l</code>
7238 (but does not actually store them).
7239 It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
7240 (see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
7241
7242
7243 <p>
7244 It is implemented as a macro.
7245 The array <code>l</code> must be the actual array,
7246 not a pointer to it.
7247
7248
7249
7250
7251
7252 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
7253 <span class="apii">[-0, +1, <em>m</em>]</span>
7254 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
7255
7256 <p>
7257 If the registry already has the key <code>tname</code>,
7258 returns 0.
7259 Otherwise,
7260 creates a new table to be used as a metatable for userdata,
7261 adds to this new table the pair <code>__name = tname</code>,
7262 adds to the registry the pair <code>[tname] = new table</code>,
7263 and returns 1.
7264
7265
7266 <p>
7267 In both cases,
7268 the function pushes onto the stack the final value associated
7269 with <code>tname</code> in the registry.
7270
7271
7272
7273
7274
7275 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
7276 <span class="apii">[-0, +0, &ndash;]</span>
7277 <pre>lua_State *luaL_newstate (void);</pre>
7278
7279 <p>
7280 Creates a new Lua state.
7281 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
7282 allocator based on the standard&nbsp;C allocation functions
7283 and then sets a warning function and a panic function (see <a href="#4.4">&sect;4.4</a>)
7284 that print messages to the standard error output.
7285
7286
7287 <p>
7288 Returns the new state,
7289 or <code>NULL</code> if there is a memory allocation error.
7290
7291
7292
7293
7294
7295 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
7296 <span class="apii">[-0, +0, <em>e</em>]</span>
7297 <pre>void luaL_openlibs (lua_State *L);</pre>
7298
7299 <p>
7300 Opens all standard Lua libraries into the given state.
7301
7302
7303
7304
7305
7306 <hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p>
7307 <span class="apii">[-0, +0, &ndash;]</span>
7308 <pre>T luaL_opt (L, func, arg, dflt);</pre>
7309
7310 <p>
7311 This macro is defined as follows:
7312
7313 <pre>
7314 (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg)))
7315 </pre><p>
7316 In words, if the argument <code>arg</code> is nil or absent,
7317 the macro results in the default <code>dflt</code>.
7318 Otherwise, it results in the result of calling <code>func</code>
7319 with the state <code>L</code> and the argument index <code>arg</code> as
7320 arguments.
7321 Note that it evaluates the expression <code>dflt</code> only if needed.
7322
7323
7324
7325
7326
7327 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
7328 <span class="apii">[-0, +0, <em>v</em>]</span>
7329 <pre>lua_Integer luaL_optinteger (lua_State *L,
7330 int arg,
7331 lua_Integer d);</pre>
7332
7333 <p>
7334 If the function argument <code>arg</code> is an integer
7335 (or it is convertible to an integer),
7336 returns this integer.
7337 If this argument is absent or is <b>nil</b>,
7338 returns <code>d</code>.
7339 Otherwise, raises an error.
7340
7341
7342
7343
7344
7345 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
7346 <span class="apii">[-0, +0, <em>v</em>]</span>
7347 <pre>const char *luaL_optlstring (lua_State *L,
7348 int arg,
7349 const char *d,
7350 size_t *l);</pre>
7351
7352 <p>
7353 If the function argument <code>arg</code> is a string,
7354 returns this string.
7355 If this argument is absent or is <b>nil</b>,
7356 returns <code>d</code>.
7357 Otherwise, raises an error.
7358
7359
7360 <p>
7361 If <code>l</code> is not <code>NULL</code>,
7362 fills its referent with the result's length.
7363 If the result is <code>NULL</code>
7364 (only possible when returning <code>d</code> and <code>d == NULL</code>),
7365 its length is considered zero.
7366
7367
7368 <p>
7369 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
7370 so all conversions and caveats of that function apply here.
7371
7372
7373
7374
7375
7376 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
7377 <span class="apii">[-0, +0, <em>v</em>]</span>
7378 <pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
7379
7380 <p>
7381 If the function argument <code>arg</code> is a number,
7382 returns this number as a <code>lua_Number</code>.
7383 If this argument is absent or is <b>nil</b>,
7384 returns <code>d</code>.
7385 Otherwise, raises an error.
7386
7387
7388
7389
7390
7391 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
7392 <span class="apii">[-0, +0, <em>v</em>]</span>
7393 <pre>const char *luaL_optstring (lua_State *L,
7394 int arg,
7395 const char *d);</pre>
7396
7397 <p>
7398 If the function argument <code>arg</code> is a string,
7399 returns this string.
7400 If this argument is absent or is <b>nil</b>,
7401 returns <code>d</code>.
7402 Otherwise, raises an error.
7403
7404
7405
7406
7407
7408 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
7409 <span class="apii">[-?, +?, <em>m</em>]</span>
7410 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
7411
7412 <p>
7413 Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
7414 with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
7415
7416
7417
7418
7419
7420 <hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
7421 <span class="apii">[-?, +?, <em>m</em>]</span>
7422 <pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
7423
7424 <p>
7425 Returns an address to a space of size <code>sz</code>
7426 where you can copy a string to be added to buffer <code>B</code>
7427 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
7428 After copying the string into this space you must call
7429 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
7430 it to the buffer.
7431
7432
7433
7434
7435
7436 <hr><h3><a name="luaL_pushfail"><code>luaL_pushfail</code></a></h3><p>
7437 <span class="apii">[-0, +1, &ndash;]</span>
7438 <pre>void luaL_pushfail (lua_State *L);</pre>
7439
7440 <p>
7441 Pushes the <b>fail</b> value onto the stack (see <a href="#6">&sect;6</a>).
7442
7443
7444
7445
7446
7447 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
7448 <span class="apii">[-?, +1, <em>m</em>]</span>
7449 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
7450
7451 <p>
7452 Finishes the use of buffer <code>B</code> leaving the final string on
7453 the top of the stack.
7454
7455
7456
7457
7458
7459 <hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
7460 <span class="apii">[-?, +1, <em>m</em>]</span>
7461 <pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
7462
7463 <p>
7464 Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
7465
7466
7467
7468
7469
7470 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
7471 <span class="apii">[-1, +0, <em>m</em>]</span>
7472 <pre>int luaL_ref (lua_State *L, int t);</pre>
7473
7474 <p>
7475 Creates and returns a <em>reference</em>,
7476 in the table at index <code>t</code>,
7477 for the object on the top of the stack (and pops the object).
7478
7479
7480 <p>
7481 A reference is a unique integer key.
7482 As long as you do not manually add integer keys into the table <code>t</code>,
7483 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
7484 You can retrieve an object referred by the reference <code>r</code>
7485 by calling <code>lua_rawgeti(L, t, r)</code>.
7486 The function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference.
7487
7488
7489 <p>
7490 If the object on the top of the stack is <b>nil</b>,
7491 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
7492 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
7493 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
7494
7495
7496
7497
7498
7499 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
7500 <pre>typedef struct luaL_Reg {
7501 const char *name;
7502 lua_CFunction func;
7503 } luaL_Reg;</pre>
7504
7505 <p>
7506 Type for arrays of functions to be registered by
7507 <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
7508 <code>name</code> is the function name and <code>func</code> is a pointer to
7509 the function.
7510 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
7511 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
7512
7513
7514
7515
7516
7517 <hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
7518 <span class="apii">[-0, +1, <em>e</em>]</span>
7519 <pre>void luaL_requiref (lua_State *L, const char *modname,
7520 lua_CFunction openf, int glb);</pre>
7521
7522 <p>
7523 If <code>package.loaded[modname]</code> is not true,
7524 calls the function <code>openf</code> with the string <code>modname</code> as an argument
7525 and sets the call result to <code>package.loaded[modname]</code>,
7526 as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
7527
7528
7529 <p>
7530 If <code>glb</code> is true,
7531 also stores the module into the global <code>modname</code>.
7532
7533
7534 <p>
7535 Leaves a copy of the module on the stack.
7536
7537
7538
7539
7540
7541 <hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
7542 <span class="apii">[-nup, +0, <em>m</em>]</span>
7543 <pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
7544
7545 <p>
7546 Registers all functions in the array <code>l</code>
7547 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
7548 (below optional upvalues, see next).
7549
7550
7551 <p>
7552 When <code>nup</code> is not zero,
7553 all functions are created with <code>nup</code> upvalues,
7554 initialized with copies of the <code>nup</code> values
7555 previously pushed on the stack
7556 on top of the library table.
7557 These values are popped from the stack after the registration.
7558
7559
7560
7561
7562
7563 <hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
7564 <span class="apii">[-0, +0, &ndash;]</span>
7565 <pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
7566
7567 <p>
7568 Sets the metatable of the object on the top of the stack
7569 as the metatable associated with name <code>tname</code>
7570 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7571
7572
7573
7574
7575
7576 <hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
7577 <pre>typedef struct luaL_Stream {
7578 FILE *f;
7579 lua_CFunction closef;
7580 } luaL_Stream;</pre>
7581
7582 <p>
7583 The standard representation for file handles
7584 used by the standard I/O library.
7585
7586
7587 <p>
7588 A file handle is implemented as a full userdata,
7589 with a metatable called <code>LUA_FILEHANDLE</code>
7590 (where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
7591 The metatable is created by the I/O library
7592 (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
7593
7594
7595 <p>
7596 This userdata must start with the structure <code>luaL_Stream</code>;
7597 it can contain other data after this initial structure.
7598 The field <code>f</code> points to the corresponding C stream
7599 (or it can be <code>NULL</code> to indicate an incompletely created handle).
7600 The field <code>closef</code> points to a Lua function
7601 that will be called to close the stream
7602 when the handle is closed or collected;
7603 this function receives the file handle as its sole argument and
7604 must return either a true value, in case of success,
7605 or a false value plus an error message, in case of error.
7606 Once Lua calls this field,
7607 it changes the field value to <code>NULL</code>
7608 to signal that the handle is closed.
7609
7610
7611
7612
7613
7614 <hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
7615 <span class="apii">[-0, +0, <em>m</em>]</span>
7616 <pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
7617
7618 <p>
7619 This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
7620 except that, when the test fails,
7621 it returns <code>NULL</code> instead of raising an error.
7622
7623
7624
7625
7626
7627 <hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
7628 <span class="apii">[-0, +1, <em>e</em>]</span>
7629 <pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
7630
7631 <p>
7632 Converts any Lua value at the given index to a C&nbsp;string
7633 in a reasonable format.
7634 The resulting string is pushed onto the stack and also
7635 returned by the function (see <a href="#4.1.3">&sect;4.1.3</a>).
7636 If <code>len</code> is not <code>NULL</code>,
7637 the function also sets <code>*len</code> with the string length.
7638
7639
7640 <p>
7641 If the value has a metatable with a <code>__tostring</code> field,
7642 then <code>luaL_tolstring</code> calls the corresponding metamethod
7643 with the value as argument,
7644 and uses the result of the call as its result.
7645
7646
7647
7648
7649
7650 <hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
7651 <span class="apii">[-0, +1, <em>m</em>]</span>
7652 <pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
7653 int level);</pre>
7654
7655 <p>
7656 Creates and pushes a traceback of the stack <code>L1</code>.
7657 If <code>msg</code> is not <code>NULL</code>, it is appended
7658 at the beginning of the traceback.
7659 The <code>level</code> parameter tells at which level
7660 to start the traceback.
7661
7662
7663
7664
7665
7666 <hr><h3><a name="luaL_typeerror"><code>luaL_typeerror</code></a></h3><p>
7667 <span class="apii">[-0, +0, <em>v</em>]</span>
7668 <pre>const char *luaL_typeerror (lua_State *L,
7669 int arg,
7670 const char *tname);</pre>
7671
7672 <p>
7673 Raises a type error for the argument <code>arg</code>
7674 of the C&nbsp;function that called it,
7675 using a standard message;
7676 <code>tname</code> is a "name" for the expected type.
7677 This function never returns.
7678
7679
7680
7681
7682
7683 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
7684 <span class="apii">[-0, +0, &ndash;]</span>
7685 <pre>const char *luaL_typename (lua_State *L, int index);</pre>
7686
7687 <p>
7688 Returns the name of the type of the value at the given index.
7689
7690
7691
7692
7693
7694 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
7695 <span class="apii">[-0, +0, &ndash;]</span>
7696 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
7697
7698 <p>
7699 Releases the reference <code>ref</code> from the table at index <code>t</code>
7700 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
7701 The entry is removed from the table,
7702 so that the referred object can be collected.
7703 The reference <code>ref</code> is also freed to be used again.
7704
7705
7706 <p>
7707 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>,
7708 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
7709
7710
7711
7712
7713
7714 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
7715 <span class="apii">[-0, +1, <em>m</em>]</span>
7716 <pre>void luaL_where (lua_State *L, int lvl);</pre>
7717
7718 <p>
7719 Pushes onto the stack a string identifying the current position
7720 of the control at level <code>lvl</code> in the call stack.
7721 Typically this string has the following format:
7722
7723 <pre>
7724 <em>chunkname</em>:<em>currentline</em>:
7725 </pre><p>
7726 Level&nbsp;0 is the running function,
7727 level&nbsp;1 is the function that called the running function,
7728 etc.
7729
7730
7731 <p>
7732 This function is used to build a prefix for error messages.
7733
7734
7735
7736
7737
7738
7739
7740 <h1>6 &ndash; <a name="6">The Standard Libraries</a></h1>
7741
7742
7743
7744 <p>
7745 The standard Lua libraries provide useful functions
7746 that are implemented in&nbsp;C through the C&nbsp;API.
7747 Some of these functions provide essential services to the language
7748 (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7749 others provide access to outside services (e.g., I/O);
7750 and others could be implemented in Lua itself,
7751 but that for different reasons
7752 deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7753
7754
7755 <p>
7756 All libraries are implemented through the official C&nbsp;API
7757 and are provided as separate C&nbsp;modules.
7758 Unless otherwise noted,
7759 these library functions do not adjust its number of arguments
7760 to its expected parameters.
7761 For instance, a function documented as <code>foo(arg)</code>
7762 should not be called without an argument.
7763
7764
7765 <p>
7766 The notation <b>fail</b> means a false value representing
7767 some kind of failure.
7768 (Currently, <b>fail</b> is equal to <b>nil</b>,
7769 but that may change in future versions.
7770 The recommendation is to always test the success of these functions
7771 with <code>(not status)</code>, instead of <code>(status == nil)</code>.)
7772
7773
7774 <p>
7775 Currently, Lua has the following standard libraries:
7776
7777 <ul>
7778
7779 <li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7780
7781 <li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7782
7783 <li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7784
7785 <li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7786
7787 <li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7788
7789 <li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7790
7791 <li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7792
7793 <li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7794
7795 <li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7796
7797 <li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7798
7799 </ul><p>
7800 Except for the basic and the package libraries,
7801 each library provides all its functions as fields of a global table
7802 or as methods of its objects.
7803
7804
7805 <p>
7806 To have access to these libraries,
7807 the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7808 which opens all standard libraries.
7809 Alternatively,
7810 the host program can open them individually by using
7811 <a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7812 <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7813 <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7814 <a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7815 <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7816 <a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF-8 library),
7817 <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7818 <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7819 <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7820 <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7821 and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7822 These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7823
7824
7825
7826
7827
7828 <h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7829
7830 <p>
7831 The basic library provides core functions to Lua.
7832 If you do not include this library in your application,
7833 you should check carefully whether you need to provide
7834 implementations for some of its facilities.
7835
7836
7837 <p>
7838 <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7839
7840
7841 <p>
7842 Raises an error if
7843 the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7844 otherwise, returns all its arguments.
7845 In case of error,
7846 <code>message</code> is the error object;
7847 when absent, it defaults to "<code>assertion failed!</code>"
7848
7849
7850
7851
7852 <p>
7853 <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7854
7855
7856 <p>
7857 This function is a generic interface to the garbage collector.
7858 It performs different functions according to its first argument, <code>opt</code>:
7859
7860 <ul>
7861
7862 <li><b>"<code>collect</code>": </b>
7863 Performs a full garbage-collection cycle.
7864 This is the default option.
7865 </li>
7866
7867 <li><b>"<code>stop</code>": </b>
7868 Stops automatic execution of the garbage collector.
7869 The collector will run only when explicitly invoked,
7870 until a call to restart it.
7871 </li>
7872
7873 <li><b>"<code>restart</code>": </b>
7874 Restarts automatic execution of the garbage collector.
7875 </li>
7876
7877 <li><b>"<code>count</code>": </b>
7878 Returns the total memory in use by Lua in Kbytes.
7879 The value has a fractional part,
7880 so that it multiplied by 1024
7881 gives the exact number of bytes in use by Lua.
7882 </li>
7883
7884 <li><b>"<code>step</code>": </b>
7885 Performs a garbage-collection step.
7886 The step "size" is controlled by <code>arg</code>.
7887 With a zero value,
7888 the collector will perform one basic (indivisible) step.
7889 For non-zero values,
7890 the collector will perform as if that amount of memory
7891 (in Kbytes) had been allocated by Lua.
7892 Returns <b>true</b> if the step finished a collection cycle.
7893 </li>
7894
7895 <li><b>"<code>isrunning</code>": </b>
7896 Returns a boolean that tells whether the collector is running
7897 (i.e., not stopped).
7898 </li>
7899
7900 <li><b>"<code>incremental</code>": </b>
7901 Change the collector mode to incremental.
7902 This option can be followed by three numbers:
7903 the garbage-collector pause,
7904 the step multiplier,
7905 and the step size (see <a href="#2.5.1">&sect;2.5.1</a>).
7906 A zero means to not change that value.
7907 </li>
7908
7909 <li><b>"<code>generational</code>": </b>
7910 Change the collector mode to generational.
7911 This option can be followed by two numbers:
7912 the garbage-collector minor multiplier
7913 and the major multiplier (see <a href="#2.5.2">&sect;2.5.2</a>).
7914 A zero means to not change that value.
7915 </li>
7916
7917 </ul><p>
7918 See <a href="#2.5">&sect;2.5</a> for more details about garbage collection
7919 and some of these options.
7920
7921
7922
7923
7924 <p>
7925 <hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7926 Opens the named file and executes its content as a Lua chunk.
7927 When called without arguments,
7928 <code>dofile</code> executes the content of the standard input (<code>stdin</code>).
7929 Returns all values returned by the chunk.
7930 In case of errors, <code>dofile</code> propagates the error
7931 to its caller.
7932 (That is, <code>dofile</code> does not run in protected mode.)
7933
7934
7935
7936
7937 <p>
7938 <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7939 Raises an error (see <a href="#2.3">&sect;2.3</a>) with @{message} as the error object.
7940 This function never returns.
7941
7942
7943 <p>
7944 Usually, <code>error</code> adds some information about the error position
7945 at the beginning of the message, if the message is a string.
7946 The <code>level</code> argument specifies how to get the error position.
7947 With level&nbsp;1 (the default), the error position is where the
7948 <code>error</code> function was called.
7949 Level&nbsp;2 points the error to where the function
7950 that called <code>error</code> was called; and so on.
7951 Passing a level&nbsp;0 avoids the addition of error position information
7952 to the message.
7953
7954
7955
7956
7957 <p>
7958 <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7959 A global variable (not a function) that
7960 holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7961 Lua itself does not use this variable;
7962 changing its value does not affect any environment,
7963 nor vice versa.
7964
7965
7966
7967
7968 <p>
7969 <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7970
7971
7972 <p>
7973 If <code>object</code> does not have a metatable, returns <b>nil</b>.
7974 Otherwise,
7975 if the object's metatable has a <code>__metatable</code> field,
7976 returns the associated value.
7977 Otherwise, returns the metatable of the given object.
7978
7979
7980
7981
7982 <p>
7983 <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7984
7985
7986 <p>
7987 Returns three values (an iterator function, the table <code>t</code>, and 0)
7988 so that the construction
7989
7990 <pre>
7991 for i,v in ipairs(t) do <em>body</em> end
7992 </pre><p>
7993 will iterate over the key&ndash;value pairs
7994 (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7995 up to the first absent index.
7996
7997
7998
7999
8000 <p>
8001 <hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
8002
8003
8004 <p>
8005 Loads a chunk.
8006
8007
8008 <p>
8009 If <code>chunk</code> is a string, the chunk is this string.
8010 If <code>chunk</code> is a function,
8011 <code>load</code> calls it repeatedly to get the chunk pieces.
8012 Each call to <code>chunk</code> must return a string that concatenates
8013 with previous results.
8014 A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
8015
8016
8017 <p>
8018 If there are no syntactic errors,
8019 <code>load</code> returns the compiled chunk as a function;
8020 otherwise, it returns <b>fail</b> plus the error message.
8021
8022
8023 <p>
8024 When you load a main chunk,
8025 the resulting function will always have exactly one upvalue,
8026 the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
8027 However,
8028 when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
8029 the resulting function can have an arbitrary number of upvalues,
8030 and there is no guarantee that its first upvalue will be
8031 the <code>_ENV</code> variable.
8032 (A non-main function may not even have an <code>_ENV</code> upvalue.)
8033
8034
8035 <p>
8036 Regardless, if the resulting function has any upvalues,
8037 its first upvalue is set to the value of <code>env</code>,
8038 if that parameter is given,
8039 or to the value of the global environment.
8040 Other upvalues are initialized with <b>nil</b>.
8041 All upvalues are fresh, that is,
8042 they are not shared with any other function.
8043
8044
8045 <p>
8046 <code>chunkname</code> is used as the name of the chunk for error messages
8047 and debug information (see <a href="#4.7">&sect;4.7</a>).
8048 When absent,
8049 it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
8050 or to "<code>=(load)</code>" otherwise.
8051
8052
8053 <p>
8054 The string <code>mode</code> controls whether the chunk can be text or binary
8055 (that is, a precompiled chunk).
8056 It may be the string "<code>b</code>" (only binary chunks),
8057 "<code>t</code>" (only text chunks),
8058 or "<code>bt</code>" (both binary and text).
8059 The default is "<code>bt</code>".
8060
8061
8062 <p>
8063 It is safe to load malformed binary chunks;
8064 <code>load</code> signals an appropriate error.
8065 However,
8066 Lua does not check the consistency of the code inside binary chunks;
8067 running maliciously crafted bytecode can crash the interpreter.
8068
8069
8070
8071
8072 <p>
8073 <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
8074
8075
8076 <p>
8077 Similar to <a href="#pdf-load"><code>load</code></a>,
8078 but gets the chunk from file <code>filename</code>
8079 or from the standard input,
8080 if no file name is given.
8081
8082
8083
8084
8085 <p>
8086 <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
8087
8088
8089 <p>
8090 Allows a program to traverse all fields of a table.
8091 Its first argument is a table and its second argument
8092 is an index in this table.
8093 A call to <code>next</code> returns the next index of the table
8094 and its associated value.
8095 When called with <b>nil</b> as its second argument,
8096 <code>next</code> returns an initial index
8097 and its associated value.
8098 When called with the last index,
8099 or with <b>nil</b> in an empty table,
8100 <code>next</code> returns <b>nil</b>.
8101 If the second argument is absent, then it is interpreted as <b>nil</b>.
8102 In particular,
8103 you can use <code>next(t)</code> to check whether a table is empty.
8104
8105
8106 <p>
8107 The order in which the indices are enumerated is not specified,
8108 <em>even for numeric indices</em>.
8109 (To traverse a table in numerical order,
8110 use a numerical <b>for</b>.)
8111
8112
8113 <p>
8114 The behavior of <code>next</code> is undefined if,
8115 during the traversal,
8116 you assign any value to a non-existent field in the table.
8117 You may however modify existing fields.
8118 In particular, you may set existing fields to nil.
8119
8120
8121
8122
8123 <p>
8124 <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
8125
8126
8127 <p>
8128 If <code>t</code> has a metamethod <code>__pairs</code>,
8129 calls it with <code>t</code> as argument and returns the first three
8130 results from the call.
8131
8132
8133 <p>
8134 Otherwise,
8135 returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
8136 so that the construction
8137
8138 <pre>
8139 for k,v in pairs(t) do <em>body</em> end
8140 </pre><p>
8141 will iterate over all key&ndash;value pairs of table <code>t</code>.
8142
8143
8144 <p>
8145 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
8146 the table during its traversal.
8147
8148
8149
8150
8151 <p>
8152 <hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
8153
8154
8155 <p>
8156 Calls the function <code>f</code> with
8157 the given arguments in <em>protected mode</em>.
8158 This means that any error inside&nbsp;<code>f</code> is not propagated;
8159 instead, <code>pcall</code> catches the error
8160 and returns a status code.
8161 Its first result is the status code (a boolean),
8162 which is true if the call succeeds without errors.
8163 In such case, <code>pcall</code> also returns all results from the call,
8164 after this first result.
8165 In case of any error, <code>pcall</code> returns <b>false</b> plus the error object.
8166 Note that errors caught by <code>pcall</code> do not call a message handler.
8167
8168
8169
8170
8171 <p>
8172 <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
8173 Receives any number of arguments
8174 and prints their values to <code>stdout</code>,
8175 converting each argument to a string
8176 following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8177
8178
8179 <p>
8180 The function <code>print</code> is not intended for formatted output,
8181 but only as a quick way to show a value,
8182 for instance for debugging.
8183 For complete control over the output,
8184 use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
8185
8186
8187
8188
8189 <p>
8190 <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
8191 Checks whether <code>v1</code> is equal to <code>v2</code>,
8192 without invoking the <code>__eq</code> metamethod.
8193 Returns a boolean.
8194
8195
8196
8197
8198 <p>
8199 <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
8200 Gets the real value of <code>table[index]</code>,
8201 without using the <code>__index</code> metavalue.
8202 <code>table</code> must be a table;
8203 <code>index</code> may be any value.
8204
8205
8206
8207
8208 <p>
8209 <hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
8210 Returns the length of the object <code>v</code>,
8211 which must be a table or a string,
8212 without invoking the <code>__len</code> metamethod.
8213 Returns an integer.
8214
8215
8216
8217
8218 <p>
8219 <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
8220 Sets the real value of <code>table[index]</code> to <code>value</code>,
8221 without using the <code>__newindex</code> metavalue.
8222 <code>table</code> must be a table,
8223 <code>index</code> any value different from <b>nil</b> and NaN,
8224 and <code>value</code> any Lua value.
8225
8226
8227 <p>
8228 This function returns <code>table</code>.
8229
8230
8231
8232
8233 <p>
8234 <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
8235
8236
8237 <p>
8238 If <code>index</code> is a number,
8239 returns all arguments after argument number <code>index</code>;
8240 a negative number indexes from the end (-1 is the last argument).
8241 Otherwise, <code>index</code> must be the string <code>"#"</code>,
8242 and <code>select</code> returns the total number of extra arguments it received.
8243
8244
8245
8246
8247 <p>
8248 <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
8249
8250
8251 <p>
8252 Sets the metatable for the given table.
8253 If <code>metatable</code> is <b>nil</b>,
8254 removes the metatable of the given table.
8255 If the original metatable has a <code>__metatable</code> field,
8256 raises an error.
8257
8258
8259 <p>
8260 This function returns <code>table</code>.
8261
8262
8263 <p>
8264 To change the metatable of other types from Lua code,
8265 you must use the debug library (<a href="#6.10">&sect;6.10</a>).
8266
8267
8268
8269
8270 <p>
8271 <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
8272
8273
8274 <p>
8275 When called with no <code>base</code>,
8276 <code>tonumber</code> tries to convert its argument to a number.
8277 If the argument is already a number or
8278 a string convertible to a number,
8279 then <code>tonumber</code> returns this number;
8280 otherwise, it returns <b>fail</b>.
8281
8282
8283 <p>
8284 The conversion of strings can result in integers or floats,
8285 according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
8286 The string may have leading and trailing spaces and a sign.
8287
8288
8289 <p>
8290 When called with <code>base</code>,
8291 then <code>e</code> must be a string to be interpreted as
8292 an integer numeral in that base.
8293 The base may be any integer between 2 and 36, inclusive.
8294 In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
8295 represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
8296 with '<code>Z</code>' representing 35.
8297 If the string <code>e</code> is not a valid numeral in the given base,
8298 the function returns <b>fail</b>.
8299
8300
8301
8302
8303 <p>
8304 <hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
8305
8306
8307 <p>
8308 Receives a value of any type and
8309 converts it to a string in a human-readable format.
8310
8311
8312 <p>
8313 If the metatable of <code>v</code> has a <code>__tostring</code> field,
8314 then <code>tostring</code> calls the corresponding value
8315 with <code>v</code> as argument,
8316 and uses the result of the call as its result.
8317 Otherwise, if the metatable of <code>v</code> has a <code>__name</code> field
8318 with a string value,
8319 <code>tostring</code> may use that string in its final result.
8320
8321
8322 <p>
8323 For complete control of how numbers are converted,
8324 use <a href="#pdf-string.format"><code>string.format</code></a>.
8325
8326
8327
8328
8329 <p>
8330 <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
8331
8332
8333 <p>
8334 Returns the type of its only argument, coded as a string.
8335 The possible results of this function are
8336 "<code>nil</code>" (a string, not the value <b>nil</b>),
8337 "<code>number</code>",
8338 "<code>string</code>",
8339 "<code>boolean</code>",
8340 "<code>table</code>",
8341 "<code>function</code>",
8342 "<code>thread</code>",
8343 and "<code>userdata</code>".
8344
8345
8346
8347
8348 <p>
8349 <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
8350
8351
8352 <p>
8353 A global variable (not a function) that
8354 holds a string containing the running Lua version.
8355 The current value of this variable is "<code>Lua 5.4</code>".
8356
8357
8358
8359
8360 <p>
8361 <hr><h3><a name="pdf-warn"><code>warn (msg1, &middot;&middot;&middot;)</code></a></h3>
8362
8363
8364 <p>
8365 Emits a warning with a message composed by the concatenation
8366 of all its arguments (which should be strings).
8367
8368
8369 <p>
8370 By convention,
8371 a one-piece message starting with '<code>@</code>'
8372 is intended to be a <em>control message</em>,
8373 which is a message to the warning system itself.
8374 In particular, the standard warning function in Lua
8375 recognizes the control messages "<code>@off</code>",
8376 to stop the emission of warnings,
8377 and "<code>@on</code>", to (re)start the emission;
8378 it ignores unknown control messages.
8379
8380
8381
8382
8383 <p>
8384 <hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
8385
8386
8387 <p>
8388 This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
8389 except that it sets a new message handler <code>msgh</code>.
8390
8391
8392
8393
8394
8395
8396
8397 <h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
8398
8399 <p>
8400 This library comprises the operations to manipulate coroutines,
8401 which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
8402 See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
8403
8404
8405 <p>
8406 <hr><h3><a name="pdf-coroutine.close"><code>coroutine.close (co)</code></a></h3>
8407
8408
8409 <p>
8410 Closes coroutine <code>co</code>,
8411 that is,
8412 closes all its pending to-be-closed variables
8413 and puts the coroutine in a dead state.
8414 The given coroutine must be dead or suspended.
8415 In case of error
8416 (either the original error that stopped the coroutine or
8417 errors in closing methods),
8418 returns <b>false</b> plus the error object;
8419 otherwise returns <b>true</b>.
8420
8421
8422
8423
8424 <p>
8425 <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
8426
8427
8428 <p>
8429 Creates a new coroutine, with body <code>f</code>.
8430 <code>f</code> must be a function.
8431 Returns this new coroutine,
8432 an object with type <code>"thread"</code>.
8433
8434
8435
8436
8437 <p>
8438 <hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ([co])</code></a></h3>
8439
8440
8441 <p>
8442 Returns true when the coroutine <code>co</code> can yield.
8443 The default for <code>co</code> is the running coroutine.
8444
8445
8446 <p>
8447 A coroutine is yieldable if it is not the main thread and
8448 it is not inside a non-yieldable C&nbsp;function.
8449
8450
8451
8452
8453 <p>
8454 <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
8455
8456
8457 <p>
8458 Starts or continues the execution of coroutine <code>co</code>.
8459 The first time you resume a coroutine,
8460 it starts running its body.
8461 The values <code>val1</code>, ... are passed
8462 as the arguments to the body function.
8463 If the coroutine has yielded,
8464 <code>resume</code> restarts it;
8465 the values <code>val1</code>, ... are passed
8466 as the results from the yield.
8467
8468
8469 <p>
8470 If the coroutine runs without any errors,
8471 <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
8472 (when the coroutine yields) or any values returned by the body function
8473 (when the coroutine terminates).
8474 If there is any error,
8475 <code>resume</code> returns <b>false</b> plus the error message.
8476
8477
8478
8479
8480 <p>
8481 <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
8482
8483
8484 <p>
8485 Returns the running coroutine plus a boolean,
8486 true when the running coroutine is the main one.
8487
8488
8489
8490
8491 <p>
8492 <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
8493
8494
8495 <p>
8496 Returns the status of the coroutine <code>co</code>, as a string:
8497 <code>"running"</code>,
8498 if the coroutine is running
8499 (that is, it is the one that called <code>status</code>);
8500 <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
8501 or if it has not started running yet;
8502 <code>"normal"</code> if the coroutine is active but not running
8503 (that is, it has resumed another coroutine);
8504 and <code>"dead"</code> if the coroutine has finished its body function,
8505 or if it has stopped with an error.
8506
8507
8508
8509
8510 <p>
8511 <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
8512
8513
8514 <p>
8515 Creates a new coroutine, with body <code>f</code>;
8516 <code>f</code> must be a function.
8517 Returns a function that resumes the coroutine each time it is called.
8518 Any arguments passed to this function behave as the
8519 extra arguments to <code>resume</code>.
8520 The function returns the same values returned by <code>resume</code>,
8521 except the first boolean.
8522 In case of error,
8523 the function closes the coroutine and propagates the error.
8524
8525
8526
8527
8528 <p>
8529 <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
8530
8531
8532 <p>
8533 Suspends the execution of the calling coroutine.
8534 Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
8535
8536
8537
8538
8539
8540
8541
8542 <h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
8543
8544 <p>
8545 The package library provides basic
8546 facilities for loading modules in Lua.
8547 It exports one function directly in the global environment:
8548 <a href="#pdf-require"><code>require</code></a>.
8549 Everything else is exported in the table <a name="pdf-package"><code>package</code></a>.
8550
8551
8552 <p>
8553 <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
8554
8555
8556 <p>
8557 Loads the given module.
8558 The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
8559 to determine whether <code>modname</code> is already loaded.
8560 If it is, then <code>require</code> returns the value stored
8561 at <code>package.loaded[modname]</code>.
8562 (The absence of a second result in this case
8563 signals that this call did not have to load the module.)
8564 Otherwise, it tries to find a <em>loader</em> for the module.
8565
8566
8567 <p>
8568 To find a loader,
8569 <code>require</code> is guided by the table <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8570 Each item in this table is a search function,
8571 that searches for the module in a particular way.
8572 By changing this table,
8573 we can change how <code>require</code> looks for a module.
8574 The following explanation is based on the default configuration
8575 for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
8576
8577
8578 <p>
8579 First <code>require</code> queries <code>package.preload[modname]</code>.
8580 If it has a value,
8581 this value (which must be a function) is the loader.
8582 Otherwise <code>require</code> searches for a Lua loader using the
8583 path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
8584 If that also fails, it searches for a C&nbsp;loader using the
8585 path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8586 If that also fails,
8587 it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
8588
8589
8590 <p>
8591 Once a loader is found,
8592 <code>require</code> calls the loader with two arguments:
8593 <code>modname</code> and an extra value,
8594 a <em>loader data</em>,
8595 also returned by the searcher.
8596 The loader data can be any value useful to the module;
8597 for the default searchers,
8598 it indicates where the loader was found.
8599 (For instance, if the loader came from a file,
8600 this extra value is the file path.)
8601 If the loader returns any non-nil value,
8602 <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
8603 If the loader does not return a non-nil value and
8604 has not assigned any value to <code>package.loaded[modname]</code>,
8605 then <code>require</code> assigns <b>true</b> to this entry.
8606 In any case, <code>require</code> returns the
8607 final value of <code>package.loaded[modname]</code>.
8608 Besides that value, <code>require</code> also returns as a second result
8609 the loader data returned by the searcher,
8610 which indicates how <code>require</code> found the module.
8611
8612
8613 <p>
8614 If there is any error loading or running the module,
8615 or if it cannot find any loader for the module,
8616 then <code>require</code> raises an error.
8617
8618
8619
8620
8621 <p>
8622 <hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
8623
8624
8625 <p>
8626 A string describing some compile-time configurations for packages.
8627 This string is a sequence of lines:
8628
8629 <ul>
8630
8631 <li>The first line is the directory separator string.
8632 Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
8633
8634 <li>The second line is the character that separates templates in a path.
8635 Default is '<code>;</code>'.</li>
8636
8637 <li>The third line is the string that marks the
8638 substitution points in a template.
8639 Default is '<code>?</code>'.</li>
8640
8641 <li>The fourth line is a string that, in a path in Windows,
8642 is replaced by the executable's directory.
8643 Default is '<code>!</code>'.</li>
8644
8645 <li>The fifth line is a mark to ignore all text after it
8646 when building the <code>luaopen_</code> function name.
8647 Default is '<code>-</code>'.</li>
8648
8649 </ul>
8650
8651
8652
8653 <p>
8654 <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
8655
8656
8657 <p>
8658 A string with the path used by <a href="#pdf-require"><code>require</code></a>
8659 to search for a C&nbsp;loader.
8660
8661
8662 <p>
8663 Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
8664 it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
8665 using the environment variable <a name="pdf-LUA_CPATH_5_4"><code>LUA_CPATH_5_4</code></a>,
8666 or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>,
8667 or a default path defined in <code>luaconf.h</code>.
8668
8669
8670
8671
8672 <p>
8673 <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
8674
8675
8676 <p>
8677 A table used by <a href="#pdf-require"><code>require</code></a> to control which
8678 modules are already loaded.
8679 When you require a module <code>modname</code> and
8680 <code>package.loaded[modname]</code> is not false,
8681 <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
8682
8683
8684 <p>
8685 This variable is only a reference to the real table;
8686 assignments to this variable do not change the
8687 table used by <a href="#pdf-require"><code>require</code></a>.
8688
8689
8690
8691
8692 <p>
8693 <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
8694
8695
8696 <p>
8697 Dynamically links the host program with the C&nbsp;library <code>libname</code>.
8698
8699
8700 <p>
8701 If <code>funcname</code> is "<code>*</code>",
8702 then it only links with the library,
8703 making the symbols exported by the library
8704 available to other dynamically linked libraries.
8705 Otherwise,
8706 it looks for a function <code>funcname</code> inside the library
8707 and returns this function as a C&nbsp;function.
8708 So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
8709 (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8710
8711
8712 <p>
8713 This is a low-level function.
8714 It completely bypasses the package and module system.
8715 Unlike <a href="#pdf-require"><code>require</code></a>,
8716 it does not perform any path searching and
8717 does not automatically adds extensions.
8718 <code>libname</code> must be the complete file name of the C&nbsp;library,
8719 including if necessary a path and an extension.
8720 <code>funcname</code> must be the exact name exported by the C&nbsp;library
8721 (which may depend on the C&nbsp;compiler and linker used).
8722
8723
8724 <p>
8725 This function is not supported by Standard&nbsp;C.
8726 As such, it is only available on some platforms
8727 (Windows, Linux, Mac OS X, Solaris, BSD,
8728 plus other Unix systems that support the <code>dlfcn</code> standard).
8729
8730
8731 <p>
8732 This function is inherently insecure,
8733 as it allows Lua to call any function in any readable dynamic
8734 library in the system.
8735 (Lua calls any function assuming the function
8736 has a proper prototype and respects a proper protocol
8737 (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
8738 Therefore,
8739 calling an arbitrary function in an arbitrary dynamic library
8740 more often than not results in an access violation.)
8741
8742
8743
8744
8745 <p>
8746 <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
8747
8748
8749 <p>
8750 A string with the path used by <a href="#pdf-require"><code>require</code></a>
8751 to search for a Lua loader.
8752
8753
8754 <p>
8755 At start-up, Lua initializes this variable with
8756 the value of the environment variable <a name="pdf-LUA_PATH_5_4"><code>LUA_PATH_5_4</code></a> or
8757 the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
8758 with a default path defined in <code>luaconf.h</code>,
8759 if those environment variables are not defined.
8760 A "<code>;;</code>" in the value of the environment variable
8761 is replaced by the default path.
8762
8763
8764
8765
8766 <p>
8767 <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
8768
8769
8770 <p>
8771 A table to store loaders for specific modules
8772 (see <a href="#pdf-require"><code>require</code></a>).
8773
8774
8775 <p>
8776 This variable is only a reference to the real table;
8777 assignments to this variable do not change the
8778 table used by <a href="#pdf-require"><code>require</code></a>.
8779
8780
8781
8782
8783 <p>
8784 <hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
8785
8786
8787 <p>
8788 A table used by <a href="#pdf-require"><code>require</code></a> to control how to find modules.
8789
8790
8791 <p>
8792 Each entry in this table is a <em>searcher function</em>.
8793 When looking for a module,
8794 <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
8795 with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
8796 sole argument.
8797 If the searcher finds the module,
8798 it returns another function, the module <em>loader</em>,
8799 plus an extra value, a <em>loader data</em>,
8800 that will be passed to that loader and
8801 returned as a second result by <a href="#pdf-require"><code>require</code></a>.
8802 If it cannot find the module,
8803 it returns a string explaining why
8804 (or <b>nil</b> if it has nothing to say).
8805
8806
8807 <p>
8808 Lua initializes this table with four searcher functions.
8809
8810
8811 <p>
8812 The first searcher simply looks for a loader in the
8813 <a href="#pdf-package.preload"><code>package.preload</code></a> table.
8814
8815
8816 <p>
8817 The second searcher looks for a loader as a Lua library,
8818 using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
8819 The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8820
8821
8822 <p>
8823 The third searcher looks for a loader as a C&nbsp;library,
8824 using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
8825 Again,
8826 the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8827 For instance,
8828 if the C&nbsp;path is the string
8829
8830 <pre>
8831 "./?.so;./?.dll;/usr/local/?/init.so"
8832 </pre><p>
8833 the searcher for module <code>foo</code>
8834 will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
8835 and <code>/usr/local/foo/init.so</code>, in that order.
8836 Once it finds a C&nbsp;library,
8837 this searcher first uses a dynamic link facility to link the
8838 application with the library.
8839 Then it tries to find a C&nbsp;function inside the library to
8840 be used as the loader.
8841 The name of this C&nbsp;function is the string "<code>luaopen_</code>"
8842 concatenated with a copy of the module name where each dot
8843 is replaced by an underscore.
8844 Moreover, if the module name has a hyphen,
8845 its suffix after (and including) the first hyphen is removed.
8846 For instance, if the module name is <code>a.b.c-v2.1</code>,
8847 the function name will be <code>luaopen_a_b_c</code>.
8848
8849
8850 <p>
8851 The fourth searcher tries an <em>all-in-one loader</em>.
8852 It searches the C&nbsp;path for a library for
8853 the root name of the given module.
8854 For instance, when requiring <code>a.b.c</code>,
8855 it will search for a C&nbsp;library for <code>a</code>.
8856 If found, it looks into it for an open function for
8857 the submodule;
8858 in our example, that would be <code>luaopen_a_b_c</code>.
8859 With this facility, a package can pack several C&nbsp;submodules
8860 into one single library,
8861 with each submodule keeping its original open function.
8862
8863
8864 <p>
8865 All searchers except the first one (preload) return as the extra value
8866 the file path where the module was found,
8867 as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8868 The first searcher always returns the string "<code>:preload:</code>".
8869
8870
8871 <p>
8872 Searchers should raise no errors and have no side effects in Lua.
8873 (They may have side effects in C,
8874 for instance by linking the application with a library.)
8875
8876
8877
8878
8879 <p>
8880 <hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8881
8882
8883 <p>
8884 Searches for the given <code>name</code> in the given <code>path</code>.
8885
8886
8887 <p>
8888 A path is a string containing a sequence of
8889 <em>templates</em> separated by semicolons.
8890 For each template,
8891 the function replaces each interrogation mark (if any)
8892 in the template with a copy of <code>name</code>
8893 wherein all occurrences of <code>sep</code>
8894 (a dot, by default)
8895 were replaced by <code>rep</code>
8896 (the system's directory separator, by default),
8897 and then tries to open the resulting file name.
8898
8899
8900 <p>
8901 For instance, if the path is the string
8902
8903 <pre>
8904 "./?.lua;./?.lc;/usr/local/?/init.lua"
8905 </pre><p>
8906 the search for the name <code>foo.a</code>
8907 will try to open the files
8908 <code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8909 <code>/usr/local/foo/a/init.lua</code>, in that order.
8910
8911
8912 <p>
8913 Returns the resulting name of the first file that it can
8914 open in read mode (after closing the file),
8915 or <b>fail</b> plus an error message if none succeeds.
8916 (This error message lists all file names it tried to open.)
8917
8918
8919
8920
8921
8922
8923
8924 <h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8925
8926
8927
8928 <p>
8929 This library provides generic functions for string manipulation,
8930 such as finding and extracting substrings, and pattern matching.
8931 When indexing a string in Lua, the first character is at position&nbsp;1
8932 (not at&nbsp;0, as in C).
8933 Indices are allowed to be negative and are interpreted as indexing backwards,
8934 from the end of the string.
8935 Thus, the last character is at position -1, and so on.
8936
8937
8938 <p>
8939 The string library provides all its functions inside the table
8940 <a name="pdf-string"><code>string</code></a>.
8941 It also sets a metatable for strings
8942 where the <code>__index</code> field points to the <code>string</code> table.
8943 Therefore, you can use the string functions in object-oriented style.
8944 For instance, <code>string.byte(s,i)</code>
8945 can be written as <code>s:byte(i)</code>.
8946
8947
8948 <p>
8949 The string library assumes one-byte character encodings.
8950
8951
8952 <p>
8953 <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8954 Returns the internal numeric codes of the characters <code>s[i]</code>,
8955 <code>s[i+1]</code>, ..., <code>s[j]</code>.
8956 The default value for <code>i</code> is&nbsp;1;
8957 the default value for <code>j</code> is&nbsp;<code>i</code>.
8958 These indices are corrected
8959 following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8960
8961
8962 <p>
8963 Numeric codes are not necessarily portable across platforms.
8964
8965
8966
8967
8968 <p>
8969 <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8970 Receives zero or more integers.
8971 Returns a string with length equal to the number of arguments,
8972 in which each character has the internal numeric code equal
8973 to its corresponding argument.
8974
8975
8976 <p>
8977 Numeric codes are not necessarily portable across platforms.
8978
8979
8980
8981
8982 <p>
8983 <hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8984
8985
8986 <p>
8987 Returns a string containing a binary representation
8988 (a <em>binary chunk</em>)
8989 of the given function,
8990 so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8991 a copy of the function (but with new upvalues).
8992 If <code>strip</code> is a true value,
8993 the binary representation may not include all debug information
8994 about the function,
8995 to save space.
8996
8997
8998 <p>
8999 Functions with upvalues have only their number of upvalues saved.
9000 When (re)loaded,
9001 those upvalues receive fresh instances.
9002 (See the <a href="#pdf-load"><code>load</code></a> function for details about
9003 how these upvalues are initialized.
9004 You can use the debug library to serialize
9005 and reload the upvalues of a function
9006 in a way adequate to your needs.)
9007
9008
9009
9010
9011 <p>
9012 <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
9013
9014
9015 <p>
9016 Looks for the first match of
9017 <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9018 If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
9019 where this occurrence starts and ends;
9020 otherwise, it returns <b>fail</b>.
9021 A third, optional numeric argument <code>init</code> specifies
9022 where to start the search;
9023 its default value is&nbsp;1 and can be negative.
9024 A value of <b>true</b> as a fourth, optional argument <code>plain</code>
9025 turns off the pattern matching facilities,
9026 so the function does a plain "find substring" operation,
9027 with no characters in <code>pattern</code> being considered magic.
9028
9029
9030 <p>
9031 If the pattern has captures,
9032 then in a successful match
9033 the captured values are also returned,
9034 after the two indices.
9035
9036
9037
9038
9039 <p>
9040 <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
9041
9042
9043 <p>
9044 Returns a formatted version of its variable number of arguments
9045 following the description given in its first argument,
9046 which must be a string.
9047 The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
9048 The only differences are that the conversion specifiers and modifiers
9049 <code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, and <code>n</code> are not supported
9050 and that there is an extra specifier, <code>q</code>.
9051
9052
9053 <p>
9054 The specifier <code>q</code> formats booleans, nil, numbers, and strings
9055 in a way that the result is a valid constant in Lua source code.
9056 Booleans and nil are written in the obvious way
9057 (<code>true</code>, <code>false</code>, <code>nil</code>).
9058 Floats are written in hexadecimal,
9059 to preserve full precision.
9060 A string is written between double quotes,
9061 using escape sequences when necessary to ensure that
9062 it can safely be read back by the Lua interpreter.
9063 For instance, the call
9064
9065 <pre>
9066 string.format('%q', 'a string with "quotes" and \n new line')
9067 </pre><p>
9068 may produce the string:
9069
9070 <pre>
9071 "a string with \"quotes\" and \
9072 new line"
9073 </pre><p>
9074 This specifier does not support modifiers (flags, width, length).
9075
9076
9077 <p>
9078 The conversion specifiers
9079 <code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>,
9080 <code>G</code>, and <code>g</code> all expect a number as argument.
9081 The specifiers <code>c</code>, <code>d</code>,
9082 <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
9083 expect an integer.
9084 When Lua is compiled with a C89 compiler,
9085 the specifiers <code>A</code> and <code>a</code> (hexadecimal floats)
9086 do not support modifiers.
9087
9088
9089 <p>
9090 The specifier <code>s</code> expects a string;
9091 if its argument is not a string,
9092 it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
9093 If the specifier has any modifier,
9094 the corresponding string argument should not contain embedded zeros.
9095
9096
9097 <p>
9098 The specifier <code>p</code> formats the pointer
9099 returned by <a href="#lua_topointer"><code>lua_topointer</code></a>.
9100 That gives a unique string identifier for tables, userdata,
9101 threads, strings, and functions.
9102 For other values (numbers, nil, booleans),
9103 this specifier results in a string representing
9104 the pointer <code>NULL</code>.
9105
9106
9107
9108
9109 <p>
9110 <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern [, init])</code></a></h3>
9111 Returns an iterator function that,
9112 each time it is called,
9113 returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
9114 over the string <code>s</code>.
9115 If <code>pattern</code> specifies no captures,
9116 then the whole match is produced in each call.
9117 A third, optional numeric argument <code>init</code> specifies
9118 where to start the search;
9119 its default value is&nbsp;1 and can be negative.
9120
9121
9122 <p>
9123 As an example, the following loop
9124 will iterate over all the words from string <code>s</code>,
9125 printing one per line:
9126
9127 <pre>
9128 s = "hello world from Lua"
9129 for w in string.gmatch(s, "%a+") do
9130 print(w)
9131 end
9132 </pre><p>
9133 The next example collects all pairs <code>key=value</code> from the
9134 given string into a table:
9135
9136 <pre>
9137 t = {}
9138 s = "from=world, to=Lua"
9139 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
9140 t[k] = v
9141 end
9142 </pre>
9143
9144 <p>
9145 For this function, a caret '<code>^</code>' at the start of a pattern does not
9146 work as an anchor, as this would prevent the iteration.
9147
9148
9149
9150
9151 <p>
9152 <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
9153 Returns a copy of <code>s</code>
9154 in which all (or the first <code>n</code>, if given)
9155 occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
9156 replaced by a replacement string specified by <code>repl</code>,
9157 which can be a string, a table, or a function.
9158 <code>gsub</code> also returns, as its second value,
9159 the total number of matches that occurred.
9160 The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
9161
9162
9163 <p>
9164 If <code>repl</code> is a string, then its value is used for replacement.
9165 The character&nbsp;<code>%</code> works as an escape character:
9166 any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
9167 with <em>d</em> between 1 and 9,
9168 stands for the value of the <em>d</em>-th captured substring;
9169 the sequence <code>%0</code> stands for the whole match;
9170 the sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
9171
9172
9173 <p>
9174 If <code>repl</code> is a table, then the table is queried for every match,
9175 using the first capture as the key.
9176
9177
9178 <p>
9179 If <code>repl</code> is a function, then this function is called every time a
9180 match occurs, with all captured substrings passed as arguments,
9181 in order.
9182
9183
9184 <p>
9185 In any case,
9186 if the pattern specifies no captures,
9187 then it behaves as if the whole pattern was inside a capture.
9188
9189
9190 <p>
9191 If the value returned by the table query or by the function call
9192 is a string or a number,
9193 then it is used as the replacement string;
9194 otherwise, if it is <b>false</b> or <b>nil</b>,
9195 then there is no replacement
9196 (that is, the original match is kept in the string).
9197
9198
9199 <p>
9200 Here are some examples:
9201
9202 <pre>
9203 x = string.gsub("hello world", "(%w+)", "%1 %1")
9204 --&gt; x="hello hello world world"
9205
9206 x = string.gsub("hello world", "%w+", "%0 %0", 1)
9207 --&gt; x="hello hello world"
9208
9209 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
9210 --&gt; x="world hello Lua from"
9211
9212 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
9213 --&gt; x="home = /home/roberto, user = roberto"
9214
9215 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
9216 return load(s)()
9217 end)
9218 --&gt; x="4+5 = 9"
9219
9220 local t = {name="lua", version="5.4"}
9221 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
9222 --&gt; x="lua-5.4.tar.gz"
9223 </pre>
9224
9225
9226
9227 <p>
9228 <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
9229
9230
9231 <p>
9232 Receives a string and returns its length.
9233 The empty string <code>""</code> has length 0.
9234 Embedded zeros are counted,
9235 so <code>"a\000bc\000"</code> has length 5.
9236
9237
9238
9239
9240 <p>
9241 <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
9242
9243
9244 <p>
9245 Receives a string and returns a copy of this string with all
9246 uppercase letters changed to lowercase.
9247 All other characters are left unchanged.
9248 The definition of what an uppercase letter is depends on the current locale.
9249
9250
9251
9252
9253 <p>
9254 <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
9255
9256
9257 <p>
9258 Looks for the first <em>match</em> of
9259 the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
9260 If it finds one, then <code>match</code> returns
9261 the captures from the pattern;
9262 otherwise it returns <b>fail</b>.
9263 If <code>pattern</code> specifies no captures,
9264 then the whole match is returned.
9265 A third, optional numeric argument <code>init</code> specifies
9266 where to start the search;
9267 its default value is&nbsp;1 and can be negative.
9268
9269
9270
9271
9272 <p>
9273 <hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
9274
9275
9276 <p>
9277 Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
9278 serialized in binary form (packed)
9279 according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9280
9281
9282
9283
9284 <p>
9285 <hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
9286
9287
9288 <p>
9289 Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
9290 with the given format.
9291 The format string cannot have the variable-length options
9292 '<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
9293
9294
9295
9296
9297 <p>
9298 <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
9299
9300
9301 <p>
9302 Returns a string that is the concatenation of <code>n</code> copies of
9303 the string <code>s</code> separated by the string <code>sep</code>.
9304 The default value for <code>sep</code> is the empty string
9305 (that is, no separator).
9306 Returns the empty string if <code>n</code> is not positive.
9307
9308
9309 <p>
9310 (Note that it is very easy to exhaust the memory of your machine
9311 with a single call to this function.)
9312
9313
9314
9315
9316 <p>
9317 <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
9318
9319
9320 <p>
9321 Returns a string that is the string <code>s</code> reversed.
9322
9323
9324
9325
9326 <p>
9327 <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
9328
9329
9330 <p>
9331 Returns the substring of <code>s</code> that
9332 starts at <code>i</code> and continues until <code>j</code>;
9333 <code>i</code> and <code>j</code> can be negative.
9334 If <code>j</code> is absent, then it is assumed to be equal to -1
9335 (which is the same as the string length).
9336 In particular,
9337 the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
9338 with length <code>j</code>,
9339 and <code>string.sub(s, -i)</code> (for a positive <code>i</code>)
9340 returns a suffix of <code>s</code>
9341 with length <code>i</code>.
9342
9343
9344 <p>
9345 If, after the translation of negative indices,
9346 <code>i</code> is less than 1,
9347 it is corrected to 1.
9348 If <code>j</code> is greater than the string length,
9349 it is corrected to that length.
9350 If, after these corrections,
9351 <code>i</code> is greater than <code>j</code>,
9352 the function returns the empty string.
9353
9354
9355
9356
9357 <p>
9358 <hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
9359
9360
9361 <p>
9362 Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
9363 according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
9364 An optional <code>pos</code> marks where
9365 to start reading in <code>s</code> (default is 1).
9366 After the read values,
9367 this function also returns the index of the first unread byte in <code>s</code>.
9368
9369
9370
9371
9372 <p>
9373 <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
9374
9375
9376 <p>
9377 Receives a string and returns a copy of this string with all
9378 lowercase letters changed to uppercase.
9379 All other characters are left unchanged.
9380 The definition of what a lowercase letter is depends on the current locale.
9381
9382
9383
9384
9385
9386
9387
9388 <h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
9389
9390
9391
9392 <p>
9393 Patterns in Lua are described by regular strings,
9394 which are interpreted as patterns by the pattern-matching functions
9395 <a href="#pdf-string.find"><code>string.find</code></a>,
9396 <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
9397 <a href="#pdf-string.gsub"><code>string.gsub</code></a>,
9398 and <a href="#pdf-string.match"><code>string.match</code></a>.
9399 This section describes the syntax and the meaning
9400 (that is, what they match) of these strings.
9401
9402
9403
9404
9405
9406 <h4>Character Class:</h4><p>
9407 A <em>character class</em> is used to represent a set of characters.
9408 The following combinations are allowed in describing a character class:
9409
9410 <ul>
9411
9412 <li><b><em>x</em>: </b>
9413 (where <em>x</em> is not one of the <em>magic characters</em>
9414 <code>^$()%.[]*+-?</code>)
9415 represents the character <em>x</em> itself.
9416 </li>
9417
9418 <li><b><code>.</code>: </b> (a dot) represents all characters.</li>
9419
9420 <li><b><code>%a</code>: </b> represents all letters.</li>
9421
9422 <li><b><code>%c</code>: </b> represents all control characters.</li>
9423
9424 <li><b><code>%d</code>: </b> represents all digits.</li>
9425
9426 <li><b><code>%g</code>: </b> represents all printable characters except space.</li>
9427
9428 <li><b><code>%l</code>: </b> represents all lowercase letters.</li>
9429
9430 <li><b><code>%p</code>: </b> represents all punctuation characters.</li>
9431
9432 <li><b><code>%s</code>: </b> represents all space characters.</li>
9433
9434 <li><b><code>%u</code>: </b> represents all uppercase letters.</li>
9435
9436 <li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
9437
9438 <li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
9439
9440 <li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
9441 represents the character <em>x</em>.
9442 This is the standard way to escape the magic characters.
9443 Any non-alphanumeric character
9444 (including all punctuation characters, even the non-magical)
9445 can be preceded by a '<code>%</code>' to represent itself in a pattern.
9446 </li>
9447
9448 <li><b><code>[<em>set</em>]</code>: </b>
9449 represents the class which is the union of all
9450 characters in <em>set</em>.
9451 A range of characters can be specified by
9452 separating the end characters of the range,
9453 in ascending order, with a '<code>-</code>'.
9454 All classes <code>%</code><em>x</em> described above can also be used as
9455 components in <em>set</em>.
9456 All other characters in <em>set</em> represent themselves.
9457 For example, <code>[%w_]</code> (or <code>[_%w]</code>)
9458 represents all alphanumeric characters plus the underscore,
9459 <code>[0-7]</code> represents the octal digits,
9460 and <code>[0-7%l%-]</code> represents the octal digits plus
9461 the lowercase letters plus the '<code>-</code>' character.
9462
9463
9464 <p>
9465 You can put a closing square bracket in a set
9466 by positioning it as the first character in the set.
9467 You can put a hyphen in a set
9468 by positioning it as the first or the last character in the set.
9469 (You can also use an escape for both cases.)
9470
9471
9472 <p>
9473 The interaction between ranges and classes is not defined.
9474 Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
9475 have no meaning.
9476 </li>
9477
9478 <li><b><code>[^<em>set</em>]</code>: </b>
9479 represents the complement of <em>set</em>,
9480 where <em>set</em> is interpreted as above.
9481 </li>
9482
9483 </ul><p>
9484 For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
9485 the corresponding uppercase letter represents the complement of the class.
9486 For instance, <code>%S</code> represents all non-space characters.
9487
9488
9489 <p>
9490 The definitions of letter, space, and other character groups
9491 depend on the current locale.
9492 In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
9493
9494
9495
9496
9497
9498 <h4>Pattern Item:</h4><p>
9499 A <em>pattern item</em> can be
9500
9501 <ul>
9502
9503 <li>
9504 a single character class,
9505 which matches any single character in the class;
9506 </li>
9507
9508 <li>
9509 a single character class followed by '<code>*</code>',
9510 which matches sequences of zero or more characters in the class.
9511 These repetition items will always match the longest possible sequence;
9512 </li>
9513
9514 <li>
9515 a single character class followed by '<code>+</code>',
9516 which matches sequences of one or more characters in the class.
9517 These repetition items will always match the longest possible sequence;
9518 </li>
9519
9520 <li>
9521 a single character class followed by '<code>-</code>',
9522 which also matches sequences of zero or more characters in the class.
9523 Unlike '<code>*</code>',
9524 these repetition items will always match the shortest possible sequence;
9525 </li>
9526
9527 <li>
9528 a single character class followed by '<code>?</code>',
9529 which matches zero or one occurrence of a character in the class.
9530 It always matches one occurrence if possible;
9531 </li>
9532
9533 <li>
9534 <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
9535 such item matches a substring equal to the <em>n</em>-th captured string
9536 (see below);
9537 </li>
9538
9539 <li>
9540 <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
9541 such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
9542 and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
9543 This means that, if one reads the string from left to right,
9544 counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
9545 the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
9546 For instance, the item <code>%b()</code> matches expressions with
9547 balanced parentheses.
9548 </li>
9549
9550 <li>
9551 <code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
9552 such item matches an empty string at any position such that
9553 the next character belongs to <em>set</em>
9554 and the previous character does not belong to <em>set</em>.
9555 The set <em>set</em> is interpreted as previously described.
9556 The beginning and the end of the subject are handled as if
9557 they were the character '<code>\0</code>'.
9558 </li>
9559
9560 </ul>
9561
9562
9563
9564
9565 <h4>Pattern:</h4><p>
9566 A <em>pattern</em> is a sequence of pattern items.
9567 A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
9568 beginning of the subject string.
9569 A '<code>$</code>' at the end of a pattern anchors the match at the
9570 end of the subject string.
9571 At other positions,
9572 '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
9573
9574
9575
9576
9577
9578 <h4>Captures:</h4><p>
9579 A pattern can contain sub-patterns enclosed in parentheses;
9580 they describe <em>captures</em>.
9581 When a match succeeds, the substrings of the subject string
9582 that match captures are stored (<em>captured</em>) for future use.
9583 Captures are numbered according to their left parentheses.
9584 For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
9585 the part of the string matching <code>"a*(.)%w(%s*)"</code> is
9586 stored as the first capture, and therefore has number&nbsp;1;
9587 the character matching "<code>.</code>" is captured with number&nbsp;2,
9588 and the part matching "<code>%s*</code>" has number&nbsp;3.
9589
9590
9591 <p>
9592 As a special case, the capture <code>()</code> captures
9593 the current string position (a number).
9594 For instance, if we apply the pattern <code>"()aa()"</code> on the
9595 string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
9596
9597
9598
9599
9600
9601 <h4>Multiple matches:</h4><p>
9602 The function <a href="#pdf-string.gsub"><code>string.gsub</code></a> and the iterator <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>
9603 match multiple occurrences of the given pattern in the subject.
9604 For these functions,
9605 a new match is considered valid only
9606 if it ends at least one byte after the end of the previous match.
9607 In other words, the pattern machine never accepts the
9608 empty string as a match immediately after another match.
9609 As an example,
9610 consider the results of the following code:
9611
9612 <pre>
9613 &gt; string.gsub("abc", "()a*()", print);
9614 --&gt; 1 2
9615 --&gt; 3 3
9616 --&gt; 4 4
9617 </pre><p>
9618 The second and third results come from Lua matching an empty
9619 string after '<code>b</code>' and another one after '<code>c</code>'.
9620 Lua does not match an empty string after '<code>a</code>',
9621 because it would end at the same position of the previous match.
9622
9623
9624
9625
9626
9627
9628
9629 <h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
9630
9631 <p>
9632 The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
9633 <a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
9634 is a format string,
9635 which describes the layout of the structure being created or read.
9636
9637
9638 <p>
9639 A format string is a sequence of conversion options.
9640 The conversion options are as follows:
9641
9642 <ul>
9643 <li><b><code>&lt;</code>: </b>sets little endian</li>
9644 <li><b><code>&gt;</code>: </b>sets big endian</li>
9645 <li><b><code>=</code>: </b>sets native endian</li>
9646 <li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
9647 (default is native alignment)</li>
9648 <li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
9649 <li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
9650 <li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
9651 <li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
9652 <li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
9653 <li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
9654 <li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
9655 <li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
9656 <li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
9657 <li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
9658 (default is native size)</li>
9659 <li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
9660 (default is native size)</li>
9661 <li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
9662 <li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
9663 <li><b><code>n</code>: </b>a <code>lua_Number</code></li>
9664 <li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
9665 <li><b><code>z</code>: </b>a zero-terminated string</li>
9666 <li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
9667 coded as an unsigned integer with <code>n</code> bytes
9668 (default is a <code>size_t</code>)</li>
9669 <li><b><code>x</code>: </b>one byte of padding</li>
9670 <li><b><code>X<em>op</em></code>: </b>an empty item that aligns
9671 according to option <code>op</code>
9672 (which is otherwise ignored)</li>
9673 <li><b>'<code> </code>': </b>(space) ignored</li>
9674 </ul><p>
9675 (A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
9676 Except for padding, spaces, and configurations
9677 (options "<code>xX &lt;=&gt;!</code>"),
9678 each option corresponds to an argument in <a href="#pdf-string.pack"><code>string.pack</code></a>
9679 or a result in <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9680
9681
9682 <p>
9683 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>",
9684 <code>n</code> can be any integer between 1 and 16.
9685 All integral options check overflows;
9686 <a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
9687 <a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
9688 For the unsigned options,
9689 Lua integers are treated as unsigned values too.
9690
9691
9692 <p>
9693 Any format string starts as if prefixed by "<code>!1=</code>",
9694 that is,
9695 with maximum alignment of 1 (no alignment)
9696 and native endianness.
9697
9698
9699 <p>
9700 Native endianness assumes that the whole system is
9701 either big or little endian.
9702 The packing functions will not emulate correctly the behavior
9703 of mixed-endian formats.
9704
9705
9706 <p>
9707 Alignment works as follows:
9708 For each option,
9709 the format gets extra padding until the data starts
9710 at an offset that is a multiple of the minimum between the
9711 option size and the maximum alignment;
9712 this minimum must be a power of 2.
9713 Options "<code>c</code>" and "<code>z</code>" are not aligned;
9714 option "<code>s</code>" follows the alignment of its starting integer.
9715
9716
9717 <p>
9718 All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
9719 and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>.
9720
9721
9722
9723
9724
9725
9726
9727 <h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
9728
9729 <p>
9730 This library provides basic support for UTF-8 encoding.
9731 It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
9732 This library does not provide any support for Unicode other
9733 than the handling of the encoding.
9734 Any operation that needs the meaning of a character,
9735 such as character classification, is outside its scope.
9736
9737
9738 <p>
9739 Unless stated otherwise,
9740 all functions that expect a byte position as a parameter
9741 assume that the given position is either the start of a byte sequence
9742 or one plus the length of the subject string.
9743 As in the string library,
9744 negative indices count from the end of the string.
9745
9746
9747 <p>
9748 Functions that create byte sequences
9749 accept all values up to <code>0x7FFFFFFF</code>,
9750 as defined in the original UTF-8 specification;
9751 that implies byte sequences of up to six bytes.
9752
9753
9754 <p>
9755 Functions that interpret byte sequences only accept
9756 valid sequences (well formed and not overlong).
9757 By default, they only accept byte sequences
9758 that result in valid Unicode code points,
9759 rejecting values greater than <code>10FFFF</code> and surrogates.
9760 A boolean argument <code>lax</code>, when available,
9761 lifts these checks,
9762 so that all values up to <code>0x7FFFFFFF</code> are accepted.
9763 (Not well formed and overlong sequences are still rejected.)
9764
9765
9766 <p>
9767 <hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
9768
9769
9770 <p>
9771 Receives zero or more integers,
9772 converts each one to its corresponding UTF-8 byte sequence
9773 and returns a string with the concatenation of all these sequences.
9774
9775
9776
9777
9778 <p>
9779 <hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
9780
9781
9782 <p>
9783 The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xFD][\x80-\xBF]*</code>"
9784 (see <a href="#6.4.1">&sect;6.4.1</a>),
9785 which matches exactly one UTF-8 byte sequence,
9786 assuming that the subject is a valid UTF-8 string.
9787
9788
9789
9790
9791 <p>
9792 <hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s [, lax])</code></a></h3>
9793
9794
9795 <p>
9796 Returns values so that the construction
9797
9798 <pre>
9799 for p, c in utf8.codes(s) do <em>body</em> end
9800 </pre><p>
9801 will iterate over all UTF-8 characters in string <code>s</code>,
9802 with <code>p</code> being the position (in bytes) and <code>c</code> the code point
9803 of each character.
9804 It raises an error if it meets any invalid byte sequence.
9805
9806
9807
9808
9809 <p>
9810 <hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j [, lax]]])</code></a></h3>
9811
9812
9813 <p>
9814 Returns the code points (as integers) from all characters in <code>s</code>
9815 that start between byte position <code>i</code> and <code>j</code> (both included).
9816 The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
9817 It raises an error if it meets any invalid byte sequence.
9818
9819
9820
9821
9822 <p>
9823 <hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j [, lax]]])</code></a></h3>
9824
9825
9826 <p>
9827 Returns the number of UTF-8 characters in string <code>s</code>
9828 that start between positions <code>i</code> and <code>j</code> (both inclusive).
9829 The default for <code>i</code> is 1 and for <code>j</code> is -1.
9830 If it finds any invalid byte sequence,
9831 returns <b>fail</b> plus the position of the first invalid byte.
9832
9833
9834
9835
9836 <p>
9837 <hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
9838
9839
9840 <p>
9841 Returns the position (in bytes) where the encoding of the
9842 <code>n</code>-th character of <code>s</code>
9843 (counting from position <code>i</code>) starts.
9844 A negative <code>n</code> gets characters before position <code>i</code>.
9845 The default for <code>i</code> is 1 when <code>n</code> is non-negative
9846 and <code>#s + 1</code> otherwise,
9847 so that <code>utf8.offset(s, -n)</code> gets the offset of the
9848 <code>n</code>-th character from the end of the string.
9849 If the specified character is neither in the subject
9850 nor right after its end,
9851 the function returns <b>fail</b>.
9852
9853
9854 <p>
9855 As a special case,
9856 when <code>n</code> is 0 the function returns the start of the encoding
9857 of the character that contains the <code>i</code>-th byte of <code>s</code>.
9858
9859
9860 <p>
9861 This function assumes that <code>s</code> is a valid UTF-8 string.
9862
9863
9864
9865
9866
9867
9868
9869 <h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
9870
9871 <p>
9872 This library provides generic functions for table manipulation.
9873 It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
9874
9875
9876 <p>
9877 Remember that, whenever an operation needs the length of a table,
9878 all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>).
9879 All functions ignore non-numeric keys
9880 in the tables given as arguments.
9881
9882
9883 <p>
9884 <hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
9885
9886
9887 <p>
9888 Given a list where all elements are strings or numbers,
9889 returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
9890 The default value for <code>sep</code> is the empty string,
9891 the default for <code>i</code> is 1,
9892 and the default for <code>j</code> is <code>#list</code>.
9893 If <code>i</code> is greater than <code>j</code>, returns the empty string.
9894
9895
9896
9897
9898 <p>
9899 <hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
9900
9901
9902 <p>
9903 Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
9904 shifting up the elements
9905 <code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
9906 The default value for <code>pos</code> is <code>#list+1</code>,
9907 so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
9908 of the list <code>t</code>.
9909
9910
9911
9912
9913 <p>
9914 <hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
9915
9916
9917 <p>
9918 Moves elements from the table <code>a1</code> to the table <code>a2</code>,
9919 performing the equivalent to the following
9920 multiple assignment:
9921 <code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
9922 The default for <code>a2</code> is <code>a1</code>.
9923 The destination range can overlap with the source range.
9924 The number of elements to be moved must fit in a Lua integer.
9925
9926
9927 <p>
9928 Returns the destination table <code>a2</code>.
9929
9930
9931
9932
9933 <p>
9934 <hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
9935
9936
9937 <p>
9938 Returns a new table with all arguments stored into keys 1, 2, etc.
9939 and with a field "<code>n</code>" with the total number of arguments.
9940 Note that the resulting table may not be a sequence,
9941 if some arguments are <b>nil</b>.
9942
9943
9944
9945
9946 <p>
9947 <hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
9948
9949
9950 <p>
9951 Removes from <code>list</code> the element at position <code>pos</code>,
9952 returning the value of the removed element.
9953 When <code>pos</code> is an integer between 1 and <code>#list</code>,
9954 it shifts down the elements
9955 <code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
9956 and erases element <code>list[#list]</code>;
9957 The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
9958 or <code>#list + 1</code>.
9959
9960
9961 <p>
9962 The default value for <code>pos</code> is <code>#list</code>,
9963 so that a call <code>table.remove(l)</code> removes the last element
9964 of the list <code>l</code>.
9965
9966
9967
9968
9969 <p>
9970 <hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
9971
9972
9973 <p>
9974 Sorts the list elements in a given order, <em>in-place</em>,
9975 from <code>list[1]</code> to <code>list[#list]</code>.
9976 If <code>comp</code> is given,
9977 then it must be a function that receives two list elements
9978 and returns true when the first element must come
9979 before the second in the final order,
9980 so that, after the sort,
9981 <code>i &lt;= j</code> implies <code>not comp(list[j],list[i])</code>.
9982 If <code>comp</code> is not given,
9983 then the standard Lua operator <code>&lt;</code> is used instead.
9984
9985
9986 <p>
9987 The <code>comp</code> function must define a consistent order;
9988 more formally, the function must define a strict weak order.
9989 (A weak order is similar to a total order,
9990 but it can equate different elements for comparison purposes.)
9991
9992
9993 <p>
9994 The sort algorithm is not stable:
9995 Different elements considered equal by the given order
9996 may have their relative positions changed by the sort.
9997
9998
9999
10000
10001 <p>
10002 <hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
10003
10004
10005 <p>
10006 Returns the elements from the given list.
10007 This function is equivalent to
10008
10009 <pre>
10010 return list[i], list[i+1], &middot;&middot;&middot;, list[j]
10011 </pre><p>
10012 By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
10013
10014
10015
10016
10017
10018
10019
10020 <h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
10021
10022 <p>
10023 This library provides basic mathematical functions.
10024 It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
10025 Functions with the annotation "<code>integer/float</code>" give
10026 integer results for integer arguments
10027 and float results for non-integer arguments.
10028 The rounding functions
10029 <a href="#pdf-math.ceil"><code>math.ceil</code></a>, <a href="#pdf-math.floor"><code>math.floor</code></a>, and <a href="#pdf-math.modf"><code>math.modf</code></a>
10030 return an integer when the result fits in the range of an integer,
10031 or a float otherwise.
10032
10033
10034 <p>
10035 <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
10036
10037
10038 <p>
10039 Returns the maximum value between <code>x</code> and <code>-x</code>. (integer/float)
10040
10041
10042
10043
10044 <p>
10045 <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
10046
10047
10048 <p>
10049 Returns the arc cosine of <code>x</code> (in radians).
10050
10051
10052
10053
10054 <p>
10055 <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
10056
10057
10058 <p>
10059 Returns the arc sine of <code>x</code> (in radians).
10060
10061
10062
10063
10064 <p>
10065 <hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
10066
10067
10068 <p>
10069
10070 Returns the arc tangent of <code>y/x</code> (in radians),
10071 but uses the signs of both arguments to find the
10072 quadrant of the result.
10073 It also handles correctly the case of <code>x</code> being zero.
10074
10075
10076 <p>
10077 The default value for <code>x</code> is 1,
10078 so that the call <code>math.atan(y)</code>
10079 returns the arc tangent of <code>y</code>.
10080
10081
10082
10083
10084 <p>
10085 <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
10086
10087
10088 <p>
10089 Returns the smallest integral value greater than or equal to <code>x</code>.
10090
10091
10092
10093
10094 <p>
10095 <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
10096
10097
10098 <p>
10099 Returns the cosine of <code>x</code> (assumed to be in radians).
10100
10101
10102
10103
10104 <p>
10105 <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
10106
10107
10108 <p>
10109 Converts the angle <code>x</code> from radians to degrees.
10110
10111
10112
10113
10114 <p>
10115 <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
10116
10117
10118 <p>
10119 Returns the value <em>e<sup>x</sup></em>
10120 (where <code>e</code> is the base of natural logarithms).
10121
10122
10123
10124
10125 <p>
10126 <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
10127
10128
10129 <p>
10130 Returns the largest integral value less than or equal to <code>x</code>.
10131
10132
10133
10134
10135 <p>
10136 <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
10137
10138
10139 <p>
10140 Returns the remainder of the division of <code>x</code> by <code>y</code>
10141 that rounds the quotient towards zero. (integer/float)
10142
10143
10144
10145
10146 <p>
10147 <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
10148
10149
10150 <p>
10151 The float value <code>HUGE_VAL</code>,
10152 a value greater than any other numeric value.
10153
10154
10155
10156
10157 <p>
10158 <hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
10159
10160
10161 <p>
10162 Returns the logarithm of <code>x</code> in the given base.
10163 The default for <code>base</code> is <em>e</em>
10164 (so that the function returns the natural logarithm of <code>x</code>).
10165
10166
10167
10168
10169 <p>
10170 <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
10171
10172
10173 <p>
10174 Returns the argument with the maximum value,
10175 according to the Lua operator <code>&lt;</code>.
10176
10177
10178
10179
10180 <p>
10181 <hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
10182 An integer with the maximum value for an integer.
10183
10184
10185
10186
10187 <p>
10188 <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
10189
10190
10191 <p>
10192 Returns the argument with the minimum value,
10193 according to the Lua operator <code>&lt;</code>.
10194
10195
10196
10197
10198 <p>
10199 <hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
10200 An integer with the minimum value for an integer.
10201
10202
10203
10204
10205 <p>
10206 <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
10207
10208
10209 <p>
10210 Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
10211 Its second result is always a float.
10212
10213
10214
10215
10216 <p>
10217 <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
10218
10219
10220 <p>
10221 The value of <em>&pi;</em>.
10222
10223
10224
10225
10226 <p>
10227 <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
10228
10229
10230 <p>
10231 Converts the angle <code>x</code> from degrees to radians.
10232
10233
10234
10235
10236 <p>
10237 <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
10238
10239
10240 <p>
10241 When called without arguments,
10242 returns a pseudo-random float with uniform distribution
10243 in the range <em>[0,1)</em>.
10244 When called with two integers <code>m</code> and <code>n</code>,
10245 <code>math.random</code> returns a pseudo-random integer
10246 with uniform distribution in the range <em>[m, n]</em>.
10247 The call <code>math.random(n)</code>, for a positive <code>n</code>,
10248 is equivalent to <code>math.random(1,n)</code>.
10249 The call <code>math.random(0)</code> produces an integer with
10250 all bits (pseudo)random.
10251
10252
10253 <p>
10254 This function uses the <code>xoshiro256**</code> algorithm to produce
10255 pseudo-random 64-bit integers,
10256 which are the results of calls with argument&nbsp;0.
10257 Other results (ranges and floats)
10258 are unbiased extracted from these integers.
10259
10260
10261 <p>
10262 Lua initializes its pseudo-random generator with the equivalent of
10263 a call to <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with no arguments,
10264 so that <code>math.random</code> should generate
10265 different sequences of results each time the program runs.
10266
10267
10268
10269
10270 <p>
10271 <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed ([x [, y]])</code></a></h3>
10272
10273
10274 <p>
10275 When called with at least one argument,
10276 the integer parameters <code>x</code> and <code>y</code> are
10277 joined into a 128-bit <em>seed</em> that
10278 is used to reinitialize the pseudo-random generator;
10279 equal seeds produce equal sequences of numbers.
10280 The default for <code>y</code> is zero.
10281
10282
10283 <p>
10284 When called with no arguments,
10285 Lua generates a seed with
10286 a weak attempt for randomness.
10287
10288
10289 <p>
10290 This function returns the two seed components
10291 that were effectively used,
10292 so that setting them again repeats the sequence.
10293
10294
10295 <p>
10296 To ensure a required level of randomness to the initial state
10297 (or contrarily, to have a deterministic sequence,
10298 for instance when debugging a program),
10299 you should call <a href="#pdf-math.randomseed"><code>math.randomseed</code></a> with explicit arguments.
10300
10301
10302
10303
10304 <p>
10305 <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
10306
10307
10308 <p>
10309 Returns the sine of <code>x</code> (assumed to be in radians).
10310
10311
10312
10313
10314 <p>
10315 <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
10316
10317
10318 <p>
10319 Returns the square root of <code>x</code>.
10320 (You can also use the expression <code>x^0.5</code> to compute this value.)
10321
10322
10323
10324
10325 <p>
10326 <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
10327
10328
10329 <p>
10330 Returns the tangent of <code>x</code> (assumed to be in radians).
10331
10332
10333
10334
10335 <p>
10336 <hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
10337
10338
10339 <p>
10340 If the value <code>x</code> is convertible to an integer,
10341 returns that integer.
10342 Otherwise, returns <b>fail</b>.
10343
10344
10345
10346
10347 <p>
10348 <hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
10349
10350
10351 <p>
10352 Returns "<code>integer</code>" if <code>x</code> is an integer,
10353 "<code>float</code>" if it is a float,
10354 or <b>fail</b> if <code>x</code> is not a number.
10355
10356
10357
10358
10359 <p>
10360 <hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
10361
10362
10363 <p>
10364 Returns a boolean,
10365 true if and only if integer <code>m</code> is below integer <code>n</code> when
10366 they are compared as unsigned integers.
10367
10368
10369
10370
10371
10372
10373
10374 <h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
10375
10376 <p>
10377 The I/O library provides two different styles for file manipulation.
10378 The first one uses implicit file handles;
10379 that is, there are operations to set a default input file and a
10380 default output file,
10381 and all input/output operations are done over these default files.
10382 The second style uses explicit file handles.
10383
10384
10385 <p>
10386 When using implicit file handles,
10387 all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
10388 When using explicit file handles,
10389 the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
10390 and then all operations are supplied as methods of the file handle.
10391
10392
10393 <p>
10394 The metatable for file handles provides metamethods
10395 for <code>__gc</code> and <code>__close</code> that try
10396 to close the file when called.
10397
10398
10399 <p>
10400 The table <code>io</code> also provides
10401 three predefined file handles with their usual meanings from C:
10402 <a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>.
10403 The I/O library never closes these files.
10404
10405
10406 <p>
10407 Unless otherwise stated,
10408 all I/O functions return <b>fail</b> on failure,
10409 plus an error message as a second result and
10410 a system-dependent error code as a third result,
10411 and some non-false value on success.
10412 On non-POSIX systems,
10413 the computation of the error message and error code
10414 in case of errors
10415 may be not thread safe,
10416 because they rely on the global C variable <code>errno</code>.
10417
10418
10419 <p>
10420 <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
10421
10422
10423 <p>
10424 Equivalent to <code>file:close()</code>.
10425 Without a <code>file</code>, closes the default output file.
10426
10427
10428
10429
10430 <p>
10431 <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
10432
10433
10434 <p>
10435 Equivalent to <code>io.output():flush()</code>.
10436
10437
10438
10439
10440 <p>
10441 <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
10442
10443
10444 <p>
10445 When called with a file name, it opens the named file (in text mode),
10446 and sets its handle as the default input file.
10447 When called with a file handle,
10448 it simply sets this file handle as the default input file.
10449 When called without arguments,
10450 it returns the current default input file.
10451
10452
10453 <p>
10454 In case of errors this function raises the error,
10455 instead of returning an error code.
10456
10457
10458
10459
10460 <p>
10461 <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3>
10462
10463
10464 <p>
10465 Opens the given file name in read mode
10466 and returns an iterator function that
10467 works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
10468 When the iterator function fails to read any value,
10469 it automatically closes the file.
10470 Besides the iterator function,
10471 <code>io.lines</code> returns three other values:
10472 two <b>nil</b> values as placeholders,
10473 plus the created file handle.
10474 Therefore, when used in a generic <b>for</b> loop,
10475 the file is closed also if the loop is interrupted by an
10476 error or a <b>break</b>.
10477
10478
10479 <p>
10480 The call <code>io.lines()</code> (with no file name) is equivalent
10481 to <code>io.input():lines("l")</code>;
10482 that is, it iterates over the lines of the default input file.
10483 In this case, the iterator does not close the file when the loop ends.
10484
10485
10486 <p>
10487 In case of errors opening the file,
10488 this function raises the error,
10489 instead of returning an error code.
10490
10491
10492
10493
10494 <p>
10495 <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
10496
10497
10498 <p>
10499 This function opens a file,
10500 in the mode specified in the string <code>mode</code>.
10501 In case of success,
10502 it returns a new file handle.
10503
10504
10505 <p>
10506 The <code>mode</code> string can be any of the following:
10507
10508 <ul>
10509 <li><b>"<code>r</code>": </b> read mode (the default);</li>
10510 <li><b>"<code>w</code>": </b> write mode;</li>
10511 <li><b>"<code>a</code>": </b> append mode;</li>
10512 <li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
10513 <li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
10514 <li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
10515 writing is only allowed at the end of file.</li>
10516 </ul><p>
10517 The <code>mode</code> string can also have a '<code>b</code>' at the end,
10518 which is needed in some systems to open the file in binary mode.
10519
10520
10521
10522
10523 <p>
10524 <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
10525
10526
10527 <p>
10528 Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
10529
10530
10531
10532
10533 <p>
10534 <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
10535
10536
10537 <p>
10538 This function is system dependent and is not available
10539 on all platforms.
10540
10541
10542 <p>
10543 Starts the program <code>prog</code> in a separated process and returns
10544 a file handle that you can use to read data from this program
10545 (if <code>mode</code> is <code>"r"</code>, the default)
10546 or to write data to this program
10547 (if <code>mode</code> is <code>"w"</code>).
10548
10549
10550
10551
10552 <p>
10553 <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
10554
10555
10556 <p>
10557 Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
10558
10559
10560
10561
10562 <p>
10563 <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
10564
10565
10566 <p>
10567 In case of success,
10568 returns a handle for a temporary file.
10569 This file is opened in update mode
10570 and it is automatically removed when the program ends.
10571
10572
10573
10574
10575 <p>
10576 <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
10577
10578
10579 <p>
10580 Checks whether <code>obj</code> is a valid file handle.
10581 Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
10582 <code>"closed file"</code> if <code>obj</code> is a closed file handle,
10583 or <b>fail</b> if <code>obj</code> is not a file handle.
10584
10585
10586
10587
10588 <p>
10589 <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
10590
10591
10592 <p>
10593 Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
10594
10595
10596
10597
10598 <p>
10599 <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
10600
10601
10602 <p>
10603 Closes <code>file</code>.
10604 Note that files are automatically closed when
10605 their handles are garbage collected,
10606 but that takes an unpredictable amount of time to happen.
10607
10608
10609 <p>
10610 When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
10611 <a href="#pdf-file:close"><code>file:close</code></a> returns the same values
10612 returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
10613
10614
10615
10616
10617 <p>
10618 <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
10619
10620
10621 <p>
10622 Saves any written data to <code>file</code>.
10623
10624
10625
10626
10627 <p>
10628 <hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
10629
10630
10631 <p>
10632 Returns an iterator function that,
10633 each time it is called,
10634 reads the file according to the given formats.
10635 When no format is given,
10636 uses "<code>l</code>" as a default.
10637 As an example, the construction
10638
10639 <pre>
10640 for c in file:lines(1) do <em>body</em> end
10641 </pre><p>
10642 will iterate over all characters of the file,
10643 starting at the current position.
10644 Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
10645 when the loop ends.
10646
10647
10648
10649
10650 <p>
10651 <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
10652
10653
10654 <p>
10655 Reads the file <code>file</code>,
10656 according to the given formats, which specify what to read.
10657 For each format,
10658 the function returns a string or a number with the characters read,
10659 or <b>fail</b> if it cannot read data with the specified format.
10660 (In this latter case,
10661 the function does not read subsequent formats.)
10662 When called without arguments,
10663 it uses a default format that reads the next line
10664 (see below).
10665
10666
10667 <p>
10668 The available formats are
10669
10670 <ul>
10671
10672 <li><b>"<code>n</code>": </b>
10673 reads a numeral and returns it as a float or an integer,
10674 following the lexical conventions of Lua.
10675 (The numeral may have leading whitespaces and a sign.)
10676 This format always reads the longest input sequence that
10677 is a valid prefix for a numeral;
10678 if that prefix does not form a valid numeral
10679 (e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>")
10680 or it is too long (more than 200 characters),
10681 it is discarded and the format returns <b>fail</b>.
10682 </li>
10683
10684 <li><b>"<code>a</code>": </b>
10685 reads the whole file, starting at the current position.
10686 On end of file, it returns the empty string;
10687 this format never fails.
10688 </li>
10689
10690 <li><b>"<code>l</code>": </b>
10691 reads the next line skipping the end of line,
10692 returning <b>fail</b> on end of file.
10693 This is the default format.
10694 </li>
10695
10696 <li><b>"<code>L</code>": </b>
10697 reads the next line keeping the end-of-line character (if present),
10698 returning <b>fail</b> on end of file.
10699 </li>
10700
10701 <li><b><em>number</em>: </b>
10702 reads a string with up to this number of bytes,
10703 returning <b>fail</b> on end of file.
10704 If <code>number</code> is zero,
10705 it reads nothing and returns an empty string,
10706 or <b>fail</b> on end of file.
10707 </li>
10708
10709 </ul><p>
10710 The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
10711
10712
10713
10714
10715 <p>
10716 <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
10717
10718
10719 <p>
10720 Sets and gets the file position,
10721 measured from the beginning of the file,
10722 to the position given by <code>offset</code> plus a base
10723 specified by the string <code>whence</code>, as follows:
10724
10725 <ul>
10726 <li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
10727 <li><b>"<code>cur</code>": </b> base is current position;</li>
10728 <li><b>"<code>end</code>": </b> base is end of file;</li>
10729 </ul><p>
10730 In case of success, <code>seek</code> returns the final file position,
10731 measured in bytes from the beginning of the file.
10732 If <code>seek</code> fails, it returns <b>fail</b>,
10733 plus a string describing the error.
10734
10735
10736 <p>
10737 The default value for <code>whence</code> is <code>"cur"</code>,
10738 and for <code>offset</code> is 0.
10739 Therefore, the call <code>file:seek()</code> returns the current
10740 file position, without changing it;
10741 the call <code>file:seek("set")</code> sets the position to the
10742 beginning of the file (and returns 0);
10743 and the call <code>file:seek("end")</code> sets the position to the
10744 end of the file, and returns its size.
10745
10746
10747
10748
10749 <p>
10750 <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
10751
10752
10753 <p>
10754 Sets the buffering mode for a file.
10755 There are three available modes:
10756
10757 <ul>
10758 <li><b>"<code>no</code>": </b> no buffering.</li>
10759 <li><b>"<code>full</code>": </b> full buffering.</li>
10760 <li><b>"<code>line</code>": </b> line buffering.</li>
10761 </ul>
10762
10763 <p>
10764 For the last two cases,
10765 <code>size</code> is a hint for the size of the buffer, in bytes.
10766 The default is an appropriate size.
10767
10768
10769 <p>
10770 The specific behavior of each mode is non portable;
10771 check the underlying ISO&nbsp;C function <code>setvbuf</code> in your platform for
10772 more details.
10773
10774
10775
10776
10777 <p>
10778 <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
10779
10780
10781 <p>
10782 Writes the value of each of its arguments to <code>file</code>.
10783 The arguments must be strings or numbers.
10784
10785
10786 <p>
10787 In case of success, this function returns <code>file</code>.
10788
10789
10790
10791
10792
10793
10794
10795 <h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
10796
10797 <p>
10798 This library is implemented through table <a name="pdf-os"><code>os</code></a>.
10799
10800
10801 <p>
10802 <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
10803
10804
10805 <p>
10806 Returns an approximation of the amount in seconds of CPU time
10807 used by the program,
10808 as returned by the underlying ISO&nbsp;C function <code>clock</code>.
10809
10810
10811
10812
10813 <p>
10814 <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
10815
10816
10817 <p>
10818 Returns a string or a table containing date and time,
10819 formatted according to the given string <code>format</code>.
10820
10821
10822 <p>
10823 If the <code>time</code> argument is present,
10824 this is the time to be formatted
10825 (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
10826 Otherwise, <code>date</code> formats the current time.
10827
10828
10829 <p>
10830 If <code>format</code> starts with '<code>!</code>',
10831 then the date is formatted in Coordinated Universal Time.
10832 After this optional character,
10833 if <code>format</code> is the string "<code>*t</code>",
10834 then <code>date</code> returns a table with the following fields:
10835 <code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
10836 <code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59),
10837 <code>sec</code> (0&ndash;61, due to leap seconds),
10838 <code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1),
10839 <code>yday</code> (day of the year, 1&ndash;366),
10840 and <code>isdst</code> (daylight saving flag, a boolean).
10841 This last field may be absent
10842 if the information is not available.
10843
10844
10845 <p>
10846 If <code>format</code> is not "<code>*t</code>",
10847 then <code>date</code> returns the date as a string,
10848 formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
10849
10850
10851 <p>
10852 If <code>format</code> is absent, it defaults to "<code>%c</code>",
10853 which gives a human-readable date and time representation
10854 using the current locale.
10855
10856
10857 <p>
10858 On non-POSIX systems,
10859 this function may be not thread safe
10860 because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
10861
10862
10863
10864
10865 <p>
10866 <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
10867
10868
10869 <p>
10870 Returns the difference, in seconds,
10871 from time <code>t1</code> to time <code>t2</code>
10872 (where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
10873 In POSIX, Windows, and some other systems,
10874 this value is exactly <code>t2</code><em>-</em><code>t1</code>.
10875
10876
10877
10878
10879 <p>
10880 <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
10881
10882
10883 <p>
10884 This function is equivalent to the ISO&nbsp;C function <code>system</code>.
10885 It passes <code>command</code> to be executed by an operating system shell.
10886 Its first result is <b>true</b>
10887 if the command terminated successfully,
10888 or <b>fail</b> otherwise.
10889 After this first result
10890 the function returns a string plus a number,
10891 as follows:
10892
10893 <ul>
10894
10895 <li><b>"<code>exit</code>": </b>
10896 the command terminated normally;
10897 the following number is the exit status of the command.
10898 </li>
10899
10900 <li><b>"<code>signal</code>": </b>
10901 the command was terminated by a signal;
10902 the following number is the signal that terminated the command.
10903 </li>
10904
10905 </ul>
10906
10907 <p>
10908 When called without a <code>command</code>,
10909 <code>os.execute</code> returns a boolean that is true if a shell is available.
10910
10911
10912
10913
10914 <p>
10915 <hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
10916
10917
10918 <p>
10919 Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
10920 If <code>code</code> is <b>true</b>,
10921 the returned status is <code>EXIT_SUCCESS</code>;
10922 if <code>code</code> is <b>false</b>,
10923 the returned status is <code>EXIT_FAILURE</code>;
10924 if <code>code</code> is a number,
10925 the returned status is this number.
10926 The default value for <code>code</code> is <b>true</b>.
10927
10928
10929 <p>
10930 If the optional second argument <code>close</code> is true,
10931 closes the Lua state before exiting.
10932
10933
10934
10935
10936 <p>
10937 <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
10938
10939
10940 <p>
10941 Returns the value of the process environment variable <code>varname</code>
10942 or <b>fail</b> if the variable is not defined.
10943
10944
10945
10946
10947 <p>
10948 <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
10949
10950
10951 <p>
10952 Deletes the file (or empty directory, on POSIX systems)
10953 with the given name.
10954 If this function fails, it returns <b>fail</b>
10955 plus a string describing the error and the error code.
10956 Otherwise, it returns true.
10957
10958
10959
10960
10961 <p>
10962 <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
10963
10964
10965 <p>
10966 Renames the file or directory named <code>oldname</code> to <code>newname</code>.
10967 If this function fails, it returns <b>fail</b>,
10968 plus a string describing the error and the error code.
10969 Otherwise, it returns true.
10970
10971
10972
10973
10974 <p>
10975 <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
10976
10977
10978 <p>
10979 Sets the current locale of the program.
10980 <code>locale</code> is a system-dependent string specifying a locale;
10981 <code>category</code> is an optional string describing which category to change:
10982 <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
10983 <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
10984 the default category is <code>"all"</code>.
10985 The function returns the name of the new locale,
10986 or <b>fail</b> if the request cannot be honored.
10987
10988
10989 <p>
10990 If <code>locale</code> is the empty string,
10991 the current locale is set to an implementation-defined native locale.
10992 If <code>locale</code> is the string "<code>C</code>",
10993 the current locale is set to the standard C locale.
10994
10995
10996 <p>
10997 When called with <b>nil</b> as the first argument,
10998 this function only returns the name of the current locale
10999 for the given category.
11000
11001
11002 <p>
11003 This function may be not thread safe
11004 because of its reliance on C&nbsp;function <code>setlocale</code>.
11005
11006
11007
11008
11009 <p>
11010 <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
11011
11012
11013 <p>
11014 Returns the current time when called without arguments,
11015 or a time representing the local date and time specified by the given table.
11016 This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
11017 and may have fields
11018 <code>hour</code> (default is 12),
11019 <code>min</code> (default is 0),
11020 <code>sec</code> (default is 0),
11021 and <code>isdst</code> (default is <b>nil</b>).
11022 Other fields are ignored.
11023 For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
11024
11025
11026 <p>
11027 When the function is called,
11028 the values in these fields do not need to be inside their valid ranges.
11029 For instance, if <code>sec</code> is -10,
11030 it means 10 seconds before the time specified by the other fields;
11031 if <code>hour</code> is 1000,
11032 it means 1000 hours after the time specified by the other fields.
11033
11034
11035 <p>
11036 The returned value is a number, whose meaning depends on your system.
11037 In POSIX, Windows, and some other systems,
11038 this number counts the number
11039 of seconds since some given start time (the "epoch").
11040 In other systems, the meaning is not specified,
11041 and the number returned by <code>time</code> can be used only as an argument to
11042 <a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
11043
11044
11045 <p>
11046 When called with a table,
11047 <code>os.time</code> also normalizes all the fields
11048 documented in the <a href="#pdf-os.date"><code>os.date</code></a> function,
11049 so that they represent the same time as before the call
11050 but with values inside their valid ranges.
11051
11052
11053
11054
11055 <p>
11056 <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
11057
11058
11059 <p>
11060 Returns a string with a file name that can
11061 be used for a temporary file.
11062 The file must be explicitly opened before its use
11063 and explicitly removed when no longer needed.
11064
11065
11066 <p>
11067 In POSIX systems,
11068 this function also creates a file with that name,
11069 to avoid security risks.
11070 (Someone else might create the file with wrong permissions
11071 in the time between getting the name and creating the file.)
11072 You still have to open the file to use it
11073 and to remove it (even if you do not use it).
11074
11075
11076 <p>
11077 When possible,
11078 you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
11079 which automatically removes the file when the program ends.
11080
11081
11082
11083
11084
11085
11086
11087 <h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
11088
11089 <p>
11090 This library provides
11091 the functionality of the debug interface (<a href="#4.7">&sect;4.7</a>) to Lua programs.
11092 You should exert care when using this library.
11093 Several of its functions
11094 violate basic assumptions about Lua code
11095 (e.g., that variables local to a function
11096 cannot be accessed from outside;
11097 that userdata metatables cannot be changed by Lua code;
11098 that Lua programs do not crash)
11099 and therefore can compromise otherwise secure code.
11100 Moreover, some functions in this library may be slow.
11101
11102
11103 <p>
11104 All functions in this library are provided
11105 inside the <a name="pdf-debug"><code>debug</code></a> table.
11106 All functions that operate over a thread
11107 have an optional first argument which is the
11108 thread to operate over.
11109 The default is always the current thread.
11110
11111
11112 <p>
11113 <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
11114
11115
11116 <p>
11117 Enters an interactive mode with the user,
11118 running each string that the user enters.
11119 Using simple commands and other debug facilities,
11120 the user can inspect global and local variables,
11121 change their values, evaluate expressions, and so on.
11122 A line containing only the word <code>cont</code> finishes this function,
11123 so that the caller continues its execution.
11124
11125
11126 <p>
11127 Note that commands for <code>debug.debug</code> are not lexically nested
11128 within any function and so have no direct access to local variables.
11129
11130
11131
11132
11133 <p>
11134 <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
11135
11136
11137 <p>
11138 Returns the current hook settings of the thread, as three values:
11139 the current hook function, the current hook mask,
11140 and the current hook count,
11141 as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function.
11142
11143
11144 <p>
11145 Returns <b>fail</b> if there is no active hook.
11146
11147
11148
11149
11150 <p>
11151 <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
11152
11153
11154 <p>
11155 Returns a table with information about a function.
11156 You can give the function directly
11157 or you can give a number as the value of <code>f</code>,
11158 which means the function running at level <code>f</code> of the call stack
11159 of the given thread:
11160 level&nbsp;0 is the current function (<code>getinfo</code> itself);
11161 level&nbsp;1 is the function that called <code>getinfo</code>
11162 (except for tail calls, which do not count in the stack);
11163 and so on.
11164 If <code>f</code> is a number greater than the number of active functions,
11165 then <code>getinfo</code> returns <b>fail</b>.
11166
11167
11168 <p>
11169 The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
11170 with the string <code>what</code> describing which fields to fill in.
11171 The default for <code>what</code> is to get all information available,
11172 except the table of valid lines.
11173 If present,
11174 the option '<code>f</code>'
11175 adds a field named <code>func</code> with the function itself.
11176 If present,
11177 the option '<code>L</code>'
11178 adds a field named <code>activelines</code> with the table of
11179 valid lines.
11180
11181
11182 <p>
11183 For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
11184 a name for the current function,
11185 if a reasonable name can be found,
11186 and the expression <code>debug.getinfo(print)</code>
11187 returns a table with all available information
11188 about the <a href="#pdf-print"><code>print</code></a> function.
11189
11190
11191
11192
11193 <p>
11194 <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
11195
11196
11197 <p>
11198 This function returns the name and the value of the local variable
11199 with index <code>local</code> of the function at level <code>f</code> of the stack.
11200 This function accesses not only explicit local variables,
11201 but also parameters and temporary values.
11202
11203
11204 <p>
11205 The first parameter or local variable has index&nbsp;1, and so on,
11206 following the order that they are declared in the code,
11207 counting only the variables that are active
11208 in the current scope of the function.
11209 Compile-time constants may not appear in this listing,
11210 if they were optimized away by the compiler.
11211 Negative indices refer to vararg arguments;
11212 -1 is the first vararg argument.
11213 The function returns <b>fail</b>
11214 if there is no variable with the given index,
11215 and raises an error when called with a level out of range.
11216 (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
11217
11218
11219 <p>
11220 Variable names starting with '<code>(</code>' (open parenthesis)
11221 represent variables with no known names
11222 (internal variables such as loop control variables,
11223 and variables from chunks saved without debug information).
11224
11225
11226 <p>
11227 The parameter <code>f</code> may also be a function.
11228 In that case, <code>getlocal</code> returns only the name of function parameters.
11229
11230
11231
11232
11233 <p>
11234 <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
11235
11236
11237 <p>
11238 Returns the metatable of the given <code>value</code>
11239 or <b>nil</b> if it does not have a metatable.
11240
11241
11242
11243
11244 <p>
11245 <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
11246
11247
11248 <p>
11249 Returns the registry table (see <a href="#4.3">&sect;4.3</a>).
11250
11251
11252
11253
11254 <p>
11255 <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
11256
11257
11258 <p>
11259 This function returns the name and the value of the upvalue
11260 with index <code>up</code> of the function <code>f</code>.
11261 The function returns <b>fail</b>
11262 if there is no upvalue with the given index.
11263
11264
11265 <p>
11266 (For Lua functions,
11267 upvalues are the external local variables that the function uses,
11268 and that are consequently included in its closure.)
11269
11270
11271 <p>
11272 For C&nbsp;functions, this function uses the empty string <code>""</code>
11273 as a name for all upvalues.
11274
11275
11276 <p>
11277 Variable name '<code>?</code>' (interrogation mark)
11278 represents variables with no known names
11279 (variables from chunks saved without debug information).
11280
11281
11282
11283
11284 <p>
11285 <hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u, n)</code></a></h3>
11286
11287
11288 <p>
11289 Returns the <code>n</code>-th user value associated
11290 to the userdata <code>u</code> plus a boolean,
11291 <b>false</b> if the userdata does not have that value.
11292
11293
11294
11295
11296 <p>
11297 <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
11298
11299
11300 <p>
11301 Sets the given function as the debug hook.
11302 The string <code>mask</code> and the number <code>count</code> describe
11303 when the hook will be called.
11304 The string mask may have any combination of the following characters,
11305 with the given meaning:
11306
11307 <ul>
11308 <li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
11309 <li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
11310 <li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
11311 </ul><p>
11312 Moreover,
11313 with a <code>count</code> different from zero,
11314 the hook is called also after every <code>count</code> instructions.
11315
11316
11317 <p>
11318 When called without arguments,
11319 <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
11320
11321
11322 <p>
11323 When the hook is called, its first parameter is a string
11324 describing the event that has triggered its call:
11325 <code>"call"</code>, <code>"tail call"</code>, <code>"return"</code>,
11326 <code>"line"</code>, and <code>"count"</code>.
11327 For line events,
11328 the hook also gets the new line number as its second parameter.
11329 Inside a hook,
11330 you can call <code>getinfo</code> with level&nbsp;2 to get more information about
11331 the running function.
11332 (Level&nbsp;0 is the <code>getinfo</code> function,
11333 and level&nbsp;1 is the hook function.)
11334
11335
11336
11337
11338 <p>
11339 <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
11340
11341
11342 <p>
11343 This function assigns the value <code>value</code> to the local variable
11344 with index <code>local</code> of the function at level <code>level</code> of the stack.
11345 The function returns <b>fail</b> if there is no local
11346 variable with the given index,
11347 and raises an error when called with a <code>level</code> out of range.
11348 (You can call <code>getinfo</code> to check whether the level is valid.)
11349 Otherwise, it returns the name of the local variable.
11350
11351
11352 <p>
11353 See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
11354 variable indices and names.
11355
11356
11357
11358
11359 <p>
11360 <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
11361
11362
11363 <p>
11364 Sets the metatable for the given <code>value</code> to the given <code>table</code>
11365 (which can be <b>nil</b>).
11366 Returns <code>value</code>.
11367
11368
11369
11370
11371 <p>
11372 <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
11373
11374
11375 <p>
11376 This function assigns the value <code>value</code> to the upvalue
11377 with index <code>up</code> of the function <code>f</code>.
11378 The function returns <b>fail</b> if there is no upvalue
11379 with the given index.
11380 Otherwise, it returns the name of the upvalue.
11381
11382
11383 <p>
11384 See <a href="#pdf-debug.getupvalue"><code>debug.getupvalue</code></a> for more information about upvalues.
11385
11386
11387
11388
11389 <p>
11390 <hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value, n)</code></a></h3>
11391
11392
11393 <p>
11394 Sets the given <code>value</code> as
11395 the <code>n</code>-th user value associated to the given <code>udata</code>.
11396 <code>udata</code> must be a full userdata.
11397
11398
11399 <p>
11400 Returns <code>udata</code>,
11401 or <b>fail</b> if the userdata does not have that value.
11402
11403
11404
11405
11406 <p>
11407 <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
11408
11409
11410 <p>
11411 If <code>message</code> is present but is neither a string nor <b>nil</b>,
11412 this function returns <code>message</code> without further processing.
11413 Otherwise,
11414 it returns a string with a traceback of the call stack.
11415 The optional <code>message</code> string is appended
11416 at the beginning of the traceback.
11417 An optional <code>level</code> number tells at which level
11418 to start the traceback
11419 (default is 1, the function calling <code>traceback</code>).
11420
11421
11422
11423
11424 <p>
11425 <hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
11426
11427
11428 <p>
11429 Returns a unique identifier (as a light userdata)
11430 for the upvalue numbered <code>n</code>
11431 from the given function.
11432
11433
11434 <p>
11435 These unique identifiers allow a program to check whether different
11436 closures share upvalues.
11437 Lua closures that share an upvalue
11438 (that is, that access a same external local variable)
11439 will return identical ids for those upvalue indices.
11440
11441
11442
11443
11444 <p>
11445 <hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
11446
11447
11448 <p>
11449 Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
11450 refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
11451
11452
11453
11454
11455
11456
11457
11458 <h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
11459
11460 <p>
11461 Although Lua has been designed as an extension language,
11462 to be embedded in a host C&nbsp;program,
11463 it is also frequently used as a standalone language.
11464 An interpreter for Lua as a standalone language,
11465 called simply <code>lua</code>,
11466 is provided with the standard distribution.
11467 The standalone interpreter includes
11468 all standard libraries.
11469 Its usage is:
11470
11471 <pre>
11472 lua [options] [script [args]]
11473 </pre><p>
11474 The options are:
11475
11476 <ul>
11477 <li><b><code>-e <em>stat</em></code>: </b> execute string <em>stat</em>;</li>
11478 <li><b><code>-i</code>: </b> enter interactive mode after running <em>script</em>;</li>
11479 <li><b><code>-l <em>mod</em></code>: </b> "require" <em>mod</em> and assign the
11480 result to global <em>mod</em>;</li>
11481 <li><b><code>-v</code>: </b> print version information;</li>
11482 <li><b><code>-E</code>: </b> ignore environment variables;</li>
11483 <li><b><code>-W</code>: </b> turn warnings on;</li>
11484 <li><b><code>--</code>: </b> stop handling options;</li>
11485 <li><b><code>-</code>: </b> execute <code>stdin</code> as a file and stop handling options.</li>
11486 </ul><p>
11487 After handling its options, <code>lua</code> runs the given <em>script</em>.
11488 When called without arguments,
11489 <code>lua</code> behaves as <code>lua -v -i</code>
11490 when the standard input (<code>stdin</code>) is a terminal,
11491 and as <code>lua -</code> otherwise.
11492
11493
11494 <p>
11495 When called without the option <code>-E</code>,
11496 the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_4"><code>LUA_INIT_5_4</code></a>
11497 (or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
11498 before running any argument.
11499 If the variable content has the format <code>@<em>filename</em></code>,
11500 then <code>lua</code> executes the file.
11501 Otherwise, <code>lua</code> executes the string itself.
11502
11503
11504 <p>
11505 When called with the option <code>-E</code>,
11506 Lua does not consult any environment variables.
11507 In particular,
11508 the values of <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
11509 are set with the default paths defined in <code>luaconf.h</code>.
11510
11511
11512 <p>
11513 The options <code>-e</code>, <code>-l</code>, and <code>-W</code> are handled in
11514 the order they appear.
11515 For instance, an invocation like
11516
11517 <pre>
11518 $ lua -e 'a=1' -llib1 script.lua
11519 </pre><p>
11520 will first set <code>a</code> to 1, then require the library <code>lib1</code>,
11521 and finally run the file <code>script.lua</code> with no arguments.
11522 (Here <code>$</code> is the shell prompt. Your prompt may be different.)
11523
11524
11525 <p>
11526 Before running any code,
11527 <code>lua</code> collects all command-line arguments
11528 in a global table called <code>arg</code>.
11529 The script name goes to index 0,
11530 the first argument after the script name goes to index 1,
11531 and so on.
11532 Any arguments before the script name
11533 (that is, the interpreter name plus its options)
11534 go to negative indices.
11535 For instance, in the call
11536
11537 <pre>
11538 $ lua -la b.lua t1 t2
11539 </pre><p>
11540 the table is like this:
11541
11542 <pre>
11543 arg = { [-2] = "lua", [-1] = "-la",
11544 [0] = "b.lua",
11545 [1] = "t1", [2] = "t2" }
11546 </pre><p>
11547 If there is no script in the call,
11548 the interpreter name goes to index 0,
11549 followed by the other arguments.
11550 For instance, the call
11551
11552 <pre>
11553 $ lua -e "print(arg[1])"
11554 </pre><p>
11555 will print "<code>-e</code>".
11556 If there is a script,
11557 the script is called with arguments
11558 <code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
11559 Like all chunks in Lua,
11560 the script is compiled as a vararg function.
11561
11562
11563 <p>
11564 In interactive mode,
11565 Lua repeatedly prompts and waits for a line.
11566 After reading a line,
11567 Lua first try to interpret the line as an expression.
11568 If it succeeds, it prints its value.
11569 Otherwise, it interprets the line as a statement.
11570 If you write an incomplete statement,
11571 the interpreter waits for its completion
11572 by issuing a different prompt.
11573
11574
11575 <p>
11576 If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
11577 then its value is used as the prompt.
11578 Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
11579 its value is used as the secondary prompt
11580 (issued during incomplete statements).
11581
11582
11583 <p>
11584 In case of unprotected errors in the script,
11585 the interpreter reports the error to the standard error stream.
11586 If the error object is not a string but
11587 has a metamethod <code>__tostring</code>,
11588 the interpreter calls this metamethod to produce the final message.
11589 Otherwise, the interpreter converts the error object to a string
11590 and adds a stack traceback to it.
11591 When warnings are on,
11592 they are simply printed in the standard error output.
11593
11594
11595 <p>
11596 When finishing normally,
11597 the interpreter closes its main Lua state
11598 (see <a href="#lua_close"><code>lua_close</code></a>).
11599 The script can avoid this step by
11600 calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
11601
11602
11603 <p>
11604 To allow the use of Lua as a
11605 script interpreter in Unix systems,
11606 Lua skips the first line of a file chunk if it starts with <code>#</code>.
11607 Therefore, Lua scripts can be made into executable programs
11608 by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
11609 as in
11610
11611 <pre>
11612 #!/usr/local/bin/lua
11613 </pre><p>
11614 Of course,
11615 the location of the Lua interpreter may be different in your machine.
11616 If <code>lua</code> is in your <code>PATH</code>,
11617 then
11618
11619 <pre>
11620 #!/usr/bin/env lua
11621 </pre><p>
11622 is a more portable solution.
11623
11624
11625
11626 <h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
11627
11628
11629
11630 <p>
11631 Here we list the incompatibilities that you may find when moving a program
11632 from Lua&nbsp;5.3 to Lua&nbsp;5.4.
11633
11634
11635 <p>
11636 You can avoid some incompatibilities by compiling Lua with
11637 appropriate options (see file <code>luaconf.h</code>).
11638 However,
11639 all these compatibility options will be removed in the future.
11640 More often than not,
11641 compatibility issues arise when these compatibility options
11642 are removed.
11643 So, whenever you have the chance,
11644 you should try to test your code with a version of Lua compiled
11645 with all compatibility options turned off.
11646 That will ease transitions to newer versions of Lua.
11647
11648
11649 <p>
11650 Lua versions can always change the C API in ways that
11651 do not imply source-code changes in a program,
11652 such as the numeric values for constants
11653 or the implementation of functions as macros.
11654 Therefore,
11655 you should never assume that binaries are compatible between
11656 different Lua versions.
11657 Always recompile clients of the Lua API when
11658 using a new version.
11659
11660
11661 <p>
11662 Similarly, Lua versions can always change the internal representation
11663 of precompiled chunks;
11664 precompiled chunks are not compatible between different Lua versions.
11665
11666
11667 <p>
11668 The standard paths in the official distribution may
11669 change between versions.
11670
11671
11672
11673
11674
11675 <h2>8.1 &ndash; <a name="8.1">Incompatibilities in the Language</a></h2>
11676 <ul>
11677
11678 <li>
11679 The coercion of strings to numbers in
11680 arithmetic and bitwise operations
11681 has been removed from the core language.
11682 The string library does a similar job
11683 for arithmetic (but not for bitwise) operations
11684 using the string metamethods.
11685 However, unlike in previous versions,
11686 the new implementation preserves the implicit type of the numeral
11687 in the string.
11688 For instance, the result of <code>"1" + "2"</code> now is an integer,
11689 not a float.
11690 </li>
11691
11692 <li>
11693 Literal decimal integer constants that overflow are read as floats,
11694 instead of wrapping around.
11695 You can use hexadecimal notation for such constants if you
11696 want the old behavior
11697 (reading them as integers with wrap around).
11698 </li>
11699
11700 <li>
11701 The use of the <code>__lt</code> metamethod to emulate <code>__le</code>
11702 has been removed.
11703 When needed, this metamethod must be explicitly defined.
11704 </li>
11705
11706 <li>
11707 The semantics of the numerical <b>for</b> loop
11708 over integers changed in some details.
11709 In particular, the control variable never wraps around.
11710 </li>
11711
11712 <li>
11713 A label for a <b>goto</b> cannot be declared where a label with the same
11714 name is visible, even if this other label is declared in an enclosing
11715 block.
11716 </li>
11717
11718 <li>
11719 When finalizing an object,
11720 Lua does not ignore <code>__gc</code> metamethods that are not functions.
11721 Any value will be called, if present.
11722 (Non-callable values will generate a warning,
11723 like any other error when calling a finalizer.)
11724 </li>
11725
11726 </ul>
11727
11728
11729
11730
11731 <h2>8.2 &ndash; <a name="8.2">Incompatibilities in the Libraries</a></h2>
11732 <ul>
11733
11734 <li>
11735 The function <a href="#pdf-print"><code>print</code></a> does not call <a href="#pdf-tostring"><code>tostring</code></a>
11736 to format its arguments;
11737 instead, it has this functionality hardwired.
11738 You should use <code>__tostring</code> to modify how values are printed.
11739 </li>
11740
11741 <li>
11742 The pseudo-random number generator used by the function <a href="#pdf-math.random"><code>math.random</code></a>
11743 now starts with a somewhat random seed.
11744 Moreover, it uses a different algorithm.
11745 </li>
11746
11747 <li>
11748 By default, the decoding functions in the <a href="#pdf-utf8"><code>utf8</code></a> library
11749 do not accept surrogates as valid code points.
11750 An extra parameter in these functions makes them more permissive.
11751 </li>
11752
11753 <li>
11754 The options "<code>setpause</code>" and "<code>setstepmul</code>"
11755 of the function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> are deprecated.
11756 You should use the new option "<code>incremental</code>" to set them.
11757 </li>
11758
11759 <li>
11760 The function <a href="#pdf-io.lines"><code>io.lines</code></a> now returns four values,
11761 instead of just one.
11762 That can be a problem when it is used as the sole
11763 argument to another function that has optional parameters,
11764 such as in <code>load(io.lines(filename, "L"))</code>.
11765 To fix that issue,
11766 you can wrap the call into parentheses,
11767 to adjust its number of results to one.
11768 </li>
11769
11770 </ul>
11771
11772
11773
11774
11775 <h2>8.3 &ndash; <a name="8.3">Incompatibilities in the API</a></h2>
11776
11777
11778 <ul>
11779
11780 <li>
11781 Full userdata now has an arbitrary number of associated user values.
11782 Therefore, the functions <code>lua_newuserdata</code>,
11783 <code>lua_setuservalue</code>, and <code>lua_getuservalue</code> were
11784 replaced by <a href="#lua_newuserdatauv"><code>lua_newuserdatauv</code></a>,
11785 <a href="#lua_setiuservalue"><code>lua_setiuservalue</code></a>, and <a href="#lua_getiuservalue"><code>lua_getiuservalue</code></a>,
11786 which have an extra argument.
11787
11788
11789 <p>
11790 For compatibility, the old names still work as macros assuming
11791 one single user value.
11792 Note, however, that userdata with zero user values
11793 are more efficient memory-wise.
11794 </li>
11795
11796 <li>
11797 The function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter.
11798 This out parameter returns the number of values on
11799 the top of the stack that were yielded or returned by the coroutine.
11800 (In previous versions,
11801 those values were the entire stack.)
11802 </li>
11803
11804 <li>
11805 The function <a href="#lua_version"><code>lua_version</code></a> returns the version number,
11806 instead of an address of the version number.
11807 The Lua core should work correctly with libraries using their
11808 own static copies of the same core,
11809 so there is no need to check whether they are using the same
11810 address space.
11811 </li>
11812
11813 <li>
11814 The constant <code>LUA_ERRGCMM</code> was removed.
11815 Errors in finalizers are never propagated;
11816 instead, they generate a warning.
11817 </li>
11818
11819 <li>
11820 The options <code>LUA_GCSETPAUSE</code> and <code>LUA_GCSETSTEPMUL</code>
11821 of the function <a href="#lua_gc"><code>lua_gc</code></a> are deprecated.
11822 You should use the new option <code>LUA_GCINC</code> to set them.
11823 </li>
11824
11825 </ul>
11826
11827
11828
11829
11830 <h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
11831
11832 <p>
11833 Here is the complete syntax of Lua in extended BNF.
11834 As usual in extended BNF,
11835 {A} means 0 or more As,
11836 and [A] means an optional A.
11837 (For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
11838 for a description of the terminals
11839 Name, Numeral,
11840 and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
11841
11842
11843
11844
11845 <pre>
11846
11847 chunk ::= block
11848
11849 block ::= {stat} [retstat]
11850
11851 stat ::= &lsquo;<b>;</b>&rsquo; |
11852 varlist &lsquo;<b>=</b>&rsquo; explist |
11853 functioncall |
11854 label |
11855 <b>break</b> |
11856 <b>goto</b> Name |
11857 <b>do</b> block <b>end</b> |
11858 <b>while</b> exp <b>do</b> block <b>end</b> |
11859 <b>repeat</b> block <b>until</b> exp |
11860 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
11861 <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b> |
11862 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
11863 <b>function</b> funcname funcbody |
11864 <b>local</b> <b>function</b> Name funcbody |
11865 <b>local</b> attnamelist [&lsquo;<b>=</b>&rsquo; explist]
11866
11867 attnamelist ::= Name attrib {&lsquo;<b>,</b>&rsquo; Name attrib}
11868
11869 attrib ::= [&lsquo;<b>&lt;</b>&rsquo; Name &lsquo;<b>&gt;</b>&rsquo;]
11870
11871 retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
11872
11873 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
11874
11875 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
11876
11877 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
11878
11879 var ::= Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
11880
11881 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
11882
11883 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
11884
11885 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
11886 prefixexp | tableconstructor | exp binop exp | unop exp
11887
11888 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
11889
11890 functioncall ::= prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
11891
11892 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
11893
11894 functiondef ::= <b>function</b> funcbody
11895
11896 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
11897
11898 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
11899
11900 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
11901
11902 fieldlist ::= field {fieldsep field} [fieldsep]
11903
11904 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
11905
11906 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
11907
11908 binop ::= &lsquo;<b>+</b>&rsquo; | &lsquo;<b>-</b>&rsquo; | &lsquo;<b>*</b>&rsquo; | &lsquo;<b>/</b>&rsquo; | &lsquo;<b>//</b>&rsquo; | &lsquo;<b>^</b>&rsquo; | &lsquo;<b>%</b>&rsquo; |
11909 &lsquo;<b>&amp;</b>&rsquo; | &lsquo;<b>~</b>&rsquo; | &lsquo;<b>|</b>&rsquo; | &lsquo;<b>&gt;&gt;</b>&rsquo; | &lsquo;<b>&lt;&lt;</b>&rsquo; | &lsquo;<b>..</b>&rsquo; |
11910 &lsquo;<b>&lt;</b>&rsquo; | &lsquo;<b>&lt;=</b>&rsquo; | &lsquo;<b>&gt;</b>&rsquo; | &lsquo;<b>&gt;=</b>&rsquo; | &lsquo;<b>==</b>&rsquo; | &lsquo;<b>~=</b>&rsquo; |
11911 <b>and</b> | <b>or</b>
11912
11913 unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
11914
11915 </pre>
11916
11917 <p>
11918
11919
11920
11921
11922
11923
11924
11925 <P CLASS="footer">
11926 Last update:
11927 Mon Mar 15 13:39:42 UTC 2021
11928 </P>
11929 <!--
11930 Last change: revised for Lua 5.4.3
11931 -->
11932
11933 </body></html>
11934