comparison website/src/manual.html @ 371:e01cddba3433

add manual.html as copy of Lua 5.3 Reference Manual
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 17 Apr 2015 07:25:51 -0600
parents
children f08cefa4594c
comparison
equal deleted inserted replaced
370:7999601586b1 371:e01cddba3433
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3
4 <head>
5 <title>Lua 5.3 Reference Manual</title>
6 <link rel="stylesheet" type="text/css" href="../../lua.css">
7 <link rel="stylesheet" type="text/css" href="../manual.css">
8 <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
9 </head>
10
11 <body>
12
13 <hr>
14 <h1>
15 <a href="../../home.html"><img src="../../images/logo.gif" alt="" border="0"></a>
16 Lua 5.3 Reference Manual
17 </h1>
18
19 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
20 <p>
21 <small>
22 Copyright &copy; 2015 Lua.org, PUC-Rio.
23 Freely available under the terms of the
24 <a href="../../license.html">Lua license</a>.
25 </small>
26 <hr>
27 <p>
28
29 <a href="contents.html#contents">contents</A>
30 &middot;
31 <a href="contents.html#index">index</A>
32 &middot;
33 <a href="../">other versions</A>
34
35 <!-- ====================================================================== -->
36 <p>
37
38 <!-- $Id: manual.of,v 1.146 2015/01/06 11:23:01 roberto Exp $ -->
39
40
41
42
43 <h1>1 &ndash; <a name="1">Introduction</a></h1>
44
45 <p>
46 Lua is an extension programming language designed to support
47 general procedural programming with data description
48 facilities.
49 Lua also offers good support for object-oriented programming,
50 functional programming, and data-driven programming.
51 Lua is intended to be used as a powerful, lightweight,
52 embeddable scripting language for any program that needs one.
53 Lua is implemented as a library, written in <em>clean C</em>,
54 the common subset of Standard&nbsp;C and C++.
55
56
57 <p>
58 As an extension language, Lua has no notion of a "main" program:
59 it only works <em>embedded</em> in a host client,
60 called the <em>embedding program</em> or simply the <em>host</em>.
61 The host program can invoke functions to execute a piece of Lua code,
62 can write and read Lua variables,
63 and can register C&nbsp;functions to be called by Lua code.
64 Through the use of C&nbsp;functions, Lua can be augmented to cope with
65 a wide range of different domains,
66 thus creating customized programming languages sharing a syntactical framework.
67 The Lua distribution includes a sample host program called <code>lua</code>,
68 which uses the Lua library to offer a complete, standalone Lua interpreter,
69 for interactive or batch use.
70
71
72 <p>
73 Lua is free software,
74 and is provided as usual with no guarantees,
75 as stated in its license.
76 The implementation described in this manual is available
77 at Lua's official web site, <code>www.lua.org</code>.
78
79
80 <p>
81 Like any other reference manual,
82 this document is dry in places.
83 For a discussion of the decisions behind the design of Lua,
84 see the technical papers available at Lua's web site.
85 For a detailed introduction to programming in Lua,
86 see Roberto's book, <em>Programming in Lua</em>.
87
88
89
90 <h1>2 &ndash; <a name="2">Basic Concepts</a></h1>
91
92 <p>
93 This section describes the basic concepts of the language.
94
95
96
97 <h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
98
99 <p>
100 Lua is a <em>dynamically typed language</em>.
101 This means that
102 variables do not have types; only values do.
103 There are no type definitions in the language.
104 All values carry their own type.
105
106
107 <p>
108 All values in Lua are <em>first-class values</em>.
109 This means that all values can be stored in variables,
110 passed as arguments to other functions, and returned as results.
111
112
113 <p>
114 There are eight basic types in Lua:
115 <em>nil</em>, <em>boolean</em>, <em>number</em>,
116 <em>string</em>, <em>function</em>, <em>userdata</em>,
117 <em>thread</em>, and <em>table</em>.
118 <em>Nil</em> is the type of the value <b>nil</b>,
119 whose main property is to be different from any other value;
120 it usually represents the absence of a useful value.
121 <em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
122 Both <b>nil</b> and <b>false</b> make a condition false;
123 any other value makes it true.
124 <em>Number</em> represents both
125 integer numbers and real (floating-point) numbers.
126 <em>String</em> represents immutable sequences of bytes.
127
128 Lua is 8-bit clean:
129 strings can contain any 8-bit value,
130 including embedded zeros ('<code>\0</code>').
131 Lua is also encoding-agnostic;
132 it makes no assumptions about the contents of a string.
133
134
135 <p>
136 The type <em>number</em> uses two internal representations,
137 one called <em>integer</em> and the other called <em>float</em>.
138 Lua has explicit rules about when each representation is used,
139 but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
140 Therefore,
141 the programmer may choose to mostly ignore the difference
142 between integers and floats
143 or to assume complete control over the representation of each number.
144 Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
145 but you can also compile Lua so that it
146 uses 32-bit integers and/or single-precision (32-bit) floats.
147 The option with 32 bits for both integers and floats
148 is particularly attractive
149 for small machines and embedded systems.
150 (See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
151
152
153 <p>
154 Lua can call (and manipulate) functions written in Lua and
155 functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
156 Both are represented by the type <em>function</em>.
157
158
159 <p>
160 The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
161 be stored in Lua variables.
162 A userdata value represents a block of raw memory.
163 There are two kinds of userdata:
164 <em>full userdata</em>,
165 which is an object with a block of memory managed by Lua,
166 and <em>light userdata</em>,
167 which is simply a C&nbsp;pointer value.
168 Userdata has no predefined operations in Lua,
169 except assignment and identity test.
170 By using <em>metatables</em>,
171 the programmer can define operations for full userdata values
172 (see <a href="#2.4">&sect;2.4</a>).
173 Userdata values cannot be created or modified in Lua,
174 only through the C&nbsp;API.
175 This guarantees the integrity of data owned by the host program.
176
177
178 <p>
179 The type <em>thread</em> represents independent threads of execution
180 and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
181 Lua threads are not related to operating-system threads.
182 Lua supports coroutines on all systems,
183 even those that do not support threads natively.
184
185
186 <p>
187 The type <em>table</em> implements associative arrays,
188 that is, arrays that can be indexed not only with numbers,
189 but with any Lua value except <b>nil</b> and NaN.
190 (<em>Not a Number</em> is a special numeric value used to represent
191 undefined or unrepresentable results, such as <code>0/0</code>.)
192 Tables can be <em>heterogeneous</em>;
193 that is, they can contain values of all types (except <b>nil</b>).
194 Any key with value <b>nil</b> is not considered part of the table.
195 Conversely, any key that is not part of a table has
196 an associated value <b>nil</b>.
197
198
199 <p>
200 Tables are the sole data-structuring mechanism in Lua;
201 they can be used to represent ordinary arrays, sequences,
202 symbol tables, sets, records, graphs, trees, etc.
203 To represent records, Lua uses the field name as an index.
204 The language supports this representation by
205 providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
206 There are several convenient ways to create tables in Lua
207 (see <a href="#3.4.9">&sect;3.4.9</a>).
208
209
210 <p>
211 We use the term <em>sequence</em> to denote a table where
212 the set of all positive numeric keys is equal to {1..<em>n</em>}
213 for some non-negative integer <em>n</em>,
214 which is called the length of the sequence (see <a href="#3.4.7">&sect;3.4.7</a>).
215
216
217 <p>
218 Like indices,
219 the values of table fields can be of any type.
220 In particular,
221 because functions are first-class values,
222 table fields can contain functions.
223 Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
224
225
226 <p>
227 The indexing of tables follows
228 the definition of raw equality in the language.
229 The expressions <code>a[i]</code> and <code>a[j]</code>
230 denote the same table element
231 if and only if <code>i</code> and <code>j</code> are raw equal
232 (that is, equal without metamethods).
233 In particular, floats with integral values
234 are equal to their respective integers
235 (e.g., <code>1.0 == 1</code>).
236 To avoid ambiguities,
237 any float with integral value used as a key
238 is converted to its respective integer.
239 For instance, if you write <code>a[2.0] = true</code>,
240 the actual key inserted into the table will be the
241 integer <code>2</code>.
242 (On the other hand,
243 2 and "<code>2</code>" are different Lua values and therefore
244 denote different table entries.)
245
246
247 <p>
248 Tables, functions, threads, and (full) userdata values are <em>objects</em>:
249 variables do not actually <em>contain</em> these values,
250 only <em>references</em> to them.
251 Assignment, parameter passing, and function returns
252 always manipulate references to such values;
253 these operations do not imply any kind of copy.
254
255
256 <p>
257 The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
258 of a given value (see <a href="#6.1">&sect;6.1</a>).
259
260
261
262
263
264 <h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
265
266 <p>
267 As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
268 any reference to a free name
269 (that is, a name not bound to any declaration) <code>var</code>
270 is syntactically translated to <code>_ENV.var</code>.
271 Moreover, every chunk is compiled in the scope of
272 an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
273 so <code>_ENV</code> itself is never a free name in a chunk.
274
275
276 <p>
277 Despite the existence of this external <code>_ENV</code> variable and
278 the translation of free names,
279 <code>_ENV</code> is a completely regular name.
280 In particular,
281 you can define new variables and parameters with that name.
282 Each reference to a free name uses the <code>_ENV</code> that is
283 visible at that point in the program,
284 following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
285
286
287 <p>
288 Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
289
290
291 <p>
292 Lua keeps a distinguished environment called the <em>global environment</em>.
293 This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
294 In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
295 (<a href="#pdf-_G"><code>_G</code></a> is never used internally.)
296
297
298 <p>
299 When Lua loads a chunk,
300 the default value for its <code>_ENV</code> upvalue
301 is the global environment (see <a href="#pdf-load"><code>load</code></a>).
302 Therefore, by default,
303 free names in Lua code refer to entries in the global environment
304 (and, therefore, they are also called <em>global variables</em>).
305 Moreover, all standard libraries are loaded in the global environment
306 and some functions there operate on that environment.
307 You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
308 to load a chunk with a different environment.
309 (In C, you have to load the chunk and then change the value
310 of its first upvalue.)
311
312
313
314
315
316 <h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
317
318 <p>
319 Because Lua is an embedded extension language,
320 all Lua actions start from C&nbsp;code in the host program
321 calling a function from the Lua library.
322 (When you use Lua standalone,
323 the <code>lua</code> application is the host program.)
324 Whenever an error occurs during
325 the compilation or execution of a Lua chunk,
326 control returns to the host,
327 which can take appropriate measures
328 (such as printing an error message).
329
330
331 <p>
332 Lua code can explicitly generate an error by calling the
333 <a href="#pdf-error"><code>error</code></a> function.
334 If you need to catch errors in Lua,
335 you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
336 to call a given function in <em>protected mode</em>.
337
338
339 <p>
340 Whenever there is an error,
341 an <em>error object</em> (also called an <em>error message</em>)
342 is propagated with information about the error.
343 Lua itself only generates errors whose error object is a string,
344 but programs may generate errors with
345 any value as the error object.
346 It is up to the Lua program or its host to handle such error objects.
347
348
349 <p>
350 When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
351 you may give a <em>message handler</em>
352 to be called in case of errors.
353 This function is called with the original error message
354 and returns a new error message.
355 It is called before the error unwinds the stack,
356 so that it can gather more information about the error,
357 for instance by inspecting the stack and creating a stack traceback.
358 This message handler is still protected by the protected call;
359 so, an error inside the message handler
360 will call the message handler again.
361 If this loop goes on for too long,
362 Lua breaks it and returns an appropriate message.
363
364
365
366
367
368 <h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
369
370 <p>
371 Every value in Lua can have a <em>metatable</em>.
372 This <em>metatable</em> is an ordinary Lua table
373 that defines the behavior of the original value
374 under certain special operations.
375 You can change several aspects of the behavior
376 of operations over a value by setting specific fields in its metatable.
377 For instance, when a non-numeric value is the operand of an addition,
378 Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
379 If it finds one,
380 Lua calls this function to perform the addition.
381
382
383 <p>
384 The keys in a metatable are derived from the <em>event</em> names;
385 the corresponding values are called <em>metamethods</em>.
386 In the previous example, the event is <code>"add"</code>
387 and the metamethod is the function that performs the addition.
388
389
390 <p>
391 You can query the metatable of any value
392 using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
393
394
395 <p>
396 You can replace the metatable of tables
397 using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
398 You cannot change the metatable of other types from Lua
399 (except by using the debug library (<a href="#6.10">&sect;6.10</a>));
400 you must use the C&nbsp;API for that.
401
402
403 <p>
404 Tables and full userdata have individual metatables
405 (although multiple tables and userdata can share their metatables).
406 Values of all other types share one single metatable per type;
407 that is, there is one single metatable for all numbers,
408 one for all strings, etc.
409 By default, a value has no metatable,
410 but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
411
412
413 <p>
414 A metatable controls how an object behaves in
415 arithmetic operations, bitwise operations,
416 order comparisons, concatenation, length operation, calls, and indexing.
417 A metatable also can define a function to be called
418 when a userdata or a table is garbage collected (<a href="#2.5">&sect;2.5</a>).
419
420
421 <p>
422 A detailed list of events controlled by metatables is given next.
423 Each operation is identified by its corresponding event name.
424 The key for each event is a string with its name prefixed by
425 two underscores, '<code>__</code>';
426 for instance, the key for operation "add" is the
427 string "<code>__add</code>".
428 Note that queries for metamethods are always raw;
429 the access to a metamethod does not invoke other metamethods.
430 You can emulate how Lua queries a metamethod for an object <code>obj</code>
431 with the following code:
432
433 <pre>
434 rawget(getmetatable(obj) or {}, "__" .. event_name)
435 </pre>
436
437 <p>
438 For the unary operators (negation, length, and bitwise not),
439 the metamethod is computed and called with a dummy second operand,
440 equal to the first one.
441 This extra operand is only to simplify Lua's internals
442 (by making these operators behave like a binary operation)
443 and may be removed in future versions.
444 (For most uses this extra operand is irrelevant.)
445
446
447
448 <ul>
449
450 <li><b>"add": </b>
451 the <code>+</code> operation.
452
453 If any operand for an addition is not a number
454 (nor a string coercible to a number),
455 Lua will try to call a metamethod.
456 First, Lua will check the first operand (even if it is valid).
457 If that operand does not define a metamethod for the "<code>__add</code>" event,
458 then Lua will check the second operand.
459 If Lua can find a metamethod,
460 it calls the metamethod with the two operands as arguments,
461 and the result of the call
462 (adjusted to one value)
463 is the result of the operation.
464 Otherwise,
465 it raises an error.
466 </li>
467
468 <li><b>"sub": </b>
469 the <code>-</code> operation.
470
471 Behavior similar to the "add" operation.
472 </li>
473
474 <li><b>"mul": </b>
475 the <code>*</code> operation.
476
477 Behavior similar to the "add" operation.
478 </li>
479
480 <li><b>"div": </b>
481 the <code>/</code> operation.
482
483 Behavior similar to the "add" operation.
484 </li>
485
486 <li><b>"mod": </b>
487 the <code>%</code> operation.
488
489 Behavior similar to the "add" operation.
490 </li>
491
492 <li><b>"pow": </b>
493 the <code>^</code> (exponentiation) operation.
494
495 Behavior similar to the "add" operation.
496 </li>
497
498 <li><b>"unm": </b>
499 the <code>-</code> (unary minus) operation.
500
501 Behavior similar to the "add" operation.
502 </li>
503
504 <li><b>"idiv": </b>
505 the <code>//</code> (floor division) operation.
506
507 Behavior similar to the "add" operation.
508 </li>
509
510 <li><b>"band": </b>
511 the <code>&amp;</code> (bitwise and) operation.
512
513 Behavior similar to the "add" operation,
514 except that Lua will try a metamethod
515 if any operator is neither an integer
516 nor a value coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
517 </li>
518
519 <li><b>"bor": </b>
520 the <code>|</code> (bitwise or) operation.
521
522 Behavior similar to the "band" operation.
523 </li>
524
525 <li><b>"bxor": </b>
526 the <code>~</code> (bitwise exclusive or) operation.
527
528 Behavior similar to the "band" operation.
529 </li>
530
531 <li><b>"bnot": </b>
532 the <code>~</code> (bitwise unary not) operation.
533
534 Behavior similar to the "band" operation.
535 </li>
536
537 <li><b>"shl": </b>
538 the <code>&lt;&lt;</code> (bitwise left shift) operation.
539
540 Behavior similar to the "band" operation.
541 </li>
542
543 <li><b>"shr": </b>
544 the <code>&gt;&gt;</code> (bitwise right shift) operation.
545
546 Behavior similar to the "band" operation.
547 </li>
548
549 <li><b>"concat": </b>
550 the <code>..</code> (concatenation) operation.
551
552 Behavior similar to the "add" operation,
553 except that Lua will try a metamethod
554 if any operator is neither a string nor a number
555 (which is always coercible to a string).
556 </li>
557
558 <li><b>"len": </b>
559 the <code>#</code> (length) operation.
560
561 If the object is not a string,
562 Lua will try its metamethod.
563 If there is a metamethod,
564 Lua calls it with the object as argument,
565 and the result of the call
566 (always adjusted to one value)
567 is the result of the operation.
568 If there is no metamethod but the object is a table,
569 then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
570 Otherwise, Lua raises an error.
571 </li>
572
573 <li><b>"eq": </b>
574 the <code>==</code> (equal) operation.
575
576 Behavior similar to the "add" operation,
577 except that Lua will try a metamethod only when the values
578 being compared are either both tables or both full userdata
579 and they are not primitively equal.
580 The result of the call is always converted to a boolean.
581 </li>
582
583 <li><b>"lt": </b>
584 the <code>&lt;</code> (less than) operation.
585
586 Behavior similar to the "add" operation,
587 except that Lua will try a metamethod only when the values
588 being compared are neither both numbers nor both strings.
589 The result of the call is always converted to a boolean.
590 </li>
591
592 <li><b>"le": </b>
593 the <code>&lt;=</code> (less equal) operation.
594
595 Unlike other operations,
596 The less-equal operation can use two different events.
597 First, Lua looks for the "<code>__le</code>" metamethod in both operands,
598 like in the "lt" operation.
599 If it cannot find such a metamethod,
600 then it will try the "<code>__lt</code>" event,
601 assuming that <code>a &lt;= b</code> is equivalent to <code>not (b &lt; a)</code>.
602 As with the other comparison operators,
603 the result is always a boolean.
604 </li>
605
606 <li><b>"index": </b>
607 The indexing access <code>table[key]</code>.
608
609 This event happens when <code>table</code> is not a table or
610 when <code>key</code> is not present in <code>table</code>.
611 The metamethod is looked up in <code>table</code>.
612
613
614 <p>
615 Despite the name,
616 the metamethod for this event can be either a function or a table.
617 If it is a function,
618 it is called with <code>table</code> and <code>key</code> as arguments.
619 If it is a table,
620 the final result is the result of indexing this table with <code>key</code>.
621 (This indexing is regular, not raw,
622 and therefore can trigger another metamethod.)
623 </li>
624
625 <li><b>"newindex": </b>
626 The indexing assignment <code>table[key] = value</code>.
627
628 Like the index event,
629 this event happens when <code>table</code> is not a table or
630 when <code>key</code> is not present in <code>table</code>.
631 The metamethod is looked up in <code>table</code>.
632
633
634 <p>
635 Like with indexing,
636 the metamethod for this event can be either a function or a table.
637 If it is a function,
638 it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
639 If it is a table,
640 Lua does an indexing assignment to this table with the same key and value.
641 (This assignment is regular, not raw,
642 and therefore can trigger another metamethod.)
643
644
645 <p>
646 Whenever there is a "newindex" metamethod,
647 Lua does not perform the primitive assignment.
648 (If necessary,
649 the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
650 to do the assignment.)
651 </li>
652
653 <li><b>"call": </b>
654 The call operation <code>func(args)</code>.
655
656 This event happens when Lua tries to call a non-function value
657 (that is, <code>func</code> is not a function).
658 The metamethod is looked up in <code>func</code>.
659 If present,
660 the metamethod is called with <code>func</code> as its first argument,
661 followed by the arguments of the original call (<code>args</code>).
662 </li>
663
664 </ul>
665
666
667
668
669 <h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
670
671 <p>
672 Lua performs automatic memory management.
673 This means that
674 you do not have to worry about allocating memory for new objects
675 or freeing it when the objects are no longer needed.
676 Lua manages memory automatically by running
677 a <em>garbage collector</em> to collect all <em>dead objects</em>
678 (that is, objects that are no longer accessible from Lua).
679 All memory used by Lua is subject to automatic management:
680 strings, tables, userdata, functions, threads, internal structures, etc.
681
682
683 <p>
684 Lua implements an incremental mark-and-sweep collector.
685 It uses two numbers to control its garbage-collection cycles:
686 the <em>garbage-collector pause</em> and
687 the <em>garbage-collector step multiplier</em>.
688 Both use percentage points as units
689 (e.g., a value of 100 means an internal value of 1).
690
691
692 <p>
693 The garbage-collector pause
694 controls how long the collector waits before starting a new cycle.
695 Larger values make the collector less aggressive.
696 Values smaller than 100 mean the collector will not wait to
697 start a new cycle.
698 A value of 200 means that the collector waits for the total memory in use
699 to double before starting a new cycle.
700
701
702 <p>
703 The garbage-collector step multiplier
704 controls the relative speed of the collector relative to
705 memory allocation.
706 Larger values make the collector more aggressive but also increase
707 the size of each incremental step.
708 You should not use values smaller than 100,
709 because they make the collector too slow and
710 can result in the collector never finishing a cycle.
711 The default is 200,
712 which means that the collector runs at "twice"
713 the speed of memory allocation.
714
715
716 <p>
717 If you set the step multiplier to a very large number
718 (larger than 10% of the maximum number of
719 bytes that the program may use),
720 the collector behaves like a stop-the-world collector.
721 If you then set the pause to 200,
722 the collector behaves as in old Lua versions,
723 doing a complete collection every time Lua doubles its
724 memory usage.
725
726
727 <p>
728 You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
729 or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
730 You can also use these functions to control
731 the collector directly (e.g., stop and restart it).
732
733
734
735 <h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
736
737 <p>
738 You can set garbage-collector metamethods for tables
739 and, using the C&nbsp;API,
740 for full userdata (see <a href="#2.4">&sect;2.4</a>).
741 These metamethods are also called <em>finalizers</em>.
742 Finalizers allow you to coordinate Lua's garbage collection
743 with external resource management
744 (such as closing files, network or database connections,
745 or freeing your own memory).
746
747
748 <p>
749 For an object (table or userdata) to be finalized when collected,
750 you must <em>mark</em> it for finalization.
751
752 You mark an object for finalization when you set its metatable
753 and the metatable has a field indexed by the string "<code>__gc</code>".
754 Note that if you set a metatable without a <code>__gc</code> field
755 and later create that field in the metatable,
756 the object will not be marked for finalization.
757 However, after an object has been marked,
758 you can freely change the <code>__gc</code> field of its metatable.
759
760
761 <p>
762 When a marked object becomes garbage,
763 it is not collected immediately by the garbage collector.
764 Instead, Lua puts it in a list.
765 After the collection,
766 Lua goes through that list.
767 For each object in the list,
768 it checks the object's <code>__gc</code> metamethod:
769 If it is a function,
770 Lua calls it with the object as its single argument;
771 if the metamethod is not a function,
772 Lua simply ignores it.
773
774
775 <p>
776 At the end of each garbage-collection cycle,
777 the finalizers for objects are called in
778 the reverse order that the objects were marked for finalization,
779 among those collected in that cycle;
780 that is, the first finalizer to be called is the one associated
781 with the object marked last in the program.
782 The execution of each finalizer may occur at any point during
783 the execution of the regular code.
784
785
786 <p>
787 Because the object being collected must still be used by the finalizer,
788 that object (and other objects accessible only through it)
789 must be <em>resurrected</em> by Lua.
790 Usually, this resurrection is transient,
791 and the object memory is freed in the next garbage-collection cycle.
792 However, if the finalizer stores the object in some global place
793 (e.g., a global variable),
794 then the resurrection is permanent.
795 Moreover, if the finalizer marks a finalizing object for finalization again,
796 its finalizer will be called again in the next cycle where the
797 object is unreachable.
798 In any case,
799 the object memory is freed only in the GC cycle where
800 the object is unreachable and not marked for finalization.
801
802
803 <p>
804 When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
805 Lua calls the finalizers of all objects marked for finalization,
806 following the reverse order that they were marked.
807 If any finalizer marks objects for collection during that phase,
808 these marks have no effect.
809
810
811
812
813
814 <h3>2.5.2 &ndash; <a name="2.5.2">Weak Tables</a></h3>
815
816 <p>
817 A <em>weak table</em> is a table whose elements are
818 <em>weak references</em>.
819 A weak reference is ignored by the garbage collector.
820 In other words,
821 if the only references to an object are weak references,
822 then the garbage collector will collect that object.
823
824
825 <p>
826 A weak table can have weak keys, weak values, or both.
827 A table with weak keys allows the collection of its keys,
828 but prevents the collection of its values.
829 A table with both weak keys and weak values allows the collection of
830 both keys and values.
831 In any case, if either the key or the value is collected,
832 the whole pair is removed from the table.
833 The weakness of a table is controlled by the
834 <code>__mode</code> field of its metatable.
835 If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
836 the keys in the table are weak.
837 If <code>__mode</code> contains '<code>v</code>',
838 the values in the table are weak.
839
840
841 <p>
842 A table with weak keys and strong values
843 is also called an <em>ephemeron table</em>.
844 In an ephemeron table,
845 a value is considered reachable only if its key is reachable.
846 In particular,
847 if the only reference to a key comes through its value,
848 the pair is removed.
849
850
851 <p>
852 Any change in the weakness of a table may take effect only
853 at the next collect cycle.
854 In particular, if you change the weakness to a stronger mode,
855 Lua may still collect some items from that table
856 before the change takes effect.
857
858
859 <p>
860 Only objects that have an explicit construction
861 are removed from weak tables.
862 Values, such as numbers and light C functions,
863 are not subject to garbage collection,
864 and therefore are not removed from weak tables
865 (unless their associated values are collected).
866 Although strings are subject to garbage collection,
867 they do not have an explicit construction,
868 and therefore are not removed from weak tables.
869
870
871 <p>
872 Resurrected objects
873 (that is, objects being finalized
874 and objects accessible only through objects being finalized)
875 have a special behavior in weak tables.
876 They are removed from weak values before running their finalizers,
877 but are removed from weak keys only in the next collection
878 after running their finalizers, when such objects are actually freed.
879 This behavior allows the finalizer to access properties
880 associated with the object through weak tables.
881
882
883 <p>
884 If a weak table is among the resurrected objects in a collection cycle,
885 it may not be properly cleared until the next cycle.
886
887
888
889
890
891
892
893 <h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
894
895 <p>
896 Lua supports coroutines,
897 also called <em>collaborative multithreading</em>.
898 A coroutine in Lua represents an independent thread of execution.
899 Unlike threads in multithread systems, however,
900 a coroutine only suspends its execution by explicitly calling
901 a yield function.
902
903
904 <p>
905 You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
906 Its sole argument is a function
907 that is the main function of the coroutine.
908 The <code>create</code> function only creates a new coroutine and
909 returns a handle to it (an object of type <em>thread</em>);
910 it does not start the coroutine.
911
912
913 <p>
914 You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
915 When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
916 passing as its first argument
917 a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
918 the coroutine starts its execution,
919 at the first line of its main function.
920 Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
921 as arguments to the coroutine's main function.
922 After the coroutine starts running,
923 it runs until it terminates or <em>yields</em>.
924
925
926 <p>
927 A coroutine can terminate its execution in two ways:
928 normally, when its main function returns
929 (explicitly or implicitly, after the last instruction);
930 and abnormally, if there is an unprotected error.
931 In case of normal termination,
932 <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
933 plus any values returned by the coroutine main function.
934 In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
935 plus an error message.
936
937
938 <p>
939 A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
940 When a coroutine yields,
941 the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
942 even if the yield happens inside nested function calls
943 (that is, not in the main function,
944 but in a function directly or indirectly called by the main function).
945 In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
946 plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
947 The next time you resume the same coroutine,
948 it continues its execution from the point where it yielded,
949 with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
950 arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
951
952
953 <p>
954 Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
955 the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
956 but instead of returning the coroutine itself,
957 it returns a function that, when called, resumes the coroutine.
958 Any arguments passed to this function
959 go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
960 <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>,
961 except the first one (the boolean error code).
962 Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
963 <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
964 any error is propagated to the caller.
965
966
967 <p>
968 As an example of how coroutines work,
969 consider the following code:
970
971 <pre>
972 function foo (a)
973 print("foo", a)
974 return coroutine.yield(2*a)
975 end
976
977 co = coroutine.create(function (a,b)
978 print("co-body", a, b)
979 local r = foo(a+1)
980 print("co-body", r)
981 local r, s = coroutine.yield(a+b, a-b)
982 print("co-body", r, s)
983 return b, "end"
984 end)
985
986 print("main", coroutine.resume(co, 1, 10))
987 print("main", coroutine.resume(co, "r"))
988 print("main", coroutine.resume(co, "x", "y"))
989 print("main", coroutine.resume(co, "x", "y"))
990 </pre><p>
991 When you run it, it produces the following output:
992
993 <pre>
994 co-body 1 10
995 foo 2
996 main true 4
997 co-body r
998 main true 11 -9
999 co-body x y
1000 main true 10 end
1001 main false cannot resume dead coroutine
1002 </pre>
1003
1004 <p>
1005 You can also create and manipulate coroutines through the C API:
1006 see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1007 and <a href="#lua_yield"><code>lua_yield</code></a>.
1008
1009
1010
1011
1012
1013 <h1>3 &ndash; <a name="3">The Language</a></h1>
1014
1015 <p>
1016 This section describes the lexis, the syntax, and the semantics of Lua.
1017 In other words,
1018 this section describes
1019 which tokens are valid,
1020 how they can be combined,
1021 and what their combinations mean.
1022
1023
1024 <p>
1025 Language constructs will be explained using the usual extended BNF notation,
1026 in which
1027 {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1028 [<em>a</em>]&nbsp;means an optional <em>a</em>.
1029 Non-terminals are shown like non-terminal,
1030 keywords are shown like <b>kword</b>,
1031 and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1032 The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1033 at the end of this manual.
1034
1035
1036
1037 <h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1038
1039 <p>
1040 Lua is a free-form language.
1041 It ignores spaces (including new lines) and comments
1042 between lexical elements (tokens),
1043 except as delimiters between names and keywords.
1044
1045
1046 <p>
1047 <em>Names</em>
1048 (also called <em>identifiers</em>)
1049 in Lua can be any string of letters,
1050 digits, and underscores,
1051 not beginning with a digit.
1052 Identifiers are used to name variables, table fields, and labels.
1053
1054
1055 <p>
1056 The following <em>keywords</em> are reserved
1057 and cannot be used as names:
1058
1059
1060 <pre>
1061 and break do else elseif end
1062 false for function goto if in
1063 local nil not or repeat return
1064 then true until while
1065 </pre>
1066
1067 <p>
1068 Lua is a case-sensitive language:
1069 <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1070 are two different, valid names.
1071 As a convention,
1072 programs should avoid creating
1073 names that start with an underscore followed by
1074 one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1075
1076
1077 <p>
1078 The following strings denote other tokens:
1079
1080 <pre>
1081 + - * / % ^ #
1082 &amp; ~ | &lt;&lt; &gt;&gt; //
1083 == ~= &lt;= &gt;= &lt; &gt; =
1084 ( ) { } [ ] ::
1085 ; : , . .. ...
1086 </pre>
1087
1088 <p>
1089 <em>Literal strings</em>
1090 can be delimited by matching single or double quotes,
1091 and can contain the following C-like escape sequences:
1092 '<code>\a</code>' (bell),
1093 '<code>\b</code>' (backspace),
1094 '<code>\f</code>' (form feed),
1095 '<code>\n</code>' (newline),
1096 '<code>\r</code>' (carriage return),
1097 '<code>\t</code>' (horizontal tab),
1098 '<code>\v</code>' (vertical tab),
1099 '<code>\\</code>' (backslash),
1100 '<code>\"</code>' (quotation mark [double quote]),
1101 and '<code>\'</code>' (apostrophe [single quote]).
1102 A backslash followed by a real newline
1103 results in a newline in the string.
1104 The escape sequence '<code>\z</code>' skips the following span
1105 of white-space characters,
1106 including line breaks;
1107 it is particularly useful to break and indent a long literal string
1108 into multiple lines without adding the newlines and spaces
1109 into the string contents.
1110
1111
1112 <p>
1113 Strings in Lua can contain any 8-bit value, including embedded zeros,
1114 which can be specified as '<code>\0</code>'.
1115 More generally,
1116 we can specify any byte in a literal string by its numerical value.
1117 This can be done
1118 with the escape sequence <code>\x<em>XX</em></code>,
1119 where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1120 or with the escape sequence <code>\<em>ddd</em></code>,
1121 where <em>ddd</em> is a sequence of up to three decimal digits.
1122 (Note that if a decimal escape sequence is to be followed by a digit,
1123 it must be expressed using exactly three digits.)
1124
1125
1126 <p>
1127 The UTF-8 encoding of a Unicode character
1128 can be inserted in a literal string with
1129 the escape sequence <code>\u{<em>XXX</em>}</code>
1130 (note the mandatory enclosing brackets),
1131 where <em>XXX</em> is a sequence of one or more hexadecimal digits
1132 representing the character code point.
1133
1134
1135 <p>
1136 Literal strings can also be defined using a long format
1137 enclosed by <em>long brackets</em>.
1138 We define an <em>opening long bracket of level <em>n</em></em> as an opening
1139 square bracket followed by <em>n</em> equal signs followed by another
1140 opening square bracket.
1141 So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1142 an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1143 and so on.
1144 A <em>closing long bracket</em> is defined similarly;
1145 for instance,
1146 a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
1147 A <em>long literal</em> starts with an opening long bracket of any level and
1148 ends at the first closing long bracket of the same level.
1149 It can contain any text except a closing bracket of the same level.
1150 Literals in this bracketed form can run for several lines,
1151 do not interpret any escape sequences,
1152 and ignore long brackets of any other level.
1153 Any kind of end-of-line sequence
1154 (carriage return, newline, carriage return followed by newline,
1155 or newline followed by carriage return)
1156 is converted to a simple newline.
1157
1158
1159 <p>
1160 Any byte in a literal string not
1161 explicitly affected by the previous rules represents itself.
1162 However, Lua opens files for parsing in text mode,
1163 and the system file functions may have problems with
1164 some control characters.
1165 So, it is safer to represent
1166 non-text data as a quoted literal with
1167 explicit escape sequences for non-text characters.
1168
1169
1170 <p>
1171 For convenience,
1172 when the opening long bracket is immediately followed by a newline,
1173 the newline is not included in the string.
1174 As an example, in a system using ASCII
1175 (in which '<code>a</code>' is coded as&nbsp;97,
1176 newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1177 the five literal strings below denote the same string:
1178
1179 <pre>
1180 a = 'alo\n123"'
1181 a = "alo\n123\""
1182 a = '\97lo\10\04923"'
1183 a = [[alo
1184 123"]]
1185 a = [==[
1186 alo
1187 123"]==]
1188 </pre>
1189
1190 <p>
1191 A <em>numerical constant</em> (or <em>numeral</em>)
1192 can be written with an optional fractional part
1193 and an optional decimal exponent,
1194 marked by a letter '<code>e</code>' or '<code>E</code>'.
1195 Lua also accepts hexadecimal constants,
1196 which start with <code>0x</code> or <code>0X</code>.
1197 Hexadecimal constants also accept an optional fractional part
1198 plus an optional binary exponent,
1199 marked by a letter '<code>p</code>' or '<code>P</code>'.
1200 A numeric constant with a fractional dot or an exponent
1201 denotes a float;
1202 otherwise it denotes an integer.
1203 Examples of valid integer constants are
1204
1205 <pre>
1206 3 345 0xff 0xBEBADA
1207 </pre><p>
1208 Examples of valid float constants are
1209
1210 <pre>
1211 3.0 3.1416 314.16e-2 0.31416E1 34e1
1212 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1213 </pre>
1214
1215 <p>
1216 A <em>comment</em> starts with a double hyphen (<code>--</code>)
1217 anywhere outside a string.
1218 If the text immediately after <code>--</code> is not an opening long bracket,
1219 the comment is a <em>short comment</em>,
1220 which runs until the end of the line.
1221 Otherwise, it is a <em>long comment</em>,
1222 which runs until the corresponding closing long bracket.
1223 Long comments are frequently used to disable code temporarily.
1224
1225
1226
1227
1228
1229 <h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1230
1231 <p>
1232 Variables are places that store values.
1233 There are three kinds of variables in Lua:
1234 global variables, local variables, and table fields.
1235
1236
1237 <p>
1238 A single name can denote a global variable or a local variable
1239 (or a function's formal parameter,
1240 which is a particular kind of local variable):
1241
1242 <pre>
1243 var ::= Name
1244 </pre><p>
1245 Name denotes identifiers, as defined in <a href="#3.1">&sect;3.1</a>.
1246
1247
1248 <p>
1249 Any variable name is assumed to be global unless explicitly declared
1250 as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1251 Local variables are <em>lexically scoped</em>:
1252 local variables can be freely accessed by functions
1253 defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1254
1255
1256 <p>
1257 Before the first assignment to a variable, its value is <b>nil</b>.
1258
1259
1260 <p>
1261 Square brackets are used to index a table:
1262
1263 <pre>
1264 var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1265 </pre><p>
1266 The meaning of accesses to table fields can be changed via metatables.
1267 An access to an indexed variable <code>t[i]</code> is equivalent to
1268 a call <code>gettable_event(t,i)</code>.
1269 (See <a href="#2.4">&sect;2.4</a> for a complete description of the
1270 <code>gettable_event</code> function.
1271 This function is not defined or callable in Lua.
1272 We use it here only for explanatory purposes.)
1273
1274
1275 <p>
1276 The syntax <code>var.Name</code> is just syntactic sugar for
1277 <code>var["Name"]</code>:
1278
1279 <pre>
1280 var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1281 </pre>
1282
1283 <p>
1284 An access to a global variable <code>x</code>
1285 is equivalent to <code>_ENV.x</code>.
1286 Due to the way that chunks are compiled,
1287 <code>_ENV</code> is never a global name (see <a href="#2.2">&sect;2.2</a>).
1288
1289
1290
1291
1292
1293 <h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1294
1295 <p>
1296 Lua supports an almost conventional set of statements,
1297 similar to those in Pascal or C.
1298 This set includes
1299 assignments, control structures, function calls,
1300 and variable declarations.
1301
1302
1303
1304 <h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1305
1306 <p>
1307 A block is a list of statements,
1308 which are executed sequentially:
1309
1310 <pre>
1311 block ::= {stat}
1312 </pre><p>
1313 Lua has <em>empty statements</em>
1314 that allow you to separate statements with semicolons,
1315 start a block with a semicolon
1316 or write two semicolons in sequence:
1317
1318 <pre>
1319 stat ::= &lsquo;<b>;</b>&rsquo;
1320 </pre>
1321
1322 <p>
1323 Function calls and assignments
1324 can start with an open parenthesis.
1325 This possibility leads to an ambiguity in Lua's grammar.
1326 Consider the following fragment:
1327
1328 <pre>
1329 a = b + c
1330 (print or io.write)('done')
1331 </pre><p>
1332 The grammar could see it in two ways:
1333
1334 <pre>
1335 a = b + c(print or io.write)('done')
1336
1337 a = b + c; (print or io.write)('done')
1338 </pre><p>
1339 The current parser always sees such constructions
1340 in the first way,
1341 interpreting the open parenthesis
1342 as the start of the arguments to a call.
1343 To avoid this ambiguity,
1344 it is a good practice to always precede with a semicolon
1345 statements that start with a parenthesis:
1346
1347 <pre>
1348 ;(print or io.write)('done')
1349 </pre>
1350
1351 <p>
1352 A block can be explicitly delimited to produce a single statement:
1353
1354 <pre>
1355 stat ::= <b>do</b> block <b>end</b>
1356 </pre><p>
1357 Explicit blocks are useful
1358 to control the scope of variable declarations.
1359 Explicit blocks are also sometimes used to
1360 add a <b>return</b> statement in the middle
1361 of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1362
1363
1364
1365
1366
1367 <h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1368
1369 <p>
1370 The unit of compilation of Lua is called a <em>chunk</em>.
1371 Syntactically,
1372 a chunk is simply a block:
1373
1374 <pre>
1375 chunk ::= block
1376 </pre>
1377
1378 <p>
1379 Lua handles a chunk as the body of an anonymous function
1380 with a variable number of arguments
1381 (see <a href="#3.4.11">&sect;3.4.11</a>).
1382 As such, chunks can define local variables,
1383 receive arguments, and return values.
1384 Moreover, such anonymous function is compiled as in the
1385 scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1386 The resulting function always has <code>_ENV</code> as its only upvalue,
1387 even if it does not use that variable.
1388
1389
1390 <p>
1391 A chunk can be stored in a file or in a string inside the host program.
1392 To execute a chunk,
1393 Lua first <em>loads</em> it,
1394 precompiling the chunk's code into instructions for a virtual machine,
1395 and then Lua executes the compiled code
1396 with an interpreter for the virtual machine.
1397
1398
1399 <p>
1400 Chunks can also be precompiled into binary form;
1401 see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1402 Programs in source and compiled forms are interchangeable;
1403 Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1404
1405
1406
1407
1408
1409 <h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1410
1411 <p>
1412 Lua allows multiple assignments.
1413 Therefore, the syntax for assignment
1414 defines a list of variables on the left side
1415 and a list of expressions on the right side.
1416 The elements in both lists are separated by commas:
1417
1418 <pre>
1419 stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1420 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1421 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1422 </pre><p>
1423 Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1424
1425
1426 <p>
1427 Before the assignment,
1428 the list of values is <em>adjusted</em> to the length of
1429 the list of variables.
1430 If there are more values than needed,
1431 the excess values are thrown away.
1432 If there are fewer values than needed,
1433 the list is extended with as many <b>nil</b>'s as needed.
1434 If the list of expressions ends with a function call,
1435 then all values returned by that call enter the list of values,
1436 before the adjustment
1437 (except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1438
1439
1440 <p>
1441 The assignment statement first evaluates all its expressions
1442 and only then the assignments are performed.
1443 Thus the code
1444
1445 <pre>
1446 i = 3
1447 i, a[i] = i+1, 20
1448 </pre><p>
1449 sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1450 because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1451 before it is assigned&nbsp;4.
1452 Similarly, the line
1453
1454 <pre>
1455 x, y = y, x
1456 </pre><p>
1457 exchanges the values of <code>x</code> and <code>y</code>,
1458 and
1459
1460 <pre>
1461 x, y, z = y, z, x
1462 </pre><p>
1463 cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1464
1465
1466 <p>
1467 The meaning of assignments to global variables
1468 and table fields can be changed via metatables.
1469 An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
1470 <code>settable_event(t,i,val)</code>.
1471 (See <a href="#2.4">&sect;2.4</a> for a complete description of the
1472 <code>settable_event</code> function.
1473 This function is not defined or callable in Lua.
1474 We use it here only for explanatory purposes.)
1475
1476
1477 <p>
1478 An assignment to a global name <code>x = val</code>
1479 is equivalent to the assignment
1480 <code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1481
1482
1483
1484
1485
1486 <h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1487 The control structures
1488 <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1489 familiar syntax:
1490
1491
1492
1493
1494 <pre>
1495 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1496 stat ::= <b>repeat</b> block <b>until</b> exp
1497 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1498 </pre><p>
1499 Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1500
1501
1502 <p>
1503 The condition expression of a
1504 control structure can return any value.
1505 Both <b>false</b> and <b>nil</b> are considered false.
1506 All values different from <b>nil</b> and <b>false</b> are considered true
1507 (in particular, the number 0 and the empty string are also true).
1508
1509
1510 <p>
1511 In the <b>repeat</b>&ndash;<b>until</b> loop,
1512 the inner block does not end at the <b>until</b> keyword,
1513 but only after the condition.
1514 So, the condition can refer to local variables
1515 declared inside the loop block.
1516
1517
1518 <p>
1519 The <b>goto</b> statement transfers the program control to a label.
1520 For syntactical reasons,
1521 labels in Lua are considered statements too:
1522
1523
1524
1525 <pre>
1526 stat ::= <b>goto</b> Name
1527 stat ::= label
1528 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1529 </pre>
1530
1531 <p>
1532 A label is visible in the entire block where it is defined,
1533 except
1534 inside nested blocks where a label with the same name is defined and
1535 inside nested functions.
1536 A goto may jump to any visible label as long as it does not
1537 enter into the scope of a local variable.
1538
1539
1540 <p>
1541 Labels and empty statements are called <em>void statements</em>,
1542 as they perform no actions.
1543
1544
1545 <p>
1546 The <b>break</b> statement terminates the execution of a
1547 <b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1548 skipping to the next statement after the loop:
1549
1550
1551 <pre>
1552 stat ::= <b>break</b>
1553 </pre><p>
1554 A <b>break</b> ends the innermost enclosing loop.
1555
1556
1557 <p>
1558 The <b>return</b> statement is used to return values
1559 from a function or a chunk
1560 (which is an anonymous function).
1561
1562 Functions can return more than one value,
1563 so the syntax for the <b>return</b> statement is
1564
1565 <pre>
1566 stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1567 </pre>
1568
1569 <p>
1570 The <b>return</b> statement can only be written
1571 as the last statement of a block.
1572 If it is really necessary to <b>return</b> in the middle of a block,
1573 then an explicit inner block can be used,
1574 as in the idiom <code>do return end</code>,
1575 because now <b>return</b> is the last statement in its (inner) block.
1576
1577
1578
1579
1580
1581 <h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1582
1583 <p>
1584
1585 The <b>for</b> statement has two forms:
1586 one numeric and one generic.
1587
1588
1589 <p>
1590 The numeric <b>for</b> loop repeats a block of code while a
1591 control variable runs through an arithmetic progression.
1592 It has the following syntax:
1593
1594 <pre>
1595 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>
1596 </pre><p>
1597 The <em>block</em> is repeated for <em>name</em> starting at the value of
1598 the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
1599 third <em>exp</em>.
1600 More precisely, a <b>for</b> statement like
1601
1602 <pre>
1603 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
1604 </pre><p>
1605 is equivalent to the code:
1606
1607 <pre>
1608 do
1609 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
1610 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
1611 <em>var</em> = <em>var</em> - <em>step</em>
1612 while true do
1613 <em>var</em> = <em>var</em> + <em>step</em>
1614 if (<em>step</em> &gt;= 0 and <em>var</em> &gt; <em>limit</em>) or (<em>step</em> &lt; 0 and <em>var</em> &lt; <em>limit</em>) then
1615 break
1616 end
1617 local v = <em>var</em>
1618 <em>block</em>
1619 end
1620 end
1621 </pre>
1622
1623 <p>
1624 Note the following:
1625
1626 <ul>
1627
1628 <li>
1629 All three control expressions are evaluated only once,
1630 before the loop starts.
1631 They must all result in numbers.
1632 </li>
1633
1634 <li>
1635 <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
1636 The names shown here are for explanatory purposes only.
1637 </li>
1638
1639 <li>
1640 If the third expression (the step) is absent,
1641 then a step of&nbsp;1 is used.
1642 </li>
1643
1644 <li>
1645 You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop.
1646 </li>
1647
1648 <li>
1649 The loop variable <code>v</code> is local to the loop body.
1650 If you need its value after the loop,
1651 assign it to another variable before exiting the loop.
1652 </li>
1653
1654 </ul>
1655
1656 <p>
1657 The generic <b>for</b> statement works over functions,
1658 called <em>iterators</em>.
1659 On each iteration, the iterator function is called to produce a new value,
1660 stopping when this new value is <b>nil</b>.
1661 The generic <b>for</b> loop has the following syntax:
1662
1663 <pre>
1664 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1665 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1666 </pre><p>
1667 A <b>for</b> statement like
1668
1669 <pre>
1670 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
1671 </pre><p>
1672 is equivalent to the code:
1673
1674 <pre>
1675 do
1676 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
1677 while true do
1678 local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
1679 if <em>var_1</em> == nil then break end
1680 <em>var</em> = <em>var_1</em>
1681 <em>block</em>
1682 end
1683 end
1684 </pre><p>
1685 Note the following:
1686
1687 <ul>
1688
1689 <li>
1690 <code><em>explist</em></code> is evaluated only once.
1691 Its results are an <em>iterator</em> function,
1692 a <em>state</em>,
1693 and an initial value for the first <em>iterator variable</em>.
1694 </li>
1695
1696 <li>
1697 <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
1698 The names are here for explanatory purposes only.
1699 </li>
1700
1701 <li>
1702 You can use <b>break</b> to exit a <b>for</b> loop.
1703 </li>
1704
1705 <li>
1706 The loop variables <code><em>var_i</em></code> are local to the loop;
1707 you cannot use their values after the <b>for</b> ends.
1708 If you need these values,
1709 then assign them to other variables before breaking or exiting the loop.
1710 </li>
1711
1712 </ul>
1713
1714
1715
1716
1717 <h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1718 To allow possible side-effects,
1719 function calls can be executed as statements:
1720
1721 <pre>
1722 stat ::= functioncall
1723 </pre><p>
1724 In this case, all returned values are thrown away.
1725 Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1726
1727
1728
1729
1730
1731 <h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1732 Local variables can be declared anywhere inside a block.
1733 The declaration can include an initial assignment:
1734
1735 <pre>
1736 stat ::= <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
1737 </pre><p>
1738 If present, an initial assignment has the same semantics
1739 of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1740 Otherwise, all variables are initialized with <b>nil</b>.
1741
1742
1743 <p>
1744 A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1745 and so local variables can be declared in a chunk outside any explicit block.
1746
1747
1748 <p>
1749 The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1750
1751
1752
1753
1754
1755
1756
1757 <h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
1758
1759 <p>
1760 The basic expressions in Lua are the following:
1761
1762 <pre>
1763 exp ::= prefixexp
1764 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1765 exp ::= Numeral
1766 exp ::= LiteralString
1767 exp ::= functiondef
1768 exp ::= tableconstructor
1769 exp ::= &lsquo;<b>...</b>&rsquo;
1770 exp ::= exp binop exp
1771 exp ::= unop exp
1772 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1773 </pre>
1774
1775 <p>
1776 Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1777 variables are explained in <a href="#3.2">&sect;3.2</a>;
1778 function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
1779 function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1780 table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
1781 Vararg expressions,
1782 denoted by three dots ('<code>...</code>'), can only be used when
1783 directly inside a vararg function;
1784 they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
1785
1786
1787 <p>
1788 Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
1789 bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
1790 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>),
1791 and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
1792 Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
1793 the unary bitwise not (see <a href="#3.4.2">&sect;3.4.2</a>),
1794 the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
1795 and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
1796
1797
1798 <p>
1799 Both function calls and vararg expressions can result in multiple values.
1800 If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
1801 then its return list is adjusted to zero elements,
1802 thus discarding all returned values.
1803 If an expression is used as the last (or the only) element
1804 of a list of expressions,
1805 then no adjustment is made
1806 (unless the expression is enclosed in parentheses).
1807 In all other contexts,
1808 Lua adjusts the result list to one element,
1809 either discarding all values except the first one
1810 or adding a single <b>nil</b> if there are no values.
1811
1812
1813 <p>
1814 Here are some examples:
1815
1816 <pre>
1817 f() -- adjusted to 0 results
1818 g(f(), x) -- f() is adjusted to 1 result
1819 g(x, f()) -- g gets x plus all results from f()
1820 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
1821 a,b = ... -- a gets the first vararg parameter, b gets
1822 -- the second (both a and b can get nil if there
1823 -- is no corresponding vararg parameter)
1824
1825 a,b,c = x, f() -- f() is adjusted to 2 results
1826 a,b,c = f() -- f() is adjusted to 3 results
1827 return f() -- returns all results from f()
1828 return ... -- returns all received vararg parameters
1829 return x,y,f() -- returns x, y, and all results from f()
1830 {f()} -- creates a list with all results from f()
1831 {...} -- creates a list with all vararg parameters
1832 {f(), nil} -- f() is adjusted to 1 result
1833 </pre>
1834
1835 <p>
1836 Any expression enclosed in parentheses always results in only one value.
1837 Thus,
1838 <code>(f(x,y,z))</code> is always a single value,
1839 even if <code>f</code> returns several values.
1840 (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
1841 or <b>nil</b> if <code>f</code> does not return any values.)
1842
1843
1844
1845 <h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1846 Lua supports the following arithmetic operators:
1847
1848 <ul>
1849 <li><b><code>+</code>: </b>addition</li>
1850 <li><b><code>-</code>: </b>subtraction</li>
1851 <li><b><code>*</code>: </b>multiplication</li>
1852 <li><b><code>/</code>: </b>float division</li>
1853 <li><b><code>//</code>: </b>floor division</li>
1854 <li><b><code>%</code>: </b>modulo</li>
1855 <li><b><code>^</code>: </b>exponentiation</li>
1856 <li><b><code>-</code>: </b>unary minus</li>
1857 </ul>
1858
1859 <p>
1860 With the exception of exponentiation and float division,
1861 the arithmetic operators work as follows:
1862 If both operands are integers,
1863 the operation is performed over integers and the result is an integer.
1864 Otherwise, if both operands are numbers
1865 or strings that can be converted to
1866 numbers (see <a href="#3.4.3">&sect;3.4.3</a>),
1867 then they are converted to floats,
1868 the operation is performed following the usual rules
1869 for floating-point arithmetic
1870 (usually the IEEE 754 standard),
1871 and the result is a float.
1872
1873
1874 <p>
1875 Exponentiation and float division (<code>/</code>)
1876 always convert their operands to floats
1877 and the result is always a float.
1878 Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
1879 so that it works for non-integer exponents too.
1880
1881
1882 <p>
1883 Floor division (<code>//</code>) is a division
1884 that rounds the quotient towards minus infinite,
1885 that is, the floor of the division of its operands.
1886
1887
1888 <p>
1889 Modulo is defined as the remainder of a division
1890 that rounds the quotient towards minus infinite (floor division).
1891
1892
1893 <p>
1894 In case of overflows in integer arithmetic,
1895 all operations <em>wrap around</em>,
1896 according to the usual rules of two-complement arithmetic.
1897 (In other words,
1898 they return the unique representable integer
1899 that is equal modulo <em>2<sup>64</sup></em> to the mathematical result.)
1900
1901
1902
1903 <h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
1904 Lua supports the following bitwise operators:
1905
1906 <ul>
1907 <li><b><code>&amp;</code>: </b>bitwise and</li>
1908 <li><b><code>&#124;</code>: </b>bitwise or</li>
1909 <li><b><code>~</code>: </b>bitwise exclusive or</li>
1910 <li><b><code>&gt;&gt;</code>: </b>right shift</li>
1911 <li><b><code>&lt;&lt;</code>: </b>left shift</li>
1912 <li><b><code>~</code>: </b>unary bitwise not</li>
1913 </ul>
1914
1915 <p>
1916 All bitwise operations convert its operands to integers
1917 (see <a href="#3.4.3">&sect;3.4.3</a>),
1918 operate on all bits of those integers,
1919 and result in an integer.
1920
1921
1922 <p>
1923 Both right and left shifts fill the vacant bits with zeros.
1924 Negative displacements shift to the other direction;
1925 displacements with absolute values equal to or higher than
1926 the number of bits in an integer
1927 result in zero (as all bits are shifted out).
1928
1929
1930
1931
1932
1933 <h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
1934 Lua provides some automatic conversions between some
1935 types and representations at run time.
1936 Bitwise operators always convert float operands to integers.
1937 Exponentiation and float division
1938 always convert integer operands to floats.
1939 All other arithmetic operations applied to mixed numbers
1940 (integers and floats) convert the integer operand to a float;
1941 this is called the <em>usual rule</em>.
1942 The C API also converts both integers to floats and
1943 floats to integers, as needed.
1944 Moreover, string concatenation accepts numbers as arguments,
1945 besides strings.
1946
1947
1948 <p>
1949 Lua also converts strings to numbers,
1950 whenever a number is expected.
1951
1952
1953 <p>
1954 In a conversion from integer to float,
1955 if the integer value has an exact representation as a float,
1956 that is the result.
1957 Otherwise,
1958 the conversion gets the nearest higher or
1959 the nearest lower representable value.
1960 This kind of conversion never fails.
1961
1962
1963 <p>
1964 The conversion from float to integer
1965 checks whether the float has an exact representation as an integer
1966 (that is, the float has an integral value and
1967 it is in the range of integer representation).
1968 If it does, that representation is the result.
1969 Otherwise, the conversion fails.
1970
1971
1972 <p>
1973 The conversion from strings to numbers goes as follows:
1974 First, the string is converted to an integer or a float,
1975 following its syntax and the rules of the Lua lexer.
1976 (The string may have also leading and trailing spaces and a sign.)
1977 Then, the resulting number is converted to the required type
1978 (float or integer) according to the previous rules.
1979
1980
1981 <p>
1982 The conversion from numbers to strings uses a
1983 non-specified human-readable format.
1984 For complete control over how numbers are converted to strings,
1985 use the <code>format</code> function from the string library
1986 (see <a href="#pdf-string.format"><code>string.format</code></a>).
1987
1988
1989
1990
1991
1992 <h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
1993 Lua supports the following relational operators:
1994
1995 <ul>
1996 <li><b><code>==</code>: </b>equality</li>
1997 <li><b><code>~=</code>: </b>inequality</li>
1998 <li><b><code>&lt;</code>: </b>less than</li>
1999 <li><b><code>&gt;</code>: </b>greater than</li>
2000 <li><b><code>&lt;=</code>: </b>less or equal</li>
2001 <li><b><code>&gt;=</code>: </b>greater or equal</li>
2002 </ul><p>
2003 These operators always result in <b>false</b> or <b>true</b>.
2004
2005
2006 <p>
2007 Equality (<code>==</code>) first compares the type of its operands.
2008 If the types are different, then the result is <b>false</b>.
2009 Otherwise, the values of the operands are compared.
2010 Strings are compared in the obvious way.
2011 Numbers follow the usual rule for binary operations:
2012 if both operands are integers,
2013 they are compared as integers;
2014 otherwise, they are converted to floats
2015 and compared as such.
2016
2017
2018 <p>
2019 Tables, userdata, and threads
2020 are compared by reference:
2021 two objects are considered equal only if they are the same object.
2022 Every time you create a new object
2023 (a table, userdata, or thread),
2024 this new object is different from any previously existing object.
2025 Closures with the same reference are always equal.
2026 Closures with any detectable difference
2027 (different behavior, different definition) are always different.
2028
2029
2030 <p>
2031 You can change the way that Lua compares tables and userdata
2032 by using the "eq" metamethod (see <a href="#2.4">&sect;2.4</a>).
2033
2034
2035 <p>
2036 Equality comparisons do not convert strings to numbers
2037 or vice versa.
2038 Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2039 and <code>t[0]</code> and <code>t["0"]</code> denote different
2040 entries in a table.
2041
2042
2043 <p>
2044 The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2045
2046
2047 <p>
2048 The order operators work as follows.
2049 If both arguments are numbers,
2050 then they are compared following
2051 the usual rule for binary operations.
2052 Otherwise, if both arguments are strings,
2053 then their values are compared according to the current locale.
2054 Otherwise, Lua tries to call the "lt" or the "le"
2055 metamethod (see <a href="#2.4">&sect;2.4</a>).
2056 A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2057 and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2058
2059
2060
2061
2062
2063 <h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2064 The logical operators in Lua are
2065 <b>and</b>, <b>or</b>, and <b>not</b>.
2066 Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2067 all logical operators consider both <b>false</b> and <b>nil</b> as false
2068 and anything else as true.
2069
2070
2071 <p>
2072 The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2073 The conjunction operator <b>and</b> returns its first argument
2074 if this value is <b>false</b> or <b>nil</b>;
2075 otherwise, <b>and</b> returns its second argument.
2076 The disjunction operator <b>or</b> returns its first argument
2077 if this value is different from <b>nil</b> and <b>false</b>;
2078 otherwise, <b>or</b> returns its second argument.
2079 Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2080 that is,
2081 the second operand is evaluated only if necessary.
2082 Here are some examples:
2083
2084 <pre>
2085 10 or 20 --&gt; 10
2086 10 or error() --&gt; 10
2087 nil or "a" --&gt; "a"
2088 nil and 10 --&gt; nil
2089 false and error() --&gt; false
2090 false and nil --&gt; false
2091 false or nil --&gt; nil
2092 10 and 20 --&gt; 20
2093 </pre><p>
2094 (In this manual,
2095 <code>--&gt;</code> indicates the result of the preceding expression.)
2096
2097
2098
2099
2100
2101 <h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2102 The string concatenation operator in Lua is
2103 denoted by two dots ('<code>..</code>').
2104 If both operands are strings or numbers, then they are converted to
2105 strings according to the rules described in <a href="#3.4.3">&sect;3.4.3</a>.
2106 Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2107
2108
2109
2110
2111
2112 <h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2113
2114 <p>
2115 The length operator is denoted by the unary prefix operator <code>#</code>.
2116 The length of a string is its number of bytes
2117 (that is, the usual meaning of string length when each
2118 character is one byte).
2119
2120
2121 <p>
2122 A program can modify the behavior of the length operator for
2123 any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2124
2125
2126 <p>
2127 Unless a <code>__len</code> metamethod is given,
2128 the length of a table <code>t</code> is only defined if the
2129 table is a <em>sequence</em>,
2130 that is,
2131 the set of its positive numeric keys is equal to <em>{1..n}</em>
2132 for some non-negative integer <em>n</em>.
2133 In that case, <em>n</em> is its length.
2134 Note that a table like
2135
2136 <pre>
2137 {10, 20, nil, 40}
2138 </pre><p>
2139 is not a sequence, because it has the key <code>4</code>
2140 but does not have the key <code>3</code>.
2141 (So, there is no <em>n</em> such that the set <em>{1..n}</em> is equal
2142 to the set of positive numeric keys of that table.)
2143 Note, however, that non-numeric keys do not interfere
2144 with whether a table is a sequence.
2145
2146
2147
2148
2149
2150 <h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2151 Operator precedence in Lua follows the table below,
2152 from lower to higher priority:
2153
2154 <pre>
2155 or
2156 and
2157 &lt; &gt; &lt;= &gt;= ~= ==
2158 |
2159 ~
2160 &amp;
2161 &lt;&lt; &gt;&gt;
2162 ..
2163 + -
2164 * / // %
2165 unary operators (not # - ~)
2166 ^
2167 </pre><p>
2168 As usual,
2169 you can use parentheses to change the precedences of an expression.
2170 The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2171 operators are right associative.
2172 All other binary operators are left associative.
2173
2174
2175
2176
2177
2178 <h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2179 Table constructors are expressions that create tables.
2180 Every time a constructor is evaluated, a new table is created.
2181 A constructor can be used to create an empty table
2182 or to create a table and initialize some of its fields.
2183 The general syntax for constructors is
2184
2185 <pre>
2186 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2187 fieldlist ::= field {fieldsep field} [fieldsep]
2188 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2189 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2190 </pre>
2191
2192 <p>
2193 Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2194 with key <code>exp1</code> and value <code>exp2</code>.
2195 A field of the form <code>name = exp</code> is equivalent to
2196 <code>["name"] = exp</code>.
2197 Finally, fields of the form <code>exp</code> are equivalent to
2198 <code>[i] = exp</code>, where <code>i</code> are consecutive integers
2199 starting with 1.
2200 Fields in the other formats do not affect this counting.
2201 For example,
2202
2203 <pre>
2204 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2205 </pre><p>
2206 is equivalent to
2207
2208 <pre>
2209 do
2210 local t = {}
2211 t[f(1)] = g
2212 t[1] = "x" -- 1st exp
2213 t[2] = "y" -- 2nd exp
2214 t.x = 1 -- t["x"] = 1
2215 t[3] = f(x) -- 3rd exp
2216 t[30] = 23
2217 t[4] = 45 -- 4th exp
2218 a = t
2219 end
2220 </pre>
2221
2222 <p>
2223 The order of the assignments in a constructor is undefined.
2224 (This order would be relevant only when there are repeated keys.)
2225
2226
2227 <p>
2228 If the last field in the list has the form <code>exp</code>
2229 and the expression is a function call or a vararg expression,
2230 then all values returned by this expression enter the list consecutively
2231 (see <a href="#3.4.10">&sect;3.4.10</a>).
2232
2233
2234 <p>
2235 The field list can have an optional trailing separator,
2236 as a convenience for machine-generated code.
2237
2238
2239
2240
2241
2242 <h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2243 A function call in Lua has the following syntax:
2244
2245 <pre>
2246 functioncall ::= prefixexp args
2247 </pre><p>
2248 In a function call,
2249 first prefixexp and args are evaluated.
2250 If the value of prefixexp has type <em>function</em>,
2251 then this function is called
2252 with the given arguments.
2253 Otherwise, the prefixexp "call" metamethod is called,
2254 having as first parameter the value of prefixexp,
2255 followed by the original call arguments
2256 (see <a href="#2.4">&sect;2.4</a>).
2257
2258
2259 <p>
2260 The form
2261
2262 <pre>
2263 functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2264 </pre><p>
2265 can be used to call "methods".
2266 A call <code>v:name(<em>args</em>)</code>
2267 is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2268 except that <code>v</code> is evaluated only once.
2269
2270
2271 <p>
2272 Arguments have the following syntax:
2273
2274 <pre>
2275 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2276 args ::= tableconstructor
2277 args ::= LiteralString
2278 </pre><p>
2279 All argument expressions are evaluated before the call.
2280 A call of the form <code>f{<em>fields</em>}</code> is
2281 syntactic sugar for <code>f({<em>fields</em>})</code>;
2282 that is, the argument list is a single new table.
2283 A call of the form <code>f'<em>string</em>'</code>
2284 (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2285 is syntactic sugar for <code>f('<em>string</em>')</code>;
2286 that is, the argument list is a single literal string.
2287
2288
2289 <p>
2290 A call of the form <code>return <em>functioncall</em></code> is called
2291 a <em>tail call</em>.
2292 Lua implements <em>proper tail calls</em>
2293 (or <em>proper tail recursion</em>):
2294 in a tail call,
2295 the called function reuses the stack entry of the calling function.
2296 Therefore, there is no limit on the number of nested tail calls that
2297 a program can execute.
2298 However, a tail call erases any debug information about the
2299 calling function.
2300 Note that a tail call only happens with a particular syntax,
2301 where the <b>return</b> has one single function call as argument;
2302 this syntax makes the calling function return exactly
2303 the returns of the called function.
2304 So, none of the following examples are tail calls:
2305
2306 <pre>
2307 return (f(x)) -- results adjusted to 1
2308 return 2 * f(x)
2309 return x, f(x) -- additional results
2310 f(x); return -- results discarded
2311 return x or f(x) -- results adjusted to 1
2312 </pre>
2313
2314
2315
2316
2317 <h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2318
2319 <p>
2320 The syntax for function definition is
2321
2322 <pre>
2323 functiondef ::= <b>function</b> funcbody
2324 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2325 </pre>
2326
2327 <p>
2328 The following syntactic sugar simplifies function definitions:
2329
2330 <pre>
2331 stat ::= <b>function</b> funcname funcbody
2332 stat ::= <b>local</b> <b>function</b> Name funcbody
2333 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2334 </pre><p>
2335 The statement
2336
2337 <pre>
2338 function f () <em>body</em> end
2339 </pre><p>
2340 translates to
2341
2342 <pre>
2343 f = function () <em>body</em> end
2344 </pre><p>
2345 The statement
2346
2347 <pre>
2348 function t.a.b.c.f () <em>body</em> end
2349 </pre><p>
2350 translates to
2351
2352 <pre>
2353 t.a.b.c.f = function () <em>body</em> end
2354 </pre><p>
2355 The statement
2356
2357 <pre>
2358 local function f () <em>body</em> end
2359 </pre><p>
2360 translates to
2361
2362 <pre>
2363 local f; f = function () <em>body</em> end
2364 </pre><p>
2365 not to
2366
2367 <pre>
2368 local f = function () <em>body</em> end
2369 </pre><p>
2370 (This only makes a difference when the body of the function
2371 contains references to <code>f</code>.)
2372
2373
2374 <p>
2375 A function definition is an executable expression,
2376 whose value has type <em>function</em>.
2377 When Lua precompiles a chunk,
2378 all its function bodies are precompiled too.
2379 Then, whenever Lua executes the function definition,
2380 the function is <em>instantiated</em> (or <em>closed</em>).
2381 This function instance (or <em>closure</em>)
2382 is the final value of the expression.
2383
2384
2385 <p>
2386 Parameters act as local variables that are
2387 initialized with the argument values:
2388
2389 <pre>
2390 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2391 </pre><p>
2392 When a function is called,
2393 the list of arguments is adjusted to
2394 the length of the list of parameters,
2395 unless the function is a <em>vararg function</em>,
2396 which is indicated by three dots ('<code>...</code>')
2397 at the end of its parameter list.
2398 A vararg function does not adjust its argument list;
2399 instead, it collects all extra arguments and supplies them
2400 to the function through a <em>vararg expression</em>,
2401 which is also written as three dots.
2402 The value of this expression is a list of all actual extra arguments,
2403 similar to a function with multiple results.
2404 If a vararg expression is used inside another expression
2405 or in the middle of a list of expressions,
2406 then its return list is adjusted to one element.
2407 If the expression is used as the last element of a list of expressions,
2408 then no adjustment is made
2409 (unless that last expression is enclosed in parentheses).
2410
2411
2412 <p>
2413 As an example, consider the following definitions:
2414
2415 <pre>
2416 function f(a, b) end
2417 function g(a, b, ...) end
2418 function r() return 1,2,3 end
2419 </pre><p>
2420 Then, we have the following mapping from arguments to parameters and
2421 to the vararg expression:
2422
2423 <pre>
2424 CALL PARAMETERS
2425
2426 f(3) a=3, b=nil
2427 f(3, 4) a=3, b=4
2428 f(3, 4, 5) a=3, b=4
2429 f(r(), 10) a=1, b=10
2430 f(r()) a=1, b=2
2431
2432 g(3) a=3, b=nil, ... --&gt; (nothing)
2433 g(3, 4) a=3, b=4, ... --&gt; (nothing)
2434 g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
2435 g(5, r()) a=5, b=1, ... --&gt; 2 3
2436 </pre>
2437
2438 <p>
2439 Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2440 If control reaches the end of a function
2441 without encountering a <b>return</b> statement,
2442 then the function returns with no results.
2443
2444
2445 <p>
2446
2447 There is a system-dependent limit on the number of values
2448 that a function may return.
2449 This limit is guaranteed to be larger than 1000.
2450
2451
2452 <p>
2453 The <em>colon</em> syntax
2454 is used for defining <em>methods</em>,
2455 that is, functions that have an implicit extra parameter <code>self</code>.
2456 Thus, the statement
2457
2458 <pre>
2459 function t.a.b.c:f (<em>params</em>) <em>body</em> end
2460 </pre><p>
2461 is syntactic sugar for
2462
2463 <pre>
2464 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2465 </pre>
2466
2467
2468
2469
2470
2471
2472 <h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2473
2474 <p>
2475
2476 Lua is a lexically scoped language.
2477 The scope of a local variable begins at the first statement after
2478 its declaration and lasts until the last non-void statement
2479 of the innermost block that includes the declaration.
2480 Consider the following example:
2481
2482 <pre>
2483 x = 10 -- global variable
2484 do -- new block
2485 local x = x -- new 'x', with value 10
2486 print(x) --&gt; 10
2487 x = x+1
2488 do -- another block
2489 local x = x+1 -- another 'x'
2490 print(x) --&gt; 12
2491 end
2492 print(x) --&gt; 11
2493 end
2494 print(x) --&gt; 10 (the global one)
2495 </pre>
2496
2497 <p>
2498 Notice that, in a declaration like <code>local x = x</code>,
2499 the new <code>x</code> being declared is not in scope yet,
2500 and so the second <code>x</code> refers to the outside variable.
2501
2502
2503 <p>
2504 Because of the lexical scoping rules,
2505 local variables can be freely accessed by functions
2506 defined inside their scope.
2507 A local variable used by an inner function is called
2508 an <em>upvalue</em>, or <em>external local variable</em>,
2509 inside the inner function.
2510
2511
2512 <p>
2513 Notice that each execution of a <b>local</b> statement
2514 defines new local variables.
2515 Consider the following example:
2516
2517 <pre>
2518 a = {}
2519 local x = 20
2520 for i=1,10 do
2521 local y = 0
2522 a[i] = function () y=y+1; return x+y end
2523 end
2524 </pre><p>
2525 The loop creates ten closures
2526 (that is, ten instances of the anonymous function).
2527 Each of these closures uses a different <code>y</code> variable,
2528 while all of them share the same <code>x</code>.
2529
2530
2531
2532
2533
2534 <h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2535
2536 <p>
2537
2538 This section describes the C&nbsp;API for Lua, that is,
2539 the set of C&nbsp;functions available to the host program to communicate
2540 with Lua.
2541 All API functions and related types and constants
2542 are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2543
2544
2545 <p>
2546 Even when we use the term "function",
2547 any facility in the API may be provided as a macro instead.
2548 Except where stated otherwise,
2549 all such macros use each of their arguments exactly once
2550 (except for the first argument, which is always a Lua state),
2551 and so do not generate any hidden side-effects.
2552
2553
2554 <p>
2555 As in most C&nbsp;libraries,
2556 the Lua API functions do not check their arguments for validity or consistency.
2557 However, you can change this behavior by compiling Lua
2558 with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2559
2560
2561
2562 <h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2563
2564 <p>
2565 Lua uses a <em>virtual stack</em> to pass values to and from C.
2566 Each element in this stack represents a Lua value
2567 (<b>nil</b>, number, string, etc.).
2568
2569
2570 <p>
2571 Whenever Lua calls C, the called function gets a new stack,
2572 which is independent of previous stacks and of stacks of
2573 C&nbsp;functions that are still active.
2574 This stack initially contains any arguments to the C&nbsp;function
2575 and it is where the C&nbsp;function pushes its results
2576 to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2577
2578
2579 <p>
2580 For convenience,
2581 most query operations in the API do not follow a strict stack discipline.
2582 Instead, they can refer to any element in the stack
2583 by using an <em>index</em>:
2584 A positive index represents an absolute stack position
2585 (starting at&nbsp;1);
2586 a negative index represents an offset relative to the top of the stack.
2587 More specifically, if the stack has <em>n</em> elements,
2588 then index&nbsp;1 represents the first element
2589 (that is, the element that was pushed onto the stack first)
2590 and
2591 index&nbsp;<em>n</em> represents the last element;
2592 index&nbsp;-1 also represents the last element
2593 (that is, the element at the&nbsp;top)
2594 and index <em>-n</em> represents the first element.
2595
2596
2597
2598
2599
2600 <h2>4.2 &ndash; <a name="4.2">Stack Size</a></h2>
2601
2602 <p>
2603 When you interact with the Lua API,
2604 you are responsible for ensuring consistency.
2605 In particular,
2606 <em>you are responsible for controlling stack overflow</em>.
2607 You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2608 to ensure that the stack has enough space for pushing new elements.
2609
2610
2611 <p>
2612 Whenever Lua calls C,
2613 it ensures that the stack has space for
2614 at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2615 <code>LUA_MINSTACK</code> is defined as 20,
2616 so that usually you do not have to worry about stack space
2617 unless your code has loops pushing elements onto the stack.
2618
2619
2620 <p>
2621 When you call a Lua function
2622 without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2623 Lua ensures that the stack has enough space for all results,
2624 but it does not ensure any extra space.
2625 So, before pushing anything in the stack after such a call
2626 you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2627
2628
2629
2630
2631
2632 <h2>4.3 &ndash; <a name="4.3">Valid and Acceptable Indices</a></h2>
2633
2634 <p>
2635 Any function in the API that receives stack indices
2636 works only with <em>valid indices</em> or <em>acceptable indices</em>.
2637
2638
2639 <p>
2640 A <em>valid index</em> is an index that refers to a
2641 real position within the stack, that is,
2642 its position lies between&nbsp;1 and the stack top
2643 (<code>1 &le; abs(index) &le; top</code>).
2644
2645 Usually, functions that can modify the value at an index
2646 require valid indices.
2647
2648
2649 <p>
2650 Unless otherwise noted,
2651 any function that accepts valid indices also accepts <em>pseudo-indices</em>,
2652 which represent some Lua values that are accessible to C&nbsp;code
2653 but which are not in the stack.
2654 Pseudo-indices are used to access the registry
2655 and the upvalues of a C&nbsp;function (see <a href="#4.4">&sect;4.4</a>).
2656
2657
2658 <p>
2659 Functions that do not need a specific stack position,
2660 but only a value in the stack (e.g., query functions),
2661 can be called with acceptable indices.
2662 An <em>acceptable index</em> can be any valid index,
2663 including the pseudo-indices,
2664 but it also can be any positive index after the stack top
2665 within the space allocated for the stack,
2666 that is, indices up to the stack size.
2667 (Note that 0 is never an acceptable index.)
2668 Except when noted otherwise,
2669 functions in the API work with acceptable indices.
2670
2671
2672 <p>
2673 Acceptable indices serve to avoid extra tests
2674 against the stack top when querying the stack.
2675 For instance, a C&nbsp;function can query its third argument
2676 without the need to first check whether there is a third argument,
2677 that is, without the need to check whether 3 is a valid index.
2678
2679
2680 <p>
2681 For functions that can be called with acceptable indices,
2682 any non-valid index is treated as if it
2683 contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
2684 which behaves like a nil value.
2685
2686
2687
2688
2689
2690 <h2>4.4 &ndash; <a name="4.4">C Closures</a></h2>
2691
2692 <p>
2693 When a C&nbsp;function is created,
2694 it is possible to associate some values with it,
2695 thus creating a <em>C&nbsp;closure</em>
2696 (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
2697 these values are called <em>upvalues</em> and are
2698 accessible to the function whenever it is called.
2699
2700
2701 <p>
2702 Whenever a C&nbsp;function is called,
2703 its upvalues are located at specific pseudo-indices.
2704 These pseudo-indices are produced by the macro
2705 <a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2706 The first value associated with a function is at position
2707 <code>lua_upvalueindex(1)</code>, and so on.
2708 Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2709 where <em>n</em> is greater than the number of upvalues of the
2710 current function (but not greater than 256),
2711 produces an acceptable but invalid index.
2712
2713
2714
2715
2716
2717 <h2>4.5 &ndash; <a name="4.5">Registry</a></h2>
2718
2719 <p>
2720 Lua provides a <em>registry</em>,
2721 a predefined table that can be used by any C&nbsp;code to
2722 store whatever Lua values it needs to store.
2723 The registry table is always located at pseudo-index
2724 <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
2725 which is a valid index.
2726 Any C&nbsp;library can store data into this table,
2727 but it must take care to choose keys
2728 that are different from those used
2729 by other libraries, to avoid collisions.
2730 Typically, you should use as key a string containing your library name,
2731 or a light userdata with the address of a C&nbsp;object in your code,
2732 or any Lua object created by your code.
2733 As with variable names,
2734 string keys starting with an underscore followed by
2735 uppercase letters are reserved for Lua.
2736
2737
2738 <p>
2739 The integer keys in the registry are used
2740 by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
2741 and by some predefined values.
2742 Therefore, integer keys must not be used for other purposes.
2743
2744
2745 <p>
2746 When you create a new Lua state,
2747 its registry comes with some predefined values.
2748 These predefined values are indexed with integer keys
2749 defined as constants in <code>lua.h</code>.
2750 The following constants are defined:
2751
2752 <ul>
2753 <li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
2754 the main thread of the state.
2755 (The main thread is the one created together with the state.)
2756 </li>
2757
2758 <li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
2759 the global environment.
2760 </li>
2761 </ul>
2762
2763
2764
2765
2766 <h2>4.6 &ndash; <a name="4.6">Error Handling in C</a></h2>
2767
2768 <p>
2769 Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2770 (Lua will use exceptions if you compile it as C++;
2771 search for <code>LUAI_THROW</code> in the source code for details.)
2772 When Lua faces any error
2773 (such as a memory allocation error, type errors, syntax errors,
2774 and runtime errors)
2775 it <em>raises</em> an error;
2776 that is, it does a long jump.
2777 A <em>protected environment</em> uses <code>setjmp</code>
2778 to set a recovery point;
2779 any error jumps to the most recent active recovery point.
2780
2781
2782 <p>
2783 If an error happens outside any protected environment,
2784 Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
2785 and then calls <code>abort</code>,
2786 thus exiting the host application.
2787 Your panic function can avoid this exit by
2788 never returning
2789 (e.g., doing a long jump to your own recovery point outside Lua).
2790
2791
2792 <p>
2793 The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
2794 in particular, the error message is at the top of the stack.
2795 However, there is no guarantee about stack space.
2796 To push anything on the stack,
2797 the panic function must first check the available space (see <a href="#4.2">&sect;4.2</a>).
2798
2799
2800 <p>
2801 Most functions in the API can raise an error,
2802 for instance due to a memory allocation error.
2803 The documentation for each function indicates whether
2804 it can raise errors.
2805
2806
2807 <p>
2808 Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2809
2810
2811
2812
2813
2814 <h2>4.7 &ndash; <a name="4.7">Handling Yields in C</a></h2>
2815
2816 <p>
2817 Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2818 Therefore, if a C function <code>foo</code> calls an API function
2819 and this API function yields
2820 (directly or indirectly by calling another function that yields),
2821 Lua cannot return to <code>foo</code> any more,
2822 because the <code>longjmp</code> removes its frame from the C stack.
2823
2824
2825 <p>
2826 To avoid this kind of problem,
2827 Lua raises an error whenever it tries to yield across an API call,
2828 except for three functions:
2829 <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>.
2830 All those functions receive a <em>continuation function</em>
2831 (as a parameter named <code>k</code>) to continue execution after a yield.
2832
2833
2834 <p>
2835 We need to set some terminology to explain continuations.
2836 We have a C function called from Lua which we will call
2837 the <em>original function</em>.
2838 This original function then calls one of those three functions in the C API,
2839 which we will call the <em>callee function</em>,
2840 that then yields the current thread.
2841 (This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
2842 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>
2843 and the function called by them yields.)
2844
2845
2846 <p>
2847 Suppose the running thread yields while executing the callee function.
2848 After the thread resumes,
2849 it eventually will finish running the callee function.
2850 However,
2851 the callee function cannot return to the original function,
2852 because its frame in the C stack was destroyed by the yield.
2853 Instead, Lua calls a <em>continuation function</em>,
2854 which was given as an argument to the callee function.
2855 As the name implies,
2856 the continuation function should continue the task
2857 of the original function.
2858
2859
2860 <p>
2861 As an illustration, consider the following function:
2862
2863 <pre>
2864 int original_function (lua_State *L) {
2865 ... /* code 1 */
2866 status = lua_pcall(L, n, m, h); /* calls Lua */
2867 ... /* code 2 */
2868 }
2869 </pre><p>
2870 Now we want to allow
2871 the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
2872 First, we can rewrite our function like here:
2873
2874 <pre>
2875 int k (lua_State *L, int status, lua_KContext ctx) {
2876 ... /* code 2 */
2877 }
2878
2879 int original_function (lua_State *L) {
2880 ... /* code 1 */
2881 return k(L, lua_pcall(L, n, m, h), ctx);
2882 }
2883 </pre><p>
2884 In the above code,
2885 the new function <code>k</code> is a
2886 <em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
2887 which should do all the work that the original function
2888 was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
2889 Now, we must inform Lua that it must call <code>k</code> if the Lua code
2890 being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
2891 (errors or yielding),
2892 so we rewrite the code as here,
2893 replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
2894
2895 <pre>
2896 int original_function (lua_State *L) {
2897 ... /* code 1 */
2898 return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
2899 }
2900 </pre><p>
2901 Note the external, explicit call to the continuation:
2902 Lua will call the continuation only if needed, that is,
2903 in case of errors or resuming after a yield.
2904 If the called function returns normally without ever yielding,
2905 <a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
2906 (Of course, instead of calling the continuation in that case,
2907 you can do the equivalent work directly inside the original function.)
2908
2909
2910 <p>
2911 Besides the Lua state,
2912 the continuation function has two other parameters:
2913 the final status of the call plus the context value (<code>ctx</code>) that
2914 was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
2915 (Lua does not use this context value;
2916 it only passes this value from the original function to the
2917 continuation function.)
2918 For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
2919 the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
2920 except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
2921 (instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
2922 For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
2923 the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
2924 (For these two functions,
2925 Lua will not call the continuation in case of errors,
2926 because they do not handle errors.)
2927 Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
2928 you should call the continuation function
2929 with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
2930 (For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
2931 directly the continuation function,
2932 because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
2933
2934
2935 <p>
2936 Lua treats the continuation function as if it were the original function.
2937 The continuation function receives the same Lua stack
2938 from the original function,
2939 in the same state it would be if the callee function had returned.
2940 (For instance,
2941 after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
2942 removed from the stack and replaced by the results from the call.)
2943 It also has the same upvalues.
2944 Whatever it returns is handled by Lua as if it were the return
2945 of the original function.
2946
2947
2948
2949
2950
2951 <h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
2952
2953 <p>
2954 Here we list all functions and types from the C&nbsp;API in
2955 alphabetical order.
2956 Each function has an indicator like this:
2957 <span class="apii">[-o, +p, <em>x</em>]</span>
2958
2959
2960 <p>
2961 The first field, <code>o</code>,
2962 is how many elements the function pops from the stack.
2963 The second field, <code>p</code>,
2964 is how many elements the function pushes onto the stack.
2965 (Any function always pushes its results after popping its arguments.)
2966 A field in the form <code>x|y</code> means the function can push (or pop)
2967 <code>x</code> or <code>y</code> elements,
2968 depending on the situation;
2969 an interrogation mark '<code>?</code>' means that
2970 we cannot know how many elements the function pops/pushes
2971 by looking only at its arguments
2972 (e.g., they may depend on what is on the stack).
2973 The third field, <code>x</code>,
2974 tells whether the function may raise errors:
2975 '<code>-</code>' means the function never raises any error;
2976 '<code>e</code>' means the function may raise errors;
2977 '<code>v</code>' means the function may raise an error on purpose.
2978
2979
2980
2981 <hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
2982 <span class="apii">[-0, +0, &ndash;]</span>
2983 <pre>int lua_absindex (lua_State *L, int idx);</pre>
2984
2985 <p>
2986 Converts the acceptable index <code>idx</code> into an absolute index
2987 (that is, one that does not depend on the stack top).
2988
2989
2990
2991
2992
2993 <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2994 <pre>typedef void * (*lua_Alloc) (void *ud,
2995 void *ptr,
2996 size_t osize,
2997 size_t nsize);</pre>
2998
2999 <p>
3000 The type of the memory-allocation function used by Lua states.
3001 The allocator function must provide a
3002 functionality similar to <code>realloc</code>,
3003 but not exactly the same.
3004 Its arguments are
3005 <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
3006 <code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
3007 <code>osize</code>, the original size of the block or some code about what
3008 is being allocated;
3009 and <code>nsize</code>, the new size of the block.
3010
3011
3012 <p>
3013 When <code>ptr</code> is not <code>NULL</code>,
3014 <code>osize</code> is the size of the block pointed by <code>ptr</code>,
3015 that is, the size given when it was allocated or reallocated.
3016
3017
3018 <p>
3019 When <code>ptr</code> is <code>NULL</code>,
3020 <code>osize</code> encodes the kind of object that Lua is allocating.
3021 <code>osize</code> is any of
3022 <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>,
3023 <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)
3024 Lua is creating a new object of that type.
3025 When <code>osize</code> is some other value,
3026 Lua is allocating memory for something else.
3027
3028
3029 <p>
3030 Lua assumes the following behavior from the allocator function:
3031
3032
3033 <p>
3034 When <code>nsize</code> is zero,
3035 the allocator must behave like <code>free</code>
3036 and return <code>NULL</code>.
3037
3038
3039 <p>
3040 When <code>nsize</code> is not zero,
3041 the allocator must behave like <code>realloc</code>.
3042 The allocator returns <code>NULL</code>
3043 if and only if it cannot fulfill the request.
3044 Lua assumes that the allocator never fails when
3045 <code>osize &gt;= nsize</code>.
3046
3047
3048 <p>
3049 Here is a simple implementation for the allocator function.
3050 It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3051
3052 <pre>
3053 static void *l_alloc (void *ud, void *ptr, size_t osize,
3054 size_t nsize) {
3055 (void)ud; (void)osize; /* not used */
3056 if (nsize == 0) {
3057 free(ptr);
3058 return NULL;
3059 }
3060 else
3061 return realloc(ptr, nsize);
3062 }
3063 </pre><p>
3064 Note that Standard&nbsp;C ensures
3065 that <code>free(NULL)</code> has no effect and that
3066 <code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
3067 This code assumes that <code>realloc</code> does not fail when shrinking a block.
3068 (Although Standard&nbsp;C does not ensure this behavior,
3069 it seems to be a safe assumption.)
3070
3071
3072
3073
3074
3075 <hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3076 <span class="apii">[-(2|1), +1, <em>e</em>]</span>
3077 <pre>void lua_arith (lua_State *L, int op);</pre>
3078
3079 <p>
3080 Performs an arithmetic or bitwise operation over the two values
3081 (or one, in the case of negations)
3082 at the top of the stack,
3083 with the value at the top being the second operand,
3084 pops these values, and pushes the result of the operation.
3085 The function follows the semantics of the corresponding Lua operator
3086 (that is, it may call metamethods).
3087
3088
3089 <p>
3090 The value of <code>op</code> must be one of the following constants:
3091
3092 <ul>
3093
3094 <li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3095 <li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3096 <li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3097 <li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3098 <li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
3099 <li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3100 <li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3101 <li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3102 <li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise negation (<code>~</code>)</li>
3103 <li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise and (<code>&amp;</code>)</li>
3104 <li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise or (<code>|</code>)</li>
3105 <li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive or (<code>~</code>)</li>
3106 <li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3107 <li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3108
3109 </ul>
3110
3111
3112
3113
3114 <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3115 <span class="apii">[-0, +0, &ndash;]</span>
3116 <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3117
3118 <p>
3119 Sets a new panic function and returns the old one (see <a href="#4.6">&sect;4.6</a>).
3120
3121
3122
3123
3124
3125 <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3126 <span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3127 <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3128
3129 <p>
3130 Calls a function.
3131
3132
3133 <p>
3134 To call a function you must use the following protocol:
3135 first, the function to be called is pushed onto the stack;
3136 then, the arguments to the function are pushed
3137 in direct order;
3138 that is, the first argument is pushed first.
3139 Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3140 <code>nargs</code> is the number of arguments that you pushed onto the stack.
3141 All arguments and the function value are popped from the stack
3142 when the function is called.
3143 The function results are pushed onto the stack when the function returns.
3144 The number of results is adjusted to <code>nresults</code>,
3145 unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3146 In this case, all results from the function are pushed.
3147 Lua takes care that the returned values fit into the stack space.
3148 The function results are pushed onto the stack in direct order
3149 (the first result is pushed first),
3150 so that after the call the last result is on the top of the stack.
3151
3152
3153 <p>
3154 Any error inside the called function is propagated upwards
3155 (with a <code>longjmp</code>).
3156
3157
3158 <p>
3159 The following example shows how the host program can do the
3160 equivalent to this Lua code:
3161
3162 <pre>
3163 a = f("how", t.x, 14)
3164 </pre><p>
3165 Here it is in&nbsp;C:
3166
3167 <pre>
3168 lua_getglobal(L, "f"); /* function to be called */
3169 lua_pushliteral(L, "how"); /* 1st argument */
3170 lua_getglobal(L, "t"); /* table to be indexed */
3171 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
3172 lua_remove(L, -2); /* remove 't' from the stack */
3173 lua_pushinteger(L, 14); /* 3rd argument */
3174 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
3175 lua_setglobal(L, "a"); /* set global 'a' */
3176 </pre><p>
3177 Note that the code above is <em>balanced</em>:
3178 at its end, the stack is back to its original configuration.
3179 This is considered good programming practice.
3180
3181
3182
3183
3184
3185 <hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3186 <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3187 <pre>void lua_callk (lua_State *L,
3188 int nargs,
3189 int nresults,
3190 lua_KContext ctx,
3191 lua_KFunction k);</pre>
3192
3193 <p>
3194 This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3195 but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
3196
3197
3198
3199
3200
3201 <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3202 <pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3203
3204 <p>
3205 Type for C&nbsp;functions.
3206
3207
3208 <p>
3209 In order to communicate properly with Lua,
3210 a C&nbsp;function must use the following protocol,
3211 which defines the way parameters and results are passed:
3212 a C&nbsp;function receives its arguments from Lua in its stack
3213 in direct order (the first argument is pushed first).
3214 So, when the function starts,
3215 <code>lua_gettop(L)</code> returns the number of arguments received by the function.
3216 The first argument (if any) is at index 1
3217 and its last argument is at index <code>lua_gettop(L)</code>.
3218 To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3219 in direct order (the first result is pushed first),
3220 and returns the number of results.
3221 Any other value in the stack below the results will be properly
3222 discarded by Lua.
3223 Like a Lua function, a C&nbsp;function called by Lua can also return
3224 many results.
3225
3226
3227 <p>
3228 As an example, the following function receives a variable number
3229 of numerical arguments and returns their average and their sum:
3230
3231 <pre>
3232 static int foo (lua_State *L) {
3233 int n = lua_gettop(L); /* number of arguments */
3234 lua_Number sum = 0.0;
3235 int i;
3236 for (i = 1; i &lt;= n; i++) {
3237 if (!lua_isnumber(L, i)) {
3238 lua_pushliteral(L, "incorrect argument");
3239 lua_error(L);
3240 }
3241 sum += lua_tonumber(L, i);
3242 }
3243 lua_pushnumber(L, sum/n); /* first result */
3244 lua_pushnumber(L, sum); /* second result */
3245 return 2; /* number of results */
3246 }
3247 </pre>
3248
3249
3250
3251
3252 <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3253 <span class="apii">[-0, +0, &ndash;]</span>
3254 <pre>int lua_checkstack (lua_State *L, int n);</pre>
3255
3256 <p>
3257 Ensures that the stack has space for at least <code>n</code> extra slots.
3258 It returns false if it cannot fulfill the request,
3259 either because it would cause the stack
3260 to be larger than a fixed maximum size
3261 (typically at least several thousand elements) or
3262 because it cannot allocate memory for the extra space.
3263 This function never shrinks the stack;
3264 if the stack is already larger than the new size,
3265 it is left unchanged.
3266
3267
3268
3269
3270
3271 <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3272 <span class="apii">[-0, +0, &ndash;]</span>
3273 <pre>void lua_close (lua_State *L);</pre>
3274
3275 <p>
3276 Destroys all objects in the given Lua state
3277 (calling the corresponding garbage-collection metamethods, if any)
3278 and frees all dynamic memory used by this state.
3279 On several platforms, you may not need to call this function,
3280 because all resources are naturally released when the host program ends.
3281 On the other hand, long-running programs that create multiple states,
3282 such as daemons or web servers,
3283 will probably need to close states as soon as they are not needed.
3284
3285
3286
3287
3288
3289 <hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3290 <span class="apii">[-0, +0, <em>e</em>]</span>
3291 <pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3292
3293 <p>
3294 Compares two Lua values.
3295 Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3296 when compared with the value at index <code>index2</code>,
3297 following the semantics of the corresponding Lua operator
3298 (that is, it may call metamethods).
3299 Otherwise returns&nbsp;0.
3300 Also returns&nbsp;0 if any of the indices is not valid.
3301
3302
3303 <p>
3304 The value of <code>op</code> must be one of the following constants:
3305
3306 <ul>
3307
3308 <li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3309 <li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3310 <li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3311
3312 </ul>
3313
3314
3315
3316
3317 <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3318 <span class="apii">[-n, +1, <em>e</em>]</span>
3319 <pre>void lua_concat (lua_State *L, int n);</pre>
3320
3321 <p>
3322 Concatenates the <code>n</code> values at the top of the stack,
3323 pops them, and leaves the result at the top.
3324 If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3325 (that is, the function does nothing);
3326 if <code>n</code> is 0, the result is the empty string.
3327 Concatenation is performed following the usual semantics of Lua
3328 (see <a href="#3.4.6">&sect;3.4.6</a>).
3329
3330
3331
3332
3333
3334 <hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3335 <span class="apii">[-0, +0, &ndash;]</span>
3336 <pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3337
3338 <p>
3339 Copies the element at index <code>fromidx</code>
3340 into the valid index <code>toidx</code>,
3341 replacing the value at that position.
3342 Values at other positions are not affected.
3343
3344
3345
3346
3347
3348 <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3349 <span class="apii">[-0, +1, <em>e</em>]</span>
3350 <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3351
3352 <p>
3353 Creates a new empty table and pushes it onto the stack.
3354 Parameter <code>narr</code> is a hint for how many elements the table
3355 will have as a sequence;
3356 parameter <code>nrec</code> is a hint for how many other elements
3357 the table will have.
3358 Lua may use these hints to preallocate memory for the new table.
3359 This pre-allocation is useful for performance when you know in advance
3360 how many elements the table will have.
3361 Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3362
3363
3364
3365
3366
3367 <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3368 <span class="apii">[-0, +0, <em>e</em>]</span>
3369 <pre>int lua_dump (lua_State *L,
3370 lua_Writer writer,
3371 void *data,
3372 int strip);</pre>
3373
3374 <p>
3375 Dumps a function as a binary chunk.
3376 Receives a Lua function on the top of the stack
3377 and produces a binary chunk that,
3378 if loaded again,
3379 results in a function equivalent to the one dumped.
3380 As it produces parts of the chunk,
3381 <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3382 with the given <code>data</code>
3383 to write them.
3384
3385
3386 <p>
3387 If <code>strip</code> is true,
3388 the binary representation is created without debug information
3389 about the function.
3390
3391
3392 <p>
3393 The value returned is the error code returned by the last
3394 call to the writer;
3395 0&nbsp;means no errors.
3396
3397
3398 <p>
3399 This function does not pop the Lua function from the stack.
3400
3401
3402
3403
3404
3405 <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3406 <span class="apii">[-1, +0, <em>v</em>]</span>
3407 <pre>int lua_error (lua_State *L);</pre>
3408
3409 <p>
3410 Generates a Lua error,
3411 using the value at the top of the stack as the error object.
3412 This function does a long jump,
3413 and therefore never returns
3414 (see <a href="#luaL_error"><code>luaL_error</code></a>).
3415
3416
3417
3418
3419
3420 <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3421 <span class="apii">[-0, +0, <em>e</em>]</span>
3422 <pre>int lua_gc (lua_State *L, int what, int data);</pre>
3423
3424 <p>
3425 Controls the garbage collector.
3426
3427
3428 <p>
3429 This function performs several tasks,
3430 according to the value of the parameter <code>what</code>:
3431
3432 <ul>
3433
3434 <li><b><code>LUA_GCSTOP</code>: </b>
3435 stops the garbage collector.
3436 </li>
3437
3438 <li><b><code>LUA_GCRESTART</code>: </b>
3439 restarts the garbage collector.
3440 </li>
3441
3442 <li><b><code>LUA_GCCOLLECT</code>: </b>
3443 performs a full garbage-collection cycle.
3444 </li>
3445
3446 <li><b><code>LUA_GCCOUNT</code>: </b>
3447 returns the current amount of memory (in Kbytes) in use by Lua.
3448 </li>
3449
3450 <li><b><code>LUA_GCCOUNTB</code>: </b>
3451 returns the remainder of dividing the current amount of bytes of
3452 memory in use by Lua by 1024.
3453 </li>
3454
3455 <li><b><code>LUA_GCSTEP</code>: </b>
3456 performs an incremental step of garbage collection.
3457 </li>
3458
3459 <li><b><code>LUA_GCSETPAUSE</code>: </b>
3460 sets <code>data</code> as the new value
3461 for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>)
3462 and returns the previous value of the pause.
3463 </li>
3464
3465 <li><b><code>LUA_GCSETSTEPMUL</code>: </b>
3466 sets <code>data</code> as the new value for the <em>step multiplier</em> of
3467 the collector (see <a href="#2.5">&sect;2.5</a>)
3468 and returns the previous value of the step multiplier.
3469 </li>
3470
3471 <li><b><code>LUA_GCISRUNNING</code>: </b>
3472 returns a boolean that tells whether the collector is running
3473 (i.e., not stopped).
3474 </li>
3475
3476 </ul>
3477
3478 <p>
3479 For more details about these options,
3480 see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3481
3482
3483
3484
3485
3486 <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3487 <span class="apii">[-0, +0, &ndash;]</span>
3488 <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3489
3490 <p>
3491 Returns the memory-allocation function of a given state.
3492 If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3493 opaque pointer given when the memory-allocator function was set.
3494
3495
3496
3497
3498
3499 <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3500 <span class="apii">[-0, +1, <em>e</em>]</span>
3501 <pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
3502
3503 <p>
3504 Pushes onto the stack the value <code>t[k]</code>,
3505 where <code>t</code> is the value at the given index.
3506 As in Lua, this function may trigger a metamethod
3507 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3508
3509
3510 <p>
3511 Returns the type of the pushed value.
3512
3513
3514
3515
3516
3517 <hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
3518 <span class="apii">[-0, +0, &ndash;]</span>
3519 <pre>void *lua_getextraspace (lua_State *L);</pre>
3520
3521 <p>
3522 Returns a pointer to a raw memory area associated with the
3523 given Lua state.
3524 The application can use this area for any purpose;
3525 Lua does not use it for anything.
3526
3527
3528 <p>
3529 Each new thread has this area initialized with a copy
3530 of the area of the main thread.
3531
3532
3533 <p>
3534 By default, this area has the size of a pointer to void,
3535 but you can recompile Lua with a different size for this area.
3536 (See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
3537
3538
3539
3540
3541
3542 <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3543 <span class="apii">[-0, +1, <em>e</em>]</span>
3544 <pre>int lua_getglobal (lua_State *L, const char *name);</pre>
3545
3546 <p>
3547 Pushes onto the stack the value of the global <code>name</code>.
3548 Returns the type of that value.
3549
3550
3551
3552
3553
3554 <hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
3555 <span class="apii">[-0, +1, <em>e</em>]</span>
3556 <pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
3557
3558 <p>
3559 Pushes onto the stack the value <code>t[i]</code>,
3560 where <code>t</code> is the value at the given index.
3561 As in Lua, this function may trigger a metamethod
3562 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3563
3564
3565 <p>
3566 Returns the type of the pushed value.
3567
3568
3569
3570
3571
3572 <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
3573 <span class="apii">[-0, +(0|1), &ndash;]</span>
3574 <pre>int lua_getmetatable (lua_State *L, int index);</pre>
3575
3576 <p>
3577 If the value at the given index has a metatable,
3578 the function pushes that metatable onto the stack and returns&nbsp;1.
3579 Otherwise,
3580 the function returns&nbsp;0 and pushes nothing on the stack.
3581
3582
3583
3584
3585
3586 <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
3587 <span class="apii">[-1, +1, <em>e</em>]</span>
3588 <pre>int lua_gettable (lua_State *L, int index);</pre>
3589
3590 <p>
3591 Pushes onto the stack the value <code>t[k]</code>,
3592 where <code>t</code> is the value at the given index
3593 and <code>k</code> is the value at the top of the stack.
3594
3595
3596 <p>
3597 This function pops the key from the stack,
3598 pushing the resulting value in its place.
3599 As in Lua, this function may trigger a metamethod
3600 for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3601
3602
3603 <p>
3604 Returns the type of the pushed value.
3605
3606
3607
3608
3609
3610 <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
3611 <span class="apii">[-0, +0, &ndash;]</span>
3612 <pre>int lua_gettop (lua_State *L);</pre>
3613
3614 <p>
3615 Returns the index of the top element in the stack.
3616 Because indices start at&nbsp;1,
3617 this result is equal to the number of elements in the stack;
3618 in particular, 0&nbsp;means an empty stack.
3619
3620
3621
3622
3623
3624 <hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
3625 <span class="apii">[-0, +1, &ndash;]</span>
3626 <pre>int lua_getuservalue (lua_State *L, int index);</pre>
3627
3628 <p>
3629 Pushes onto the stack the Lua value associated with the userdata
3630 at the given index.
3631
3632
3633 <p>
3634 Returns the type of the pushed value.
3635
3636
3637
3638
3639
3640 <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
3641 <span class="apii">[-1, +1, &ndash;]</span>
3642 <pre>void lua_insert (lua_State *L, int index);</pre>
3643
3644 <p>
3645 Moves the top element into the given valid index,
3646 shifting up the elements above this index to open space.
3647 This function cannot be called with a pseudo-index,
3648 because a pseudo-index is not an actual stack position.
3649
3650
3651
3652
3653
3654 <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3655 <pre>typedef ... lua_Integer;</pre>
3656
3657 <p>
3658 The type of integers in Lua.
3659
3660
3661 <p>
3662 By default this type is <code>long long</code>,
3663 (usually a 64-bit two-complement integer),
3664 but that can be changed to <code>long</code> or <code>int</code>
3665 (usually a 32-bit two-complement integer).
3666 (See <code>LUA_INT</code> in <code>luaconf.h</code>.)
3667
3668
3669 <p>
3670 Lua also defines the constants
3671 <a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
3672 with the minimum and the maximum values that fit in this type.
3673
3674
3675
3676
3677
3678 <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3679 <span class="apii">[-0, +0, &ndash;]</span>
3680 <pre>int lua_isboolean (lua_State *L, int index);</pre>
3681
3682 <p>
3683 Returns 1 if the value at the given index is a boolean,
3684 and 0&nbsp;otherwise.
3685
3686
3687
3688
3689
3690 <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3691 <span class="apii">[-0, +0, &ndash;]</span>
3692 <pre>int lua_iscfunction (lua_State *L, int index);</pre>
3693
3694 <p>
3695 Returns 1 if the value at the given index is a C&nbsp;function,
3696 and 0&nbsp;otherwise.
3697
3698
3699
3700
3701
3702 <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3703 <span class="apii">[-0, +0, &ndash;]</span>
3704 <pre>int lua_isfunction (lua_State *L, int index);</pre>
3705
3706 <p>
3707 Returns 1 if the value at the given index is a function
3708 (either C or Lua), and 0&nbsp;otherwise.
3709
3710
3711
3712
3713
3714 <hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
3715 <span class="apii">[-0, +0, &ndash;]</span>
3716 <pre>int lua_isinteger (lua_State *L, int index);</pre>
3717
3718 <p>
3719 Returns 1 if the value at the given index is an integer
3720 (that is, the value is a number and is represented as an integer),
3721 and 0&nbsp;otherwise.
3722
3723
3724
3725
3726
3727 <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3728 <span class="apii">[-0, +0, &ndash;]</span>
3729 <pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3730
3731 <p>
3732 Returns 1 if the value at the given index is a light userdata,
3733 and 0&nbsp;otherwise.
3734
3735
3736
3737
3738
3739 <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3740 <span class="apii">[-0, +0, &ndash;]</span>
3741 <pre>int lua_isnil (lua_State *L, int index);</pre>
3742
3743 <p>
3744 Returns 1 if the value at the given index is <b>nil</b>,
3745 and 0&nbsp;otherwise.
3746
3747
3748
3749
3750
3751 <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3752 <span class="apii">[-0, +0, &ndash;]</span>
3753 <pre>int lua_isnone (lua_State *L, int index);</pre>
3754
3755 <p>
3756 Returns 1 if the given index is not valid,
3757 and 0&nbsp;otherwise.
3758
3759
3760
3761
3762
3763 <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3764 <span class="apii">[-0, +0, &ndash;]</span>
3765 <pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3766
3767 <p>
3768 Returns 1 if the given index is not valid
3769 or if the value at this index is <b>nil</b>,
3770 and 0&nbsp;otherwise.
3771
3772
3773
3774
3775
3776 <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3777 <span class="apii">[-0, +0, &ndash;]</span>
3778 <pre>int lua_isnumber (lua_State *L, int index);</pre>
3779
3780 <p>
3781 Returns 1 if the value at the given index is a number
3782 or a string convertible to a number,
3783 and 0&nbsp;otherwise.
3784
3785
3786
3787
3788
3789 <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3790 <span class="apii">[-0, +0, &ndash;]</span>
3791 <pre>int lua_isstring (lua_State *L, int index);</pre>
3792
3793 <p>
3794 Returns 1 if the value at the given index is a string
3795 or a number (which is always convertible to a string),
3796 and 0&nbsp;otherwise.
3797
3798
3799
3800
3801
3802 <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3803 <span class="apii">[-0, +0, &ndash;]</span>
3804 <pre>int lua_istable (lua_State *L, int index);</pre>
3805
3806 <p>
3807 Returns 1 if the value at the given index is a table,
3808 and 0&nbsp;otherwise.
3809
3810
3811
3812
3813
3814 <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3815 <span class="apii">[-0, +0, &ndash;]</span>
3816 <pre>int lua_isthread (lua_State *L, int index);</pre>
3817
3818 <p>
3819 Returns 1 if the value at the given index is a thread,
3820 and 0&nbsp;otherwise.
3821
3822
3823
3824
3825
3826 <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3827 <span class="apii">[-0, +0, &ndash;]</span>
3828 <pre>int lua_isuserdata (lua_State *L, int index);</pre>
3829
3830 <p>
3831 Returns 1 if the value at the given index is a userdata
3832 (either full or light), and 0&nbsp;otherwise.
3833
3834
3835
3836
3837
3838 <hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
3839 <span class="apii">[-0, +0, &ndash;]</span>
3840 <pre>int lua_isyieldable (lua_State *L);</pre>
3841
3842 <p>
3843 Returns 1 if the given coroutine can yield,
3844 and 0&nbsp;otherwise.
3845
3846
3847
3848
3849
3850 <hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
3851 <pre>typedef ... lua_KContext;</pre>
3852
3853 <p>
3854 The type for continuation-function contexts.
3855 It must be a numerical type.
3856 This type is defined as <code>intptr_t</code>
3857 when <code>intptr_t</code> is available,
3858 so that it can store pointers too.
3859 Otherwise, it is defined as <code>ptrdiff_t</code>.
3860
3861
3862
3863
3864
3865 <hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
3866 <pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
3867
3868 <p>
3869 Type for continuation functions (see <a href="#4.7">&sect;4.7</a>).
3870
3871
3872
3873
3874
3875 <hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
3876 <span class="apii">[-0, +1, <em>e</em>]</span>
3877 <pre>void lua_len (lua_State *L, int index);</pre>
3878
3879 <p>
3880 Returns the length of the value at the given index.
3881 It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
3882 may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
3883 The result is pushed on the stack.
3884
3885
3886
3887
3888
3889 <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3890 <span class="apii">[-0, +1, &ndash;]</span>
3891 <pre>int lua_load (lua_State *L,
3892 lua_Reader reader,
3893 void *data,
3894 const char *chunkname,
3895 const char *mode);</pre>
3896
3897 <p>
3898 Loads a Lua chunk without running it.
3899 If there are no errors,
3900 <code>lua_load</code> pushes the compiled chunk as a Lua
3901 function on top of the stack.
3902 Otherwise, it pushes an error message.
3903
3904
3905 <p>
3906 The return values of <code>lua_load</code> are:
3907
3908 <ul>
3909
3910 <li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li>
3911
3912 <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b>
3913 syntax error during precompilation;</li>
3914
3915 <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3916 memory allocation error;</li>
3917
3918 <li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
3919 error while running a <code>__gc</code> metamethod.
3920 (This error has no relation with the chunk being loaded.
3921 It is generated by the garbage collector.)
3922 </li>
3923
3924 </ul>
3925
3926 <p>
3927 The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
3928 to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3929 The <code>data</code> argument is an opaque value passed to the reader function.
3930
3931
3932 <p>
3933 The <code>chunkname</code> argument gives a name to the chunk,
3934 which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>).
3935
3936
3937 <p>
3938 <code>lua_load</code> automatically detects whether the chunk is text or binary
3939 and loads it accordingly (see program <code>luac</code>).
3940 The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
3941 with the addition that
3942 a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
3943
3944
3945 <p>
3946 <code>lua_load</code> uses the stack internally,
3947 so the reader function must always leave the stack
3948 unmodified when returning.
3949
3950
3951 <p>
3952 If the resulting function has upvalues,
3953 its first upvalue is set to the value of the global environment
3954 stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>).
3955 When loading main chunks,
3956 this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
3957 Other upvalues are initialized with <b>nil</b>.
3958
3959
3960
3961
3962
3963 <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3964 <span class="apii">[-0, +0, &ndash;]</span>
3965 <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3966
3967 <p>
3968 Creates a new thread running in a new, independent state.
3969 Returns <code>NULL</code> if it cannot create the thread or the state
3970 (due to lack of memory).
3971 The argument <code>f</code> is the allocator function;
3972 Lua does all memory allocation for this state through this function.
3973 The second argument, <code>ud</code>, is an opaque pointer that Lua
3974 passes to the allocator in every call.
3975
3976
3977
3978
3979
3980 <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
3981 <span class="apii">[-0, +1, <em>e</em>]</span>
3982 <pre>void lua_newtable (lua_State *L);</pre>
3983
3984 <p>
3985 Creates a new empty table and pushes it onto the stack.
3986 It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3987
3988
3989
3990
3991
3992 <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
3993 <span class="apii">[-0, +1, <em>e</em>]</span>
3994 <pre>lua_State *lua_newthread (lua_State *L);</pre>
3995
3996 <p>
3997 Creates a new thread, pushes it on the stack,
3998 and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3999 The new thread returned by this function shares with the original thread
4000 its global environment,
4001 but has an independent execution stack.
4002
4003
4004 <p>
4005 There is no explicit function to close or to destroy a thread.
4006 Threads are subject to garbage collection,
4007 like any Lua object.
4008
4009
4010
4011
4012
4013 <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
4014 <span class="apii">[-0, +1, <em>e</em>]</span>
4015 <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
4016
4017 <p>
4018 This function allocates a new block of memory with the given size,
4019 pushes onto the stack a new full userdata with the block address,
4020 and returns this address.
4021 The host program can freely use this memory.
4022
4023
4024
4025
4026
4027 <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
4028 <span class="apii">[-1, +(2|0), <em>e</em>]</span>
4029 <pre>int lua_next (lua_State *L, int index);</pre>
4030
4031 <p>
4032 Pops a key from the stack,
4033 and pushes a key&ndash;value pair from the table at the given index
4034 (the "next" pair after the given key).
4035 If there are no more elements in the table,
4036 then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
4037
4038
4039 <p>
4040 A typical traversal looks like this:
4041
4042 <pre>
4043 /* table is in the stack at index 't' */
4044 lua_pushnil(L); /* first key */
4045 while (lua_next(L, t) != 0) {
4046 /* uses 'key' (at index -2) and 'value' (at index -1) */
4047 printf("%s - %s\n",
4048 lua_typename(L, lua_type(L, -2)),
4049 lua_typename(L, lua_type(L, -1)));
4050 /* removes 'value'; keeps 'key' for next iteration */
4051 lua_pop(L, 1);
4052 }
4053 </pre>
4054
4055 <p>
4056 While traversing a table,
4057 do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
4058 unless you know that the key is actually a string.
4059 Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
4060 the value at the given index;
4061 this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
4062
4063
4064 <p>
4065 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
4066 the table during its traversal.
4067
4068
4069
4070
4071
4072 <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
4073 <pre>typedef double lua_Number;</pre>
4074
4075 <p>
4076 The type of floats in Lua.
4077
4078
4079 <p>
4080 By default this type is double,
4081 but that can be changed to a single float.
4082 (See <code>LUA_REAL</code> in <code>luaconf.h</code>.)
4083
4084
4085
4086
4087
4088 <hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4089 <pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4090
4091 <p>
4092 Converts a Lua float to a Lua integer.
4093 This macro assumes that <code>n</code> has an integral value.
4094 If that value is within the range of Lua integers,
4095 it is converted to an integer and assigned to <code>*p</code>.
4096 The macro results in a boolean indicating whether the
4097 conversion was successful.
4098 (Note that this range test can be tricky to do
4099 correctly without this macro,
4100 due to roundings.)
4101
4102
4103 <p>
4104 This macro may evaluate its arguments more than once.
4105
4106
4107
4108
4109
4110 <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4111 <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4112 <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4113
4114 <p>
4115 Calls a function in protected mode.
4116
4117
4118 <p>
4119 Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4120 in <a href="#lua_call"><code>lua_call</code></a>.
4121 If there are no errors during the call,
4122 <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4123 However, if there is any error,
4124 <a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4125 pushes a single value on the stack (the error message),
4126 and returns an error code.
4127 Like <a href="#lua_call"><code>lua_call</code></a>,
4128 <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4129 and its arguments from the stack.
4130
4131
4132 <p>
4133 If <code>msgh</code> is 0,
4134 then the error message returned on the stack
4135 is exactly the original error message.
4136 Otherwise, <code>msgh</code> is the stack index of a
4137 <em>message handler</em>.
4138 (In the current implementation, this index cannot be a pseudo-index.)
4139 In case of runtime errors,
4140 this function will be called with the error message
4141 and its return value will be the message
4142 returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4143
4144
4145 <p>
4146 Typically, the message handler is used to add more debug
4147 information to the error message, such as a stack traceback.
4148 Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4149 since by then the stack has unwound.
4150
4151
4152 <p>
4153 The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants
4154 (defined in <code>lua.h</code>):
4155
4156 <ul>
4157
4158 <li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b>
4159 success.</li>
4160
4161 <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b>
4162 a runtime error.
4163 </li>
4164
4165 <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
4166 memory allocation error.
4167 For such errors, Lua does not call the message handler.
4168 </li>
4169
4170 <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b>
4171 error while running the message handler.
4172 </li>
4173
4174 <li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
4175 error while running a <code>__gc</code> metamethod.
4176 (This error typically has no relation with the function being called.)
4177 </li>
4178
4179 </ul>
4180
4181
4182
4183
4184 <hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4185 <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4186 <pre>int lua_pcallk (lua_State *L,
4187 int nargs,
4188 int nresults,
4189 int msgh,
4190 lua_KContext ctx,
4191 lua_KFunction k);</pre>
4192
4193 <p>
4194 This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4195 but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
4196
4197
4198
4199
4200
4201 <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4202 <span class="apii">[-n, +0, &ndash;]</span>
4203 <pre>void lua_pop (lua_State *L, int n);</pre>
4204
4205 <p>
4206 Pops <code>n</code> elements from the stack.
4207
4208
4209
4210
4211
4212 <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4213 <span class="apii">[-0, +1, &ndash;]</span>
4214 <pre>void lua_pushboolean (lua_State *L, int b);</pre>
4215
4216 <p>
4217 Pushes a boolean value with value <code>b</code> onto the stack.
4218
4219
4220
4221
4222
4223 <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4224 <span class="apii">[-n, +1, <em>e</em>]</span>
4225 <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4226
4227 <p>
4228 Pushes a new C&nbsp;closure onto the stack.
4229
4230
4231 <p>
4232 When a C&nbsp;function is created,
4233 it is possible to associate some values with it,
4234 thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>);
4235 these values are then accessible to the function whenever it is called.
4236 To associate values with a C&nbsp;function,
4237 first these values must be pushed onto the stack
4238 (when there are multiple values, the first value is pushed first).
4239 Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4240 is called to create and push the C&nbsp;function onto the stack,
4241 with the argument <code>n</code> telling how many values will be
4242 associated with the function.
4243 <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4244
4245
4246 <p>
4247 The maximum value for <code>n</code> is 255.
4248
4249
4250 <p>
4251 When <code>n</code> is zero,
4252 this function creates a <em>light C function</em>,
4253 which is just a pointer to the C&nbsp;function.
4254 In that case, it never raises a memory error.
4255
4256
4257
4258
4259
4260 <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4261 <span class="apii">[-0, +1, &ndash;]</span>
4262 <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4263
4264 <p>
4265 Pushes a C&nbsp;function onto the stack.
4266 This function receives a pointer to a C function
4267 and pushes onto the stack a Lua value of type <code>function</code> that,
4268 when called, invokes the corresponding C&nbsp;function.
4269
4270
4271 <p>
4272 Any function to be registered in Lua must
4273 follow the correct protocol to receive its parameters
4274 and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4275
4276
4277 <p>
4278 <code>lua_pushcfunction</code> is defined as a macro:
4279
4280 <pre>
4281 #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
4282 </pre><p>
4283 Note that <code>f</code> is used twice.
4284
4285
4286
4287
4288
4289 <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4290 <span class="apii">[-0, +1, <em>e</em>]</span>
4291 <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4292
4293 <p>
4294 Pushes onto the stack a formatted string
4295 and returns a pointer to this string.
4296 It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4297 but has some important differences:
4298
4299 <ul>
4300
4301 <li>
4302 You do not have to allocate space for the result:
4303 the result is a Lua string and Lua takes care of memory allocation
4304 (and deallocation, through garbage collection).
4305 </li>
4306
4307 <li>
4308 The conversion specifiers are quite restricted.
4309 There are no flags, widths, or precisions.
4310 The conversion specifiers can only be
4311 '<code>%%</code>' (inserts the character '<code>%</code>'),
4312 '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4313 '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4314 '<code>%L</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4315 '<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
4316 '<code>%d</code>' (inserts an <code>int</code>),
4317 '<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4318 '<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
4319 </li>
4320
4321 </ul>
4322
4323
4324
4325
4326 <hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4327 <span class="apii">[-0, +1, &ndash;]</span>
4328 <pre>void lua_pushglobaltable (lua_State *L);</pre>
4329
4330 <p>
4331 Pushes the global environment onto the stack.
4332
4333
4334
4335
4336
4337 <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4338 <span class="apii">[-0, +1, &ndash;]</span>
4339 <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4340
4341 <p>
4342 Pushes an integer with value <code>n</code> onto the stack.
4343
4344
4345
4346
4347
4348 <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4349 <span class="apii">[-0, +1, &ndash;]</span>
4350 <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4351
4352 <p>
4353 Pushes a light userdata onto the stack.
4354
4355
4356 <p>
4357 Userdata represent C&nbsp;values in Lua.
4358 A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4359 It is a value (like a number):
4360 you do not create it, it has no individual metatable,
4361 and it is not collected (as it was never created).
4362 A light userdata is equal to "any"
4363 light userdata with the same C&nbsp;address.
4364
4365
4366
4367
4368
4369 <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4370 <span class="apii">[-0, +1, <em>e</em>]</span>
4371 <pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4372
4373 <p>
4374 This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
4375 but can be used only when <code>s</code> is a literal string.
4376 It automatically provides the string length.
4377
4378
4379
4380
4381
4382 <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4383 <span class="apii">[-0, +1, <em>e</em>]</span>
4384 <pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4385
4386 <p>
4387 Pushes the string pointed to by <code>s</code> with size <code>len</code>
4388 onto the stack.
4389 Lua makes (or reuses) an internal copy of the given string,
4390 so the memory at <code>s</code> can be freed or reused immediately after
4391 the function returns.
4392 The string can contain any binary data,
4393 including embedded zeros.
4394
4395
4396 <p>
4397 Returns a pointer to the internal copy of the string.
4398
4399
4400
4401
4402
4403 <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4404 <span class="apii">[-0, +1, &ndash;]</span>
4405 <pre>void lua_pushnil (lua_State *L);</pre>
4406
4407 <p>
4408 Pushes a nil value onto the stack.
4409
4410
4411
4412
4413
4414 <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4415 <span class="apii">[-0, +1, &ndash;]</span>
4416 <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4417
4418 <p>
4419 Pushes a float with value <code>n</code> onto the stack.
4420
4421
4422
4423
4424
4425 <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4426 <span class="apii">[-0, +1, <em>e</em>]</span>
4427 <pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4428
4429 <p>
4430 Pushes the zero-terminated string pointed to by <code>s</code>
4431 onto the stack.
4432 Lua makes (or reuses) an internal copy of the given string,
4433 so the memory at <code>s</code> can be freed or reused immediately after
4434 the function returns.
4435
4436
4437 <p>
4438 Returns a pointer to the internal copy of the string.
4439
4440
4441 <p>
4442 If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4443
4444
4445
4446
4447
4448 <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4449 <span class="apii">[-0, +1, &ndash;]</span>
4450 <pre>int lua_pushthread (lua_State *L);</pre>
4451
4452 <p>
4453 Pushes the thread represented by <code>L</code> onto the stack.
4454 Returns 1 if this thread is the main thread of its state.
4455
4456
4457
4458
4459
4460 <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4461 <span class="apii">[-0, +1, &ndash;]</span>
4462 <pre>void lua_pushvalue (lua_State *L, int index);</pre>
4463
4464 <p>
4465 Pushes a copy of the element at the given index
4466 onto the stack.
4467
4468
4469
4470
4471
4472 <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4473 <span class="apii">[-0, +1, <em>e</em>]</span>
4474 <pre>const char *lua_pushvfstring (lua_State *L,
4475 const char *fmt,
4476 va_list argp);</pre>
4477
4478 <p>
4479 Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4480 instead of a variable number of arguments.
4481
4482
4483
4484
4485
4486 <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4487 <span class="apii">[-0, +0, &ndash;]</span>
4488 <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4489
4490 <p>
4491 Returns 1 if the two values in indices <code>index1</code> and
4492 <code>index2</code> are primitively equal
4493 (that is, without calling metamethods).
4494 Otherwise returns&nbsp;0.
4495 Also returns&nbsp;0 if any of the indices are not valid.
4496
4497
4498
4499
4500
4501 <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4502 <span class="apii">[-1, +1, &ndash;]</span>
4503 <pre>int lua_rawget (lua_State *L, int index);</pre>
4504
4505 <p>
4506 Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4507 (i.e., without metamethods).
4508
4509
4510
4511
4512
4513 <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4514 <span class="apii">[-0, +1, &ndash;]</span>
4515 <pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4516
4517 <p>
4518 Pushes onto the stack the value <code>t[n]</code>,
4519 where <code>t</code> is the table at the given index.
4520 The access is raw;
4521 that is, it does not invoke metamethods.
4522
4523
4524 <p>
4525 Returns the type of the pushed value.
4526
4527
4528
4529
4530
4531 <hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4532 <span class="apii">[-0, +1, &ndash;]</span>
4533 <pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4534
4535 <p>
4536 Pushes onto the stack the value <code>t[k]</code>,
4537 where <code>t</code> is the table at the given index and
4538 <code>k</code> is the pointer <code>p</code> represented as a light userdata.
4539 The access is raw;
4540 that is, it does not invoke metamethods.
4541
4542
4543 <p>
4544 Returns the type of the pushed value.
4545
4546
4547
4548
4549
4550 <hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
4551 <span class="apii">[-0, +0, &ndash;]</span>
4552 <pre>size_t lua_rawlen (lua_State *L, int index);</pre>
4553
4554 <p>
4555 Returns the raw "length" of the value at the given index:
4556 for strings, this is the string length;
4557 for tables, this is the result of the length operator ('<code>#</code>')
4558 with no metamethods;
4559 for userdata, this is the size of the block of memory allocated
4560 for the userdata;
4561 for other values, it is&nbsp;0.
4562
4563
4564
4565
4566
4567 <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
4568 <span class="apii">[-2, +0, <em>e</em>]</span>
4569 <pre>void lua_rawset (lua_State *L, int index);</pre>
4570
4571 <p>
4572 Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
4573 (i.e., without metamethods).
4574
4575
4576
4577
4578
4579 <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
4580 <span class="apii">[-1, +0, <em>e</em>]</span>
4581 <pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
4582
4583 <p>
4584 Does the equivalent of <code>t[i] = v</code>,
4585 where <code>t</code> is the table at the given index
4586 and <code>v</code> is the value at the top of the stack.
4587
4588
4589 <p>
4590 This function pops the value from the stack.
4591 The assignment is raw;
4592 that is, it does not invoke metamethods.
4593
4594
4595
4596
4597
4598 <hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
4599 <span class="apii">[-1, +0, <em>e</em>]</span>
4600 <pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
4601
4602 <p>
4603 Does the equivalent of <code>t[k] = v</code>,
4604 where <code>t</code> is the table at the given index,
4605 <code>k</code> is the pointer <code>p</code> represented as a light userdata,
4606 and <code>v</code> is the value at the top of the stack.
4607
4608
4609 <p>
4610 This function pops the value from the stack.
4611 The assignment is raw;
4612 that is, it does not invoke metamethods.
4613
4614
4615
4616
4617
4618 <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
4619 <pre>typedef const char * (*lua_Reader) (lua_State *L,
4620 void *data,
4621 size_t *size);</pre>
4622
4623 <p>
4624 The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
4625 Every time it needs another piece of the chunk,
4626 <a href="#lua_load"><code>lua_load</code></a> calls the reader,
4627 passing along its <code>data</code> parameter.
4628 The reader must return a pointer to a block of memory
4629 with a new piece of the chunk
4630 and set <code>size</code> to the block size.
4631 The block must exist until the reader function is called again.
4632 To signal the end of the chunk,
4633 the reader must return <code>NULL</code> or set <code>size</code> to zero.
4634 The reader function may return pieces of any size greater than zero.
4635
4636
4637
4638
4639
4640 <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
4641 <span class="apii">[-0, +0, <em>e</em>]</span>
4642 <pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
4643
4644 <p>
4645 Sets the C function <code>f</code> as the new value of global <code>name</code>.
4646 It is defined as a macro:
4647
4648 <pre>
4649 #define lua_register(L,n,f) \
4650 (lua_pushcfunction(L, f), lua_setglobal(L, n))
4651 </pre>
4652
4653
4654
4655
4656 <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
4657 <span class="apii">[-1, +0, &ndash;]</span>
4658 <pre>void lua_remove (lua_State *L, int index);</pre>
4659
4660 <p>
4661 Removes the element at the given valid index,
4662 shifting down the elements above this index to fill the gap.
4663 This function cannot be called with a pseudo-index,
4664 because a pseudo-index is not an actual stack position.
4665
4666
4667
4668
4669
4670 <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
4671 <span class="apii">[-1, +0, &ndash;]</span>
4672 <pre>void lua_replace (lua_State *L, int index);</pre>
4673
4674 <p>
4675 Moves the top element into the given valid index
4676 without shifting any element
4677 (therefore replacing the value at the given index),
4678 and then pops the top element.
4679
4680
4681
4682
4683
4684 <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
4685 <span class="apii">[-?, +?, &ndash;]</span>
4686 <pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre>
4687
4688 <p>
4689 Starts and resumes a coroutine in a given thread.
4690
4691
4692 <p>
4693 To start a coroutine,
4694 you push onto the thread stack the main function plus any arguments;
4695 then you call <a href="#lua_resume"><code>lua_resume</code></a>,
4696 with <code>nargs</code> being the number of arguments.
4697 This call returns when the coroutine suspends or finishes its execution.
4698 When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
4699 or all values returned by the body function.
4700 <a href="#lua_resume"><code>lua_resume</code></a> returns
4701 <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
4702 <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
4703 without errors,
4704 or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
4705
4706
4707 <p>
4708 In case of errors,
4709 the stack is not unwound,
4710 so you can use the debug API over it.
4711 The error message is on the top of the stack.
4712
4713
4714 <p>
4715 To resume a coroutine,
4716 you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>,
4717 put on its stack only the values to
4718 be passed as results from <code>yield</code>,
4719 and then call <a href="#lua_resume"><code>lua_resume</code></a>.
4720
4721
4722 <p>
4723 The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
4724 If there is no such coroutine,
4725 this parameter can be <code>NULL</code>.
4726
4727
4728
4729
4730
4731 <hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
4732 <span class="apii">[-0, +0, &ndash;]</span>
4733 <pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
4734
4735 <p>
4736 Rotates the stack elements from <code>idx</code> to the top <code>n</code> positions
4737 in the direction of the top, for a positive <code>n</code>,
4738 or <code>-n</code> positions in the direction of the bottom,
4739 for a negative <code>n</code>.
4740 The absolute value of <code>n</code> must not be greater than the size
4741 of the slice being rotated.
4742
4743
4744
4745
4746
4747 <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
4748 <span class="apii">[-0, +0, &ndash;]</span>
4749 <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
4750
4751 <p>
4752 Changes the allocator function of a given state to <code>f</code>
4753 with user data <code>ud</code>.
4754
4755
4756
4757
4758
4759 <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
4760 <span class="apii">[-1, +0, <em>e</em>]</span>
4761 <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
4762
4763 <p>
4764 Does the equivalent to <code>t[k] = v</code>,
4765 where <code>t</code> is the value at the given index
4766 and <code>v</code> is the value at the top of the stack.
4767
4768
4769 <p>
4770 This function pops the value from the stack.
4771 As in Lua, this function may trigger a metamethod
4772 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4773
4774
4775
4776
4777
4778 <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
4779 <span class="apii">[-1, +0, <em>e</em>]</span>
4780 <pre>void lua_setglobal (lua_State *L, const char *name);</pre>
4781
4782 <p>
4783 Pops a value from the stack and
4784 sets it as the new value of global <code>name</code>.
4785
4786
4787
4788
4789
4790 <hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
4791 <span class="apii">[-1, +0, <em>e</em>]</span>
4792 <pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
4793
4794 <p>
4795 Does the equivalent to <code>t[n] = v</code>,
4796 where <code>t</code> is the value at the given index
4797 and <code>v</code> is the value at the top of the stack.
4798
4799
4800 <p>
4801 This function pops the value from the stack.
4802 As in Lua, this function may trigger a metamethod
4803 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4804
4805
4806
4807
4808
4809 <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
4810 <span class="apii">[-1, +0, &ndash;]</span>
4811 <pre>void lua_setmetatable (lua_State *L, int index);</pre>
4812
4813 <p>
4814 Pops a table from the stack and
4815 sets it as the new metatable for the value at the given index.
4816
4817
4818
4819
4820
4821 <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
4822 <span class="apii">[-2, +0, <em>e</em>]</span>
4823 <pre>void lua_settable (lua_State *L, int index);</pre>
4824
4825 <p>
4826 Does the equivalent to <code>t[k] = v</code>,
4827 where <code>t</code> is the value at the given index,
4828 <code>v</code> is the value at the top of the stack,
4829 and <code>k</code> is the value just below the top.
4830
4831
4832 <p>
4833 This function pops both the key and the value from the stack.
4834 As in Lua, this function may trigger a metamethod
4835 for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4836
4837
4838
4839
4840
4841 <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
4842 <span class="apii">[-?, +?, &ndash;]</span>
4843 <pre>void lua_settop (lua_State *L, int index);</pre>
4844
4845 <p>
4846 Accepts any index, or&nbsp;0,
4847 and sets the stack top to this index.
4848 If the new top is larger than the old one,
4849 then the new elements are filled with <b>nil</b>.
4850 If <code>index</code> is&nbsp;0, then all stack elements are removed.
4851
4852
4853
4854
4855
4856 <hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p>
4857 <span class="apii">[-1, +0, &ndash;]</span>
4858 <pre>void lua_setuservalue (lua_State *L, int index);</pre>
4859
4860 <p>
4861 Pops a value from the stack and sets it as
4862 the new value associated to the userdata at the given index.
4863
4864
4865
4866
4867
4868 <hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
4869 <pre>typedef struct lua_State lua_State;</pre>
4870
4871 <p>
4872 An opaque structure that points to a thread and indirectly
4873 (through the thread) to the whole state of a Lua interpreter.
4874 The Lua library is fully reentrant:
4875 it has no global variables.
4876 All information about a state is accessible through this structure.
4877
4878
4879 <p>
4880 A pointer to this structure must be passed as the first argument to
4881 every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4882 which creates a Lua state from scratch.
4883
4884
4885
4886
4887
4888 <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4889 <span class="apii">[-0, +0, &ndash;]</span>
4890 <pre>int lua_status (lua_State *L);</pre>
4891
4892 <p>
4893 Returns the status of the thread <code>L</code>.
4894
4895
4896 <p>
4897 The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread,
4898 an error code if the thread finished the execution
4899 of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
4900 or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4901
4902
4903 <p>
4904 You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
4905 You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
4906 (to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
4907 (to resume a coroutine).
4908
4909
4910
4911
4912
4913 <hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
4914 <span class="apii">[-0, +1, &ndash;]</span>
4915 <pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
4916
4917 <p>
4918 Converts the zero-terminated string <code>s</code> to a number,
4919 pushes that number into the stack,
4920 and returns the total size of the string,
4921 that is, its length plus one.
4922 The conversion can result in an integer or a float,
4923 according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
4924 The string may have leading and trailing spaces and a sign.
4925 If the string is not a valid numeral,
4926 returns 0 and pushes nothing.
4927 (Note that the result can be used as a boolean,
4928 true if the conversion succeeds.)
4929
4930
4931
4932
4933
4934 <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4935 <span class="apii">[-0, +0, &ndash;]</span>
4936 <pre>int lua_toboolean (lua_State *L, int index);</pre>
4937
4938 <p>
4939 Converts the Lua value at the given index to a C&nbsp;boolean
4940 value (0&nbsp;or&nbsp;1).
4941 Like all tests in Lua,
4942 <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
4943 different from <b>false</b> and <b>nil</b>;
4944 otherwise it returns false.
4945 (If you want to accept only actual boolean values,
4946 use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4947
4948
4949
4950
4951
4952 <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4953 <span class="apii">[-0, +0, &ndash;]</span>
4954 <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4955
4956 <p>
4957 Converts a value at the given index to a C&nbsp;function.
4958 That value must be a C&nbsp;function;
4959 otherwise, returns <code>NULL</code>.
4960
4961
4962
4963
4964
4965 <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4966 <span class="apii">[-0, +0, &ndash;]</span>
4967 <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4968
4969 <p>
4970 Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4971
4972
4973
4974
4975
4976 <hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
4977 <span class="apii">[-0, +0, &ndash;]</span>
4978 <pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
4979
4980 <p>
4981 Converts the Lua value at the given index
4982 to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4983 The Lua value must be an integer,
4984 or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
4985 otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
4986
4987
4988 <p>
4989 If <code>isnum</code> is not <code>NULL</code>,
4990 its referent is assigned a boolean value that
4991 indicates whether the operation succeeded.
4992
4993
4994
4995
4996
4997 <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
4998 <span class="apii">[-0, +0, <em>e</em>]</span>
4999 <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
5000
5001 <p>
5002 Converts the Lua value at the given index to a C&nbsp;string.
5003 If <code>len</code> is not <code>NULL</code>,
5004 it also sets <code>*len</code> with the string length.
5005 The Lua value must be a string or a number;
5006 otherwise, the function returns <code>NULL</code>.
5007 If the value is a number,
5008 then <code>lua_tolstring</code> also
5009 <em>changes the actual value in the stack to a string</em>.
5010 (This change confuses <a href="#lua_next"><code>lua_next</code></a>
5011 when <code>lua_tolstring</code> is applied to keys during a table traversal.)
5012
5013
5014 <p>
5015 <code>lua_tolstring</code> returns a fully aligned pointer
5016 to a string inside the Lua state.
5017 This string always has a zero ('<code>\0</code>')
5018 after its last character (as in&nbsp;C),
5019 but can contain other zeros in its body.
5020
5021
5022 <p>
5023 Because Lua has garbage collection,
5024 there is no guarantee that the pointer returned by <code>lua_tolstring</code>
5025 will be valid after the corresponding Lua value is removed from the stack.
5026
5027
5028
5029
5030
5031 <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
5032 <span class="apii">[-0, +0, &ndash;]</span>
5033 <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
5034
5035 <p>
5036 Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5037
5038
5039
5040
5041
5042 <hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
5043 <span class="apii">[-0, +0, &ndash;]</span>
5044 <pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
5045
5046 <p>
5047 Converts the Lua value at the given index
5048 to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
5049 The Lua value must be a number or a string convertible to a number
5050 (see <a href="#3.4.3">&sect;3.4.3</a>);
5051 otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
5052
5053
5054 <p>
5055 If <code>isnum</code> is not <code>NULL</code>,
5056 its referent is assigned a boolean value that
5057 indicates whether the operation succeeded.
5058
5059
5060
5061
5062
5063 <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
5064 <span class="apii">[-0, +0, &ndash;]</span>
5065 <pre>const void *lua_topointer (lua_State *L, int index);</pre>
5066
5067 <p>
5068 Converts the value at the given index to a generic
5069 C&nbsp;pointer (<code>void*</code>).
5070 The value can be a userdata, a table, a thread, or a function;
5071 otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
5072 Different objects will give different pointers.
5073 There is no way to convert the pointer back to its original value.
5074
5075
5076 <p>
5077 Typically this function is used only for debug information.
5078
5079
5080
5081
5082
5083 <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
5084 <span class="apii">[-0, +0, <em>e</em>]</span>
5085 <pre>const char *lua_tostring (lua_State *L, int index);</pre>
5086
5087 <p>
5088 Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
5089
5090
5091
5092
5093
5094 <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
5095 <span class="apii">[-0, +0, &ndash;]</span>
5096 <pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
5097
5098 <p>
5099 Converts the value at the given index to a Lua thread
5100 (represented as <code>lua_State*</code>).
5101 This value must be a thread;
5102 otherwise, the function returns <code>NULL</code>.
5103
5104
5105
5106
5107
5108 <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5109 <span class="apii">[-0, +0, &ndash;]</span>
5110 <pre>void *lua_touserdata (lua_State *L, int index);</pre>
5111
5112 <p>
5113 If the value at the given index is a full userdata,
5114 returns its block address.
5115 If the value is a light userdata,
5116 returns its pointer.
5117 Otherwise, returns <code>NULL</code>.
5118
5119
5120
5121
5122
5123 <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5124 <span class="apii">[-0, +0, &ndash;]</span>
5125 <pre>int lua_type (lua_State *L, int index);</pre>
5126
5127 <p>
5128 Returns the type of the value in the given valid index,
5129 or <code>LUA_TNONE</code> for a non-valid (but acceptable) index.
5130 The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5131 defined in <code>lua.h</code>:
5132 <a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5133 <a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5134 <a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5135 <a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5136 <a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5137 <a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5138 <a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5139 <a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5140 and
5141 <a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5142
5143
5144
5145
5146
5147 <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5148 <span class="apii">[-0, +0, &ndash;]</span>
5149 <pre>const char *lua_typename (lua_State *L, int tp);</pre>
5150
5151 <p>
5152 Returns the name of the type encoded by the value <code>tp</code>,
5153 which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5154
5155
5156
5157
5158
5159 <hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5160 <pre>typedef ... lua_Unsigned;</pre>
5161
5162 <p>
5163 The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5164
5165
5166
5167
5168
5169 <hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5170 <span class="apii">[-0, +0, &ndash;]</span>
5171 <pre>int lua_upvalueindex (int i);</pre>
5172
5173 <p>
5174 Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5175 the running function (see <a href="#4.4">&sect;4.4</a>).
5176
5177
5178
5179
5180
5181 <hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5182 <span class="apii">[-0, +0, <em>v</em>]</span>
5183 <pre>const lua_Number *lua_version (lua_State *L);</pre>
5184
5185 <p>
5186 Returns the address of the version number stored in the Lua core.
5187 When called with a valid <a href="#lua_State"><code>lua_State</code></a>,
5188 returns the address of the version used to create that state.
5189 When called with <code>NULL</code>,
5190 returns the address of the version running the call.
5191
5192
5193
5194
5195
5196 <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5197 <pre>typedef int (*lua_Writer) (lua_State *L,
5198 const void* p,
5199 size_t sz,
5200 void* ud);</pre>
5201
5202 <p>
5203 The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5204 Every time it produces another piece of chunk,
5205 <a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
5206 passing along the buffer to be written (<code>p</code>),
5207 its size (<code>sz</code>),
5208 and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5209
5210
5211 <p>
5212 The writer returns an error code:
5213 0&nbsp;means no errors;
5214 any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5215 calling the writer again.
5216
5217
5218
5219
5220
5221 <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5222 <span class="apii">[-?, +?, &ndash;]</span>
5223 <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5224
5225 <p>
5226 Exchange values between different threads of the same state.
5227
5228
5229 <p>
5230 This function pops <code>n</code> values from the stack <code>from</code>,
5231 and pushes them onto the stack <code>to</code>.
5232
5233
5234
5235
5236
5237 <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5238 <span class="apii">[-?, +?, <em>e</em>]</span>
5239 <pre>int lua_yield (lua_State *L, int nresults);</pre>
5240
5241 <p>
5242 This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5243 but it has no continuation (see <a href="#4.7">&sect;4.7</a>).
5244 Therefore, when the thread resumes,
5245 it continues the function that called
5246 the function calling <code>lua_yield</code>.
5247
5248
5249
5250
5251
5252 <hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5253 <span class="apii">[-?, +?, <em>e</em>]</span>
5254 <pre>int lua_yieldk (lua_State *L,
5255 int nresults,
5256 lua_KContext ctx,
5257 lua_KFunction k);</pre>
5258
5259 <p>
5260 Yields a coroutine (thread).
5261
5262
5263 <p>
5264 When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5265 the running coroutine suspends its execution,
5266 and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5267 The parameter <code>nresults</code> is the number of values from the stack
5268 that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5269
5270
5271 <p>
5272 When the coroutine is resumed again,
5273 Lua calls the given continuation function <code>k</code> to continue
5274 the execution of the C function that yielded (see <a href="#4.7">&sect;4.7</a>).
5275 This continuation function receives the same stack
5276 from the previous function,
5277 with the <code>n</code> results removed and
5278 replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5279 Moreover,
5280 the continuation function receives the value <code>ctx</code>
5281 that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5282
5283
5284 <p>
5285 Usually, this function does not return;
5286 when the coroutine eventually resumes,
5287 it continues executing the continuation function.
5288 However, there is one special case,
5289 which is when this function is called
5290 from inside a line hook (see <a href="#4.9">&sect;4.9</a>).
5291 In that case, <code>lua_yieldk</code> should be called with no continuation
5292 (probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>),
5293 and the hook should return immediately after the call.
5294 Lua will yield and,
5295 when the coroutine resumes again,
5296 it will continue the normal execution
5297 of the (Lua) function that triggered the hook.
5298
5299
5300 <p>
5301 This function can raise an error if it is called from a thread
5302 with a pending C call with no continuation function,
5303 or it is called from a thread that is not running inside a resume
5304 (e.g., the main thread).
5305
5306
5307
5308
5309
5310
5311
5312 <h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2>
5313
5314 <p>
5315 Lua has no built-in debugging facilities.
5316 Instead, it offers a special interface
5317 by means of functions and <em>hooks</em>.
5318 This interface allows the construction of different
5319 kinds of debuggers, profilers, and other tools
5320 that need "inside information" from the interpreter.
5321
5322
5323
5324 <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5325 <pre>typedef struct lua_Debug {
5326 int event;
5327 const char *name; /* (n) */
5328 const char *namewhat; /* (n) */
5329 const char *what; /* (S) */
5330 const char *source; /* (S) */
5331 int currentline; /* (l) */
5332 int linedefined; /* (S) */
5333 int lastlinedefined; /* (S) */
5334 unsigned char nups; /* (u) number of upvalues */
5335 unsigned char nparams; /* (u) number of parameters */
5336 char isvararg; /* (u) */
5337 char istailcall; /* (t) */
5338 char short_src[LUA_IDSIZE]; /* (S) */
5339 /* private part */
5340 <em>other fields</em>
5341 } lua_Debug;</pre>
5342
5343 <p>
5344 A structure used to carry different pieces of
5345 information about a function or an activation record.
5346 <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5347 of this structure, for later use.
5348 To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5349 call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5350
5351
5352 <p>
5353 The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5354
5355 <ul>
5356
5357 <li><b><code>source</code>: </b>
5358 the name of the chunk that created the function.
5359 If <code>source</code> starts with a '<code>@</code>',
5360 it means that the function was defined in a file where
5361 the file name follows the '<code>@</code>'.
5362 If <code>source</code> starts with a '<code>=</code>',
5363 the remainder of its contents describe the source in a user-dependent manner.
5364 Otherwise,
5365 the function was defined in a string where
5366 <code>source</code> is that string.
5367 </li>
5368
5369 <li><b><code>short_src</code>: </b>
5370 a "printable" version of <code>source</code>, to be used in error messages.
5371 </li>
5372
5373 <li><b><code>linedefined</code>: </b>
5374 the line number where the definition of the function starts.
5375 </li>
5376
5377 <li><b><code>lastlinedefined</code>: </b>
5378 the line number where the definition of the function ends.
5379 </li>
5380
5381 <li><b><code>what</code>: </b>
5382 the string <code>"Lua"</code> if the function is a Lua function,
5383 <code>"C"</code> if it is a C&nbsp;function,
5384 <code>"main"</code> if it is the main part of a chunk.
5385 </li>
5386
5387 <li><b><code>currentline</code>: </b>
5388 the current line where the given function is executing.
5389 When no line information is available,
5390 <code>currentline</code> is set to -1.
5391 </li>
5392
5393 <li><b><code>name</code>: </b>
5394 a reasonable name for the given function.
5395 Because functions in Lua are first-class values,
5396 they do not have a fixed name:
5397 some functions can be the value of multiple global variables,
5398 while others can be stored only in a table field.
5399 The <code>lua_getinfo</code> function checks how the function was
5400 called to find a suitable name.
5401 If it cannot find a name,
5402 then <code>name</code> is set to <code>NULL</code>.
5403 </li>
5404
5405 <li><b><code>namewhat</code>: </b>
5406 explains the <code>name</code> field.
5407 The value of <code>namewhat</code> can be
5408 <code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
5409 <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
5410 according to how the function was called.
5411 (Lua uses the empty string when no other option seems to apply.)
5412 </li>
5413
5414 <li><b><code>istailcall</code>: </b>
5415 true if this function invocation was called by a tail call.
5416 In this case, the caller of this level is not in the stack.
5417 </li>
5418
5419 <li><b><code>nups</code>: </b>
5420 the number of upvalues of the function.
5421 </li>
5422
5423 <li><b><code>nparams</code>: </b>
5424 the number of fixed parameters of the function
5425 (always 0&nbsp;for C&nbsp;functions).
5426 </li>
5427
5428 <li><b><code>isvararg</code>: </b>
5429 true if the function is a vararg function
5430 (always true for C&nbsp;functions).
5431 </li>
5432
5433 </ul>
5434
5435
5436
5437
5438 <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
5439 <span class="apii">[-0, +0, &ndash;]</span>
5440 <pre>lua_Hook lua_gethook (lua_State *L);</pre>
5441
5442 <p>
5443 Returns the current hook function.
5444
5445
5446
5447
5448
5449 <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
5450 <span class="apii">[-0, +0, &ndash;]</span>
5451 <pre>int lua_gethookcount (lua_State *L);</pre>
5452
5453 <p>
5454 Returns the current hook count.
5455
5456
5457
5458
5459
5460 <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
5461 <span class="apii">[-0, +0, &ndash;]</span>
5462 <pre>int lua_gethookmask (lua_State *L);</pre>
5463
5464 <p>
5465 Returns the current hook mask.
5466
5467
5468
5469
5470
5471 <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
5472 <span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span>
5473 <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
5474
5475 <p>
5476 Gets information about a specific function or function invocation.
5477
5478
5479 <p>
5480 To get information about a function invocation,
5481 the parameter <code>ar</code> must be a valid activation record that was
5482 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5483 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5484
5485
5486 <p>
5487 To get information about a function you push it onto the stack
5488 and start the <code>what</code> string with the character '<code>&gt;</code>'.
5489 (In that case,
5490 <code>lua_getinfo</code> pops the function from the top of the stack.)
5491 For instance, to know in which line a function <code>f</code> was defined,
5492 you can write the following code:
5493
5494 <pre>
5495 lua_Debug ar;
5496 lua_getglobal(L, "f"); /* get global 'f' */
5497 lua_getinfo(L, "&gt;S", &amp;ar);
5498 printf("%d\n", ar.linedefined);
5499 </pre>
5500
5501 <p>
5502 Each character in the string <code>what</code>
5503 selects some fields of the structure <code>ar</code> to be filled or
5504 a value to be pushed on the stack:
5505
5506 <ul>
5507
5508 <li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
5509 </li>
5510
5511 <li><b>'<code>S</code>': </b>
5512 fills in the fields <code>source</code>, <code>short_src</code>,
5513 <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
5514 </li>
5515
5516 <li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
5517 </li>
5518
5519 <li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
5520 </li>
5521
5522 <li><b>'<code>u</code>': </b> fills in the fields
5523 <code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
5524 </li>
5525
5526 <li><b>'<code>f</code>': </b>
5527 pushes onto the stack the function that is
5528 running at the given level;
5529 </li>
5530
5531 <li><b>'<code>L</code>': </b>
5532 pushes onto the stack a table whose indices are the
5533 numbers of the lines that are valid on the function.
5534 (A <em>valid line</em> is a line with some associated code,
5535 that is, a line where you can put a break point.
5536 Non-valid lines include empty lines and comments.)
5537
5538
5539 <p>
5540 If this option is given together with option '<code>f</code>',
5541 its table is pushed after the function.
5542 </li>
5543
5544 </ul>
5545
5546 <p>
5547 This function returns 0 on error
5548 (for instance, an invalid option in <code>what</code>).
5549
5550
5551
5552
5553
5554 <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
5555 <span class="apii">[-0, +(0|1), &ndash;]</span>
5556 <pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
5557
5558 <p>
5559 Gets information about a local variable of
5560 a given activation record or a given function.
5561
5562
5563 <p>
5564 In the first case,
5565 the parameter <code>ar</code> must be a valid activation record that was
5566 filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5567 given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5568 The index <code>n</code> selects which local variable to inspect;
5569 see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
5570 and names.
5571
5572
5573 <p>
5574 <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
5575 and returns its name.
5576
5577
5578 <p>
5579 In the second case, <code>ar</code> must be <code>NULL</code> and the function
5580 to be inspected must be at the top of the stack.
5581 In this case, only parameters of Lua functions are visible
5582 (as there is no information about what variables are active)
5583 and no values are pushed onto the stack.
5584
5585
5586 <p>
5587 Returns <code>NULL</code> (and pushes nothing)
5588 when the index is greater than
5589 the number of active local variables.
5590
5591
5592
5593
5594
5595 <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
5596 <span class="apii">[-0, +0, &ndash;]</span>
5597 <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
5598
5599 <p>
5600 Gets information about the interpreter runtime stack.
5601
5602
5603 <p>
5604 This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
5605 an identification of the <em>activation record</em>
5606 of the function executing at a given level.
5607 Level&nbsp;0 is the current running function,
5608 whereas level <em>n+1</em> is the function that has called level <em>n</em>
5609 (except for tail calls, which do not count on the stack).
5610 When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
5611 when called with a level greater than the stack depth,
5612 it returns 0.
5613
5614
5615
5616
5617
5618 <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
5619 <span class="apii">[-0, +(0|1), &ndash;]</span>
5620 <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
5621
5622 <p>
5623 Gets information about a closure's upvalue.
5624 (For Lua functions,
5625 upvalues are the external local variables that the function uses,
5626 and that are consequently included in its closure.)
5627 <a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
5628 pushes the upvalue's value onto the stack,
5629 and returns its name.
5630 <code>funcindex</code> points to the closure in the stack.
5631 (Upvalues have no particular order,
5632 as they are active through the whole function.
5633 So, they are numbered in an arbitrary order.)
5634
5635
5636 <p>
5637 Returns <code>NULL</code> (and pushes nothing)
5638 when the index is greater than the number of upvalues.
5639 For C&nbsp;functions, this function uses the empty string <code>""</code>
5640 as a name for all upvalues.
5641
5642
5643
5644
5645
5646 <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
5647 <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
5648
5649 <p>
5650 Type for debugging hook functions.
5651
5652
5653 <p>
5654 Whenever a hook is called, its <code>ar</code> argument has its field
5655 <code>event</code> set to the specific event that triggered the hook.
5656 Lua identifies these events with the following constants:
5657 <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
5658 <a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
5659 and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
5660 Moreover, for line events, the field <code>currentline</code> is also set.
5661 To get the value of any other field in <code>ar</code>,
5662 the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5663
5664
5665 <p>
5666 For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
5667 the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
5668 in this case, there will be no corresponding return event.
5669
5670
5671 <p>
5672 While Lua is running a hook, it disables other calls to hooks.
5673 Therefore, if a hook calls back Lua to execute a function or a chunk,
5674 this execution occurs without any calls to hooks.
5675
5676
5677 <p>
5678 Hook functions cannot have continuations,
5679 that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5680 <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>.
5681
5682
5683 <p>
5684 Hook functions can yield under the following conditions:
5685 Only count and line events can yield
5686 and they cannot yield any value;
5687 to yield a hook function must finish its execution
5688 calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero.
5689
5690
5691
5692
5693
5694 <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
5695 <span class="apii">[-0, +0, &ndash;]</span>
5696 <pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5697
5698 <p>
5699 Sets the debugging hook function.
5700
5701
5702 <p>
5703 Argument <code>f</code> is the hook function.
5704 <code>mask</code> specifies on which events the hook will be called:
5705 it is formed by a bitwise or of the constants
5706 <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
5707 <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
5708 <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
5709 and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
5710 The <code>count</code> argument is only meaningful when the mask
5711 includes <code>LUA_MASKCOUNT</code>.
5712 For each event, the hook is called as explained below:
5713
5714 <ul>
5715
5716 <li><b>The call hook: </b> is called when the interpreter calls a function.
5717 The hook is called just after Lua enters the new function,
5718 before the function gets its arguments.
5719 </li>
5720
5721 <li><b>The return hook: </b> is called when the interpreter returns from a function.
5722 The hook is called just before Lua leaves the function.
5723 There is no standard way to access the values
5724 to be returned by the function.
5725 </li>
5726
5727 <li><b>The line hook: </b> is called when the interpreter is about to
5728 start the execution of a new line of code,
5729 or when it jumps back in the code (even to the same line).
5730 (This event only happens while Lua is executing a Lua function.)
5731 </li>
5732
5733 <li><b>The count hook: </b> is called after the interpreter executes every
5734 <code>count</code> instructions.
5735 (This event only happens while Lua is executing a Lua function.)
5736 </li>
5737
5738 </ul>
5739
5740 <p>
5741 A hook is disabled by setting <code>mask</code> to zero.
5742
5743
5744
5745
5746
5747 <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
5748 <span class="apii">[-(0|1), +0, &ndash;]</span>
5749 <pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
5750
5751 <p>
5752 Sets the value of a local variable of a given activation record.
5753 Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
5754 (see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
5755 <a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
5756 to the variable and returns its name.
5757 It also pops the value from the stack.
5758
5759
5760 <p>
5761 Returns <code>NULL</code> (and pops nothing)
5762 when the index is greater than
5763 the number of active local variables.
5764
5765
5766
5767
5768
5769 <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
5770 <span class="apii">[-(0|1), +0, &ndash;]</span>
5771 <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
5772
5773 <p>
5774 Sets the value of a closure's upvalue.
5775 It assigns the value at the top of the stack
5776 to the upvalue and returns its name.
5777 It also pops the value from the stack.
5778 Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
5779 (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
5780
5781
5782 <p>
5783 Returns <code>NULL</code> (and pops nothing)
5784 when the index is greater than the number of upvalues.
5785
5786
5787
5788
5789
5790 <hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
5791 <span class="apii">[-0, +0, &ndash;]</span>
5792 <pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
5793
5794 <p>
5795 Returns a unique identifier for the upvalue numbered <code>n</code>
5796 from the closure at index <code>funcindex</code>.
5797 Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
5798 (see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>)
5799 (but <code>n</code> cannot be greater than the number of upvalues).
5800
5801
5802 <p>
5803 These unique identifiers allow a program to check whether different
5804 closures share upvalues.
5805 Lua closures that share an upvalue
5806 (that is, that access a same external local variable)
5807 will return identical ids for those upvalue indices.
5808
5809
5810
5811
5812
5813 <hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
5814 <span class="apii">[-0, +0, &ndash;]</span>
5815 <pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
5816 int funcindex2, int n2);</pre>
5817
5818 <p>
5819 Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
5820 refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
5821
5822
5823
5824
5825
5826
5827
5828 <h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
5829
5830 <p>
5831
5832 The <em>auxiliary library</em> provides several convenient functions
5833 to interface C with Lua.
5834 While the basic API provides the primitive functions for all
5835 interactions between C and Lua,
5836 the auxiliary library provides higher-level functions for some
5837 common tasks.
5838
5839
5840 <p>
5841 All functions and types from the auxiliary library
5842 are defined in header file <code>lauxlib.h</code> and
5843 have a prefix <code>luaL_</code>.
5844
5845
5846 <p>
5847 All functions in the auxiliary library are built on
5848 top of the basic API,
5849 and so they provide nothing that cannot be done with that API.
5850 Nevertheless, the use of the auxiliary library ensures
5851 more consistency to your code.
5852
5853
5854 <p>
5855 Several functions in the auxiliary library use internally some
5856 extra stack slots.
5857 When a function in the auxiliary library uses less than five slots,
5858 it does not check the stack size;
5859 it simply assumes that there are enough slots.
5860
5861
5862 <p>
5863 Several functions in the auxiliary library are used to
5864 check C&nbsp;function arguments.
5865 Because the error message is formatted for arguments
5866 (e.g., "<code>bad argument #1</code>"),
5867 you should not use these functions for other stack values.
5868
5869
5870 <p>
5871 Functions called <code>luaL_check*</code>
5872 always raise an error if the check is not satisfied.
5873
5874
5875
5876 <h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
5877
5878 <p>
5879 Here we list all functions and types from the auxiliary library
5880 in alphabetical order.
5881
5882
5883
5884 <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
5885 <span class="apii">[-?, +?, <em>e</em>]</span>
5886 <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
5887
5888 <p>
5889 Adds the byte <code>c</code> to the buffer <code>B</code>
5890 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5891
5892
5893
5894
5895
5896 <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
5897 <span class="apii">[-?, +?, <em>e</em>]</span>
5898 <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
5899
5900 <p>
5901 Adds the string pointed to by <code>s</code> with length <code>l</code> to
5902 the buffer <code>B</code>
5903 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5904 The string can contain embedded zeros.
5905
5906
5907
5908
5909
5910 <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
5911 <span class="apii">[-?, +?, <em>e</em>]</span>
5912 <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
5913
5914 <p>
5915 Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
5916 a string of length <code>n</code> previously copied to the
5917 buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
5918
5919
5920
5921
5922
5923 <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
5924 <span class="apii">[-?, +?, <em>e</em>]</span>
5925 <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
5926
5927 <p>
5928 Adds the zero-terminated string pointed to by <code>s</code>
5929 to the buffer <code>B</code>
5930 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5931
5932
5933
5934
5935
5936 <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
5937 <span class="apii">[-1, +?, <em>e</em>]</span>
5938 <pre>void luaL_addvalue (luaL_Buffer *B);</pre>
5939
5940 <p>
5941 Adds the value at the top of the stack
5942 to the buffer <code>B</code>
5943 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5944 Pops the value.
5945
5946
5947 <p>
5948 This is the only function on string buffers that can (and must)
5949 be called with an extra element on the stack,
5950 which is the value to be added to the buffer.
5951
5952
5953
5954
5955
5956 <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
5957 <span class="apii">[-0, +0, <em>v</em>]</span>
5958 <pre>void luaL_argcheck (lua_State *L,
5959 int cond,
5960 int arg,
5961 const char *extramsg);</pre>
5962
5963 <p>
5964 Checks whether <code>cond</code> is true.
5965 If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
5966
5967
5968
5969
5970
5971 <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
5972 <span class="apii">[-0, +0, <em>v</em>]</span>
5973 <pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
5974
5975 <p>
5976 Raises an error reporting a problem with argument <code>arg</code>
5977 of the C function that called it,
5978 using a standard message
5979 that includes <code>extramsg</code> as a comment:
5980
5981 <pre>
5982 bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
5983 </pre><p>
5984 This function never returns.
5985
5986
5987
5988
5989
5990 <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
5991 <pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
5992
5993 <p>
5994 Type for a <em>string buffer</em>.
5995
5996
5997 <p>
5998 A string buffer allows C&nbsp;code to build Lua strings piecemeal.
5999 Its pattern of use is as follows:
6000
6001 <ul>
6002
6003 <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6004
6005 <li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
6006
6007 <li>
6008 Then add string pieces to the buffer calling any of
6009 the <code>luaL_add*</code> functions.
6010 </li>
6011
6012 <li>
6013 Finish by calling <code>luaL_pushresult(&amp;b)</code>.
6014 This call leaves the final string on the top of the stack.
6015 </li>
6016
6017 </ul>
6018
6019 <p>
6020 If you know beforehand the total size of the resulting string,
6021 you can use the buffer like this:
6022
6023 <ul>
6024
6025 <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
6026
6027 <li>Then initialize it and preallocate a space of
6028 size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
6029
6030 <li>Then copy the string into that space.</li>
6031
6032 <li>
6033 Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
6034 where <code>sz</code> is the total size of the resulting string
6035 copied into that space.
6036 </li>
6037
6038 </ul>
6039
6040 <p>
6041 During its normal operation,
6042 a string buffer uses a variable number of stack slots.
6043 So, while using a buffer, you cannot assume that you know where
6044 the top of the stack is.
6045 You can use the stack between successive calls to buffer operations
6046 as long as that use is balanced;
6047 that is,
6048 when you call a buffer operation,
6049 the stack is at the same level
6050 it was immediately after the previous buffer operation.
6051 (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
6052 After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
6053 level when the buffer was initialized,
6054 plus the final string on its top.
6055
6056
6057
6058
6059
6060 <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
6061 <span class="apii">[-0, +0, &ndash;]</span>
6062 <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
6063
6064 <p>
6065 Initializes a buffer <code>B</code>.
6066 This function does not allocate any space;
6067 the buffer must be declared as a variable
6068 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6069
6070
6071
6072
6073
6074 <hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
6075 <span class="apii">[-?, +?, <em>e</em>]</span>
6076 <pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6077
6078 <p>
6079 Equivalent to the sequence
6080 <a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6081
6082
6083
6084
6085
6086 <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6087 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
6088 <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6089
6090 <p>
6091 Calls a metamethod.
6092
6093
6094 <p>
6095 If the object at index <code>obj</code> has a metatable and this
6096 metatable has a field <code>e</code>,
6097 this function calls this field passing the object as its only argument.
6098 In this case this function returns true and pushes onto the
6099 stack the value returned by the call.
6100 If there is no metatable or no metamethod,
6101 this function returns false (without pushing any value on the stack).
6102
6103
6104
6105
6106
6107 <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6108 <span class="apii">[-0, +0, <em>v</em>]</span>
6109 <pre>void luaL_checkany (lua_State *L, int arg);</pre>
6110
6111 <p>
6112 Checks whether the function has an argument
6113 of any type (including <b>nil</b>) at position <code>arg</code>.
6114
6115
6116
6117
6118
6119 <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6120 <span class="apii">[-0, +0, <em>v</em>]</span>
6121 <pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6122
6123 <p>
6124 Checks whether the function argument <code>arg</code> is an integer
6125 (or can be converted to an integer)
6126 and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6127
6128
6129
6130
6131
6132 <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6133 <span class="apii">[-0, +0, <em>v</em>]</span>
6134 <pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6135
6136 <p>
6137 Checks whether the function argument <code>arg</code> is a string
6138 and returns this string;
6139 if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
6140 with the string's length.
6141
6142
6143 <p>
6144 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6145 so all conversions and caveats of that function apply here.
6146
6147
6148
6149
6150
6151 <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6152 <span class="apii">[-0, +0, <em>v</em>]</span>
6153 <pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6154
6155 <p>
6156 Checks whether the function argument <code>arg</code> is a number
6157 and returns this number.
6158
6159
6160
6161
6162
6163 <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6164 <span class="apii">[-0, +0, <em>v</em>]</span>
6165 <pre>int luaL_checkoption (lua_State *L,
6166 int arg,
6167 const char *def,
6168 const char *const lst[]);</pre>
6169
6170 <p>
6171 Checks whether the function argument <code>arg</code> is a string and
6172 searches for this string in the array <code>lst</code>
6173 (which must be NULL-terminated).
6174 Returns the index in the array where the string was found.
6175 Raises an error if the argument is not a string or
6176 if the string cannot be found.
6177
6178
6179 <p>
6180 If <code>def</code> is not <code>NULL</code>,
6181 the function uses <code>def</code> as a default value when
6182 there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6183
6184
6185 <p>
6186 This is a useful function for mapping strings to C&nbsp;enums.
6187 (The usual convention in Lua libraries is
6188 to use strings instead of numbers to select options.)
6189
6190
6191
6192
6193
6194 <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6195 <span class="apii">[-0, +0, <em>v</em>]</span>
6196 <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6197
6198 <p>
6199 Grows the stack size to <code>top + sz</code> elements,
6200 raising an error if the stack cannot grow to that size.
6201 <code>msg</code> is an additional text to go into the error message
6202 (or <code>NULL</code> for no additional text).
6203
6204
6205
6206
6207
6208 <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6209 <span class="apii">[-0, +0, <em>v</em>]</span>
6210 <pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6211
6212 <p>
6213 Checks whether the function argument <code>arg</code> is a string
6214 and returns this string.
6215
6216
6217 <p>
6218 This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6219 so all conversions and caveats of that function apply here.
6220
6221
6222
6223
6224
6225 <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6226 <span class="apii">[-0, +0, <em>v</em>]</span>
6227 <pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6228
6229 <p>
6230 Checks whether the function argument <code>arg</code> has type <code>t</code>.
6231 See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6232
6233
6234
6235
6236
6237 <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6238 <span class="apii">[-0, +0, <em>v</em>]</span>
6239 <pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6240
6241 <p>
6242 Checks whether the function argument <code>arg</code> is a userdata
6243 of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6244 returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6245
6246
6247
6248
6249
6250 <hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6251 <span class="apii">[-0, +0, &ndash;]</span>
6252 <pre>void luaL_checkversion (lua_State *L);</pre>
6253
6254 <p>
6255 Checks whether the core running the call,
6256 the core that created the Lua state,
6257 and the code making the call are all using the same version of Lua.
6258 Also checks whether the core running the call
6259 and the core that created the Lua state
6260 are using the same address space.
6261
6262
6263
6264
6265
6266 <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6267 <span class="apii">[-0, +?, <em>e</em>]</span>
6268 <pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6269
6270 <p>
6271 Loads and runs the given file.
6272 It is defined as the following macro:
6273
6274 <pre>
6275 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6276 </pre><p>
6277 It returns false if there are no errors
6278 or true in case of errors.
6279
6280
6281
6282
6283
6284 <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6285 <span class="apii">[-0, +?, &ndash;]</span>
6286 <pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6287
6288 <p>
6289 Loads and runs the given string.
6290 It is defined as the following macro:
6291
6292 <pre>
6293 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6294 </pre><p>
6295 It returns false if there are no errors
6296 or true in case of errors.
6297
6298
6299
6300
6301
6302 <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6303 <span class="apii">[-0, +0, <em>v</em>]</span>
6304 <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6305
6306 <p>
6307 Raises an error.
6308 The error message format is given by <code>fmt</code>
6309 plus any extra arguments,
6310 following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6311 It also adds at the beginning of the message the file name and
6312 the line number where the error occurred,
6313 if this information is available.
6314
6315
6316 <p>
6317 This function never returns,
6318 but it is an idiom to use it in C&nbsp;functions
6319 as <code>return luaL_error(<em>args</em>)</code>.
6320
6321
6322
6323
6324
6325 <hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
6326 <span class="apii">[-0, +3, <em>e</em>]</span>
6327 <pre>int luaL_execresult (lua_State *L, int stat);</pre>
6328
6329 <p>
6330 This function produces the return values for
6331 process-related functions in the standard library
6332 (<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
6333
6334
6335
6336
6337
6338 <hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
6339 <span class="apii">[-0, +(1|3), <em>e</em>]</span>
6340 <pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
6341
6342 <p>
6343 This function produces the return values for
6344 file-related functions in the standard library
6345 (<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.).
6346
6347
6348
6349
6350
6351 <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
6352 <span class="apii">[-0, +(0|1), <em>e</em>]</span>
6353 <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
6354
6355 <p>
6356 Pushes onto the stack the field <code>e</code> from the metatable
6357 of the object at index <code>obj</code> and returns the type of pushed value.
6358 If the object does not have a metatable,
6359 or if the metatable does not have this field,
6360 pushes nothing and returns <code>LUA_TNIL</code>.
6361
6362
6363
6364
6365
6366 <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
6367 <span class="apii">[-0, +1, &ndash;]</span>
6368 <pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
6369
6370 <p>
6371 Pushes onto the stack the metatable associated with name <code>tname</code>
6372 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6373 If there is no metatable associated with <code>tname</code>,
6374 returns false and pushes <b>nil</b>.
6375
6376
6377
6378
6379
6380 <hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
6381 <span class="apii">[-0, +1, <em>e</em>]</span>
6382 <pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
6383
6384 <p>
6385 Ensures that the value <code>t[fname]</code>,
6386 where <code>t</code> is the value at index <code>idx</code>,
6387 is a table,
6388 and pushes that table onto the stack.
6389 Returns true if it finds a previous table there
6390 and false if it creates a new table.
6391
6392
6393
6394
6395
6396 <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
6397 <span class="apii">[-0, +1, <em>e</em>]</span>
6398 <pre>const char *luaL_gsub (lua_State *L,
6399 const char *s,
6400 const char *p,
6401 const char *r);</pre>
6402
6403 <p>
6404 Creates a copy of string <code>s</code> by replacing
6405 any occurrence of the string <code>p</code>
6406 with the string <code>r</code>.
6407 Pushes the resulting string on the stack and returns it.
6408
6409
6410
6411
6412
6413 <hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
6414 <span class="apii">[-0, +0, <em>e</em>]</span>
6415 <pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
6416
6417 <p>
6418 Returns the "length" of the value at the given index
6419 as a number;
6420 it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
6421 Raises an error if the result of the operation is not an integer.
6422 (This case only can happen through metamethods.)
6423
6424
6425
6426
6427
6428 <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
6429 <span class="apii">[-0, +1, &ndash;]</span>
6430 <pre>int luaL_loadbuffer (lua_State *L,
6431 const char *buff,
6432 size_t sz,
6433 const char *name);</pre>
6434
6435 <p>
6436 Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
6437
6438
6439
6440
6441
6442 <hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
6443 <span class="apii">[-0, +1, &ndash;]</span>
6444 <pre>int luaL_loadbufferx (lua_State *L,
6445 const char *buff,
6446 size_t sz,
6447 const char *name,
6448 const char *mode);</pre>
6449
6450 <p>
6451 Loads a buffer as a Lua chunk.
6452 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
6453 buffer pointed to by <code>buff</code> with size <code>sz</code>.
6454
6455
6456 <p>
6457 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6458 <code>name</code> is the chunk name,
6459 used for debug information and error messages.
6460 The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6461
6462
6463
6464
6465
6466 <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
6467 <span class="apii">[-0, +1, <em>e</em>]</span>
6468 <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
6469
6470 <p>
6471 Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
6472
6473
6474
6475
6476
6477 <hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
6478 <span class="apii">[-0, +1, <em>e</em>]</span>
6479 <pre>int luaL_loadfilex (lua_State *L, const char *filename,
6480 const char *mode);</pre>
6481
6482 <p>
6483 Loads a file as a Lua chunk.
6484 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
6485 named <code>filename</code>.
6486 If <code>filename</code> is <code>NULL</code>,
6487 then it loads from the standard input.
6488 The first line in the file is ignored if it starts with a <code>#</code>.
6489
6490
6491 <p>
6492 The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6493
6494
6495 <p>
6496 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
6497 but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
6498 if it cannot open/read the file or the file has a wrong mode.
6499
6500
6501 <p>
6502 As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6503 it does not run it.
6504
6505
6506
6507
6508
6509 <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
6510 <span class="apii">[-0, +1, &ndash;]</span>
6511 <pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
6512
6513 <p>
6514 Loads a string as a Lua chunk.
6515 This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
6516 the zero-terminated string <code>s</code>.
6517
6518
6519 <p>
6520 This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6521
6522
6523 <p>
6524 Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6525 it does not run it.
6526
6527
6528
6529
6530
6531 <hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
6532 <span class="apii">[-0, +1, <em>e</em>]</span>
6533 <pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
6534
6535 <p>
6536 Creates a new table and registers there
6537 the functions in list <code>l</code>.
6538
6539
6540 <p>
6541 It is implemented as the following macro:
6542
6543 <pre>
6544 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
6545 </pre><p>
6546 The array <code>l</code> must be the actual array,
6547 not a pointer to it.
6548
6549
6550
6551
6552
6553 <hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
6554 <span class="apii">[-0, +1, <em>e</em>]</span>
6555 <pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
6556
6557 <p>
6558 Creates a new table with a size optimized
6559 to store all entries in the array <code>l</code>
6560 (but does not actually store them).
6561 It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
6562 (see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
6563
6564
6565 <p>
6566 It is implemented as a macro.
6567 The array <code>l</code> must be the actual array,
6568 not a pointer to it.
6569
6570
6571
6572
6573
6574 <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
6575 <span class="apii">[-0, +1, <em>e</em>]</span>
6576 <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
6577
6578 <p>
6579 If the registry already has the key <code>tname</code>,
6580 returns 0.
6581 Otherwise,
6582 creates a new table to be used as a metatable for userdata,
6583 adds to this new table the pair <code>__name = tname</code>,
6584 adds to the registry the pair <code>[tname] = new table</code>,
6585 and returns 1.
6586 (The entry <code>__name</code> is used by some error-reporting functions.)
6587
6588
6589 <p>
6590 In both cases pushes onto the stack the final value associated
6591 with <code>tname</code> in the registry.
6592
6593
6594
6595
6596
6597 <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
6598 <span class="apii">[-0, +0, &ndash;]</span>
6599 <pre>lua_State *luaL_newstate (void);</pre>
6600
6601 <p>
6602 Creates a new Lua state.
6603 It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
6604 allocator based on the standard&nbsp;C <code>realloc</code> function
6605 and then sets a panic function (see <a href="#4.6">&sect;4.6</a>) that prints
6606 an error message to the standard error output in case of fatal
6607 errors.
6608
6609
6610 <p>
6611 Returns the new state,
6612 or <code>NULL</code> if there is a memory allocation error.
6613
6614
6615
6616
6617
6618 <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
6619 <span class="apii">[-0, +0, <em>e</em>]</span>
6620 <pre>void luaL_openlibs (lua_State *L);</pre>
6621
6622 <p>
6623 Opens all standard Lua libraries into the given state.
6624
6625
6626
6627
6628
6629 <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
6630 <span class="apii">[-0, +0, <em>v</em>]</span>
6631 <pre>lua_Integer luaL_optinteger (lua_State *L,
6632 int arg,
6633 lua_Integer d);</pre>
6634
6635 <p>
6636 If the function argument <code>arg</code> is an integer
6637 (or convertible to an integer),
6638 returns this integer.
6639 If this argument is absent or is <b>nil</b>,
6640 returns <code>d</code>.
6641 Otherwise, raises an error.
6642
6643
6644
6645
6646
6647 <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
6648 <span class="apii">[-0, +0, <em>v</em>]</span>
6649 <pre>const char *luaL_optlstring (lua_State *L,
6650 int arg,
6651 const char *d,
6652 size_t *l);</pre>
6653
6654 <p>
6655 If the function argument <code>arg</code> is a string,
6656 returns this string.
6657 If this argument is absent or is <b>nil</b>,
6658 returns <code>d</code>.
6659 Otherwise, raises an error.
6660
6661
6662 <p>
6663 If <code>l</code> is not <code>NULL</code>,
6664 fills the position <code>*l</code> with the result's length.
6665
6666
6667
6668
6669
6670 <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
6671 <span class="apii">[-0, +0, <em>v</em>]</span>
6672 <pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
6673
6674 <p>
6675 If the function argument <code>arg</code> is a number,
6676 returns this number.
6677 If this argument is absent or is <b>nil</b>,
6678 returns <code>d</code>.
6679 Otherwise, raises an error.
6680
6681
6682
6683
6684
6685 <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
6686 <span class="apii">[-0, +0, <em>v</em>]</span>
6687 <pre>const char *luaL_optstring (lua_State *L,
6688 int arg,
6689 const char *d);</pre>
6690
6691 <p>
6692 If the function argument <code>arg</code> is a string,
6693 returns this string.
6694 If this argument is absent or is <b>nil</b>,
6695 returns <code>d</code>.
6696 Otherwise, raises an error.
6697
6698
6699
6700
6701
6702 <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
6703 <span class="apii">[-?, +?, <em>e</em>]</span>
6704 <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
6705
6706 <p>
6707 Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
6708 with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
6709
6710
6711
6712
6713
6714 <hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
6715 <span class="apii">[-?, +?, <em>e</em>]</span>
6716 <pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
6717
6718 <p>
6719 Returns an address to a space of size <code>sz</code>
6720 where you can copy a string to be added to buffer <code>B</code>
6721 (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6722 After copying the string into this space you must call
6723 <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
6724 it to the buffer.
6725
6726
6727
6728
6729
6730 <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
6731 <span class="apii">[-?, +1, <em>e</em>]</span>
6732 <pre>void luaL_pushresult (luaL_Buffer *B);</pre>
6733
6734 <p>
6735 Finishes the use of buffer <code>B</code> leaving the final string on
6736 the top of the stack.
6737
6738
6739
6740
6741
6742 <hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
6743 <span class="apii">[-?, +1, <em>e</em>]</span>
6744 <pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
6745
6746 <p>
6747 Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
6748
6749
6750
6751
6752
6753 <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
6754 <span class="apii">[-1, +0, <em>e</em>]</span>
6755 <pre>int luaL_ref (lua_State *L, int t);</pre>
6756
6757 <p>
6758 Creates and returns a <em>reference</em>,
6759 in the table at index <code>t</code>,
6760 for the object at the top of the stack (and pops the object).
6761
6762
6763 <p>
6764 A reference is a unique integer key.
6765 As long as you do not manually add integer keys into table <code>t</code>,
6766 <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
6767 You can retrieve an object referred by reference <code>r</code>
6768 by calling <code>lua_rawgeti(L, t, r)</code>.
6769 Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
6770
6771
6772 <p>
6773 If the object at the top of the stack is <b>nil</b>,
6774 <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
6775 The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
6776 from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
6777
6778
6779
6780
6781
6782 <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
6783 <pre>typedef struct luaL_Reg {
6784 const char *name;
6785 lua_CFunction func;
6786 } luaL_Reg;</pre>
6787
6788 <p>
6789 Type for arrays of functions to be registered by
6790 <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
6791 <code>name</code> is the function name and <code>func</code> is a pointer to
6792 the function.
6793 Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
6794 in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
6795
6796
6797
6798
6799
6800 <hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
6801 <span class="apii">[-0, +1, <em>e</em>]</span>
6802 <pre>void luaL_requiref (lua_State *L, const char *modname,
6803 lua_CFunction openf, int glb);</pre>
6804
6805 <p>
6806 If <code>modname</code> is not already present in <a href="#pdf-package.loaded"><code>package.loaded</code></a>,
6807 calls function <code>openf</code> with string <code>modname</code> as an argument
6808 and sets the call result in <code>package.loaded[modname]</code>,
6809 as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
6810
6811
6812 <p>
6813 If <code>glb</code> is true,
6814 also stores the module into global <code>modname</code>.
6815
6816
6817 <p>
6818 Leaves a copy of the module on the stack.
6819
6820
6821
6822
6823
6824 <hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
6825 <span class="apii">[-nup, +0, <em>e</em>]</span>
6826 <pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
6827
6828 <p>
6829 Registers all functions in the array <code>l</code>
6830 (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
6831 (below optional upvalues, see next).
6832
6833
6834 <p>
6835 When <code>nup</code> is not zero,
6836 all functions are created sharing <code>nup</code> upvalues,
6837 which must be previously pushed on the stack
6838 on top of the library table.
6839 These values are popped from the stack after the registration.
6840
6841
6842
6843
6844
6845 <hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
6846 <span class="apii">[-0, +0, &ndash;]</span>
6847 <pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
6848
6849 <p>
6850 Sets the metatable of the object at the top of the stack
6851 as the metatable associated with name <code>tname</code>
6852 in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6853
6854
6855
6856
6857
6858 <hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
6859 <pre>typedef struct luaL_Stream {
6860 FILE *f;
6861 lua_CFunction closef;
6862 } luaL_Stream;</pre>
6863
6864 <p>
6865 The standard representation for file handles,
6866 which is used by the standard I/O library.
6867
6868
6869 <p>
6870 A file handle is implemented as a full userdata,
6871 with a metatable called <code>LUA_FILEHANDLE</code>
6872 (where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
6873 The metatable is created by the I/O library
6874 (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6875
6876
6877 <p>
6878 This userdata must start with the structure <code>luaL_Stream</code>;
6879 it can contain other data after this initial structure.
6880 Field <code>f</code> points to the corresponding C stream
6881 (or it can be <code>NULL</code> to indicate an incompletely created handle).
6882 Field <code>closef</code> points to a Lua function
6883 that will be called to close the stream
6884 when the handle is closed or collected;
6885 this function receives the file handle as its sole argument and
6886 must return either <b>true</b> (in case of success)
6887 or <b>nil</b> plus an error message (in case of error).
6888 Once Lua calls this field,
6889 the field value is changed to <code>NULL</code>
6890 to signal that the handle is closed.
6891
6892
6893
6894
6895
6896 <hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
6897 <span class="apii">[-0, +0, <em>e</em>]</span>
6898 <pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
6899
6900 <p>
6901 This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
6902 except that, when the test fails,
6903 it returns <code>NULL</code> instead of raising an error.
6904
6905
6906
6907
6908
6909 <hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
6910 <span class="apii">[-0, +1, <em>e</em>]</span>
6911 <pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
6912
6913 <p>
6914 Converts any Lua value at the given index to a C&nbsp;string
6915 in a reasonable format.
6916 The resulting string is pushed onto the stack and also
6917 returned by the function.
6918 If <code>len</code> is not <code>NULL</code>,
6919 the function also sets <code>*len</code> with the string length.
6920
6921
6922 <p>
6923 If the value has a metatable with a <code>"__tostring"</code> field,
6924 then <code>luaL_tolstring</code> calls the corresponding metamethod
6925 with the value as argument,
6926 and uses the result of the call as its result.
6927
6928
6929
6930
6931
6932 <hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
6933 <span class="apii">[-0, +1, <em>e</em>]</span>
6934 <pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
6935 int level);</pre>
6936
6937 <p>
6938 Creates and pushes a traceback of the stack <code>L1</code>.
6939 If <code>msg</code> is not <code>NULL</code> it is appended
6940 at the beginning of the traceback.
6941 The <code>level</code> parameter tells at which level
6942 to start the traceback.
6943
6944
6945
6946
6947
6948 <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
6949 <span class="apii">[-0, +0, &ndash;]</span>
6950 <pre>const char *luaL_typename (lua_State *L, int index);</pre>
6951
6952 <p>
6953 Returns the name of the type of the value at the given index.
6954
6955
6956
6957
6958
6959 <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
6960 <span class="apii">[-0, +0, &ndash;]</span>
6961 <pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
6962
6963 <p>
6964 Releases reference <code>ref</code> from the table at index <code>t</code>
6965 (see <a href="#luaL_ref"><code>luaL_ref</code></a>).
6966 The entry is removed from the table,
6967 so that the referred object can be collected.
6968 The reference <code>ref</code> is also freed to be used again.
6969
6970
6971 <p>
6972 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>,
6973 <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
6974
6975
6976
6977
6978
6979 <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
6980 <span class="apii">[-0, +1, <em>e</em>]</span>
6981 <pre>void luaL_where (lua_State *L, int lvl);</pre>
6982
6983 <p>
6984 Pushes onto the stack a string identifying the current position
6985 of the control at level <code>lvl</code> in the call stack.
6986 Typically this string has the following format:
6987
6988 <pre>
6989 <em>chunkname</em>:<em>currentline</em>:
6990 </pre><p>
6991 Level&nbsp;0 is the running function,
6992 level&nbsp;1 is the function that called the running function,
6993 etc.
6994
6995
6996 <p>
6997 This function is used to build a prefix for error messages.
6998
6999
7000
7001
7002
7003
7004
7005 <h1>6 &ndash; <a name="6">Standard Libraries</a></h1>
7006
7007 <p>
7008 The standard Lua libraries provide useful functions
7009 that are implemented directly through the C&nbsp;API.
7010 Some of these functions provide essential services to the language
7011 (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7012 others provide access to "outside" services (e.g., I/O);
7013 and others could be implemented in Lua itself,
7014 but are quite useful or have critical performance requirements that
7015 deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7016
7017
7018 <p>
7019 All libraries are implemented through the official C&nbsp;API
7020 and are provided as separate C&nbsp;modules.
7021 Currently, Lua has the following standard libraries:
7022
7023 <ul>
7024
7025 <li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7026
7027 <li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7028
7029 <li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7030
7031 <li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7032
7033 <li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7034
7035 <li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7036
7037 <li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7038
7039 <li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7040
7041 <li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7042
7043 <li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7044
7045 </ul><p>
7046 Except for the basic and the package libraries,
7047 each library provides all its functions as fields of a global table
7048 or as methods of its objects.
7049
7050
7051 <p>
7052 To have access to these libraries,
7053 the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7054 which opens all standard libraries.
7055 Alternatively,
7056 the host program can open them individually by using
7057 <a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7058 <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7059 <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7060 <a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7061 <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7062 <a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF8 library),
7063 <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7064 <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7065 <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7066 <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
7067 and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7068 These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7069
7070
7071
7072 <h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7073
7074 <p>
7075 The basic library provides core functions to Lua.
7076 If you do not include this library in your application,
7077 you should check carefully whether you need to provide
7078 implementations for some of its facilities.
7079
7080
7081 <p>
7082 <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7083
7084
7085 <p>
7086 Calls <a href="#pdf-error"><code>error</code></a> if
7087 the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7088 otherwise, returns all its arguments.
7089 In case of error,
7090 <code>message</code> is the error object;
7091 when absent, it defaults to "<code>assertion failed!</code>"
7092
7093
7094
7095
7096 <p>
7097 <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7098
7099
7100 <p>
7101 This function is a generic interface to the garbage collector.
7102 It performs different functions according to its first argument, <code>opt</code>:
7103
7104 <ul>
7105
7106 <li><b>"<code>collect</code>": </b>
7107 performs a full garbage-collection cycle.
7108 This is the default option.
7109 </li>
7110
7111 <li><b>"<code>stop</code>": </b>
7112 stops automatic execution of the garbage collector.
7113 The collector will run only when explicitly invoked,
7114 until a call to restart it.
7115 </li>
7116
7117 <li><b>"<code>restart</code>": </b>
7118 restarts automatic execution of the garbage collector.
7119 </li>
7120
7121 <li><b>"<code>count</code>": </b>
7122 returns the total memory in use by Lua in Kbytes.
7123 The value has a fractional part,
7124 so that it multiplied by 1024
7125 gives the exact number of bytes in use by Lua
7126 (except for overflows).
7127 </li>
7128
7129 <li><b>"<code>step</code>": </b>
7130 performs a garbage-collection step.
7131 The step "size" is controlled by <code>arg</code>.
7132 With a zero value,
7133 the collector will perform one basic (indivisible) step.
7134 For non-zero values,
7135 the collector will perform as if that amount of memory
7136 (in KBytes) had been allocated by Lua.
7137 Returns <b>true</b> if the step finished a collection cycle.
7138 </li>
7139
7140 <li><b>"<code>setpause</code>": </b>
7141 sets <code>arg</code> as the new value for the <em>pause</em> of
7142 the collector (see <a href="#2.5">&sect;2.5</a>).
7143 Returns the previous value for <em>pause</em>.
7144 </li>
7145
7146 <li><b>"<code>setstepmul</code>": </b>
7147 sets <code>arg</code> as the new value for the <em>step multiplier</em> of
7148 the collector (see <a href="#2.5">&sect;2.5</a>).
7149 Returns the previous value for <em>step</em>.
7150 </li>
7151
7152 <li><b>"<code>isrunning</code>": </b>
7153 returns a boolean that tells whether the collector is running
7154 (i.e., not stopped).
7155 </li>
7156
7157 </ul>
7158
7159
7160
7161 <p>
7162 <hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7163 Opens the named file and executes its contents as a Lua chunk.
7164 When called without arguments,
7165 <code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
7166 Returns all values returned by the chunk.
7167 In case of errors, <code>dofile</code> propagates the error
7168 to its caller (that is, <code>dofile</code> does not run in protected mode).
7169
7170
7171
7172
7173 <p>
7174 <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7175 Terminates the last protected function called
7176 and returns <code>message</code> as the error object.
7177 Function <code>error</code> never returns.
7178
7179
7180 <p>
7181 Usually, <code>error</code> adds some information about the error position
7182 at the beginning of the message, if the message is a string.
7183 The <code>level</code> argument specifies how to get the error position.
7184 With level&nbsp;1 (the default), the error position is where the
7185 <code>error</code> function was called.
7186 Level&nbsp;2 points the error to where the function
7187 that called <code>error</code> was called; and so on.
7188 Passing a level&nbsp;0 avoids the addition of error position information
7189 to the message.
7190
7191
7192
7193
7194 <p>
7195 <hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7196 A global variable (not a function) that
7197 holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7198 Lua itself does not use this variable;
7199 changing its value does not affect any environment,
7200 nor vice versa.
7201
7202
7203
7204
7205 <p>
7206 <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7207
7208
7209 <p>
7210 If <code>object</code> does not have a metatable, returns <b>nil</b>.
7211 Otherwise,
7212 if the object's metatable has a <code>"__metatable"</code> field,
7213 returns the associated value.
7214 Otherwise, returns the metatable of the given object.
7215
7216
7217
7218
7219 <p>
7220 <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7221
7222
7223 <p>
7224 Returns three values (an iterator function, the table <code>t</code>, and 0)
7225 so that the construction
7226
7227 <pre>
7228 for i,v in ipairs(t) do <em>body</em> end
7229 </pre><p>
7230 will iterate over the key&ndash;value pairs
7231 (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7232 up to the first nil value.
7233
7234
7235
7236
7237 <p>
7238 <hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
7239
7240
7241 <p>
7242 Loads a chunk.
7243
7244
7245 <p>
7246 If <code>chunk</code> is a string, the chunk is this string.
7247 If <code>chunk</code> is a function,
7248 <code>load</code> calls it repeatedly to get the chunk pieces.
7249 Each call to <code>chunk</code> must return a string that concatenates
7250 with previous results.
7251 A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
7252
7253
7254 <p>
7255 If there are no syntactic errors,
7256 returns the compiled chunk as a function;
7257 otherwise, returns <b>nil</b> plus the error message.
7258
7259
7260 <p>
7261 If the resulting function has upvalues,
7262 the first upvalue is set to the value of <code>env</code>,
7263 if that parameter is given,
7264 or to the value of the global environment.
7265 Other upvalues are initialized with <b>nil</b>.
7266 (When you load a main chunk,
7267 the resulting function will always have exactly one upvalue,
7268 the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
7269 However,
7270 when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7271 the resulting function can have an arbitrary number of upvalues.)
7272 All upvalues are fresh, that is,
7273 they are not shared with any other function.
7274
7275
7276 <p>
7277 <code>chunkname</code> is used as the name of the chunk for error messages
7278 and debug information (see <a href="#4.9">&sect;4.9</a>).
7279 When absent,
7280 it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
7281 or to "<code>=(load)</code>" otherwise.
7282
7283
7284 <p>
7285 The string <code>mode</code> controls whether the chunk can be text or binary
7286 (that is, a precompiled chunk).
7287 It may be the string "<code>b</code>" (only binary chunks),
7288 "<code>t</code>" (only text chunks),
7289 or "<code>bt</code>" (both binary and text).
7290 The default is "<code>bt</code>".
7291
7292
7293 <p>
7294 Lua does not check the consistency of binary chunks.
7295 Maliciously crafted binary chunks can crash
7296 the interpreter.
7297
7298
7299
7300
7301 <p>
7302 <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
7303
7304
7305 <p>
7306 Similar to <a href="#pdf-load"><code>load</code></a>,
7307 but gets the chunk from file <code>filename</code>
7308 or from the standard input,
7309 if no file name is given.
7310
7311
7312
7313
7314 <p>
7315 <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
7316
7317
7318 <p>
7319 Allows a program to traverse all fields of a table.
7320 Its first argument is a table and its second argument
7321 is an index in this table.
7322 <code>next</code> returns the next index of the table
7323 and its associated value.
7324 When called with <b>nil</b> as its second argument,
7325 <code>next</code> returns an initial index
7326 and its associated value.
7327 When called with the last index,
7328 or with <b>nil</b> in an empty table,
7329 <code>next</code> returns <b>nil</b>.
7330 If the second argument is absent, then it is interpreted as <b>nil</b>.
7331 In particular,
7332 you can use <code>next(t)</code> to check whether a table is empty.
7333
7334
7335 <p>
7336 The order in which the indices are enumerated is not specified,
7337 <em>even for numeric indices</em>.
7338 (To traverse a table in numeric order,
7339 use a numerical <b>for</b>.)
7340
7341
7342 <p>
7343 The behavior of <code>next</code> is undefined if,
7344 during the traversal,
7345 you assign any value to a non-existent field in the table.
7346 You may however modify existing fields.
7347 In particular, you may clear existing fields.
7348
7349
7350
7351
7352 <p>
7353 <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
7354
7355
7356 <p>
7357 If <code>t</code> has a metamethod <code>__pairs</code>,
7358 calls it with <code>t</code> as argument and returns the first three
7359 results from the call.
7360
7361
7362 <p>
7363 Otherwise,
7364 returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
7365 so that the construction
7366
7367 <pre>
7368 for k,v in pairs(t) do <em>body</em> end
7369 </pre><p>
7370 will iterate over all key&ndash;value pairs of table <code>t</code>.
7371
7372
7373 <p>
7374 See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
7375 the table during its traversal.
7376
7377
7378
7379
7380 <p>
7381 <hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
7382
7383
7384 <p>
7385 Calls function <code>f</code> with
7386 the given arguments in <em>protected mode</em>.
7387 This means that any error inside&nbsp;<code>f</code> is not propagated;
7388 instead, <code>pcall</code> catches the error
7389 and returns a status code.
7390 Its first result is the status code (a boolean),
7391 which is true if the call succeeds without errors.
7392 In such case, <code>pcall</code> also returns all results from the call,
7393 after this first result.
7394 In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
7395
7396
7397
7398
7399 <p>
7400 <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
7401 Receives any number of arguments
7402 and prints their values to <code>stdout</code>,
7403 using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string.
7404 <code>print</code> is not intended for formatted output,
7405 but only as a quick way to show a value,
7406 for instance for debugging.
7407 For complete control over the output,
7408 use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
7409
7410
7411
7412
7413 <p>
7414 <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
7415 Checks whether <code>v1</code> is equal to <code>v2</code>,
7416 without invoking any metamethod.
7417 Returns a boolean.
7418
7419
7420
7421
7422 <p>
7423 <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
7424 Gets the real value of <code>table[index]</code>,
7425 without invoking any metamethod.
7426 <code>table</code> must be a table;
7427 <code>index</code> may be any value.
7428
7429
7430
7431
7432 <p>
7433 <hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
7434 Returns the length of the object <code>v</code>,
7435 which must be a table or a string,
7436 without invoking any metamethod.
7437 Returns an integer.
7438
7439
7440
7441
7442 <p>
7443 <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
7444 Sets the real value of <code>table[index]</code> to <code>value</code>,
7445 without invoking any metamethod.
7446 <code>table</code> must be a table,
7447 <code>index</code> any value different from <b>nil</b> and NaN,
7448 and <code>value</code> any Lua value.
7449
7450
7451 <p>
7452 This function returns <code>table</code>.
7453
7454
7455
7456
7457 <p>
7458 <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
7459
7460
7461 <p>
7462 If <code>index</code> is a number,
7463 returns all arguments after argument number <code>index</code>;
7464 a negative number indexes from the end (-1 is the last argument).
7465 Otherwise, <code>index</code> must be the string <code>"#"</code>,
7466 and <code>select</code> returns the total number of extra arguments it received.
7467
7468
7469
7470
7471 <p>
7472 <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
7473
7474
7475 <p>
7476 Sets the metatable for the given table.
7477 (You cannot change the metatable of other types from Lua, only from&nbsp;C.)
7478 If <code>metatable</code> is <b>nil</b>,
7479 removes the metatable of the given table.
7480 If the original metatable has a <code>"__metatable"</code> field,
7481 raises an error.
7482
7483
7484 <p>
7485 This function returns <code>table</code>.
7486
7487
7488
7489
7490 <p>
7491 <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
7492
7493
7494 <p>
7495 When called with no <code>base</code>,
7496 <code>tonumber</code> tries to convert its argument to a number.
7497 If the argument is already a number or
7498 a string convertible to a number,
7499 then <code>tonumber</code> returns this number;
7500 otherwise, it returns <b>nil</b>.
7501
7502
7503 <p>
7504 The conversion of strings can result in integers or floats,
7505 according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
7506 (The string may have leading and trailing spaces and a sign.)
7507
7508
7509 <p>
7510 When called with <code>base</code>,
7511 then <code>e</code> must be a string to be interpreted as
7512 an integer numeral in that base.
7513 The base may be any integer between 2 and 36, inclusive.
7514 In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
7515 represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
7516 with '<code>Z</code>' representing 35.
7517 If the string <code>e</code> is not a valid numeral in the given base,
7518 the function returns <b>nil</b>.
7519
7520
7521
7522
7523 <p>
7524 <hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
7525 Receives a value of any type and
7526 converts it to a string in a human-readable format.
7527 Floats always produce strings with some
7528 floating-point indication (either a decimal dot or an exponent).
7529 (For complete control of how numbers are converted,
7530 use <a href="#pdf-string.format"><code>string.format</code></a>.)
7531
7532
7533 <p>
7534 If the metatable of <code>v</code> has a <code>"__tostring"</code> field,
7535 then <code>tostring</code> calls the corresponding value
7536 with <code>v</code> as argument,
7537 and uses the result of the call as its result.
7538
7539
7540
7541
7542 <p>
7543 <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
7544 Returns the type of its only argument, coded as a string.
7545 The possible results of this function are
7546 "<code>nil</code>" (a string, not the value <b>nil</b>),
7547 "<code>number</code>",
7548 "<code>string</code>",
7549 "<code>boolean</code>",
7550 "<code>table</code>",
7551 "<code>function</code>",
7552 "<code>thread</code>",
7553 and "<code>userdata</code>".
7554
7555
7556
7557
7558 <p>
7559 <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
7560 A global variable (not a function) that
7561 holds a string containing the current interpreter version.
7562 The current value of this variable is "<code>Lua 5.3</code>".
7563
7564
7565
7566
7567 <p>
7568 <hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
7569
7570
7571 <p>
7572 This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
7573 except that it sets a new message handler <code>msgh</code>.
7574
7575
7576
7577
7578
7579
7580
7581 <h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
7582
7583 <p>
7584 The operations related to coroutines comprise a sub-library of
7585 the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
7586 See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
7587
7588
7589 <p>
7590 <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
7591
7592
7593 <p>
7594 Creates a new coroutine, with body <code>f</code>.
7595 <code>f</code> must be a Lua function.
7596 Returns this new coroutine,
7597 an object with type <code>"thread"</code>.
7598
7599
7600
7601
7602 <p>
7603 <hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3>
7604
7605
7606 <p>
7607 Returns true when the running coroutine can yield.
7608
7609
7610 <p>
7611 A running coroutine is yieldable if it is not the main thread and
7612 it is not inside a non-yieldable C function.
7613
7614
7615
7616
7617 <p>
7618 <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
7619
7620
7621 <p>
7622 Starts or continues the execution of coroutine <code>co</code>.
7623 The first time you resume a coroutine,
7624 it starts running its body.
7625 The values <code>val1</code>, ... are passed
7626 as the arguments to the body function.
7627 If the coroutine has yielded,
7628 <code>resume</code> restarts it;
7629 the values <code>val1</code>, ... are passed
7630 as the results from the yield.
7631
7632
7633 <p>
7634 If the coroutine runs without any errors,
7635 <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
7636 (when the coroutine yields) or any values returned by the body function
7637 (when the coroutine terminates).
7638 If there is any error,
7639 <code>resume</code> returns <b>false</b> plus the error message.
7640
7641
7642
7643
7644 <p>
7645 <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
7646
7647
7648 <p>
7649 Returns the running coroutine plus a boolean,
7650 true when the running coroutine is the main one.
7651
7652
7653
7654
7655 <p>
7656 <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
7657
7658
7659 <p>
7660 Returns the status of coroutine <code>co</code>, as a string:
7661 <code>"running"</code>,
7662 if the coroutine is running (that is, it called <code>status</code>);
7663 <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
7664 or if it has not started running yet;
7665 <code>"normal"</code> if the coroutine is active but not running
7666 (that is, it has resumed another coroutine);
7667 and <code>"dead"</code> if the coroutine has finished its body function,
7668 or if it has stopped with an error.
7669
7670
7671
7672
7673 <p>
7674 <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
7675
7676
7677 <p>
7678 Creates a new coroutine, with body <code>f</code>.
7679 <code>f</code> must be a Lua function.
7680 Returns a function that resumes the coroutine each time it is called.
7681 Any arguments passed to the function behave as the
7682 extra arguments to <code>resume</code>.
7683 Returns the same values returned by <code>resume</code>,
7684 except the first boolean.
7685 In case of error, propagates the error.
7686
7687
7688
7689
7690 <p>
7691 <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
7692
7693
7694 <p>
7695 Suspends the execution of the calling coroutine.
7696 Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
7697
7698
7699
7700
7701
7702
7703
7704 <h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
7705
7706 <p>
7707 The package library provides basic
7708 facilities for loading modules in Lua.
7709 It exports one function directly in the global environment:
7710 <a href="#pdf-require"><code>require</code></a>.
7711 Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
7712
7713
7714 <p>
7715 <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
7716
7717
7718 <p>
7719 Loads the given module.
7720 The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
7721 to determine whether <code>modname</code> is already loaded.
7722 If it is, then <code>require</code> returns the value stored
7723 at <code>package.loaded[modname]</code>.
7724 Otherwise, it tries to find a <em>loader</em> for the module.
7725
7726
7727 <p>
7728 To find a loader,
7729 <code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence.
7730 By changing this sequence,
7731 we can change how <code>require</code> looks for a module.
7732 The following explanation is based on the default configuration
7733 for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
7734
7735
7736 <p>
7737 First <code>require</code> queries <code>package.preload[modname]</code>.
7738 If it has a value,
7739 this value (which must be a function) is the loader.
7740 Otherwise <code>require</code> searches for a Lua loader using the
7741 path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
7742 If that also fails, it searches for a C&nbsp;loader using the
7743 path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7744 If that also fails,
7745 it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
7746
7747
7748 <p>
7749 Once a loader is found,
7750 <code>require</code> calls the loader with two arguments:
7751 <code>modname</code> and an extra value dependent on how it got the loader.
7752 (If the loader came from a file,
7753 this extra value is the file name.)
7754 If the loader returns any non-nil value,
7755 <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
7756 If the loader does not return a non-nil value and
7757 has not assigned any value to <code>package.loaded[modname]</code>,
7758 then <code>require</code> assigns <b>true</b> to this entry.
7759 In any case, <code>require</code> returns the
7760 final value of <code>package.loaded[modname]</code>.
7761
7762
7763 <p>
7764 If there is any error loading or running the module,
7765 or if it cannot find any loader for the module,
7766 then <code>require</code> raises an error.
7767
7768
7769
7770
7771 <p>
7772 <hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
7773
7774
7775 <p>
7776 A string describing some compile-time configurations for packages.
7777 This string is a sequence of lines:
7778
7779 <ul>
7780
7781 <li>The first line is the directory separator string.
7782 Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
7783
7784 <li>The second line is the character that separates templates in a path.
7785 Default is '<code>;</code>'.</li>
7786
7787 <li>The third line is the string that marks the
7788 substitution points in a template.
7789 Default is '<code>?</code>'.</li>
7790
7791 <li>The fourth line is a string that, in a path in Windows,
7792 is replaced by the executable's directory.
7793 Default is '<code>!</code>'.</li>
7794
7795 <li>The fifth line is a mark to ignore all text after it
7796 when building the <code>luaopen_</code> function name.
7797 Default is '<code>-</code>'.</li>
7798
7799 </ul>
7800
7801
7802
7803 <p>
7804 <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
7805
7806
7807 <p>
7808 The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
7809
7810
7811 <p>
7812 Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
7813 it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7814 using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a>
7815 or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
7816 or a default path defined in <code>luaconf.h</code>.
7817
7818
7819
7820
7821 <p>
7822 <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
7823
7824
7825 <p>
7826 A table used by <a href="#pdf-require"><code>require</code></a> to control which
7827 modules are already loaded.
7828 When you require a module <code>modname</code> and
7829 <code>package.loaded[modname]</code> is not false,
7830 <a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
7831
7832
7833 <p>
7834 This variable is only a reference to the real table;
7835 assignments to this variable do not change the
7836 table used by <a href="#pdf-require"><code>require</code></a>.
7837
7838
7839
7840
7841 <p>
7842 <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
7843
7844
7845 <p>
7846 Dynamically links the host program with the C&nbsp;library <code>libname</code>.
7847
7848
7849 <p>
7850 If <code>funcname</code> is "<code>*</code>",
7851 then it only links with the library,
7852 making the symbols exported by the library
7853 available to other dynamically linked libraries.
7854 Otherwise,
7855 it looks for a function <code>funcname</code> inside the library
7856 and returns this function as a C&nbsp;function.
7857 So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
7858 (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
7859
7860
7861 <p>
7862 This is a low-level function.
7863 It completely bypasses the package and module system.
7864 Unlike <a href="#pdf-require"><code>require</code></a>,
7865 it does not perform any path searching and
7866 does not automatically adds extensions.
7867 <code>libname</code> must be the complete file name of the C&nbsp;library,
7868 including if necessary a path and an extension.
7869 <code>funcname</code> must be the exact name exported by the C&nbsp;library
7870 (which may depend on the C&nbsp;compiler and linker used).
7871
7872
7873 <p>
7874 This function is not supported by Standard&nbsp;C.
7875 As such, it is only available on some platforms
7876 (Windows, Linux, Mac OS X, Solaris, BSD,
7877 plus other Unix systems that support the <code>dlfcn</code> standard).
7878
7879
7880
7881
7882 <p>
7883 <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
7884
7885
7886 <p>
7887 The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
7888
7889
7890 <p>
7891 At start-up, Lua initializes this variable with
7892 the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or
7893 the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
7894 with a default path defined in <code>luaconf.h</code>,
7895 if those environment variables are not defined.
7896 Any "<code>;;</code>" in the value of the environment variable
7897 is replaced by the default path.
7898
7899
7900
7901
7902 <p>
7903 <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
7904
7905
7906 <p>
7907 A table to store loaders for specific modules
7908 (see <a href="#pdf-require"><code>require</code></a>).
7909
7910
7911 <p>
7912 This variable is only a reference to the real table;
7913 assignments to this variable do not change the
7914 table used by <a href="#pdf-require"><code>require</code></a>.
7915
7916
7917
7918
7919 <p>
7920 <hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
7921
7922
7923 <p>
7924 A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
7925
7926
7927 <p>
7928 Each entry in this table is a <em>searcher function</em>.
7929 When looking for a module,
7930 <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
7931 with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
7932 sole parameter.
7933 The function can return another function (the module <em>loader</em>)
7934 plus an extra value that will be passed to that loader,
7935 or a string explaining why it did not find that module
7936 (or <b>nil</b> if it has nothing to say).
7937
7938
7939 <p>
7940 Lua initializes this table with four searcher functions.
7941
7942
7943 <p>
7944 The first searcher simply looks for a loader in the
7945 <a href="#pdf-package.preload"><code>package.preload</code></a> table.
7946
7947
7948 <p>
7949 The second searcher looks for a loader as a Lua library,
7950 using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
7951 The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7952
7953
7954 <p>
7955 The third searcher looks for a loader as a C&nbsp;library,
7956 using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7957 Again,
7958 the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7959 For instance,
7960 if the C&nbsp;path is the string
7961
7962 <pre>
7963 "./?.so;./?.dll;/usr/local/?/init.so"
7964 </pre><p>
7965 the searcher for module <code>foo</code>
7966 will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
7967 and <code>/usr/local/foo/init.so</code>, in that order.
7968 Once it finds a C&nbsp;library,
7969 this searcher first uses a dynamic link facility to link the
7970 application with the library.
7971 Then it tries to find a C&nbsp;function inside the library to
7972 be used as the loader.
7973 The name of this C&nbsp;function is the string "<code>luaopen_</code>"
7974 concatenated with a copy of the module name where each dot
7975 is replaced by an underscore.
7976 Moreover, if the module name has a hyphen,
7977 its suffix after (and including) the first hyphen is removed.
7978 For instance, if the module name is <code>a.b.c-v2.1</code>,
7979 the function name will be <code>luaopen_a_b_c</code>.
7980
7981
7982 <p>
7983 The fourth searcher tries an <em>all-in-one loader</em>.
7984 It searches the C&nbsp;path for a library for
7985 the root name of the given module.
7986 For instance, when requiring <code>a.b.c</code>,
7987 it will search for a C&nbsp;library for <code>a</code>.
7988 If found, it looks into it for an open function for
7989 the submodule;
7990 in our example, that would be <code>luaopen_a_b_c</code>.
7991 With this facility, a package can pack several C&nbsp;submodules
7992 into one single library,
7993 with each submodule keeping its original open function.
7994
7995
7996 <p>
7997 All searchers except the first one (preload) return as the extra value
7998 the file name where the module was found,
7999 as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
8000 The first searcher returns no extra value.
8001
8002
8003
8004
8005 <p>
8006 <hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8007
8008
8009 <p>
8010 Searches for the given <code>name</code> in the given <code>path</code>.
8011
8012
8013 <p>
8014 A path is a string containing a sequence of
8015 <em>templates</em> separated by semicolons.
8016 For each template,
8017 the function replaces each interrogation mark (if any)
8018 in the template with a copy of <code>name</code>
8019 wherein all occurrences of <code>sep</code>
8020 (a dot, by default)
8021 were replaced by <code>rep</code>
8022 (the system's directory separator, by default),
8023 and then tries to open the resulting file name.
8024
8025
8026 <p>
8027 For instance, if the path is the string
8028
8029 <pre>
8030 "./?.lua;./?.lc;/usr/local/?/init.lua"
8031 </pre><p>
8032 the search for the name <code>foo.a</code>
8033 will try to open the files
8034 <code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8035 <code>/usr/local/foo/a/init.lua</code>, in that order.
8036
8037
8038 <p>
8039 Returns the resulting name of the first file that it can
8040 open in read mode (after closing the file),
8041 or <b>nil</b> plus an error message if none succeeds.
8042 (This error message lists all file names it tried to open.)
8043
8044
8045
8046
8047
8048
8049
8050 <h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8051
8052 <p>
8053 This library provides generic functions for string manipulation,
8054 such as finding and extracting substrings, and pattern matching.
8055 When indexing a string in Lua, the first character is at position&nbsp;1
8056 (not at&nbsp;0, as in C).
8057 Indices are allowed to be negative and are interpreted as indexing backwards,
8058 from the end of the string.
8059 Thus, the last character is at position -1, and so on.
8060
8061
8062 <p>
8063 The string library provides all its functions inside the table
8064 <a name="pdf-string"><code>string</code></a>.
8065 It also sets a metatable for strings
8066 where the <code>__index</code> field points to the <code>string</code> table.
8067 Therefore, you can use the string functions in object-oriented style.
8068 For instance, <code>string.byte(s,i)</code>
8069 can be written as <code>s:byte(i)</code>.
8070
8071
8072 <p>
8073 The string library assumes one-byte character encodings.
8074
8075
8076 <p>
8077 <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8078 Returns the internal numerical codes of the characters <code>s[i]</code>,
8079 <code>s[i+1]</code>, ..., <code>s[j]</code>.
8080 The default value for <code>i</code> is&nbsp;1;
8081 the default value for <code>j</code> is&nbsp;<code>i</code>.
8082 These indices are corrected
8083 following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8084
8085
8086 <p>
8087 Numerical codes are not necessarily portable across platforms.
8088
8089
8090
8091
8092 <p>
8093 <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8094 Receives zero or more integers.
8095 Returns a string with length equal to the number of arguments,
8096 in which each character has the internal numerical code equal
8097 to its corresponding argument.
8098
8099
8100 <p>
8101 Numerical codes are not necessarily portable across platforms.
8102
8103
8104
8105
8106 <p>
8107 <hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8108
8109
8110 <p>
8111 Returns a string containing a binary representation
8112 (a <em>binary chunk</em>)
8113 of the given function,
8114 so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8115 a copy of the function (but with new upvalues).
8116 If <code>strip</code> is a true value,
8117 the binary representation is created without debug information
8118 about the function
8119 (local variable names, lines, etc.).
8120
8121
8122 <p>
8123 Functions with upvalues have only their number of upvalues saved.
8124 When (re)loaded,
8125 those upvalues receive fresh instances containing <b>nil</b>.
8126 (You can use the debug library to serialize
8127 and reload the upvalues of a function
8128 in a way adequate to your needs.)
8129
8130
8131
8132
8133 <p>
8134 <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
8135
8136
8137 <p>
8138 Looks for the first match of
8139 <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
8140 If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
8141 where this occurrence starts and ends;
8142 otherwise, it returns <b>nil</b>.
8143 A third, optional numerical argument <code>init</code> specifies
8144 where to start the search;
8145 its default value is&nbsp;1 and can be negative.
8146 A value of <b>true</b> as a fourth, optional argument <code>plain</code>
8147 turns off the pattern matching facilities,
8148 so the function does a plain "find substring" operation,
8149 with no characters in <code>pattern</code> being considered magic.
8150 Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
8151
8152
8153 <p>
8154 If the pattern has captures,
8155 then in a successful match
8156 the captured values are also returned,
8157 after the two indices.
8158
8159
8160
8161
8162 <p>
8163 <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
8164
8165
8166 <p>
8167 Returns a formatted version of its variable number of arguments
8168 following the description given in its first argument (which must be a string).
8169 The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
8170 The only differences are that the options/modifiers
8171 <code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
8172 and <code>p</code> are not supported
8173 and that there is an extra option, <code>q</code>.
8174 The <code>q</code> option formats a string between double quotes,
8175 using escape sequences when necessary to ensure that
8176 it can safely be read back by the Lua interpreter.
8177 For instance, the call
8178
8179 <pre>
8180 string.format('%q', 'a string with "quotes" and \n new line')
8181 </pre><p>
8182 may produce the string:
8183
8184 <pre>
8185 "a string with \"quotes\" and \
8186 new line"
8187 </pre>
8188
8189 <p>
8190 Options
8191 <code>A</code> and <code>a</code> (when available),
8192 <code>E</code>, <code>e</code>, <code>f</code>,
8193 <code>G</code>, and <code>g</code> all expect a number as argument.
8194 Options <code>c</code>, <code>d</code>,
8195 <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
8196 expect an integer.
8197 Option <code>q</code> expects a string;
8198 option <code>s</code> expects a string without embedded zeros.
8199 If the argument to option <code>s</code> is not a string,
8200 it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8201
8202
8203
8204
8205 <p>
8206 <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
8207 Returns an iterator function that,
8208 each time it is called,
8209 returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
8210 over the string <code>s</code>.
8211 If <code>pattern</code> specifies no captures,
8212 then the whole match is produced in each call.
8213
8214
8215 <p>
8216 As an example, the following loop
8217 will iterate over all the words from string <code>s</code>,
8218 printing one per line:
8219
8220 <pre>
8221 s = "hello world from Lua"
8222 for w in string.gmatch(s, "%a+") do
8223 print(w)
8224 end
8225 </pre><p>
8226 The next example collects all pairs <code>key=value</code> from the
8227 given string into a table:
8228
8229 <pre>
8230 t = {}
8231 s = "from=world, to=Lua"
8232 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
8233 t[k] = v
8234 end
8235 </pre>
8236
8237 <p>
8238 For this function, a caret '<code>^</code>' at the start of a pattern does not
8239 work as an anchor, as this would prevent the iteration.
8240
8241
8242
8243
8244 <p>
8245 <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
8246 Returns a copy of <code>s</code>
8247 in which all (or the first <code>n</code>, if given)
8248 occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
8249 replaced by a replacement string specified by <code>repl</code>,
8250 which can be a string, a table, or a function.
8251 <code>gsub</code> also returns, as its second value,
8252 the total number of matches that occurred.
8253 The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
8254
8255
8256 <p>
8257 If <code>repl</code> is a string, then its value is used for replacement.
8258 The character&nbsp;<code>%</code> works as an escape character:
8259 any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
8260 with <em>d</em> between 1 and 9,
8261 stands for the value of the <em>d</em>-th captured substring.
8262 The sequence <code>%0</code> stands for the whole match.
8263 The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
8264
8265
8266 <p>
8267 If <code>repl</code> is a table, then the table is queried for every match,
8268 using the first capture as the key.
8269
8270
8271 <p>
8272 If <code>repl</code> is a function, then this function is called every time a
8273 match occurs, with all captured substrings passed as arguments,
8274 in order.
8275
8276
8277 <p>
8278 In any case,
8279 if the pattern specifies no captures,
8280 then it behaves as if the whole pattern was inside a capture.
8281
8282
8283 <p>
8284 If the value returned by the table query or by the function call
8285 is a string or a number,
8286 then it is used as the replacement string;
8287 otherwise, if it is <b>false</b> or <b>nil</b>,
8288 then there is no replacement
8289 (that is, the original match is kept in the string).
8290
8291
8292 <p>
8293 Here are some examples:
8294
8295 <pre>
8296 x = string.gsub("hello world", "(%w+)", "%1 %1")
8297 --&gt; x="hello hello world world"
8298
8299 x = string.gsub("hello world", "%w+", "%0 %0", 1)
8300 --&gt; x="hello hello world"
8301
8302 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
8303 --&gt; x="world hello Lua from"
8304
8305 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
8306 --&gt; x="home = /home/roberto, user = roberto"
8307
8308 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
8309 return load(s)()
8310 end)
8311 --&gt; x="4+5 = 9"
8312
8313 local t = {name="lua", version="5.3"}
8314 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8315 --&gt; x="lua-5.3.tar.gz"
8316 </pre>
8317
8318
8319
8320 <p>
8321 <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
8322 Receives a string and returns its length.
8323 The empty string <code>""</code> has length 0.
8324 Embedded zeros are counted,
8325 so <code>"a\000bc\000"</code> has length 5.
8326
8327
8328
8329
8330 <p>
8331 <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
8332 Receives a string and returns a copy of this string with all
8333 uppercase letters changed to lowercase.
8334 All other characters are left unchanged.
8335 The definition of what an uppercase letter is depends on the current locale.
8336
8337
8338
8339
8340 <p>
8341 <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
8342 Looks for the first <em>match</em> of
8343 <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
8344 If it finds one, then <code>match</code> returns
8345 the captures from the pattern;
8346 otherwise it returns <b>nil</b>.
8347 If <code>pattern</code> specifies no captures,
8348 then the whole match is returned.
8349 A third, optional numerical argument <code>init</code> specifies
8350 where to start the search;
8351 its default value is&nbsp;1 and can be negative.
8352
8353
8354
8355
8356 <p>
8357 <hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
8358
8359
8360 <p>
8361 Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
8362 packed (that is, serialized in binary form)
8363 according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
8364
8365
8366
8367
8368 <p>
8369 <hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
8370
8371
8372 <p>
8373 Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
8374 with the given format.
8375 The format string cannot have the variable-length options
8376 '<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
8377
8378
8379
8380
8381 <p>
8382 <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
8383 Returns a string that is the concatenation of <code>n</code> copies of
8384 the string <code>s</code> separated by the string <code>sep</code>.
8385 The default value for <code>sep</code> is the empty string
8386 (that is, no separator).
8387 Returns the empty string if <code>n</code> is not positive.
8388
8389
8390
8391
8392 <p>
8393 <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
8394 Returns a string that is the string <code>s</code> reversed.
8395
8396
8397
8398
8399 <p>
8400 <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
8401 Returns the substring of <code>s</code> that
8402 starts at <code>i</code> and continues until <code>j</code>;
8403 <code>i</code> and <code>j</code> can be negative.
8404 If <code>j</code> is absent, then it is assumed to be equal to -1
8405 (which is the same as the string length).
8406 In particular,
8407 the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
8408 with length <code>j</code>,
8409 and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
8410 with length <code>i</code>.
8411
8412
8413 <p>
8414 If, after the translation of negative indices,
8415 <code>i</code> is less than 1,
8416 it is corrected to 1.
8417 If <code>j</code> is greater than the string length,
8418 it is corrected to that length.
8419 If, after these corrections,
8420 <code>i</code> is greater than <code>j</code>,
8421 the function returns the empty string.
8422
8423
8424
8425
8426 <p>
8427 <hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
8428
8429
8430 <p>
8431 Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
8432 according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
8433 An optional <code>pos</code> marks where
8434 to start reading in <code>s</code> (default is 1).
8435 After the read values,
8436 this function also returns the index of the first unread byte in <code>s</code>.
8437
8438
8439
8440
8441 <p>
8442 <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
8443 Receives a string and returns a copy of this string with all
8444 lowercase letters changed to uppercase.
8445 All other characters are left unchanged.
8446 The definition of what a lowercase letter is depends on the current locale.
8447
8448
8449
8450
8451
8452 <h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
8453
8454 <p>
8455 Patterns in Lua are described by regular strings,
8456 which are interpreted as patterns by the pattern-matching functions
8457 <a href="#pdf-string.find"><code>string.find</code></a>,
8458 <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
8459 <a href="#pdf-string.gsub"><code>string.gsub</code></a>,
8460 and <a href="#pdf-string.match"><code>string.match</code></a>.
8461 This section describes the syntax and the meaning
8462 (that is, what they match) of these strings.
8463
8464
8465
8466 <h4>Character Class:</h4><p>
8467 A <em>character class</em> is used to represent a set of characters.
8468 The following combinations are allowed in describing a character class:
8469
8470 <ul>
8471
8472 <li><b><em>x</em>: </b>
8473 (where <em>x</em> is not one of the <em>magic characters</em>
8474 <code>^$()%.[]*+-?</code>)
8475 represents the character <em>x</em> itself.
8476 </li>
8477
8478 <li><b><code>.</code>: </b> (a dot) represents all characters.</li>
8479
8480 <li><b><code>%a</code>: </b> represents all letters.</li>
8481
8482 <li><b><code>%c</code>: </b> represents all control characters.</li>
8483
8484 <li><b><code>%d</code>: </b> represents all digits.</li>
8485
8486 <li><b><code>%g</code>: </b> represents all printable characters except space.</li>
8487
8488 <li><b><code>%l</code>: </b> represents all lowercase letters.</li>
8489
8490 <li><b><code>%p</code>: </b> represents all punctuation characters.</li>
8491
8492 <li><b><code>%s</code>: </b> represents all space characters.</li>
8493
8494 <li><b><code>%u</code>: </b> represents all uppercase letters.</li>
8495
8496 <li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
8497
8498 <li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
8499
8500 <li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
8501 represents the character <em>x</em>.
8502 This is the standard way to escape the magic characters.
8503 Any non-alphanumeric character
8504 (including all punctuations, even the non-magical)
8505 can be preceded by a '<code>%</code>'
8506 when used to represent itself in a pattern.
8507 </li>
8508
8509 <li><b><code>[<em>set</em>]</code>: </b>
8510 represents the class which is the union of all
8511 characters in <em>set</em>.
8512 A range of characters can be specified by
8513 separating the end characters of the range,
8514 in ascending order, with a '<code>-</code>'.
8515 All classes <code>%</code><em>x</em> described above can also be used as
8516 components in <em>set</em>.
8517 All other characters in <em>set</em> represent themselves.
8518 For example, <code>[%w_]</code> (or <code>[_%w]</code>)
8519 represents all alphanumeric characters plus the underscore,
8520 <code>[0-7]</code> represents the octal digits,
8521 and <code>[0-7%l%-]</code> represents the octal digits plus
8522 the lowercase letters plus the '<code>-</code>' character.
8523
8524
8525 <p>
8526 The interaction between ranges and classes is not defined.
8527 Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
8528 have no meaning.
8529 </li>
8530
8531 <li><b><code>[^<em>set</em>]</code>: </b>
8532 represents the complement of <em>set</em>,
8533 where <em>set</em> is interpreted as above.
8534 </li>
8535
8536 </ul><p>
8537 For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
8538 the corresponding uppercase letter represents the complement of the class.
8539 For instance, <code>%S</code> represents all non-space characters.
8540
8541
8542 <p>
8543 The definitions of letter, space, and other character groups
8544 depend on the current locale.
8545 In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
8546
8547
8548
8549
8550
8551 <h4>Pattern Item:</h4><p>
8552 A <em>pattern item</em> can be
8553
8554 <ul>
8555
8556 <li>
8557 a single character class,
8558 which matches any single character in the class;
8559 </li>
8560
8561 <li>
8562 a single character class followed by '<code>*</code>',
8563 which matches zero or more repetitions of characters in the class.
8564 These repetition items will always match the longest possible sequence;
8565 </li>
8566
8567 <li>
8568 a single character class followed by '<code>+</code>',
8569 which matches one or more repetitions of characters in the class.
8570 These repetition items will always match the longest possible sequence;
8571 </li>
8572
8573 <li>
8574 a single character class followed by '<code>-</code>',
8575 which also matches zero or more repetitions of characters in the class.
8576 Unlike '<code>*</code>',
8577 these repetition items will always match the shortest possible sequence;
8578 </li>
8579
8580 <li>
8581 a single character class followed by '<code>?</code>',
8582 which matches zero or one occurrence of a character in the class.
8583 It always matches one occurrence if possible;
8584 </li>
8585
8586 <li>
8587 <code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
8588 such item matches a substring equal to the <em>n</em>-th captured string
8589 (see below);
8590 </li>
8591
8592 <li>
8593 <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
8594 such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
8595 and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
8596 This means that, if one reads the string from left to right,
8597 counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
8598 the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
8599 For instance, the item <code>%b()</code> matches expressions with
8600 balanced parentheses.
8601 </li>
8602
8603 <li>
8604 <code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
8605 such item matches an empty string at any position such that
8606 the next character belongs to <em>set</em>
8607 and the previous character does not belong to <em>set</em>.
8608 The set <em>set</em> is interpreted as previously described.
8609 The beginning and the end of the subject are handled as if
8610 they were the character '<code>\0</code>'.
8611 </li>
8612
8613 </ul>
8614
8615
8616
8617
8618 <h4>Pattern:</h4><p>
8619 A <em>pattern</em> is a sequence of pattern items.
8620 A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
8621 beginning of the subject string.
8622 A '<code>$</code>' at the end of a pattern anchors the match at the
8623 end of the subject string.
8624 At other positions,
8625 '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
8626
8627
8628
8629
8630
8631 <h4>Captures:</h4><p>
8632 A pattern can contain sub-patterns enclosed in parentheses;
8633 they describe <em>captures</em>.
8634 When a match succeeds, the substrings of the subject string
8635 that match captures are stored (<em>captured</em>) for future use.
8636 Captures are numbered according to their left parentheses.
8637 For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
8638 the part of the string matching <code>"a*(.)%w(%s*)"</code> is
8639 stored as the first capture (and therefore has number&nbsp;1);
8640 the character matching "<code>.</code>" is captured with number&nbsp;2,
8641 and the part matching "<code>%s*</code>" has number&nbsp;3.
8642
8643
8644 <p>
8645 As a special case, the empty capture <code>()</code> captures
8646 the current string position (a number).
8647 For instance, if we apply the pattern <code>"()aa()"</code> on the
8648 string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
8649
8650
8651
8652
8653
8654
8655
8656 <h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
8657
8658 <p>
8659 The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
8660 <a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
8661 is a format string,
8662 which describes the layout of the structure being created or read.
8663
8664
8665 <p>
8666 A format string is a sequence of conversion options.
8667 The conversion options are as follows:
8668
8669 <ul>
8670 <li><b><code>&lt;</code>: </b>sets little endian</li>
8671 <li><b><code>&gt;</code>: </b>sets big endian</li>
8672 <li><b><code>=</code>: </b>sets native endian</li>
8673 <li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
8674 (default is native alignment)</li>
8675 <li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
8676 <li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
8677 <li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
8678 <li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
8679 <li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
8680 <li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
8681 <li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
8682 <li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
8683 <li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
8684 <li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
8685 (default is native size)</li>
8686 <li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
8687 (default is native size)</li>
8688 <li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
8689 <li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
8690 <li><b><code>n</code>: </b>a <code>lua_Number</code></li>
8691 <li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
8692 <li><b><code>z</code>: </b>a zero-terminated string</li>
8693 <li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
8694 coded as an unsigned integer with <code>n</code> bytes
8695 (default is a <code>size_t</code>)</li>
8696 <li><b><code>x</code>: </b>one byte of padding</li>
8697 <li><b><code>X<em>op</em></code>: </b>an empty item that aligns
8698 according to option <code>op</code>
8699 (which is otherwise ignored)</li>
8700 <li><b>'<code> </code>': </b>(empty space) ignored</li>
8701 </ul><p>
8702 (A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
8703 Except for padding, spaces, and configurations
8704 (options "<code>xX &lt;=&gt;!</code>"),
8705 each option corresponds to an argument (in <a href="#pdf-string.pack"><code>string.pack</code></a>)
8706 or a result (in <a href="#pdf-string.unpack"><code>string.unpack</code></a>).
8707
8708
8709 <p>
8710 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>",
8711 <code>n</code> can be any integer between 1 and 16.
8712 All integral options check overflows;
8713 <a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
8714 <a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
8715
8716
8717 <p>
8718 Any format string starts as if prefixed by "<code>!1=</code>",
8719 that is,
8720 with maximum alignment of 1 (no alignment)
8721 and native endianness.
8722
8723
8724 <p>
8725 Alignment works as follows:
8726 For each option,
8727 the format gets extra padding until the data starts
8728 at an offset that is a multiple of the minimum between the
8729 option size and the maximum alignment;
8730 this minimum must be a power of 2.
8731 Options "<code>c</code>" and "<code>z</code>" are not aligned;
8732 option "<code>s</code>" follows the alignment of its starting integer.
8733
8734
8735 <p>
8736 All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
8737 (and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>).
8738
8739
8740
8741
8742
8743
8744
8745 <h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
8746
8747 <p>
8748 This library provides basic support for UTF-8 encoding.
8749 It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
8750 This library does not provide any support for Unicode other
8751 than the handling of the encoding.
8752 Any operation that needs the meaning of a character,
8753 such as character classification, is outside its scope.
8754
8755
8756 <p>
8757 Unless stated otherwise,
8758 all functions that expect a byte position as a parameter
8759 assume that the given position is either the start of a byte sequence
8760 or one plus the length of the subject string.
8761 As in the string library,
8762 negative indices count from the end of the string.
8763
8764
8765 <p>
8766 <hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
8767 Receives zero or more integers,
8768 converts each one to its corresponding UTF-8 byte sequence
8769 and returns a string with the concatenation of all these sequences.
8770
8771
8772
8773
8774 <p>
8775 <hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
8776 The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>"
8777 (see <a href="#6.4.1">&sect;6.4.1</a>),
8778 which matches exactly one UTF-8 byte sequence,
8779 assuming that the subject is a valid UTF-8 string.
8780
8781
8782
8783
8784 <p>
8785 <hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3>
8786
8787
8788 <p>
8789 Returns values so that the construction
8790
8791 <pre>
8792 for p, c in utf8.codes(s) do <em>body</em> end
8793 </pre><p>
8794 will iterate over all characters in string <code>s</code>,
8795 with <code>p</code> being the position (in bytes) and <code>c</code> the code point
8796 of each character.
8797 It raises an error if it meets any invalid byte sequence.
8798
8799
8800
8801
8802 <p>
8803 <hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3>
8804 Returns the codepoints (as integers) from all characters in <code>s</code>
8805 that start between byte position <code>i</code> and <code>j</code> (both included).
8806 The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
8807 It raises an error if it meets any invalid byte sequence.
8808
8809
8810
8811
8812 <p>
8813 <hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3>
8814 Returns the number of UTF-8 characters in string <code>s</code>
8815 that start between positions <code>i</code> and <code>j</code> (both inclusive).
8816 The default for <code>i</code> is 1 and for <code>j</code> is -1.
8817 If it finds any invalid byte sequence,
8818 returns a false value plus the position of the first invalid byte.
8819
8820
8821
8822
8823 <p>
8824 <hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
8825 Returns the position (in bytes) where the encoding of the
8826 <code>n</code>-th character of <code>s</code>
8827 (counting from position <code>i</code>) starts.
8828 A negative <code>n</code> gets characters before position <code>i</code>.
8829 The default for <code>i</code> is 1 when <code>n</code> is non-negative
8830 and <code>#s + 1</code> otherwise,
8831 so that <code>utf8.offset(s, -n)</code> gets the offset of the
8832 <code>n</code>-th character from the end of the string.
8833 If the specified character is neither in the subject
8834 nor right after its end,
8835 the function returns <b>nil</b>.
8836
8837
8838 <p>
8839 As a special case,
8840 when <code>n</code> is 0 the function returns the start of the encoding
8841 of the character that contains the <code>i</code>-th byte of <code>s</code>.
8842
8843
8844 <p>
8845 This function assumes that <code>s</code> is a valid UTF-8 string.
8846
8847
8848
8849
8850
8851
8852
8853 <h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
8854
8855 <p>
8856 This library provides generic functions for table manipulation.
8857 It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
8858
8859
8860 <p>
8861 Remember that, whenever an operation needs the length of a table,
8862 the table must be a proper sequence
8863 or have a <code>__len</code> metamethod (see <a href="#3.4.7">&sect;3.4.7</a>).
8864 All functions ignore non-numeric keys
8865 in the tables given as arguments.
8866
8867
8868 <p>
8869 <hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
8870
8871
8872 <p>
8873 Given a list where all elements are strings or numbers,
8874 returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
8875 The default value for <code>sep</code> is the empty string,
8876 the default for <code>i</code> is 1,
8877 and the default for <code>j</code> is <code>#list</code>.
8878 If <code>i</code> is greater than <code>j</code>, returns the empty string.
8879
8880
8881
8882
8883 <p>
8884 <hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
8885
8886
8887 <p>
8888 Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
8889 shifting up the elements
8890 <code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
8891 The default value for <code>pos</code> is <code>#list+1</code>,
8892 so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
8893 of list <code>t</code>.
8894
8895
8896
8897
8898 <p>
8899 <hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
8900
8901
8902 <p>
8903 Moves elements from table <code>a1</code> to table <code>a2</code>.
8904 This function performs the equivalent to the following
8905 multiple assignment:
8906 <code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
8907 The default for <code>a2</code> is <code>a1</code>.
8908 The destination range can overlap with the source range.
8909 Index <code>f</code> must be positive.
8910
8911
8912
8913
8914 <p>
8915 <hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
8916
8917
8918 <p>
8919 Returns a new table with all parameters stored into keys 1, 2, etc.
8920 and with a field "<code>n</code>" with the total number of parameters.
8921 Note that the resulting table may not be a sequence.
8922
8923
8924
8925
8926 <p>
8927 <hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
8928
8929
8930 <p>
8931 Removes from <code>list</code> the element at position <code>pos</code>,
8932 returning the value of the removed element.
8933 When <code>pos</code> is an integer between 1 and <code>#list</code>,
8934 it shifts down the elements
8935 <code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
8936 and erases element <code>list[#list]</code>;
8937 The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
8938 or <code>#list + 1</code>;
8939 in those cases, the function erases the element <code>list[pos]</code>.
8940
8941
8942 <p>
8943 The default value for <code>pos</code> is <code>#list</code>,
8944 so that a call <code>table.remove(l)</code> removes the last element
8945 of list <code>l</code>.
8946
8947
8948
8949
8950 <p>
8951 <hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
8952
8953
8954 <p>
8955 Sorts list elements in a given order, <em>in-place</em>,
8956 from <code>list[1]</code> to <code>list[#list]</code>.
8957 If <code>comp</code> is given,
8958 then it must be a function that receives two list elements
8959 and returns true when the first element must come
8960 before the second in the final order
8961 (so that <code>not comp(list[i+1],list[i])</code> will be true after the sort).
8962 If <code>comp</code> is not given,
8963 then the standard Lua operator <code>&lt;</code> is used instead.
8964
8965
8966 <p>
8967 The sort algorithm is not stable;
8968 that is, elements considered equal by the given order
8969 may have their relative positions changed by the sort.
8970
8971
8972
8973
8974 <p>
8975 <hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
8976
8977
8978 <p>
8979 Returns the elements from the given list.
8980 This function is equivalent to
8981
8982 <pre>
8983 return list[i], list[i+1], &middot;&middot;&middot;, list[j]
8984 </pre><p>
8985 By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
8986
8987
8988
8989
8990
8991
8992
8993 <h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
8994
8995 <p>
8996 This library provides basic mathematical functions.
8997 It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
8998 Functions with the annotation "<code>integer/float</code>" give
8999 integer results for integer arguments
9000 and float results for float (or mixed) arguments.
9001 Rounding functions
9002 (<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>)
9003 return an integer when the result fits in the range of an integer,
9004 or a float otherwise.
9005
9006
9007 <p>
9008 <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
9009
9010
9011 <p>
9012 Returns the absolute value of <code>x</code>. (integer/float)
9013
9014
9015
9016
9017 <p>
9018 <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
9019
9020
9021 <p>
9022 Returns the arc cosine of <code>x</code> (in radians).
9023
9024
9025
9026
9027 <p>
9028 <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
9029
9030
9031 <p>
9032 Returns the arc sine of <code>x</code> (in radians).
9033
9034
9035
9036
9037 <p>
9038 <hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
9039
9040
9041 <p>
9042
9043 Returns the arc tangent of <code>y/x</code> (in radians),
9044 but uses the signs of both parameters to find the
9045 quadrant of the result.
9046 (It also handles correctly the case of <code>x</code> being zero.)
9047
9048
9049 <p>
9050 The default value for <code>x</code> is 1,
9051 so that the call <code>math.atan(y)</code>
9052 returns the arc tangent of <code>y</code>.
9053
9054
9055
9056
9057 <p>
9058 <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
9059
9060
9061 <p>
9062 Returns the smallest integral value larger than or equal to <code>x</code>.
9063
9064
9065
9066
9067 <p>
9068 <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
9069
9070
9071 <p>
9072 Returns the cosine of <code>x</code> (assumed to be in radians).
9073
9074
9075
9076
9077 <p>
9078 <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
9079
9080
9081 <p>
9082 Converts the angle <code>x</code> from radians to degrees.
9083
9084
9085
9086
9087 <p>
9088 <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
9089
9090
9091 <p>
9092 Returns the value <em>e<sup>x</sup></em>
9093 (where <code>e</code> is the base of natural logarithms).
9094
9095
9096
9097
9098 <p>
9099 <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
9100
9101
9102 <p>
9103 Returns the largest integral value smaller than or equal to <code>x</code>.
9104
9105
9106
9107
9108 <p>
9109 <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
9110
9111
9112 <p>
9113 Returns the remainder of the division of <code>x</code> by <code>y</code>
9114 that rounds the quotient towards zero. (integer/float)
9115
9116
9117
9118
9119 <p>
9120 <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
9121
9122
9123 <p>
9124 The float value <code>HUGE_VAL</code>,
9125 a value larger than any other numerical value.
9126
9127
9128
9129
9130 <p>
9131 <hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
9132
9133
9134 <p>
9135 Returns the logarithm of <code>x</code> in the given base.
9136 The default for <code>base</code> is <em>e</em>
9137 (so that the function returns the natural logarithm of <code>x</code>).
9138
9139
9140
9141
9142 <p>
9143 <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
9144
9145
9146 <p>
9147 Returns the argument with the maximum value,
9148 according to the Lua operator <code>&lt;</code>. (integer/float)
9149
9150
9151
9152
9153 <p>
9154 <hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
9155 An integer with the maximum value for an integer.
9156
9157
9158
9159
9160 <p>
9161 <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
9162
9163
9164 <p>
9165 Returns the argument with the minimum value,
9166 according to the Lua operator <code>&lt;</code>. (integer/float)
9167
9168
9169
9170
9171 <p>
9172 <hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
9173 An integer with the minimum value for an integer.
9174
9175
9176
9177
9178 <p>
9179 <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
9180
9181
9182 <p>
9183 Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
9184 Its second result is always a float.
9185
9186
9187
9188
9189 <p>
9190 <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
9191
9192
9193 <p>
9194 The value of <em>&pi;</em>.
9195
9196
9197
9198
9199 <p>
9200 <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
9201
9202
9203 <p>
9204 Converts the angle <code>x</code> from degrees to radians.
9205
9206
9207
9208
9209 <p>
9210 <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
9211
9212
9213 <p>
9214 When called without arguments,
9215 returns a pseudo-random float with uniform distribution
9216 in the range <em>[0,1)</em>.
9217 When called with two integers <code>m</code> and <code>n</code>,
9218 <code>math.random</code> returns a pseudo-random integer
9219 with uniform distribution in the range <em>[m, n]</em>.
9220 (The value <em>m-n</em> cannot be negative and must fit in a Lua integer.)
9221 The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>.
9222
9223
9224 <p>
9225 This function is an interface to the underling
9226 pseudo-random generator function provided by C.
9227 No guarantees can be given for its statistical properties.
9228
9229
9230
9231
9232 <p>
9233 <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
9234
9235
9236 <p>
9237 Sets <code>x</code> as the "seed"
9238 for the pseudo-random generator:
9239 equal seeds produce equal sequences of numbers.
9240
9241
9242
9243
9244 <p>
9245 <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
9246
9247
9248 <p>
9249 Returns the sine of <code>x</code> (assumed to be in radians).
9250
9251
9252
9253
9254 <p>
9255 <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
9256
9257
9258 <p>
9259 Returns the square root of <code>x</code>.
9260 (You can also use the expression <code>x^0.5</code> to compute this value.)
9261
9262
9263
9264
9265 <p>
9266 <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
9267
9268
9269 <p>
9270 Returns the tangent of <code>x</code> (assumed to be in radians).
9271
9272
9273
9274
9275 <p>
9276 <hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
9277
9278
9279 <p>
9280 If the value <code>x</code> is convertible to an integer,
9281 returns that integer.
9282 Otherwise, returns <b>nil</b>.
9283
9284
9285
9286
9287 <p>
9288 <hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
9289
9290
9291 <p>
9292 Returns "<code>integer</code>" if <code>x</code> is an integer,
9293 "<code>float</code>" if it is a float,
9294 or <b>nil</b> if <code>x</code> is not a number.
9295
9296
9297
9298
9299 <p>
9300 <hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
9301
9302
9303 <p>
9304 Returns a boolean,
9305 true if integer <code>m</code> is below integer <code>n</code> when
9306 they are compared as unsigned integers.
9307
9308
9309
9310
9311
9312
9313
9314 <h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
9315
9316 <p>
9317 The I/O library provides two different styles for file manipulation.
9318 The first one uses implicit file handles;
9319 that is, there are operations to set a default input file and a
9320 default output file,
9321 and all input/output operations are over these default files.
9322 The second style uses explicit file handles.
9323
9324
9325 <p>
9326 When using implicit file handles,
9327 all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
9328 When using explicit file handles,
9329 the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
9330 and then all operations are supplied as methods of the file handle.
9331
9332
9333 <p>
9334 The table <code>io</code> also provides
9335 three predefined file handles with their usual meanings from C:
9336 <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>.
9337 The I/O library never closes these files.
9338
9339
9340 <p>
9341 Unless otherwise stated,
9342 all I/O functions return <b>nil</b> on failure
9343 (plus an error message as a second result and
9344 a system-dependent error code as a third result)
9345 and some value different from <b>nil</b> on success.
9346 On non-POSIX systems,
9347 the computation of the error message and error code
9348 in case of errors
9349 may be not thread safe,
9350 because they rely on the global C variable <code>errno</code>.
9351
9352
9353 <p>
9354 <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
9355
9356
9357 <p>
9358 Equivalent to <code>file:close()</code>.
9359 Without a <code>file</code>, closes the default output file.
9360
9361
9362
9363
9364 <p>
9365 <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
9366
9367
9368 <p>
9369 Equivalent to <code>io.output():flush()</code>.
9370
9371
9372
9373
9374 <p>
9375 <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
9376
9377
9378 <p>
9379 When called with a file name, it opens the named file (in text mode),
9380 and sets its handle as the default input file.
9381 When called with a file handle,
9382 it simply sets this file handle as the default input file.
9383 When called without parameters,
9384 it returns the current default input file.
9385
9386
9387 <p>
9388 In case of errors this function raises the error,
9389 instead of returning an error code.
9390
9391
9392
9393
9394 <p>
9395 <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename &middot;&middot;&middot;])</code></a></h3>
9396
9397
9398 <p>
9399 Opens the given file name in read mode
9400 and returns an iterator function that
9401 works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
9402 When the iterator function detects the end of file,
9403 it returns no values (to finish the loop) and automatically closes the file.
9404
9405
9406 <p>
9407 The call <code>io.lines()</code> (with no file name) is equivalent
9408 to <code>io.input():lines("*l")</code>;
9409 that is, it iterates over the lines of the default input file.
9410 In this case it does not close the file when the loop ends.
9411
9412
9413 <p>
9414 In case of errors this function raises the error,
9415 instead of returning an error code.
9416
9417
9418
9419
9420 <p>
9421 <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
9422
9423
9424 <p>
9425 This function opens a file,
9426 in the mode specified in the string <code>mode</code>.
9427 It returns a new file handle,
9428 or, in case of errors, <b>nil</b> plus an error message.
9429
9430
9431 <p>
9432 The <code>mode</code> string can be any of the following:
9433
9434 <ul>
9435 <li><b>"<code>r</code>": </b> read mode (the default);</li>
9436 <li><b>"<code>w</code>": </b> write mode;</li>
9437 <li><b>"<code>a</code>": </b> append mode;</li>
9438 <li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
9439 <li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
9440 <li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
9441 writing is only allowed at the end of file.</li>
9442 </ul><p>
9443 The <code>mode</code> string can also have a '<code>b</code>' at the end,
9444 which is needed in some systems to open the file in binary mode.
9445
9446
9447
9448
9449 <p>
9450 <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
9451
9452
9453 <p>
9454 Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
9455
9456
9457
9458
9459 <p>
9460 <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
9461
9462
9463 <p>
9464 This function is system dependent and is not available
9465 on all platforms.
9466
9467
9468 <p>
9469 Starts program <code>prog</code> in a separated process and returns
9470 a file handle that you can use to read data from this program
9471 (if <code>mode</code> is <code>"r"</code>, the default)
9472 or to write data to this program
9473 (if <code>mode</code> is <code>"w"</code>).
9474
9475
9476
9477
9478 <p>
9479 <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
9480
9481
9482 <p>
9483 Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
9484
9485
9486
9487
9488 <p>
9489 <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
9490
9491
9492 <p>
9493 Returns a handle for a temporary file.
9494 This file is opened in update mode
9495 and it is automatically removed when the program ends.
9496
9497
9498
9499
9500 <p>
9501 <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
9502
9503
9504 <p>
9505 Checks whether <code>obj</code> is a valid file handle.
9506 Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
9507 <code>"closed file"</code> if <code>obj</code> is a closed file handle,
9508 or <b>nil</b> if <code>obj</code> is not a file handle.
9509
9510
9511
9512
9513 <p>
9514 <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
9515
9516
9517 <p>
9518 Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
9519
9520
9521
9522
9523 <p>
9524 <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
9525
9526
9527 <p>
9528 Closes <code>file</code>.
9529 Note that files are automatically closed when
9530 their handles are garbage collected,
9531 but that takes an unpredictable amount of time to happen.
9532
9533
9534 <p>
9535 When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
9536 <a href="#pdf-file:close"><code>file:close</code></a> returns the same values
9537 returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
9538
9539
9540
9541
9542 <p>
9543 <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
9544
9545
9546 <p>
9547 Saves any written data to <code>file</code>.
9548
9549
9550
9551
9552 <p>
9553 <hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
9554
9555
9556 <p>
9557 Returns an iterator function that,
9558 each time it is called,
9559 reads the file according to the given formats.
9560 When no format is given,
9561 uses "<code>l</code>" as a default.
9562 As an example, the construction
9563
9564 <pre>
9565 for c in file:lines(1) do <em>body</em> end
9566 </pre><p>
9567 will iterate over all characters of the file,
9568 starting at the current position.
9569 Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
9570 when the loop ends.
9571
9572
9573 <p>
9574 In case of errors this function raises the error,
9575 instead of returning an error code.
9576
9577
9578
9579
9580 <p>
9581 <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
9582
9583
9584 <p>
9585 Reads the file <code>file</code>,
9586 according to the given formats, which specify what to read.
9587 For each format,
9588 the function returns a string or a number with the characters read,
9589 or <b>nil</b> if it cannot read data with the specified format.
9590 (In this latter case,
9591 the function does not read subsequent formats.)
9592 When called without formats,
9593 it uses a default format that reads the next line
9594 (see below).
9595
9596
9597 <p>
9598 The available formats are
9599
9600 <ul>
9601
9602 <li><b>"<code>n</code>": </b>
9603 reads a numeral and returns it as a float or an integer,
9604 following the lexical conventions of Lua.
9605 (The numeral may have leading spaces and a sign.)
9606 This format always reads the longest input sequence that
9607 is a valid prefix for a number;
9608 if that prefix does not form a valid number
9609 (e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"),
9610 it is discarded and the function returns <b>nil</b>.
9611 </li>
9612
9613 <li><b>"<code>i</code>": </b>
9614 reads an integral number and returns it as an integer.
9615 </li>
9616
9617 <li><b>"<code>a</code>": </b>
9618 reads the whole file, starting at the current position.
9619 On end of file, it returns the empty string.
9620 </li>
9621
9622 <li><b>"<code>l</code>": </b>
9623 reads the next line skipping the end of line,
9624 returning <b>nil</b> on end of file.
9625 This is the default format.
9626 </li>
9627
9628 <li><b>"<code>L</code>": </b>
9629 reads the next line keeping the end-of-line character (if present),
9630 returning <b>nil</b> on end of file.
9631 </li>
9632
9633 <li><b><em>number</em>: </b>
9634 reads a string with up to this number of bytes,
9635 returning <b>nil</b> on end of file.
9636 If <code>number</code> is zero,
9637 it reads nothing and returns an empty string,
9638 or <b>nil</b> on end of file.
9639 </li>
9640
9641 </ul><p>
9642 The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
9643
9644
9645
9646
9647 <p>
9648 <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
9649
9650
9651 <p>
9652 Sets and gets the file position,
9653 measured from the beginning of the file,
9654 to the position given by <code>offset</code> plus a base
9655 specified by the string <code>whence</code>, as follows:
9656
9657 <ul>
9658 <li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
9659 <li><b>"<code>cur</code>": </b> base is current position;</li>
9660 <li><b>"<code>end</code>": </b> base is end of file;</li>
9661 </ul><p>
9662 In case of success, <code>seek</code> returns the final file position,
9663 measured in bytes from the beginning of the file.
9664 If <code>seek</code> fails, it returns <b>nil</b>,
9665 plus a string describing the error.
9666
9667
9668 <p>
9669 The default value for <code>whence</code> is <code>"cur"</code>,
9670 and for <code>offset</code> is 0.
9671 Therefore, the call <code>file:seek()</code> returns the current
9672 file position, without changing it;
9673 the call <code>file:seek("set")</code> sets the position to the
9674 beginning of the file (and returns 0);
9675 and the call <code>file:seek("end")</code> sets the position to the
9676 end of the file, and returns its size.
9677
9678
9679
9680
9681 <p>
9682 <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
9683
9684
9685 <p>
9686 Sets the buffering mode for an output file.
9687 There are three available modes:
9688
9689 <ul>
9690
9691 <li><b>"<code>no</code>": </b>
9692 no buffering; the result of any output operation appears immediately.
9693 </li>
9694
9695 <li><b>"<code>full</code>": </b>
9696 full buffering; output operation is performed only
9697 when the buffer is full or when
9698 you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>).
9699 </li>
9700
9701 <li><b>"<code>line</code>": </b>
9702 line buffering; output is buffered until a newline is output
9703 or there is any input from some special files
9704 (such as a terminal device).
9705 </li>
9706
9707 </ul><p>
9708 For the last two cases, <code>size</code>
9709 specifies the size of the buffer, in bytes.
9710 The default is an appropriate size.
9711
9712
9713
9714
9715 <p>
9716 <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
9717
9718
9719 <p>
9720 Writes the value of each of its arguments to <code>file</code>.
9721 The arguments must be strings or numbers.
9722
9723
9724 <p>
9725 In case of success, this function returns <code>file</code>.
9726 Otherwise it returns <b>nil</b> plus a string describing the error.
9727
9728
9729
9730
9731
9732
9733
9734 <h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
9735
9736 <p>
9737 This library is implemented through table <a name="pdf-os"><code>os</code></a>.
9738
9739
9740 <p>
9741 <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
9742
9743
9744 <p>
9745 Returns an approximation of the amount in seconds of CPU time
9746 used by the program.
9747
9748
9749
9750
9751 <p>
9752 <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
9753
9754
9755 <p>
9756 Returns a string or a table containing date and time,
9757 formatted according to the given string <code>format</code>.
9758
9759
9760 <p>
9761 If the <code>time</code> argument is present,
9762 this is the time to be formatted
9763 (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
9764 Otherwise, <code>date</code> formats the current time.
9765
9766
9767 <p>
9768 If <code>format</code> starts with '<code>!</code>',
9769 then the date is formatted in Coordinated Universal Time.
9770 After this optional character,
9771 if <code>format</code> is the string "<code>*t</code>",
9772 then <code>date</code> returns a table with the following fields:
9773 <code>year</code> (four digits), <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
9774 <code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59), <code>sec</code> (0&ndash;61),
9775 <code>wday</code> (weekday, Sunday is&nbsp;1),
9776 <code>yday</code> (day of the year),
9777 and <code>isdst</code> (daylight saving flag, a boolean).
9778 This last field may be absent
9779 if the information is not available.
9780
9781
9782 <p>
9783 If <code>format</code> is not "<code>*t</code>",
9784 then <code>date</code> returns the date as a string,
9785 formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
9786
9787
9788 <p>
9789 When called without arguments,
9790 <code>date</code> returns a reasonable date and time representation that depends on
9791 the host system and on the current locale
9792 (that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
9793
9794
9795 <p>
9796 On non-POSIX systems,
9797 this function may be not thread safe
9798 because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
9799
9800
9801
9802
9803 <p>
9804 <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
9805
9806
9807 <p>
9808 Returns the difference, in seconds,
9809 from time <code>t1</code> to time <code>t2</code>
9810 (where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
9811 In POSIX, Windows, and some other systems,
9812 this value is exactly <code>t2</code><em>-</em><code>t1</code>.
9813
9814
9815
9816
9817 <p>
9818 <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
9819
9820
9821 <p>
9822 This function is equivalent to the ISO&nbsp;C function <code>system</code>.
9823 It passes <code>command</code> to be executed by an operating system shell.
9824 Its first result is <b>true</b>
9825 if the command terminated successfully,
9826 or <b>nil</b> otherwise.
9827 After this first result
9828 the function returns a string plus a number,
9829 as follows:
9830
9831 <ul>
9832
9833 <li><b>"<code>exit</code>": </b>
9834 the command terminated normally;
9835 the following number is the exit status of the command.
9836 </li>
9837
9838 <li><b>"<code>signal</code>": </b>
9839 the command was terminated by a signal;
9840 the following number is the signal that terminated the command.
9841 </li>
9842
9843 </ul>
9844
9845 <p>
9846 When called without a <code>command</code>,
9847 <code>os.execute</code> returns a boolean that is true if a shell is available.
9848
9849
9850
9851
9852 <p>
9853 <hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
9854
9855
9856 <p>
9857 Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
9858 If <code>code</code> is <b>true</b>,
9859 the returned status is <code>EXIT_SUCCESS</code>;
9860 if <code>code</code> is <b>false</b>,
9861 the returned status is <code>EXIT_FAILURE</code>;
9862 if <code>code</code> is a number,
9863 the returned status is this number.
9864 The default value for <code>code</code> is <b>true</b>.
9865
9866
9867 <p>
9868 If the optional second argument <code>close</code> is true,
9869 closes the Lua state before exiting.
9870
9871
9872
9873
9874 <p>
9875 <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
9876
9877
9878 <p>
9879 Returns the value of the process environment variable <code>varname</code>,
9880 or <b>nil</b> if the variable is not defined.
9881
9882
9883
9884
9885 <p>
9886 <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
9887
9888
9889 <p>
9890 Deletes the file (or empty directory, on POSIX systems)
9891 with the given name.
9892 If this function fails, it returns <b>nil</b>,
9893 plus a string describing the error and the error code.
9894
9895
9896
9897
9898 <p>
9899 <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
9900
9901
9902 <p>
9903 Renames file or directory named <code>oldname</code> to <code>newname</code>.
9904 If this function fails, it returns <b>nil</b>,
9905 plus a string describing the error and the error code.
9906
9907
9908
9909
9910 <p>
9911 <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
9912
9913
9914 <p>
9915 Sets the current locale of the program.
9916 <code>locale</code> is a system-dependent string specifying a locale;
9917 <code>category</code> is an optional string describing which category to change:
9918 <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
9919 <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
9920 the default category is <code>"all"</code>.
9921 The function returns the name of the new locale,
9922 or <b>nil</b> if the request cannot be honored.
9923
9924
9925 <p>
9926 If <code>locale</code> is the empty string,
9927 the current locale is set to an implementation-defined native locale.
9928 If <code>locale</code> is the string "<code>C</code>",
9929 the current locale is set to the standard C locale.
9930
9931
9932 <p>
9933 When called with <b>nil</b> as the first argument,
9934 this function only returns the name of the current locale
9935 for the given category.
9936
9937
9938 <p>
9939 This function may be not thread safe
9940 because of its reliance on C&nbsp;function <code>setlocale</code>.
9941
9942
9943
9944
9945 <p>
9946 <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
9947
9948
9949 <p>
9950 Returns the current time when called without arguments,
9951 or a time representing the date and time specified by the given table.
9952 This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
9953 and may have fields
9954 <code>hour</code> (default is 12),
9955 <code>min</code> (default is 0),
9956 <code>sec</code> (default is 0),
9957 and <code>isdst</code> (default is <b>nil</b>).
9958 For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
9959
9960
9961 <p>
9962 The returned value is a number, whose meaning depends on your system.
9963 In POSIX, Windows, and some other systems,
9964 this number counts the number
9965 of seconds since some given start time (the "epoch").
9966 In other systems, the meaning is not specified,
9967 and the number returned by <code>time</code> can be used only as an argument to
9968 <a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
9969
9970
9971
9972
9973 <p>
9974 <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
9975
9976
9977 <p>
9978 Returns a string with a file name that can
9979 be used for a temporary file.
9980 The file must be explicitly opened before its use
9981 and explicitly removed when no longer needed.
9982
9983
9984 <p>
9985 On POSIX systems,
9986 this function also creates a file with that name,
9987 to avoid security risks.
9988 (Someone else might create the file with wrong permissions
9989 in the time between getting the name and creating the file.)
9990 You still have to open the file to use it
9991 and to remove it (even if you do not use it).
9992
9993
9994 <p>
9995 When possible,
9996 you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
9997 which automatically removes the file when the program ends.
9998
9999
10000
10001
10002
10003
10004
10005 <h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
10006
10007 <p>
10008 This library provides
10009 the functionality of the debug interface (<a href="#4.9">&sect;4.9</a>) to Lua programs.
10010 You should exert care when using this library.
10011 Several of its functions
10012 violate basic assumptions about Lua code
10013 (e.g., that variables local to a function
10014 cannot be accessed from outside;
10015 that userdata metatables cannot be changed by Lua code;
10016 that Lua programs do not crash)
10017 and therefore can compromise otherwise secure code.
10018 Moreover, some functions in this library may be slow.
10019
10020
10021 <p>
10022 All functions in this library are provided
10023 inside the <a name="pdf-debug"><code>debug</code></a> table.
10024 All functions that operate over a thread
10025 have an optional first argument which is the
10026 thread to operate over.
10027 The default is always the current thread.
10028
10029
10030 <p>
10031 <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
10032
10033
10034 <p>
10035 Enters an interactive mode with the user,
10036 running each string that the user enters.
10037 Using simple commands and other debug facilities,
10038 the user can inspect global and local variables,
10039 change their values, evaluate expressions, and so on.
10040 A line containing only the word <code>cont</code> finishes this function,
10041 so that the caller continues its execution.
10042
10043
10044 <p>
10045 Note that commands for <code>debug.debug</code> are not lexically nested
10046 within any function and so have no direct access to local variables.
10047
10048
10049
10050
10051 <p>
10052 <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
10053
10054
10055 <p>
10056 Returns the current hook settings of the thread, as three values:
10057 the current hook function, the current hook mask,
10058 and the current hook count
10059 (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
10060
10061
10062
10063
10064 <p>
10065 <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
10066
10067
10068 <p>
10069 Returns a table with information about a function.
10070 You can give the function directly
10071 or you can give a number as the value of <code>f</code>,
10072 which means the function running at level <code>f</code> of the call stack
10073 of the given thread:
10074 level&nbsp;0 is the current function (<code>getinfo</code> itself);
10075 level&nbsp;1 is the function that called <code>getinfo</code>
10076 (except for tail calls, which do not count on the stack);
10077 and so on.
10078 If <code>f</code> is a number larger than the number of active functions,
10079 then <code>getinfo</code> returns <b>nil</b>.
10080
10081
10082 <p>
10083 The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
10084 with the string <code>what</code> describing which fields to fill in.
10085 The default for <code>what</code> is to get all information available,
10086 except the table of valid lines.
10087 If present,
10088 the option '<code>f</code>'
10089 adds a field named <code>func</code> with the function itself.
10090 If present,
10091 the option '<code>L</code>'
10092 adds a field named <code>activelines</code> with the table of
10093 valid lines.
10094
10095
10096 <p>
10097 For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
10098 a table with a name for the current function,
10099 if a reasonable name can be found,
10100 and the expression <code>debug.getinfo(print)</code>
10101 returns a table with all available information
10102 about the <a href="#pdf-print"><code>print</code></a> function.
10103
10104
10105
10106
10107 <p>
10108 <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
10109
10110
10111 <p>
10112 This function returns the name and the value of the local variable
10113 with index <code>local</code> of the function at level <code>f</code> of the stack.
10114 This function accesses not only explicit local variables,
10115 but also parameters, temporaries, etc.
10116
10117
10118 <p>
10119 The first parameter or local variable has index&nbsp;1, and so on,
10120 following the order that they are declared in the code,
10121 counting only the variables that are active
10122 in the current scope of the function.
10123 Negative indices refer to vararg parameters;
10124 -1 is the first vararg parameter.
10125 The function returns <b>nil</b> if there is no variable with the given index,
10126 and raises an error when called with a level out of range.
10127 (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
10128
10129
10130 <p>
10131 Variable names starting with '<code>(</code>' (open parenthesis)
10132 represent variables with no known names
10133 (internal variables such as loop control variables,
10134 and variables from chunks saved without debug information).
10135
10136
10137 <p>
10138 The parameter <code>f</code> may also be a function.
10139 In that case, <code>getlocal</code> returns only the name of function parameters.
10140
10141
10142
10143
10144 <p>
10145 <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
10146
10147
10148 <p>
10149 Returns the metatable of the given <code>value</code>
10150 or <b>nil</b> if it does not have a metatable.
10151
10152
10153
10154
10155 <p>
10156 <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
10157
10158
10159 <p>
10160 Returns the registry table (see <a href="#4.5">&sect;4.5</a>).
10161
10162
10163
10164
10165 <p>
10166 <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
10167
10168
10169 <p>
10170 This function returns the name and the value of the upvalue
10171 with index <code>up</code> of the function <code>f</code>.
10172 The function returns <b>nil</b> if there is no upvalue with the given index.
10173
10174
10175 <p>
10176 Variable names starting with '<code>(</code>' (open parenthesis)
10177 represent variables with no known names
10178 (variables from chunks saved without debug information).
10179
10180
10181
10182
10183 <p>
10184 <hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
10185
10186
10187 <p>
10188 Returns the Lua value associated to <code>u</code>.
10189 If <code>u</code> is not a userdata,
10190 returns <b>nil</b>.
10191
10192
10193
10194
10195 <p>
10196 <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
10197
10198
10199 <p>
10200 Sets the given function as a hook.
10201 The string <code>mask</code> and the number <code>count</code> describe
10202 when the hook will be called.
10203 The string mask may have any combination of the following characters,
10204 with the given meaning:
10205
10206 <ul>
10207 <li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
10208 <li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
10209 <li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
10210 </ul><p>
10211 Moreover,
10212 with a <code>count</code> different from zero,
10213 the hook is called also after every <code>count</code> instructions.
10214
10215
10216 <p>
10217 When called without arguments,
10218 <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
10219
10220
10221 <p>
10222 When the hook is called, its first parameter is a string
10223 describing the event that has triggered its call:
10224 <code>"call"</code> (or <code>"tail call"</code>),
10225 <code>"return"</code>,
10226 <code>"line"</code>, and <code>"count"</code>.
10227 For line events,
10228 the hook also gets the new line number as its second parameter.
10229 Inside a hook,
10230 you can call <code>getinfo</code> with level&nbsp;2 to get more information about
10231 the running function
10232 (level&nbsp;0 is the <code>getinfo</code> function,
10233 and level&nbsp;1 is the hook function).
10234
10235
10236
10237
10238 <p>
10239 <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
10240
10241
10242 <p>
10243 This function assigns the value <code>value</code> to the local variable
10244 with index <code>local</code> of the function at level <code>level</code> of the stack.
10245 The function returns <b>nil</b> if there is no local
10246 variable with the given index,
10247 and raises an error when called with a <code>level</code> out of range.
10248 (You can call <code>getinfo</code> to check whether the level is valid.)
10249 Otherwise, it returns the name of the local variable.
10250
10251
10252 <p>
10253 See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
10254 variable indices and names.
10255
10256
10257
10258
10259 <p>
10260 <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
10261
10262
10263 <p>
10264 Sets the metatable for the given <code>value</code> to the given <code>table</code>
10265 (which can be <b>nil</b>).
10266 Returns <code>value</code>.
10267
10268
10269
10270
10271 <p>
10272 <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
10273
10274
10275 <p>
10276 This function assigns the value <code>value</code> to the upvalue
10277 with index <code>up</code> of the function <code>f</code>.
10278 The function returns <b>nil</b> if there is no upvalue
10279 with the given index.
10280 Otherwise, it returns the name of the upvalue.
10281
10282
10283
10284
10285 <p>
10286 <hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3>
10287
10288
10289 <p>
10290 Sets the given <code>value</code> as
10291 the Lua value associated to the given <code>udata</code>.
10292 <code>udata</code> must be a full userdata.
10293
10294
10295 <p>
10296 Returns <code>udata</code>.
10297
10298
10299
10300
10301 <p>
10302 <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
10303
10304
10305 <p>
10306 If <code>message</code> is present but is neither a string nor <b>nil</b>,
10307 this function returns <code>message</code> without further processing.
10308 Otherwise,
10309 it returns a string with a traceback of the call stack.
10310 The optional <code>message</code> string is appended
10311 at the beginning of the traceback.
10312 An optional <code>level</code> number tells at which level
10313 to start the traceback
10314 (default is 1, the function calling <code>traceback</code>).
10315
10316
10317
10318
10319 <p>
10320 <hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
10321
10322
10323 <p>
10324 Returns a unique identifier (as a light userdata)
10325 for the upvalue numbered <code>n</code>
10326 from the given function.
10327
10328
10329 <p>
10330 These unique identifiers allow a program to check whether different
10331 closures share upvalues.
10332 Lua closures that share an upvalue
10333 (that is, that access a same external local variable)
10334 will return identical ids for those upvalue indices.
10335
10336
10337
10338
10339 <p>
10340 <hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
10341
10342
10343 <p>
10344 Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
10345 refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
10346
10347
10348
10349
10350
10351
10352
10353 <h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
10354
10355 <p>
10356 Although Lua has been designed as an extension language,
10357 to be embedded in a host C&nbsp;program,
10358 it is also frequently used as a standalone language.
10359 An interpreter for Lua as a standalone language,
10360 called simply <code>lua</code>,
10361 is provided with the standard distribution.
10362 The standalone interpreter includes
10363 all standard libraries, including the debug library.
10364 Its usage is:
10365
10366 <pre>
10367 lua [options] [script [args]]
10368 </pre><p>
10369 The options are:
10370
10371 <ul>
10372 <li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li>
10373 <li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em>;</li>
10374 <li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li>
10375 <li><b><code>-v</code>: </b> prints version information;</li>
10376 <li><b><code>-E</code>: </b> ignores environment variables;</li>
10377 <li><b><code>--</code>: </b> stops handling options;</li>
10378 <li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
10379 </ul><p>
10380 After handling its options, <code>lua</code> runs the given <em>script</em>.
10381 When called without arguments,
10382 <code>lua</code> behaves as <code>lua -v -i</code>
10383 when the standard input (<code>stdin</code>) is a terminal,
10384 and as <code>lua -</code> otherwise.
10385
10386
10387 <p>
10388 When called without option <code>-E</code>,
10389 the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a>
10390 (or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
10391 before running any argument.
10392 If the variable content has the format <code>@<em>filename</em></code>,
10393 then <code>lua</code> executes the file.
10394 Otherwise, <code>lua</code> executes the string itself.
10395
10396
10397 <p>
10398 When called with option <code>-E</code>,
10399 besides ignoring <code>LUA_INIT</code>,
10400 Lua also ignores
10401 the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>,
10402 setting the values of
10403 <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
10404 with the default paths defined in <code>luaconf.h</code>.
10405
10406
10407 <p>
10408 All options are handled in order, except <code>-i</code> and <code>-E</code>.
10409 For instance, an invocation like
10410
10411 <pre>
10412 $ lua -e'a=1' -e 'print(a)' script.lua
10413 </pre><p>
10414 will first set <code>a</code> to 1, then print the value of <code>a</code>,
10415 and finally run the file <code>script.lua</code> with no arguments.
10416 (Here <code>$</code> is the shell prompt. Your prompt may be different.)
10417
10418
10419 <p>
10420 Before running any code,
10421 <code>lua</code> collects all command-line arguments
10422 in a global table called <code>arg</code>.
10423 The script name goes to index 0,
10424 the first argument after the script name goes to index 1,
10425 and so on.
10426 Any arguments before the script name
10427 (that is, the interpreter name plus its options)
10428 go to negative indices.
10429 For instance, in the call
10430
10431 <pre>
10432 $ lua -la b.lua t1 t2
10433 </pre><p>
10434 the table is like this:
10435
10436 <pre>
10437 arg = { [-2] = "lua", [-1] = "-la",
10438 [0] = "b.lua",
10439 [1] = "t1", [2] = "t2" }
10440 </pre><p>
10441 If there is no script in the call,
10442 the interpreter name goes to index 0,
10443 followed by the other arguments.
10444 For instance, the call
10445
10446 <pre>
10447 $ lua -e "print(arg[1])"
10448 </pre><p>
10449 will print "<code>-e</code>".
10450 If there is a script,
10451 the script is called with parameters
10452 <code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
10453 (Like all chunks in Lua,
10454 the script is compiled as a vararg function.)
10455
10456
10457 <p>
10458 In interactive mode,
10459 Lua repeatedly prompts and waits for a line.
10460 After reading a line,
10461 Lua first try to interpret the line as an expression.
10462 If it succeeds, it prints its value.
10463 Otherwise, it interprets the line as a statement.
10464 If you write an incomplete statement,
10465 the interpreter waits for its completion
10466 by issuing a different prompt.
10467
10468
10469 <p>
10470 In case of unprotected errors in the script,
10471 the interpreter reports the error to the standard error stream.
10472 If the error object is not a string but
10473 has a metamethod <code>__tostring</code>,
10474 the interpreter calls this metamethod to produce the final message.
10475 Otherwise, the interpreter converts the error object to a string
10476 and adds a stack traceback to it.
10477
10478
10479 <p>
10480 When finishing normally,
10481 the interpreter closes its main Lua state
10482 (see <a href="#lua_close"><code>lua_close</code></a>).
10483 The script can avoid this step by
10484 calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
10485
10486
10487 <p>
10488 To allow the use of Lua as a
10489 script interpreter in Unix systems,
10490 the standalone interpreter skips
10491 the first line of a chunk if it starts with <code>#</code>.
10492 Therefore, Lua scripts can be made into executable programs
10493 by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
10494 as in
10495
10496 <pre>
10497 #!/usr/local/bin/lua
10498 </pre><p>
10499 (Of course,
10500 the location of the Lua interpreter may be different in your machine.
10501 If <code>lua</code> is in your <code>PATH</code>,
10502 then
10503
10504 <pre>
10505 #!/usr/bin/env lua
10506 </pre><p>
10507 is a more portable solution.)
10508
10509
10510
10511 <h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
10512
10513 <p>
10514 Here we list the incompatibilities that you may find when moving a program
10515 from Lua&nbsp;5.2 to Lua&nbsp;5.3.
10516 You can avoid some incompatibilities by compiling Lua with
10517 appropriate options (see file <code>luaconf.h</code>).
10518 However,
10519 all these compatibility options will be removed in the future.
10520
10521
10522 <p>
10523 Lua versions can always change the C API in ways that
10524 do not imply source-code changes in a program,
10525 such as the numeric values for constants
10526 or the implementation of functions as macros.
10527 Therefore,
10528 you should not assume that binaries are compatible between
10529 different Lua versions.
10530 Always recompile clients of the Lua API when
10531 using a new version.
10532
10533
10534 <p>
10535 Similarly, Lua versions can always change the internal representation
10536 of precompiled chunks;
10537 precompiled chunks are not compatible between different Lua versions.
10538
10539
10540 <p>
10541 The standard paths in the official distribution may
10542 change between versions.
10543
10544
10545
10546 <h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10547 <ul>
10548
10549 <li>
10550 The main difference between Lua&nbsp;5.2 and Lua&nbsp;5.3 is the
10551 introduction of an integer subtype for numbers.
10552 Although this change should not affect "normal" computations,
10553 some computations
10554 (mainly those that involve some kind of overflow)
10555 can give different results.
10556
10557
10558 <p>
10559 You can fix these differences by forcing a number to be a float
10560 (in Lua&nbsp;5.2 all numbers were float),
10561 in particular writing constants with an ending <code>.0</code>
10562 or using <code>x = x + 0.0</code> to convert a variable.
10563 (This recommendation is only for a quick fix
10564 for an occasional incompatibility;
10565 it is not a general guideline for good programming.
10566 For good programming,
10567 use floats where you need floats
10568 and integers where you need integers.)
10569 </li>
10570
10571 <li>
10572 The conversion of a float to a string now adds a <code>.0</code> suffix
10573 to the result if it looks like an integer.
10574 (For instance, the float 2.0 will be printed as <code>2.0</code>,
10575 not as <code>2</code>.)
10576 You should always use an explicit format
10577 when you need a specific format for numbers.
10578
10579
10580 <p>
10581 (Formally this is not an incompatibility,
10582 because Lua does not specify how numbers are formatted as strings,
10583 but some programs assumed a specific format.)
10584 </li>
10585
10586 <li>
10587 The generational mode for the garbage collector was removed.
10588 (It was an experimental feature in Lua&nbsp;5.2.)
10589 </li>
10590
10591 </ul>
10592
10593
10594
10595
10596 <h2>8.2 &ndash; <a name="8.2">Changes in the Libraries</a></h2>
10597 <ul>
10598
10599 <li>
10600 The <code>bit32</code> library has been deprecated.
10601 It is easy to require a compatible external library or,
10602 better yet, to replace its functions with appropriate bitwise operations.
10603 (Keep in mind that <code>bit32</code> operates on 32-bit integers,
10604 while the bitwise operators in standard Lua operate on 64-bit integers.)
10605 </li>
10606
10607 <li>
10608 The Table library now respects metamethods
10609 for setting and getting elements.
10610 </li>
10611
10612 <li>
10613 The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and
10614 its <code>__ipairs</code> metamethod has been deprecated.
10615 </li>
10616
10617 <li>
10618 Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore.
10619 For compatibility, Lua will continue to ignore this character.
10620 </li>
10621
10622 <li>
10623 The following functions were deprecated in the mathematical library:
10624 <code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>,
10625 <code>frexp</code>, and <code>ldexp</code>.
10626 You can replace <code>math.pow(x,y)</code> with <code>x^y</code>;
10627 you can replace <code>math.atan2</code> with <code>math.atan</code>,
10628 which now accepts one or two parameters;
10629 you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>.
10630 For the other operations,
10631 you can either use an external library or
10632 implement them in Lua.
10633 </li>
10634
10635 <li>
10636 The searcher for C loaders used by <a href="#pdf-require"><code>require</code></a>
10637 changed the way it handles versioned names.
10638 Now, the version should come after the module name
10639 (as is usual in most other tools).
10640 For compatibility, that searcher still tries the old format
10641 if it cannot find an open function according to the new style.
10642 (Lua&nbsp;5.2 already worked that way,
10643 but it did not document the change.)
10644 </li>
10645
10646 </ul>
10647
10648
10649
10650
10651 <h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2>
10652
10653
10654 <ul>
10655
10656 <li>
10657 Continuation functions now receive as parameters what they needed
10658 to get through <code>lua_getctx</code>,
10659 so <code>lua_getctx</code> has been removed.
10660 Adapt your code accordingly.
10661 </li>
10662
10663 <li>
10664 Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>.
10665 Use 0 as the value of this parameter to get the old behavior.
10666 </li>
10667
10668 <li>
10669 Functions to inject/project unsigned integers
10670 (<code>lua_pushunsigned</code>, <code>lua_tounsigned</code>, <code>lua_tounsignedx</code>,
10671 <code>luaL_checkunsigned</code>, <code>luaL_optunsigned</code>)
10672 were deprecated.
10673 Use their signed equivalents with a type cast.
10674 </li>
10675
10676 <li>
10677 Macros to project non-default integer types
10678 (<code>luaL_checkint</code>, <code>luaL_optint</code>, <code>luaL_checklong</code>, <code>luaL_optlong</code>)
10679 were deprecated.
10680 Use their equivalent over <a href="#lua_Integer"><code>lua_Integer</code></a> with a type cast
10681 (or, when possible, use <a href="#lua_Integer"><code>lua_Integer</code></a> in your code).
10682 </li>
10683
10684 </ul>
10685
10686
10687
10688
10689 <h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
10690
10691 <p>
10692 Here is the complete syntax of Lua in extended BNF.
10693 As usual in extended BNF,
10694 {A} means 0 or more As,
10695 and [A] means an optional A.
10696 (For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
10697 for a description of the terminals
10698 Name, Numeral,
10699 and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
10700
10701
10702
10703
10704 <pre>
10705
10706 chunk ::= block
10707
10708 block ::= {stat} [retstat]
10709
10710 stat ::= &lsquo;<b>;</b>&rsquo; |
10711 varlist &lsquo;<b>=</b>&rsquo; explist |
10712 functioncall |
10713 label |
10714 <b>break</b> |
10715 <b>goto</b> Name |
10716 <b>do</b> block <b>end</b> |
10717 <b>while</b> exp <b>do</b> block <b>end</b> |
10718 <b>repeat</b> block <b>until</b> exp |
10719 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
10720 <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> |
10721 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
10722 <b>function</b> funcname funcbody |
10723 <b>local</b> <b>function</b> Name funcbody |
10724 <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
10725
10726 retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
10727
10728 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
10729
10730 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
10731
10732 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
10733
10734 var ::= Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
10735
10736 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
10737
10738 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
10739
10740 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
10741 prefixexp | tableconstructor | exp binop exp | unop exp
10742
10743 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
10744
10745 functioncall ::= prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
10746
10747 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
10748
10749 functiondef ::= <b>function</b> funcbody
10750
10751 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
10752
10753 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
10754
10755 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
10756
10757 fieldlist ::= field {fieldsep field} [fieldsep]
10758
10759 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
10760
10761 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
10762
10763 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; |
10764 &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; |
10765 &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; |
10766 <b>and</b> | <b>or</b>
10767
10768 unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
10769
10770 </pre>
10771
10772 <p>
10773
10774
10775
10776
10777
10778
10779
10780
10781 <HR>
10782 <SMALL CLASS="footer">
10783 Last update:
10784 Fri Jan 16 00:58:20 BRST 2015
10785 </SMALL>
10786 <!--
10787 Last change: minor edit
10788 -->
10789
10790 </body></html>
10791