xref: /netbsd-src/external/mit/lua/dist/doc/manual.html (revision 6cf6fe02a981b55727c49c3d37b0d8191a98c0ee)
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="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
16Lua 5.3 Reference Manual
17</h1>
18
19<P>
20<IMG SRC="alert.png" ALIGN="absbottom">
21<EM>All details may change in the final version.</EM>
22<P>
23
24by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
25<p>
26<small>
27Copyright &copy; 2011&ndash;2014 Lua.org, PUC-Rio.
28Freely available under the terms of the
29<a href="http://www.lua.org/license.html">Lua license</a>.
30</small>
31<hr>
32<p>
33
34<a href="contents.html#contents">contents</A>
35&middot;
36<a href="contents.html#index">index</A>
37
38<!-- ====================================================================== -->
39<p>
40
41<!-- $Id: manual.html,v 1.2 2014/07/19 18:38:34 lneto Exp $ -->
42
43
44
45
46<h1>1 &ndash; <a name="1">Introduction</a></h1>
47
48<p>
49Lua is an extension programming language designed to support
50general procedural programming with data description
51facilities.
52It also offers good support for object-oriented programming,
53functional programming, and data-driven programming.
54Lua is intended to be used as a powerful, lightweight,
55embeddable scripting language for any program that needs one.
56Lua is implemented as a library, written in <em>clean C</em>,
57the common subset of Standard&nbsp;C and C++.
58
59
60<p>
61Being an extension language, Lua has no notion of a "main" program:
62it only works <em>embedded</em> in a host client,
63called the <em>embedding program</em> or simply the <em>host</em>.
64The host program can invoke functions to execute a piece of Lua code,
65can write and read Lua variables,
66and can register C&nbsp;functions to be called by Lua code.
67Through the use of C&nbsp;functions, Lua can be augmented to cope with
68a wide range of different domains,
69thus creating customized programming languages sharing a syntactical framework.
70The Lua distribution includes a sample host program called <code>lua</code>,
71which uses the Lua library to offer a complete, standalone Lua interpreter,
72for interactive or batch use.
73
74
75<p>
76Lua is free software,
77and is provided as usual with no guarantees,
78as stated in its license.
79The implementation described in this manual is available
80at Lua's official web site, <code>www.lua.org</code>.
81
82
83<p>
84Like any other reference manual,
85this document is dry in places.
86For a discussion of the decisions behind the design of Lua,
87see the technical papers available at Lua's web site.
88For a detailed introduction to programming in Lua,
89see Roberto's book, <em>Programming in Lua</em>.
90
91
92
93<h1>2 &ndash; <a name="2">Basic Concepts</a></h1>
94
95<p>
96This section describes the basic concepts of the language.
97
98
99
100<h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
101
102<p>
103Lua is a <em>dynamically typed language</em>.
104This means that
105variables do not have types; only values do.
106There are no type definitions in the language.
107All values carry their own type.
108
109
110<p>
111All values in Lua are <em>first-class values</em>.
112This means that all values can be stored in variables,
113passed as arguments to other functions, and returned as results.
114
115
116<p>
117There are eight basic types in Lua:
118<em>nil</em>, <em>boolean</em>, <em>number</em>,
119<em>string</em>, <em>function</em>, <em>userdata</em>,
120<em>thread</em>, and <em>table</em>.
121<em>Nil</em> is the type of the value <b>nil</b>,
122whose main property is to be different from any other value;
123it usually represents the absence of a useful value.
124<em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
125Both <b>nil</b> and <b>false</b> make a condition false;
126any other value makes it true.
127<em>Number</em> represents both
128integral numbers and real (floating-point) numbers.
129<em>String</em> represents immutable sequences of bytes.
130
131Lua is 8-bit clean:
132strings can contain any 8-bit value,
133including embedded zeros ('<code>\0</code>').
134
135
136<p>
137The type <em>number</em> uses two internal representations,
138one called <em>integer</em> and the other called <em>float</em>.
139Lua has explicit rules about when each representation is used,
140but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
141Therefore,
142the programmer has the option of mostly ignoring the difference
143between integers and floats
144or assuming complete control over the representation of each value.
145Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
146but you can also compile Lua so that it
147uses 32-bit integers and/or single-precision (32-bit) floats.
148The option with 32 bits both for integers and floats
149(what is called <em>Small Lua</em>) is particularly attractive
150for small machines.
151
152
153<p>
154Lua can call (and manipulate) functions written in Lua and
155functions written in C
156(see <a href="#3.4.10">&sect;3.4.10</a>).
157
158
159<p>
160The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
161be stored in Lua variables.
162A userdata value is a pointer to a block of raw memory.
163There are two kinds of userdata:
164full userdata, where the block of memory is managed by Lua,
165and light userdata, where the block of memory is managed by the host.
166Userdata has no predefined operations in Lua,
167except assignment and identity test.
168By using <em>metatables</em>,
169the programmer can define operations for full userdata values
170(see <a href="#2.4">&sect;2.4</a>).
171Userdata values cannot be created or modified in Lua,
172only through the C&nbsp;API.
173This guarantees the integrity of data owned by the host program.
174
175
176<p>
177The type <em>thread</em> represents independent threads of execution
178and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
179Do not confuse Lua threads with operating-system threads.
180Lua supports coroutines on all systems,
181even those that do not support threads.
182
183
184<p>
185The type <em>table</em> implements associative arrays,
186that is, arrays that can be indexed not only with numbers,
187but with any Lua value except <b>nil</b> and NaN
188(<em>Not a Number</em>, a special numeric value used to represent
189undefined or unrepresentable results, such as <code>0/0</code>).
190Tables can be <em>heterogeneous</em>;
191that is, they can contain values of all types (except <b>nil</b>).
192Any key with value <b>nil</b> is not considered part of the table.
193Conversely, any key that is not part of a table has
194an associated value <b>nil</b>.
195
196
197<p>
198Tables are the sole data structuring mechanism in Lua;
199they can be used to represent ordinary arrays, sequences,
200symbol tables, sets, records, graphs, trees, etc.
201To represent records, Lua uses the field name as an index.
202The language supports this representation by
203providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
204There are several convenient ways to create tables in Lua
205(see <a href="#3.4.9">&sect;3.4.9</a>).
206
207
208<p>
209We use the term <em>sequence</em> to denote a table where
210the set of all positive numeric keys is equal to <em>{1..n}</em>
211for some integer <em>n</em>,
212which is called the length of the sequence (see <a href="#3.4.7">&sect;3.4.7</a>).
213
214
215<p>
216Like indices,
217the values of table fields can be of any type.
218In particular,
219because functions are first-class values,
220table fields can contain functions.
221Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
222
223
224<p>
225The indexing of tables follows
226the definition of raw equality in the language.
227The expressions <code>a[i]</code> and <code>a[j]</code>
228denote the same table element
229if and only if <code>i</code> and <code>j</code> are raw equal
230(that is, equal without metamethods).
231
232
233<p>
234In particular, floats with integral values
235are equal to their respective integers
236(e.g., <code>1.0 == 1</code>).
237To avoid ambiguities,
238any float with integral value used as a key
239is converted to its respective integer.
240For instance, if you write <code>a[2.0] = true</code>,
241the actual key inserted into the table will be the
242integer <code>2</code>.
243
244
245<p>
246Tables, functions, threads, and (full) userdata values are <em>objects</em>:
247variables do not actually <em>contain</em> these values,
248only <em>references</em> to them.
249Assignment, parameter passing, and function returns
250always manipulate references to such values;
251these operations do not imply any kind of copy.
252
253
254<p>
255The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
256of a given value (see <a href="#6.1">&sect;6.1</a>).
257
258
259
260
261
262<h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
263
264<p>
265As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
266any reference to a global name <code>var</code> is syntactically translated
267to <code>_ENV.var</code>.
268Moreover, every chunk is compiled in the scope of
269an external local variable called <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
270so <code>_ENV</code> itself is never a global name in a chunk.
271
272
273<p>
274Despite the existence of this external <code>_ENV</code> variable and
275the translation of global names,
276<code>_ENV</code> is a completely regular name.
277In particular,
278you can define new variables and parameters with that name.
279Each reference to a global name uses the <code>_ENV</code> that is
280visible at that point in the program,
281following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
282
283
284<p>
285Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
286
287
288<p>
289Lua keeps a distinguished environment called the <em>global environment</em>.
290This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
291In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
292
293
294<p>
295When Lua compiles a chunk,
296it initializes the value of its <code>_ENV</code> upvalue
297with the global environment (see <a href="#pdf-load"><code>load</code></a>).
298Therefore, by default,
299global variables in Lua code refer to entries in the global environment.
300Moreover, all standard libraries are loaded in the global environment
301and several functions there operate on that environment.
302You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
303to load a chunk with a different environment.
304(In C, you have to load the chunk and then change the value
305of its first upvalue.)
306
307
308<p>
309If you change the global environment in the registry
310(through C code or the debug library),
311all chunks loaded after the change will get the new environment.
312Previously loaded chunks are not affected, however,
313as each has its own reference to the environment in its <code>_ENV</code> variable.
314Moreover, the variable <a href="#pdf-_G"><code>_G</code></a>
315(which is stored in the original global environment)
316is never updated by Lua.
317
318
319
320
321
322<h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
323
324<p>
325Because Lua is an embedded extension language,
326all Lua actions start from C&nbsp;code in the host program
327calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
328Whenever an error occurs during
329the compilation or execution of a Lua chunk,
330control returns to the host,
331which can take appropriate measures
332(such as printing an error message).
333
334
335<p>
336Lua code can explicitly generate an error by calling the
337<a href="#pdf-error"><code>error</code></a> function.
338If you need to catch errors in Lua,
339you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
340to call a given function in <em>protected mode</em>.
341
342
343<p>
344Whenever there is an error,
345an <em>error object</em> (also called an <em>error message</em>)
346is propagated with information about the error.
347Lua itself only generates errors where the error object is a string,
348but programs may generate errors with
349any value for the error object.
350
351
352<p>
353When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
354you may give a <em>message handler</em>
355to be called in case of errors.
356This function is called with the original error message
357and returns a new error message.
358It is called before the error unwinds the stack,
359so that it can gather more information about the error,
360for instance by inspecting the stack and creating a stack traceback.
361This message handler is still protected by the protected call;
362so, an error inside the message handler
363will call the message handler again.
364If this loop goes on, Lua breaks it and returns an appropriate message.
365
366
367
368
369
370<h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
371
372<p>
373Every value in Lua can have a <em>metatable</em>.
374This <em>metatable</em> is an ordinary Lua table
375that defines the behavior of the original value
376under certain special operations.
377You can change several aspects of the behavior
378of operations over a value by setting specific fields in its metatable.
379For instance, when a non-numeric value is the operand of an addition,
380Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
381If it finds one,
382Lua calls this function to perform the addition.
383
384
385<p>
386The keys in a metatable are derived from the <em>event</em> names;
387the corresponding values are called <em>metamethods</em>.
388In the previous example, the event is <code>"add"</code>
389and the metamethod is the function that performs the addition.
390
391
392<p>
393You can query the metatable of any value
394using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
395
396
397<p>
398You can replace the metatable of tables
399using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
400You cannot change the metatable of other types from Lua
401(except by using the debug library);
402you must use the C&nbsp;API for that.
403
404
405<p>
406Tables and full userdata have individual metatables
407(although multiple tables and userdata can share their metatables).
408Values of all other types share one single metatable per type;
409that is, there is one single metatable for all numbers,
410one for all strings, etc.
411By default, a value has no metatable,
412but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
413
414
415<p>
416A metatable controls how an object behaves in
417arithmetic and bitwise operations,
418order comparisons, concatenation, length operation, calls, and indexing.
419A metatable also can define a function to be called
420when a userdata or a table is garbage collected.
421
422
423<p>
424A detailed list of events controlled by metatables is given next.
425Each operation is identified by its corresponding event name.
426The key for each event is a string with its name prefixed by
427two underscores, '<code>__</code>';
428for instance, the key for operation "add" is the
429string "<code>__add</code>".
430Note that queries for metamethods are always raw;
431the access to a metamethod does not invoke other metamethods.
432You can emulate how Lua queries a metamethod for an object <code>obj</code>
433with the following code:
434
435<pre>
436     rawget(getmetatable(obj) or {}, event_name)
437</pre>
438
439<p>
440For the unary operators (negation, length, and bitwise not),
441the metamethod is computed and called with a dummy second operand,
442equal to the first one.
443This extra operand is only to simplify Lua's internals
444(by making these operators behave like a binary operation)
445and may be removed in future versions.
446(For most uses this extra operand is irrelevant.)
447
448
449
450<ul>
451
452<li><b>"add": </b>
453the <code>+</code> operation.
454
455If any operand for an addition is not a number
456(nor a string coercible to a number),
457Lua will try to call a metamethod.
458First, Lua will check the first operand (even if it is valid).
459If that operand does not define a metamethod for the "<code>__add</code>" event,
460then Lua will check the second operand.
461If Lua cannot find a metamethod,
462it raises an error.
463Otherwise,
464it calls the metamethod with the two operands as arguments,
465and the result of the call
466(adjusted to one value)
467is the result of the operation.
468</li>
469
470<li><b>"sub": </b>
471the <code>-</code> operation.
472
473Behavior similar to the "add" operation.
474</li>
475
476<li><b>"mul": </b>
477the <code>*</code> operation.
478
479Behavior similar to the "add" operation.
480</li>
481
482<li><b>"div": </b>
483the <code>/</code> operation.
484
485Behavior similar to the "add" operation.
486</li>
487
488<li><b>"mod": </b>
489the <code>%</code> operation.
490
491Behavior similar to the "add" operation.
492</li>
493
494<li><b>"pow": </b>
495the <code>^</code> (exponentiation) operation.
496
497Behavior similar to the "add" operation.
498</li>
499
500<li><b>"unm": </b>
501the <code>-</code> (unary minus) operation.
502
503Behavior similar to the "add" operation.
504</li>
505
506<li><b>"idiv": </b>
507the <code>//</code> (integer division) operation.
508
509Behavior similar to the "add" operation,
510except that Lua will try a metamethod
511if any operator is neither an integer
512nor a value coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
513</li>
514
515<li><b>"band": </b>
516the <code>&amp;</code> (bitwise and) operation.
517
518Behavior similar to the "idiv" operation.
519</li>
520
521<li><b>"bor": </b>
522the <code>|</code> (bitwise or) operation.
523
524Behavior similar to the "band" operation.
525</li>
526
527<li><b>"bxor": </b>
528the <code>~</code> (bitwise exclusive or) operation.
529
530Behavior similar to the "band" operation.
531</li>
532
533<li><b>"bnot": </b>
534the <code>~</code> (bitwise unary not) operation.
535
536Behavior similar to the "band" operation.
537</li>
538
539<li><b>"shl": </b>
540the <code>&lt;&lt;</code> (bitwise left shift) operation.
541
542Behavior similar to the "band" operation.
543</li>
544
545<li><b>"shr": </b>
546the <code>&gt;&gt;</code> (bitwise right shift) operation.
547
548Behavior similar to the "band" operation.
549</li>
550
551<li><b>"concat": </b>
552the <code>..</code> (concatenation) operation.
553
554Behavior similar to the "add" operation,
555except that Lua will try a metamethod
556if any operator is neither a string nor a number
557(which is always coercible to a string).
558</li>
559
560<li><b>"len": </b>
561the <code>#</code> (length) operation.
562
563If the object is not a string,
564Lua will try its metamethod.
565If there is a metamethod,
566Lua calls it with the object as argument,
567and the result of the call
568(always adjusted to one value)
569is the result of the operation.
570If there is no metamethod but the object is a table,
571then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
572Otherwise, Lua raises an error.
573</li>
574
575<li><b>"eq": </b>
576the <code>==</code> (equal) operation.
577
578Behavior similar to the "add" operation,
579except that Lua will try a metamethod only when the values
580being compared are either both tables or both full userdata
581and they are not primitively equal.
582The result of the call is always converted to a boolean.
583</li>
584
585<li><b>"lt": </b>
586the <code>&lt;</code> (less than) operation.
587
588Behavior similar to the "add" operation,
589except that Lua will try a metamethod only when the values
590being compared are neither both numbers nor both strings.
591The result of the call is always converted to a boolean.
592</li>
593
594<li><b>"le": </b>
595the <code>&lt;=</code> (less equal) operation.
596
597Unlike other operations,
598The less-equal operation can use two different events.
599First, Lua looks for the "<code>__le</code>" metamethod in both operands,
600like in the "lt" operation.
601If it cannot find such a metamethod,
602then it will try the "<code>__lt</code>" event,
603assuming that <code>a &lt;= b</code> is equivalent to <code>not (b &lt; a)</code>.
604As with the other comparison operators,
605the result is always a boolean.
606</li>
607
608<li><b>"index": </b>
609The indexing access <code>table[key]</code>.
610
611This event happens when <code>table</code> is not a table or
612when <code>key</code> is not present in <code>table</code>.
613The metamethod is looked up in <code>table</code>.
614
615
616<p>
617Despite the name,
618the metamethod for this event can be either a function or a table.
619If it is a function,
620it is called with <code>table</code> and <code>key</code> as arguments.
621If it is a table,
622the final result is the result of indexing this table with <code>key</code>.
623(This indexing is regular, not raw,
624and therefore can trigger another metamethod.)
625</li>
626
627<li><b>"newindex": </b>
628The indexing assignment <code>table[key] = value</code>.
629
630Like the index event,
631this event happens when <code>table</code> is not a table or
632when <code>key</code> is not present in <code>table</code>.
633The metamethod is looked up in <code>table</code>.
634
635
636<p>
637Again like with indexing,
638the metamethod for this event can be either a function or a table.
639If it is a function,
640it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
641If it is a table,
642Lua does an indexing assignment to this table with the same key and value.
643(This assignment is regular, not raw,
644and therefore can trigger another metamethod.)
645
646
647<p>
648Whenever there is a metamethod,
649Lua does not perform the primitive assignment.
650(If necessary,
651the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
652to do the assignment.)
653</li>
654
655<li><b>"call": </b>
656The call operation <code>func(args)</code>.
657
658This event happens when Lua tries to call a non-function value
659(that is, <code>func</code> is not a function).
660The metamethod is looked up in <code>func</code>.
661If present,
662the metamethod is called with <code>func</code> as its first argument,
663followed by the arguments of the original call (<code>args</code>).
664</li>
665
666</ul>
667
668
669
670
671<h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
672
673<p>
674Lua performs automatic memory management.
675This means that
676you have to worry neither about allocating memory for new objects
677nor about freeing it when the objects are no longer needed.
678Lua manages memory automatically by running
679a <em>garbage collector</em> to collect all <em>dead objects</em>
680(that is, objects that are no longer accessible from Lua).
681All memory used by Lua is subject to automatic management:
682strings, tables, userdata, functions, threads, internal structures, etc.
683
684
685<p>
686Lua implements an incremental mark-and-sweep collector.
687It uses two numbers to control its garbage-collection cycles:
688the <em>garbage-collector pause</em> and
689the <em>garbage-collector step multiplier</em>.
690Both use percentage points as units
691(e.g., a value of 100 means an internal value of 1).
692
693
694<p>
695The garbage-collector pause
696controls how long the collector waits before starting a new cycle.
697Larger values make the collector less aggressive.
698Values smaller than 100 mean the collector will not wait to
699start a new cycle.
700A value of 200 means that the collector waits for the total memory in use
701to double before starting a new cycle.
702
703
704<p>
705The garbage-collector step multiplier
706controls the relative speed of the collector relative to
707memory allocation.
708Larger values make the collector more aggressive but also increase
709the size of each incremental step.
710You should not use values smaller than 100,
711as they make the collector too slow and
712can result in the collector never finishing a cycle.
713The default is 200,
714which means that the collector runs at "twice"
715the speed of memory allocation.
716
717
718<p>
719If you set the step multiplier to a very large number
720(larger than 10% of the maximum number of
721bytes that the program may use),
722the collector behaves like a stop-the-world collector.
723If you then set the pause to 200,
724the collector behaves as in old Lua versions,
725doing a complete collection every time Lua doubles its
726memory usage.
727
728
729<p>
730You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
731or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
732You can also use these functions to control
733the collector directly (e.g., stop and restart it).
734
735
736
737<h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
738
739<p>
740You can set garbage-collector metamethods for tables
741and, using the C&nbsp;API,
742for full userdata (see <a href="#2.4">&sect;2.4</a>).
743These metamethods are also called <em>finalizers</em>.
744Finalizers allow you to coordinate Lua's garbage collection
745with external resource management
746(such as closing files, network or database connections,
747or freeing your own memory).
748
749
750<p>
751For an object (table or userdata) to be finalized when collected,
752you must <em>mark</em> it for finalization.
753
754You mark an object for finalization when you set its metatable
755and the metatable has a field indexed by the string "<code>__gc</code>".
756Note that if you set a metatable without a <code>__gc</code> field
757and later create that field in the metatable,
758the object will not be marked for finalization.
759However, after an object is marked,
760you can freely change the <code>__gc</code> field of its metatable.
761
762
763<p>
764When a marked object becomes garbage,
765it is not collected immediately by the garbage collector.
766Instead, Lua puts it in a list.
767After the collection,
768Lua goes through that list:
769For each object,
770it checks the object's <code>__gc</code> metamethod;
771if it is a function,
772Lua calls it with the object as its single argument.
773(If the metamethod is not a function,
774Lua simply ignores it.)
775
776
777<p>
778At the end of each garbage-collection cycle,
779the finalizers for objects are called in
780the reverse order that they were marked for finalization,
781among those collected in that cycle;
782that is, the first finalizer to be called is the one associated
783with the object marked last in the program.
784The execution of each finalizer may occur at any point during
785the execution of the regular code.
786
787
788<p>
789Because the object being collected must still be used by the finalizer,
790it (and other objects accessible only through it)
791must be <em>resurrected</em> by Lua.
792Usually, this resurrection is transient,
793and the object memory is freed in the next garbage-collection cycle.
794However, if the finalizer stores the object in some global place
795(e.g., a global variable),
796then there is a permanent resurrection.
797Moreover, if the finalizer marks a finalizing object for finalization again,
798its finalizer will be called again in the next cycle where the
799object is unreachable.
800In any case,
801the object memory is freed only in the GC cycle where
802the object is unreachable and not marked for finalization.
803
804
805<p>
806When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
807Lua calls the finalizers of all objects marked for finalization,
808following the reverse order that they were marked.
809If any finalizer marks objects for collection during that phase,
810these marks have no effect.
811
812
813
814
815
816<h3>2.5.2 &ndash; <a name="2.5.2">Weak Tables</a></h3>
817
818<p>
819A <em>weak table</em> is a table whose elements are
820<em>weak references</em>.
821A weak reference is ignored by the garbage collector.
822In other words,
823if the only references to an object are weak references,
824then the garbage collector will collect that object.
825
826
827<p>
828A weak table can have weak keys, weak values, or both.
829A table with weak keys allows the collection of its keys,
830but prevents the collection of its values.
831A table with both weak keys and weak values allows the collection of
832both keys and values.
833In any case, if either the key or the value is collected,
834the whole pair is removed from the table.
835The weakness of a table is controlled by the
836<code>__mode</code> field of its metatable.
837If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
838the keys in the table are weak.
839If <code>__mode</code> contains '<code>v</code>',
840the values in the table are weak.
841
842
843<p>
844A table with weak keys and strong values
845is also called an <em>ephemeron table</em>.
846In an ephemeron table,
847a value is considered reachable only if its key is reachable.
848In particular,
849if the only reference to a key comes through its value,
850the pair is removed.
851
852
853<p>
854Any change in the weakness of a table may take effect only
855at the next collect cycle.
856In particular, if you change the weakness to a stronger mode,
857Lua may still collect some items from that table
858before the change takes effect.
859
860
861<p>
862Only objects that have an explicit construction
863are removed from weak tables.
864Values, such as numbers and light C functions,
865are not subject to garbage collection,
866and therefore are not removed from weak tables
867(unless its associated value is collected).
868Although strings are subject to garbage collection,
869they do not have an explicit construction,
870and therefore are not removed from weak tables.
871
872
873<p>
874Resurrected objects
875(that is, objects being finalized
876and objects accessible only through objects being finalized)
877have a special behavior in weak tables.
878They are removed from weak values before running their finalizers,
879but are removed from weak keys only in the next collection
880after running their finalizers, when such objects are actually freed.
881This behavior allows the finalizer to access properties
882associated with the object through weak tables.
883
884
885<p>
886If a weak table is among the resurrected objects in a collection cycle,
887it may not be properly cleared until the next cycle.
888
889
890
891
892
893
894
895<h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
896
897<p>
898Lua supports coroutines,
899also called <em>collaborative multithreading</em>.
900A coroutine in Lua represents an independent thread of execution.
901Unlike threads in multithread systems, however,
902a coroutine only suspends its execution by explicitly calling
903a yield function.
904
905
906<p>
907You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
908Its sole argument is a function
909that is the main function of the coroutine.
910The <code>create</code> function only creates a new coroutine and
911returns a handle to it (an object of type <em>thread</em>);
912it does not start the coroutine.
913
914
915<p>
916You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
917When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
918passing as its first argument
919a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
920the coroutine starts its execution,
921at the first line of its main function.
922Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
923to the coroutine main function.
924After the coroutine starts running,
925it runs until it terminates or <em>yields</em>.
926
927
928<p>
929A coroutine can terminate its execution in two ways:
930normally, when its main function returns
931(explicitly or implicitly, after the last instruction);
932and abnormally, if there is an unprotected error.
933In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
934plus any values returned by the coroutine main function.
935In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
936plus an error message.
937
938
939<p>
940A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
941When a coroutine yields,
942the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
943even if the yield happens inside nested function calls
944(that is, not in the main function,
945but in a function directly or indirectly called by the main function).
946In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
947plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
948The next time you resume the same coroutine,
949it continues its execution from the point where it yielded,
950with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
951arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
952
953
954<p>
955Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
956the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
957but instead of returning the coroutine itself,
958it returns a function that, when called, resumes the coroutine.
959Any arguments passed to this function
960go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
961<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>,
962except the first one (the boolean error code).
963Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
964<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
965any error is propagated to the caller.
966
967
968<p>
969As an example of how coroutines work,
970consider the following code:
971
972<pre>
973     function foo (a)
974       print("foo", a)
975       return coroutine.yield(2*a)
976     end
977
978     co = coroutine.create(function (a,b)
979           print("co-body", a, b)
980           local r = foo(a+1)
981           print("co-body", r)
982           local r, s = coroutine.yield(a+b, a-b)
983           print("co-body", r, s)
984           return b, "end"
985     end)
986
987     print("main", coroutine.resume(co, 1, 10))
988     print("main", coroutine.resume(co, "r"))
989     print("main", coroutine.resume(co, "x", "y"))
990     print("main", coroutine.resume(co, "x", "y"))
991</pre><p>
992When you run it, it produces the following output:
993
994<pre>
995     co-body 1       10
996     foo     2
997     main    true    4
998     co-body r
999     main    true    11      -9
1000     co-body x       y
1001     main    true    10      end
1002     main    false   cannot resume dead coroutine
1003</pre>
1004
1005<p>
1006You can also create and manipulate coroutines through the C API:
1007see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1008and <a href="#lua_yield"><code>lua_yield</code></a>.
1009
1010
1011
1012
1013
1014<h1>3 &ndash; <a name="3">The Language</a></h1>
1015
1016<p>
1017This section describes the lexis, the syntax, and the semantics of Lua.
1018In other words,
1019this section describes
1020which tokens are valid,
1021how they can be combined,
1022and what their combinations mean.
1023
1024
1025<p>
1026Language constructs will be explained using the usual extended BNF notation,
1027in which
1028{<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1029[<em>a</em>]&nbsp;means an optional <em>a</em>.
1030Non-terminals are shown like non-terminal,
1031keywords are shown like <b>kword</b>,
1032and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1033The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1034at the end of this manual.
1035
1036
1037
1038<h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1039
1040<p>
1041Lua is a free-form language.
1042It ignores spaces (including new lines) and comments
1043between lexical elements (tokens),
1044except as delimiters between names and keywords.
1045
1046
1047<p>
1048<em>Names</em>
1049(also called <em>identifiers</em>)
1050in Lua can be any string of letters,
1051digits, and underscores,
1052not beginning with a digit.
1053Identifiers are used to name variables, table fields, and labels.
1054
1055
1056<p>
1057The following <em>keywords</em> are reserved
1058and cannot be used as names:
1059
1060
1061<pre>
1062     and       break     do        else      elseif    end
1063     false     for       function  goto      if        in
1064     local     nil       not       or        repeat    return
1065     then      true      until     while
1066</pre>
1067
1068<p>
1069Lua is a case-sensitive language:
1070<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1071are two different, valid names.
1072As a convention,
1073programs should avoid creating
1074names that start with an underscore followed by
1075one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
1076
1077
1078<p>
1079The following strings denote other tokens:
1080
1081<pre>
1082     +     -     *     /     %     ^     #
1083     &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
1084     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
1085     (     )     {     }     [     ]     ::
1086     ;     :     ,     .     ..    ...
1087</pre>
1088
1089<p>
1090<em>Literal strings</em>
1091can be delimited by matching single or double quotes,
1092and can contain the following C-like escape sequences:
1093'<code>\a</code>' (bell),
1094'<code>\b</code>' (backspace),
1095'<code>\f</code>' (form feed),
1096'<code>\n</code>' (newline),
1097'<code>\r</code>' (carriage return),
1098'<code>\t</code>' (horizontal tab),
1099'<code>\v</code>' (vertical tab),
1100'<code>\\</code>' (backslash),
1101'<code>\"</code>' (quotation mark [double quote]),
1102and '<code>\'</code>' (apostrophe [single quote]).
1103A backslash followed by a real newline
1104results in a newline in the string.
1105The escape sequence '<code>\z</code>' skips the following span
1106of white-space characters,
1107including line breaks;
1108it is particularly useful to break and indent a long literal string
1109into multiple lines without adding the newlines and spaces
1110into the string contents.
1111
1112
1113<p>
1114A byte in a literal string can also be specified by its numerical value.
1115This can be done with the escape sequence <code>\x<em>XX</em></code>,
1116where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1117or with the escape sequence <code>\<em>ddd</em></code>,
1118where <em>ddd</em> is a sequence of up to three decimal digits.
1119(Note that if a decimal escape is to be followed by a digit,
1120it must be expressed using exactly three digits.)
1121Strings in Lua can contain any 8-bit value, including embedded zeros,
1122which can be specified as '<code>\0</code>'.
1123
1124
1125<p>
1126The UTF-8 encoding of a Unicode character
1127can be inserted in a literal string with
1128the escape sequence <code>\u{<em>XXX</em>}</code>
1129(note the mandatory enclosing brackets),
1130where <em>XXX</em> is a sequence of one or more hexadecimal digits
1131representing the character code point.
1132
1133
1134<p>
1135Literal strings can also be defined using a long format
1136enclosed by <em>long brackets</em>.
1137We define an <em>opening long bracket of level <em>n</em></em> as an opening
1138square bracket followed by <em>n</em> equal signs followed by another
1139opening square bracket.
1140So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1141an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1142and so on.
1143A <em>closing long bracket</em> is defined similarly;
1144for instance,
1145a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
1146A <em>long literal</em> starts with an opening long bracket of any level and
1147ends at the first closing long bracket of the same level.
1148It can contain any text except a closing bracket of the proper level.
1149Literals in this bracketed form can run for several lines,
1150do not interpret any escape sequences,
1151and ignore long brackets of any other level.
1152Any kind of end-of-line sequence
1153(carriage return, newline, carriage return followed by newline,
1154or newline followed by carriage return)
1155is converted to a simple newline.
1156
1157
1158<p>
1159Any byte in a literal string not
1160explicitly affected by the previous rules represents itself.
1161However, Lua opens files for parsing in text mode,
1162and the system file functions may have problems with
1163some control characters.
1164So, it is safer to represent
1165non-text data as a quoted literal with
1166explicit escape sequences for non-text characters.
1167
1168
1169<p>
1170For convenience,
1171when the opening long bracket is immediately followed by a newline,
1172the newline is not included in the string.
1173As an example, in a system using ASCII
1174(in which '<code>a</code>' is coded as&nbsp;97,
1175newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1176the five literal strings below denote the same string:
1177
1178<pre>
1179     a = 'alo\n123"'
1180     a = "alo\n123\""
1181     a = '\97lo\10\04923"'
1182     a = [[alo
1183     123"]]
1184     a = [==[
1185     alo
1186     123"]==]
1187</pre>
1188
1189<p>
1190A <em>numerical constant</em> can be written with an optional fractional part
1191and an optional decimal exponent,
1192marked by a letter '<code>e</code>' or '<code>E</code>'.
1193Lua also accepts hexadecimal constants,
1194which start with <code>0x</code> or <code>0X</code>.
1195Hexadecimal constants also accept an optional fractional part
1196plus an optional binary exponent,
1197marked by a letter '<code>p</code>' or '<code>P</code>'.
1198A numeric constant with a fractional dot or an exponent
1199denotes a float;
1200otherwise it denotes an integer.
1201Examples of valid integer constants are
1202
1203<pre>
1204     3   345   0xff   0xBEBADA
1205</pre><p>
1206Examples of valid float constants are
1207
1208<pre>
1209     3.0     3.1416     314.16e-2     0.31416E1     34e1
1210     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
1211</pre>
1212
1213<p>
1214A <em>comment</em> starts with a double hyphen (<code>--</code>)
1215anywhere outside a string.
1216If the text immediately after <code>--</code> is not an opening long bracket,
1217the comment is a <em>short comment</em>,
1218which runs until the end of the line.
1219Otherwise, it is a <em>long comment</em>,
1220which runs until the corresponding closing long bracket.
1221Long comments are frequently used to disable code temporarily.
1222
1223
1224
1225
1226
1227<h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1228
1229<p>
1230Variables are places that store values.
1231There are three kinds of variables in Lua:
1232global variables, local variables, and table fields.
1233
1234
1235<p>
1236A single name can denote a global variable or a local variable
1237(or a function's formal parameter,
1238which is a particular kind of local variable):
1239
1240<pre>
1241	var ::= Name
1242</pre><p>
1243Name denotes identifiers, as defined in <a href="#3.1">&sect;3.1</a>.
1244
1245
1246<p>
1247Any variable name is assumed to be global unless explicitly declared
1248as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1249Local variables are <em>lexically scoped</em>:
1250local variables can be freely accessed by functions
1251defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1252
1253
1254<p>
1255Before the first assignment to a variable, its value is <b>nil</b>.
1256
1257
1258<p>
1259Square brackets are used to index a table:
1260
1261<pre>
1262	var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1263</pre><p>
1264The meaning of accesses to table fields can be changed via metatables.
1265An access to an indexed variable <code>t[i]</code> is equivalent to
1266a call <code>gettable_event(t,i)</code>.
1267(See <a href="#2.4">&sect;2.4</a> for a complete description of the
1268<code>gettable_event</code> function.
1269This function is not defined or callable in Lua.
1270We use it here only for explanatory purposes.)
1271
1272
1273<p>
1274The syntax <code>var.Name</code> is just syntactic sugar for
1275<code>var["Name"]</code>:
1276
1277<pre>
1278	var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1279</pre>
1280
1281<p>
1282An access to a global variable <code>x</code>
1283is equivalent to <code>_ENV.x</code>.
1284Due to the way that chunks are compiled,
1285<code>_ENV</code> is never a global name (see <a href="#2.2">&sect;2.2</a>).
1286
1287
1288
1289
1290
1291<h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1292
1293<p>
1294Lua supports an almost conventional set of statements,
1295similar to those in Pascal or C.
1296This set includes
1297assignments, control structures, function calls,
1298and variable declarations.
1299
1300
1301
1302<h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1303
1304<p>
1305A block is a list of statements,
1306which are executed sequentially:
1307
1308<pre>
1309	block ::= {stat}
1310</pre><p>
1311Lua has <em>empty statements</em>
1312that allow you to separate statements with semicolons,
1313start a block with a semicolon
1314or write two semicolons in sequence:
1315
1316<pre>
1317	stat ::= &lsquo;<b>;</b>&rsquo;
1318</pre>
1319
1320<p>
1321Function calls and assignments
1322can start with an open parenthesis.
1323This possibility leads to an ambiguity in Lua's grammar.
1324Consider the following fragment:
1325
1326<pre>
1327     a = b + c
1328     (print or io.write)('done')
1329</pre><p>
1330The grammar could see it in two ways:
1331
1332<pre>
1333     a = b + c(print or io.write)('done')
1334
1335     a = b + c; (print or io.write)('done')
1336</pre><p>
1337The current parser always sees such constructions
1338in the first way,
1339interpreting the open parenthesis
1340as the start of the arguments to a call.
1341To avoid this ambiguity,
1342it is a good practice to always precede with a semicolon
1343statements that start with a parenthesis:
1344
1345<pre>
1346     ;(print or io.write)('done')
1347</pre>
1348
1349<p>
1350A block can be explicitly delimited to produce a single statement:
1351
1352<pre>
1353	stat ::= <b>do</b> block <b>end</b>
1354</pre><p>
1355Explicit blocks are useful
1356to control the scope of variable declarations.
1357Explicit blocks are also sometimes used to
1358add a <b>return</b> statement in the middle
1359of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1360
1361
1362
1363
1364
1365<h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1366
1367<p>
1368The unit of compilation of Lua is called a <em>chunk</em>.
1369Syntactically,
1370a chunk is simply a block:
1371
1372<pre>
1373	chunk ::= block
1374</pre>
1375
1376<p>
1377Lua handles a chunk as the body of an anonymous function
1378with a variable number of arguments
1379(see <a href="#3.4.11">&sect;3.4.11</a>).
1380As such, chunks can define local variables,
1381receive arguments, and return values.
1382Moreover, such anonymous function is compiled as in the
1383scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1384The resulting function always has <code>_ENV</code> as its only upvalue,
1385even if it does not use that variable.
1386
1387
1388<p>
1389A chunk can be stored in a file or in a string inside the host program.
1390To execute a chunk,
1391Lua first precompiles the chunk into instructions for a virtual machine,
1392and then it executes the compiled code
1393with an interpreter for the virtual machine.
1394
1395
1396<p>
1397Chunks can also be precompiled into binary form;
1398see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1399Programs in source and compiled forms are interchangeable;
1400Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1401
1402
1403
1404
1405
1406<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1407
1408<p>
1409Lua allows multiple assignments.
1410Therefore, the syntax for assignment
1411defines a list of variables on the left side
1412and a list of expressions on the right side.
1413The elements in both lists are separated by commas:
1414
1415<pre>
1416	stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1417	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1418	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1419</pre><p>
1420Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1421
1422
1423<p>
1424Before the assignment,
1425the list of values is <em>adjusted</em> to the length of
1426the list of variables.
1427If there are more values than needed,
1428the excess values are thrown away.
1429If there are fewer values than needed,
1430the list is extended with as many  <b>nil</b>'s as needed.
1431If the list of expressions ends with a function call,
1432then all values returned by that call enter the list of values,
1433before the adjustment
1434(except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1435
1436
1437<p>
1438The assignment statement first evaluates all its expressions
1439and only then are the assignments performed.
1440Thus the code
1441
1442<pre>
1443     i = 3
1444     i, a[i] = i+1, 20
1445</pre><p>
1446sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1447because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1448before it is assigned&nbsp;4.
1449Similarly, the line
1450
1451<pre>
1452     x, y = y, x
1453</pre><p>
1454exchanges the values of <code>x</code> and <code>y</code>,
1455and
1456
1457<pre>
1458     x, y, z = y, z, x
1459</pre><p>
1460cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1461
1462
1463<p>
1464The meaning of assignments to global variables
1465and table fields can be changed via metatables.
1466An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
1467<code>settable_event(t,i,val)</code>.
1468(See <a href="#2.4">&sect;2.4</a> for a complete description of the
1469<code>settable_event</code> function.
1470This function is not defined or callable in Lua.
1471We use it here only for explanatory purposes.)
1472
1473
1474<p>
1475An assignment to a global variable <code>x = val</code>
1476is equivalent to the assignment
1477<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1478
1479
1480
1481
1482
1483<h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1484The control structures
1485<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1486familiar syntax:
1487
1488
1489
1490
1491<pre>
1492	stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1493	stat ::= <b>repeat</b> block <b>until</b> exp
1494	stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1495</pre><p>
1496Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1497
1498
1499<p>
1500The condition expression of a
1501control structure can return any value.
1502Both <b>false</b> and <b>nil</b> are considered false.
1503All values different from <b>nil</b> and <b>false</b> are considered true
1504(in particular, the number 0 and the empty string are also true).
1505
1506
1507<p>
1508In the <b>repeat</b>&ndash;<b>until</b> loop,
1509the inner block does not end at the <b>until</b> keyword,
1510but only after the condition.
1511So, the condition can refer to local variables
1512declared inside the loop block.
1513
1514
1515<p>
1516The <b>goto</b> statement transfers the program control to a label.
1517For syntactical reasons,
1518labels in Lua are considered statements too:
1519
1520
1521
1522<pre>
1523	stat ::= <b>goto</b> Name
1524	stat ::= label
1525	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1526</pre>
1527
1528<p>
1529A label is visible in the entire block where it is defined,
1530except
1531inside nested blocks where a label with the same name is defined and
1532inside nested functions.
1533A goto may jump to any visible label as long as it does not
1534enter into the scope of a local variable.
1535
1536
1537<p>
1538Labels and empty statements are called <em>void statements</em>,
1539as they perform no actions.
1540
1541
1542<p>
1543The <b>break</b> statement terminates the execution of a
1544<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1545skipping to the next statement after the loop:
1546
1547
1548<pre>
1549	stat ::= <b>break</b>
1550</pre><p>
1551A <b>break</b> ends the innermost enclosing loop.
1552
1553
1554<p>
1555The <b>return</b> statement is used to return values
1556from a function or a chunk (which is a function in disguise).
1557
1558Functions can return more than one value,
1559so the syntax for the <b>return</b> statement is
1560
1561<pre>
1562	stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1563</pre>
1564
1565<p>
1566The <b>return</b> statement can only be written
1567as the last statement of a block.
1568If it is really necessary to <b>return</b> in the middle of a block,
1569then an explicit inner block can be used,
1570as in the idiom <code>do return end</code>,
1571because now <b>return</b> is the last statement in its (inner) block.
1572
1573
1574
1575
1576
1577<h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1578
1579<p>
1580
1581The <b>for</b> statement has two forms:
1582one numeric and one generic.
1583
1584
1585<p>
1586The numeric <b>for</b> loop repeats a block of code while a
1587control variable runs through an arithmetic progression.
1588It has the following syntax:
1589
1590<pre>
1591	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>
1592</pre><p>
1593The <em>block</em> is repeated for <em>name</em> starting at the value of
1594the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
1595third <em>exp</em>.
1596More precisely, a <b>for</b> statement like
1597
1598<pre>
1599     for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
1600</pre><p>
1601is equivalent to the code:
1602
1603<pre>
1604     do
1605       local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
1606       if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
1607       <em>var</em> = <em>var</em> - <em>step</em>
1608       while true do
1609         <em>var</em> = <em>var</em> + <em>step</em>
1610         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
1611           break
1612         end
1613         local v = <em>var</em>
1614         <em>block</em>
1615       end
1616     end
1617</pre>
1618
1619<p>
1620Note the following:
1621
1622<ul>
1623
1624<li>
1625All three control expressions are evaluated only once,
1626before the loop starts.
1627They must all result in numbers.
1628</li>
1629
1630<li>
1631<code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
1632The names shown here are for explanatory purposes only.
1633</li>
1634
1635<li>
1636If the third expression (the step) is absent,
1637then a step of&nbsp;1 is used.
1638</li>
1639
1640<li>
1641You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop.
1642</li>
1643
1644<li>
1645The loop variable <code>v</code> is local to the loop body.
1646If you need its value after the loop,
1647assign it to another variable before exiting the loop.
1648</li>
1649
1650</ul>
1651
1652<p>
1653The generic <b>for</b> statement works over functions,
1654called <em>iterators</em>.
1655On each iteration, the iterator function is called to produce a new value,
1656stopping when this new value is <b>nil</b>.
1657The generic <b>for</b> loop has the following syntax:
1658
1659<pre>
1660	stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1661	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1662</pre><p>
1663A <b>for</b> statement like
1664
1665<pre>
1666     for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
1667</pre><p>
1668is equivalent to the code:
1669
1670<pre>
1671     do
1672       local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
1673       while true do
1674         local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
1675         if <em>var_1</em> == nil then break end
1676         <em>var</em> = <em>var_1</em>
1677         <em>block</em>
1678       end
1679     end
1680</pre><p>
1681Note the following:
1682
1683<ul>
1684
1685<li>
1686<code><em>explist</em></code> is evaluated only once.
1687Its results are an <em>iterator</em> function,
1688a <em>state</em>,
1689and an initial value for the first <em>iterator variable</em>.
1690</li>
1691
1692<li>
1693<code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
1694The names are here for explanatory purposes only.
1695</li>
1696
1697<li>
1698You can use <b>break</b> to exit a <b>for</b> loop.
1699</li>
1700
1701<li>
1702The loop variables <code><em>var_i</em></code> are local to the loop;
1703you cannot use their values after the <b>for</b> ends.
1704If you need these values,
1705then assign them to other variables before breaking or exiting the loop.
1706</li>
1707
1708</ul>
1709
1710
1711
1712
1713<h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1714To allow possible side-effects,
1715function calls can be executed as statements:
1716
1717<pre>
1718	stat ::= functioncall
1719</pre><p>
1720In this case, all returned values are thrown away.
1721Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1722
1723
1724
1725
1726
1727<h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1728Local variables can be declared anywhere inside a block.
1729The declaration can include an initial assignment:
1730
1731<pre>
1732	stat ::= <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
1733</pre><p>
1734If present, an initial assignment has the same semantics
1735of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1736Otherwise, all variables are initialized with <b>nil</b>.
1737
1738
1739<p>
1740A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1741and so local variables can be declared in a chunk outside any explicit block.
1742
1743
1744<p>
1745The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1746
1747
1748
1749
1750
1751
1752
1753<h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
1754
1755<p>
1756The basic expressions in Lua are the following:
1757
1758<pre>
1759	exp ::= prefixexp
1760	exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1761	exp ::= Number
1762	exp ::= String
1763	exp ::= functiondef
1764	exp ::= tableconstructor
1765	exp ::= &lsquo;<b>...</b>&rsquo;
1766	exp ::= exp binop exp
1767	exp ::= unop exp
1768	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1769</pre>
1770
1771<p>
1772Numbers and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1773variables are explained in <a href="#3.2">&sect;3.2</a>;
1774function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
1775function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1776table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
1777Vararg expressions,
1778denoted by three dots ('<code>...</code>'), can only be used when
1779directly inside a vararg function;
1780they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
1781
1782
1783<p>
1784Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
1785bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
1786relational 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>),
1787and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
1788Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
1789the unary bitwise not (see <a href="#3.4.2">&sect;3.4.2</a>),
1790the unary logic <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
1791and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
1792
1793
1794<p>
1795Both function calls and vararg expressions can result in multiple values.
1796If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
1797then its return list is adjusted to zero elements,
1798thus discarding all returned values.
1799If an expression is used as the last (or the only) element
1800of a list of expressions,
1801then no adjustment is made
1802(unless the expression is enclosed in parentheses).
1803In all other contexts,
1804Lua adjusts the result list to one element,
1805either discarding all values except the first one
1806or adding a single <b>nil</b> if there are no values.
1807
1808
1809<p>
1810Here are some examples:
1811
1812<pre>
1813     f()                -- adjusted to 0 results
1814     g(f(), x)          -- f() is adjusted to 1 result
1815     g(x, f())          -- g gets x plus all results from f()
1816     a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
1817     a,b = ...          -- a gets the first vararg parameter, b gets
1818                        -- the second (both a and b can get nil if there
1819                        -- is no corresponding vararg parameter)
1820
1821     a,b,c = x, f()     -- f() is adjusted to 2 results
1822     a,b,c = f()        -- f() is adjusted to 3 results
1823     return f()         -- returns all results from f()
1824     return ...         -- returns all received vararg parameters
1825     return x,y,f()     -- returns x, y, and all results from f()
1826     {f()}              -- creates a list with all results from f()
1827     {...}              -- creates a list with all vararg parameters
1828     {f(), nil}         -- f() is adjusted to 1 result
1829</pre>
1830
1831<p>
1832Any expression enclosed in parentheses always results in only one value.
1833Thus,
1834<code>(f(x,y,z))</code> is always a single value,
1835even if <code>f</code> returns several values.
1836(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
1837or <b>nil</b> if <code>f</code> does not return any values.)
1838
1839
1840
1841<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1842Lua supports the following arithmetic operators:
1843<table border="1">
1844<tr><td><code>+</code></td><td>addition</td></tr>
1845<tr><td><code>-</code></td><td>subtraction</td></tr>
1846<tr><td><code>*</code></td><td>multiplication</td></tr>
1847<tr><td><code>/</code></td><td>float division</td></tr>
1848<tr><td><code>//</code></td><td>integer division</td></tr>
1849<tr><td><code>%</code></td><td>modulo</td></tr>
1850<tr><td><code>^</code></td><td>exponentiation</td></tr>
1851<tr><td><code>-</code></td><td>unary minus</td></tr>
1852</table>
1853
1854
1855<p>
1856With the exception of divisions and exponentiation,
1857the arithmetic operators work as follows:
1858If both operands are integers,
1859the operation is performed over integers and the result is an integer.
1860Otherwise, if both operands are numbers
1861or strings that can be converted to
1862numbers (see <a href="#3.4.3">&sect;3.4.3</a>),
1863then they are converted to floats,
1864the operation is performed following the usual rules
1865for floating-point arithmetic
1866(usually the IEEE 754 standard),
1867and the result is a float.
1868
1869
1870<p>
1871Float division (<code>/</code>) and exponentiation
1872always convert their operands to floats
1873and the result is always a float.
1874Exponentiation uses the ANSI&nbsp;C function <code>pow</code>,
1875so that it works for non-integer exponents too.
1876
1877
1878<p>
1879Integer division (<code>//</code>) converts its operands to integers
1880(see <a href="#3.4.3">&sect;3.4.3</a>)
1881and its result is always an integer.
1882The result is always rounded towards minus infinite (floor).
1883
1884
1885<p>
1886Modulo is defined as the remainder of a division
1887that rounds the quotient towards minus infinite (floor).
1888
1889
1890<p>
1891In case of overflows in integer arithmetic,
1892all operations <em>wrap around</em>,
1893according to the usual rules of two-complement arithmetic.
1894(In other words, they return the correct result modulo <em>2<sup>64</sup></em>.)
1895
1896
1897
1898
1899
1900<h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
1901Lua supports the following bitwise operators:
1902<table border="1">
1903<tr><td><code>&amp;</code></td><td>bitwise and</td></tr>
1904<tr><td><code>|</code></td><td>bitwise or</td></tr>
1905<tr><td><code>~</code></td><td>bitwise exclusive or</td></tr>
1906<tr><td><code>&gt;&gt;</code></td><td>right shift</td></tr>
1907<tr><td><code>&lt;&lt;</code></td><td>left shift</td></tr>
1908<tr><td><code>~</code></td><td>unary bitwise not</td></tr>
1909</table>
1910
1911
1912<p>
1913All bitwise operations convert its operands to integers
1914(see <a href="#3.4.3">&sect;3.4.3</a>),
1915operate on all bits of those integers,
1916and result in an integer.
1917
1918
1919<p>
1920Both right and left shifts fill the vacant bits with zeros.
1921Negative displacements shift to the other direction;
1922displacements with absolute values equal to or higher than
1923the number of bits in an integer
1924result in zero (all bits are shifted out).
1925
1926
1927
1928
1929
1930<h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
1931Lua provides some automatic conversions between some
1932types and representations at run time.
1933Most arithmetic operations applied to mixed numbers
1934(integers and floats) convert the integer operand to a float;
1935this is called the <em>usual rule</em>.
1936Float division always convert integer operands to floats;
1937integer division and bitwise operators
1938always convert float operands to integers.
1939The C API also converts both integers to floats and
1940floats to integers, as needed.
1941Moreover, string concatenation accepts numbers as arguments,
1942besides strings.
1943
1944
1945<p>
1946Lua also converts strings to numbers,
1947whenever a number is expected.
1948
1949
1950<p>
1951In a conversion from integer to float,
1952if the integer value has an exact representation as a float,
1953that is the result.
1954Otherwise,
1955the conversion gets the nearest higher or lower representable value.
1956This kind of conversion never fails.
1957
1958
1959<p>
1960The conversion from float to integer
1961first takes the floor of the float number.
1962If that value can be represented as an integer
1963(that is, it is in the range of integer representation),
1964that is the result.
1965Otherwise, the conversion fails.
1966
1967
1968<p>
1969The conversion from strings to numbers goes as follows:
1970First, the string is converted to an integer or a float,
1971following its syntax and the rules of the Lua lexer.
1972(The string may have also leading and trailing spaces and a sign.)
1973Then, the resulting number is converted to the required type
1974(float or integer) according to the previous rules.
1975
1976
1977<p>
1978The conversion from numbers to strings uses a human-readable,
1979non-specified format.
1980For complete control over how numbers are converted to strings,
1981use the <code>format</code> function from the string library
1982(see <a href="#pdf-string.format"><code>string.format</code></a>).
1983
1984
1985
1986
1987
1988<h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
1989Lua supports the following relational operators:
1990<table border="1">
1991<tr><td><code>==</code></td><td>equality</td></tr>
1992<tr><td><code>~=</code></td><td>inequality</td></tr>
1993<tr><td><code>&lt;</code></td><td>less than</td></tr>
1994<tr><td><code>&gt;</code></td><td>greater than</td></tr>
1995<tr><td><code>&lt;=</code></td><td>less or equal</td></tr>
1996<tr><td><code>&gt;=</code></td><td>greater or equal</td></tr>
1997</table>
1998These operators always result in <b>false</b> or <b>true</b>.
1999
2000
2001<p>
2002Equality (<code>==</code>) first compares the type of its operands.
2003If the types are different, then the result is <b>false</b>.
2004Otherwise, the values of the operands are compared.
2005Strings are compared in the obvious way.
2006Numbers follow the usual rule for binary operations:
2007if both operands are integers,
2008the are compared as integers;
2009otherwise, they are converted to floats
2010and compared as such.
2011
2012
2013<p>
2014Tables, userdata, and threads
2015are compared by reference:
2016two objects are considered equal only if they are the same object.
2017Every time you create a new object
2018(a table, userdata, or thread),
2019this new object is different from any previously existing object.
2020Closures with the same reference are always equal.
2021Closures with any detectable difference
2022(different behavior, different definition) are always different.
2023
2024
2025<p>
2026You can change the way that Lua compares tables and userdata
2027by using the "eq" metamethod (see <a href="#2.4">&sect;2.4</a>).
2028
2029
2030<p>
2031Equality comparisons never convert strings to numbers
2032or vice versa.
2033Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2034and <code>t[0]</code> and <code>t["0"]</code> denote different
2035entries in a table.
2036
2037
2038<p>
2039The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2040
2041
2042<p>
2043The order operators work as follows.
2044If both arguments are numbers,
2045then they are compared following
2046the usual rule for binary operations.
2047Otherwise, if both arguments are strings,
2048then their values are compared according to the current locale.
2049Otherwise, Lua tries to call the "lt" or the "le"
2050metamethod (see <a href="#2.4">&sect;2.4</a>).
2051A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2052and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2053
2054
2055
2056
2057
2058<h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2059The logical operators in Lua are
2060<b>and</b>, <b>or</b>, and <b>not</b>.
2061Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2062all logical operators consider both <b>false</b> and <b>nil</b> as false
2063and anything else as true.
2064
2065
2066<p>
2067The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2068The conjunction operator <b>and</b> returns its first argument
2069if this value is <b>false</b> or <b>nil</b>;
2070otherwise, <b>and</b> returns its second argument.
2071The disjunction operator <b>or</b> returns its first argument
2072if this value is different from <b>nil</b> and <b>false</b>;
2073otherwise, <b>or</b> returns its second argument.
2074Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2075that is,
2076the second operand is evaluated only if necessary.
2077Here are some examples:
2078
2079<pre>
2080     10 or 20            --&gt; 10
2081     10 or error()       --&gt; 10
2082     nil or "a"          --&gt; "a"
2083     nil and 10          --&gt; nil
2084     false and error()   --&gt; false
2085     false and nil       --&gt; false
2086     false or nil        --&gt; nil
2087     10 and 20           --&gt; 20
2088</pre><p>
2089(In this manual,
2090<code>--&gt;</code> indicates the result of the preceding expression.)
2091
2092
2093
2094
2095
2096<h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2097The string concatenation operator in Lua is
2098denoted by two dots ('<code>..</code>').
2099If both operands are strings or numbers, then they are converted to
2100strings according to the rules described in <a href="#3.4.3">&sect;3.4.3</a>.
2101Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2102
2103
2104
2105
2106
2107<h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2108
2109<p>
2110The length operator is denoted by the unary prefix operator <code>#</code>.
2111The length of a string is its number of bytes
2112(that is, the usual meaning of string length when each
2113character is one byte).
2114
2115
2116<p>
2117A program can modify the behavior of the length operator for
2118any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2119
2120
2121<p>
2122Unless a <code>__len</code> metamethod is given,
2123the length of a table <code>t</code> is only defined if the
2124table is a <em>sequence</em>,
2125that is,
2126the set of its positive numeric keys is equal to <em>{1..n}</em>
2127for some non-negative integer <em>n</em>.
2128In that case, <em>n</em> is its length.
2129Note that a table like
2130
2131<pre>
2132     {10, 20, nil, 40}
2133</pre><p>
2134is not a sequence, because it has the key <code>4</code>
2135but does not have the key <code>3</code>.
2136(So, there is no <em>n</em> such that the set <em>{1..n}</em> is equal
2137to the set of positive numeric keys of that table.)
2138Note, however, that non-numeric keys do not interfere
2139with whether a table is a sequence.
2140
2141
2142
2143
2144
2145<h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2146Operator precedence in Lua follows the table below,
2147from lower to higher priority:
2148
2149<pre>
2150     or
2151     and
2152     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2153     |
2154     ~
2155     &amp;
2156     &lt;&lt;    &gt;&gt;
2157     ..
2158     +     -
2159     *     /     //    %
2160     unary operators (not   #     -     ~)
2161     ^
2162</pre><p>
2163As usual,
2164you can use parentheses to change the precedences of an expression.
2165The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2166operators are right associative.
2167All other binary operators are left associative.
2168
2169
2170
2171
2172
2173<h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2174Table constructors are expressions that create tables.
2175Every time a constructor is evaluated, a new table is created.
2176A constructor can be used to create an empty table
2177or to create a table and initialize some of its fields.
2178The general syntax for constructors is
2179
2180<pre>
2181	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2182	fieldlist ::= field {fieldsep field} [fieldsep]
2183	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2184	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2185</pre>
2186
2187<p>
2188Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2189with key <code>exp1</code> and value <code>exp2</code>.
2190A field of the form <code>name = exp</code> is equivalent to
2191<code>["name"] = exp</code>.
2192Finally, fields of the form <code>exp</code> are equivalent to
2193<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
2194starting with 1.
2195Fields in the other formats do not affect this counting.
2196For example,
2197
2198<pre>
2199     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2200</pre><p>
2201is equivalent to
2202
2203<pre>
2204     do
2205       local t = {}
2206       t[f(1)] = g
2207       t[1] = "x"         -- 1st exp
2208       t[2] = "y"         -- 2nd exp
2209       t.x = 1            -- t["x"] = 1
2210       t[3] = f(x)        -- 3rd exp
2211       t[30] = 23
2212       t[4] = 45          -- 4th exp
2213       a = t
2214     end
2215</pre>
2216
2217<p>
2218If the last field in the list has the form <code>exp</code>
2219and the expression is a function call or a vararg expression,
2220then all values returned by this expression enter the list consecutively
2221(see <a href="#3.4.10">&sect;3.4.10</a>).
2222
2223
2224<p>
2225The field list can have an optional trailing separator,
2226as a convenience for machine-generated code.
2227
2228
2229
2230
2231
2232<h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2233A function call in Lua has the following syntax:
2234
2235<pre>
2236	functioncall ::= prefixexp args
2237</pre><p>
2238In a function call,
2239first prefixexp and args are evaluated.
2240If the value of prefixexp has type <em>function</em>,
2241then this function is called
2242with the given arguments.
2243Otherwise, the prefixexp "call" metamethod is called,
2244having as first parameter the value of prefixexp,
2245followed by the original call arguments
2246(see <a href="#2.4">&sect;2.4</a>).
2247
2248
2249<p>
2250The form
2251
2252<pre>
2253	functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2254</pre><p>
2255can be used to call "methods".
2256A call <code>v:name(<em>args</em>)</code>
2257is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2258except that <code>v</code> is evaluated only once.
2259
2260
2261<p>
2262Arguments have the following syntax:
2263
2264<pre>
2265	args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2266	args ::= tableconstructor
2267	args ::= String
2268</pre><p>
2269All argument expressions are evaluated before the call.
2270A call of the form <code>f{<em>fields</em>}</code> is
2271syntactic sugar for <code>f({<em>fields</em>})</code>;
2272that is, the argument list is a single new table.
2273A call of the form <code>f'<em>string</em>'</code>
2274(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2275is syntactic sugar for <code>f('<em>string</em>')</code>;
2276that is, the argument list is a single literal string.
2277
2278
2279<p>
2280A call of the form <code>return <em>functioncall</em></code> is called
2281a <em>tail call</em>.
2282Lua implements <em>proper tail calls</em>
2283(or <em>proper tail recursion</em>):
2284in a tail call,
2285the called function reuses the stack entry of the calling function.
2286Therefore, there is no limit on the number of nested tail calls that
2287a program can execute.
2288However, a tail call erases any debug information about the
2289calling function.
2290Note that a tail call only happens with a particular syntax,
2291where the <b>return</b> has one single function call as argument;
2292this syntax makes the calling function return exactly
2293the returns of the called function.
2294So, none of the following examples are tail calls:
2295
2296<pre>
2297     return (f(x))        -- results adjusted to 1
2298     return 2 * f(x)
2299     return x, f(x)       -- additional results
2300     f(x); return         -- results discarded
2301     return x or f(x)     -- results adjusted to 1
2302</pre>
2303
2304
2305
2306
2307<h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2308
2309<p>
2310The syntax for function definition is
2311
2312<pre>
2313	functiondef ::= <b>function</b> funcbody
2314	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2315</pre>
2316
2317<p>
2318The following syntactic sugar simplifies function definitions:
2319
2320<pre>
2321	stat ::= <b>function</b> funcname funcbody
2322	stat ::= <b>local</b> <b>function</b> Name funcbody
2323	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2324</pre><p>
2325The statement
2326
2327<pre>
2328     function f () <em>body</em> end
2329</pre><p>
2330translates to
2331
2332<pre>
2333     f = function () <em>body</em> end
2334</pre><p>
2335The statement
2336
2337<pre>
2338     function t.a.b.c.f () <em>body</em> end
2339</pre><p>
2340translates to
2341
2342<pre>
2343     t.a.b.c.f = function () <em>body</em> end
2344</pre><p>
2345The statement
2346
2347<pre>
2348     local function f () <em>body</em> end
2349</pre><p>
2350translates to
2351
2352<pre>
2353     local f; f = function () <em>body</em> end
2354</pre><p>
2355not to
2356
2357<pre>
2358     local f = function () <em>body</em> end
2359</pre><p>
2360(This only makes a difference when the body of the function
2361contains references to <code>f</code>.)
2362
2363
2364<p>
2365A function definition is an executable expression,
2366whose value has type <em>function</em>.
2367When Lua precompiles a chunk,
2368all its function bodies are precompiled too.
2369Then, whenever Lua executes the function definition,
2370the function is <em>instantiated</em> (or <em>closed</em>).
2371This function instance (or <em>closure</em>)
2372is the final value of the expression.
2373
2374
2375<p>
2376Parameters act as local variables that are
2377initialized with the argument values:
2378
2379<pre>
2380	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2381</pre><p>
2382When a function is called,
2383the list of arguments is adjusted to
2384the length of the list of parameters,
2385unless the function is a <em>vararg function</em>,
2386which is indicated by three dots ('<code>...</code>')
2387at the end of its parameter list.
2388A vararg function does not adjust its argument list;
2389instead, it collects all extra arguments and supplies them
2390to the function through a <em>vararg expression</em>,
2391which is also written as three dots.
2392The value of this expression is a list of all actual extra arguments,
2393similar to a function with multiple results.
2394If a vararg expression is used inside another expression
2395or in the middle of a list of expressions,
2396then its return list is adjusted to one element.
2397If the expression is used as the last element of a list of expressions,
2398then no adjustment is made
2399(unless that last expression is enclosed in parentheses).
2400
2401
2402<p>
2403As an example, consider the following definitions:
2404
2405<pre>
2406     function f(a, b) end
2407     function g(a, b, ...) end
2408     function r() return 1,2,3 end
2409</pre><p>
2410Then, we have the following mapping from arguments to parameters and
2411to the vararg expression:
2412
2413<pre>
2414     CALL            PARAMETERS
2415
2416     f(3)             a=3, b=nil
2417     f(3, 4)          a=3, b=4
2418     f(3, 4, 5)       a=3, b=4
2419     f(r(), 10)       a=1, b=10
2420     f(r())           a=1, b=2
2421
2422     g(3)             a=3, b=nil, ... --&gt;  (nothing)
2423     g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
2424     g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
2425     g(5, r())        a=5, b=1,   ... --&gt;  2  3
2426</pre>
2427
2428<p>
2429Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2430If control reaches the end of a function
2431without encountering a <b>return</b> statement,
2432then the function returns with no results.
2433
2434
2435<p>
2436
2437There is a system-dependent limit on the number of values
2438that a function may return.
2439This limit is guaranteed to be larger than 1000.
2440
2441
2442<p>
2443The <em>colon</em> syntax
2444is used for defining <em>methods</em>,
2445that is, functions that have an implicit extra parameter <code>self</code>.
2446Thus, the statement
2447
2448<pre>
2449     function t.a.b.c:f (<em>params</em>) <em>body</em> end
2450</pre><p>
2451is syntactic sugar for
2452
2453<pre>
2454     t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2455</pre>
2456
2457
2458
2459
2460
2461
2462<h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2463
2464<p>
2465
2466Lua is a lexically scoped language.
2467The scope of a local variable begins at the first statement after
2468its declaration and lasts until the last non-void statement
2469of the innermost block that includes the declaration.
2470Consider the following example:
2471
2472<pre>
2473     x = 10                -- global variable
2474     do                    -- new block
2475       local x = x         -- new 'x', with value 10
2476       print(x)            --&gt; 10
2477       x = x+1
2478       do                  -- another block
2479         local x = x+1     -- another 'x'
2480         print(x)          --&gt; 12
2481       end
2482       print(x)            --&gt; 11
2483     end
2484     print(x)              --&gt; 10  (the global one)
2485</pre>
2486
2487<p>
2488Notice that, in a declaration like <code>local x = x</code>,
2489the new <code>x</code> being declared is not in scope yet,
2490and so the second <code>x</code> refers to the outside variable.
2491
2492
2493<p>
2494Because of the lexical scoping rules,
2495local variables can be freely accessed by functions
2496defined inside their scope.
2497A local variable used by an inner function is called
2498an <em>upvalue</em>, or <em>external local variable</em>,
2499inside the inner function.
2500
2501
2502<p>
2503Notice that each execution of a <b>local</b> statement
2504defines new local variables.
2505Consider the following example:
2506
2507<pre>
2508     a = {}
2509     local x = 20
2510     for i=1,10 do
2511       local y = 0
2512       a[i] = function () y=y+1; return x+y end
2513     end
2514</pre><p>
2515The loop creates ten closures
2516(that is, ten instances of the anonymous function).
2517Each of these closures uses a different <code>y</code> variable,
2518while all of them share the same <code>x</code>.
2519
2520
2521
2522
2523
2524<h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2525
2526<p>
2527
2528This section describes the C&nbsp;API for Lua, that is,
2529the set of C&nbsp;functions available to the host program to communicate
2530with Lua.
2531All API functions and related types and constants
2532are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2533
2534
2535<p>
2536Even when we use the term "function",
2537any facility in the API may be provided as a macro instead.
2538Except where stated otherwise,
2539all such macros use each of their arguments exactly once
2540(except for the first argument, which is always a Lua state),
2541and so do not generate any hidden side-effects.
2542
2543
2544<p>
2545As in most C&nbsp;libraries,
2546the Lua API functions do not check their arguments for validity or consistency.
2547However, you can change this behavior by compiling Lua
2548with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2549
2550
2551
2552<h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2553
2554<p>
2555Lua uses a <em>virtual stack</em> to pass values to and from C.
2556Each element in this stack represents a Lua value
2557(<b>nil</b>, number, string, etc.).
2558
2559
2560<p>
2561Whenever Lua calls C, the called function gets a new stack,
2562which is independent of previous stacks and of stacks of
2563C&nbsp;functions that are still active.
2564This stack initially contains any arguments to the C&nbsp;function
2565and it is where the C&nbsp;function pushes its results
2566to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2567
2568
2569<p>
2570For convenience,
2571most query operations in the API do not follow a strict stack discipline.
2572Instead, they can refer to any element in the stack
2573by using an <em>index</em>:
2574A positive index represents an absolute stack position
2575(starting at&nbsp;1);
2576a negative index represents an offset relative to the top of the stack.
2577More specifically, if the stack has <em>n</em> elements,
2578then index&nbsp;1 represents the first element
2579(that is, the element that was pushed onto the stack first)
2580and
2581index&nbsp;<em>n</em> represents the last element;
2582index&nbsp;-1 also represents the last element
2583(that is, the element at the&nbsp;top)
2584and index <em>-n</em> represents the first element.
2585
2586
2587
2588
2589
2590<h2>4.2 &ndash; <a name="4.2">Stack Size</a></h2>
2591
2592<p>
2593When you interact with the Lua API,
2594you are responsible for ensuring consistency.
2595In particular,
2596<em>you are responsible for controlling stack overflow</em>.
2597You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2598to ensure that the stack has extra slots when pushing new elements.
2599
2600
2601<p>
2602Whenever Lua calls C,
2603it ensures that the stack has at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2604<code>LUA_MINSTACK</code> is defined as 20,
2605so that usually you do not have to worry about stack space
2606unless your code has loops pushing elements onto the stack.
2607
2608
2609<p>
2610When you call a Lua function
2611without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2612Lua ensures that the stack has enough size for all results,
2613but it does not ensure any extra space.
2614So, before pushing anything in the stack after such a call
2615you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2616
2617
2618
2619
2620
2621<h2>4.3 &ndash; <a name="4.3">Valid and Acceptable Indices</a></h2>
2622
2623<p>
2624Any function in the API that receives stack indices
2625works only with <em>valid indices</em> or <em>acceptable indices</em>.
2626
2627
2628<p>
2629A <em>valid index</em> is an index that refers to a
2630real position within the stack, that is,
2631its position lies between&nbsp;1 and the stack top
2632(<code>1 &le; abs(index) &le; top</code>).
2633
2634Usually, functions that can modify the value at an index
2635require valid indices.
2636
2637
2638<p>
2639Unless otherwise noted,
2640any function that accepts valid indices also accepts <em>pseudo-indices</em>,
2641which represent some Lua values that are accessible to C&nbsp;code
2642but which are not in the stack.
2643Pseudo-indices are used to access the registry
2644and the upvalues of a C&nbsp;function (see <a href="#4.4">&sect;4.4</a>).
2645
2646
2647<p>
2648Functions that do not need a specific stack position,
2649but only a value in the stack (e.g., query functions),
2650can be called with acceptable indices.
2651An <em>acceptable index</em> can be any valid index,
2652including the pseudo-indices,
2653but it also can be any positive index after the stack top
2654within the space allocated for the stack,
2655that is, indices up to the stack size.
2656(Note that 0 is never an acceptable index.)
2657Except when noted otherwise,
2658functions in the API work with acceptable indices.
2659
2660
2661<p>
2662Acceptable indices serve to avoid extra tests
2663against the stack top when querying the stack.
2664For instance, a C&nbsp;function can query its third argument
2665without the need to first check whether there is a third argument,
2666that is, without the need to check whether 3 is a valid index.
2667
2668
2669<p>
2670For functions that can be called with acceptable indices,
2671any non-valid index is treated as if it
2672contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
2673which behaves like a nil value.
2674
2675
2676
2677
2678
2679<h2>4.4 &ndash; <a name="4.4">C Closures</a></h2>
2680
2681<p>
2682When a C&nbsp;function is created,
2683it is possible to associate some values with it,
2684thus creating a <em>C&nbsp;closure</em>
2685(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
2686these values are called <em>upvalues</em> and are
2687accessible to the function whenever it is called.
2688
2689
2690<p>
2691Whenever a C&nbsp;function is called,
2692its upvalues are located at specific pseudo-indices.
2693These pseudo-indices are produced by the macro
2694<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2695The first value associated with a function is at position
2696<code>lua_upvalueindex(1)</code>, and so on.
2697Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2698where <em>n</em> is greater than the number of upvalues of the
2699current function (but not greater than 256),
2700produces an acceptable but invalid index.
2701
2702
2703
2704
2705
2706<h2>4.5 &ndash; <a name="4.5">Registry</a></h2>
2707
2708<p>
2709Lua provides a <em>registry</em>,
2710a predefined table that can be used by any C&nbsp;code to
2711store whatever Lua values it needs to store.
2712The registry table is always located at pseudo-index
2713<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
2714which is a valid index.
2715Any C&nbsp;library can store data into this table,
2716but it must take care to choose keys
2717that are different from those used
2718by other libraries, to avoid collisions.
2719Typically, you should use as key a string containing your library name,
2720or a light userdata with the address of a C&nbsp;object in your code,
2721or any Lua object created by your code.
2722As with global names,
2723string keys starting with an underscore followed by
2724uppercase letters are reserved for Lua.
2725
2726
2727<p>
2728The integer keys in the registry are used by the reference mechanism,
2729implemented by the auxiliary library,
2730and by some predefined values.
2731Therefore, integer keys must not be used for other purposes.
2732
2733
2734<p>
2735When you create a new Lua state,
2736its registry comes with some predefined values.
2737These predefined values are indexed with integer keys
2738defined as constants in <code>lua.h</code>.
2739The following constants are defined:
2740
2741<ul>
2742<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
2743the main thread of the state.
2744(The main thread is the one created together with the state.)
2745</li>
2746
2747<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
2748the global environment.
2749</li>
2750</ul>
2751
2752
2753
2754
2755<h2>4.6 &ndash; <a name="4.6">Error Handling in C</a></h2>
2756
2757<p>
2758Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2759(You can also choose to use exceptions if you compile Lua as C++;
2760search for <code>LUAI_THROW</code> in the source code.)
2761When Lua faces any error
2762(such as a memory allocation error, type errors, syntax errors,
2763and runtime errors)
2764it <em>raises</em> an error;
2765that is, it does a long jump.
2766A <em>protected environment</em> uses <code>setjmp</code>
2767to set a recovery point;
2768any error jumps to the most recent active recovery point.
2769
2770
2771<p>
2772If an error happens outside any protected environment,
2773Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
2774and then calls <code>abort</code>,
2775thus exiting the host application.
2776Your panic function can avoid this exit by
2777never returning
2778(e.g., doing a long jump to your own recovery point outside Lua).
2779
2780
2781<p>
2782The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
2783in particular, the error message is at the top of the stack.
2784However, there is no guarantees about stack space.
2785To push anything on the stack,
2786the panic function must first check the available space (see <a href="#4.2">&sect;4.2</a>).
2787
2788
2789<p>
2790Most functions in the API can raise an error,
2791for instance due to a memory allocation error.
2792The documentation for each function indicates whether
2793it can raise errors.
2794
2795
2796<p>
2797Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2798
2799
2800
2801
2802
2803<h2>4.7 &ndash; <a name="4.7">Handling Yields in C</a></h2>
2804
2805<p>
2806Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2807Therefore, if a C function <code>foo</code> calls an API function
2808and this API function yields
2809(directly or indirectly by calling another function that yields),
2810Lua cannot return to <code>foo</code> any more,
2811because the <code>longjmp</code> removes its frame from the C stack.
2812
2813
2814<p>
2815To avoid this kind of problem,
2816Lua raises an error whenever it tries to yield across an API call,
2817except for three functions:
2818<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>.
2819All those functions receive a <em>continuation function</em>
2820(as a parameter called <code>k</code>) to continue execution after a yield.
2821
2822
2823<p>
2824We need to set some terminology to explain continuations.
2825We have a C function called from Lua which we will call
2826the <em>original function</em>.
2827This original function then calls one of those three functions in the C API,
2828which we will call the <em>callee function</em>,
2829that then yields the current thread.
2830(This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
2831or 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>
2832and the function called by them yields.)
2833
2834
2835<p>
2836Suppose the running thread yields while executing the callee function.
2837After the thread resumes,
2838it eventually will finish running the callee function.
2839However,
2840the callee function cannot return to the original function,
2841because its frame in the C stack was destroyed by the yield.
2842Instead, Lua calls a <em>continuation function</em>,
2843which was given as an argument to the callee function.
2844As the name implies,
2845the continuation function should continue the task
2846of the original function.
2847
2848
2849<p>
2850As an illustration, consider the following function:
2851
2852<pre>
2853     int original_function (lua_State *L) {
2854       ...     /* code 1 */
2855       status = lua_pcall(L, n, m, h);  /* calls Lua */
2856       ...     /* code 2 */
2857     }
2858</pre><p>
2859Now we want to allow
2860the Lua code being ran by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
2861First, we can rewrite our function like here:
2862
2863<pre>
2864     int k (lua_State *L, int status, int ctx) {
2865       ...  /* code 2 */
2866     }
2867
2868     int original_function (lua_State *L) {
2869       ...     /* code 1 */
2870       return k(L, lua_pcall(L, n, m, h), ctx);
2871     }
2872</pre><p>
2873In the above code,
2874the new function <code>k</code> is a
2875<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
2876which should do all the work that the original function
2877was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
2878Now, we must inform Lua that it must call <code>k</code> if the Lua code
2879begin running by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
2880(errors or yielding),
2881so we rewrite the code as here,
2882replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
2883
2884<pre>
2885     int original_function (lua_State *L) {
2886       ...     /* code 1 */
2887       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
2888     }
2889</pre>
2890
2891<p>
2892Besides the Lua state,
2893the continuation function has two other parameters:
2894the final status of the call plus the context value (<code>ctx</code>) that
2895was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
2896(Lua does not use this context value;
2897it only passes this value from the original function to the
2898continuation function.)
2899For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
2900the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
2901except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after an yield
2902(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
2903For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
2904the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
2905(For these two functions,
2906Lua will not call the continuation in case of errors,
2907because they do not handle errors.)
2908
2909
2910<p>
2911Lua treats the continuation function as if it were the original function.
2912The continuation function receives the same Lua stack
2913from the original function,
2914in the same state it would be if the callee function had returned.
2915(For instance,
2916after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
2917removed from the stack and replaced by the results from the call.)
2918It also has the same upvalues.
2919Whatever it returns is handled by Lua as if it were the return
2920of the original function.
2921
2922
2923
2924
2925
2926<h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
2927
2928<p>
2929Here we list all functions and types from the C&nbsp;API in
2930alphabetical order.
2931Each function has an indicator like this:
2932<span class="apii">[-o, +p, <em>x</em>]</span>
2933
2934
2935<p>
2936The first field, <code>o</code>,
2937is how many elements the function pops from the stack.
2938The second field, <code>p</code>,
2939is how many elements the function pushes onto the stack.
2940(Any function always pushes its results after popping its arguments.)
2941A field in the form <code>x|y</code> means the function can push (or pop)
2942<code>x</code> or <code>y</code> elements,
2943depending on the situation;
2944an interrogation mark '<code>?</code>' means that
2945we cannot know how many elements the function pops/pushes
2946by looking only at its arguments
2947(e.g., they may depend on what is on the stack).
2948The third field, <code>x</code>,
2949tells whether the function may raise errors:
2950'<code>-</code>' means the function never raises any error;
2951'<code>e</code>' means the function may raise errors;
2952'<code>v</code>' means the function may raise an error on purpose.
2953
2954
2955
2956<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
2957<span class="apii">[-0, +0, &ndash;]</span>
2958<pre>int lua_absindex (lua_State *L, int idx);</pre>
2959
2960<p>
2961Converts the acceptable index <code>idx</code> into an absolute index
2962(that is, one that does not depend on the stack top).
2963
2964
2965
2966
2967
2968<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2969<pre>typedef void * (*lua_Alloc) (void *ud,
2970                             void *ptr,
2971                             size_t osize,
2972                             size_t nsize);</pre>
2973
2974<p>
2975The type of the memory-allocation function used by Lua states.
2976The allocator function must provide a
2977functionality similar to <code>realloc</code>,
2978but not exactly the same.
2979Its arguments are
2980<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2981<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2982<code>osize</code>, the original size of the block or some code about what
2983is being allocated;
2984<code>nsize</code>, the new size of the block.
2985
2986
2987<p>
2988When <code>ptr</code> is not <code>NULL</code>,
2989<code>osize</code> is the size of the block pointed by <code>ptr</code>,
2990that is, the size given when it was allocated or reallocated.
2991
2992
2993<p>
2994When <code>ptr</code> is <code>NULL</code>,
2995<code>osize</code> encodes the kind of object that Lua is allocating.
2996<code>osize</code> is any of
2997<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>,
2998<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)
2999Lua is creating a new object of that type.
3000When <code>osize</code> is some other value,
3001Lua is allocating memory for something else.
3002
3003
3004<p>
3005Lua assumes the following behavior from the allocator function:
3006
3007
3008<p>
3009When <code>nsize</code> is zero,
3010the allocator must behave like <code>free</code>
3011and return <code>NULL</code>.
3012
3013
3014<p>
3015When <code>nsize</code> is not zero,
3016the allocator must behave like <code>realloc</code>.
3017The allocator returns <code>NULL</code>
3018if and only if it cannot fulfill the request.
3019Lua assumes that the allocator never fails when
3020<code>osize &gt;= nsize</code>.
3021
3022
3023<p>
3024Here is a simple implementation for the allocator function.
3025It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
3026
3027<pre>
3028     static void *l_alloc (void *ud, void *ptr, size_t osize,
3029                                                size_t nsize) {
3030       (void)ud;  (void)osize;  /* not used */
3031       if (nsize == 0) {
3032         free(ptr);
3033         return NULL;
3034       }
3035       else
3036         return realloc(ptr, nsize);
3037     }
3038</pre><p>
3039Note that Standard&nbsp;C ensures
3040that <code>free(NULL)</code> has no effect and that
3041<code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
3042This code assumes that <code>realloc</code> does not fail when shrinking a block.
3043(Although Standard&nbsp;C does not ensure this behavior,
3044it seems to be a safe assumption.)
3045
3046
3047
3048
3049
3050<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
3051<span class="apii">[-(2|1), +1, <em>e</em>]</span>
3052<pre>void lua_arith (lua_State *L, int op);</pre>
3053
3054<p>
3055Performs an arithmetic or bitwise operation over the two values
3056(or one, in the case of negations)
3057at the top of the stack,
3058with the value at the top being the second operand,
3059pops these values, and pushes the result of the operation.
3060The function follows the semantics of the corresponding Lua operator
3061(that is, it may call metamethods).
3062
3063
3064<p>
3065The value of <code>op</code> must be one of the following constants:
3066
3067<ul>
3068
3069<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
3070<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
3071<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
3072<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3073<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs integer division (<code>//</code>)</li>
3074<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
3075<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
3076<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3077<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise negation (<code>~</code>)</li>
3078<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise and (<code>&amp;</code>)</li>
3079<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise or (<code>|</code>)</li>
3080<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive or (<code>~</code>)</li>
3081<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3082<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
3083
3084</ul>
3085
3086
3087
3088
3089<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
3090<span class="apii">[-0, +0, &ndash;]</span>
3091<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
3092
3093<p>
3094Sets a new panic function and returns the old one (see <a href="#4.6">&sect;4.6</a>).
3095
3096
3097
3098
3099
3100<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
3101<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
3102<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3103
3104<p>
3105Calls a function.
3106
3107
3108<p>
3109To call a function you must use the following protocol:
3110first, the function to be called is pushed onto the stack;
3111then, the arguments to the function are pushed
3112in direct order;
3113that is, the first argument is pushed first.
3114Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3115<code>nargs</code> is the number of arguments that you pushed onto the stack.
3116All arguments and the function value are popped from the stack
3117when the function is called.
3118The function results are pushed onto the stack when the function returns.
3119The number of results is adjusted to <code>nresults</code>,
3120unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3121In this case, all results from the function are pushed.
3122Lua takes care that the returned values fit into the stack space.
3123The function results are pushed onto the stack in direct order
3124(the first result is pushed first),
3125so that after the call the last result is on the top of the stack.
3126
3127
3128<p>
3129Any error inside the called function is propagated upwards
3130(with a <code>longjmp</code>).
3131
3132
3133<p>
3134The following example shows how the host program can do the
3135equivalent to this Lua code:
3136
3137<pre>
3138     a = f("how", t.x, 14)
3139</pre><p>
3140Here it is in&nbsp;C:
3141
3142<pre>
3143     lua_getglobal(L, "f");                  /* function to be called */
3144     lua_pushstring(L, "how");                        /* 1st argument */
3145     lua_getglobal(L, "t");                    /* table to be indexed */
3146     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
3147     lua_remove(L, -2);                  /* remove 't' from the stack */
3148     lua_pushinteger(L, 14);                          /* 3rd argument */
3149     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
3150     lua_setglobal(L, "a");                         /* set global 'a' */
3151</pre><p>
3152Note that the code above is "balanced":
3153at its end, the stack is back to its original configuration.
3154This is considered good programming practice.
3155
3156
3157
3158
3159
3160<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3161<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3162<pre>void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
3163                lua_KFunction k);</pre>
3164
3165<p>
3166This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3167but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
3168
3169
3170
3171
3172
3173<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3174<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3175
3176<p>
3177Type for C&nbsp;functions.
3178
3179
3180<p>
3181In order to communicate properly with Lua,
3182a C&nbsp;function must use the following protocol,
3183which defines the way parameters and results are passed:
3184a C&nbsp;function receives its arguments from Lua in its stack
3185in direct order (the first argument is pushed first).
3186So, when the function starts,
3187<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3188The first argument (if any) is at index 1
3189and its last argument is at index <code>lua_gettop(L)</code>.
3190To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3191in direct order (the first result is pushed first),
3192and returns the number of results.
3193Any other value in the stack below the results will be properly
3194discarded by Lua.
3195Like a Lua function, a C&nbsp;function called by Lua can also return
3196many results.
3197
3198
3199<p>
3200As an example, the following function receives a variable number
3201of numerical arguments and returns their average and sum:
3202
3203<pre>
3204     static int foo (lua_State *L) {
3205       int n = lua_gettop(L);    /* number of arguments */
3206       lua_Number sum = 0;
3207       int i;
3208       for (i = 1; i &lt;= n; i++) {
3209         if (!lua_isnumber(L, i)) {
3210           lua_pushstring(L, "incorrect argument");
3211           lua_error(L);
3212         }
3213         sum += lua_tonumber(L, i);
3214       }
3215       lua_pushnumber(L, sum/n);        /* first result */
3216       lua_pushnumber(L, sum);         /* second result */
3217       return 2;                   /* number of results */
3218     }
3219</pre>
3220
3221
3222
3223
3224<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3225<span class="apii">[-0, +0, &ndash;]</span>
3226<pre>int lua_checkstack (lua_State *L, int extra);</pre>
3227
3228<p>
3229Ensures that there are at least <code>extra</code> free stack slots in the stack.
3230It returns false if it cannot fulfill the request,
3231because it would cause the stack to be larger than a fixed maximum size
3232(typically at least a few thousand elements) or
3233because it cannot allocate memory for the new stack size.
3234This function never shrinks the stack;
3235if the stack is already larger than the new size,
3236it is left unchanged.
3237
3238
3239
3240
3241
3242<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3243<span class="apii">[-0, +0, &ndash;]</span>
3244<pre>void lua_close (lua_State *L);</pre>
3245
3246<p>
3247Destroys all objects in the given Lua state
3248(calling the corresponding garbage-collection metamethods, if any)
3249and frees all dynamic memory used by this state.
3250On several platforms, you may not need to call this function,
3251because all resources are naturally released when the host program ends.
3252On the other hand, long-running programs that create multiple states,
3253such as daemons or web servers,
3254might need to close states as soon as they are not needed.
3255
3256
3257
3258
3259
3260<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3261<span class="apii">[-0, +0, <em>e</em>]</span>
3262<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3263
3264<p>
3265Compares two Lua values.
3266Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3267when compared with the value at index <code>index2</code>,
3268following the semantics of the corresponding Lua operator
3269(that is, it may call metamethods).
3270Otherwise returns&nbsp;0.
3271Also returns&nbsp;0 if any of the indices is non valid.
3272
3273
3274<p>
3275The value of <code>op</code> must be one of the following constants:
3276
3277<ul>
3278
3279<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3280<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3281<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3282
3283</ul>
3284
3285
3286
3287
3288<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3289<span class="apii">[-n, +1, <em>e</em>]</span>
3290<pre>void lua_concat (lua_State *L, int n);</pre>
3291
3292<p>
3293Concatenates the <code>n</code> values at the top of the stack,
3294pops them, and leaves the result at the top.
3295If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3296(that is, the function does nothing);
3297if <code>n</code> is 0, the result is the empty string.
3298Concatenation is performed following the usual semantics of Lua
3299(see <a href="#3.4.6">&sect;3.4.6</a>).
3300
3301
3302
3303
3304
3305<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3306<span class="apii">[-0, +0, &ndash;]</span>
3307<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3308
3309<p>
3310Moves the element at index <code>fromidx</code>
3311into the valid index <code>toidx</code>
3312without shifting any element
3313(therefore replacing the value at that position).
3314
3315
3316
3317
3318
3319<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3320<span class="apii">[-0, +1, <em>e</em>]</span>
3321<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3322
3323<p>
3324Creates a new empty table and pushes it onto the stack.
3325Parameter <code>narr</code> is a hint for how many elements the table
3326will have as a sequence;
3327parameter <code>nrec</code> is a hint for how many other elements
3328the table will have.
3329Lua may use these hints to preallocate memory for the new table.
3330This pre-allocation is useful for performance when you know in advance
3331how many elements the table will have.
3332Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3333
3334
3335
3336
3337
3338<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3339<span class="apii">[-0, +0, <em>e</em>]</span>
3340<pre>int lua_dump (lua_State *L,
3341                        lua_Writer writer,
3342                        void *data,
3343                        int strip);</pre>
3344
3345<p>
3346Dumps a function as a binary chunk.
3347Receives a Lua function on the top of the stack
3348and produces a binary chunk that,
3349if loaded again,
3350results in a function equivalent to the one dumped.
3351As it produces parts of the chunk,
3352<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3353with the given <code>data</code>
3354to write them.
3355
3356
3357<p>
3358If <code>strip</code> is true,
3359the binary representation is created without debug information
3360about the function.
3361
3362
3363<p>
3364The value returned is the error code returned by the last
3365call to the writer;
33660&nbsp;means no errors.
3367
3368
3369<p>
3370This function does not pop the Lua function from the stack.
3371
3372
3373
3374
3375
3376<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3377<span class="apii">[-1, +0, <em>v</em>]</span>
3378<pre>int lua_error (lua_State *L);</pre>
3379
3380<p>
3381Generates a Lua error.
3382The error object must be on the stack top.
3383This function does a long jump,
3384and therefore never returns
3385(see <a href="#luaL_error"><code>luaL_error</code></a>).
3386
3387
3388
3389
3390
3391<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3392<span class="apii">[-0, +0, <em>e</em>]</span>
3393<pre>int lua_gc (lua_State *L, int what, int data);</pre>
3394
3395<p>
3396Controls the garbage collector.
3397
3398
3399<p>
3400This function performs several tasks,
3401according to the value of the parameter <code>what</code>:
3402
3403<ul>
3404
3405<li><b><code>LUA_GCSTOP</code>: </b>
3406stops the garbage collector.
3407</li>
3408
3409<li><b><code>LUA_GCRESTART</code>: </b>
3410restarts the garbage collector.
3411</li>
3412
3413<li><b><code>LUA_GCCOLLECT</code>: </b>
3414performs a full garbage-collection cycle.
3415</li>
3416
3417<li><b><code>LUA_GCCOUNT</code>: </b>
3418returns the current amount of memory (in Kbytes) in use by Lua.
3419</li>
3420
3421<li><b><code>LUA_GCCOUNTB</code>: </b>
3422returns the remainder of dividing the current amount of bytes of
3423memory in use by Lua by 1024.
3424</li>
3425
3426<li><b><code>LUA_GCSTEP</code>: </b>
3427performs an incremental step of garbage collection.
3428</li>
3429
3430<li><b><code>LUA_GCSETPAUSE</code>: </b>
3431sets <code>data</code> as the new value
3432for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>)
3433and returns the previous value of the pause.
3434</li>
3435
3436<li><b><code>LUA_GCSETSTEPMUL</code>: </b>
3437sets <code>data</code> as the new value for the <em>step multiplier</em> of
3438the collector (see <a href="#2.5">&sect;2.5</a>)
3439and returns the previous value of the step multiplier.
3440</li>
3441
3442<li><b><code>LUA_GCISRUNNING</code>: </b>
3443returns a boolean that tells whether the collector is running
3444(i.e., not stopped).
3445</li>
3446
3447</ul>
3448
3449<p>
3450For more details about these options,
3451see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3452
3453
3454
3455
3456
3457<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3458<span class="apii">[-0, +0, &ndash;]</span>
3459<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3460
3461<p>
3462Returns the memory-allocation function of a given state.
3463If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3464opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
3465
3466
3467
3468
3469
3470<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3471<span class="apii">[-0, +1, <em>e</em>]</span>
3472<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
3473
3474<p>
3475Pushes onto the stack the value <code>t[k]</code>,
3476where <code>t</code> is the value at the given index.
3477As in Lua, this function may trigger a metamethod
3478for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3479
3480
3481<p>
3482Returns the type of the pushed value.
3483
3484
3485
3486
3487
3488<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3489<span class="apii">[-0, +1, <em>e</em>]</span>
3490<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
3491
3492<p>
3493Pushes onto the stack the value of the global <code>name</code>.
3494Returns the type of that value.
3495
3496
3497
3498
3499
3500<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
3501<span class="apii">[-0, +(0|1), &ndash;]</span>
3502<pre>int lua_getmetatable (lua_State *L, int index);</pre>
3503
3504<p>
3505Pushes onto the stack the metatable of the value at the given index.
3506If the value does not have a metatable,
3507the function returns&nbsp;0 and pushes nothing on the stack.
3508
3509
3510
3511
3512
3513<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
3514<span class="apii">[-1, +1, <em>e</em>]</span>
3515<pre>int lua_gettable (lua_State *L, int index);</pre>
3516
3517<p>
3518Pushes onto the stack the value <code>t[k]</code>,
3519where <code>t</code> is the value at the given index
3520and <code>k</code> is the value at the top of the stack.
3521
3522
3523<p>
3524This function pops the key from the stack
3525(putting the resulting value in its place).
3526As in Lua, this function may trigger a metamethod
3527for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3528
3529
3530<p>
3531Returns the type of the pushed value.
3532
3533
3534
3535
3536
3537<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
3538<span class="apii">[-0, +0, &ndash;]</span>
3539<pre>int lua_gettop (lua_State *L);</pre>
3540
3541<p>
3542Returns the index of the top element in the stack.
3543Because indices start at&nbsp;1,
3544this result is equal to the number of elements in the stack
3545(and so 0&nbsp;means an empty stack).
3546
3547
3548
3549
3550
3551<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
3552<span class="apii">[-0, +1, &ndash;]</span>
3553<pre>int lua_getuservalue (lua_State *L, int index);</pre>
3554
3555<p>
3556Pushes onto the stack the Lua value associated with the userdata
3557at the given index.
3558
3559
3560<p>
3561Returns the type of the pushed value.
3562
3563
3564
3565
3566
3567<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
3568<span class="apii">[-1, +1, &ndash;]</span>
3569<pre>void lua_insert (lua_State *L, int index);</pre>
3570
3571<p>
3572Moves the top element into the given valid index,
3573shifting up the elements above this index to open space.
3574This function cannot be called with a pseudo-index,
3575because a pseudo-index is not an actual stack position.
3576
3577
3578
3579
3580
3581<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3582<pre>typedef ... lua_Integer;</pre>
3583
3584<p>
3585The type of integers in Lua.
3586
3587
3588<p>
3589By default this type is <code>long long</code>
3590(usually a 64-bit two-complement integer),
3591but that can be changed in <code>luaconf.h</code>
3592to <code>long</code> or <code>int</code>
3593(usually a 32-bit two-complement integer).
3594
3595
3596<p>
3597Lua also defines the constants
3598<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
3599with the minimum and the maximum values that fit in this type.
3600
3601
3602
3603
3604
3605<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3606<span class="apii">[-0, +0, &ndash;]</span>
3607<pre>int lua_isboolean (lua_State *L, int index);</pre>
3608
3609<p>
3610Returns 1 if the value at the given index is a boolean,
3611and 0&nbsp;otherwise.
3612
3613
3614
3615
3616
3617<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3618<span class="apii">[-0, +0, &ndash;]</span>
3619<pre>int lua_iscfunction (lua_State *L, int index);</pre>
3620
3621<p>
3622Returns 1 if the value at the given index is a C&nbsp;function,
3623and 0&nbsp;otherwise.
3624
3625
3626
3627
3628
3629<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3630<span class="apii">[-0, +0, &ndash;]</span>
3631<pre>int lua_isfunction (lua_State *L, int index);</pre>
3632
3633<p>
3634Returns 1 if the value at the given index is a function
3635(either C or Lua), and 0&nbsp;otherwise.
3636
3637
3638
3639
3640
3641<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
3642<span class="apii">[-0, +0, &ndash;]</span>
3643<pre>int lua_isinteger (lua_State *L, int index);</pre>
3644
3645<p>
3646Returns 1 if the value at the given index is an integer
3647(that is, the value is a number and is represented as an integer),
3648and 0&nbsp;otherwise.
3649
3650
3651
3652
3653
3654<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3655<span class="apii">[-0, +0, &ndash;]</span>
3656<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3657
3658<p>
3659Returns 1 if the value at the given index is a light userdata,
3660and 0&nbsp;otherwise.
3661
3662
3663
3664
3665
3666<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3667<span class="apii">[-0, +0, &ndash;]</span>
3668<pre>int lua_isnil (lua_State *L, int index);</pre>
3669
3670<p>
3671Returns 1 if the value at the given index is <b>nil</b>,
3672and 0&nbsp;otherwise.
3673
3674
3675
3676
3677
3678<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3679<span class="apii">[-0, +0, &ndash;]</span>
3680<pre>int lua_isnone (lua_State *L, int index);</pre>
3681
3682<p>
3683Returns 1 if the given index is not valid,
3684and 0&nbsp;otherwise.
3685
3686
3687
3688
3689
3690<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3691<span class="apii">[-0, +0, &ndash;]</span>
3692<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3693
3694<p>
3695Returns 1 if the given index is not valid
3696or if the value at this index is <b>nil</b>,
3697and 0&nbsp;otherwise.
3698
3699
3700
3701
3702
3703<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3704<span class="apii">[-0, +0, &ndash;]</span>
3705<pre>int lua_isnumber (lua_State *L, int index);</pre>
3706
3707<p>
3708Returns 1 if the value at the given index is a number
3709or a string convertible to a number,
3710and 0&nbsp;otherwise.
3711
3712
3713
3714
3715
3716<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3717<span class="apii">[-0, +0, &ndash;]</span>
3718<pre>int lua_isstring (lua_State *L, int index);</pre>
3719
3720<p>
3721Returns 1 if the value at the given index is a string
3722or a number (which is always convertible to a string),
3723and 0&nbsp;otherwise.
3724
3725
3726
3727
3728
3729<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3730<span class="apii">[-0, +0, &ndash;]</span>
3731<pre>int lua_istable (lua_State *L, int index);</pre>
3732
3733<p>
3734Returns 1 if the value at the given index is a table,
3735and 0&nbsp;otherwise.
3736
3737
3738
3739
3740
3741<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3742<span class="apii">[-0, +0, &ndash;]</span>
3743<pre>int lua_isthread (lua_State *L, int index);</pre>
3744
3745<p>
3746Returns 1 if the value at the given index is a thread,
3747and 0&nbsp;otherwise.
3748
3749
3750
3751
3752
3753<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3754<span class="apii">[-0, +0, &ndash;]</span>
3755<pre>int lua_isuserdata (lua_State *L, int index);</pre>
3756
3757<p>
3758Returns 1 if the value at the given index is a userdata
3759(either full or light), and 0&nbsp;otherwise.
3760
3761
3762
3763
3764
3765<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
3766<span class="apii">[-0, +0, &ndash;]</span>
3767<pre>int lua_isyieldable (lua_State *L);</pre>
3768
3769<p>
3770Returns 1 if the given coroutine can yield,
3771and 0&nbsp;otherwise.
3772
3773
3774
3775
3776
3777<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
3778<pre>typedef int (*lua_KFunction) (lua_State *L, int status, int ctx);</pre>
3779
3780<p>
3781Type for continuation functions (see <a href="#4.7">&sect;4.7</a>).
3782
3783
3784
3785
3786
3787<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
3788<span class="apii">[-0, +1, <em>e</em>]</span>
3789<pre>void lua_len (lua_State *L, int index);</pre>
3790
3791<p>
3792Returns the "length" of the value at the given index;
3793it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
3794The result is pushed on the stack.
3795
3796
3797
3798
3799
3800<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3801<span class="apii">[-0, +1, &ndash;]</span>
3802<pre>int lua_load (lua_State *L,
3803              lua_Reader reader,
3804              void *data,
3805              const char *source,
3806              const char *mode);</pre>
3807
3808<p>
3809Loads a Lua chunk (without running it).
3810If there are no errors,
3811<code>lua_load</code> pushes the compiled chunk as a Lua
3812function on top of the stack.
3813Otherwise, it pushes an error message.
3814
3815
3816<p>
3817The return values of <code>lua_load</code> are:
3818
3819<ul>
3820
3821<li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li>
3822
3823<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b>
3824syntax error during precompilation;</li>
3825
3826<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3827memory allocation error;</li>
3828
3829<li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
3830error while running a <code>__gc</code> metamethod.
3831(This error has no relation with the chunk being loaded.
3832It is generated by the garbage collector.)
3833</li>
3834
3835</ul>
3836
3837<p>
3838The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
3839to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3840The <code>data</code> argument is an opaque value passed to the reader function.
3841
3842
3843<p>
3844The <code>source</code> argument gives a name to the chunk,
3845which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>).
3846
3847
3848<p>
3849<code>lua_load</code> automatically detects whether the chunk is text or binary
3850and loads it accordingly (see program <code>luac</code>).
3851The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
3852with the addition that
3853a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
3854
3855
3856<p>
3857<code>lua_load</code> uses the stack internally,
3858so the reader function must always leave the stack
3859unmodified when returning.
3860
3861
3862<p>
3863If the resulting function has one upvalue,
3864this upvalue is set to the value of the global environment
3865stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>).
3866When loading main chunks,
3867this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
3868
3869
3870
3871
3872
3873<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3874<span class="apii">[-0, +0, &ndash;]</span>
3875<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3876
3877<p>
3878Creates a new thread running in a new, independent state.
3879Returns <code>NULL</code> if it cannot create the thread or the state
3880(due to lack of memory).
3881The argument <code>f</code> is the allocator function;
3882Lua does all memory allocation for this state through this function.
3883The second argument, <code>ud</code>, is an opaque pointer that Lua
3884passes to the allocator in every call.
3885
3886
3887
3888
3889
3890<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
3891<span class="apii">[-0, +1, <em>e</em>]</span>
3892<pre>void lua_newtable (lua_State *L);</pre>
3893
3894<p>
3895Creates a new empty table and pushes it onto the stack.
3896It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3897
3898
3899
3900
3901
3902<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
3903<span class="apii">[-0, +1, <em>e</em>]</span>
3904<pre>lua_State *lua_newthread (lua_State *L);</pre>
3905
3906<p>
3907Creates a new thread, pushes it on the stack,
3908and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3909The new thread returned by this function shares with the original thread
3910its global environment,
3911but has an independent execution stack.
3912
3913
3914<p>
3915There is no explicit function to close or to destroy a thread.
3916Threads are subject to garbage collection,
3917like any Lua object.
3918
3919
3920
3921
3922
3923<hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
3924<span class="apii">[-0, +1, <em>e</em>]</span>
3925<pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3926
3927<p>
3928This function allocates a new block of memory with the given size,
3929pushes onto the stack a new full userdata with the block address,
3930and returns this address.
3931The host program can freely use this memory.
3932
3933
3934
3935
3936
3937<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
3938<span class="apii">[-1, +(2|0), <em>e</em>]</span>
3939<pre>int lua_next (lua_State *L, int index);</pre>
3940
3941<p>
3942Pops a key from the stack,
3943and pushes a key&ndash;value pair from the table at the given index
3944(the "next" pair after the given key).
3945If there are no more elements in the table,
3946then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3947
3948
3949<p>
3950A typical traversal looks like this:
3951
3952<pre>
3953     /* table is in the stack at index 't' */
3954     lua_pushnil(L);  /* first key */
3955     while (lua_next(L, t) != 0) {
3956       /* uses 'key' (at index -2) and 'value' (at index -1) */
3957       printf("%s - %s\n",
3958              lua_typename(L, lua_type(L, -2)),
3959              lua_typename(L, lua_type(L, -1)));
3960       /* removes 'value'; keeps 'key' for next iteration */
3961       lua_pop(L, 1);
3962     }
3963</pre>
3964
3965<p>
3966While traversing a table,
3967do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3968unless you know that the key is actually a string.
3969Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
3970the value at the given index;
3971this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3972
3973
3974<p>
3975See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
3976the table during its traversal.
3977
3978
3979
3980
3981
3982<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3983<pre>typedef double lua_Number;</pre>
3984
3985<p>
3986The type of floats in Lua.
3987
3988
3989<p>
3990By default this type is double,
3991but that can be changed in <code>luaconf.h</code> to a single float.
3992
3993
3994
3995
3996
3997<hr><h3><a name="lua_numtointeger"><code>lua_numtointeger</code></a></h3>
3998<pre>int lua_numtointeger (lua_Number n, lua_Integer *p);</pre>
3999
4000<p>
4001Converts a Lua float to a Lua integer.
4002This macro assumes that <code>n</code> has an integral value.
4003If that value is within the range of Lua integers,
4004it is converted to an integer and assigned to <code>*p</code>.
4005The macro results in a boolean indicating whether the
4006conversion was successful.
4007(Note that this range test can be tricky to do
4008correctly without this macro,
4009due to roundings.)
4010
4011
4012<p>
4013This macro may evaluate its arguments more than once.
4014
4015
4016
4017
4018
4019<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
4020<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4021<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
4022
4023<p>
4024Calls a function in protected mode.
4025
4026
4027<p>
4028Both <code>nargs</code> and <code>nresults</code> have the same meaning as
4029in <a href="#lua_call"><code>lua_call</code></a>.
4030If there are no errors during the call,
4031<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
4032However, if there is any error,
4033<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
4034pushes a single value on the stack (the error message),
4035and returns an error code.
4036Like <a href="#lua_call"><code>lua_call</code></a>,
4037<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
4038and its arguments from the stack.
4039
4040
4041<p>
4042If <code>msgh</code> is 0,
4043then the error message returned on the stack
4044is exactly the original error message.
4045Otherwise, <code>msgh</code> is the stack index of a
4046<em>message handler</em>.
4047(In the current implementation, this index cannot be a pseudo-index.)
4048In case of runtime errors,
4049this function will be called with the error message
4050and its return value will be the message
4051returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
4052
4053
4054<p>
4055Typically, the message handler is used to add more debug
4056information to the error message, such as a stack traceback.
4057Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
4058since by then the stack has unwound.
4059
4060
4061<p>
4062The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants
4063(defined in <code>lua.h</code>):
4064
4065<ul>
4066
4067<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b>
4068success.</li>
4069
4070<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b>
4071a runtime error.
4072</li>
4073
4074<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
4075memory allocation error.
4076For such errors, Lua does not call the message handler.
4077</li>
4078
4079<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b>
4080error while running the message handler.
4081</li>
4082
4083<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
4084error while running a <code>__gc</code> metamethod.
4085(This error typically has no relation with the function being called.)
4086</li>
4087
4088</ul>
4089
4090
4091
4092
4093<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
4094<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
4095<pre>int lua_pcallk (lua_State *L,
4096                int nargs,
4097                int nresults,
4098                int errfunc,
4099                int ctx,
4100                lua_KFunction k);</pre>
4101
4102<p>
4103This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
4104but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
4105
4106
4107
4108
4109
4110<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
4111<span class="apii">[-n, +0, &ndash;]</span>
4112<pre>void lua_pop (lua_State *L, int n);</pre>
4113
4114<p>
4115Pops <code>n</code> elements from the stack.
4116
4117
4118
4119
4120
4121<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
4122<span class="apii">[-0, +1, &ndash;]</span>
4123<pre>void lua_pushboolean (lua_State *L, int b);</pre>
4124
4125<p>
4126Pushes a boolean value with value <code>b</code> onto the stack.
4127
4128
4129
4130
4131
4132<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
4133<span class="apii">[-n, +1, <em>e</em>]</span>
4134<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
4135
4136<p>
4137Pushes a new C&nbsp;closure onto the stack.
4138
4139
4140<p>
4141When a C&nbsp;function is created,
4142it is possible to associate some values with it,
4143thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>);
4144these values are then accessible to the function whenever it is called.
4145To associate values with a C&nbsp;function,
4146first these values must be pushed onto the stack
4147(when there are multiple values, the first value is pushed first).
4148Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4149is called to create and push the C&nbsp;function onto the stack,
4150with the argument <code>n</code> telling how many values will be
4151associated with the function.
4152<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4153
4154
4155<p>
4156The maximum value for <code>n</code> is 255.
4157
4158
4159<p>
4160When <code>n</code> is zero,
4161this function creates a <em>light C function</em>,
4162which is just a pointer to the C&nbsp;function.
4163In that case, it never raises a memory error.
4164
4165
4166
4167
4168
4169<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4170<span class="apii">[-0, +1, &ndash;]</span>
4171<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4172
4173<p>
4174Pushes a C&nbsp;function onto the stack.
4175This function receives a pointer to a C function
4176and pushes onto the stack a Lua value of type <code>function</code> that,
4177when called, invokes the corresponding C&nbsp;function.
4178
4179
4180<p>
4181Any function to be registered in Lua must
4182follow the correct protocol to receive its parameters
4183and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4184
4185
4186<p>
4187<code>lua_pushcfunction</code> is defined as a macro:
4188
4189<pre>
4190     #define lua_pushcfunction(L,f)  lua_pushcclosure(L,f,0)
4191</pre><p>
4192Note that <code>f</code> is used twice.
4193
4194
4195
4196
4197
4198<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4199<span class="apii">[-0, +1, <em>e</em>]</span>
4200<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4201
4202<p>
4203Pushes onto the stack a formatted string
4204and returns a pointer to this string.
4205It is similar to the ANSI&nbsp;C function <code>sprintf</code>,
4206but has some important differences:
4207
4208<ul>
4209
4210<li>
4211You do not have to allocate space for the result:
4212the result is a Lua string and Lua takes care of memory allocation
4213(and deallocation, through garbage collection).
4214</li>
4215
4216<li>
4217The conversion specifiers are quite restricted.
4218There are no flags, widths, or precisions.
4219The conversion specifiers can only be
4220'<code>%%</code>' (inserts the character '<code>%</code>'),
4221'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4222'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4223'<code>%L</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
4224'<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
4225'<code>%d</code>' (inserts an <code>int</code>),
4226'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4227'<code>%U</code>' (inserts an <code>int</code> as a UTF-8 byte sequence).
4228</li>
4229
4230</ul>
4231
4232
4233
4234
4235<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4236<span class="apii">[-0, +1, &ndash;]</span>
4237<pre>void lua_pushglobaltable (lua_State *L);</pre>
4238
4239<p>
4240Pushes the global environment onto the stack.
4241
4242
4243
4244
4245
4246<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4247<span class="apii">[-0, +1, &ndash;]</span>
4248<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4249
4250<p>
4251Pushes an integer with value <code>n</code> onto the stack.
4252
4253
4254
4255
4256
4257<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4258<span class="apii">[-0, +1, &ndash;]</span>
4259<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4260
4261<p>
4262Pushes a light userdata onto the stack.
4263
4264
4265<p>
4266Userdata represent C&nbsp;values in Lua.
4267A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4268It is a value (like a number):
4269you do not create it, it has no individual metatable,
4270and it is not collected (as it was never created).
4271A light userdata is equal to "any"
4272light userdata with the same C&nbsp;address.
4273
4274
4275
4276
4277
4278<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4279<span class="apii">[-0, +1, <em>e</em>]</span>
4280<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4281
4282<p>
4283This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
4284but can be used only when <code>s</code> is a literal string.
4285It automatically provides the string length.
4286
4287
4288
4289
4290
4291<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4292<span class="apii">[-0, +1, <em>e</em>]</span>
4293<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4294
4295<p>
4296Pushes the string pointed to by <code>s</code> with size <code>len</code>
4297onto the stack.
4298Lua makes (or reuses) an internal copy of the given string,
4299so the memory at <code>s</code> can be freed or reused immediately after
4300the function returns.
4301The string can contain any binary data,
4302including embedded zeros.
4303
4304
4305<p>
4306Returns a pointer to the internal copy of the string.
4307
4308
4309
4310
4311
4312<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4313<span class="apii">[-0, +1, &ndash;]</span>
4314<pre>void lua_pushnil (lua_State *L);</pre>
4315
4316<p>
4317Pushes a nil value onto the stack.
4318
4319
4320
4321
4322
4323<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4324<span class="apii">[-0, +1, &ndash;]</span>
4325<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4326
4327<p>
4328Pushes a float with value <code>n</code> onto the stack.
4329
4330
4331
4332
4333
4334<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4335<span class="apii">[-0, +1, <em>e</em>]</span>
4336<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4337
4338<p>
4339Pushes the zero-terminated string pointed to by <code>s</code>
4340onto the stack.
4341Lua makes (or reuses) an internal copy of the given string,
4342so the memory at <code>s</code> can be freed or reused immediately after
4343the function returns.
4344
4345
4346<p>
4347Returns a pointer to the internal copy of the string.
4348
4349
4350<p>
4351If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4352
4353
4354
4355
4356
4357<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4358<span class="apii">[-0, +1, &ndash;]</span>
4359<pre>int lua_pushthread (lua_State *L);</pre>
4360
4361<p>
4362Pushes the thread represented by <code>L</code> onto the stack.
4363Returns 1 if this thread is the main thread of its state.
4364
4365
4366
4367
4368
4369<hr><h3><a name="lua_pushunsigned"><code>lua_pushunsigned</code></a></h3><p>
4370<span class="apii">[-0, +1, &ndash;]</span>
4371<pre>void lua_pushunsigned (lua_State *L, lua_Unsigned n);</pre>
4372
4373<p>
4374Pushes an integer with value <code>n</code> onto the stack.
4375
4376
4377
4378
4379
4380<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4381<span class="apii">[-0, +1, &ndash;]</span>
4382<pre>void lua_pushvalue (lua_State *L, int index);</pre>
4383
4384<p>
4385Pushes a copy of the element at the given index
4386onto the stack.
4387
4388
4389
4390
4391
4392<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4393<span class="apii">[-0, +1, <em>e</em>]</span>
4394<pre>const char *lua_pushvfstring (lua_State *L,
4395                              const char *fmt,
4396                              va_list argp);</pre>
4397
4398<p>
4399Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4400instead of a variable number of arguments.
4401
4402
4403
4404
4405
4406<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4407<span class="apii">[-0, +0, &ndash;]</span>
4408<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4409
4410<p>
4411Returns 1 if the two values in indices <code>index1</code> and
4412<code>index2</code> are primitively equal
4413(that is, without calling metamethods).
4414Otherwise returns&nbsp;0.
4415Also returns&nbsp;0 if any of the indices are non valid.
4416
4417
4418
4419
4420
4421<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4422<span class="apii">[-1, +1, &ndash;]</span>
4423<pre>int lua_rawget (lua_State *L, int index);</pre>
4424
4425<p>
4426Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4427(i.e., without metamethods).
4428
4429
4430
4431
4432
4433<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4434<span class="apii">[-0, +1, &ndash;]</span>
4435<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4436
4437<p>
4438Pushes onto the stack the value <code>t[n]</code>,
4439where <code>t</code> is the table at the given index.
4440The access is raw;
4441that is, it does not invoke metamethods.
4442
4443
4444<p>
4445Returns the type of the pushed value.
4446
4447
4448
4449
4450
4451<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4452<span class="apii">[-0, +1, &ndash;]</span>
4453<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4454
4455<p>
4456Pushes onto the stack the value <code>t[k]</code>,
4457where <code>t</code> is the table at the given index and
4458<code>k</code> is the pointer <code>p</code> represented as a light userdata.
4459The access is raw;
4460that is, it does not invoke metamethods.
4461
4462
4463<p>
4464Returns the type of the pushed value.
4465
4466
4467
4468
4469
4470<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
4471<span class="apii">[-0, +0, &ndash;]</span>
4472<pre>size_t lua_rawlen (lua_State *L, int index);</pre>
4473
4474<p>
4475Returns the raw "length" of the value at the given index:
4476for strings, this is the string length;
4477for tables, this is the result of the length operator ('<code>#</code>')
4478with no metamethods;
4479for userdata, this is the size of the block of memory allocated
4480for the userdata;
4481for other values, it is&nbsp;0.
4482
4483
4484
4485
4486
4487<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
4488<span class="apii">[-2, +0, <em>e</em>]</span>
4489<pre>void lua_rawset (lua_State *L, int index);</pre>
4490
4491<p>
4492Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
4493(i.e., without metamethods).
4494
4495
4496
4497
4498
4499<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
4500<span class="apii">[-1, +0, <em>e</em>]</span>
4501<pre>void lua_rawseti (lua_State *L, int index, lua_Integer n);</pre>
4502
4503<p>
4504Does the equivalent of <code>t[n] = v</code>,
4505where <code>t</code> is the table at the given index
4506and <code>v</code> is the value at the top of the stack.
4507
4508
4509<p>
4510This function pops the value from the stack.
4511The assignment is raw;
4512that is, it does not invoke metamethods.
4513
4514
4515
4516
4517
4518<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
4519<span class="apii">[-1, +0, <em>e</em>]</span>
4520<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
4521
4522<p>
4523Does the equivalent of <code>t[k] = v</code>,
4524where <code>t</code> is the table at the given index,
4525<code>k</code> is the pointer <code>p</code> represented as a light userdata,
4526and <code>v</code> is the value at the top of the stack.
4527
4528
4529<p>
4530This function pops the value from the stack.
4531The assignment is raw;
4532that is, it does not invoke metamethods.
4533
4534
4535
4536
4537
4538<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
4539<pre>typedef const char * (*lua_Reader) (lua_State *L,
4540                                    void *data,
4541                                    size_t *size);</pre>
4542
4543<p>
4544The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
4545Every time it needs another piece of the chunk,
4546<a href="#lua_load"><code>lua_load</code></a> calls the reader,
4547passing along its <code>data</code> parameter.
4548The reader must return a pointer to a block of memory
4549with a new piece of the chunk
4550and set <code>size</code> to the block size.
4551The block must exist until the reader function is called again.
4552To signal the end of the chunk,
4553the reader must return <code>NULL</code> or set <code>size</code> to zero.
4554The reader function may return pieces of any size greater than zero.
4555
4556
4557
4558
4559
4560<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
4561<span class="apii">[-0, +0, <em>e</em>]</span>
4562<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
4563
4564<p>
4565Sets the C function <code>f</code> as the new value of global <code>name</code>.
4566It is defined as a macro:
4567
4568<pre>
4569     #define lua_register(L,n,f) \
4570            (lua_pushcfunction(L, f), lua_setglobal(L, n))
4571</pre>
4572
4573
4574
4575
4576<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
4577<span class="apii">[-1, +0, &ndash;]</span>
4578<pre>void lua_remove (lua_State *L, int index);</pre>
4579
4580<p>
4581Removes the element at the given valid index,
4582shifting down the elements above this index to fill the gap.
4583This function cannot be called with a pseudo-index,
4584because a pseudo-index is not an actual stack position.
4585
4586
4587
4588
4589
4590<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
4591<span class="apii">[-1, +0, &ndash;]</span>
4592<pre>void lua_replace (lua_State *L, int index);</pre>
4593
4594<p>
4595Moves the top element into the given valid index
4596without shifting any element
4597(therefore replacing the value at the given index),
4598and then pops the top element.
4599
4600
4601
4602
4603
4604<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
4605<span class="apii">[-?, +?, &ndash;]</span>
4606<pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre>
4607
4608<p>
4609Starts and resumes a coroutine in a given thread.
4610
4611
4612<p>
4613To start a coroutine,
4614you push onto the thread stack the main function plus any arguments;
4615then you call <a href="#lua_resume"><code>lua_resume</code></a>,
4616with <code>nargs</code> being the number of arguments.
4617This call returns when the coroutine suspends or finishes its execution.
4618When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
4619or all values returned by the body function.
4620<a href="#lua_resume"><code>lua_resume</code></a> returns
4621<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
4622<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
4623without errors,
4624or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
4625
4626
4627<p>
4628In case of errors,
4629the stack is not unwound,
4630so you can use the debug API over it.
4631The error message is on the top of the stack.
4632
4633
4634<p>
4635To resume a coroutine,
4636you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>,
4637put on its stack only the values to
4638be passed as results from <code>yield</code>,
4639and then call <a href="#lua_resume"><code>lua_resume</code></a>.
4640
4641
4642<p>
4643The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
4644If there is no such coroutine,
4645this parameter can be <code>NULL</code>.
4646
4647
4648
4649
4650
4651<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
4652<span class="apii">[-0, +0, &ndash;]</span>
4653<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
4654
4655<p>
4656Rotates the stack elements from <code>idx</code> to the top <code>n</code> positions
4657in the direction of the top, for a positive <code>n</code>,
4658or <code>-n</code> positions in the direction of the bottom,
4659for a negative <code>n</code>.
4660The absolute value of <code>n</code> must not be greater than the size
4661of the slice being rotated.
4662
4663
4664
4665
4666
4667<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
4668<span class="apii">[-0, +0, &ndash;]</span>
4669<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
4670
4671<p>
4672Changes the allocator function of a given state to <code>f</code>
4673with user data <code>ud</code>.
4674
4675
4676
4677
4678
4679<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
4680<span class="apii">[-1, +0, <em>e</em>]</span>
4681<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
4682
4683<p>
4684Does the equivalent to <code>t[k] = v</code>,
4685where <code>t</code> is the value at the given index
4686and <code>v</code> is the value at the top of the stack.
4687
4688
4689<p>
4690This function pops the value from the stack.
4691As in Lua, this function may trigger a metamethod
4692for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4693
4694
4695
4696
4697
4698<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
4699<span class="apii">[-1, +0, <em>e</em>]</span>
4700<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
4701
4702<p>
4703Pops a value from the stack and
4704sets it as the new value of global <code>name</code>.
4705
4706
4707
4708
4709
4710<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
4711<span class="apii">[-1, +0, &ndash;]</span>
4712<pre>void lua_setmetatable (lua_State *L, int index);</pre>
4713
4714<p>
4715Pops a table from the stack and
4716sets it as the new metatable for the value at the given index.
4717
4718
4719
4720
4721
4722<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
4723<span class="apii">[-2, +0, <em>e</em>]</span>
4724<pre>void lua_settable (lua_State *L, int index);</pre>
4725
4726<p>
4727Does the equivalent to <code>t[k] = v</code>,
4728where <code>t</code> is the value at the given index,
4729<code>v</code> is the value at the top of the stack,
4730and <code>k</code> is the value just below the top.
4731
4732
4733<p>
4734This function pops both the key and the value from the stack.
4735As in Lua, this function may trigger a metamethod
4736for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4737
4738
4739
4740
4741
4742<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
4743<span class="apii">[-?, +?, &ndash;]</span>
4744<pre>void lua_settop (lua_State *L, int index);</pre>
4745
4746<p>
4747Accepts any index, or&nbsp;0,
4748and sets the stack top to this index.
4749If the new top is larger than the old one,
4750then the new elements are filled with <b>nil</b>.
4751If <code>index</code> is&nbsp;0, then all stack elements are removed.
4752
4753
4754
4755
4756
4757<hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p>
4758<span class="apii">[-1, +0, &ndash;]</span>
4759<pre>void lua_setuservalue (lua_State *L, int index);</pre>
4760
4761<p>
4762Pops a value from the stack and sets it as
4763the new value associated to the userdata at the given index.
4764
4765
4766
4767
4768
4769<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
4770<pre>typedef struct lua_State lua_State;</pre>
4771
4772<p>
4773An opaque structure that points to a thread and indirectly
4774(through the thread) to the whole state of a Lua interpreter.
4775The Lua library is fully reentrant:
4776it has no global variables.
4777All information about a state is accessible through this structure.
4778
4779
4780<p>
4781A pointer to this structure must be passed as the first argument to
4782every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4783which creates a Lua state from scratch.
4784
4785
4786
4787
4788
4789<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4790<span class="apii">[-0, +0, &ndash;]</span>
4791<pre>int lua_status (lua_State *L);</pre>
4792
4793<p>
4794Returns the status of the thread <code>L</code>.
4795
4796
4797<p>
4798The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread,
4799an error code if the thread finished the execution
4800of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
4801or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4802
4803
4804<p>
4805You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
4806You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
4807(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
4808(to resume a coroutine).
4809
4810
4811
4812
4813
4814<hr><h3><a name="lua_strtonum"><code>lua_strtonum</code></a></h3><p>
4815<span class="apii">[-0, +1, &ndash;]</span>
4816<pre>size_t lua_strtonum (lua_State *L, const char *s);</pre>
4817
4818<p>
4819Converts the zero-terminated string <code>s</code> to a number,
4820pushes that number into the stack,
4821and returns the total size of the string
4822(that is, its length plus one).
4823The conversion can result in an integer or a float,
4824according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
4825The string may have leading and trailing spaces and a sign.
4826If the string is not a valid numeral,
4827returns 0 and pushes nothing.
4828
4829
4830
4831
4832
4833<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4834<span class="apii">[-0, +0, &ndash;]</span>
4835<pre>int lua_toboolean (lua_State *L, int index);</pre>
4836
4837<p>
4838Converts the Lua value at the given index to a C&nbsp;boolean
4839value (0&nbsp;or&nbsp;1).
4840Like all tests in Lua,
4841<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
4842different from <b>false</b> and <b>nil</b>;
4843otherwise it returns false.
4844(If you want to accept only actual boolean values,
4845use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4846
4847
4848
4849
4850
4851<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4852<span class="apii">[-0, +0, &ndash;]</span>
4853<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4854
4855<p>
4856Converts a value at the given index to a C&nbsp;function.
4857That value must be a C&nbsp;function;
4858otherwise, returns <code>NULL</code>.
4859
4860
4861
4862
4863
4864<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4865<span class="apii">[-0, +0, &ndash;]</span>
4866<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4867
4868<p>
4869Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4870
4871
4872
4873
4874
4875<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
4876<span class="apii">[-0, +0, &ndash;]</span>
4877<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
4878
4879<p>
4880Converts the Lua value at the given index
4881to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4882The Lua value must be an integer,
4883or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
4884otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
4885
4886
4887<p>
4888If <code>isnum</code> is not <code>NULL</code>,
4889its referent is assigned a boolean value that
4890indicates whether the operation succeeded.
4891
4892
4893
4894
4895
4896<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
4897<span class="apii">[-0, +0, <em>e</em>]</span>
4898<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
4899
4900<p>
4901Converts the Lua value at the given index to a C&nbsp;string.
4902If <code>len</code> is not <code>NULL</code>,
4903it also sets <code>*len</code> with the string length.
4904The Lua value must be a string or a number;
4905otherwise, the function returns <code>NULL</code>.
4906If the value is a number,
4907then <code>lua_tolstring</code> also
4908<em>changes the actual value in the stack to a string</em>.
4909(This change confuses <a href="#lua_next"><code>lua_next</code></a>
4910when <code>lua_tolstring</code> is applied to keys during a table traversal.)
4911
4912
4913<p>
4914<code>lua_tolstring</code> returns a fully aligned pointer
4915to a string inside the Lua state.
4916This string always has a zero ('<code>\0</code>')
4917after its last character (as in&nbsp;C),
4918but can contain other zeros in its body.
4919Because Lua has garbage collection,
4920there is no guarantee that the pointer returned by <code>lua_tolstring</code>
4921will be valid after the corresponding value is removed from the stack.
4922
4923
4924
4925
4926
4927<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
4928<span class="apii">[-0, +0, &ndash;]</span>
4929<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
4930
4931<p>
4932Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4933
4934
4935
4936
4937
4938<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
4939<span class="apii">[-0, +0, &ndash;]</span>
4940<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
4941
4942<p>
4943Converts the Lua value at the given index
4944to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
4945The Lua value must be a number or a string convertible to a number
4946(see <a href="#3.4.3">&sect;3.4.3</a>);
4947otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
4948
4949
4950<p>
4951If <code>isnum</code> is not <code>NULL</code>,
4952its referent is assigned a boolean value that
4953indicates whether the operation succeeded.
4954
4955
4956
4957
4958
4959<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
4960<span class="apii">[-0, +0, &ndash;]</span>
4961<pre>const void *lua_topointer (lua_State *L, int index);</pre>
4962
4963<p>
4964Converts the value at the given index to a generic
4965C&nbsp;pointer (<code>void*</code>).
4966The value can be a userdata, a table, a thread, or a function;
4967otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
4968Different objects will give different pointers.
4969There is no way to convert the pointer back to its original value.
4970
4971
4972<p>
4973Typically this function is used only for debug information.
4974
4975
4976
4977
4978
4979<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
4980<span class="apii">[-0, +0, <em>e</em>]</span>
4981<pre>const char *lua_tostring (lua_State *L, int index);</pre>
4982
4983<p>
4984Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4985
4986
4987
4988
4989
4990<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
4991<span class="apii">[-0, +0, &ndash;]</span>
4992<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4993
4994<p>
4995Converts the value at the given index to a Lua thread
4996(represented as <code>lua_State*</code>).
4997This value must be a thread;
4998otherwise, the function returns <code>NULL</code>.
4999
5000
5001
5002
5003
5004<hr><h3><a name="lua_tounsigned"><code>lua_tounsigned</code></a></h3><p>
5005<span class="apii">[-0, +0, &ndash;]</span>
5006<pre>lua_Unsigned lua_tounsigned (lua_State *L, int index);</pre>
5007
5008<p>
5009Equivalent to <a href="#lua_tounsignedx"><code>lua_tounsignedx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
5010
5011
5012
5013
5014
5015<hr><h3><a name="lua_tounsignedx"><code>lua_tounsignedx</code></a></h3><p>
5016<span class="apii">[-0, +0, &ndash;]</span>
5017<pre>lua_Unsigned lua_tounsignedx (lua_State *L, int index, int *isnum);</pre>
5018
5019<p>
5020Converts the Lua value at the given index
5021to the unsigned integral type <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
5022The Lua value must be an integer,
5023or a float,
5024or a string convertible to a number
5025(see <a href="#3.4.3">&sect;3.4.3</a>);
5026otherwise, <code>lua_tounsignedx</code> returns&nbsp;0.
5027
5028
5029<p>
5030If the number is not an integer,
5031it is rounded towards minus infinite (floor).
5032If the result is outside the range of representable values,
5033it is normalized to the module of its division by
5034one more than the maximum representable value.
5035
5036
5037<p>
5038If <code>isnum</code> is not <code>NULL</code>,
5039its referent is assigned a boolean value that
5040indicates whether the operation succeeded.
5041
5042
5043
5044
5045
5046<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
5047<span class="apii">[-0, +0, &ndash;]</span>
5048<pre>void *lua_touserdata (lua_State *L, int index);</pre>
5049
5050<p>
5051If the value at the given index is a full userdata,
5052returns its block address.
5053If the value is a light userdata,
5054returns its pointer.
5055Otherwise, returns <code>NULL</code>.
5056
5057
5058
5059
5060
5061<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
5062<span class="apii">[-0, +0, &ndash;]</span>
5063<pre>int lua_type (lua_State *L, int index);</pre>
5064
5065<p>
5066Returns the type of the value in the given valid index,
5067or <code>LUA_TNONE</code> for a non-valid (but acceptable) index.
5068The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
5069defined in <code>lua.h</code>:
5070<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
5071<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
5072<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
5073<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
5074<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
5075<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
5076<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
5077<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
5078and
5079<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
5080
5081
5082
5083
5084
5085<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
5086<span class="apii">[-0, +0, &ndash;]</span>
5087<pre>const char *lua_typename (lua_State *L, int tp);</pre>
5088
5089<p>
5090Returns the name of the type encoded by the value <code>tp</code>,
5091which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
5092
5093
5094
5095
5096
5097<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5098<pre>typedef ... lua_Unsigned;</pre>
5099
5100<p>
5101The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
5102
5103
5104<p>
5105Lua also defines the constant <a name="pdf-LUA_MAXUNSIGNED"><code>LUA_MAXUNSIGNED</code></a>,
5106with the maximum value that fits in this type.
5107
5108
5109
5110
5111
5112<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
5113<span class="apii">[-0, +0, &ndash;]</span>
5114<pre>int lua_upvalueindex (int i);</pre>
5115
5116<p>
5117Returns the pseudo-index that represents the <code>i</code>-th upvalue of
5118the running function (see <a href="#4.4">&sect;4.4</a>).
5119
5120
5121
5122
5123
5124<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
5125<span class="apii">[-0, +0, <em>v</em>]</span>
5126<pre>const lua_Number *lua_version (lua_State *L);</pre>
5127
5128<p>
5129Returns the address of the version number stored in the Lua core.
5130When called with a valid <a href="#lua_State"><code>lua_State</code></a>,
5131returns the address of the version used to create that state.
5132When called with <code>NULL</code>,
5133returns the address of the version running the call.
5134
5135
5136
5137
5138
5139<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
5140<pre>typedef int (*lua_Writer) (lua_State *L,
5141                           const void* p,
5142                           size_t sz,
5143                           void* ud);</pre>
5144
5145<p>
5146The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
5147Every time it produces another piece of chunk,
5148<a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
5149passing along the buffer to be written (<code>p</code>),
5150its size (<code>sz</code>),
5151and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
5152
5153
5154<p>
5155The writer returns an error code:
51560&nbsp;means no errors;
5157any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
5158calling the writer again.
5159
5160
5161
5162
5163
5164<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
5165<span class="apii">[-?, +?, &ndash;]</span>
5166<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
5167
5168<p>
5169Exchange values between different threads of the same state.
5170
5171
5172<p>
5173This function pops <code>n</code> values from the stack <code>from</code>,
5174and pushes them onto the stack <code>to</code>.
5175
5176
5177
5178
5179
5180<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5181<span class="apii">[-?, +?, &ndash;]</span>
5182<pre>int lua_yield (lua_State *L, int nresults);</pre>
5183
5184<p>
5185This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5186but it has no continuation (see <a href="#4.7">&sect;4.7</a>).
5187Therefore, when the thread resumes,
5188it returns to the function that called
5189the function calling <code>lua_yield</code>.
5190
5191
5192
5193
5194
5195<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5196<span class="apii">[-?, +?, &ndash;]</span>
5197<pre>int lua_yieldk (lua_State *L, int nresults, int ctx, lua_KFunction k);</pre>
5198
5199<p>
5200Yields a coroutine.
5201
5202
5203<p>
5204This function should only be called as the
5205return expression of a C&nbsp;function, as follows:
5206
5207<pre>
5208     return lua_yieldk (L, n, ctx, k);
5209</pre><p>
5210When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a> in that way,
5211the running coroutine suspends its execution,
5212and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5213The parameter <code>nresults</code> is the number of values from the stack
5214that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5215
5216
5217<p>
5218When the coroutine is resumed again,
5219Lua calls the given continuation function <code>k</code> to continue
5220the execution of the C function that yielded (see <a href="#4.7">&sect;4.7</a>).
5221This continuation function receives the same stack
5222from the previous function,
5223with the <code>n</code> results removed and
5224replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5225Moreover,
5226the continuation function receives the value <code>ctx</code>
5227that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5228
5229
5230
5231
5232
5233
5234
5235<h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2>
5236
5237<p>
5238Lua has no built-in debugging facilities.
5239Instead, it offers a special interface
5240by means of functions and <em>hooks</em>.
5241This interface allows the construction of different
5242kinds of debuggers, profilers, and other tools
5243that need "inside information" from the interpreter.
5244
5245
5246
5247<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5248<pre>typedef struct lua_Debug {
5249  int event;
5250  const char *name;           /* (n) */
5251  const char *namewhat;       /* (n) */
5252  const char *what;           /* (S) */
5253  const char *source;         /* (S) */
5254  int currentline;            /* (l) */
5255  int linedefined;            /* (S) */
5256  int lastlinedefined;        /* (S) */
5257  unsigned char nups;         /* (u) number of upvalues */
5258  unsigned char nparams;      /* (u) number of parameters */
5259  char isvararg;              /* (u) */
5260  char istailcall;            /* (t) */
5261  char short_src[LUA_IDSIZE]; /* (S) */
5262  /* private part */
5263  <em>other fields</em>
5264} lua_Debug;</pre>
5265
5266<p>
5267A structure used to carry different pieces of
5268information about a function or an activation record.
5269<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5270of this structure, for later use.
5271To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5272call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5273
5274
5275<p>
5276The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5277
5278<ul>
5279
5280<li><b><code>source</code>: </b>
5281the source of the chunk that created the function.
5282If <code>source</code> starts with a '<code>@</code>',
5283it means that the function was defined in a file where
5284the file name follows the '<code>@</code>'.
5285If <code>source</code> starts with a '<code>=</code>',
5286the remainder of its contents describe the source in a user-dependent manner.
5287Otherwise,
5288the function was defined in a string where
5289<code>source</code> is that string.
5290</li>
5291
5292<li><b><code>short_src</code>: </b>
5293a "printable" version of <code>source</code>, to be used in error messages.
5294</li>
5295
5296<li><b><code>linedefined</code>: </b>
5297the line number where the definition of the function starts.
5298</li>
5299
5300<li><b><code>lastlinedefined</code>: </b>
5301the line number where the definition of the function ends.
5302</li>
5303
5304<li><b><code>what</code>: </b>
5305the string <code>"Lua"</code> if the function is a Lua function,
5306<code>"C"</code> if it is a C&nbsp;function,
5307<code>"main"</code> if it is the main part of a chunk.
5308</li>
5309
5310<li><b><code>currentline</code>: </b>
5311the current line where the given function is executing.
5312When no line information is available,
5313<code>currentline</code> is set to -1.
5314</li>
5315
5316<li><b><code>name</code>: </b>
5317a reasonable name for the given function.
5318Because functions in Lua are first-class values,
5319they do not have a fixed name:
5320some functions can be the value of multiple global variables,
5321while others can be stored only in a table field.
5322The <code>lua_getinfo</code> function checks how the function was
5323called to find a suitable name.
5324If it cannot find a name,
5325then <code>name</code> is set to <code>NULL</code>.
5326</li>
5327
5328<li><b><code>namewhat</code>: </b>
5329explains the <code>name</code> field.
5330The value of <code>namewhat</code> can be
5331<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
5332<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
5333according to how the function was called.
5334(Lua uses the empty string when no other option seems to apply.)
5335</li>
5336
5337<li><b><code>istailcall</code>: </b>
5338true if this function invocation was called by a tail call.
5339In this case, the caller of this level is not in the stack.
5340</li>
5341
5342<li><b><code>nups</code>: </b>
5343the number of upvalues of the function.
5344</li>
5345
5346<li><b><code>nparams</code>: </b>
5347the number of fixed parameters of the function
5348(always 0&nbsp;for C&nbsp;functions).
5349</li>
5350
5351<li><b><code>isvararg</code>: </b>
5352true if the function is a vararg function
5353(always true for C&nbsp;functions).
5354</li>
5355
5356</ul>
5357
5358
5359
5360
5361<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
5362<span class="apii">[-0, +0, &ndash;]</span>
5363<pre>lua_Hook lua_gethook (lua_State *L);</pre>
5364
5365<p>
5366Returns the current hook function.
5367
5368
5369
5370
5371
5372<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
5373<span class="apii">[-0, +0, &ndash;]</span>
5374<pre>int lua_gethookcount (lua_State *L);</pre>
5375
5376<p>
5377Returns the current hook count.
5378
5379
5380
5381
5382
5383<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
5384<span class="apii">[-0, +0, &ndash;]</span>
5385<pre>int lua_gethookmask (lua_State *L);</pre>
5386
5387<p>
5388Returns the current hook mask.
5389
5390
5391
5392
5393
5394<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
5395<span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span>
5396<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
5397
5398<p>
5399Gets information about a specific function or function invocation.
5400
5401
5402<p>
5403To get information about a function invocation,
5404the parameter <code>ar</code> must be a valid activation record that was
5405filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5406given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5407
5408
5409<p>
5410To get information about a function you push it onto the stack
5411and start the <code>what</code> string with the character '<code>&gt;</code>'.
5412(In that case,
5413<code>lua_getinfo</code> pops the function from the top of the stack.)
5414For instance, to know in which line a function <code>f</code> was defined,
5415you can write the following code:
5416
5417<pre>
5418     lua_Debug ar;
5419     lua_getglobal(L, "f");  /* get global 'f' */
5420     lua_getinfo(L, "&gt;S", &amp;ar);
5421     printf("%d\n", ar.linedefined);
5422</pre>
5423
5424<p>
5425Each character in the string <code>what</code>
5426selects some fields of the structure <code>ar</code> to be filled or
5427a value to be pushed on the stack:
5428
5429<ul>
5430
5431<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
5432</li>
5433
5434<li><b>'<code>S</code>': </b>
5435fills in the fields <code>source</code>, <code>short_src</code>,
5436<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
5437</li>
5438
5439<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
5440</li>
5441
5442<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
5443</li>
5444
5445<li><b>'<code>u</code>': </b> fills in the fields
5446<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
5447</li>
5448
5449<li><b>'<code>f</code>': </b>
5450pushes onto the stack the function that is
5451running at the given level;
5452</li>
5453
5454<li><b>'<code>L</code>': </b>
5455pushes onto the stack a table whose indices are the
5456numbers of the lines that are valid on the function.
5457(A <em>valid line</em> is a line with some associated code,
5458that is, a line where you can put a break point.
5459Non-valid lines include empty lines and comments.)
5460
5461
5462<p>
5463If this option is given together with option '<code>f</code>',
5464its table is pushed after the function.
5465</li>
5466
5467</ul>
5468
5469<p>
5470This function returns 0 on error
5471(for instance, an invalid option in <code>what</code>).
5472
5473
5474
5475
5476
5477<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
5478<span class="apii">[-0, +(0|1), &ndash;]</span>
5479<pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5480
5481<p>
5482Gets information about a local variable of
5483a given activation record or a given function.
5484
5485
5486<p>
5487In the first case,
5488the parameter <code>ar</code> must be a valid activation record that was
5489filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5490given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5491The index <code>n</code> selects which local variable to inspect;
5492see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
5493and names.
5494
5495
5496<p>
5497<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
5498and returns its name.
5499
5500
5501<p>
5502In the second case, <code>ar</code> must be <code>NULL</code> and the function
5503to be inspected must be at the top of the stack.
5504In this case, only parameters of Lua functions are visible
5505(as there is no information about what variables are active)
5506and no values are pushed onto the stack.
5507
5508
5509<p>
5510Returns <code>NULL</code> (and pushes nothing)
5511when the index is greater than
5512the number of active local variables.
5513
5514
5515
5516
5517
5518<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
5519<span class="apii">[-0, +0, &ndash;]</span>
5520<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
5521
5522<p>
5523Gets information about the interpreter runtime stack.
5524
5525
5526<p>
5527This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
5528an identification of the <em>activation record</em>
5529of the function executing at a given level.
5530Level&nbsp;0 is the current running function,
5531whereas level <em>n+1</em> is the function that has called level <em>n</em>
5532(except for tail calls, which do not count on the stack).
5533When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
5534when called with a level greater than the stack depth,
5535it returns 0.
5536
5537
5538
5539
5540
5541<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
5542<span class="apii">[-0, +(0|1), &ndash;]</span>
5543<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
5544
5545<p>
5546Gets information about a closure's upvalue.
5547(For Lua functions,
5548upvalues are the external local variables that the function uses,
5549and that are consequently included in its closure.)
5550<a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
5551pushes the upvalue's value onto the stack,
5552and returns its name.
5553<code>funcindex</code> points to the closure in the stack.
5554(Upvalues have no particular order,
5555as they are active through the whole function.
5556So, they are numbered in an arbitrary order.)
5557
5558
5559<p>
5560Returns <code>NULL</code> (and pushes nothing)
5561when the index is greater than the number of upvalues.
5562For C&nbsp;functions, this function uses the empty string <code>""</code>
5563as a name for all upvalues.
5564
5565
5566
5567
5568
5569<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
5570<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
5571
5572<p>
5573Type for debugging hook functions.
5574
5575
5576<p>
5577Whenever a hook is called, its <code>ar</code> argument has its field
5578<code>event</code> set to the specific event that triggered the hook.
5579Lua identifies these events with the following constants:
5580<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
5581<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
5582and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
5583Moreover, for line events, the field <code>currentline</code> is also set.
5584To get the value of any other field in <code>ar</code>,
5585the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5586
5587
5588<p>
5589For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
5590the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
5591in this case, there will be no corresponding return event.
5592
5593
5594<p>
5595While Lua is running a hook, it disables other calls to hooks.
5596Therefore, if a hook calls back Lua to execute a function or a chunk,
5597this execution occurs without any calls to hooks.
5598
5599
5600<p>
5601Hook functions cannot have continuations,
5602that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5603<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>.
5604
5605
5606<p>
5607Hook functions can yield under the following conditions:
5608Only count and line events can yield
5609and they cannot yield any value;
5610to yield a hook function must finish its execution
5611calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero.
5612
5613
5614
5615
5616
5617<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
5618<span class="apii">[-0, +0, &ndash;]</span>
5619<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5620
5621<p>
5622Sets the debugging hook function.
5623
5624
5625<p>
5626Argument <code>f</code> is the hook function.
5627<code>mask</code> specifies on which events the hook will be called:
5628it is formed by a bitwise or of the constants
5629<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
5630<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
5631<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
5632and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
5633The <code>count</code> argument is only meaningful when the mask
5634includes <code>LUA_MASKCOUNT</code>.
5635For each event, the hook is called as explained below:
5636
5637<ul>
5638
5639<li><b>The call hook: </b> is called when the interpreter calls a function.
5640The hook is called just after Lua enters the new function,
5641before the function gets its arguments.
5642</li>
5643
5644<li><b>The return hook: </b> is called when the interpreter returns from a function.
5645The hook is called just before Lua leaves the function.
5646There is no standard way to access the values
5647to be returned by the function.
5648</li>
5649
5650<li><b>The line hook: </b> is called when the interpreter is about to
5651start the execution of a new line of code,
5652or when it jumps back in the code (even to the same line).
5653(This event only happens while Lua is executing a Lua function.)
5654</li>
5655
5656<li><b>The count hook: </b> is called after the interpreter executes every
5657<code>count</code> instructions.
5658(This event only happens while Lua is executing a Lua function.)
5659</li>
5660
5661</ul>
5662
5663<p>
5664A hook is disabled by setting <code>mask</code> to zero.
5665
5666
5667
5668
5669
5670<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
5671<span class="apii">[-(0|1), +0, &ndash;]</span>
5672<pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5673
5674<p>
5675Sets the value of a local variable of a given activation record.
5676Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
5677(see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
5678<a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
5679to the variable and returns its name.
5680It also pops the value from the stack.
5681
5682
5683<p>
5684Returns <code>NULL</code> (and pops nothing)
5685when the index is greater than
5686the number of active local variables.
5687
5688
5689
5690
5691
5692<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
5693<span class="apii">[-(0|1), +0, &ndash;]</span>
5694<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
5695
5696<p>
5697Sets the value of a closure's upvalue.
5698It assigns the value at the top of the stack
5699to the upvalue and returns its name.
5700It also pops the value from the stack.
5701Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
5702(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
5703
5704
5705<p>
5706Returns <code>NULL</code> (and pops nothing)
5707when the index is greater than the number of upvalues.
5708
5709
5710
5711
5712
5713<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
5714<span class="apii">[-0, +0, &ndash;]</span>
5715<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
5716
5717<p>
5718Returns an unique identifier for the upvalue numbered <code>n</code>
5719from the closure at index <code>funcindex</code>.
5720Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
5721(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>)
5722(but <code>n</code> cannot be greater than the number of upvalues).
5723
5724
5725<p>
5726These unique identifiers allow a program to check whether different
5727closures share upvalues.
5728Lua closures that share an upvalue
5729(that is, that access a same external local variable)
5730will return identical ids for those upvalue indices.
5731
5732
5733
5734
5735
5736<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
5737<span class="apii">[-0, +0, &ndash;]</span>
5738<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
5739                                    int funcindex2, int n2);</pre>
5740
5741<p>
5742Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
5743refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
5744
5745
5746
5747
5748
5749
5750
5751<h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
5752
5753<p>
5754
5755The <em>auxiliary library</em> provides several convenient functions
5756to interface C with Lua.
5757While the basic API provides the primitive functions for all
5758interactions between C and Lua,
5759the auxiliary library provides higher-level functions for some
5760common tasks.
5761
5762
5763<p>
5764All functions and types from the auxiliary library
5765are defined in header file <code>lauxlib.h</code> and
5766have a prefix <code>luaL_</code>.
5767
5768
5769<p>
5770All functions in the auxiliary library are built on
5771top of the basic API,
5772and so they provide nothing that cannot be done with that API.
5773Nevertheless, the use of the auxiliary library ensures
5774more consistency to your code.
5775
5776
5777<p>
5778Several functions in the auxiliary library use internally some
5779extra stack slots.
5780When a function in the auxiliary library uses less than five slots,
5781it does not check the stack size;
5782it simply assumes that there are enough slots.
5783
5784
5785<p>
5786Several functions in the auxiliary library are used to
5787check C&nbsp;function arguments.
5788Because the error message is formatted for arguments
5789(e.g., "<code>bad argument #1</code>"),
5790you should not use these functions for other stack values.
5791
5792
5793<p>
5794Functions called <code>luaL_check*</code>
5795always raise an error if the check is not satisfied.
5796
5797
5798
5799<h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
5800
5801<p>
5802Here we list all functions and types from the auxiliary library
5803in alphabetical order.
5804
5805
5806
5807<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
5808<span class="apii">[-?, +?, <em>e</em>]</span>
5809<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
5810
5811<p>
5812Adds the byte <code>c</code> to the buffer <code>B</code>
5813(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5814
5815
5816
5817
5818
5819<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
5820<span class="apii">[-?, +?, <em>e</em>]</span>
5821<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
5822
5823<p>
5824Adds the string pointed to by <code>s</code> with length <code>l</code> to
5825the buffer <code>B</code>
5826(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5827The string can contain embedded zeros.
5828
5829
5830
5831
5832
5833<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
5834<span class="apii">[-?, +?, <em>e</em>]</span>
5835<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
5836
5837<p>
5838Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
5839a string of length <code>n</code> previously copied to the
5840buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
5841
5842
5843
5844
5845
5846<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
5847<span class="apii">[-?, +?, <em>e</em>]</span>
5848<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
5849
5850<p>
5851Adds the zero-terminated string pointed to by <code>s</code>
5852to the buffer <code>B</code>
5853(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5854
5855
5856
5857
5858
5859<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
5860<span class="apii">[-1, +?, <em>e</em>]</span>
5861<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
5862
5863<p>
5864Adds the value at the top of the stack
5865to the buffer <code>B</code>
5866(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5867Pops the value.
5868
5869
5870<p>
5871This is the only function on string buffers that can (and must)
5872be called with an extra element on the stack,
5873which is the value to be added to the buffer.
5874
5875
5876
5877
5878
5879<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
5880<span class="apii">[-0, +0, <em>v</em>]</span>
5881<pre>void luaL_argcheck (lua_State *L,
5882                    int cond,
5883                    int arg,
5884                    const char *extramsg);</pre>
5885
5886<p>
5887Checks whether <code>cond</code> is true.
5888If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
5889
5890
5891
5892
5893
5894<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
5895<span class="apii">[-0, +0, <em>v</em>]</span>
5896<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
5897
5898<p>
5899Raises an error reporting a problem with argument <code>arg</code>
5900of the C function that called it,
5901using a standard message
5902that includes <code>extramsg</code> as a comment:
5903
5904<pre>
5905     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
5906</pre><p>
5907This function never returns.
5908
5909
5910
5911
5912
5913<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
5914<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
5915
5916<p>
5917Type for a <em>string buffer</em>.
5918
5919
5920<p>
5921A string buffer allows C&nbsp;code to build Lua strings piecemeal.
5922Its pattern of use is as follows:
5923
5924<ul>
5925
5926<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
5927
5928<li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
5929
5930<li>
5931Then add string pieces to the buffer calling any of
5932the <code>luaL_add*</code> functions.
5933</li>
5934
5935<li>
5936Finish by calling <code>luaL_pushresult(&amp;b)</code>.
5937This call leaves the final string on the top of the stack.
5938</li>
5939
5940</ul>
5941
5942<p>
5943If you know beforehand the total size of the resulting string,
5944you can use the buffer like this:
5945
5946<ul>
5947
5948<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
5949
5950<li>Then initialize it and preallocate a space of
5951size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
5952
5953<li>Then copy the string into that space.</li>
5954
5955<li>
5956Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
5957where <code>sz</code> is the total size of the resulting string
5958copied into that space.
5959</li>
5960
5961</ul>
5962
5963<p>
5964During its normal operation,
5965a string buffer uses a variable number of stack slots.
5966So, while using a buffer, you cannot assume that you know where
5967the top of the stack is.
5968You can use the stack between successive calls to buffer operations
5969as long as that use is balanced;
5970that is,
5971when you call a buffer operation,
5972the stack is at the same level
5973it was immediately after the previous buffer operation.
5974(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
5975After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
5976level when the buffer was initialized,
5977plus the final string on its top.
5978
5979
5980
5981
5982
5983<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
5984<span class="apii">[-0, +0, &ndash;]</span>
5985<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
5986
5987<p>
5988Initializes a buffer <code>B</code>.
5989This function does not allocate any space;
5990the buffer must be declared as a variable
5991(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5992
5993
5994
5995
5996
5997<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
5998<span class="apii">[-?, +?, <em>e</em>]</span>
5999<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
6000
6001<p>
6002Equivalent to the sequence
6003<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
6004
6005
6006
6007
6008
6009<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
6010<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6011<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
6012
6013<p>
6014Calls a metamethod.
6015
6016
6017<p>
6018If the object at index <code>obj</code> has a metatable and this
6019metatable has a field <code>e</code>,
6020this function calls this field passing the object as its only argument.
6021In this case this function returns true and pushes onto the
6022stack the value returned by the call.
6023If there is no metatable or no metamethod,
6024this function returns false (without pushing any value on the stack).
6025
6026
6027
6028
6029
6030<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
6031<span class="apii">[-0, +0, <em>v</em>]</span>
6032<pre>void luaL_checkany (lua_State *L, int arg);</pre>
6033
6034<p>
6035Checks whether the function has an argument
6036of any type (including <b>nil</b>) at position <code>arg</code>.
6037
6038
6039
6040
6041
6042<hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
6043<span class="apii">[-0, +0, <em>v</em>]</span>
6044<pre>int luaL_checkint (lua_State *L, int arg);</pre>
6045
6046<p>
6047Checks whether the function argument <code>arg</code> is an integer
6048(or can be converted to an integer)
6049and returns this integer cast to an <code>int</code>.
6050
6051
6052
6053
6054
6055<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
6056<span class="apii">[-0, +0, <em>v</em>]</span>
6057<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
6058
6059<p>
6060Checks whether the function argument <code>arg</code> is an integer
6061(or can be converted to an integer)
6062and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6063
6064
6065
6066
6067
6068<hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
6069<span class="apii">[-0, +0, <em>v</em>]</span>
6070<pre>long luaL_checklong (lua_State *L, int arg);</pre>
6071
6072<p>
6073Checks whether the function argument <code>arg</code> is an integer
6074(or can be converted to an integer)
6075and returns this integer cast to a <code>long</code>.
6076
6077
6078
6079
6080
6081<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
6082<span class="apii">[-0, +0, <em>v</em>]</span>
6083<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
6084
6085<p>
6086Checks whether the function argument <code>arg</code> is a string
6087and returns this string;
6088if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
6089with the string's length.
6090
6091
6092<p>
6093This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6094so all conversions and caveats of that function apply here.
6095
6096
6097
6098
6099
6100<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
6101<span class="apii">[-0, +0, <em>v</em>]</span>
6102<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
6103
6104<p>
6105Checks whether the function argument <code>arg</code> is a number
6106and returns this number.
6107
6108
6109
6110
6111
6112<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
6113<span class="apii">[-0, +0, <em>v</em>]</span>
6114<pre>int luaL_checkoption (lua_State *L,
6115                      int arg,
6116                      const char *def,
6117                      const char *const lst[]);</pre>
6118
6119<p>
6120Checks whether the function argument <code>arg</code> is a string and
6121searches for this string in the array <code>lst</code>
6122(which must be NULL-terminated).
6123Returns the index in the array where the string was found.
6124Raises an error if the argument is not a string or
6125if the string cannot be found.
6126
6127
6128<p>
6129If <code>def</code> is not <code>NULL</code>,
6130the function uses <code>def</code> as a default value when
6131there is no argument <code>arg</code> or when this argument is <b>nil</b>.
6132
6133
6134<p>
6135This is a useful function for mapping strings to C&nbsp;enums.
6136(The usual convention in Lua libraries is
6137to use strings instead of numbers to select options.)
6138
6139
6140
6141
6142
6143<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
6144<span class="apii">[-0, +0, <em>v</em>]</span>
6145<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
6146
6147<p>
6148Grows the stack size to <code>top + sz</code> elements,
6149raising an error if the stack cannot grow to that size.
6150<code>msg</code> is an additional text to go into the error message
6151(or <code>NULL</code> for no additional text).
6152
6153
6154
6155
6156
6157<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
6158<span class="apii">[-0, +0, <em>v</em>]</span>
6159<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
6160
6161<p>
6162Checks whether the function argument <code>arg</code> is a string
6163and returns this string.
6164
6165
6166<p>
6167This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
6168so all conversions and caveats of that function apply here.
6169
6170
6171
6172
6173
6174<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
6175<span class="apii">[-0, +0, <em>v</em>]</span>
6176<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
6177
6178<p>
6179Checks whether the function argument <code>arg</code> has type <code>t</code>.
6180See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
6181
6182
6183
6184
6185
6186<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6187<span class="apii">[-0, +0, <em>v</em>]</span>
6188<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6189
6190<p>
6191Checks whether the function argument <code>arg</code> is a userdata
6192of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6193returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6194
6195
6196
6197
6198
6199<hr><h3><a name="luaL_checkunsigned"><code>luaL_checkunsigned</code></a></h3><p>
6200<span class="apii">[-0, +0, <em>v</em>]</span>
6201<pre>lua_Unsigned luaL_checkunsigned (lua_State *L, int arg);</pre>
6202
6203<p>
6204Checks whether the function argument <code>arg</code> is a number
6205and returns this number converted to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6206
6207
6208
6209
6210
6211<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6212<span class="apii">[-0, +0, &ndash;]</span>
6213<pre>void luaL_checkversion (lua_State *L);</pre>
6214
6215<p>
6216Checks whether the core running the call,
6217the core that created the Lua state,
6218and the code making the call are all using the same version of Lua.
6219Also checks whether the core running the call
6220and the core that created the Lua state
6221are using the same address space.
6222
6223
6224
6225
6226
6227<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6228<span class="apii">[-0, +?, <em>e</em>]</span>
6229<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6230
6231<p>
6232Loads and runs the given file.
6233It is defined as the following macro:
6234
6235<pre>
6236     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6237</pre><p>
6238It returns false if there are no errors
6239or true in case of errors.
6240
6241
6242
6243
6244
6245<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6246<span class="apii">[-0, +?, &ndash;]</span>
6247<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6248
6249<p>
6250Loads and runs the given string.
6251It is defined as the following macro:
6252
6253<pre>
6254     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6255</pre><p>
6256It returns false if there are no errors
6257or true in case of errors.
6258
6259
6260
6261
6262
6263<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6264<span class="apii">[-0, +0, <em>v</em>]</span>
6265<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6266
6267<p>
6268Raises an error.
6269The error message format is given by <code>fmt</code>
6270plus any extra arguments,
6271following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6272It also adds at the beginning of the message the file name and
6273the line number where the error occurred,
6274if this information is available.
6275
6276
6277<p>
6278This function never returns,
6279but it is an idiom to use it in C&nbsp;functions
6280as <code>return luaL_error(<em>args</em>)</code>.
6281
6282
6283
6284
6285
6286<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
6287<span class="apii">[-0, +3, <em>e</em>]</span>
6288<pre>int luaL_execresult (lua_State *L, int stat);</pre>
6289
6290<p>
6291This function produces the return values for
6292process-related functions in the standard library
6293(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
6294
6295
6296
6297
6298
6299<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
6300<span class="apii">[-0, +(1|3), <em>e</em>]</span>
6301<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
6302
6303<p>
6304This function produces the return values for
6305file-related functions in the standard library
6306(<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.).
6307
6308
6309
6310
6311
6312<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
6313<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6314<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
6315
6316<p>
6317Pushes onto the stack the field <code>e</code> from the metatable
6318of the object at index <code>obj</code>.
6319If the object does not have a metatable,
6320or if the metatable does not have this field,
6321returns false and pushes nothing.
6322
6323
6324
6325
6326
6327<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
6328<span class="apii">[-0, +1, &ndash;]</span>
6329<pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
6330
6331<p>
6332Pushes onto the stack the metatable associated with name <code>tname</code>
6333in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6334
6335
6336
6337
6338
6339<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
6340<span class="apii">[-0, +1, <em>e</em>]</span>
6341<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
6342
6343<p>
6344Ensures that the value <code>t[fname]</code>,
6345where <code>t</code> is the value at index <code>idx</code>,
6346is a table,
6347and pushes that table onto the stack.
6348Returns true if it finds a previous table there
6349and false if it creates a new table.
6350
6351
6352
6353
6354
6355<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
6356<span class="apii">[-0, +1, <em>e</em>]</span>
6357<pre>const char *luaL_gsub (lua_State *L,
6358                       const char *s,
6359                       const char *p,
6360                       const char *r);</pre>
6361
6362<p>
6363Creates a copy of string <code>s</code> by replacing
6364any occurrence of the string <code>p</code>
6365with the string <code>r</code>.
6366Pushes the resulting string on the stack and returns it.
6367
6368
6369
6370
6371
6372<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
6373<span class="apii">[-0, +0, <em>e</em>]</span>
6374<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
6375
6376<p>
6377Returns the "length" of the value at the given index
6378as a number;
6379it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
6380Raises an error if the result of the operation is not an integer.
6381(This case only can happen through metamethods.)
6382
6383
6384
6385
6386
6387<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
6388<span class="apii">[-0, +1, &ndash;]</span>
6389<pre>int luaL_loadbuffer (lua_State *L,
6390                     const char *buff,
6391                     size_t sz,
6392                     const char *name);</pre>
6393
6394<p>
6395Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
6396
6397
6398
6399
6400
6401<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
6402<span class="apii">[-0, +1, &ndash;]</span>
6403<pre>int luaL_loadbufferx (lua_State *L,
6404                      const char *buff,
6405                      size_t sz,
6406                      const char *name,
6407                      const char *mode);</pre>
6408
6409<p>
6410Loads a buffer as a Lua chunk.
6411This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
6412buffer pointed to by <code>buff</code> with size <code>sz</code>.
6413
6414
6415<p>
6416This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6417<code>name</code> is the chunk name,
6418used for debug information and error messages.
6419The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6420
6421
6422
6423
6424
6425<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
6426<span class="apii">[-0, +1, <em>e</em>]</span>
6427<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
6428
6429<p>
6430Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
6431
6432
6433
6434
6435
6436<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
6437<span class="apii">[-0, +1, <em>e</em>]</span>
6438<pre>int luaL_loadfilex (lua_State *L, const char *filename,
6439                                            const char *mode);</pre>
6440
6441<p>
6442Loads a file as a Lua chunk.
6443This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
6444named <code>filename</code>.
6445If <code>filename</code> is <code>NULL</code>,
6446then it loads from the standard input.
6447The first line in the file is ignored if it starts with a <code>#</code>.
6448
6449
6450<p>
6451The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6452
6453
6454<p>
6455This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
6456but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
6457if it cannot open/read the file or the file has a wrong mode.
6458
6459
6460<p>
6461As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6462it does not run it.
6463
6464
6465
6466
6467
6468<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
6469<span class="apii">[-0, +1, &ndash;]</span>
6470<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
6471
6472<p>
6473Loads a string as a Lua chunk.
6474This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
6475the zero-terminated string <code>s</code>.
6476
6477
6478<p>
6479This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6480
6481
6482<p>
6483Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6484it does not run it.
6485
6486
6487
6488
6489
6490<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
6491<span class="apii">[-0, +1, <em>e</em>]</span>
6492<pre>void luaL_newlib (lua_State *L, const luaL_Reg *l);</pre>
6493
6494<p>
6495Creates a new table and registers there
6496the functions in list <code>l</code>.
6497It is implemented as the following macro:
6498
6499<pre>
6500     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
6501</pre>
6502
6503
6504
6505
6506<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
6507<span class="apii">[-0, +1, <em>e</em>]</span>
6508<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
6509
6510<p>
6511Creates a new table with a size optimized
6512to store all entries in the array <code>l</code>
6513(but does not actually store them).
6514It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
6515(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
6516
6517
6518<p>
6519It is implemented as a macro.
6520The array <code>l</code> must be the actual array,
6521not a pointer to it.
6522
6523
6524
6525
6526
6527<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
6528<span class="apii">[-0, +1, <em>e</em>]</span>
6529<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
6530
6531<p>
6532If the registry already has the key <code>tname</code>,
6533returns 0.
6534Otherwise,
6535creates a new table to be used as a metatable for userdata,
6536adds to this new table the pair <code>__name = tname</code>,
6537adds to the registry the pair <code>[tname] = new table</code>,
6538and returns 1.
6539
6540
6541<p>
6542In both cases pushes onto the stack the final value associated
6543with <code>tname</code> in the registry.
6544
6545
6546
6547
6548
6549<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
6550<span class="apii">[-0, +0, &ndash;]</span>
6551<pre>lua_State *luaL_newstate (void);</pre>
6552
6553<p>
6554Creates a new Lua state.
6555It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
6556allocator based on the standard&nbsp;C <code>realloc</code> function
6557and then sets a panic function (see <a href="#4.6">&sect;4.6</a>) that prints
6558an error message to the standard error output in case of fatal
6559errors.
6560
6561
6562<p>
6563Returns the new state,
6564or <code>NULL</code> if there is a memory allocation error.
6565
6566
6567
6568
6569
6570<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
6571<span class="apii">[-0, +0, <em>e</em>]</span>
6572<pre>void luaL_openlibs (lua_State *L);</pre>
6573
6574<p>
6575Opens all standard Lua libraries into the given state.
6576
6577
6578
6579
6580
6581<hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
6582<span class="apii">[-0, +0, <em>v</em>]</span>
6583<pre>int luaL_optint (lua_State *L, int arg, int d);</pre>
6584
6585<p>
6586If the function argument <code>arg</code> is a number,
6587returns this number cast to an <code>int</code>.
6588If this argument is absent or is <b>nil</b>,
6589returns <code>d</code>.
6590Otherwise, raises an error.
6591
6592
6593
6594
6595
6596<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
6597<span class="apii">[-0, +0, <em>v</em>]</span>
6598<pre>lua_Integer luaL_optinteger (lua_State *L,
6599                             int arg,
6600                             lua_Integer d);</pre>
6601
6602<p>
6603If the function argument <code>arg</code> is an integer
6604(or convertible to an integer),
6605returns this integer.
6606If this argument is absent or is <b>nil</b>,
6607returns <code>d</code>.
6608Otherwise, raises an error.
6609
6610
6611
6612
6613
6614<hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3><p>
6615<span class="apii">[-0, +0, <em>v</em>]</span>
6616<pre>long luaL_optlong (lua_State *L, int arg, long d);</pre>
6617
6618<p>
6619If the function argument <code>arg</code> is an integer
6620(or convertible to an integer),
6621returns this integer cast to a <code>long</code>.
6622If this argument is absent or is <b>nil</b>,
6623returns <code>d</code>.
6624Otherwise, raises an error.
6625
6626
6627
6628
6629
6630<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
6631<span class="apii">[-0, +0, <em>v</em>]</span>
6632<pre>const char *luaL_optlstring (lua_State *L,
6633                             int arg,
6634                             const char *d,
6635                             size_t *l);</pre>
6636
6637<p>
6638If the function argument <code>arg</code> is a string,
6639returns this string.
6640If this argument is absent or is <b>nil</b>,
6641returns <code>d</code>.
6642Otherwise, raises an error.
6643
6644
6645<p>
6646If <code>l</code> is not <code>NULL</code>,
6647fills the position <code>*l</code> with the result's length.
6648
6649
6650
6651
6652
6653<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
6654<span class="apii">[-0, +0, <em>v</em>]</span>
6655<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
6656
6657<p>
6658If the function argument <code>arg</code> is a number,
6659returns this number.
6660If this argument is absent or is <b>nil</b>,
6661returns <code>d</code>.
6662Otherwise, raises an error.
6663
6664
6665
6666
6667
6668<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
6669<span class="apii">[-0, +0, <em>v</em>]</span>
6670<pre>const char *luaL_optstring (lua_State *L,
6671                            int arg,
6672                            const char *d);</pre>
6673
6674<p>
6675If the function argument <code>arg</code> is a string,
6676returns this string.
6677If this argument is absent or is <b>nil</b>,
6678returns <code>d</code>.
6679Otherwise, raises an error.
6680
6681
6682
6683
6684
6685<hr><h3><a name="luaL_optunsigned"><code>luaL_optunsigned</code></a></h3><p>
6686<span class="apii">[-0, +0, <em>v</em>]</span>
6687<pre>lua_Unsigned luaL_optunsigned (lua_State *L,
6688                               int arg,
6689                               lua_Unsigned u);</pre>
6690
6691<p>
6692If the function argument <code>arg</code> is a number,
6693returns this number converted to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6694If this argument is absent or is <b>nil</b>,
6695returns <code>u</code>.
6696Otherwise, 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>
6707Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
6708with 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>
6719Returns an address to a space of size <code>sz</code>
6720where you can copy a string to be added to buffer <code>B</code>
6721(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6722After 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
6724it 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>
6735Finishes the use of buffer <code>B</code> leaving the final string on
6736the 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>
6747Equivalent 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>
6758Creates and returns a <em>reference</em>,
6759in the table at index <code>t</code>,
6760for the object at the top of the stack (and pops the object).
6761
6762
6763<p>
6764A reference is a unique integer key.
6765As 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.
6767You can retrieve an object referred by reference <code>r</code>
6768by calling <code>lua_rawgeti(L, t, r)</code>.
6769Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
6770
6771
6772<p>
6773If 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>.
6775The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
6776from 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>
6789Type 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
6792the function.
6793Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
6794in 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>
6806Calls function <code>openf</code> with string <code>modname</code> as an argument
6807and sets the call result in <code>package.loaded[modname]</code>,
6808as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
6809
6810
6811<p>
6812If <code>glb</code> is true,
6813also stores the result into global <code>modname</code>.
6814
6815
6816<p>
6817Leaves a copy of that result on the stack.
6818
6819
6820
6821
6822
6823<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
6824<span class="apii">[-nup, +0, <em>e</em>]</span>
6825<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
6826
6827<p>
6828Registers all functions in the array <code>l</code>
6829(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
6830(below optional upvalues, see next).
6831
6832
6833<p>
6834When <code>nup</code> is not zero,
6835all functions are created sharing <code>nup</code> upvalues,
6836which must be previously pushed on the stack
6837on top of the library table.
6838These values are popped from the stack after the registration.
6839
6840
6841
6842
6843
6844<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
6845<span class="apii">[-0, +0, &ndash;]</span>
6846<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
6847
6848<p>
6849Sets the metatable of the object at the top of the stack
6850as the metatable associated with name <code>tname</code>
6851in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6852
6853
6854
6855
6856
6857<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
6858<pre>typedef struct luaL_Stream {
6859  FILE *f;
6860  lua_CFunction closef;
6861} luaL_Stream;</pre>
6862
6863<p>
6864The standard representation for file handles,
6865which is used by the standard I/O library.
6866
6867
6868<p>
6869A file handle is implemented as a full userdata,
6870with a metatable called <code>LUA_FILEHANDLE</code>.
6871<code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name.
6872The metatable is created by the I/O library
6873(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6874
6875
6876<p>
6877This userdata must start with the structure <code>luaL_Stream</code>;
6878it can contain other data after this initial structure.
6879Field <code>f</code> points to the corresponding C stream
6880(or it can be <code>NULL</code> to indicate an incompletely created handle).
6881Field <code>closef</code> points to a Lua function
6882that will be called to close the stream
6883when the handle is closed or collected;
6884this function receives the file handle as its sole argument and
6885must return either <b>true</b> (in case of success)
6886or <b>nil</b> plus an error message (in case of error).
6887Once Lua calls this field,
6888the field value is changed to <b>nil</b> to signal that the handle is closed.
6889
6890
6891
6892
6893
6894<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
6895<span class="apii">[-0, +0, <em>e</em>]</span>
6896<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
6897
6898<p>
6899This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
6900except that, when the test fails,
6901it returns <code>NULL</code> instead of raising an error.
6902
6903
6904
6905
6906
6907<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
6908<span class="apii">[-0, +1, <em>e</em>]</span>
6909<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
6910
6911<p>
6912Converts any Lua value at the given index to a C&nbsp;string
6913in a reasonable format.
6914The resulting string is pushed onto the stack and also
6915returned by the function.
6916If <code>len</code> is not <code>NULL</code>,
6917the function also sets <code>*len</code> with the string length.
6918
6919
6920<p>
6921If the value has a metatable with a <code>"__tostring"</code> field,
6922then <code>luaL_tolstring</code> calls the corresponding metamethod
6923with the value as argument,
6924and uses the result of the call as its result.
6925
6926
6927
6928
6929
6930<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
6931<span class="apii">[-0, +1, <em>e</em>]</span>
6932<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
6933                     int level);</pre>
6934
6935<p>
6936Creates and pushes a traceback of the stack <code>L1</code>.
6937If <code>msg</code> is not <code>NULL</code> it is appended
6938at the beginning of the traceback.
6939The <code>level</code> parameter tells at which level
6940to start the traceback.
6941
6942
6943
6944
6945
6946<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
6947<span class="apii">[-0, +0, &ndash;]</span>
6948<pre>const char *luaL_typename (lua_State *L, int index);</pre>
6949
6950<p>
6951Returns the name of the type of the value at the given index.
6952
6953
6954
6955
6956
6957<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
6958<span class="apii">[-0, +0, &ndash;]</span>
6959<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
6960
6961<p>
6962Releases reference <code>ref</code> from the table at index <code>t</code>
6963(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
6964The entry is removed from the table,
6965so that the referred object can be collected.
6966The reference <code>ref</code> is also freed to be used again.
6967
6968
6969<p>
6970If <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>,
6971<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
6972
6973
6974
6975
6976
6977<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
6978<span class="apii">[-0, +1, <em>e</em>]</span>
6979<pre>void luaL_where (lua_State *L, int lvl);</pre>
6980
6981<p>
6982Pushes onto the stack a string identifying the current position
6983of the control at level <code>lvl</code> in the call stack.
6984Typically this string has the following format:
6985
6986<pre>
6987     <em>chunkname</em>:<em>currentline</em>:
6988</pre><p>
6989Level&nbsp;0 is the running function,
6990level&nbsp;1 is the function that called the running function,
6991etc.
6992
6993
6994<p>
6995This function is used to build a prefix for error messages.
6996
6997
6998
6999
7000
7001
7002
7003<h1>6 &ndash; <a name="6">Standard Libraries</a></h1>
7004
7005<p>
7006The standard Lua libraries provide useful functions
7007that are implemented directly through the C&nbsp;API.
7008Some of these functions provide essential services to the language
7009(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
7010others provide access to "outside" services (e.g., I/O);
7011and others could be implemented in Lua itself,
7012but are quite useful or have critical performance requirements that
7013deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
7014
7015
7016<p>
7017All libraries are implemented through the official C&nbsp;API
7018and are provided as separate C&nbsp;modules.
7019Currently, Lua has the following standard libraries:
7020
7021<ul>
7022
7023<li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
7024
7025<li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
7026
7027<li>package library (<a href="#6.3">&sect;6.3</a>);</li>
7028
7029<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
7030
7031<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
7032
7033<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
7034
7035<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
7036
7037<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
7038
7039<li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
7040
7041<li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
7042
7043</ul><p>
7044Except for the basic and the package libraries,
7045each library provides all its functions as fields of a global table
7046or as methods of its objects.
7047
7048
7049<p>
7050To have access to these libraries,
7051the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
7052which opens all standard libraries.
7053Alternatively,
7054the host program can open them individually by using
7055<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
7056<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
7057<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
7058<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
7059<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7060<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
7061<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
7062<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7063<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
7064and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
7065These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
7066
7067
7068
7069<h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
7070
7071<p>
7072The basic library provides core functions to Lua.
7073If you do not include this library in your application,
7074you should check carefully whether you need to provide
7075implementations for some of its facilities.
7076
7077
7078<p>
7079<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7080
7081
7082<p>
7083Calls <a href="#pdf-error"><code>error</code></a> if
7084the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
7085otherwise, returns all its arguments.
7086In case of error,
7087<code>message</code> is the error object;
7088when absent, it defaults to "<code>assertion failed!</code>"
7089
7090
7091
7092
7093<p>
7094<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
7095
7096
7097<p>
7098This function is a generic interface to the garbage collector.
7099It performs different functions according to its first argument, <code>opt</code>:
7100
7101<ul>
7102
7103<li><b>"<code>collect</code>": </b>
7104performs a full garbage-collection cycle.
7105This is the default option.
7106</li>
7107
7108<li><b>"<code>stop</code>": </b>
7109stops automatic execution of the garbage collector.
7110The collector will run only when explicitly invoked,
7111until a call to restart it.
7112</li>
7113
7114<li><b>"<code>restart</code>": </b>
7115restarts automatic execution of the garbage collector.
7116</li>
7117
7118<li><b>"<code>count</code>": </b>
7119returns the total memory in use by Lua in Kbytes.
7120The value has a fractional part,
7121so that it multiplied by 1024
7122gives the exact number of bytes in use by Lua
7123(except for overflows).
7124</li>
7125
7126<li><b>"<code>step</code>": </b>
7127performs a garbage-collection step.
7128The step "size" is controlled by <code>arg</code>.
7129With a zero value,
7130the collector will perform one basic (indivisible) step.
7131For non-zero values,
7132the collector will perform as if that amount of memory
7133(in KBytes) had been allocated by Lua.
7134Returns <b>true</b> if the step finished a collection cycle.
7135</li>
7136
7137<li><b>"<code>setpause</code>": </b>
7138sets <code>arg</code> as the new value for the <em>pause</em> of
7139the collector (see <a href="#2.5">&sect;2.5</a>).
7140Returns the previous value for <em>pause</em>.
7141</li>
7142
7143<li><b>"<code>setstepmul</code>": </b>
7144sets <code>arg</code> as the new value for the <em>step multiplier</em> of
7145the collector (see <a href="#2.5">&sect;2.5</a>).
7146Returns the previous value for <em>step</em>.
7147</li>
7148
7149<li><b>"<code>isrunning</code>": </b>
7150returns a boolean that tells whether the collector is running
7151(i.e., not stopped).
7152</li>
7153
7154</ul>
7155
7156
7157
7158<p>
7159<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
7160Opens the named file and executes its contents as a Lua chunk.
7161When called without arguments,
7162<code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
7163Returns all values returned by the chunk.
7164In case of errors, <code>dofile</code> propagates the error
7165to its caller (that is, <code>dofile</code> does not run in protected mode).
7166
7167
7168
7169
7170<p>
7171<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
7172Terminates the last protected function called
7173and returns <code>message</code> as the error object.
7174Function <code>error</code> never returns.
7175
7176
7177<p>
7178Usually, <code>error</code> adds some information about the error position
7179at the beginning of the message, if the message is a string.
7180The <code>level</code> argument specifies how to get the error position.
7181With level&nbsp;1 (the default), the error position is where the
7182<code>error</code> function was called.
7183Level&nbsp;2 points the error to where the function
7184that called <code>error</code> was called; and so on.
7185Passing a level&nbsp;0 avoids the addition of error position information
7186to the message.
7187
7188
7189
7190
7191<p>
7192<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
7193A global variable (not a function) that
7194holds the global environment (see <a href="#2.2">&sect;2.2</a>).
7195Lua itself does not use this variable;
7196changing its value does not affect any environment,
7197nor vice versa.
7198
7199
7200
7201
7202<p>
7203<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
7204
7205
7206<p>
7207If <code>object</code> does not have a metatable, returns <b>nil</b>.
7208Otherwise,
7209if the object's metatable has a <code>"__metatable"</code> field,
7210returns the associated value.
7211Otherwise, returns the metatable of the given object.
7212
7213
7214
7215
7216<p>
7217<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7218
7219
7220<p>
7221If <code>t</code> has a metamethod <code>__ipairs</code>,
7222calls it with <code>t</code> as argument and returns the first three
7223results from the call.
7224
7225
7226<p>
7227Otherwise,
7228returns three values: an iterator function, the table <code>t</code>, and 0,
7229so that the construction
7230
7231<pre>
7232     for i,v in ipairs(t) do <em>body</em> end
7233</pre><p>
7234will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7235up to the first integer key absent from the table.
7236
7237
7238
7239
7240<p>
7241<hr><h3><a name="pdf-load"><code>load (ld [, source [, mode [, env]]])</code></a></h3>
7242
7243
7244<p>
7245Loads a chunk.
7246
7247
7248<p>
7249If <code>ld</code> is a string, the chunk is this string.
7250If <code>ld</code> is a function,
7251<code>load</code> calls it repeatedly to get the chunk pieces.
7252Each call to <code>ld</code> must return a string that concatenates
7253with previous results.
7254A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
7255
7256
7257<p>
7258If there are no syntactic errors,
7259returns the compiled chunk as a function;
7260otherwise, returns <b>nil</b> plus the error message.
7261
7262
7263<p>
7264If the resulting function has upvalues,
7265the first upvalue is set to the value of <code>env</code>,
7266if that parameter is given,
7267or to the value of the global environment.
7268(When you load a main chunk,
7269the resulting function will always have exactly one upvalue,
7270the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
7271When you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7272the resulting function can have arbitrary upvalues.)
7273
7274
7275<p>
7276<code>source</code> is used as the source of the chunk for error messages
7277and debug information (see <a href="#4.9">&sect;4.9</a>).
7278When absent,
7279it defaults to <code>ld</code>, if <code>ld</code> is a string,
7280or to "<code>=(load)</code>" otherwise.
7281
7282
7283<p>
7284The string <code>mode</code> controls whether the chunk can be text or binary
7285(that is, a precompiled chunk).
7286It may be the string "<code>b</code>" (only binary chunks),
7287"<code>t</code>" (only text chunks),
7288or "<code>bt</code>" (both binary and text).
7289The default is "<code>bt</code>".
7290
7291
7292<p>
7293Lua does not check the consistency of binary chunks.
7294Maliciously crafted binary chunks can crash
7295the interpreter.
7296
7297
7298
7299
7300<p>
7301<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
7302
7303
7304<p>
7305Similar to <a href="#pdf-load"><code>load</code></a>,
7306but gets the chunk from file <code>filename</code>
7307or from the standard input,
7308if no file name is given.
7309
7310
7311
7312
7313<p>
7314<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
7315
7316
7317<p>
7318Allows a program to traverse all fields of a table.
7319Its first argument is a table and its second argument
7320is an index in this table.
7321<code>next</code> returns the next index of the table
7322and its associated value.
7323When called with <b>nil</b> as its second argument,
7324<code>next</code> returns an initial index
7325and its associated value.
7326When called with the last index,
7327or with <b>nil</b> in an empty table,
7328<code>next</code> returns <b>nil</b>.
7329If the second argument is absent, then it is interpreted as <b>nil</b>.
7330In particular,
7331you can use <code>next(t)</code> to check whether a table is empty.
7332
7333
7334<p>
7335The order in which the indices are enumerated is not specified,
7336<em>even for numeric indices</em>.
7337(To traverse a table in numeric order,
7338use a numerical <b>for</b>.)
7339
7340
7341<p>
7342The behavior of <code>next</code> is undefined if,
7343during the traversal,
7344you assign any value to a non-existent field in the table.
7345You may however modify existing fields.
7346In particular, you may clear existing fields.
7347
7348
7349
7350
7351<p>
7352<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
7353
7354
7355<p>
7356If <code>t</code> has a metamethod <code>__pairs</code>,
7357calls it with <code>t</code> as argument and returns the first three
7358results from the call.
7359
7360
7361<p>
7362Otherwise,
7363returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
7364so that the construction
7365
7366<pre>
7367     for k,v in pairs(t) do <em>body</em> end
7368</pre><p>
7369will iterate over all key&ndash;value pairs of table <code>t</code>.
7370
7371
7372<p>
7373See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
7374the table during its traversal.
7375
7376
7377
7378
7379<p>
7380<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
7381
7382
7383<p>
7384Calls function <code>f</code> with
7385the given arguments in <em>protected mode</em>.
7386This means that any error inside&nbsp;<code>f</code> is not propagated;
7387instead, <code>pcall</code> catches the error
7388and returns a status code.
7389Its first result is the status code (a boolean),
7390which is true if the call succeeds without errors.
7391In such case, <code>pcall</code> also returns all results from the call,
7392after this first result.
7393In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
7394
7395
7396
7397
7398<p>
7399<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
7400Receives any number of arguments
7401and prints their values to <code>stdout</code>,
7402using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string.
7403<code>print</code> is not intended for formatted output,
7404but only as a quick way to show a value,
7405for instance for debugging.
7406For complete control over the output,
7407use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
7408
7409
7410
7411
7412<p>
7413<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
7414Checks whether <code>v1</code> is equal to <code>v2</code>,
7415without invoking any metamethod.
7416Returns a boolean.
7417
7418
7419
7420
7421<p>
7422<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
7423Gets the real value of <code>table[index]</code>,
7424without invoking any metamethod.
7425<code>table</code> must be a table;
7426<code>index</code> may be any value.
7427
7428
7429
7430
7431<p>
7432<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
7433Returns the length of the object <code>v</code>,
7434which must be a table or a string,
7435without invoking any metamethod.
7436Returns an integer.
7437
7438
7439
7440
7441<p>
7442<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
7443Sets the real value of <code>table[index]</code> to <code>value</code>,
7444without invoking any metamethod.
7445<code>table</code> must be a table,
7446<code>index</code> any value different from <b>nil</b> and NaN,
7447and <code>value</code> any Lua value.
7448
7449
7450<p>
7451This function returns <code>table</code>.
7452
7453
7454
7455
7456<p>
7457<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
7458
7459
7460<p>
7461If <code>index</code> is a number,
7462returns all arguments after argument number <code>index</code>;
7463a negative number indexes from the end (-1 is the last argument).
7464Otherwise, <code>index</code> must be the string <code>"#"</code>,
7465and <code>select</code> returns the total number of extra arguments it received.
7466
7467
7468
7469
7470<p>
7471<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
7472
7473
7474<p>
7475Sets the metatable for the given table.
7476(You cannot change the metatable of other types from Lua, only from&nbsp;C.)
7477If <code>metatable</code> is <b>nil</b>,
7478removes the metatable of the given table.
7479If the original metatable has a <code>"__metatable"</code> field,
7480raises an error.
7481
7482
7483<p>
7484This function returns <code>table</code>.
7485
7486
7487
7488
7489<p>
7490<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
7491
7492
7493<p>
7494When called with no <code>base</code>,
7495<code>tonumber</code> tries to convert its argument to a number.
7496If the argument is already a number or
7497a string convertible to a number,
7498then <code>tonumber</code> returns this number;
7499otherwise, it returns <b>nil</b>.
7500
7501
7502<p>
7503The conversion of strings can result in integers or floats,
7504according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
7505(The string may have leading and trailing spaces and a sign.)
7506
7507
7508<p>
7509When called with <code>base</code>,
7510then <code>e</code> must be a string to be interpreted as
7511an integer numeral in that base.
7512The base may be any integer between 2 and 36, inclusive.
7513In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
7514represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
7515with '<code>Z</code>' representing 35.
7516If the string <code>e</code> is not a valid numeral in the given base,
7517the function returns <b>nil</b>.
7518
7519
7520
7521
7522<p>
7523<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
7524Receives a value of any type and
7525converts it to a string in a human-readable format.
7526Floats always produce strings with some
7527floating-point indication (either a decimal dot or an exponent).
7528(For complete control of how numbers are converted,
7529use <a href="#pdf-string.format"><code>string.format</code></a>.)
7530
7531
7532<p>
7533If the metatable of <code>v</code> has a <code>"__tostring"</code> field,
7534then <code>tostring</code> calls the corresponding value
7535with <code>v</code> as argument,
7536and uses the result of the call as its result.
7537
7538
7539
7540
7541<p>
7542<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
7543Returns the type of its only argument, coded as a string.
7544The possible results of this function are
7545"<code>nil</code>" (a string, not the value <b>nil</b>),
7546"<code>number</code>",
7547"<code>string</code>",
7548"<code>boolean</code>",
7549"<code>table</code>",
7550"<code>function</code>",
7551"<code>thread</code>",
7552and "<code>userdata</code>".
7553
7554
7555
7556
7557<p>
7558<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
7559A global variable (not a function) that
7560holds a string containing the current interpreter version.
7561The current value of this variable is "<code>Lua 5.3</code>".
7562
7563
7564
7565
7566<p>
7567<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
7568
7569
7570<p>
7571This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
7572except that it sets a new message handler <code>msgh</code>.
7573
7574
7575
7576
7577
7578
7579
7580<h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
7581
7582<p>
7583The operations related to coroutines comprise a sub-library of
7584the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
7585See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
7586
7587
7588<p>
7589<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
7590
7591
7592<p>
7593Creates a new coroutine, with body <code>f</code>.
7594<code>f</code> must be a Lua function.
7595Returns this new coroutine,
7596an object with type <code>"thread"</code>.
7597
7598
7599
7600
7601<p>
7602<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3>
7603
7604
7605<p>
7606Returns true when the running coroutine can yield.
7607
7608
7609<p>
7610A running coroutine is yieldable if it is not the main thread and
7611it is not inside a non-yieldable C function.
7612
7613
7614
7615
7616<p>
7617<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
7618
7619
7620<p>
7621Starts or continues the execution of coroutine <code>co</code>.
7622The first time you resume a coroutine,
7623it starts running its body.
7624The values <code>val1</code>, ... are passed
7625as the arguments to the body function.
7626If the coroutine has yielded,
7627<code>resume</code> restarts it;
7628the values <code>val1</code>, ... are passed
7629as the results from the yield.
7630
7631
7632<p>
7633If the coroutine runs without any errors,
7634<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
7635(when the coroutine yields) or any values returned by the body function
7636(when the coroutine terminates).
7637If there is any error,
7638<code>resume</code> returns <b>false</b> plus the error message.
7639
7640
7641
7642
7643<p>
7644<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
7645
7646
7647<p>
7648Returns the running coroutine plus a boolean,
7649true when the running coroutine is the main one.
7650
7651
7652
7653
7654<p>
7655<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
7656
7657
7658<p>
7659Returns the status of coroutine <code>co</code>, as a string:
7660<code>"running"</code>,
7661if the coroutine is running (that is, it called <code>status</code>);
7662<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
7663or if it has not started running yet;
7664<code>"normal"</code> if the coroutine is active but not running
7665(that is, it has resumed another coroutine);
7666and <code>"dead"</code> if the coroutine has finished its body function,
7667or if it has stopped with an error.
7668
7669
7670
7671
7672<p>
7673<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
7674
7675
7676<p>
7677Creates a new coroutine, with body <code>f</code>.
7678<code>f</code> must be a Lua function.
7679Returns a function that resumes the coroutine each time it is called.
7680Any arguments passed to the function behave as the
7681extra arguments to <code>resume</code>.
7682Returns the same values returned by <code>resume</code>,
7683except the first boolean.
7684In case of error, propagates the error.
7685
7686
7687
7688
7689<p>
7690<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
7691
7692
7693<p>
7694Suspends the execution of the calling coroutine.
7695Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
7696
7697
7698
7699
7700
7701
7702
7703<h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
7704
7705<p>
7706The package library provides basic
7707facilities for loading modules in Lua.
7708It exports one function directly in the global environment:
7709<a href="#pdf-require"><code>require</code></a>.
7710Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
7711
7712
7713<p>
7714<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
7715
7716
7717<p>
7718Loads the given module.
7719The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
7720to determine whether <code>modname</code> is already loaded.
7721If it is, then <code>require</code> returns the value stored
7722at <code>package.loaded[modname]</code>.
7723Otherwise, it tries to find a <em>loader</em> for the module.
7724
7725
7726<p>
7727To find a loader,
7728<code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence.
7729By changing this sequence,
7730we can change how <code>require</code> looks for a module.
7731The following explanation is based on the default configuration
7732for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
7733
7734
7735<p>
7736First <code>require</code> queries <code>package.preload[modname]</code>.
7737If it has a value,
7738this value (which must be a function) is the loader.
7739Otherwise <code>require</code> searches for a Lua loader using the
7740path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
7741If that also fails, it searches for a C&nbsp;loader using the
7742path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7743If that also fails,
7744it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
7745
7746
7747<p>
7748Once a loader is found,
7749<code>require</code> calls the loader with two arguments:
7750<code>modname</code> and an extra value dependent on how it got the loader.
7751(If the loader came from a file,
7752this extra value is the file name.)
7753If the loader returns any non-nil value,
7754<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
7755If the loader does not return a non-nil value and
7756has not assigned any value to <code>package.loaded[modname]</code>,
7757then <code>require</code> assigns <b>true</b> to this entry.
7758In any case, <code>require</code> returns the
7759final value of <code>package.loaded[modname]</code>.
7760
7761
7762<p>
7763If there is any error loading or running the module,
7764or if it cannot find any loader for the module,
7765then <code>require</code> raises an error.
7766
7767
7768
7769
7770<p>
7771<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
7772
7773
7774<p>
7775A string describing some compile-time configurations for packages.
7776This string is a sequence of lines:
7777
7778<ul>
7779
7780<li>The first line is the directory separator string.
7781Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
7782
7783<li>The second line is the character that separates templates in a path.
7784Default is '<code>;</code>'.</li>
7785
7786<li>The third line is the string that marks the
7787substitution points in a template.
7788Default is '<code>?</code>'.</li>
7789
7790<li>The fourth line is a string that, in a path in Windows,
7791is replaced by the executable's directory.
7792Default is '<code>!</code>'.</li>
7793
7794<li>The fifth line is a mark to ignore all text before it
7795when building the <code>luaopen_</code> function name.
7796Default is '<code>-</code>'.</li>
7797
7798</ul>
7799
7800
7801
7802<p>
7803<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
7804
7805
7806<p>
7807The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
7808
7809
7810<p>
7811Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
7812it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7813using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a>
7814or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
7815or a default path defined in <code>luaconf.h</code>.
7816
7817
7818
7819
7820<p>
7821<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
7822
7823
7824<p>
7825A table used by <a href="#pdf-require"><code>require</code></a> to control which
7826modules are already loaded.
7827When you require a module <code>modname</code> and
7828<code>package.loaded[modname]</code> is not false,
7829<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
7830
7831
7832<p>
7833This variable is only a reference to the real table;
7834assignments to this variable do not change the
7835table used by <a href="#pdf-require"><code>require</code></a>.
7836
7837
7838
7839
7840<p>
7841<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
7842
7843
7844<p>
7845Dynamically links the host program with the C&nbsp;library <code>libname</code>.
7846
7847
7848<p>
7849If <code>funcname</code> is "<code>*</code>",
7850then it only links with the library,
7851making the symbols exported by the library
7852available to other dynamically linked libraries.
7853Otherwise,
7854it looks for a function <code>funcname</code> inside the library
7855and returns this function as a C&nbsp;function.
7856So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
7857(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
7858
7859
7860<p>
7861This is a low-level function.
7862It completely bypasses the package and module system.
7863Unlike <a href="#pdf-require"><code>require</code></a>,
7864it does not perform any path searching and
7865does not automatically adds extensions.
7866<code>libname</code> must be the complete file name of the C&nbsp;library,
7867including if necessary a path and an extension.
7868<code>funcname</code> must be the exact name exported by the C&nbsp;library
7869(which may depend on the C&nbsp;compiler and linker used).
7870
7871
7872<p>
7873This function is not supported by Standard&nbsp;C.
7874As such, it is only available on some platforms
7875(Windows, Linux, Mac OS X, Solaris, BSD,
7876plus other Unix systems that support the <code>dlfcn</code> standard).
7877
7878
7879
7880
7881<p>
7882<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
7883
7884
7885<p>
7886The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
7887
7888
7889<p>
7890At start-up, Lua initializes this variable with
7891the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or
7892the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
7893with a default path defined in <code>luaconf.h</code>,
7894if those environment variables are not defined.
7895Any "<code>;;</code>" in the value of the environment variable
7896is replaced by the default path.
7897
7898
7899
7900
7901<p>
7902<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
7903
7904
7905<p>
7906A table to store loaders for specific modules
7907(see <a href="#pdf-require"><code>require</code></a>).
7908
7909
7910<p>
7911This variable is only a reference to the real table;
7912assignments to this variable do not change the
7913table used by <a href="#pdf-require"><code>require</code></a>.
7914
7915
7916
7917
7918<p>
7919<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
7920
7921
7922<p>
7923A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
7924
7925
7926<p>
7927Each entry in this table is a <em>searcher function</em>.
7928When looking for a module,
7929<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
7930with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
7931sole parameter.
7932The function can return another function (the module <em>loader</em>)
7933plus an extra value that will be passed to that loader,
7934or a string explaining why it did not find that module
7935(or <b>nil</b> if it has nothing to say).
7936
7937
7938<p>
7939Lua initializes this table with four searcher functions.
7940
7941
7942<p>
7943The first searcher simply looks for a loader in the
7944<a href="#pdf-package.preload"><code>package.preload</code></a> table.
7945
7946
7947<p>
7948The second searcher looks for a loader as a Lua library,
7949using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
7950The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7951
7952
7953<p>
7954The third searcher looks for a loader as a C&nbsp;library,
7955using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7956Again,
7957the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7958For instance,
7959if the C&nbsp;path is the string
7960
7961<pre>
7962     "./?.so;./?.dll;/usr/local/?/init.so"
7963</pre><p>
7964the searcher for module <code>foo</code>
7965will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
7966and <code>/usr/local/foo/init.so</code>, in that order.
7967Once it finds a C&nbsp;library,
7968this searcher first uses a dynamic link facility to link the
7969application with the library.
7970Then it tries to find a C&nbsp;function inside the library to
7971be used as the loader.
7972The name of this C&nbsp;function is the string "<code>luaopen_</code>"
7973concatenated with a copy of the module name where each dot
7974is replaced by an underscore.
7975Moreover, if the module name has a hyphen,
7976its prefix up to (and including) the first hyphen is removed.
7977For instance, if the module name is <code>a.v1-b.c</code>,
7978the function name will be <code>luaopen_b_c</code>.
7979
7980
7981<p>
7982The fourth searcher tries an <em>all-in-one loader</em>.
7983It searches the C&nbsp;path for a library for
7984the root name of the given module.
7985For instance, when requiring <code>a.b.c</code>,
7986it will search for a C&nbsp;library for <code>a</code>.
7987If found, it looks into it for an open function for
7988the submodule;
7989in our example, that would be <code>luaopen_a_b_c</code>.
7990With this facility, a package can pack several C&nbsp;submodules
7991into one single library,
7992with each submodule keeping its original open function.
7993
7994
7995<p>
7996All searchers except the first one (preload) return as the extra value
7997the file name where the module was found,
7998as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7999The first searcher returns no extra value.
8000
8001
8002
8003
8004<p>
8005<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
8006
8007
8008<p>
8009Searches for the given <code>name</code> in the given <code>path</code>.
8010
8011
8012<p>
8013A path is a string containing a sequence of
8014<em>templates</em> separated by semicolons.
8015For each template,
8016the function replaces each interrogation mark (if any)
8017in the template with a copy of <code>name</code>
8018wherein all occurrences of <code>sep</code>
8019(a dot, by default)
8020were replaced by <code>rep</code>
8021(the system's directory separator, by default),
8022and then tries to open the resulting file name.
8023
8024
8025<p>
8026For instance, if the path is the string
8027
8028<pre>
8029     "./?.lua;./?.lc;/usr/local/?/init.lua"
8030</pre><p>
8031the search for the name <code>foo.a</code>
8032will try to open the files
8033<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
8034<code>/usr/local/foo/a/init.lua</code>, in that order.
8035
8036
8037<p>
8038Returns the resulting name of the first file that it can
8039open in read mode (after closing the file),
8040or <b>nil</b> plus an error message if none succeeds.
8041(This error message lists all file names it tried to open.)
8042
8043
8044
8045
8046
8047
8048
8049<h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
8050
8051<p>
8052This library provides generic functions for string manipulation,
8053such as finding and extracting substrings, and pattern matching.
8054When indexing a string in Lua, the first character is at position&nbsp;1
8055(not at&nbsp;0, as in C).
8056Indices are allowed to be negative and are interpreted as indexing backwards,
8057from the end of the string.
8058Thus, the last character is at position -1, and so on.
8059
8060
8061<p>
8062The string library provides all its functions inside the table
8063<a name="pdf-string"><code>string</code></a>.
8064It also sets a metatable for strings
8065where the <code>__index</code> field points to the <code>string</code> table.
8066Therefore, you can use the string functions in object-oriented style.
8067For instance, <code>string.byte(s,i)</code>
8068can be written as <code>s:byte(i)</code>.
8069
8070
8071<p>
8072The string library assumes one-byte character encodings.
8073
8074
8075<p>
8076<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
8077Returns the internal numerical codes of the characters <code>s[i]</code>,
8078<code>s[i+1]</code>, ..., <code>s[j]</code>.
8079The default value for <code>i</code> is&nbsp;1;
8080the default value for <code>j</code> is&nbsp;<code>i</code>.
8081These indices are corrected
8082following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
8083
8084
8085<p>
8086Numerical codes are not necessarily portable across platforms.
8087
8088
8089
8090
8091<p>
8092<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
8093Receives zero or more integers.
8094Returns a string with length equal to the number of arguments,
8095in which each character has the internal numerical code equal
8096to its corresponding argument.
8097
8098
8099<p>
8100Numerical codes are not necessarily portable across platforms.
8101
8102
8103
8104
8105<p>
8106<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
8107
8108
8109<p>
8110Returns a string containing a binary representation
8111(a <em>binary chunk</em>)
8112of the given function,
8113so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
8114a copy of the function (but with new upvalues).
8115If <code>strip</code> is a true value,
8116the binary representation is created without debug information
8117about the function
8118(local variable names, lines, etc.).
8119
8120
8121
8122
8123<p>
8124<hr><h3><a name="pdf-string.dumpfloat"><code>string.dumpfloat (n [, size [, endianness]])</code></a></h3>
8125Returns a string with the machine representation of float <code>n</code>,
8126with given size and endianness.
8127The <code>size</code> is the string "<code>f</code>" (single precision),
8128"<code>d</code>" (double precision), or "<code>n</code>",
8129which means the size of a <a href="#lua_Number"><code>lua_Number</code></a>;
8130its default is "<code>n</code>".
8131The endianness is the string "<code>l</code>" (little endian), "<code>b</code>" (big endian),
8132or "<code>n</code>" (native);
8133the default is the native endianness.
8134
8135
8136<p>
8137This function may not work correctly in architectures
8138with mixed endian.
8139
8140
8141<p>
8142<hr><h3><a name="pdf-string.dumpint"><code>string.dumpint (n [, size [, endianness]])</code></a></h3>
8143Returns a string with the two-complement representation of integer <code>n</code>,
8144with <code>size</code> bytes and given endianness.
8145The <code>size</code> can be any value from 1 to 12,
8146or 0, which means the size of a <a href="#lua_Integer"><code>lua_Integer</code></a>
8147(8 bytes in standard Lua);
8148its default is zero.
8149The endianness is the string "<code>l</code>" (little endian), "<code>b</code>" (big endian),
8150or "<code>n</code>" (native);
8151the default is the native endianness.
8152
8153
8154<p>
8155This function may not work correctly in architectures
8156with mixed endian or
8157that do not use a two-complement representation for integers.
8158
8159
8160
8161
8162<p>
8163<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
8164
8165
8166<p>
8167Looks for the first match of
8168<code>pattern</code> in the string <code>s</code>.
8169If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
8170where this occurrence starts and ends;
8171otherwise, it returns <b>nil</b>.
8172A third, optional numerical argument <code>init</code> specifies
8173where to start the search;
8174its default value is&nbsp;1 and can be negative.
8175A value of <b>true</b> as a fourth, optional argument <code>plain</code>
8176turns off the pattern matching facilities,
8177so the function does a plain "find substring" operation,
8178with no characters in <code>pattern</code> being considered magic.
8179Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
8180
8181
8182<p>
8183If the pattern has captures,
8184then in a successful match
8185the captured values are also returned,
8186after the two indices.
8187
8188
8189
8190
8191<p>
8192<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
8193
8194
8195<p>
8196Returns a formatted version of its variable number of arguments
8197following the description given in its first argument (which must be a string).
8198The format string follows the same rules as the ANSI&nbsp;C function <code>sprintf</code>.
8199The only differences are that the options/modifiers
8200<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
8201and <code>p</code> are not supported
8202and that there is an extra option, <code>q</code>.
8203The <code>q</code> option formats a string between double quotes,
8204using escape sequences when necessary to ensure that
8205it can safely be read back by the Lua interpreter.
8206For instance, the call
8207
8208<pre>
8209     string.format('%q', 'a string with "quotes" and \n new line')
8210</pre><p>
8211may produce the string:
8212
8213<pre>
8214     "a string with \"quotes\" and \
8215      new line"
8216</pre>
8217
8218<p>
8219Options
8220<code>A</code> and <code>a</code> (when available),
8221<code>E</code>, <code>e</code>, <code>f</code>,
8222<code>G</code>, and <code>g</code> all expect a number as argument.
8223Options <code>c</code>, <code>d</code>,
8224<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
8225expect an integer.
8226Option <code>q</code> expects a string;
8227option <code>s</code> expects a string without embedded zeros.
8228If the argument to option <code>s</code> is not a string,
8229it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
8230
8231
8232
8233
8234<p>
8235<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
8236Returns an iterator function that,
8237each time it is called,
8238returns the next captures from <code>pattern</code> over the string <code>s</code>.
8239If <code>pattern</code> specifies no captures,
8240then the whole match is produced in each call.
8241
8242
8243<p>
8244As an example, the following loop
8245will iterate over all the words from string <code>s</code>,
8246printing one per line:
8247
8248<pre>
8249     s = "hello world from Lua"
8250     for w in string.gmatch(s, "%a+") do
8251       print(w)
8252     end
8253</pre><p>
8254The next example collects all pairs <code>key=value</code> from the
8255given string into a table:
8256
8257<pre>
8258     t = {}
8259     s = "from=world, to=Lua"
8260     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
8261       t[k] = v
8262     end
8263</pre>
8264
8265<p>
8266For this function, a caret '<code>^</code>' at the start of a pattern does not
8267work as an anchor, as this would prevent the iteration.
8268
8269
8270
8271
8272<p>
8273<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
8274Returns a copy of <code>s</code>
8275in which all (or the first <code>n</code>, if given)
8276occurrences of the <code>pattern</code> have been
8277replaced by a replacement string specified by <code>repl</code>,
8278which can be a string, a table, or a function.
8279<code>gsub</code> also returns, as its second value,
8280the total number of matches that occurred.
8281The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
8282
8283
8284<p>
8285If <code>repl</code> is a string, then its value is used for replacement.
8286The character&nbsp;<code>%</code> works as an escape character:
8287any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
8288with <em>d</em> between 1 and 9,
8289stands for the value of the <em>d</em>-th captured substring.
8290The sequence <code>%0</code> stands for the whole match.
8291The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
8292
8293
8294<p>
8295If <code>repl</code> is a table, then the table is queried for every match,
8296using the first capture as the key.
8297
8298
8299<p>
8300If <code>repl</code> is a function, then this function is called every time a
8301match occurs, with all captured substrings passed as arguments,
8302in order.
8303
8304
8305<p>
8306In any case,
8307if the pattern specifies no captures,
8308then it behaves as if the whole pattern was inside a capture.
8309
8310
8311<p>
8312If the value returned by the table query or by the function call
8313is a string or a number,
8314then it is used as the replacement string;
8315otherwise, if it is <b>false</b> or <b>nil</b>,
8316then there is no replacement
8317(that is, the original match is kept in the string).
8318
8319
8320<p>
8321Here are some examples:
8322
8323<pre>
8324     x = string.gsub("hello world", "(%w+)", "%1 %1")
8325     --&gt; x="hello hello world world"
8326
8327     x = string.gsub("hello world", "%w+", "%0 %0", 1)
8328     --&gt; x="hello hello world"
8329
8330     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
8331     --&gt; x="world hello Lua from"
8332
8333     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
8334     --&gt; x="home = /home/roberto, user = roberto"
8335
8336     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
8337           return load(s)()
8338         end)
8339     --&gt; x="4+5 = 9"
8340
8341     local t = {name="lua", version="5.3"}
8342     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8343     --&gt; x="lua-5.3.tar.gz"
8344</pre>
8345
8346
8347
8348<p>
8349<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
8350Receives a string and returns its length.
8351The empty string <code>""</code> has length 0.
8352Embedded zeros are counted,
8353so <code>"a\000bc\000"</code> has length 5.
8354
8355
8356
8357
8358<p>
8359<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
8360Receives a string and returns a copy of this string with all
8361uppercase letters changed to lowercase.
8362All other characters are left unchanged.
8363The definition of what an uppercase letter is depends on the current locale.
8364
8365
8366
8367
8368<p>
8369<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
8370Looks for the first <em>match</em> of
8371<code>pattern</code> in the string <code>s</code>.
8372If it finds one, then <code>match</code> returns
8373the captures from the pattern;
8374otherwise it returns <b>nil</b>.
8375If <code>pattern</code> specifies no captures,
8376then the whole match is returned.
8377A third, optional numerical argument <code>init</code> specifies
8378where to start the search;
8379its default value is&nbsp;1 and can be negative.
8380
8381
8382
8383
8384<p>
8385<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
8386Returns a string that is the concatenation of <code>n</code> copies of
8387the string <code>s</code> separated by the string <code>sep</code>.
8388The default value for <code>sep</code> is the empty string
8389(that is, no separator).
8390
8391
8392
8393
8394<p>
8395<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
8396Returns a string that is the string <code>s</code> reversed.
8397
8398
8399
8400
8401<p>
8402<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
8403Returns the substring of <code>s</code> that
8404starts at <code>i</code>  and continues until <code>j</code>;
8405<code>i</code> and <code>j</code> can be negative.
8406If <code>j</code> is absent, then it is assumed to be equal to -1
8407(which is the same as the string length).
8408In particular,
8409the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
8410with length <code>j</code>,
8411and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
8412with length <code>i</code>.
8413
8414
8415<p>
8416If, after the translation of negative indices,
8417<code>i</code> is less than 1,
8418it is corrected to 1.
8419If <code>j</code> is greater than the string length,
8420it is corrected to that length.
8421If, after these corrections,
8422<code>i</code> is greater than <code>j</code>,
8423the function returns the empty string.
8424
8425
8426
8427
8428<p>
8429<hr><h3><a name="pdf-string.undumpfloat"><code>string.undumpfloat (s [, pos [, size [, endianness]]])</code></a></h3>
8430Reads the machine representation of a float starting at position
8431<code>pos</code> in string <code>s</code> and returns that number.
8432See <a href="#pdf-string.dumpfloat"><code>string.dumpfloat</code></a> for details about <code>size</code> and <code>endianness</code>.
8433
8434
8435
8436
8437<p>
8438<hr><h3><a name="pdf-string.undumpint"><code>string.undumpint (s [, pos [, size [, endianness]]])</code></a></h3>
8439Reads the machine representation of an integer starting at position
8440<code>pos</code> in string <code>s</code> and returns that integer.
8441See <a href="#pdf-string.dumpint"><code>string.dumpint</code></a> for details about <code>size</code> and <code>endianness</code>.
8442
8443
8444<p>
8445Integers are always read as signed.
8446
8447
8448
8449
8450<p>
8451<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
8452Receives a string and returns a copy of this string with all
8453lowercase letters changed to uppercase.
8454All other characters are left unchanged.
8455The definition of what a lowercase letter is depends on the current locale.
8456
8457
8458
8459<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
8460
8461
8462<h4>Character Class:</h4><p>
8463A <em>character class</em> is used to represent a set of characters.
8464The following combinations are allowed in describing a character class:
8465
8466<ul>
8467
8468<li><b><em>x</em>: </b>
8469(where <em>x</em> is not one of the <em>magic characters</em>
8470<code>^$()%.[]*+-?</code>)
8471represents the character <em>x</em> itself.
8472</li>
8473
8474<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
8475
8476<li><b><code>%a</code>: </b> represents all letters.</li>
8477
8478<li><b><code>%c</code>: </b> represents all control characters.</li>
8479
8480<li><b><code>%d</code>: </b> represents all digits.</li>
8481
8482<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
8483
8484<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
8485
8486<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
8487
8488<li><b><code>%s</code>: </b> represents all space characters.</li>
8489
8490<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
8491
8492<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
8493
8494<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
8495
8496<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
8497represents the character <em>x</em>.
8498This is the standard way to escape the magic characters.
8499Any punctuation character (even the non magic)
8500can be preceded by a '<code>%</code>'
8501when used to represent itself in a pattern.
8502</li>
8503
8504<li><b><code>[<em>set</em>]</code>: </b>
8505represents the class which is the union of all
8506characters in <em>set</em>.
8507A range of characters can be specified by
8508separating the end characters of the range,
8509in ascending order, with a '<code>-</code>'.
8510All classes <code>%</code><em>x</em> described above can also be used as
8511components in <em>set</em>.
8512All other characters in <em>set</em> represent themselves.
8513For example, <code>[%w_]</code> (or <code>[_%w]</code>)
8514represents all alphanumeric characters plus the underscore,
8515<code>[0-7]</code> represents the octal digits,
8516and <code>[0-7%l%-]</code> represents the octal digits plus
8517the lowercase letters plus the '<code>-</code>' character.
8518
8519
8520<p>
8521The interaction between ranges and classes is not defined.
8522Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
8523have no meaning.
8524</li>
8525
8526<li><b><code>[^<em>set</em>]</code>: </b>
8527represents the complement of <em>set</em>,
8528where <em>set</em> is interpreted as above.
8529</li>
8530
8531</ul><p>
8532For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
8533the corresponding uppercase letter represents the complement of the class.
8534For instance, <code>%S</code> represents all non-space characters.
8535
8536
8537<p>
8538The definitions of letter, space, and other character groups
8539depend on the current locale.
8540In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
8541
8542
8543
8544
8545
8546<h4>Pattern Item:</h4><p>
8547A <em>pattern item</em> can be
8548
8549<ul>
8550
8551<li>
8552a single character class,
8553which matches any single character in the class;
8554</li>
8555
8556<li>
8557a single character class followed by '<code>*</code>',
8558which matches 0 or more repetitions of characters in the class.
8559These repetition items will always match the longest possible sequence;
8560</li>
8561
8562<li>
8563a single character class followed by '<code>+</code>',
8564which matches 1 or more repetitions of characters in the class.
8565These repetition items will always match the longest possible sequence;
8566</li>
8567
8568<li>
8569a single character class followed by '<code>-</code>',
8570which also matches 0 or more repetitions of characters in the class.
8571Unlike '<code>*</code>',
8572these repetition items will always match the shortest possible sequence;
8573</li>
8574
8575<li>
8576a single character class followed by '<code>?</code>',
8577which matches 0 or 1 occurrence of a character in the class;
8578</li>
8579
8580<li>
8581<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
8582such item matches a substring equal to the <em>n</em>-th captured string
8583(see below);
8584</li>
8585
8586<li>
8587<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
8588such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
8589and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
8590This means that, if one reads the string from left to right,
8591counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
8592the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
8593For instance, the item <code>%b()</code> matches expressions with
8594balanced parentheses.
8595</li>
8596
8597<li>
8598<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
8599such item matches an empty string at any position such that
8600the next character belongs to <em>set</em>
8601and the previous character does not belong to <em>set</em>.
8602The set <em>set</em> is interpreted as previously described.
8603The beginning and the end of the subject are handled as if
8604they were the character '<code>\0</code>'.
8605</li>
8606
8607</ul>
8608
8609
8610
8611
8612<h4>Pattern:</h4><p>
8613A <em>pattern</em> is a sequence of pattern items.
8614A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
8615beginning of the subject string.
8616A '<code>$</code>' at the end of a pattern anchors the match at the
8617end of the subject string.
8618At other positions,
8619'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
8620
8621
8622
8623
8624
8625<h4>Captures:</h4><p>
8626A pattern can contain sub-patterns enclosed in parentheses;
8627they describe <em>captures</em>.
8628When a match succeeds, the substrings of the subject string
8629that match captures are stored (<em>captured</em>) for future use.
8630Captures are numbered according to their left parentheses.
8631For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
8632the part of the string matching <code>"a*(.)%w(%s*)"</code> is
8633stored as the first capture (and therefore has number&nbsp;1);
8634the character matching "<code>.</code>" is captured with number&nbsp;2,
8635and the part matching "<code>%s*</code>" has number&nbsp;3.
8636
8637
8638<p>
8639As a special case, the empty capture <code>()</code> captures
8640the current string position (a number).
8641For instance, if we apply the pattern <code>"()aa()"</code> on the
8642string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654<h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
8655
8656<p>
8657This library provides basic support for UTF-8 encoding.
8658It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
8659This library does not provide any support for Unicode other
8660than the handling of the encoding.
8661Any operation that needs the meaning of a character,
8662such as character classification, is outside its scope.
8663
8664
8665<p>
8666Unless stated otherwise,
8667all functions that expect a byte position as a parameter
8668assume that the given position is either the start of a byte sequence
8669or one plus the length of the subject string.
8670As in the string library,
8671negative indices count from the end of the string.
8672
8673
8674<p>
8675<hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
8676Receives zero or more integers,
8677converts each one to its corresponding UTF-8 byte sequence
8678and returns a string with the concatenation of all these sequences.
8679
8680
8681
8682
8683<p>
8684<hr><h3><a name="pdf-utf8.charpatt"><code>utf8.charpatt</code></a></h3>
8685The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>"
8686(see <a href="#6.4.1">&sect;6.4.1</a>),
8687which matches exactly one UTF-8 byte sequence,
8688assuming that the subject is a valid UTF-8 string.
8689
8690
8691
8692
8693<p>
8694<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3>
8695
8696
8697<p>
8698Returns values so that the construction
8699
8700<pre>
8701     for p, c in utf8.codes(s) do <em>body</em> end
8702</pre><p>
8703will iterate over all characters in string <code>s</code>,
8704with <code>p</code> being the position (in bytes) and <code>c</code> the code point
8705of each character.
8706It raises an error if it meets any invalid byte sequence.
8707
8708
8709
8710
8711<p>
8712<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3>
8713Returns the codepoints (as integers) from all characters in <code>s</code>
8714that start between byte position <code>i</code> and <code>j</code> (both included).
8715The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
8716It raises an error if it meets any invalid byte sequence.
8717
8718
8719
8720
8721<p>
8722<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3>
8723Returns the number of UTF-8 characters in string <code>s</code>
8724that start between positions <code>i</code> and @{j} (both inclusive).
8725The default for <code>i</code> is 1 and for <code>j</code> is -1.
8726If it finds any invalid byte sequence,
8727returns <b>nil</b> plus the position of the first invalid byte.
8728
8729
8730
8731
8732<p>
8733<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
8734Returns the position (in bytes) where the encoding of the
8735<code>n</code>-th character of <code>s</code>
8736(counting from position <code>i</code>) starts.
8737A negative <code>n</code> gets characters before position <code>i</code>.
8738The default for <code>i</code> is 1 when <code>n</code> is non-negative
8739and <code>#s + 1</code> otherwise,
8740so that <code>utf8.offset(s, -n)</code> gets the offset of the
8741<code>n</code>-th character from the end of the string.
8742If the specified character is not in the subject
8743or right after its end,
8744the function returns <b>nil</b>.
8745
8746
8747<p>
8748As a special case,
8749when <code>n</code> is 0 the function returns the start of the encoding
8750of the character that contains the <code>i</code>-th byte of <code>s</code>.
8751
8752
8753<p>
8754This function assumes that <code>s</code> is a valid UTF-8 string.
8755
8756
8757
8758
8759
8760
8761
8762<h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
8763
8764<p>
8765This library provides generic functions for table manipulation.
8766It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
8767
8768
8769<p>
8770Remember that, whenever an operation needs the length of a table,
8771the table must be a proper sequence
8772or have a <code>__len</code> metamethod (see <a href="#3.4.7">&sect;3.4.7</a>).
8773All functions ignore non-numeric keys
8774in tables given as arguments.
8775
8776
8777<p>
8778For performance reasons,
8779all table accesses (get/set) performed by these functions are raw.
8780
8781
8782<p>
8783<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
8784
8785
8786<p>
8787Given a list where all elements are strings or numbers,
8788returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
8789The default value for <code>sep</code> is the empty string,
8790the default for <code>i</code> is 1,
8791and the default for <code>j</code> is <code>#list</code>.
8792If <code>i</code> is greater than <code>j</code>, returns the empty string.
8793
8794
8795
8796
8797<p>
8798<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
8799
8800
8801<p>
8802Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
8803shifting up the elements
8804<code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
8805The default value for <code>pos</code> is <code>#list+1</code>,
8806so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
8807of list <code>t</code>.
8808
8809
8810
8811
8812<p>
8813<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
8814
8815
8816<p>
8817Returns a new table with all parameters stored into keys 1, 2, etc.
8818and with a field "<code>n</code>" with the total number of parameters.
8819Note that the resulting table may not be a sequence.
8820
8821
8822
8823
8824<p>
8825<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
8826
8827
8828<p>
8829Removes from <code>list</code> the element at position <code>pos</code>,
8830returning the value of the removed element.
8831When <code>pos</code> is an integer between 1 and <code>#list</code>,
8832it shifts down the elements
8833<code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
8834and erases element <code>list[#list]</code>;
8835The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
8836or <code>#list + 1</code>;
8837in those cases, the function erases the element <code>list[pos]</code>.
8838
8839
8840<p>
8841The default value for <code>pos</code> is <code>#list</code>,
8842so that a call <code>table.remove(l)</code> removes the last element
8843of list <code>l</code>.
8844
8845
8846
8847
8848<p>
8849<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
8850
8851
8852<p>
8853Sorts list elements in a given order, <em>in-place</em>,
8854from <code>list[1]</code> to <code>list[#list]</code>.
8855If <code>comp</code> is given,
8856then it must be a function that receives two list elements
8857and returns true when the first element must come
8858before the second in the final order
8859(so that <code>not comp(list[i+1],list[i])</code> will be true after the sort).
8860If <code>comp</code> is not given,
8861then the standard Lua operator <code>&lt;</code> is used instead.
8862
8863
8864<p>
8865The sort algorithm is not stable;
8866that is, elements considered equal by the given order
8867may have their relative positions changed by the sort.
8868
8869
8870
8871
8872<p>
8873<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
8874
8875
8876<p>
8877Returns the elements from the given list.
8878This function is equivalent to
8879
8880<pre>
8881     return list[i], list[i+1], &middot;&middot;&middot;, list[j]
8882</pre><p>
8883By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
8884
8885
8886
8887
8888
8889
8890
8891<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
8892
8893<p>
8894This library provides basic mathematical functions.
8895It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
8896Functions with the annotation "<code>integer/float</code>" give
8897integer results for integer arguments
8898and float results for float (or mixed) arguments.
8899Rounding functions
8900(<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>)
8901return an integer when the result fits in the range of an integer,
8902otherwise they return a float.
8903
8904
8905<p>
8906<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
8907
8908
8909<p>
8910Returns the absolute value of <code>x</code>. (integer/float)
8911
8912
8913
8914
8915<p>
8916<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
8917
8918
8919<p>
8920Returns the arc cosine of <code>x</code> (in radians).
8921
8922
8923
8924
8925<p>
8926<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
8927
8928
8929<p>
8930Returns the arc sine of <code>x</code> (in radians).
8931
8932
8933
8934
8935<p>
8936<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
8937
8938
8939<p>
8940
8941Returns the arc tangent of <code>y/x</code> (in radians),
8942but uses the signs of both parameters to find the
8943quadrant of the result.
8944(It also handles correctly the case of <code>x</code> being zero.)
8945
8946
8947<p>
8948The default value for <code>x</code> is 1,
8949so that the call <code>math.atan(y)</code>
8950returns the arc tangent of <code>y</code>.
8951
8952
8953
8954
8955<p>
8956<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
8957
8958
8959<p>
8960Returns the smaller integral value larger than or equal to <code>x</code>.
8961
8962
8963
8964
8965<p>
8966<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
8967
8968
8969<p>
8970Returns the cosine of <code>x</code> (assumed to be in radians).
8971
8972
8973
8974
8975<p>
8976<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
8977
8978
8979<p>
8980Converts the angle <code>x</code> from radians to degrees.
8981
8982
8983
8984
8985<p>
8986<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
8987
8988
8989<p>
8990Returns the largest integral value smaller than or equal to <code>x</code>.
8991
8992
8993
8994
8995<p>
8996<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
8997
8998
8999<p>
9000Returns the remainder of the division of <code>x</code> by <code>y</code>
9001that rounds the quotient towards zero. (integer/float)
9002
9003
9004
9005
9006<p>
9007<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
9008
9009
9010<p>
9011The float value <code>HUGE_VAL</code>,
9012a value larger than any other numerical value.
9013
9014
9015
9016
9017<p>
9018<hr><h3><a name="pdf-math.ifloor"><code>math.ifloor (x)</code></a></h3>
9019
9020
9021<p>
9022Returns the largest integer smaller than or equal to <code>x</code>.
9023If the value does not fit in an integer,
9024returns <b>nil</b>.
9025
9026
9027
9028
9029<p>
9030<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
9031
9032
9033<p>
9034Returns the logarithm of <code>x</code> in the given base.
9035The default for <code>base</code> is <em>e</em>
9036(so that the function returns the natural logarithm of <code>x</code>).
9037
9038
9039
9040
9041<p>
9042<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
9043
9044
9045<p>
9046Returns the argument with the maximum value,
9047according to the Lua operator <code>&lt;</code>. (integer/float)
9048
9049
9050
9051
9052<p>
9053<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
9054An integer with the maximum value for an integer.
9055
9056
9057
9058
9059<p>
9060<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
9061
9062
9063<p>
9064Returns the argument with the minimum value,
9065according to the Lua operator <code>&lt;</code>. (integer/float)
9066
9067
9068
9069
9070<p>
9071<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
9072An integer with the minimum value for an integer.
9073
9074
9075
9076
9077<p>
9078<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
9079
9080
9081<p>
9082Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
9083Its second result is always a float.
9084
9085
9086
9087
9088<p>
9089<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
9090
9091
9092<p>
9093The value of <em>&pi;</em>.
9094
9095
9096
9097
9098<p>
9099<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
9100
9101
9102<p>
9103Converts the angle <code>x</code> from degrees to radians.
9104
9105
9106
9107
9108<p>
9109<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
9110
9111
9112<p>
9113When called without arguments,
9114returns a pseudo-random float with uniform distribution
9115in the range  <em>[0,1)</em>.
9116When called with two integers <code>m</code> and <code>n</code>,
9117<code>math.random</code> returns a pseudo-random integer
9118with uniform distribution in the range <em>[m, n]</em>.
9119(The interval size must fit in a Lua integer.)
9120The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>.
9121
9122
9123<p>
9124This function is an interface to the underling
9125pseudo-random generator function provided by C.
9126No guarantees can be given for its statistical properties.
9127
9128
9129
9130
9131<p>
9132<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
9133
9134
9135<p>
9136Sets <code>x</code> as the "seed"
9137for the pseudo-random generator:
9138equal seeds produce equal sequences of numbers.
9139
9140
9141
9142
9143<p>
9144<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
9145
9146
9147<p>
9148Returns the sine of <code>x</code> (assumed to be in radians).
9149
9150
9151
9152
9153<p>
9154<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
9155
9156
9157<p>
9158Returns the square root of <code>x</code>.
9159(You can also use the expression <code>x^0.5</code> to compute this value.)
9160
9161
9162
9163
9164<p>
9165<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
9166
9167
9168<p>
9169Returns the tangent of <code>x</code> (assumed to be in radians).
9170
9171
9172
9173
9174<p>
9175<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
9176
9177
9178<p>
9179Returns "<code>integer</code>" if <code>x</code> is an integer,
9180"<code>float</code>" if it is a float,
9181or <b>nil</b> if <code>x</code> is not a number.
9182
9183
9184
9185
9186
9187
9188
9189<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
9190
9191<p>
9192The I/O library provides two different styles for file manipulation.
9193The first one uses implicit file handles;
9194that is, there are operations to set a default input file and a
9195default output file,
9196and all input/output operations are over these default files.
9197The second style uses explicit file handles.
9198
9199
9200<p>
9201When using implicit file handles,
9202all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
9203When using explicit file handles,
9204the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
9205and then all operations are supplied as methods of the file handle.
9206
9207
9208<p>
9209The table <code>io</code> also provides
9210three predefined file handles with their usual meanings from C:
9211<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>.
9212The I/O library never closes these files.
9213
9214
9215<p>
9216Unless otherwise stated,
9217all I/O functions return <b>nil</b> on failure
9218(plus an error message as a second result and
9219a system-dependent error code as a third result)
9220and some value different from <b>nil</b> on success.
9221On non-POSIX systems,
9222the computation of the error message and error code
9223in case of errors
9224may be not thread safe,
9225because they rely on the global C variable <code>errno</code>.
9226
9227
9228<p>
9229<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
9230
9231
9232<p>
9233Equivalent to <code>file:close()</code>.
9234Without a <code>file</code>, closes the default output file.
9235
9236
9237
9238
9239<p>
9240<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
9241
9242
9243<p>
9244Equivalent to <code>io.output():flush()</code>.
9245
9246
9247
9248
9249<p>
9250<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
9251
9252
9253<p>
9254When called with a file name, it opens the named file (in text mode),
9255and sets its handle as the default input file.
9256When called with a file handle,
9257it simply sets this file handle as the default input file.
9258When called without parameters,
9259it returns the current default input file.
9260
9261
9262<p>
9263In case of errors this function raises the error,
9264instead of returning an error code.
9265
9266
9267
9268
9269<p>
9270<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename &middot;&middot;&middot;])</code></a></h3>
9271
9272
9273<p>
9274Opens the given file name in read mode
9275and returns an iterator function that
9276works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
9277When the iterator function detects the end of file,
9278it returns no values (to finish the loop) and automatically closes the file.
9279
9280
9281<p>
9282The call <code>io.lines()</code> (with no file name) is equivalent
9283to <code>io.input():lines("*l")</code>;
9284that is, it iterates over the lines of the default input file.
9285In this case it does not close the file when the loop ends.
9286
9287
9288<p>
9289In case of errors this function raises the error,
9290instead of returning an error code.
9291
9292
9293
9294
9295<p>
9296<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
9297
9298
9299<p>
9300This function opens a file,
9301in the mode specified in the string <code>mode</code>.
9302It returns a new file handle,
9303or, in case of errors, <b>nil</b> plus an error message.
9304
9305
9306<p>
9307The <code>mode</code> string can be any of the following:
9308
9309<ul>
9310<li><b>"<code>r</code>": </b> read mode (the default);</li>
9311<li><b>"<code>w</code>": </b> write mode;</li>
9312<li><b>"<code>a</code>": </b> append mode;</li>
9313<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
9314<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
9315<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
9316  writing is only allowed at the end of file.</li>
9317</ul><p>
9318The <code>mode</code> string can also have a '<code>b</code>' at the end,
9319which is needed in some systems to open the file in binary mode.
9320
9321
9322
9323
9324<p>
9325<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
9326
9327
9328<p>
9329Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
9330
9331
9332
9333
9334<p>
9335<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
9336
9337
9338<p>
9339This function is system dependent and is not available
9340on all platforms.
9341
9342
9343<p>
9344Starts program <code>prog</code> in a separated process and returns
9345a file handle that you can use to read data from this program
9346(if <code>mode</code> is <code>"r"</code>, the default)
9347or to write data to this program
9348(if <code>mode</code> is <code>"w"</code>).
9349
9350
9351
9352
9353<p>
9354<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
9355
9356
9357<p>
9358Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
9359
9360
9361
9362
9363<p>
9364<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
9365
9366
9367<p>
9368Returns a handle for a temporary file.
9369This file is opened in update mode
9370and it is automatically removed when the program ends.
9371
9372
9373
9374
9375<p>
9376<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
9377
9378
9379<p>
9380Checks whether <code>obj</code> is a valid file handle.
9381Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
9382<code>"closed file"</code> if <code>obj</code> is a closed file handle,
9383or <b>nil</b> if <code>obj</code> is not a file handle.
9384
9385
9386
9387
9388<p>
9389<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
9390
9391
9392<p>
9393Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
9394
9395
9396
9397
9398<p>
9399<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
9400
9401
9402<p>
9403Closes <code>file</code>.
9404Note that files are automatically closed when
9405their handles are garbage collected,
9406but that takes an unpredictable amount of time to happen.
9407
9408
9409<p>
9410When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
9411<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
9412returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
9413
9414
9415
9416
9417<p>
9418<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
9419
9420
9421<p>
9422Saves any written data to <code>file</code>.
9423
9424
9425
9426
9427<p>
9428<hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
9429
9430
9431<p>
9432Returns an iterator function that,
9433each time it is called,
9434reads the file according to the given formats.
9435When no format is given,
9436uses "<code>l</code>" as a default.
9437As an example, the construction
9438
9439<pre>
9440     for c in file:lines(1) do <em>body</em> end
9441</pre><p>
9442will iterate over all characters of the file,
9443starting at the current position.
9444Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
9445when the loop ends.
9446
9447
9448<p>
9449In case of errors this function raises the error,
9450instead of returning an error code.
9451
9452
9453
9454
9455<p>
9456<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
9457
9458
9459<p>
9460Reads the file <code>file</code>,
9461according to the given formats, which specify what to read.
9462For each format,
9463the function returns a string or a number with the characters read,
9464or <b>nil</b> if it cannot read data with the specified format.
9465When called without formats,
9466it uses a default format that reads the next line
9467(see below).
9468
9469
9470<p>
9471The available formats are
9472
9473<ul>
9474
9475<li><b>"<code>n</code>": </b>
9476reads a numeral and returns it as a float or an integer,
9477following the lexical conventions of Lua.
9478(The numeral may have leading spaces and a sign.)
9479This format always reads the longest input sequence that
9480is a valid prefix for a number;
9481if that prefix does not form a valid number
9482(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"),
9483it is discarded and the function returns <b>nil</b>.
9484</li>
9485
9486<li><b>"<code>i</code>": </b>
9487reads an integral number and returns it as an integer.
9488</li>
9489
9490<li><b>"<code>a</code>": </b>
9491reads the whole file, starting at the current position.
9492On end of file, it returns the empty string.
9493</li>
9494
9495<li><b>"<code>l</code>": </b>
9496reads the next line skipping the end of line,
9497returning <b>nil</b> on end of file.
9498This is the default format.
9499</li>
9500
9501<li><b>"<code>L</code>": </b>
9502reads the next line keeping the end-of-line character (if present),
9503returning <b>nil</b> on end of file.
9504</li>
9505
9506<li><b><em>number</em>: </b>
9507reads a string with up to this number of bytes,
9508returning <b>nil</b> on end of file.
9509If <code>number</code> is zero,
9510it reads nothing and returns an empty string,
9511or <b>nil</b> on end of file.
9512</li>
9513
9514</ul><p>
9515The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
9516
9517
9518
9519
9520<p>
9521<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
9522
9523
9524<p>
9525Sets and gets the file position,
9526measured from the beginning of the file,
9527to the position given by <code>offset</code> plus a base
9528specified by the string <code>whence</code>, as follows:
9529
9530<ul>
9531<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
9532<li><b>"<code>cur</code>": </b> base is current position;</li>
9533<li><b>"<code>end</code>": </b> base is end of file;</li>
9534</ul><p>
9535In case of success, <code>seek</code> returns the final file position,
9536measured in bytes from the beginning of the file.
9537If <code>seek</code> fails, it returns <b>nil</b>,
9538plus a string describing the error.
9539
9540
9541<p>
9542The default value for <code>whence</code> is <code>"cur"</code>,
9543and for <code>offset</code> is 0.
9544Therefore, the call <code>file:seek()</code> returns the current
9545file position, without changing it;
9546the call <code>file:seek("set")</code> sets the position to the
9547beginning of the file (and returns 0);
9548and the call <code>file:seek("end")</code> sets the position to the
9549end of the file, and returns its size.
9550
9551
9552
9553
9554<p>
9555<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
9556
9557
9558<p>
9559Sets the buffering mode for an output file.
9560There are three available modes:
9561
9562<ul>
9563
9564<li><b>"<code>no</code>": </b>
9565no buffering; the result of any output operation appears immediately.
9566</li>
9567
9568<li><b>"<code>full</code>": </b>
9569full buffering; output operation is performed only
9570when the buffer is full or when
9571you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>).
9572</li>
9573
9574<li><b>"<code>line</code>": </b>
9575line buffering; output is buffered until a newline is output
9576or there is any input from some special files
9577(such as a terminal device).
9578</li>
9579
9580</ul><p>
9581For the last two cases, <code>size</code>
9582specifies the size of the buffer, in bytes.
9583The default is an appropriate size.
9584
9585
9586
9587
9588<p>
9589<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
9590
9591
9592<p>
9593Writes the value of each of its arguments to <code>file</code>.
9594The arguments must be strings or numbers.
9595
9596
9597<p>
9598In case of success, this function returns <code>file</code>.
9599Otherwise it returns <b>nil</b> plus a string describing the error.
9600
9601
9602
9603
9604
9605
9606
9607<h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
9608
9609<p>
9610This library is implemented through table <a name="pdf-os"><code>os</code></a>.
9611
9612
9613<p>
9614<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
9615
9616
9617<p>
9618Returns an approximation of the amount in seconds of CPU time
9619used by the program.
9620
9621
9622
9623
9624<p>
9625<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
9626
9627
9628<p>
9629Returns a string or a table containing date and time,
9630formatted according to the given string <code>format</code>.
9631
9632
9633<p>
9634If the <code>time</code> argument is present,
9635this is the time to be formatted
9636(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
9637Otherwise, <code>date</code> formats the current time.
9638
9639
9640<p>
9641If <code>format</code> starts with '<code>!</code>',
9642then the date is formatted in Coordinated Universal Time.
9643After this optional character,
9644if <code>format</code> is the string "<code>*t</code>",
9645then <code>date</code> returns a table with the following fields:
9646<code>year</code> (four digits), <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
9647<code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59), <code>sec</code> (0&ndash;61),
9648<code>wday</code> (weekday, Sunday is&nbsp;1),
9649<code>yday</code> (day of the year),
9650and <code>isdst</code> (daylight saving flag, a boolean).
9651This last field may be absent
9652if the information is not available.
9653
9654
9655<p>
9656If <code>format</code> is not "<code>*t</code>",
9657then <code>date</code> returns the date as a string,
9658formatted according to the same rules as the ANSI&nbsp;C function <code>strftime</code>.
9659
9660
9661<p>
9662When called without arguments,
9663<code>date</code> returns a reasonable date and time representation that depends on
9664the host system and on the current locale
9665(that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
9666
9667
9668<p>
9669On non-POSIX systems,
9670this function may be not thread safe
9671because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
9672
9673
9674
9675
9676<p>
9677<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
9678
9679
9680<p>
9681Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
9682In POSIX, Windows, and some other systems,
9683this value is exactly <code>t2</code><em>-</em><code>t1</code>.
9684
9685
9686
9687
9688<p>
9689<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
9690
9691
9692<p>
9693This function is equivalent to the ANSI&nbsp;C function <code>system</code>.
9694It passes <code>command</code> to be executed by an operating system shell.
9695Its first result is <b>true</b>
9696if the command terminated successfully,
9697or <b>nil</b> otherwise.
9698After this first result
9699the function returns a string plus a number,
9700as follows:
9701
9702<ul>
9703
9704<li><b>"<code>exit</code>": </b>
9705the command terminated normally;
9706the following number is the exit status of the command.
9707</li>
9708
9709<li><b>"<code>signal</code>": </b>
9710the command was terminated by a signal;
9711the following number is the signal that terminated the command.
9712</li>
9713
9714</ul>
9715
9716<p>
9717When called without a <code>command</code>,
9718<code>os.execute</code> returns a boolean that is true if a shell is available.
9719
9720
9721
9722
9723<p>
9724<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
9725
9726
9727<p>
9728Calls the ANSI&nbsp;C function <code>exit</code> to terminate the host program.
9729If <code>code</code> is <b>true</b>,
9730the returned status is <code>EXIT_SUCCESS</code>;
9731if <code>code</code> is <b>false</b>,
9732the returned status is <code>EXIT_FAILURE</code>;
9733if <code>code</code> is a number,
9734the returned status is this number.
9735The default value for <code>code</code> is <b>true</b>.
9736
9737
9738<p>
9739If the optional second argument <code>close</code> is true,
9740closes the Lua state before exiting.
9741
9742
9743
9744
9745<p>
9746<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
9747
9748
9749<p>
9750Returns the value of the process environment variable <code>varname</code>,
9751or <b>nil</b> if the variable is not defined.
9752
9753
9754
9755
9756<p>
9757<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
9758
9759
9760<p>
9761Deletes the file (or empty directory, on POSIX systems)
9762with the given name.
9763If this function fails, it returns <b>nil</b>,
9764plus a string describing the error and the error code.
9765
9766
9767
9768
9769<p>
9770<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
9771
9772
9773<p>
9774Renames file or directory named <code>oldname</code> to <code>newname</code>.
9775If this function fails, it returns <b>nil</b>,
9776plus a string describing the error and the error code.
9777
9778
9779
9780
9781<p>
9782<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
9783
9784
9785<p>
9786Sets the current locale of the program.
9787<code>locale</code> is a system-dependent string specifying a locale;
9788<code>category</code> is an optional string describing which category to change:
9789<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
9790<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
9791the default category is <code>"all"</code>.
9792The function returns the name of the new locale,
9793or <b>nil</b> if the request cannot be honored.
9794
9795
9796<p>
9797If <code>locale</code> is the empty string,
9798the current locale is set to an implementation-defined native locale.
9799If <code>locale</code> is the string "<code>C</code>",
9800the current locale is set to the standard C locale.
9801
9802
9803<p>
9804When called with <b>nil</b> as the first argument,
9805this function only returns the name of the current locale
9806for the given category.
9807
9808
9809<p>
9810This function may be not thread safe
9811because of its reliance on C&nbsp;function <code>setlocale</code>.
9812
9813
9814
9815
9816<p>
9817<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
9818
9819
9820<p>
9821Returns the current time when called without arguments,
9822or a time representing the date and time specified by the given table.
9823This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
9824and may have fields
9825<code>hour</code> (default is 12),
9826<code>min</code> (default is 0),
9827<code>sec</code> (default is 0),
9828and <code>isdst</code> (default is <b>nil</b>).
9829For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
9830
9831
9832<p>
9833The returned value is a number, whose meaning depends on your system.
9834In POSIX, Windows, and some other systems,
9835this number counts the number
9836of seconds since some given start time (the "epoch").
9837In other systems, the meaning is not specified,
9838and the number returned by <code>time</code> can be used only as an argument to
9839<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
9840
9841
9842
9843
9844<p>
9845<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
9846
9847
9848<p>
9849Returns a string with a file name that can
9850be used for a temporary file.
9851The file must be explicitly opened before its use
9852and explicitly removed when no longer needed.
9853
9854
9855<p>
9856On POSIX systems,
9857this function also creates a file with that name,
9858to avoid security risks.
9859(Someone else might create the file with wrong permissions
9860in the time between getting the name and creating the file.)
9861You still have to open the file to use it
9862and to remove it (even if you do not use it).
9863
9864
9865<p>
9866When possible,
9867you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
9868which automatically removes the file when the program ends.
9869
9870
9871
9872
9873
9874
9875
9876<h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
9877
9878<p>
9879This library provides
9880the functionality of the debug interface (<a href="#4.9">&sect;4.9</a>) to Lua programs.
9881You should exert care when using this library.
9882Several of its functions
9883violate basic assumptions about Lua code
9884(e.g., that variables local to a function
9885cannot be accessed from outside;
9886that userdata metatables cannot be changed by Lua code;
9887that Lua programs do not crash)
9888and therefore can compromise otherwise secure code.
9889Moreover, some functions in this library may be slow.
9890
9891
9892<p>
9893All functions in this library are provided
9894inside the <a name="pdf-debug"><code>debug</code></a> table.
9895All functions that operate over a thread
9896have an optional first argument which is the
9897thread to operate over.
9898The default is always the current thread.
9899
9900
9901<p>
9902<hr><h3><a name="pdf-debug.Csize"><code>debug.Csize (t)</code></a></h3>
9903
9904
9905<p>
9906Returns the size of the underlying representation of a given C type,
9907according to the following table:
9908<table border="1">
9909<tr><td>'<code>I</code>'</td><td><code>lua_Integer</code></td></tr>
9910<tr><td>'<code>F</code>'</td><td><code>lua_Number</code></td></tr>
9911<tr><td>'<code>b</code>'</td><td><code>byte</code></td></tr>
9912<tr><td>'<code>d</code>'</td><td><code>double</code></td></tr>
9913<tr><td>'<code>f</code>'</td><td><code>float</code></td></tr>
9914<tr><td>'<code>h</code>'</td><td><code>short int</code></td></tr>
9915<tr><td>'<code>i</code>'</td><td><code>int</code></td></tr>
9916<tr><td>'<code>l</code>'</td><td><code>long int</code></td></tr>
9917<tr><td>'<code>z</code>'</td><td><code>size_t</code></td></tr>
9918</table>
9919For all options except '<code>b</code>',
9920the size is given in number of bytes;
9921for option '<code>b</code>',
9922the size is its number of bits.
9923
9924
9925
9926
9927<p>
9928<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
9929
9930
9931<p>
9932Enters an interactive mode with the user,
9933running each string that the user enters.
9934Using simple commands and other debug facilities,
9935the user can inspect global and local variables,
9936change their values, evaluate expressions, and so on.
9937A line containing only the word <code>cont</code> finishes this function,
9938so that the caller continues its execution.
9939
9940
9941<p>
9942Note that commands for <code>debug.debug</code> are not lexically nested
9943within any function and so have no direct access to local variables.
9944
9945
9946
9947
9948<p>
9949<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
9950
9951
9952<p>
9953Returns the current hook settings of the thread, as three values:
9954the current hook function, the current hook mask,
9955and the current hook count
9956(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
9957
9958
9959
9960
9961<p>
9962<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
9963
9964
9965<p>
9966Returns a table with information about a function.
9967You can give the function directly
9968or you can give a number as the value of <code>f</code>,
9969which means the function running at level <code>f</code> of the call stack
9970of the given thread:
9971level&nbsp;0 is the current function (<code>getinfo</code> itself);
9972level&nbsp;1 is the function that called <code>getinfo</code>
9973(except for tail calls, which do not count on the stack);
9974and so on.
9975If <code>f</code> is a number larger than the number of active functions,
9976then <code>getinfo</code> returns <b>nil</b>.
9977
9978
9979<p>
9980The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
9981with the string <code>what</code> describing which fields to fill in.
9982The default for <code>what</code> is to get all information available,
9983except the table of valid lines.
9984If present,
9985the option '<code>f</code>'
9986adds a field named <code>func</code> with the function itself.
9987If present,
9988the option '<code>L</code>'
9989adds a field named <code>activelines</code> with the table of
9990valid lines.
9991
9992
9993<p>
9994For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
9995a table with a name for the current function,
9996if a reasonable name can be found,
9997and the expression <code>debug.getinfo(print)</code>
9998returns a table with all available information
9999about the <a href="#pdf-print"><code>print</code></a> function.
10000
10001
10002
10003
10004<p>
10005<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
10006
10007
10008<p>
10009This function returns the name and the value of the local variable
10010with index <code>local</code> of the function at level <code>f</code> of the stack.
10011This function accesses not only explicit local variables,
10012but also parameters, temporaries, etc.
10013
10014
10015<p>
10016The first parameter or local variable has index&nbsp;1, and so on,
10017until the last active variable.
10018Negative indices refer to vararg parameters;
10019-1 is the first vararg parameter.
10020The function returns <b>nil</b> if there is no variable with the given index,
10021and raises an error when called with a level out of range.
10022(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
10023
10024
10025<p>
10026Variable names starting with '<code>(</code>' (open parenthesis)
10027represent variables with no known names
10028(internal variables like loop control variables,
10029and variables from chunks saved without debug information).
10030
10031
10032<p>
10033The parameter <code>f</code> may also be a function.
10034In that case, <code>getlocal</code> returns only the name of function parameters.
10035
10036
10037
10038
10039<p>
10040<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
10041
10042
10043<p>
10044Returns the metatable of the given <code>value</code>
10045or <b>nil</b> if it does not have a metatable.
10046
10047
10048
10049
10050<p>
10051<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
10052
10053
10054<p>
10055Returns the registry table (see <a href="#4.5">&sect;4.5</a>).
10056
10057
10058
10059
10060<p>
10061<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
10062
10063
10064<p>
10065This function returns the name and the value of the upvalue
10066with index <code>up</code> of the function <code>f</code>.
10067The function returns <b>nil</b> if there is no upvalue with the given index.
10068
10069
10070<p>
10071Variable names starting with '<code>(</code>' (open parenthesis)
10072represent variables with no known names
10073(variables from chunks saved without debug information).
10074
10075
10076
10077
10078<p>
10079<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
10080
10081
10082<p>
10083Returns the Lua value associated to <code>u</code>.
10084If <code>u</code> is not a userdata,
10085returns <b>nil</b>.
10086
10087
10088
10089
10090<p>
10091<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
10092
10093
10094<p>
10095Sets the given function as a hook.
10096The string <code>mask</code> and the number <code>count</code> describe
10097when the hook will be called.
10098The string mask may have any combination of the following characters,
10099with the given meaning:
10100
10101<ul>
10102<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
10103<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
10104<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
10105</ul><p>
10106Moreover,
10107with a <code>count</code> different from zero,
10108the hook is called also after every <code>count</code> instructions.
10109
10110
10111<p>
10112When called without arguments,
10113<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
10114
10115
10116<p>
10117When the hook is called, its first parameter is a string
10118describing the event that has triggered its call:
10119<code>"call"</code> (or <code>"tail call"</code>),
10120<code>"return"</code>,
10121<code>"line"</code>, and <code>"count"</code>.
10122For line events,
10123the hook also gets the new line number as its second parameter.
10124Inside a hook,
10125you can call <code>getinfo</code> with level&nbsp;2 to get more information about
10126the running function
10127(level&nbsp;0 is the <code>getinfo</code> function,
10128and level&nbsp;1 is the hook function).
10129
10130
10131
10132
10133<p>
10134<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
10135
10136
10137<p>
10138This function assigns the value <code>value</code> to the local variable
10139with index <code>local</code> of the function at level <code>level</code> of the stack.
10140The function returns <b>nil</b> if there is no local
10141variable with the given index,
10142and raises an error when called with a <code>level</code> out of range.
10143(You can call <code>getinfo</code> to check whether the level is valid.)
10144Otherwise, it returns the name of the local variable.
10145
10146
10147<p>
10148See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
10149variable indices and names.
10150
10151
10152
10153
10154<p>
10155<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
10156
10157
10158<p>
10159Sets the metatable for the given <code>value</code> to the given <code>table</code>
10160(which can be <b>nil</b>).
10161Returns <code>value</code>.
10162
10163
10164
10165
10166<p>
10167<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
10168
10169
10170<p>
10171This function assigns the value <code>value</code> to the upvalue
10172with index <code>up</code> of the function <code>f</code>.
10173The function returns <b>nil</b> if there is no upvalue
10174with the given index.
10175Otherwise, it returns the name of the upvalue.
10176
10177
10178
10179
10180<p>
10181<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3>
10182
10183
10184<p>
10185Sets the given <code>value</code> as
10186the Lua value associated to the given <code>udata</code>.
10187<code>udata</code> must be a full userdata.
10188
10189
10190<p>
10191Returns <code>udata</code>.
10192
10193
10194
10195
10196<p>
10197<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
10198
10199
10200<p>
10201If <code>message</code> is present but is neither a string nor <b>nil</b>,
10202this function returns <code>message</code> without further processing.
10203Otherwise,
10204it returns a string with a traceback of the call stack.
10205An optional <code>message</code> string is appended
10206at the beginning of the traceback.
10207An optional <code>level</code> number tells at which level
10208to start the traceback
10209(default is 1, the function calling <code>traceback</code>).
10210
10211
10212
10213
10214<p>
10215<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
10216
10217
10218<p>
10219Returns an unique identifier (as a light userdata)
10220for the upvalue numbered <code>n</code>
10221from the given function.
10222
10223
10224<p>
10225These unique identifiers allow a program to check whether different
10226closures share upvalues.
10227Lua closures that share an upvalue
10228(that is, that access a same external local variable)
10229will return identical ids for those upvalue indices.
10230
10231
10232
10233
10234<p>
10235<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
10236
10237
10238<p>
10239Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
10240refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
10241
10242
10243
10244
10245
10246
10247
10248<h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
10249
10250<p>
10251Although Lua has been designed as an extension language,
10252to be embedded in a host C&nbsp;program,
10253it is also frequently used as a standalone language.
10254An interpreter for Lua as a standalone language,
10255called simply <code>lua</code>,
10256is provided with the standard distribution.
10257The standalone interpreter includes
10258all standard libraries, including the debug library.
10259Its usage is:
10260
10261<pre>
10262     lua [options] [script [args]]
10263</pre><p>
10264The options are:
10265
10266<ul>
10267<li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li>
10268<li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em>;</li>
10269<li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li>
10270<li><b><code>-v</code>: </b> prints version information;</li>
10271<li><b><code>-E</code>: </b> ignores environment variables;</li>
10272<li><b><code>--</code>: </b> stops handling options;</li>
10273<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
10274</ul><p>
10275After handling its options, <code>lua</code> runs the given <em>script</em>,
10276passing to it the given <em>args</em> as string arguments.
10277When called without arguments,
10278<code>lua</code> behaves as <code>lua -v -i</code>
10279when the standard input (<code>stdin</code>) is a terminal,
10280and as <code>lua -</code> otherwise.
10281
10282
10283<p>
10284When called without option <code>-E</code>,
10285the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a>
10286(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if it is not defined)
10287before running any argument.
10288If the variable content has the format <code>@<em>filename</em></code>,
10289then <code>lua</code> executes the file.
10290Otherwise, <code>lua</code> executes the string itself.
10291
10292
10293<p>
10294When called with option <code>-E</code>,
10295besides ignoring <code>LUA_INIT</code>,
10296Lua also ignores
10297the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>,
10298setting the values of
10299<a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
10300with the default paths defined in <code>luaconf.h</code>.
10301
10302
10303<p>
10304All options are handled in order, except <code>-i</code> and <code>-E</code>.
10305For instance, an invocation like
10306
10307<pre>
10308     $ lua -e'a=1' -e 'print(a)' script.lua
10309</pre><p>
10310will first set <code>a</code> to 1, then print the value of <code>a</code>,
10311and finally run the file <code>script.lua</code> with no arguments.
10312(Here <code>$</code> is the shell prompt. Your prompt may be different.)
10313
10314
10315<p>
10316Before running any code,
10317<code>lua</code> collects all command-line arguments
10318in a global table called <code>arg</code>.
10319The script name goes to index 0,
10320the first argument after the script name goes to index 1,
10321and so on.
10322Any arguments before the script name
10323(that is, the interpreter name plus its options)
10324go to negative indices.
10325For instance, in the call
10326
10327<pre>
10328     $ lua -la b.lua t1 t2
10329</pre><p>
10330the table is like this:
10331
10332<pre>
10333     arg = { [-2] = "lua", [-1] = "-la",
10334             [0] = "b.lua",
10335             [1] = "t1", [2] = "t2" }
10336</pre><p>
10337If there is no script in the call,
10338the interpreter name goes to index 0,
10339followed by the other arguments.
10340For instance, the call
10341
10342<pre>
10343     $ lua -e "print(arg[1])"
10344</pre><p>
10345will print "<code>-e</code>".
10346
10347
10348<p>
10349In interactive mode,
10350Lua repeatedly prompts and waits for a line.
10351After reading a line,
10352Lua first try to interpret the line as an expression.
10353If it succeeds, it prints its value.
10354Otherwise, it interprets the line as a statement.
10355If you write an incomplete statement,
10356the interpreter waits for its completion
10357by issuing a different prompt.
10358
10359
10360<p>
10361In case of unprotected errors in the script,
10362the interpreter reports the error to the standard error stream.
10363If the error object is a string,
10364the interpreter adds a stack traceback to it.
10365Otherwise, if the error object has a metamethod <code>__tostring</code>,
10366the interpreter calls this metamethod to produce the final message.
10367Finally, if the error object is <b>nil</b>,
10368the interpreter does not report the error.
10369
10370
10371<p>
10372When finishing normally,
10373the interpreter closes its main Lua state
10374(see <a href="#lua_close"><code>lua_close</code></a>).
10375The script can avoid this step by
10376calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
10377
10378
10379<p>
10380To allow the use of Lua as a
10381script interpreter in Unix systems,
10382the standalone interpreter skips
10383the first line of a chunk if it starts with <code>#</code>.
10384Therefore, Lua scripts can be made into executable programs
10385by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
10386as in
10387
10388<pre>
10389     #!/usr/local/bin/lua
10390</pre><p>
10391(Of course,
10392the location of the Lua interpreter may be different in your machine.
10393If <code>lua</code> is in your <code>PATH</code>,
10394then
10395
10396<pre>
10397     #!/usr/bin/env lua
10398</pre><p>
10399is a more portable solution.)
10400
10401
10402
10403<h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
10404
10405<p>
10406Here we list the incompatibilities that you may find when moving a program
10407from Lua&nbsp;5.2 to Lua&nbsp;5.3.
10408You can avoid some incompatibilities by compiling Lua with
10409appropriate options (see file <code>luaconf.h</code>).
10410However,
10411all these compatibility options will be removed in the future.
10412
10413
10414<p>
10415Lua versions can always change the C API in ways that
10416do not imply source-code changes in a program,
10417such as the numeric values for constants
10418or the implementation of functions as macros.
10419Therefore,
10420you should never assume that binaries are compatible between
10421different Lua versions.
10422Always recompile clients of the Lua API when
10423using a new version.
10424
10425
10426<p>
10427Similarly, Lua versions can always change the internal representation
10428of precompiled chunks;
10429precompiled chunks are never compatible between different Lua versions.
10430
10431
10432<p>
10433The standard paths in the official distribution may
10434change between versions.
10435
10436
10437
10438<h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10439<ul>
10440
10441<li>
10442The main difference between Lua&nbsp;5.2 and Lua&nbsp;5.3 is the
10443introduction of an integer subtype for numbers.
10444Although this change should not affect "normal" computations,
10445some computations
10446(mainly those that involve some kind of overflow)
10447can give different results.
10448
10449
10450<p>
10451You can fix these differences by forcing a number to be a float
10452(in Lua&nbsp;5.2 all numbers were float),
10453in particular writing constants with an ending <code>.0</code>
10454or using <code>x = x + 0.0</code> to convert a variable.
10455(This recommendation is only for a quick fix
10456for an occasional incompatibility;
10457it is not a general guideline for good programming.
10458For good programming,
10459use floats where you need floats
10460and integers where you need integers.)
10461
10462
10463<p>
10464Although not formally an incompatibility,
10465the proper differentiation between floats and integers
10466have an impact on performance.
10467</li>
10468
10469<li>
10470The conversion of a float to a string now adds a <code>.0</code> suffix
10471to the result if it looks like an integer.
10472(For instance, the float 2.0 will be printed as <code>2.0</code>,
10473not as <code>2</code>.)
10474You should always use an explicit format
10475when you need a specific format for numbers.
10476
10477
10478<p>
10479(Formally this is not an incompatibility,
10480because Lua does not specify how numbers are formatted as strings,
10481but some programs assumed a specific format.)
10482</li>
10483
10484<li>
10485The generational mode for the garbage collector was removed.
10486(It was an experimental feature in Lua&nbsp;5.2.)
10487</li>
10488
10489</ul>
10490
10491
10492
10493
10494<h2>8.2 &ndash; <a name="8.2">Changes in the Libraries</a></h2>
10495<ul>
10496
10497<li>
10498The <code>bit32</code> library has been deprecated.
10499It is easy to require a compatible external library or,
10500better yet, to replace its functions with appropriate bitwise operations.
10501(Keep in mind that <code>bit32</code> operates on 32-bit integers,
10502while the bitwise operators in Standard Lua operate on 64-bit integers.)
10503</li>
10504
10505<li>
10506Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore.
10507For compatibility, Lua will continue to ignore this character.
10508</li>
10509
10510<li>
10511The following functions were deprecated in the mathematical library:
10512<code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>,
10513<code>frexp</code>, and <code>ldexp</code>.
10514You can replace <code>math.pow(x,y)</code> with <code>x^y</code>;
10515you can replace <code>math.atan2</code> with <code>math.atan</code>,
10516which now accepts two parameters;
10517you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>.
10518For the other operations,
10519the best choice is to use an external library.
10520</li>
10521
10522</ul>
10523
10524
10525
10526
10527<h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2>
10528
10529
10530<ul>
10531
10532<li>
10533Continuation functions now receive as parameters what they needed
10534to get through <code>lua_getctx</code>,
10535so <code>lua_getctx</code> has been removed.
10536Adapt your code accordingly.
10537</li>
10538
10539<li>
10540Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>.
10541Use 0 as the value of this parameter to get the old behavior.
10542</li>
10543
10544</ul>
10545
10546
10547
10548
10549<h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
10550
10551<p>
10552Here is the complete syntax of Lua in extended BNF.
10553(It does not describe operator precedences.)
10554
10555
10556
10557
10558<pre>
10559
10560	chunk ::= block
10561
10562	block ::= {stat} [retstat]
10563
10564	stat ::=  &lsquo;<b>;</b>&rsquo; |
10565		 varlist &lsquo;<b>=</b>&rsquo; explist |
10566		 functioncall |
10567		 label |
10568		 <b>break</b> |
10569		 <b>goto</b> Name |
10570		 <b>do</b> block <b>end</b> |
10571		 <b>while</b> exp <b>do</b> block <b>end</b> |
10572		 <b>repeat</b> block <b>until</b> exp |
10573		 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
10574		 <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> |
10575		 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
10576		 <b>function</b> funcname funcbody |
10577		 <b>local</b> <b>function</b> Name funcbody |
10578		 <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
10579
10580	retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
10581
10582	label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
10583
10584	funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
10585
10586	varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
10587
10588	var ::=  Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
10589
10590	namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
10591
10592	explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
10593
10594	exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | &lsquo;<b>...</b>&rsquo; | functiondef |
10595		 prefixexp | tableconstructor | exp binop exp | unop exp
10596
10597	prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
10598
10599	functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
10600
10601	args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | String
10602
10603	functiondef ::= <b>function</b> funcbody
10604
10605	funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
10606
10607	parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
10608
10609	tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
10610
10611	fieldlist ::= field {fieldsep field} [fieldsep]
10612
10613	field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
10614
10615	fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
10616
10617	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; |
10618		 &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; |
10619		 &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; |
10620		 <b>and</b> | <b>or</b>
10621
10622	unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
10623
10624</pre>
10625
10626<p>
10627
10628
10629
10630
10631
10632
10633
10634
10635<HR>
10636<SMALL CLASS="footer">
10637Last update:
10638Thu Jun 19 17:13:19 BRT 2014
10639</SMALL>
10640<!--
10641Last change: updated for Lua 5.3.0 (work3)
10642-->
10643
10644</body></html>
10645
10646