]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Lua/doc/manual.html
AppPkg: Add the Lua interpreter and library.
[mirror_edk2.git] / AppPkg / Applications / Lua / doc / manual.html
CommitLineData
16a5fed6 1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<html>
3
4<head>
5<title>Lua 5.2 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.2 Reference Manual
17</h1>
18
19by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
20<p>
21<small>
22Copyright &copy; 2011&ndash;2013 Lua.org, PUC-Rio.
23Freely available under the terms of the
24<a href="http://www.lua.org/license.html">Lua license</a>.
25</small>
26<hr>
27<p>
28
29<a href="contents.html#contents">contents</A>
30&middot;
31<a href="contents.html#index">index</A>
32
33<!-- ====================================================================== -->
34<p>
35
36<!-- $Id: manual.of,v 1.103 2013/03/14 18:51:56 roberto Exp $ -->
37
38
39
40
41<h1>1 &ndash; <a name="1">Introduction</a></h1>
42
43<p>
44Lua is an extension programming language designed to support
45general procedural programming with data description
46facilities.
47It also offers good support for object-oriented programming,
48functional programming, and data-driven programming.
49Lua is intended to be used as a powerful, lightweight,
50embeddable scripting language for any program that needs one.
51Lua is implemented as a library, written in <em>clean C</em>,
52the common subset of Standard&nbsp;C and C++.
53
54
55<p>
56Being an extension language, Lua has no notion of a "main" program:
57it only works <em>embedded</em> in a host client,
58called the <em>embedding program</em> or simply the <em>host</em>.
59The host program can invoke functions to execute a piece of Lua code,
60can write and read Lua variables,
61and can register C&nbsp;functions to be called by Lua code.
62Through the use of C&nbsp;functions, Lua can be augmented to cope with
63a wide range of different domains,
64thus creating customized programming languages sharing a syntactical framework.
65The Lua distribution includes a sample host program called <code>lua</code>,
66which uses the Lua library to offer a complete, standalone Lua interpreter,
67for interactive or batch use.
68
69
70<p>
71Lua is free software,
72and is provided as usual with no guarantees,
73as stated in its license.
74The implementation described in this manual is available
75at Lua's official web site, <code>www.lua.org</code>.
76
77
78<p>
79Like any other reference manual,
80this document is dry in places.
81For a discussion of the decisions behind the design of Lua,
82see the technical papers available at Lua's web site.
83For a detailed introduction to programming in Lua,
84see Roberto's book, <em>Programming in Lua</em>.
85
86
87
88<h1>2 &ndash; <a name="2">Basic Concepts</a></h1>
89
90<p>
91This section describes the basic concepts of the language.
92
93
94
95<h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2>
96
97<p>
98Lua is a <em>dynamically typed language</em>.
99This means that
100variables do not have types; only values do.
101There are no type definitions in the language.
102All values carry their own type.
103
104
105<p>
106All values in Lua are <em>first-class values</em>.
107This means that all values can be stored in variables,
108passed as arguments to other functions, and returned as results.
109
110
111<p>
112There are eight basic types in Lua:
113<em>nil</em>, <em>boolean</em>, <em>number</em>,
114<em>string</em>, <em>function</em>, <em>userdata</em>,
115<em>thread</em>, and <em>table</em>.
116<em>Nil</em> is the type of the value <b>nil</b>,
117whose main property is to be different from any other value;
118it usually represents the absence of a useful value.
119<em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
120Both <b>nil</b> and <b>false</b> make a condition false;
121any other value makes it true.
122<em>Number</em> represents real (double-precision floating-point) numbers.
123Operations on numbers follow the same rules of
124the underlying C&nbsp;implementation,
125which, in turn, usually follows the IEEE 754 standard.
126(It is easy to build Lua interpreters that use other
127internal representations for numbers,
128such as single-precision floats or long integers;
129see file <code>luaconf.h</code>.)
130<em>String</em> represents immutable sequences of bytes.
131
132Lua is 8-bit clean:
133strings can contain any 8-bit value,
134including embedded zeros ('<code>\0</code>').
135
136
137<p>
138Lua can call (and manipulate) functions written in Lua and
139functions written in C
140(see <a href="#3.4.9">&sect;3.4.9</a>).
141
142
143<p>
144The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
145be stored in Lua variables.
146A userdata value is a pointer to a block of raw memory.
147There are two kinds of userdata:
148full userdata, where the block of memory is managed by Lua,
149and light userdata, where the block of memory is managed by the host.
150Userdata has no predefined operations in Lua,
151except assignment and identity test.
152By using <em>metatables</em>,
153the programmer can define operations for full userdata values
154(see <a href="#2.4">&sect;2.4</a>).
155Userdata values cannot be created or modified in Lua,
156only through the C&nbsp;API.
157This guarantees the integrity of data owned by the host program.
158
159
160<p>
161The type <em>thread</em> represents independent threads of execution
162and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
163Do not confuse Lua threads with operating-system threads.
164Lua supports coroutines on all systems,
165even those that do not support threads.
166
167
168<p>
169The type <em>table</em> implements associative arrays,
170that is, arrays that can be indexed not only with numbers,
171but with any Lua value except <b>nil</b> and NaN
172(<em>Not a Number</em>, a special numeric value used to represent
173undefined or unrepresentable results, such as <code>0/0</code>).
174Tables can be <em>heterogeneous</em>;
175that is, they can contain values of all types (except <b>nil</b>).
176Any key with value <b>nil</b> is not considered part of the table.
177Conversely, any key that is not part of a table has
178an associated value <b>nil</b>.
179
180
181<p>
182Tables are the sole data structuring mechanism in Lua;
183they can be used to represent ordinary arrays, sequences,
184symbol tables, sets, records, graphs, trees, etc.
185To represent records, Lua uses the field name as an index.
186The language supports this representation by
187providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
188There are several convenient ways to create tables in Lua
189(see <a href="#3.4.8">&sect;3.4.8</a>).
190
191
192<p>
193We use the term <em>sequence</em> to denote a table where
194the set of all positive numeric keys is equal to <em>{1..n}</em>
195for some integer <em>n</em>,
196which is called the length of the sequence (see <a href="#3.4.6">&sect;3.4.6</a>).
197
198
199<p>
200Like indices,
201the values of table fields can be of any type.
202In particular,
203because functions are first-class values,
204table fields can contain functions.
205Thus tables can also carry <em>methods</em> (see <a href="#3.4.10">&sect;3.4.10</a>).
206
207
208<p>
209The indexing of tables follows
210the definition of raw equality in the language.
211The expressions <code>a[i]</code> and <code>a[j]</code>
212denote the same table element
213if and only if <code>i</code> and <code>j</code> are raw equal
214(that is, equal without metamethods).
215
216
217<p>
218Tables, functions, threads, and (full) userdata values are <em>objects</em>:
219variables do not actually <em>contain</em> these values,
220only <em>references</em> to them.
221Assignment, parameter passing, and function returns
222always manipulate references to such values;
223these operations do not imply any kind of copy.
224
225
226<p>
227The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
228of a given value (see <a href="#6.1">&sect;6.1</a>).
229
230
231
232
233
234<h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2>
235
236<p>
237As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
238any reference to a global name <code>var</code> is syntactically translated
239to <code>_ENV.var</code>.
240Moreover, every chunk is compiled in the scope of
241an external local variable called <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
242so <code>_ENV</code> itself is never a global name in a chunk.
243
244
245<p>
246Despite the existence of this external <code>_ENV</code> variable and
247the translation of global names,
248<code>_ENV</code> is a completely regular name.
249In particular,
250you can define new variables and parameters with that name.
251Each reference to a global name uses the <code>_ENV</code> that is
252visible at that point in the program,
253following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
254
255
256<p>
257Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
258
259
260<p>
261Lua keeps a distinguished environment called the <em>global environment</em>.
262This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
263In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
264
265
266<p>
267When Lua compiles a chunk,
268it initializes the value of its <code>_ENV</code> upvalue
269with the global environment (see <a href="#pdf-load"><code>load</code></a>).
270Therefore, by default,
271global variables in Lua code refer to entries in the global environment.
272Moreover, all standard libraries are loaded in the global environment
273and several functions there operate on that environment.
274You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
275to load a chunk with a different environment.
276(In C, you have to load the chunk and then change the value
277of its first upvalue.)
278
279
280<p>
281If you change the global environment in the registry
282(through C code or the debug library),
283all chunks loaded after the change will get the new environment.
284Previously loaded chunks are not affected, however,
285as each has its own reference to the environment in its <code>_ENV</code> variable.
286Moreover, the variable <a href="#pdf-_G"><code>_G</code></a>
287(which is stored in the original global environment)
288is never updated by Lua.
289
290
291
292
293
294<h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
295
296<p>
297Because Lua is an embedded extension language,
298all Lua actions start from C&nbsp;code in the host program
299calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
300Whenever an error occurs during
301the compilation or execution of a Lua chunk,
302control returns to the host,
303which can take appropriate measures
304(such as printing an error message).
305
306
307<p>
308Lua code can explicitly generate an error by calling the
309<a href="#pdf-error"><code>error</code></a> function.
310If you need to catch errors in Lua,
311you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
312to call a given function in <em>protected mode</em>.
313
314
315<p>
316Whenever there is an error,
317an <em>error object</em> (also called an <em>error message</em>)
318is propagated with information about the error.
319Lua itself only generates errors where the error object is a string,
320but programs may generate errors with
321any value for the error object.
322
323
324<p>
325When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
326you may give a <em>message handler</em>
327to be called in case of errors.
328This function is called with the original error message
329and returns a new error message.
330It is called before the error unwinds the stack,
331so that it can gather more information about the error,
332for instance by inspecting the stack and creating a stack traceback.
333This message handler is still protected by the protected call;
334so, an error inside the message handler
335will call the message handler again.
336If this loop goes on, Lua breaks it and returns an appropriate message.
337
338
339
340
341
342<h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2>
343
344<p>
345Every value in Lua can have a <em>metatable</em>.
346This <em>metatable</em> is an ordinary Lua table
347that defines the behavior of the original value
348under certain special operations.
349You can change several aspects of the behavior
350of operations over a value by setting specific fields in its metatable.
351For instance, when a non-numeric value is the operand of an addition,
352Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
353If it finds one,
354Lua calls this function to perform the addition.
355
356
357<p>
358The keys in a metatable are derived from the <em>event</em> names;
359the corresponding values are called <em>metamethods</em>.
360In the previous example, the event is <code>"add"</code>
361and the metamethod is the function that performs the addition.
362
363
364<p>
365You can query the metatable of any value
366using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
367
368
369<p>
370You can replace the metatable of tables
371using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
372You cannot change the metatable of other types from Lua
373(except by using the debug library);
374you must use the C&nbsp;API for that.
375
376
377<p>
378Tables and full userdata have individual metatables
379(although multiple tables and userdata can share their metatables).
380Values of all other types share one single metatable per type;
381that is, there is one single metatable for all numbers,
382one for all strings, etc.
383By default, a value has no metatable,
384but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>).
385
386
387<p>
388A metatable controls how an object behaves in arithmetic operations,
389order comparisons, concatenation, length operation, and indexing.
390A metatable also can define a function to be called
391when a userdata or a table is garbage collected.
392When Lua performs one of these operations over a value,
393it checks whether this value has a metatable with the corresponding event.
394If so, the value associated with that key (the metamethod)
395controls how Lua will perform the operation.
396
397
398<p>
399Metatables control the operations listed next.
400Each operation is identified by its corresponding name.
401The key for each operation is a string with its name prefixed by
402two underscores, '<code>__</code>';
403for instance, the key for operation "add" is the
404string "<code>__add</code>".
405
406
407<p>
408The semantics of these operations is better explained by a Lua function
409describing how the interpreter executes the operation.
410The code shown here in Lua is only illustrative;
411the real behavior is hard coded in the interpreter
412and it is much more efficient than this simulation.
413All functions used in these descriptions
414(<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
415are described in <a href="#6.1">&sect;6.1</a>.
416In particular, to retrieve the metamethod of a given object,
417we use the expression
418
419<pre>
420 metatable(obj)[event]
421</pre><p>
422This should be read as
423
424<pre>
425 rawget(getmetatable(obj) or {}, event)
426</pre><p>
427This means that the access to a metamethod does not invoke other metamethods,
428and access to objects with no metatables does not fail
429(it simply results in <b>nil</b>).
430
431
432<p>
433For the unary <code>-</code> and <code>#</code> operators,
434the metamethod is called with a dummy second argument.
435This extra argument is only to simplify Lua's internals;
436it may be removed in future versions and therefore it is not present
437in the following code.
438(For most uses this extra argument is irrelevant.)
439
440
441
442<ul>
443
444<li><b>"add": </b>
445the <code>+</code> operation.
446
447
448
449<p>
450The function <code>getbinhandler</code> below defines how Lua chooses a handler
451for a binary operation.
452First, Lua tries the first operand.
453If its type does not define a handler for the operation,
454then Lua tries the second operand.
455
456<pre>
457 function getbinhandler (op1, op2, event)
458 return metatable(op1)[event] or metatable(op2)[event]
459 end
460</pre><p>
461By using this function,
462the behavior of the <code>op1 + op2</code> is
463
464<pre>
465 function add_event (op1, op2)
466 local o1, o2 = tonumber(op1), tonumber(op2)
467 if o1 and o2 then -- both operands are numeric?
468 return o1 + o2 -- '+' here is the primitive 'add'
469 else -- at least one of the operands is not numeric
470 local h = getbinhandler(op1, op2, "__add")
471 if h then
472 -- call the handler with both operands
473 return (h(op1, op2))
474 else -- no handler available: default behavior
475 error(&middot;&middot;&middot;)
476 end
477 end
478 end
479</pre><p>
480</li>
481
482<li><b>"sub": </b>
483the <code>-</code> operation.
484
485Behavior similar to the "add" operation.
486</li>
487
488<li><b>"mul": </b>
489the <code>*</code> operation.
490
491Behavior similar to the "add" operation.
492</li>
493
494<li><b>"div": </b>
495the <code>/</code> operation.
496
497Behavior similar to the "add" operation.
498</li>
499
500<li><b>"mod": </b>
501the <code>%</code> operation.
502
503Behavior similar to the "add" operation,
504with the operation
505<code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
506</li>
507
508<li><b>"pow": </b>
509the <code>^</code> (exponentiation) operation.
510
511Behavior similar to the "add" operation,
512with the function <code>pow</code> (from the C&nbsp;math library)
513as the primitive operation.
514</li>
515
516<li><b>"unm": </b>
517the unary <code>-</code> operation.
518
519
520<pre>
521 function unm_event (op)
522 local o = tonumber(op)
523 if o then -- operand is numeric?
524 return -o -- '-' here is the primitive 'unm'
525 else -- the operand is not numeric.
526 -- Try to get a handler from the operand
527 local h = metatable(op).__unm
528 if h then
529 -- call the handler with the operand
530 return (h(op))
531 else -- no handler available: default behavior
532 error(&middot;&middot;&middot;)
533 end
534 end
535 end
536</pre><p>
537</li>
538
539<li><b>"concat": </b>
540the <code>..</code> (concatenation) operation.
541
542
543<pre>
544 function concat_event (op1, op2)
545 if (type(op1) == "string" or type(op1) == "number") and
546 (type(op2) == "string" or type(op2) == "number") then
547 return op1 .. op2 -- primitive string concatenation
548 else
549 local h = getbinhandler(op1, op2, "__concat")
550 if h then
551 return (h(op1, op2))
552 else
553 error(&middot;&middot;&middot;)
554 end
555 end
556 end
557</pre><p>
558</li>
559
560<li><b>"len": </b>
561the <code>#</code> operation.
562
563
564<pre>
565 function len_event (op)
566 if type(op) == "string" then
567 return strlen(op) -- primitive string length
568 else
569 local h = metatable(op).__len
570 if h then
571 return (h(op)) -- call handler with the operand
572 elseif type(op) == "table" then
573 return #op -- primitive table length
574 else -- no handler available: error
575 error(&middot;&middot;&middot;)
576 end
577 end
578 end
579</pre><p>
580See <a href="#3.4.6">&sect;3.4.6</a> for a description of the length of a table.
581</li>
582
583<li><b>"eq": </b>
584the <code>==</code> operation.
585
586The function <code>getequalhandler</code> defines how Lua chooses a metamethod
587for equality.
588A metamethod is selected only when both values
589being compared have the same type
590and the same metamethod for the selected operation,
591and the values are either tables or full userdata.
592
593<pre>
594 function getequalhandler (op1, op2)
595 if type(op1) ~= type(op2) or
596 (type(op1) ~= "table" and type(op1) ~= "userdata") then
597 return nil -- different values
598 end
599 local mm1 = metatable(op1).__eq
600 local mm2 = metatable(op2).__eq
601 if mm1 == mm2 then return mm1 else return nil end
602 end
603</pre><p>
604The "eq" event is defined as follows:
605
606<pre>
607 function eq_event (op1, op2)
608 if op1 == op2 then -- primitive equal?
609 return true -- values are equal
610 end
611 -- try metamethod
612 local h = getequalhandler(op1, op2)
613 if h then
614 return not not h(op1, op2)
615 else
616 return false
617 end
618 end
619</pre><p>
620Note that the result is always a boolean.
621</li>
622
623<li><b>"lt": </b>
624the <code>&lt;</code> operation.
625
626
627<pre>
628 function lt_event (op1, op2)
629 if type(op1) == "number" and type(op2) == "number" then
630 return op1 &lt; op2 -- numeric comparison
631 elseif type(op1) == "string" and type(op2) == "string" then
632 return op1 &lt; op2 -- lexicographic comparison
633 else
634 local h = getbinhandler(op1, op2, "__lt")
635 if h then
636 return not not h(op1, op2)
637 else
638 error(&middot;&middot;&middot;)
639 end
640 end
641 end
642</pre><p>
643Note that the result is always a boolean.
644</li>
645
646<li><b>"le": </b>
647the <code>&lt;=</code> operation.
648
649
650<pre>
651 function le_event (op1, op2)
652 if type(op1) == "number" and type(op2) == "number" then
653 return op1 &lt;= op2 -- numeric comparison
654 elseif type(op1) == "string" and type(op2) == "string" then
655 return op1 &lt;= op2 -- lexicographic comparison
656 else
657 local h = getbinhandler(op1, op2, "__le")
658 if h then
659 return not not h(op1, op2)
660 else
661 h = getbinhandler(op1, op2, "__lt")
662 if h then
663 return not h(op2, op1)
664 else
665 error(&middot;&middot;&middot;)
666 end
667 end
668 end
669 end
670</pre><p>
671Note that, in the absence of a "le" metamethod,
672Lua tries the "lt", assuming that <code>a &lt;= b</code> is
673equivalent to <code>not (b &lt; a)</code>.
674
675
676<p>
677As with the other comparison operators,
678the result is always a boolean.
679</li>
680
681<li><b>"index": </b>
682The indexing access <code>table[key]</code>.
683Note that the metamethod is tried only
684when <code>key</code> is not present in <code>table</code>.
685(When <code>table</code> is not a table,
686no key is ever present,
687so the metamethod is always tried.)
688
689
690<pre>
691 function gettable_event (table, key)
692 local h
693 if type(table) == "table" then
694 local v = rawget(table, key)
695 -- if key is present, return raw value
696 if v ~= nil then return v end
697 h = metatable(table).__index
698 if h == nil then return nil end
699 else
700 h = metatable(table).__index
701 if h == nil then
702 error(&middot;&middot;&middot;)
703 end
704 end
705 if type(h) == "function" then
706 return (h(table, key)) -- call the handler
707 else return h[key] -- or repeat operation on it
708 end
709 end
710</pre><p>
711</li>
712
713<li><b>"newindex": </b>
714The indexing assignment <code>table[key] = value</code>.
715Note that the metamethod is tried only
716when <code>key</code> is not present in <code>table</code>.
717
718
719<pre>
720 function settable_event (table, key, value)
721 local h
722 if type(table) == "table" then
723 local v = rawget(table, key)
724 -- if key is present, do raw assignment
725 if v ~= nil then rawset(table, key, value); return end
726 h = metatable(table).__newindex
727 if h == nil then rawset(table, key, value); return end
728 else
729 h = metatable(table).__newindex
730 if h == nil then
731 error(&middot;&middot;&middot;)
732 end
733 end
734 if type(h) == "function" then
735 h(table, key,value) -- call the handler
736 else h[key] = value -- or repeat operation on it
737 end
738 end
739</pre><p>
740</li>
741
742<li><b>"call": </b>
743called when Lua calls a value.
744
745
746<pre>
747 function function_event (func, ...)
748 if type(func) == "function" then
749 return func(...) -- primitive call
750 else
751 local h = metatable(func).__call
752 if h then
753 return h(func, ...)
754 else
755 error(&middot;&middot;&middot;)
756 end
757 end
758 end
759</pre><p>
760</li>
761
762</ul>
763
764
765
766
767<h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2>
768
769<p>
770Lua performs automatic memory management.
771This means that
772you have to worry neither about allocating memory for new objects
773nor about freeing it when the objects are no longer needed.
774Lua manages memory automatically by running
775a <em>garbage collector</em> to collect all <em>dead objects</em>
776(that is, objects that are no longer accessible from Lua).
777All memory used by Lua is subject to automatic management:
778strings, tables, userdata, functions, threads, internal structures, etc.
779
780
781<p>
782Lua implements an incremental mark-and-sweep collector.
783It uses two numbers to control its garbage-collection cycles:
784the <em>garbage-collector pause</em> and
785the <em>garbage-collector step multiplier</em>.
786Both use percentage points as units
787(e.g., a value of 100 means an internal value of 1).
788
789
790<p>
791The garbage-collector pause
792controls how long the collector waits before starting a new cycle.
793Larger values make the collector less aggressive.
794Values smaller than 100 mean the collector will not wait to
795start a new cycle.
796A value of 200 means that the collector waits for the total memory in use
797to double before starting a new cycle.
798
799
800<p>
801The garbage-collector step multiplier
802controls the relative speed of the collector relative to
803memory allocation.
804Larger values make the collector more aggressive but also increase
805the size of each incremental step.
806Values smaller than 100 make the collector too slow and
807can result in the collector never finishing a cycle.
808The default is 200,
809which means that the collector runs at "twice"
810the speed of memory allocation.
811
812
813<p>
814If you set the step multiplier to a very large number
815(larger than 10% of the maximum number of
816bytes that the program may use),
817the collector behaves like a stop-the-world collector.
818If you then set the pause to 200,
819the collector behaves as in old Lua versions,
820doing a complete collection every time Lua doubles its
821memory usage.
822
823
824<p>
825You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
826or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
827You can also use these functions to control
828the collector directly (e.g., stop and restart it).
829
830
831<p>
832As an experimental feature in Lua 5.2,
833you can change the collector's operation mode
834from incremental to <em>generational</em>.
835A <em>generational collector</em> assumes that most objects die young,
836and therefore it traverses only young (recently created) objects.
837This behavior can reduce the time used by the collector,
838but also increases memory usage (as old dead objects may accumulate).
839To mitigate this second problem,
840from time to time the generational collector performs a full collection.
841Remember that this is an experimental feature;
842you are welcome to try it,
843but check your gains.
844
845
846
847<h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
848
849<p>
850You can set garbage-collector metamethods for tables
851and, using the C&nbsp;API,
852for full userdata (see <a href="#2.4">&sect;2.4</a>).
853These metamethods are also called <em>finalizers</em>.
854Finalizers allow you to coordinate Lua's garbage collection
855with external resource management
856(such as closing files, network or database connections,
857or freeing your own memory).
858
859
860<p>
861For an object (table or userdata) to be finalized when collected,
862you must <em>mark</em> it for finalization.
863
864You mark an object for finalization when you set its metatable
865and the metatable has a field indexed by the string "<code>__gc</code>".
866Note that if you set a metatable without a <code>__gc</code> field
867and later create that field in the metatable,
868the object will not be marked for finalization.
869However, after an object is marked,
870you can freely change the <code>__gc</code> field of its metatable.
871
872
873<p>
874When a marked object becomes garbage,
875it is not collected immediately by the garbage collector.
876Instead, Lua puts it in a list.
877After the collection,
878Lua does the equivalent of the following function
879for each object in that list:
880
881<pre>
882 function gc_event (obj)
883 local h = metatable(obj).__gc
884 if type(h) == "function" then
885 h(obj)
886 end
887 end
888</pre>
889
890<p>
891At the end of each garbage-collection cycle,
892the finalizers for objects are called in
893the reverse order that they were marked for collection,
894among those collected in that cycle;
895that is, the first finalizer to be called is the one associated
896with the object marked last in the program.
897The execution of each finalizer may occur at any point during
898the execution of the regular code.
899
900
901<p>
902Because the object being collected must still be used by the finalizer,
903it (and other objects accessible only through it)
904must be <em>resurrected</em> by Lua.
905Usually, this resurrection is transient,
906and the object memory is freed in the next garbage-collection cycle.
907However, if the finalizer stores the object in some global place
908(e.g., a global variable),
909then there is a permanent resurrection.
910In any case,
911the object memory is freed only when it becomes completely inaccessible;
912its finalizer will never be called twice.
913
914
915<p>
916When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
917Lua calls the finalizers of all objects marked for finalization,
918following the reverse order that they were marked.
919If any finalizer marks new objects for collection during that phase,
920these new objects will not be finalized.
921
922
923
924
925
926<h3>2.5.2 &ndash; <a name="2.5.2">Weak Tables</a></h3>
927
928<p>
929A <em>weak table</em> is a table whose elements are
930<em>weak references</em>.
931A weak reference is ignored by the garbage collector.
932In other words,
933if the only references to an object are weak references,
934then the garbage collector will collect that object.
935
936
937<p>
938A weak table can have weak keys, weak values, or both.
939A table with weak keys allows the collection of its keys,
940but prevents the collection of its values.
941A table with both weak keys and weak values allows the collection of
942both keys and values.
943In any case, if either the key or the value is collected,
944the whole pair is removed from the table.
945The weakness of a table is controlled by the
946<code>__mode</code> field of its metatable.
947If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
948the keys in the table are weak.
949If <code>__mode</code> contains '<code>v</code>',
950the values in the table are weak.
951
952
953<p>
954A table with weak keys and strong values
955is also called an <em>ephemeron table</em>.
956In an ephemeron table,
957a value is considered reachable only if its key is reachable.
958In particular,
959if the only reference to a key comes through its value,
960the pair is removed.
961
962
963<p>
964Any change in the weakness of a table may take effect only
965at the next collect cycle.
966In particular, if you change the weakness to a stronger mode,
967Lua may still collect some items from that table
968before the change takes effect.
969
970
971<p>
972Only objects that have an explicit construction
973are removed from weak tables.
974Values, such as numbers and light C functions,
975are not subject to garbage collection,
976and therefore are not removed from weak tables
977(unless its associated value is collected).
978Although strings are subject to garbage collection,
979they do not have an explicit construction,
980and therefore are not removed from weak tables.
981
982
983<p>
984Resurrected objects
985(that is, objects being finalized
986and objects accessible only through objects being finalized)
987have a special behavior in weak tables.
988They are removed from weak values before running their finalizers,
989but are removed from weak keys only in the next collection
990after running their finalizers, when such objects are actually freed.
991This behavior allows the finalizer to access properties
992associated with the object through weak tables.
993
994
995<p>
996If a weak table is among the resurrected objects in a collection cycle,
997it may not be properly cleared until the next cycle.
998
999
1000
1001
1002
1003
1004
1005<h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2>
1006
1007<p>
1008Lua supports coroutines,
1009also called <em>collaborative multithreading</em>.
1010A coroutine in Lua represents an independent thread of execution.
1011Unlike threads in multithread systems, however,
1012a coroutine only suspends its execution by explicitly calling
1013a yield function.
1014
1015
1016<p>
1017You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1018Its sole argument is a function
1019that is the main function of the coroutine.
1020The <code>create</code> function only creates a new coroutine and
1021returns a handle to it (an object of type <em>thread</em>);
1022it does not start the coroutine.
1023
1024
1025<p>
1026You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1027When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1028passing as its first argument
1029a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1030the coroutine starts its execution,
1031at the first line of its main function.
1032Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
1033to the coroutine main function.
1034After the coroutine starts running,
1035it runs until it terminates or <em>yields</em>.
1036
1037
1038<p>
1039A coroutine can terminate its execution in two ways:
1040normally, when its main function returns
1041(explicitly or implicitly, after the last instruction);
1042and abnormally, if there is an unprotected error.
1043In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1044plus any values returned by the coroutine main function.
1045In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1046plus an error message.
1047
1048
1049<p>
1050A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1051When a coroutine yields,
1052the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1053even if the yield happens inside nested function calls
1054(that is, not in the main function,
1055but in a function directly or indirectly called by the main function).
1056In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1057plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1058The next time you resume the same coroutine,
1059it continues its execution from the point where it yielded,
1060with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1061arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1062
1063
1064<p>
1065Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1066the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1067but instead of returning the coroutine itself,
1068it returns a function that, when called, resumes the coroutine.
1069Any arguments passed to this function
1070go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1071<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>,
1072except the first one (the boolean error code).
1073Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1074<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
1075any error is propagated to the caller.
1076
1077
1078<p>
1079As an example of how coroutines work,
1080consider the following code:
1081
1082<pre>
1083 function foo (a)
1084 print("foo", a)
1085 return coroutine.yield(2*a)
1086 end
1087
1088 co = coroutine.create(function (a,b)
1089 print("co-body", a, b)
1090 local r = foo(a+1)
1091 print("co-body", r)
1092 local r, s = coroutine.yield(a+b, a-b)
1093 print("co-body", r, s)
1094 return b, "end"
1095 end)
1096
1097 print("main", coroutine.resume(co, 1, 10))
1098 print("main", coroutine.resume(co, "r"))
1099 print("main", coroutine.resume(co, "x", "y"))
1100 print("main", coroutine.resume(co, "x", "y"))
1101</pre><p>
1102When you run it, it produces the following output:
1103
1104<pre>
1105 co-body 1 10
1106 foo 2
1107 main true 4
1108 co-body r
1109 main true 11 -9
1110 co-body x y
1111 main true 10 end
1112 main false cannot resume dead coroutine
1113</pre>
1114
1115<p>
1116You can also create and manipulate coroutines through the C API:
1117see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1118and <a href="#lua_yield"><code>lua_yield</code></a>.
1119
1120
1121
1122
1123
1124<h1>3 &ndash; <a name="3">The Language</a></h1>
1125
1126<p>
1127This section describes the lexis, the syntax, and the semantics of Lua.
1128In other words,
1129this section describes
1130which tokens are valid,
1131how they can be combined,
1132and what their combinations mean.
1133
1134
1135<p>
1136Language constructs will be explained using the usual extended BNF notation,
1137in which
1138{<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
1139[<em>a</em>]&nbsp;means an optional <em>a</em>.
1140Non-terminals are shown like non-terminal,
1141keywords are shown like <b>kword</b>,
1142and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;.
1143The complete syntax of Lua can be found in <a href="#9">&sect;9</a>
1144at the end of this manual.
1145
1146
1147
1148<h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2>
1149
1150<p>
1151Lua is a free-form language.
1152It ignores spaces (including new lines) and comments
1153between lexical elements (tokens),
1154except as delimiters between names and keywords.
1155
1156
1157<p>
1158<em>Names</em>
1159(also called <em>identifiers</em>)
1160in Lua can be any string of letters,
1161digits, and underscores,
1162not beginning with a digit.
1163Identifiers are used to name variables, table fields, and labels.
1164
1165
1166<p>
1167The following <em>keywords</em> are reserved
1168and cannot be used as names:
1169
1170
1171<pre>
1172 and break do else elseif end
1173 false for function goto if in
1174 local nil not or repeat return
1175 then true until while
1176</pre>
1177
1178<p>
1179Lua is a case-sensitive language:
1180<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1181are two different, valid names.
1182As a convention, names starting with an underscore followed by
1183uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
1184are reserved for variables used by Lua.
1185
1186
1187<p>
1188The following strings denote other tokens:
1189
1190<pre>
1191 + - * / % ^ #
1192 == ~= &lt;= &gt;= &lt; &gt; =
1193 ( ) { } [ ] ::
1194 ; : , . .. ...
1195</pre>
1196
1197<p>
1198<em>Literal strings</em>
1199can be delimited by matching single or double quotes,
1200and can contain the following C-like escape sequences:
1201'<code>\a</code>' (bell),
1202'<code>\b</code>' (backspace),
1203'<code>\f</code>' (form feed),
1204'<code>\n</code>' (newline),
1205'<code>\r</code>' (carriage return),
1206'<code>\t</code>' (horizontal tab),
1207'<code>\v</code>' (vertical tab),
1208'<code>\\</code>' (backslash),
1209'<code>\"</code>' (quotation mark [double quote]),
1210and '<code>\'</code>' (apostrophe [single quote]).
1211A backslash followed by a real newline
1212results in a newline in the string.
1213The escape sequence '<code>\z</code>' skips the following span
1214of white-space characters,
1215including line breaks;
1216it is particularly useful to break and indent a long literal string
1217into multiple lines without adding the newlines and spaces
1218into the string contents.
1219
1220
1221<p>
1222A byte in a literal string can also be specified by its numerical value.
1223This can be done with the escape sequence <code>\x<em>XX</em></code>,
1224where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1225or with the escape sequence <code>\<em>ddd</em></code>,
1226where <em>ddd</em> is a sequence of up to three decimal digits.
1227(Note that if a decimal escape is to be followed by a digit,
1228it must be expressed using exactly three digits.)
1229Strings in Lua can contain any 8-bit value, including embedded zeros,
1230which can be specified as '<code>\0</code>'.
1231
1232
1233<p>
1234Literal strings can also be defined using a long format
1235enclosed by <em>long brackets</em>.
1236We define an <em>opening long bracket of level <em>n</em></em> as an opening
1237square bracket followed by <em>n</em> equal signs followed by another
1238opening square bracket.
1239So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1240an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1241and so on.
1242A <em>closing long bracket</em> is defined similarly;
1243for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
1244A <em>long literal</em> starts with an opening long bracket of any level and
1245ends at the first closing long bracket of the same level.
1246It can contain any text except a closing bracket of the proper level.
1247Literals in this bracketed form can run for several lines,
1248do not interpret any escape sequences,
1249and ignore long brackets of any other level.
1250Any kind of end-of-line sequence
1251(carriage return, newline, carriage return followed by newline,
1252or newline followed by carriage return)
1253is converted to a simple newline.
1254
1255
1256<p>
1257Any byte in a literal string not
1258explicitly affected by the previous rules represents itself.
1259However, Lua opens files for parsing in text mode,
1260and the system file functions may have problems with
1261some control characters.
1262So, it is safer to represent
1263non-text data as a quoted literal with
1264explicit escape sequences for non-text characters.
1265
1266
1267<p>
1268For convenience,
1269when the opening long bracket is immediately followed by a newline,
1270the newline is not included in the string.
1271As an example, in a system using ASCII
1272(in which '<code>a</code>' is coded as&nbsp;97,
1273newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
1274the five literal strings below denote the same string:
1275
1276<pre>
1277 a = 'alo\n123"'
1278 a = "alo\n123\""
1279 a = '\97lo\10\04923"'
1280 a = [[alo
1281 123"]]
1282 a = [==[
1283 alo
1284 123"]==]
1285</pre>
1286
1287<p>
1288A <em>numerical constant</em> can be written with an optional fractional part
1289and an optional decimal exponent,
1290marked by a letter '<code>e</code>' or '<code>E</code>'.
1291Lua also accepts hexadecimal constants,
1292which start with <code>0x</code> or <code>0X</code>.
1293Hexadecimal constants also accept an optional fractional part
1294plus an optional binary exponent,
1295marked by a letter '<code>p</code>' or '<code>P</code>'.
1296Examples of valid numerical constants are
1297
1298<pre>
1299 3 3.0 3.1416 314.16e-2 0.31416E1
1300 0xff 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1301</pre>
1302
1303<p>
1304A <em>comment</em> starts with a double hyphen (<code>--</code>)
1305anywhere outside a string.
1306If the text immediately after <code>--</code> is not an opening long bracket,
1307the comment is a <em>short comment</em>,
1308which runs until the end of the line.
1309Otherwise, it is a <em>long comment</em>,
1310which runs until the corresponding closing long bracket.
1311Long comments are frequently used to disable code temporarily.
1312
1313
1314
1315
1316
1317<h2>3.2 &ndash; <a name="3.2">Variables</a></h2>
1318
1319<p>
1320Variables are places that store values.
1321There are three kinds of variables in Lua:
1322global variables, local variables, and table fields.
1323
1324
1325<p>
1326A single name can denote a global variable or a local variable
1327(or a function's formal parameter,
1328which is a particular kind of local variable):
1329
1330<pre>
1331 var ::= Name
1332</pre><p>
1333Name denotes identifiers, as defined in <a href="#3.1">&sect;3.1</a>.
1334
1335
1336<p>
1337Any variable name is assumed to be global unless explicitly declared
1338as a local (see <a href="#3.3.7">&sect;3.3.7</a>).
1339Local variables are <em>lexically scoped</em>:
1340local variables can be freely accessed by functions
1341defined inside their scope (see <a href="#3.5">&sect;3.5</a>).
1342
1343
1344<p>
1345Before the first assignment to a variable, its value is <b>nil</b>.
1346
1347
1348<p>
1349Square brackets are used to index a table:
1350
1351<pre>
1352 var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo;
1353</pre><p>
1354The meaning of accesses to table fields can be changed via metatables.
1355An access to an indexed variable <code>t[i]</code> is equivalent to
1356a call <code>gettable_event(t,i)</code>.
1357(See <a href="#2.4">&sect;2.4</a> for a complete description of the
1358<code>gettable_event</code> function.
1359This function is not defined or callable in Lua.
1360We use it here only for explanatory purposes.)
1361
1362
1363<p>
1364The syntax <code>var.Name</code> is just syntactic sugar for
1365<code>var["Name"]</code>:
1366
1367<pre>
1368 var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name
1369</pre>
1370
1371<p>
1372An access to a global variable <code>x</code>
1373is equivalent to <code>_ENV.x</code>.
1374Due to the way that chunks are compiled,
1375<code>_ENV</code> is never a global name (see <a href="#2.2">&sect;2.2</a>).
1376
1377
1378
1379
1380
1381<h2>3.3 &ndash; <a name="3.3">Statements</a></h2>
1382
1383<p>
1384Lua supports an almost conventional set of statements,
1385similar to those in Pascal or C.
1386This set includes
1387assignments, control structures, function calls,
1388and variable declarations.
1389
1390
1391
1392<h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3>
1393
1394<p>
1395A block is a list of statements,
1396which are executed sequentially:
1397
1398<pre>
1399 block ::= {stat}
1400</pre><p>
1401Lua has <em>empty statements</em>
1402that allow you to separate statements with semicolons,
1403start a block with a semicolon
1404or write two semicolons in sequence:
1405
1406<pre>
1407 stat ::= &lsquo;<b>;</b>&rsquo;
1408</pre>
1409
1410<p>
1411Function calls and assignments
1412can start with an open parenthesis.
1413This possibility leads to an ambiguity in Lua's grammar.
1414Consider the following fragment:
1415
1416<pre>
1417 a = b + c
1418 (print or io.write)('done')
1419</pre><p>
1420The grammar could see it in two ways:
1421
1422<pre>
1423 a = b + c(print or io.write)('done')
1424
1425 a = b + c; (print or io.write)('done')
1426</pre><p>
1427The current parser always sees such constructions
1428in the first way,
1429interpreting the open parenthesis
1430as the start of the arguments to a call.
1431To avoid this ambiguity,
1432it is a good practice to always precede with a semicolon
1433statements that start with a parenthesis:
1434
1435<pre>
1436 ;(print or io.write)('done')
1437</pre>
1438
1439<p>
1440A block can be explicitly delimited to produce a single statement:
1441
1442<pre>
1443 stat ::= <b>do</b> block <b>end</b>
1444</pre><p>
1445Explicit blocks are useful
1446to control the scope of variable declarations.
1447Explicit blocks are also sometimes used to
1448add a <b>return</b> statement in the middle
1449of another block (see <a href="#3.3.4">&sect;3.3.4</a>).
1450
1451
1452
1453
1454
1455<h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3>
1456
1457<p>
1458The unit of compilation of Lua is called a <em>chunk</em>.
1459Syntactically,
1460a chunk is simply a block:
1461
1462<pre>
1463 chunk ::= block
1464</pre>
1465
1466<p>
1467Lua handles a chunk as the body of an anonymous function
1468with a variable number of arguments
1469(see <a href="#3.4.10">&sect;3.4.10</a>).
1470As such, chunks can define local variables,
1471receive arguments, and return values.
1472Moreover, such anonymous function is compiled as in the
1473scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>).
1474The resulting function always has <code>_ENV</code> as its only upvalue,
1475even if it does not use that variable.
1476
1477
1478<p>
1479A chunk can be stored in a file or in a string inside the host program.
1480To execute a chunk,
1481Lua first precompiles the chunk into instructions for a virtual machine,
1482and then it executes the compiled code
1483with an interpreter for the virtual machine.
1484
1485
1486<p>
1487Chunks can also be precompiled into binary form;
1488see program <code>luac</code> for details.
1489Programs in source and compiled forms are interchangeable;
1490Lua automatically detects the file type and acts accordingly.
1491
1492
1493
1494
1495
1496
1497<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
1498
1499<p>
1500Lua allows multiple assignments.
1501Therefore, the syntax for assignment
1502defines a list of variables on the left side
1503and a list of expressions on the right side.
1504The elements in both lists are separated by commas:
1505
1506<pre>
1507 stat ::= varlist &lsquo;<b>=</b>&rsquo; explist
1508 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
1509 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1510</pre><p>
1511Expressions are discussed in <a href="#3.4">&sect;3.4</a>.
1512
1513
1514<p>
1515Before the assignment,
1516the list of values is <em>adjusted</em> to the length of
1517the list of variables.
1518If there are more values than needed,
1519the excess values are thrown away.
1520If there are fewer values than needed,
1521the list is extended with as many <b>nil</b>'s as needed.
1522If the list of expressions ends with a function call,
1523then all values returned by that call enter the list of values,
1524before the adjustment
1525(except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>).
1526
1527
1528<p>
1529The assignment statement first evaluates all its expressions
1530and only then are the assignments performed.
1531Thus the code
1532
1533<pre>
1534 i = 3
1535 i, a[i] = i+1, 20
1536</pre><p>
1537sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1538because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1539before it is assigned&nbsp;4.
1540Similarly, the line
1541
1542<pre>
1543 x, y = y, x
1544</pre><p>
1545exchanges the values of <code>x</code> and <code>y</code>,
1546and
1547
1548<pre>
1549 x, y, z = y, z, x
1550</pre><p>
1551cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1552
1553
1554<p>
1555The meaning of assignments to global variables
1556and table fields can be changed via metatables.
1557An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
1558<code>settable_event(t,i,val)</code>.
1559(See <a href="#2.4">&sect;2.4</a> for a complete description of the
1560<code>settable_event</code> function.
1561This function is not defined or callable in Lua.
1562We use it here only for explanatory purposes.)
1563
1564
1565<p>
1566An assignment to a global variable <code>x = val</code>
1567is equivalent to the assignment
1568<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
1569
1570
1571
1572
1573
1574<h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p>
1575The control structures
1576<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
1577familiar syntax:
1578
1579
1580
1581
1582<pre>
1583 stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
1584 stat ::= <b>repeat</b> block <b>until</b> exp
1585 stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
1586</pre><p>
1587Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>).
1588
1589
1590<p>
1591The condition expression of a
1592control structure can return any value.
1593Both <b>false</b> and <b>nil</b> are considered false.
1594All values different from <b>nil</b> and <b>false</b> are considered true
1595(in particular, the number 0 and the empty string are also true).
1596
1597
1598<p>
1599In the <b>repeat</b>&ndash;<b>until</b> loop,
1600the inner block does not end at the <b>until</b> keyword,
1601but only after the condition.
1602So, the condition can refer to local variables
1603declared inside the loop block.
1604
1605
1606<p>
1607The <b>goto</b> statement transfers the program control to a label.
1608For syntactical reasons,
1609labels in Lua are considered statements too:
1610
1611
1612
1613<pre>
1614 stat ::= <b>goto</b> Name
1615 stat ::= label
1616 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
1617</pre>
1618
1619<p>
1620A label is visible in the entire block where it is defined,
1621except
1622inside nested blocks where a label with the same name is defined and
1623inside nested functions.
1624A goto may jump to any visible label as long as it does not
1625enter into the scope of a local variable.
1626
1627
1628<p>
1629Labels and empty statements are called <em>void statements</em>,
1630as they perform no actions.
1631
1632
1633<p>
1634The <b>break</b> statement terminates the execution of a
1635<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1636skipping to the next statement after the loop:
1637
1638
1639<pre>
1640 stat ::= <b>break</b>
1641</pre><p>
1642A <b>break</b> ends the innermost enclosing loop.
1643
1644
1645<p>
1646The <b>return</b> statement is used to return values
1647from a function or a chunk (which is a function in disguise).
1648
1649Functions can return more than one value,
1650so the syntax for the <b>return</b> statement is
1651
1652<pre>
1653 stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
1654</pre>
1655
1656<p>
1657The <b>return</b> statement can only be written
1658as the last statement of a block.
1659If it is really necessary to <b>return</b> in the middle of a block,
1660then an explicit inner block can be used,
1661as in the idiom <code>do return end</code>,
1662because now <b>return</b> is the last statement in its (inner) block.
1663
1664
1665
1666
1667
1668<h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3>
1669
1670<p>
1671
1672The <b>for</b> statement has two forms:
1673one numeric and one generic.
1674
1675
1676<p>
1677The numeric <b>for</b> loop repeats a block of code while a
1678control variable runs through an arithmetic progression.
1679It has the following syntax:
1680
1681<pre>
1682 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>
1683</pre><p>
1684The <em>block</em> is repeated for <em>name</em> starting at the value of
1685the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
1686third <em>exp</em>.
1687More precisely, a <b>for</b> statement like
1688
1689<pre>
1690 for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
1691</pre><p>
1692is equivalent to the code:
1693
1694<pre>
1695 do
1696 local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
1697 if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
1698 while (<em>step</em> &gt; 0 and <em>var</em> &lt;= <em>limit</em>) or (<em>step</em> &lt;= 0 and <em>var</em> &gt;= <em>limit</em>) do
1699 local v = <em>var</em>
1700 <em>block</em>
1701 <em>var</em> = <em>var</em> + <em>step</em>
1702 end
1703 end
1704</pre><p>
1705Note the following:
1706
1707<ul>
1708
1709<li>
1710All three control expressions are evaluated only once,
1711before the loop starts.
1712They must all result in numbers.
1713</li>
1714
1715<li>
1716<code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
1717The names shown here are for explanatory purposes only.
1718</li>
1719
1720<li>
1721If the third expression (the step) is absent,
1722then a step of&nbsp;1 is used.
1723</li>
1724
1725<li>
1726You can use <b>break</b> to exit a <b>for</b> loop.
1727</li>
1728
1729<li>
1730The loop variable <code>v</code> is local to the loop;
1731you cannot use its value after the <b>for</b> ends or is broken.
1732If you need this value,
1733assign it to another variable before breaking or exiting the loop.
1734</li>
1735
1736</ul>
1737
1738<p>
1739The generic <b>for</b> statement works over functions,
1740called <em>iterators</em>.
1741On each iteration, the iterator function is called to produce a new value,
1742stopping when this new value is <b>nil</b>.
1743The generic <b>for</b> loop has the following syntax:
1744
1745<pre>
1746 stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1747 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
1748</pre><p>
1749A <b>for</b> statement like
1750
1751<pre>
1752 for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end
1753</pre><p>
1754is equivalent to the code:
1755
1756<pre>
1757 do
1758 local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
1759 while true do
1760 local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>)
1761 if <em>var_1</em> == nil then break end
1762 <em>var</em> = <em>var_1</em>
1763 <em>block</em>
1764 end
1765 end
1766</pre><p>
1767Note the following:
1768
1769<ul>
1770
1771<li>
1772<code><em>explist</em></code> is evaluated only once.
1773Its results are an <em>iterator</em> function,
1774a <em>state</em>,
1775and an initial value for the first <em>iterator variable</em>.
1776</li>
1777
1778<li>
1779<code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
1780The names are here for explanatory purposes only.
1781</li>
1782
1783<li>
1784You can use <b>break</b> to exit a <b>for</b> loop.
1785</li>
1786
1787<li>
1788The loop variables <code><em>var_i</em></code> are local to the loop;
1789you cannot use their values after the <b>for</b> ends.
1790If you need these values,
1791then assign them to other variables before breaking or exiting the loop.
1792</li>
1793
1794</ul>
1795
1796
1797
1798
1799<h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p>
1800To allow possible side-effects,
1801function calls can be executed as statements:
1802
1803<pre>
1804 stat ::= functioncall
1805</pre><p>
1806In this case, all returned values are thrown away.
1807Function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>.
1808
1809
1810
1811
1812
1813<h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p>
1814Local variables can be declared anywhere inside a block.
1815The declaration can include an initial assignment:
1816
1817<pre>
1818 stat ::= <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
1819</pre><p>
1820If present, an initial assignment has the same semantics
1821of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>).
1822Otherwise, all variables are initialized with <b>nil</b>.
1823
1824
1825<p>
1826A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>),
1827and so local variables can be declared in a chunk outside any explicit block.
1828
1829
1830<p>
1831The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>.
1832
1833
1834
1835
1836
1837
1838
1839<h2>3.4 &ndash; <a name="3.4">Expressions</a></h2>
1840
1841<p>
1842The basic expressions in Lua are the following:
1843
1844<pre>
1845 exp ::= prefixexp
1846 exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1847 exp ::= Number
1848 exp ::= String
1849 exp ::= functiondef
1850 exp ::= tableconstructor
1851 exp ::= &lsquo;<b>...</b>&rsquo;
1852 exp ::= exp binop exp
1853 exp ::= unop exp
1854 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1855</pre>
1856
1857<p>
1858Numbers and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1859variables are explained in <a href="#3.2">&sect;3.2</a>;
1860function definitions are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1861function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>;
1862table constructors are explained in <a href="#3.4.8">&sect;3.4.8</a>.
1863Vararg expressions,
1864denoted by three dots ('<code>...</code>'), can only be used when
1865directly inside a vararg function;
1866they are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1867
1868
1869<p>
1870Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
1871relational operators (see <a href="#3.4.3">&sect;3.4.3</a>), logical operators (see <a href="#3.4.4">&sect;3.4.4</a>),
1872and the concatenation operator (see <a href="#3.4.5">&sect;3.4.5</a>).
1873Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
1874the unary <b>not</b> (see <a href="#3.4.4">&sect;3.4.4</a>),
1875and the unary <em>length operator</em> (see <a href="#3.4.6">&sect;3.4.6</a>).
1876
1877
1878<p>
1879Both function calls and vararg expressions can result in multiple values.
1880If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>),
1881then its return list is adjusted to zero elements,
1882thus discarding all returned values.
1883If an expression is used as the last (or the only) element
1884of a list of expressions,
1885then no adjustment is made
1886(unless the expression is enclosed in parentheses).
1887In all other contexts,
1888Lua adjusts the result list to one element,
1889either discarding all values except the first one
1890or adding a single <b>nil</b> if there are no values.
1891
1892
1893<p>
1894Here are some examples:
1895
1896<pre>
1897 f() -- adjusted to 0 results
1898 g(f(), x) -- f() is adjusted to 1 result
1899 g(x, f()) -- g gets x plus all results from f()
1900 a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
1901 a,b = ... -- a gets the first vararg parameter, b gets
1902 -- the second (both a and b can get nil if there
1903 -- is no corresponding vararg parameter)
1904
1905 a,b,c = x, f() -- f() is adjusted to 2 results
1906 a,b,c = f() -- f() is adjusted to 3 results
1907 return f() -- returns all results from f()
1908 return ... -- returns all received vararg parameters
1909 return x,y,f() -- returns x, y, and all results from f()
1910 {f()} -- creates a list with all results from f()
1911 {...} -- creates a list with all vararg parameters
1912 {f(), nil} -- f() is adjusted to 1 result
1913</pre>
1914
1915<p>
1916Any expression enclosed in parentheses always results in only one value.
1917Thus,
1918<code>(f(x,y,z))</code> is always a single value,
1919even if <code>f</code> returns several values.
1920(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
1921or <b>nil</b> if <code>f</code> does not return any values.)
1922
1923
1924
1925<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1926Lua supports the usual arithmetic operators:
1927the binary <code>+</code> (addition),
1928<code>-</code> (subtraction), <code>*</code> (multiplication),
1929<code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
1930and unary <code>-</code> (mathematical negation).
1931If the operands are numbers, or strings that can be converted to
1932numbers (see <a href="#3.4.2">&sect;3.4.2</a>),
1933then all operations have the usual meaning.
1934Exponentiation works for any exponent.
1935For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
1936Modulo is defined as
1937
1938<pre>
1939 a % b == a - math.floor(a/b)*b
1940</pre><p>
1941That is, it is the remainder of a division that rounds
1942the quotient towards minus infinity.
1943
1944
1945
1946
1947
1948<h3>3.4.2 &ndash; <a name="3.4.2">Coercion</a></h3>
1949
1950<p>
1951Lua provides automatic conversion between
1952string and number values at run time.
1953Any arithmetic operation applied to a string tries to convert
1954this string to a number, following the rules of the Lua lexer.
1955(The string may have leading and trailing spaces and a sign.)
1956Conversely, whenever a number is used where a string is expected,
1957the number is converted to a string, in a reasonable format.
1958For complete control over how numbers are converted to strings,
1959use the <code>format</code> function from the string library
1960(see <a href="#pdf-string.format"><code>string.format</code></a>).
1961
1962
1963
1964
1965
1966<h3>3.4.3 &ndash; <a name="3.4.3">Relational Operators</a></h3><p>
1967The relational operators in Lua are
1968
1969<pre>
1970 == ~= &lt; &gt; &lt;= &gt;=
1971</pre><p>
1972These operators always result in <b>false</b> or <b>true</b>.
1973
1974
1975<p>
1976Equality (<code>==</code>) first compares the type of its operands.
1977If the types are different, then the result is <b>false</b>.
1978Otherwise, the values of the operands are compared.
1979Numbers and strings are compared in the usual way.
1980Tables, userdata, and threads
1981are compared by reference:
1982two objects are considered equal only if they are the same object.
1983Every time you create a new object
1984(a table, userdata, or thread),
1985this new object is different from any previously existing object.
1986Closures with the same reference are always equal.
1987Closures with any detectable difference
1988(different behavior, different definition) are always different.
1989
1990
1991<p>
1992You can change the way that Lua compares tables and userdata
1993by using the "eq" metamethod (see <a href="#2.4">&sect;2.4</a>).
1994
1995
1996<p>
1997The conversion rules of <a href="#3.4.2">&sect;3.4.2</a>
1998do not apply to equality comparisons.
1999Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2000and <code>t[0]</code> and <code>t["0"]</code> denote different
2001entries in a table.
2002
2003
2004<p>
2005The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2006
2007
2008<p>
2009The order operators work as follows.
2010If both arguments are numbers, then they are compared as such.
2011Otherwise, if both arguments are strings,
2012then their values are compared according to the current locale.
2013Otherwise, Lua tries to call the "lt" or the "le"
2014metamethod (see <a href="#2.4">&sect;2.4</a>).
2015A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code>
2016and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>.
2017
2018
2019
2020
2021
2022<h3>3.4.4 &ndash; <a name="3.4.4">Logical Operators</a></h3><p>
2023The logical operators in Lua are
2024<b>and</b>, <b>or</b>, and <b>not</b>.
2025Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
2026all logical operators consider both <b>false</b> and <b>nil</b> as false
2027and anything else as true.
2028
2029
2030<p>
2031The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2032The conjunction operator <b>and</b> returns its first argument
2033if this value is <b>false</b> or <b>nil</b>;
2034otherwise, <b>and</b> returns its second argument.
2035The disjunction operator <b>or</b> returns its first argument
2036if this value is different from <b>nil</b> and <b>false</b>;
2037otherwise, <b>or</b> returns its second argument.
2038Both <b>and</b> and <b>or</b> use short-cut evaluation;
2039that is,
2040the second operand is evaluated only if necessary.
2041Here are some examples:
2042
2043<pre>
2044 10 or 20 --&gt; 10
2045 10 or error() --&gt; 10
2046 nil or "a" --&gt; "a"
2047 nil and 10 --&gt; nil
2048 false and error() --&gt; false
2049 false and nil --&gt; false
2050 false or nil --&gt; nil
2051 10 and 20 --&gt; 20
2052</pre><p>
2053(In this manual,
2054<code>--&gt;</code> indicates the result of the preceding expression.)
2055
2056
2057
2058
2059
2060<h3>3.4.5 &ndash; <a name="3.4.5">Concatenation</a></h3><p>
2061The string concatenation operator in Lua is
2062denoted by two dots ('<code>..</code>').
2063If both operands are strings or numbers, then they are converted to
2064strings according to the rules mentioned in <a href="#3.4.2">&sect;3.4.2</a>.
2065Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
2066
2067
2068
2069
2070
2071<h3>3.4.6 &ndash; <a name="3.4.6">The Length Operator</a></h3>
2072
2073<p>
2074The length operator is denoted by the unary prefix operator <code>#</code>.
2075The length of a string is its number of bytes
2076(that is, the usual meaning of string length when each
2077character is one byte).
2078
2079
2080<p>
2081A program can modify the behavior of the length operator for
2082any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>).
2083
2084
2085<p>
2086Unless a <code>__len</code> metamethod is given,
2087the length of a table <code>t</code> is only defined if the
2088table is a <em>sequence</em>,
2089that is,
2090the set of its positive numeric keys is equal to <em>{1..n}</em>
2091for some integer <em>n</em>.
2092In that case, <em>n</em> is its length.
2093Note that a table like
2094
2095<pre>
2096 {10, 20, nil, 40}
2097</pre><p>
2098is not a sequence, because it has the key <code>4</code>
2099but does not have the key <code>3</code>.
2100(So, there is no <em>n</em> such that the set <em>{1..n}</em> is equal
2101to the set of positive numeric keys of that table.)
2102Note, however, that non-numeric keys do not interfere
2103with whether a table is a sequence.
2104
2105
2106
2107
2108
2109<h3>3.4.7 &ndash; <a name="3.4.7">Precedence</a></h3><p>
2110Operator precedence in Lua follows the table below,
2111from lower to higher priority:
2112
2113<pre>
2114 or
2115 and
2116 &lt; &gt; &lt;= &gt;= ~= ==
2117 ..
2118 + -
2119 * / %
2120 not # - (unary)
2121 ^
2122</pre><p>
2123As usual,
2124you can use parentheses to change the precedences of an expression.
2125The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2126operators are right associative.
2127All other binary operators are left associative.
2128
2129
2130
2131
2132
2133<h3>3.4.8 &ndash; <a name="3.4.8">Table Constructors</a></h3><p>
2134Table constructors are expressions that create tables.
2135Every time a constructor is evaluated, a new table is created.
2136A constructor can be used to create an empty table
2137or to create a table and initialize some of its fields.
2138The general syntax for constructors is
2139
2140<pre>
2141 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
2142 fieldlist ::= field {fieldsep field} [fieldsep]
2143 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
2144 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
2145</pre>
2146
2147<p>
2148Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2149with key <code>exp1</code> and value <code>exp2</code>.
2150A field of the form <code>name = exp</code> is equivalent to
2151<code>["name"] = exp</code>.
2152Finally, fields of the form <code>exp</code> are equivalent to
2153<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
2154starting with 1.
2155Fields in the other formats do not affect this counting.
2156For example,
2157
2158<pre>
2159 a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
2160</pre><p>
2161is equivalent to
2162
2163<pre>
2164 do
2165 local t = {}
2166 t[f(1)] = g
2167 t[1] = "x" -- 1st exp
2168 t[2] = "y" -- 2nd exp
2169 t.x = 1 -- t["x"] = 1
2170 t[3] = f(x) -- 3rd exp
2171 t[30] = 23
2172 t[4] = 45 -- 4th exp
2173 a = t
2174 end
2175</pre>
2176
2177<p>
2178If the last field in the list has the form <code>exp</code>
2179and the expression is a function call or a vararg expression,
2180then all values returned by this expression enter the list consecutively
2181(see <a href="#3.4.9">&sect;3.4.9</a>).
2182
2183
2184<p>
2185The field list can have an optional trailing separator,
2186as a convenience for machine-generated code.
2187
2188
2189
2190
2191
2192<h3>3.4.9 &ndash; <a name="3.4.9">Function Calls</a></h3><p>
2193A function call in Lua has the following syntax:
2194
2195<pre>
2196 functioncall ::= prefixexp args
2197</pre><p>
2198In a function call,
2199first prefixexp and args are evaluated.
2200If the value of prefixexp has type <em>function</em>,
2201then this function is called
2202with the given arguments.
2203Otherwise, the prefixexp "call" metamethod is called,
2204having as first parameter the value of prefixexp,
2205followed by the original call arguments
2206(see <a href="#2.4">&sect;2.4</a>).
2207
2208
2209<p>
2210The form
2211
2212<pre>
2213 functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args
2214</pre><p>
2215can be used to call "methods".
2216A call <code>v:name(<em>args</em>)</code>
2217is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2218except that <code>v</code> is evaluated only once.
2219
2220
2221<p>
2222Arguments have the following syntax:
2223
2224<pre>
2225 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
2226 args ::= tableconstructor
2227 args ::= String
2228</pre><p>
2229All argument expressions are evaluated before the call.
2230A call of the form <code>f{<em>fields</em>}</code> is
2231syntactic sugar for <code>f({<em>fields</em>})</code>;
2232that is, the argument list is a single new table.
2233A call of the form <code>f'<em>string</em>'</code>
2234(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
2235is syntactic sugar for <code>f('<em>string</em>')</code>;
2236that is, the argument list is a single literal string.
2237
2238
2239<p>
2240A call of the form <code>return <em>functioncall</em></code> is called
2241a <em>tail call</em>.
2242Lua implements <em>proper tail calls</em>
2243(or <em>proper tail recursion</em>):
2244in a tail call,
2245the called function reuses the stack entry of the calling function.
2246Therefore, there is no limit on the number of nested tail calls that
2247a program can execute.
2248However, a tail call erases any debug information about the
2249calling function.
2250Note that a tail call only happens with a particular syntax,
2251where the <b>return</b> has one single function call as argument;
2252this syntax makes the calling function return exactly
2253the returns of the called function.
2254So, none of the following examples are tail calls:
2255
2256<pre>
2257 return (f(x)) -- results adjusted to 1
2258 return 2 * f(x)
2259 return x, f(x) -- additional results
2260 f(x); return -- results discarded
2261 return x or f(x) -- results adjusted to 1
2262</pre>
2263
2264
2265
2266
2267<h3>3.4.10 &ndash; <a name="3.4.10">Function Definitions</a></h3>
2268
2269<p>
2270The syntax for function definition is
2271
2272<pre>
2273 functiondef ::= <b>function</b> funcbody
2274 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
2275</pre>
2276
2277<p>
2278The following syntactic sugar simplifies function definitions:
2279
2280<pre>
2281 stat ::= <b>function</b> funcname funcbody
2282 stat ::= <b>local</b> <b>function</b> Name funcbody
2283 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
2284</pre><p>
2285The statement
2286
2287<pre>
2288 function f () <em>body</em> end
2289</pre><p>
2290translates to
2291
2292<pre>
2293 f = function () <em>body</em> end
2294</pre><p>
2295The statement
2296
2297<pre>
2298 function t.a.b.c.f () <em>body</em> end
2299</pre><p>
2300translates to
2301
2302<pre>
2303 t.a.b.c.f = function () <em>body</em> end
2304</pre><p>
2305The statement
2306
2307<pre>
2308 local function f () <em>body</em> end
2309</pre><p>
2310translates to
2311
2312<pre>
2313 local f; f = function () <em>body</em> end
2314</pre><p>
2315not to
2316
2317<pre>
2318 local f = function () <em>body</em> end
2319</pre><p>
2320(This only makes a difference when the body of the function
2321contains references to <code>f</code>.)
2322
2323
2324<p>
2325A function definition is an executable expression,
2326whose value has type <em>function</em>.
2327When Lua precompiles a chunk,
2328all its function bodies are precompiled too.
2329Then, whenever Lua executes the function definition,
2330the function is <em>instantiated</em> (or <em>closed</em>).
2331This function instance (or <em>closure</em>)
2332is the final value of the expression.
2333
2334
2335<p>
2336Parameters act as local variables that are
2337initialized with the argument values:
2338
2339<pre>
2340 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
2341</pre><p>
2342When a function is called,
2343the list of arguments is adjusted to
2344the length of the list of parameters,
2345unless the function is a <em>vararg function</em>,
2346which is indicated by three dots ('<code>...</code>')
2347at the end of its parameter list.
2348A vararg function does not adjust its argument list;
2349instead, it collects all extra arguments and supplies them
2350to the function through a <em>vararg expression</em>,
2351which is also written as three dots.
2352The value of this expression is a list of all actual extra arguments,
2353similar to a function with multiple results.
2354If a vararg expression is used inside another expression
2355or in the middle of a list of expressions,
2356then its return list is adjusted to one element.
2357If the expression is used as the last element of a list of expressions,
2358then no adjustment is made
2359(unless that last expression is enclosed in parentheses).
2360
2361
2362<p>
2363As an example, consider the following definitions:
2364
2365<pre>
2366 function f(a, b) end
2367 function g(a, b, ...) end
2368 function r() return 1,2,3 end
2369</pre><p>
2370Then, we have the following mapping from arguments to parameters and
2371to the vararg expression:
2372
2373<pre>
2374 CALL PARAMETERS
2375
2376 f(3) a=3, b=nil
2377 f(3, 4) a=3, b=4
2378 f(3, 4, 5) a=3, b=4
2379 f(r(), 10) a=1, b=10
2380 f(r()) a=1, b=2
2381
2382 g(3) a=3, b=nil, ... --&gt; (nothing)
2383 g(3, 4) a=3, b=4, ... --&gt; (nothing)
2384 g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8
2385 g(5, r()) a=5, b=1, ... --&gt; 2 3
2386</pre>
2387
2388<p>
2389Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>).
2390If control reaches the end of a function
2391without encountering a <b>return</b> statement,
2392then the function returns with no results.
2393
2394
2395<p>
2396
2397There is a system-dependent limit on the number of values
2398that a function may return.
2399This limit is guaranteed to be larger than 1000.
2400
2401
2402<p>
2403The <em>colon</em> syntax
2404is used for defining <em>methods</em>,
2405that is, functions that have an implicit extra parameter <code>self</code>.
2406Thus, the statement
2407
2408<pre>
2409 function t.a.b.c:f (<em>params</em>) <em>body</em> end
2410</pre><p>
2411is syntactic sugar for
2412
2413<pre>
2414 t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2415</pre>
2416
2417
2418
2419
2420
2421
2422<h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2>
2423
2424<p>
2425
2426Lua is a lexically scoped language.
2427The scope of a local variable begins at the first statement after
2428its declaration and lasts until the last non-void statement
2429of the innermost block that includes the declaration.
2430Consider the following example:
2431
2432<pre>
2433 x = 10 -- global variable
2434 do -- new block
2435 local x = x -- new 'x', with value 10
2436 print(x) --&gt; 10
2437 x = x+1
2438 do -- another block
2439 local x = x+1 -- another 'x'
2440 print(x) --&gt; 12
2441 end
2442 print(x) --&gt; 11
2443 end
2444 print(x) --&gt; 10 (the global one)
2445</pre>
2446
2447<p>
2448Notice that, in a declaration like <code>local x = x</code>,
2449the new <code>x</code> being declared is not in scope yet,
2450and so the second <code>x</code> refers to the outside variable.
2451
2452
2453<p>
2454Because of the lexical scoping rules,
2455local variables can be freely accessed by functions
2456defined inside their scope.
2457A local variable used by an inner function is called
2458an <em>upvalue</em>, or <em>external local variable</em>,
2459inside the inner function.
2460
2461
2462<p>
2463Notice that each execution of a <b>local</b> statement
2464defines new local variables.
2465Consider the following example:
2466
2467<pre>
2468 a = {}
2469 local x = 20
2470 for i=1,10 do
2471 local y = 0
2472 a[i] = function () y=y+1; return x+y end
2473 end
2474</pre><p>
2475The loop creates ten closures
2476(that is, ten instances of the anonymous function).
2477Each of these closures uses a different <code>y</code> variable,
2478while all of them share the same <code>x</code>.
2479
2480
2481
2482
2483
2484<h1>4 &ndash; <a name="4">The Application Program Interface</a></h1>
2485
2486<p>
2487
2488This section describes the C&nbsp;API for Lua, that is,
2489the set of C&nbsp;functions available to the host program to communicate
2490with Lua.
2491All API functions and related types and constants
2492are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2493
2494
2495<p>
2496Even when we use the term "function",
2497any facility in the API may be provided as a macro instead.
2498Except where stated otherwise,
2499all such macros use each of their arguments exactly once
2500(except for the first argument, which is always a Lua state),
2501and so do not generate any hidden side-effects.
2502
2503
2504<p>
2505As in most C&nbsp;libraries,
2506the Lua API functions do not check their arguments for validity or consistency.
2507However, you can change this behavior by compiling Lua
2508with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2509
2510
2511
2512<h2>4.1 &ndash; <a name="4.1">The Stack</a></h2>
2513
2514<p>
2515Lua uses a <em>virtual stack</em> to pass values to and from C.
2516Each element in this stack represents a Lua value
2517(<b>nil</b>, number, string, etc.).
2518
2519
2520<p>
2521Whenever Lua calls C, the called function gets a new stack,
2522which is independent of previous stacks and of stacks of
2523C&nbsp;functions that are still active.
2524This stack initially contains any arguments to the C&nbsp;function
2525and it is where the C&nbsp;function pushes its results
2526to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2527
2528
2529<p>
2530For convenience,
2531most query operations in the API do not follow a strict stack discipline.
2532Instead, they can refer to any element in the stack
2533by using an <em>index</em>:
2534A positive index represents an absolute stack position
2535(starting at&nbsp;1);
2536a negative index represents an offset relative to the top of the stack.
2537More specifically, if the stack has <em>n</em> elements,
2538then index&nbsp;1 represents the first element
2539(that is, the element that was pushed onto the stack first)
2540and
2541index&nbsp;<em>n</em> represents the last element;
2542index&nbsp;-1 also represents the last element
2543(that is, the element at the&nbsp;top)
2544and index <em>-n</em> represents the first element.
2545
2546
2547
2548
2549
2550<h2>4.2 &ndash; <a name="4.2">Stack Size</a></h2>
2551
2552<p>
2553When you interact with the Lua API,
2554you are responsible for ensuring consistency.
2555In particular,
2556<em>you are responsible for controlling stack overflow</em>.
2557You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2558to ensure that the stack has extra slots when pushing new elements.
2559
2560
2561<p>
2562Whenever Lua calls C,
2563it ensures that the stack has at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2564<code>LUA_MINSTACK</code> is defined as 20,
2565so that usually you do not have to worry about stack space
2566unless your code has loops pushing elements onto the stack.
2567
2568
2569<p>
2570When you call a Lua function
2571without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2572Lua ensures that the stack has enough size for all results,
2573but it does not ensure any extra space.
2574So, before pushing anything in the stack after such a call
2575you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2576
2577
2578
2579
2580
2581<h2>4.3 &ndash; <a name="4.3">Valid and Acceptable Indices</a></h2>
2582
2583<p>
2584Any function in the API that receives stack indices
2585works only with <em>valid indices</em> or <em>acceptable indices</em>.
2586
2587
2588<p>
2589A <em>valid index</em> is an index that refers to a
2590real position within the stack, that is,
2591its position lies between&nbsp;1 and the stack top
2592(<code>1 &le; abs(index) &le; top</code>).
2593
2594Usually, functions that can modify the value at an index
2595require valid indices.
2596
2597
2598<p>
2599Unless otherwise noted,
2600any function that accepts valid indices also accepts <em>pseudo-indices</em>,
2601which represent some Lua values that are accessible to C&nbsp;code
2602but which are not in the stack.
2603Pseudo-indices are used to access the registry
2604and the upvalues of a C&nbsp;function (see <a href="#4.4">&sect;4.4</a>).
2605
2606
2607<p>
2608Functions that do not need a specific stack position,
2609but only a value in the stack (e.g., query functions),
2610can be called with acceptable indices.
2611An <em>acceptable index</em> can be any valid index,
2612including the pseudo-indices,
2613but it also can be any positive index after the stack top
2614within the space allocated for the stack,
2615that is, indices up to the stack size.
2616(Note that 0 is never an acceptable index.)
2617Except when noted otherwise,
2618functions in the API work with acceptable indices.
2619
2620
2621<p>
2622Acceptable indices serve to avoid extra tests
2623against the stack top when querying the stack.
2624For instance, a C&nbsp;function can query its third argument
2625without the need to first check whether there is a third argument,
2626that is, without the need to check whether 3 is a valid index.
2627
2628
2629<p>
2630For functions that can be called with acceptable indices,
2631any non-valid index is treated as if it
2632contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
2633which behaves like a nil value.
2634
2635
2636
2637
2638
2639<h2>4.4 &ndash; <a name="4.4">C Closures</a></h2>
2640
2641<p>
2642When a C&nbsp;function is created,
2643it is possible to associate some values with it,
2644thus creating a <em>C&nbsp;closure</em>
2645(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
2646these values are called <em>upvalues</em> and are
2647accessible to the function whenever it is called.
2648
2649
2650<p>
2651Whenever a C&nbsp;function is called,
2652its upvalues are located at specific pseudo-indices.
2653These pseudo-indices are produced by the macro
2654<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2655The first value associated with a function is at position
2656<code>lua_upvalueindex(1)</code>, and so on.
2657Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2658where <em>n</em> is greater than the number of upvalues of the
2659current function (but not greater than 256),
2660produces an acceptable but invalid index.
2661
2662
2663
2664
2665
2666<h2>4.5 &ndash; <a name="4.5">Registry</a></h2>
2667
2668<p>
2669Lua provides a <em>registry</em>,
2670a predefined table that can be used by any C&nbsp;code to
2671store whatever Lua values it needs to store.
2672The registry table is always located at pseudo-index
2673<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
2674which is a valid index.
2675Any C&nbsp;library can store data into this table,
2676but it should take care to choose keys
2677that are different from those used
2678by other libraries, to avoid collisions.
2679Typically, you should use as key a string containing your library name,
2680or a light userdata with the address of a C&nbsp;object in your code,
2681or any Lua object created by your code.
2682As with global names,
2683string keys starting with an underscore followed by
2684uppercase letters are reserved for Lua.
2685
2686
2687<p>
2688The integer keys in the registry are used by the reference mechanism,
2689implemented by the auxiliary library,
2690and by some predefined values.
2691Therefore, integer keys should not be used for other purposes.
2692
2693
2694<p>
2695When you create a new Lua state,
2696its registry comes with some predefined values.
2697These predefined values are indexed with integer keys
2698defined as constants in <code>lua.h</code>.
2699The following constants are defined:
2700
2701<ul>
2702<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
2703the main thread of the state.
2704(The main thread is the one created together with the state.)
2705</li>
2706
2707<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
2708the global environment.
2709</li>
2710</ul>
2711
2712
2713
2714
2715<h2>4.6 &ndash; <a name="4.6">Error Handling in C</a></h2>
2716
2717<p>
2718Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2719(You can also choose to use exceptions if you compile Lua as C++;
2720search for <code>LUAI_THROW</code> in the source code.)
2721When Lua faces any error
2722(such as a memory allocation error, type errors, syntax errors,
2723and runtime errors)
2724it <em>raises</em> an error;
2725that is, it does a long jump.
2726A <em>protected environment</em> uses <code>setjmp</code>
2727to set a recovery point;
2728any error jumps to the most recent active recovery point.
2729
2730
2731<p>
2732If an error happens outside any protected environment,
2733Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
2734and then calls <code>abort</code>,
2735thus exiting the host application.
2736Your panic function can avoid this exit by
2737never returning
2738(e.g., doing a long jump to your own recovery point outside Lua).
2739
2740
2741<p>
2742The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
2743in particular, the error message is at the top of the stack.
2744However, there is no guarantees about stack space.
2745To push anything on the stack,
2746the panic function should first check the available space (see <a href="#4.2">&sect;4.2</a>).
2747
2748
2749<p>
2750Most functions in the API can throw an error,
2751for instance due to a memory allocation error.
2752The documentation for each function indicates whether
2753it can throw errors.
2754
2755
2756<p>
2757Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2758
2759
2760
2761
2762
2763<h2>4.7 &ndash; <a name="4.7">Handling Yields in C</a></h2>
2764
2765<p>
2766Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2767Therefore, if a function <code>foo</code> calls an API function
2768and this API function yields
2769(directly or indirectly by calling another function that yields),
2770Lua cannot return to <code>foo</code> any more,
2771because the <code>longjmp</code> removes its frame from the C stack.
2772
2773
2774<p>
2775To avoid this kind of problem,
2776Lua raises an error whenever it tries to yield across an API call,
2777except for three functions:
2778<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>.
2779All those functions receive a <em>continuation function</em>
2780(as a parameter called <code>k</code>) to continue execution after a yield.
2781
2782
2783<p>
2784We need to set some terminology to explain continuations.
2785We have a C function called from Lua which we will call
2786the <em>original function</em>.
2787This original function then calls one of those three functions in the C API,
2788which we will call the <em>callee function</em>,
2789that then yields the current thread.
2790(This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
2791or 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>
2792and the function called by them yields.)
2793
2794
2795<p>
2796Suppose the running thread yields while executing the callee function.
2797After the thread resumes,
2798it eventually will finish running the callee function.
2799However,
2800the callee function cannot return to the original function,
2801because its frame in the C stack was destroyed by the yield.
2802Instead, Lua calls a <em>continuation function</em>,
2803which was given as an argument to the callee function.
2804As the name implies,
2805the continuation function should continue the task
2806of the original function.
2807
2808
2809<p>
2810Lua treats the continuation function as if it were the original function.
2811The continuation function receives the same Lua stack
2812from the original function,
2813in the same state it would be if the callee function had returned.
2814(For instance,
2815after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
2816removed from the stack and replaced by the results from the call.)
2817It also has the same upvalues.
2818Whatever it returns is handled by Lua as if it were the return
2819of the original function.
2820
2821
2822<p>
2823The only difference in the Lua state between the original function
2824and its continuation is the result of a call to <a href="#lua_getctx"><code>lua_getctx</code></a>.
2825
2826
2827
2828
2829
2830<h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
2831
2832<p>
2833Here we list all functions and types from the C&nbsp;API in
2834alphabetical order.
2835Each function has an indicator like this:
2836<span class="apii">[-o, +p, <em>x</em>]</span>
2837
2838
2839<p>
2840The first field, <code>o</code>,
2841is how many elements the function pops from the stack.
2842The second field, <code>p</code>,
2843is how many elements the function pushes onto the stack.
2844(Any function always pushes its results after popping its arguments.)
2845A field in the form <code>x|y</code> means the function can push (or pop)
2846<code>x</code> or <code>y</code> elements,
2847depending on the situation;
2848an interrogation mark '<code>?</code>' means that
2849we cannot know how many elements the function pops/pushes
2850by looking only at its arguments
2851(e.g., they may depend on what is on the stack).
2852The third field, <code>x</code>,
2853tells whether the function may throw errors:
2854'<code>-</code>' means the function never throws any error;
2855'<code>e</code>' means the function may throw errors;
2856'<code>v</code>' means the function may throw an error on purpose.
2857
2858
2859
2860<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
2861<span class="apii">[-0, +0, &ndash;]</span>
2862<pre>int lua_absindex (lua_State *L, int idx);</pre>
2863
2864<p>
2865Converts the acceptable index <code>idx</code> into an absolute index
2866(that is, one that does not depend on the stack top).
2867
2868
2869
2870
2871
2872<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2873<pre>typedef void * (*lua_Alloc) (void *ud,
2874 void *ptr,
2875 size_t osize,
2876 size_t nsize);</pre>
2877
2878<p>
2879The type of the memory-allocation function used by Lua states.
2880The allocator function must provide a
2881functionality similar to <code>realloc</code>,
2882but not exactly the same.
2883Its arguments are
2884<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2885<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2886<code>osize</code>, the original size of the block or some code about what
2887is being allocated;
2888<code>nsize</code>, the new size of the block.
2889
2890
2891<p>
2892When <code>ptr</code> is not <code>NULL</code>,
2893<code>osize</code> is the size of the block pointed by <code>ptr</code>,
2894that is, the size given when it was allocated or reallocated.
2895
2896
2897<p>
2898When <code>ptr</code> is <code>NULL</code>,
2899<code>osize</code> encodes the kind of object that Lua is allocating.
2900<code>osize</code> is any of
2901<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>,
2902<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)
2903Lua is creating a new object of that type.
2904When <code>osize</code> is some other value,
2905Lua is allocating memory for something else.
2906
2907
2908<p>
2909Lua assumes the following behavior from the allocator function:
2910
2911
2912<p>
2913When <code>nsize</code> is zero,
2914the allocator should behave like <code>free</code>
2915and return <code>NULL</code>.
2916
2917
2918<p>
2919When <code>nsize</code> is not zero,
2920the allocator should behave like <code>realloc</code>.
2921The allocator returns <code>NULL</code>
2922if and only if it cannot fulfill the request.
2923Lua assumes that the allocator never fails when
2924<code>osize &gt;= nsize</code>.
2925
2926
2927<p>
2928Here is a simple implementation for the allocator function.
2929It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2930
2931<pre>
2932 static void *l_alloc (void *ud, void *ptr, size_t osize,
2933 size_t nsize) {
2934 (void)ud; (void)osize; /* not used */
2935 if (nsize == 0) {
2936 free(ptr);
2937 return NULL;
2938 }
2939 else
2940 return realloc(ptr, nsize);
2941 }
2942</pre><p>
2943Note that Standard&nbsp;C ensures
2944that <code>free(NULL)</code> has no effect and that
2945<code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2946This code assumes that <code>realloc</code> does not fail when shrinking a block.
2947(Although Standard&nbsp;C does not ensure this behavior,
2948it seems to be a safe assumption.)
2949
2950
2951
2952
2953
2954<hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p>
2955<span class="apii">[-(2|1), +1, <em>e</em>]</span>
2956<pre>void lua_arith (lua_State *L, int op);</pre>
2957
2958<p>
2959Performs an arithmetic operation over the two values
2960(or one, in the case of negation)
2961at the top of the stack,
2962with the value at the top being the second operand,
2963pops these values, and pushes the result of the operation.
2964The function follows the semantics of the corresponding Lua operator
2965(that is, it may call metamethods).
2966
2967
2968<p>
2969The value of <code>op</code> must be one of the following constants:
2970
2971<ul>
2972
2973<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
2974<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
2975<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
2976<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs division (<code>/</code>)</li>
2977<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
2978<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
2979<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
2980
2981</ul>
2982
2983
2984
2985
2986<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
2987<span class="apii">[-0, +0, &ndash;]</span>
2988<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2989
2990<p>
2991Sets a new panic function and returns the old one (see <a href="#4.6">&sect;4.6</a>).
2992
2993
2994
2995
2996
2997<hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p>
2998<span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span>
2999<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
3000
3001<p>
3002Calls a function.
3003
3004
3005<p>
3006To call a function you must use the following protocol:
3007first, the function to be called is pushed onto the stack;
3008then, the arguments to the function are pushed
3009in direct order;
3010that is, the first argument is pushed first.
3011Finally you call <a href="#lua_call"><code>lua_call</code></a>;
3012<code>nargs</code> is the number of arguments that you pushed onto the stack.
3013All arguments and the function value are popped from the stack
3014when the function is called.
3015The function results are pushed onto the stack when the function returns.
3016The number of results is adjusted to <code>nresults</code>,
3017unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3018In this case, all results from the function are pushed.
3019Lua takes care that the returned values fit into the stack space.
3020The function results are pushed onto the stack in direct order
3021(the first result is pushed first),
3022so that after the call the last result is on the top of the stack.
3023
3024
3025<p>
3026Any error inside the called function is propagated upwards
3027(with a <code>longjmp</code>).
3028
3029
3030<p>
3031The following example shows how the host program can do the
3032equivalent to this Lua code:
3033
3034<pre>
3035 a = f("how", t.x, 14)
3036</pre><p>
3037Here it is in&nbsp;C:
3038
3039<pre>
3040 lua_getglobal(L, "f"); /* function to be called */
3041 lua_pushstring(L, "how"); /* 1st argument */
3042 lua_getglobal(L, "t"); /* table to be indexed */
3043 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
3044 lua_remove(L, -2); /* remove 't' from the stack */
3045 lua_pushinteger(L, 14); /* 3rd argument */
3046 lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */
3047 lua_setglobal(L, "a"); /* set global 'a' */
3048</pre><p>
3049Note that the code above is "balanced":
3050at its end, the stack is back to its original configuration.
3051This is considered good programming practice.
3052
3053
3054
3055
3056
3057<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
3058<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3059<pre>void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
3060 lua_CFunction k);</pre>
3061
3062<p>
3063This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3064but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
3065
3066
3067
3068
3069
3070<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3071<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3072
3073<p>
3074Type for C&nbsp;functions.
3075
3076
3077<p>
3078In order to communicate properly with Lua,
3079a C&nbsp;function must use the following protocol,
3080which defines the way parameters and results are passed:
3081a C&nbsp;function receives its arguments from Lua in its stack
3082in direct order (the first argument is pushed first).
3083So, when the function starts,
3084<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3085The first argument (if any) is at index 1
3086and its last argument is at index <code>lua_gettop(L)</code>.
3087To return values to Lua, a C&nbsp;function just pushes them onto the stack,
3088in direct order (the first result is pushed first),
3089and returns the number of results.
3090Any other value in the stack below the results will be properly
3091discarded by Lua.
3092Like a Lua function, a C&nbsp;function called by Lua can also return
3093many results.
3094
3095
3096<p>
3097As an example, the following function receives a variable number
3098of numerical arguments and returns their average and sum:
3099
3100<pre>
3101 static int foo (lua_State *L) {
3102 int n = lua_gettop(L); /* number of arguments */
3103 lua_Number sum = 0;
3104 int i;
3105 for (i = 1; i &lt;= n; i++) {
3106 if (!lua_isnumber(L, i)) {
3107 lua_pushstring(L, "incorrect argument");
3108 lua_error(L);
3109 }
3110 sum += lua_tonumber(L, i);
3111 }
3112 lua_pushnumber(L, sum/n); /* first result */
3113 lua_pushnumber(L, sum); /* second result */
3114 return 2; /* number of results */
3115 }
3116</pre>
3117
3118
3119
3120
3121<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3122<span class="apii">[-0, +0, &ndash;]</span>
3123<pre>int lua_checkstack (lua_State *L, int extra);</pre>
3124
3125<p>
3126Ensures that there are at least <code>extra</code> free stack slots in the stack.
3127It returns false if it cannot fulfill the request,
3128because it would cause the stack to be larger than a fixed maximum size
3129(typically at least a few thousand elements) or
3130because it cannot allocate memory for the new stack size.
3131This function never shrinks the stack;
3132if the stack is already larger than the new size,
3133it is left unchanged.
3134
3135
3136
3137
3138
3139<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3140<span class="apii">[-0, +0, &ndash;]</span>
3141<pre>void lua_close (lua_State *L);</pre>
3142
3143<p>
3144Destroys all objects in the given Lua state
3145(calling the corresponding garbage-collection metamethods, if any)
3146and frees all dynamic memory used by this state.
3147On several platforms, you may not need to call this function,
3148because all resources are naturally released when the host program ends.
3149On the other hand, long-running programs that create multiple states,
3150such as daemons or web servers,
3151might need to close states as soon as they are not needed.
3152
3153
3154
3155
3156
3157<hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p>
3158<span class="apii">[-0, +0, <em>e</em>]</span>
3159<pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre>
3160
3161<p>
3162Compares two Lua values.
3163Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3164when compared with the value at index <code>index2</code>,
3165following the semantics of the corresponding Lua operator
3166(that is, it may call metamethods).
3167Otherwise returns&nbsp;0.
3168Also returns&nbsp;0 if any of the indices is non valid.
3169
3170
3171<p>
3172The value of <code>op</code> must be one of the following constants:
3173
3174<ul>
3175
3176<li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li>
3177<li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li>
3178<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li>
3179
3180</ul>
3181
3182
3183
3184
3185<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p>
3186<span class="apii">[-n, +1, <em>e</em>]</span>
3187<pre>void lua_concat (lua_State *L, int n);</pre>
3188
3189<p>
3190Concatenates the <code>n</code> values at the top of the stack,
3191pops them, and leaves the result at the top.
3192If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack
3193(that is, the function does nothing);
3194if <code>n</code> is 0, the result is the empty string.
3195Concatenation is performed following the usual semantics of Lua
3196(see <a href="#3.4.5">&sect;3.4.5</a>).
3197
3198
3199
3200
3201
3202<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3203<span class="apii">[-0, +0, &ndash;]</span>
3204<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3205
3206<p>
3207Moves the element at index <code>fromidx</code>
3208into the valid index <code>toidx</code>
3209without shifting any element
3210(therefore replacing the value at that position).
3211
3212
3213
3214
3215
3216<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p>
3217<span class="apii">[-0, +1, <em>e</em>]</span>
3218<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
3219
3220<p>
3221Creates a new empty table and pushes it onto the stack.
3222Parameter <code>narr</code> is a hint for how many elements the table
3223will have as a sequence;
3224parameter <code>nrec</code> is a hint for how many other elements
3225the table will have.
3226Lua may use these hints to preallocate memory for the new table.
3227This pre-allocation is useful for performance when you know in advance
3228how many elements the table will have.
3229Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
3230
3231
3232
3233
3234
3235<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
3236<span class="apii">[-0, +0, <em>e</em>]</span>
3237<pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
3238
3239<p>
3240Dumps a function as a binary chunk.
3241Receives a Lua function on the top of the stack
3242and produces a binary chunk that,
3243if loaded again,
3244results in a function equivalent to the one dumped.
3245As it produces parts of the chunk,
3246<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
3247with the given <code>data</code>
3248to write them.
3249
3250
3251<p>
3252The value returned is the error code returned by the last
3253call to the writer;
32540&nbsp;means no errors.
3255
3256
3257<p>
3258This function does not pop the Lua function from the stack.
3259
3260
3261
3262
3263
3264<hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p>
3265<span class="apii">[-1, +0, <em>v</em>]</span>
3266<pre>int lua_error (lua_State *L);</pre>
3267
3268<p>
3269Generates a Lua error.
3270The error message (which can actually be a Lua value of any type)
3271must be on the stack top.
3272This function does a long jump,
3273and therefore never returns
3274(see <a href="#luaL_error"><code>luaL_error</code></a>).
3275
3276
3277
3278
3279
3280<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p>
3281<span class="apii">[-0, +0, <em>e</em>]</span>
3282<pre>int lua_gc (lua_State *L, int what, int data);</pre>
3283
3284<p>
3285Controls the garbage collector.
3286
3287
3288<p>
3289This function performs several tasks,
3290according to the value of the parameter <code>what</code>:
3291
3292<ul>
3293
3294<li><b><code>LUA_GCSTOP</code>: </b>
3295stops the garbage collector.
3296</li>
3297
3298<li><b><code>LUA_GCRESTART</code>: </b>
3299restarts the garbage collector.
3300</li>
3301
3302<li><b><code>LUA_GCCOLLECT</code>: </b>
3303performs a full garbage-collection cycle.
3304</li>
3305
3306<li><b><code>LUA_GCCOUNT</code>: </b>
3307returns the current amount of memory (in Kbytes) in use by Lua.
3308</li>
3309
3310<li><b><code>LUA_GCCOUNTB</code>: </b>
3311returns the remainder of dividing the current amount of bytes of
3312memory in use by Lua by 1024.
3313</li>
3314
3315<li><b><code>LUA_GCSTEP</code>: </b>
3316performs an incremental step of garbage collection.
3317The step "size" is controlled by <code>data</code>
3318(larger values mean more steps) in a non-specified way.
3319If you want to control the step size
3320you must experimentally tune the value of <code>data</code>.
3321The function returns 1 if the step finished a
3322garbage-collection cycle.
3323</li>
3324
3325<li><b><code>LUA_GCSETPAUSE</code>: </b>
3326sets <code>data</code> as the new value
3327for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>).
3328The function returns the previous value of the pause.
3329</li>
3330
3331<li><b><code>LUA_GCSETSTEPMUL</code>: </b>
3332sets <code>data</code> as the new value for the <em>step multiplier</em> of
3333the collector (see <a href="#2.5">&sect;2.5</a>).
3334The function returns the previous value of the step multiplier.
3335</li>
3336
3337<li><b><code>LUA_GCISRUNNING</code>: </b>
3338returns a boolean that tells whether the collector is running
3339(i.e., not stopped).
3340</li>
3341
3342<li><b><code>LUA_GCGEN</code>: </b>
3343changes the collector to generational mode
3344(see <a href="#2.5">&sect;2.5</a>).
3345</li>
3346
3347<li><b><code>LUA_GCINC</code>: </b>
3348changes the collector to incremental mode.
3349This is the default mode.
3350</li>
3351
3352</ul>
3353
3354<p>
3355For more details about these options,
3356see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3357
3358
3359
3360
3361
3362<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3363<span class="apii">[-0, +0, &ndash;]</span>
3364<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3365
3366<p>
3367Returns the memory-allocation function of a given state.
3368If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3369opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
3370
3371
3372
3373
3374
3375<hr><h3><a name="lua_getctx"><code>lua_getctx</code></a></h3><p>
3376<span class="apii">[-0, +0, &ndash;]</span>
3377<pre>int lua_getctx (lua_State *L, int *ctx);</pre>
3378
3379<p>
3380This function is called by a continuation function (see <a href="#4.7">&sect;4.7</a>)
3381to retrieve the status of the thread and a context information.
3382
3383
3384<p>
3385When called in the original function,
3386<a href="#lua_getctx"><code>lua_getctx</code></a> always returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
3387and does not change the value of its argument <code>ctx</code>.
3388When called inside a continuation function,
3389<a href="#lua_getctx"><code>lua_getctx</code></a> returns <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> and sets
3390the value of <code>ctx</code> to be the context information
3391(the value passed as the <code>ctx</code> argument
3392to the callee together with the continuation function).
3393
3394
3395<p>
3396When the callee is <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3397Lua may also call its continuation function
3398to handle errors during the call.
3399That is, upon an error in the function called by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3400Lua may not return to the original function
3401but instead may call the continuation function.
3402In that case, a call to <a href="#lua_getctx"><code>lua_getctx</code></a> will return the error code
3403(the value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>);
3404the value of <code>ctx</code> will be set to the context information,
3405as in the case of a yield.
3406
3407
3408
3409
3410
3411<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3412<span class="apii">[-0, +1, <em>e</em>]</span>
3413<pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
3414
3415<p>
3416Pushes onto the stack the value <code>t[k]</code>,
3417where <code>t</code> is the value at the given index.
3418As in Lua, this function may trigger a metamethod
3419for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3420
3421
3422
3423
3424
3425<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3426<span class="apii">[-0, +1, <em>e</em>]</span>
3427<pre>void lua_getglobal (lua_State *L, const char *name);</pre>
3428
3429<p>
3430Pushes onto the stack the value of the global <code>name</code>.
3431
3432
3433
3434
3435
3436<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
3437<span class="apii">[-0, +(0|1), &ndash;]</span>
3438<pre>int lua_getmetatable (lua_State *L, int index);</pre>
3439
3440<p>
3441Pushes onto the stack the metatable of the value at the given index.
3442If the value does not have a metatable,
3443the function returns&nbsp;0 and pushes nothing on the stack.
3444
3445
3446
3447
3448
3449<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
3450<span class="apii">[-1, +1, <em>e</em>]</span>
3451<pre>void lua_gettable (lua_State *L, int index);</pre>
3452
3453<p>
3454Pushes onto the stack the value <code>t[k]</code>,
3455where <code>t</code> is the value at the given index
3456and <code>k</code> is the value at the top of the stack.
3457
3458
3459<p>
3460This function pops the key from the stack
3461(putting the resulting value in its place).
3462As in Lua, this function may trigger a metamethod
3463for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3464
3465
3466
3467
3468
3469<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
3470<span class="apii">[-0, +0, &ndash;]</span>
3471<pre>int lua_gettop (lua_State *L);</pre>
3472
3473<p>
3474Returns the index of the top element in the stack.
3475Because indices start at&nbsp;1,
3476this result is equal to the number of elements in the stack
3477(and so 0&nbsp;means an empty stack).
3478
3479
3480
3481
3482
3483<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
3484<span class="apii">[-0, +1, &ndash;]</span>
3485<pre>void lua_getuservalue (lua_State *L, int index);</pre>
3486
3487<p>
3488Pushes onto the stack the Lua value associated with the userdata
3489at the given index.
3490This Lua value must be a table or <b>nil</b>.
3491
3492
3493
3494
3495
3496<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
3497<span class="apii">[-1, +1, &ndash;]</span>
3498<pre>void lua_insert (lua_State *L, int index);</pre>
3499
3500<p>
3501Moves the top element into the given valid index,
3502shifting up the elements above this index to open space.
3503This function cannot be called with a pseudo-index,
3504because a pseudo-index is not an actual stack position.
3505
3506
3507
3508
3509
3510<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3511<pre>typedef ptrdiff_t lua_Integer;</pre>
3512
3513<p>
3514The type used by the Lua API to represent signed integral values.
3515
3516
3517<p>
3518By default it is a <code>ptrdiff_t</code>,
3519which is usually the largest signed integral type the machine handles
3520"comfortably".
3521
3522
3523
3524
3525
3526<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3527<span class="apii">[-0, +0, &ndash;]</span>
3528<pre>int lua_isboolean (lua_State *L, int index);</pre>
3529
3530<p>
3531Returns 1 if the value at the given index is a boolean,
3532and 0&nbsp;otherwise.
3533
3534
3535
3536
3537
3538<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3539<span class="apii">[-0, +0, &ndash;]</span>
3540<pre>int lua_iscfunction (lua_State *L, int index);</pre>
3541
3542<p>
3543Returns 1 if the value at the given index is a C&nbsp;function,
3544and 0&nbsp;otherwise.
3545
3546
3547
3548
3549
3550<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3551<span class="apii">[-0, +0, &ndash;]</span>
3552<pre>int lua_isfunction (lua_State *L, int index);</pre>
3553
3554<p>
3555Returns 1 if the value at the given index is a function
3556(either C or Lua), and 0&nbsp;otherwise.
3557
3558
3559
3560
3561
3562<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3563<span class="apii">[-0, +0, &ndash;]</span>
3564<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3565
3566<p>
3567Returns 1 if the value at the given index is a light userdata,
3568and 0&nbsp;otherwise.
3569
3570
3571
3572
3573
3574<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3575<span class="apii">[-0, +0, &ndash;]</span>
3576<pre>int lua_isnil (lua_State *L, int index);</pre>
3577
3578<p>
3579Returns 1 if the value at the given index is <b>nil</b>,
3580and 0&nbsp;otherwise.
3581
3582
3583
3584
3585
3586<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3587<span class="apii">[-0, +0, &ndash;]</span>
3588<pre>int lua_isnone (lua_State *L, int index);</pre>
3589
3590<p>
3591Returns 1 if the given index is not valid,
3592and 0&nbsp;otherwise.
3593
3594
3595
3596
3597
3598<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3599<span class="apii">[-0, +0, &ndash;]</span>
3600<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3601
3602<p>
3603Returns 1 if the given index is not valid
3604or if the value at this index is <b>nil</b>,
3605and 0&nbsp;otherwise.
3606
3607
3608
3609
3610
3611<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3612<span class="apii">[-0, +0, &ndash;]</span>
3613<pre>int lua_isnumber (lua_State *L, int index);</pre>
3614
3615<p>
3616Returns 1 if the value at the given index is a number
3617or a string convertible to a number,
3618and 0&nbsp;otherwise.
3619
3620
3621
3622
3623
3624<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3625<span class="apii">[-0, +0, &ndash;]</span>
3626<pre>int lua_isstring (lua_State *L, int index);</pre>
3627
3628<p>
3629Returns 1 if the value at the given index is a string
3630or a number (which is always convertible to a string),
3631and 0&nbsp;otherwise.
3632
3633
3634
3635
3636
3637<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3638<span class="apii">[-0, +0, &ndash;]</span>
3639<pre>int lua_istable (lua_State *L, int index);</pre>
3640
3641<p>
3642Returns 1 if the value at the given index is a table,
3643and 0&nbsp;otherwise.
3644
3645
3646
3647
3648
3649<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3650<span class="apii">[-0, +0, &ndash;]</span>
3651<pre>int lua_isthread (lua_State *L, int index);</pre>
3652
3653<p>
3654Returns 1 if the value at the given index is a thread,
3655and 0&nbsp;otherwise.
3656
3657
3658
3659
3660
3661<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3662<span class="apii">[-0, +0, &ndash;]</span>
3663<pre>int lua_isuserdata (lua_State *L, int index);</pre>
3664
3665<p>
3666Returns 1 if the value at the given index is a userdata
3667(either full or light), and 0&nbsp;otherwise.
3668
3669
3670
3671
3672
3673<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
3674<span class="apii">[-0, +1, <em>e</em>]</span>
3675<pre>void lua_len (lua_State *L, int index);</pre>
3676
3677<p>
3678Returns the "length" of the value at the given index;
3679it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.6">&sect;3.4.6</a>).
3680The result is pushed on the stack.
3681
3682
3683
3684
3685
3686<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3687<span class="apii">[-0, +1, &ndash;]</span>
3688<pre>int lua_load (lua_State *L,
3689 lua_Reader reader,
3690 void *data,
3691 const char *source,
3692 const char *mode);</pre>
3693
3694<p>
3695Loads a Lua chunk (without running it).
3696If there are no errors,
3697<code>lua_load</code> pushes the compiled chunk as a Lua
3698function on top of the stack.
3699Otherwise, it pushes an error message.
3700
3701
3702<p>
3703The return values of <code>lua_load</code> are:
3704
3705<ul>
3706
3707<li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li>
3708
3709<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b>
3710syntax error during precompilation;</li>
3711
3712<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3713memory allocation error;</li>
3714
3715<li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
3716error while running a <code>__gc</code> metamethod.
3717(This error has no relation with the chunk being loaded.
3718It is generated by the garbage collector.)
3719</li>
3720
3721</ul>
3722
3723<p>
3724The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
3725to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3726The <code>data</code> argument is an opaque value passed to the reader function.
3727
3728
3729<p>
3730The <code>source</code> argument gives a name to the chunk,
3731which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>).
3732
3733
3734<p>
3735<code>lua_load</code> automatically detects whether the chunk is text or binary
3736and loads it accordingly (see program <code>luac</code>).
3737The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
3738with the addition that
3739a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
3740
3741
3742<p>
3743<code>lua_load</code> uses the stack internally,
3744so the reader function should always leave the stack
3745unmodified when returning.
3746
3747
3748<p>
3749If the resulting function has one upvalue,
3750this upvalue is set to the value of the global environment
3751stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>).
3752When loading main chunks,
3753this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
3754
3755
3756
3757
3758
3759<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3760<span class="apii">[-0, +0, &ndash;]</span>
3761<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3762
3763<p>
3764Creates a new thread running in a new, independent state.
3765Returns <code>NULL</code> if cannot create the thread or the state
3766(due to lack of memory).
3767The argument <code>f</code> is the allocator function;
3768Lua does all memory allocation for this state through this function.
3769The second argument, <code>ud</code>, is an opaque pointer that Lua
3770passes to the allocator in every call.
3771
3772
3773
3774
3775
3776<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p>
3777<span class="apii">[-0, +1, <em>e</em>]</span>
3778<pre>void lua_newtable (lua_State *L);</pre>
3779
3780<p>
3781Creates a new empty table and pushes it onto the stack.
3782It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3783
3784
3785
3786
3787
3788<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p>
3789<span class="apii">[-0, +1, <em>e</em>]</span>
3790<pre>lua_State *lua_newthread (lua_State *L);</pre>
3791
3792<p>
3793Creates a new thread, pushes it on the stack,
3794and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3795The new thread returned by this function shares with the original thread
3796its global environment,
3797but has an independent execution stack.
3798
3799
3800<p>
3801There is no explicit function to close or to destroy a thread.
3802Threads are subject to garbage collection,
3803like any Lua object.
3804
3805
3806
3807
3808
3809<hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p>
3810<span class="apii">[-0, +1, <em>e</em>]</span>
3811<pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3812
3813<p>
3814This function allocates a new block of memory with the given size,
3815pushes onto the stack a new full userdata with the block address,
3816and returns this address.
3817The host program can freely use this memory.
3818
3819
3820
3821
3822
3823<hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p>
3824<span class="apii">[-1, +(2|0), <em>e</em>]</span>
3825<pre>int lua_next (lua_State *L, int index);</pre>
3826
3827<p>
3828Pops a key from the stack,
3829and pushes a key&ndash;value pair from the table at the given index
3830(the "next" pair after the given key).
3831If there are no more elements in the table,
3832then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3833
3834
3835<p>
3836A typical traversal looks like this:
3837
3838<pre>
3839 /* table is in the stack at index 't' */
3840 lua_pushnil(L); /* first key */
3841 while (lua_next(L, t) != 0) {
3842 /* uses 'key' (at index -2) and 'value' (at index -1) */
3843 printf("%s - %s\n",
3844 lua_typename(L, lua_type(L, -2)),
3845 lua_typename(L, lua_type(L, -1)));
3846 /* removes 'value'; keeps 'key' for next iteration */
3847 lua_pop(L, 1);
3848 }
3849</pre>
3850
3851<p>
3852While traversing a table,
3853do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3854unless you know that the key is actually a string.
3855Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
3856the value at the given index;
3857this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3858
3859
3860<p>
3861See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
3862the table during its traversal.
3863
3864
3865
3866
3867
3868<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3869<pre>typedef double lua_Number;</pre>
3870
3871<p>
3872The type of numbers in Lua.
3873By default, it is double, but that can be changed in <code>luaconf.h</code>.
3874Through this configuration file you can change
3875Lua to operate with another type for numbers (e.g., float or long).
3876
3877
3878
3879
3880
3881<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
3882<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
3883<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
3884
3885<p>
3886Calls a function in protected mode.
3887
3888
3889<p>
3890Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3891in <a href="#lua_call"><code>lua_call</code></a>.
3892If there are no errors during the call,
3893<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
3894However, if there is any error,
3895<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3896pushes a single value on the stack (the error message),
3897and returns an error code.
3898Like <a href="#lua_call"><code>lua_call</code></a>,
3899<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3900and its arguments from the stack.
3901
3902
3903<p>
3904If <code>msgh</code> is 0,
3905then the error message returned on the stack
3906is exactly the original error message.
3907Otherwise, <code>msgh</code> is the stack index of a
3908<em>message handler</em>.
3909(In the current implementation, this index cannot be a pseudo-index.)
3910In case of runtime errors,
3911this function will be called with the error message
3912and its return value will be the message
3913returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3914
3915
3916<p>
3917Typically, the message handler is used to add more debug
3918information to the error message, such as a stack traceback.
3919Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3920since by then the stack has unwound.
3921
3922
3923<p>
3924The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following codes
3925(defined in <code>lua.h</code>):
3926
3927<ul>
3928
3929<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b>
3930success.</li>
3931
3932<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b>
3933a runtime error.
3934</li>
3935
3936<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3937memory allocation error.
3938For such errors, Lua does not call the message handler.
3939</li>
3940
3941<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b>
3942error while running the message handler.
3943</li>
3944
3945<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
3946error while running a <code>__gc</code> metamethod.
3947(This error typically has no relation with the function being called.
3948It is generated by the garbage collector.)
3949</li>
3950
3951</ul>
3952
3953
3954
3955
3956<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
3957<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
3958<pre>int lua_pcallk (lua_State *L,
3959 int nargs,
3960 int nresults,
3961 int errfunc,
3962 int ctx,
3963 lua_CFunction k);</pre>
3964
3965<p>
3966This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
3967but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>).
3968
3969
3970
3971
3972
3973<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
3974<span class="apii">[-n, +0, &ndash;]</span>
3975<pre>void lua_pop (lua_State *L, int n);</pre>
3976
3977<p>
3978Pops <code>n</code> elements from the stack.
3979
3980
3981
3982
3983
3984<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
3985<span class="apii">[-0, +1, &ndash;]</span>
3986<pre>void lua_pushboolean (lua_State *L, int b);</pre>
3987
3988<p>
3989Pushes a boolean value with value <code>b</code> onto the stack.
3990
3991
3992
3993
3994
3995<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p>
3996<span class="apii">[-n, +1, <em>e</em>]</span>
3997<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
3998
3999<p>
4000Pushes a new C&nbsp;closure onto the stack.
4001
4002
4003<p>
4004When a C&nbsp;function is created,
4005it is possible to associate some values with it,
4006thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>);
4007these values are then accessible to the function whenever it is called.
4008To associate values with a C&nbsp;function,
4009first these values should be pushed onto the stack
4010(when there are multiple values, the first value is pushed first).
4011Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4012is called to create and push the C&nbsp;function onto the stack,
4013with the argument <code>n</code> telling how many values should be
4014associated with the function.
4015<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4016
4017
4018<p>
4019The maximum value for <code>n</code> is 255.
4020
4021
4022<p>
4023When <code>n</code> is zero,
4024this function creates a <em>light C function</em>,
4025which is just a pointer to the C&nbsp;function.
4026In that case, it never throws a memory error.
4027
4028
4029
4030
4031
4032<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4033<span class="apii">[-0, +1, &ndash;]</span>
4034<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4035
4036<p>
4037Pushes a C&nbsp;function onto the stack.
4038This function receives a pointer to a C function
4039and pushes onto the stack a Lua value of type <code>function</code> that,
4040when called, invokes the corresponding C&nbsp;function.
4041
4042
4043<p>
4044Any function to be registered in Lua must
4045follow the correct protocol to receive its parameters
4046and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4047
4048
4049<p>
4050<code>lua_pushcfunction</code> is defined as a macro:
4051
4052<pre>
4053 #define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
4054</pre><p>
4055Note that <code>f</code> is used twice.
4056
4057
4058
4059
4060
4061<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p>
4062<span class="apii">[-0, +1, <em>e</em>]</span>
4063<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
4064
4065<p>
4066Pushes onto the stack a formatted string
4067and returns a pointer to this string.
4068It is similar to the ANSI&nbsp;C function <code>sprintf</code>,
4069but has some important differences:
4070
4071<ul>
4072
4073<li>
4074You do not have to allocate space for the result:
4075the result is a Lua string and Lua takes care of memory allocation
4076(and deallocation, through garbage collection).
4077</li>
4078
4079<li>
4080The conversion specifiers are quite restricted.
4081There are no flags, widths, or precisions.
4082The conversion specifiers can only be
4083'<code>%%</code>' (inserts a '<code>%</code>' in the string),
4084'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
4085'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4086'<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
4087'<code>%d</code>' (inserts an <code>int</code>), and
4088'<code>%c</code>' (inserts an <code>int</code> as a byte).
4089</li>
4090
4091</ul>
4092
4093
4094
4095
4096<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4097<span class="apii">[-0, +1, &ndash;]</span>
4098<pre>void lua_pushglobaltable (lua_State *L);</pre>
4099
4100<p>
4101Pushes the global environment onto the stack.
4102
4103
4104
4105
4106
4107<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4108<span class="apii">[-0, +1, &ndash;]</span>
4109<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4110
4111<p>
4112Pushes a number with value <code>n</code> onto the stack.
4113
4114
4115
4116
4117
4118<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4119<span class="apii">[-0, +1, &ndash;]</span>
4120<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4121
4122<p>
4123Pushes a light userdata onto the stack.
4124
4125
4126<p>
4127Userdata represent C&nbsp;values in Lua.
4128A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4129It is a value (like a number):
4130you do not create it, it has no individual metatable,
4131and it is not collected (as it was never created).
4132A light userdata is equal to "any"
4133light userdata with the same C&nbsp;address.
4134
4135
4136
4137
4138
4139<hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p>
4140<span class="apii">[-0, +1, <em>e</em>]</span>
4141<pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre>
4142
4143<p>
4144This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
4145but can be used only when <code>s</code> is a literal string.
4146It automatically provides the string length.
4147
4148
4149
4150
4151
4152<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p>
4153<span class="apii">[-0, +1, <em>e</em>]</span>
4154<pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
4155
4156<p>
4157Pushes the string pointed to by <code>s</code> with size <code>len</code>
4158onto the stack.
4159Lua makes (or reuses) an internal copy of the given string,
4160so the memory at <code>s</code> can be freed or reused immediately after
4161the function returns.
4162The string can contain any binary data,
4163including embedded zeros.
4164
4165
4166<p>
4167Returns a pointer to the internal copy of the string.
4168
4169
4170
4171
4172
4173<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4174<span class="apii">[-0, +1, &ndash;]</span>
4175<pre>void lua_pushnil (lua_State *L);</pre>
4176
4177<p>
4178Pushes a nil value onto the stack.
4179
4180
4181
4182
4183
4184<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4185<span class="apii">[-0, +1, &ndash;]</span>
4186<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4187
4188<p>
4189Pushes a number with value <code>n</code> onto the stack.
4190
4191
4192
4193
4194
4195<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p>
4196<span class="apii">[-0, +1, <em>e</em>]</span>
4197<pre>const char *lua_pushstring (lua_State *L, const char *s);</pre>
4198
4199<p>
4200Pushes the zero-terminated string pointed to by <code>s</code>
4201onto the stack.
4202Lua makes (or reuses) an internal copy of the given string,
4203so the memory at <code>s</code> can be freed or reused immediately after
4204the function returns.
4205
4206
4207<p>
4208Returns a pointer to the internal copy of the string.
4209
4210
4211<p>
4212If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4213
4214
4215
4216
4217
4218<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4219<span class="apii">[-0, +1, &ndash;]</span>
4220<pre>int lua_pushthread (lua_State *L);</pre>
4221
4222<p>
4223Pushes the thread represented by <code>L</code> onto the stack.
4224Returns 1 if this thread is the main thread of its state.
4225
4226
4227
4228
4229
4230<hr><h3><a name="lua_pushunsigned"><code>lua_pushunsigned</code></a></h3><p>
4231<span class="apii">[-0, +1, &ndash;]</span>
4232<pre>void lua_pushunsigned (lua_State *L, lua_Unsigned n);</pre>
4233
4234<p>
4235Pushes a number with value <code>n</code> onto the stack.
4236
4237
4238
4239
4240
4241<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4242<span class="apii">[-0, +1, &ndash;]</span>
4243<pre>void lua_pushvalue (lua_State *L, int index);</pre>
4244
4245<p>
4246Pushes a copy of the element at the given index
4247onto the stack.
4248
4249
4250
4251
4252
4253<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p>
4254<span class="apii">[-0, +1, <em>e</em>]</span>
4255<pre>const char *lua_pushvfstring (lua_State *L,
4256 const char *fmt,
4257 va_list argp);</pre>
4258
4259<p>
4260Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4261instead of a variable number of arguments.
4262
4263
4264
4265
4266
4267<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4268<span class="apii">[-0, +0, &ndash;]</span>
4269<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4270
4271<p>
4272Returns 1 if the two values in indices <code>index1</code> and
4273<code>index2</code> are primitively equal
4274(that is, without calling metamethods).
4275Otherwise returns&nbsp;0.
4276Also returns&nbsp;0 if any of the indices are non valid.
4277
4278
4279
4280
4281
4282<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4283<span class="apii">[-1, +1, &ndash;]</span>
4284<pre>void lua_rawget (lua_State *L, int index);</pre>
4285
4286<p>
4287Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4288(i.e., without metamethods).
4289
4290
4291
4292
4293
4294<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4295<span class="apii">[-0, +1, &ndash;]</span>
4296<pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
4297
4298<p>
4299Pushes onto the stack the value <code>t[n]</code>,
4300where <code>t</code> is the table at the given index.
4301The access is raw;
4302that is, it does not invoke metamethods.
4303
4304
4305
4306
4307
4308<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4309<span class="apii">[-0, +1, &ndash;]</span>
4310<pre>void lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4311
4312<p>
4313Pushes onto the stack the value <code>t[k]</code>,
4314where <code>t</code> is the table at the given index and
4315<code>k</code> is the pointer <code>p</code> represented as a light userdata.
4316The access is raw;
4317that is, it does not invoke metamethods.
4318
4319
4320
4321
4322
4323<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
4324<span class="apii">[-0, +0, &ndash;]</span>
4325<pre>size_t lua_rawlen (lua_State *L, int index);</pre>
4326
4327<p>
4328Returns the raw "length" of the value at the given index:
4329for strings, this is the string length;
4330for tables, this is the result of the length operator ('<code>#</code>')
4331with no metamethods;
4332for userdata, this is the size of the block of memory allocated
4333for the userdata;
4334for other values, it is&nbsp;0.
4335
4336
4337
4338
4339
4340<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p>
4341<span class="apii">[-2, +0, <em>e</em>]</span>
4342<pre>void lua_rawset (lua_State *L, int index);</pre>
4343
4344<p>
4345Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
4346(i.e., without metamethods).
4347
4348
4349
4350
4351
4352<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
4353<span class="apii">[-1, +0, <em>e</em>]</span>
4354<pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
4355
4356<p>
4357Does the equivalent of <code>t[n] = v</code>,
4358where <code>t</code> is the table at the given index
4359and <code>v</code> is the value at the top of the stack.
4360
4361
4362<p>
4363This function pops the value from the stack.
4364The assignment is raw;
4365that is, it does not invoke metamethods.
4366
4367
4368
4369
4370
4371<hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p>
4372<span class="apii">[-1, +0, <em>e</em>]</span>
4373<pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre>
4374
4375<p>
4376Does the equivalent of <code>t[k] = v</code>,
4377where <code>t</code> is the table at the given index,
4378<code>k</code> is the pointer <code>p</code> represented as a light userdata,
4379and <code>v</code> is the value at the top of the stack.
4380
4381
4382<p>
4383This function pops the value from the stack.
4384The assignment is raw;
4385that is, it does not invoke metamethods.
4386
4387
4388
4389
4390
4391<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
4392<pre>typedef const char * (*lua_Reader) (lua_State *L,
4393 void *data,
4394 size_t *size);</pre>
4395
4396<p>
4397The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
4398Every time it needs another piece of the chunk,
4399<a href="#lua_load"><code>lua_load</code></a> calls the reader,
4400passing along its <code>data</code> parameter.
4401The reader must return a pointer to a block of memory
4402with a new piece of the chunk
4403and set <code>size</code> to the block size.
4404The block must exist until the reader function is called again.
4405To signal the end of the chunk,
4406the reader must return <code>NULL</code> or set <code>size</code> to zero.
4407The reader function may return pieces of any size greater than zero.
4408
4409
4410
4411
4412
4413<hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p>
4414<span class="apii">[-0, +0, <em>e</em>]</span>
4415<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
4416
4417<p>
4418Sets the C function <code>f</code> as the new value of global <code>name</code>.
4419It is defined as a macro:
4420
4421<pre>
4422 #define lua_register(L,n,f) \
4423 (lua_pushcfunction(L, f), lua_setglobal(L, n))
4424</pre>
4425
4426
4427
4428
4429<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
4430<span class="apii">[-1, +0, &ndash;]</span>
4431<pre>void lua_remove (lua_State *L, int index);</pre>
4432
4433<p>
4434Removes the element at the given valid index,
4435shifting down the elements above this index to fill the gap.
4436This function cannot be called with a pseudo-index,
4437because a pseudo-index is not an actual stack position.
4438
4439
4440
4441
4442
4443<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
4444<span class="apii">[-1, +0, &ndash;]</span>
4445<pre>void lua_replace (lua_State *L, int index);</pre>
4446
4447<p>
4448Moves the top element into the given valid index
4449without shifting any element
4450(therefore replacing the value at the given index),
4451and then pops the top element.
4452
4453
4454
4455
4456
4457<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
4458<span class="apii">[-?, +?, &ndash;]</span>
4459<pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre>
4460
4461<p>
4462Starts and resumes a coroutine in a given thread.
4463
4464
4465<p>
4466To start a coroutine,
4467you push onto the thread stack the main function plus any arguments;
4468then you call <a href="#lua_resume"><code>lua_resume</code></a>,
4469with <code>nargs</code> being the number of arguments.
4470This call returns when the coroutine suspends or finishes its execution.
4471When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
4472or all values returned by the body function.
4473<a href="#lua_resume"><code>lua_resume</code></a> returns
4474<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
4475<a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution
4476without errors,
4477or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
4478
4479
4480<p>
4481In case of errors,
4482the stack is not unwound,
4483so you can use the debug API over it.
4484The error message is on the top of the stack.
4485
4486
4487<p>
4488To resume a coroutine,
4489you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>,
4490put on its stack only the values to
4491be passed as results from <code>yield</code>,
4492and then call <a href="#lua_resume"><code>lua_resume</code></a>.
4493
4494
4495<p>
4496The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
4497If there is no such coroutine,
4498this parameter can be <code>NULL</code>.
4499
4500
4501
4502
4503
4504<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
4505<span class="apii">[-0, +0, &ndash;]</span>
4506<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
4507
4508<p>
4509Changes the allocator function of a given state to <code>f</code>
4510with user data <code>ud</code>.
4511
4512
4513
4514
4515
4516<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p>
4517<span class="apii">[-1, +0, <em>e</em>]</span>
4518<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
4519
4520<p>
4521Does the equivalent to <code>t[k] = v</code>,
4522where <code>t</code> is the value at the given index
4523and <code>v</code> is the value at the top of the stack.
4524
4525
4526<p>
4527This function pops the value from the stack.
4528As in Lua, this function may trigger a metamethod
4529for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4530
4531
4532
4533
4534
4535<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p>
4536<span class="apii">[-1, +0, <em>e</em>]</span>
4537<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
4538
4539<p>
4540Pops a value from the stack and
4541sets it as the new value of global <code>name</code>.
4542
4543
4544
4545
4546
4547<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
4548<span class="apii">[-1, +0, &ndash;]</span>
4549<pre>void lua_setmetatable (lua_State *L, int index);</pre>
4550
4551<p>
4552Pops a table from the stack and
4553sets it as the new metatable for the value at the given index.
4554
4555
4556
4557
4558
4559<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p>
4560<span class="apii">[-2, +0, <em>e</em>]</span>
4561<pre>void lua_settable (lua_State *L, int index);</pre>
4562
4563<p>
4564Does the equivalent to <code>t[k] = v</code>,
4565where <code>t</code> is the value at the given index,
4566<code>v</code> is the value at the top of the stack,
4567and <code>k</code> is the value just below the top.
4568
4569
4570<p>
4571This function pops both the key and the value from the stack.
4572As in Lua, this function may trigger a metamethod
4573for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4574
4575
4576
4577
4578
4579<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
4580<span class="apii">[-?, +?, &ndash;]</span>
4581<pre>void lua_settop (lua_State *L, int index);</pre>
4582
4583<p>
4584Accepts any index, or&nbsp;0,
4585and sets the stack top to this index.
4586If the new top is larger than the old one,
4587then the new elements are filled with <b>nil</b>.
4588If <code>index</code> is&nbsp;0, then all stack elements are removed.
4589
4590
4591
4592
4593
4594<hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p>
4595<span class="apii">[-1, +0, &ndash;]</span>
4596<pre>void lua_setuservalue (lua_State *L, int index);</pre>
4597
4598<p>
4599Pops a table or <b>nil</b> from the stack and sets it as
4600the new value associated to the userdata at the given index.
4601
4602
4603
4604
4605
4606<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
4607<pre>typedef struct lua_State lua_State;</pre>
4608
4609<p>
4610An opaque structure that points to a thread and indirectly
4611(through the thread) to the whole state of a Lua interpreter.
4612The Lua library is fully reentrant:
4613it has no global variables.
4614All information about a state is accessible through this structure.
4615
4616
4617<p>
4618A pointer to this structure must be passed as the first argument to
4619every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4620which creates a Lua state from scratch.
4621
4622
4623
4624
4625
4626<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4627<span class="apii">[-0, +0, &ndash;]</span>
4628<pre>int lua_status (lua_State *L);</pre>
4629
4630<p>
4631Returns the status of the thread <code>L</code>.
4632
4633
4634<p>
4635The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread,
4636an error code if the thread finished the execution
4637of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
4638or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4639
4640
4641<p>
4642You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
4643You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
4644(to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a>
4645(to resume a coroutine).
4646
4647
4648
4649
4650
4651<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4652<span class="apii">[-0, +0, &ndash;]</span>
4653<pre>int lua_toboolean (lua_State *L, int index);</pre>
4654
4655<p>
4656Converts the Lua value at the given index to a C&nbsp;boolean
4657value (0&nbsp;or&nbsp;1).
4658Like all tests in Lua,
4659<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
4660different from <b>false</b> and <b>nil</b>;
4661otherwise it returns false.
4662(If you want to accept only actual boolean values,
4663use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4664
4665
4666
4667
4668
4669<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4670<span class="apii">[-0, +0, &ndash;]</span>
4671<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4672
4673<p>
4674Converts a value at the given index to a C&nbsp;function.
4675That value must be a C&nbsp;function;
4676otherwise, returns <code>NULL</code>.
4677
4678
4679
4680
4681
4682<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4683<span class="apii">[-0, +0, &ndash;]</span>
4684<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4685
4686<p>
4687Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4688
4689
4690
4691
4692
4693<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
4694<span class="apii">[-0, +0, &ndash;]</span>
4695<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
4696
4697<p>
4698Converts the Lua value at the given index
4699to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4700The Lua value must be a number or a string convertible to a number
4701(see <a href="#3.4.2">&sect;3.4.2</a>);
4702otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
4703
4704
4705<p>
4706If the number is not an integer,
4707it is truncated in some non-specified way.
4708
4709
4710<p>
4711If <code>isnum</code> is not <code>NULL</code>,
4712its referent is assigned a boolean value that
4713indicates whether the operation succeeded.
4714
4715
4716
4717
4718
4719<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p>
4720<span class="apii">[-0, +0, <em>e</em>]</span>
4721<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
4722
4723<p>
4724Converts the Lua value at the given index to a C&nbsp;string.
4725If <code>len</code> is not <code>NULL</code>,
4726it also sets <code>*len</code> with the string length.
4727The Lua value must be a string or a number;
4728otherwise, the function returns <code>NULL</code>.
4729If the value is a number,
4730then <code>lua_tolstring</code> also
4731<em>changes the actual value in the stack to a string</em>.
4732(This change confuses <a href="#lua_next"><code>lua_next</code></a>
4733when <code>lua_tolstring</code> is applied to keys during a table traversal.)
4734
4735
4736<p>
4737<code>lua_tolstring</code> returns a fully aligned pointer
4738to a string inside the Lua state.
4739This string always has a zero ('<code>\0</code>')
4740after its last character (as in&nbsp;C),
4741but can contain other zeros in its body.
4742Because Lua has garbage collection,
4743there is no guarantee that the pointer returned by <code>lua_tolstring</code>
4744will be valid after the corresponding value is removed from the stack.
4745
4746
4747
4748
4749
4750<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
4751<span class="apii">[-0, +0, &ndash;]</span>
4752<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
4753
4754<p>
4755Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4756
4757
4758
4759
4760
4761<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
4762<span class="apii">[-0, +0, &ndash;]</span>
4763<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
4764
4765<p>
4766Converts the Lua value at the given index
4767to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
4768The Lua value must be a number or a string convertible to a number
4769(see <a href="#3.4.2">&sect;3.4.2</a>);
4770otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
4771
4772
4773<p>
4774If <code>isnum</code> is not <code>NULL</code>,
4775its referent is assigned a boolean value that
4776indicates whether the operation succeeded.
4777
4778
4779
4780
4781
4782<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
4783<span class="apii">[-0, +0, &ndash;]</span>
4784<pre>const void *lua_topointer (lua_State *L, int index);</pre>
4785
4786<p>
4787Converts the value at the given index to a generic
4788C&nbsp;pointer (<code>void*</code>).
4789The value can be a userdata, a table, a thread, or a function;
4790otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
4791Different objects will give different pointers.
4792There is no way to convert the pointer back to its original value.
4793
4794
4795<p>
4796Typically this function is used only for debug information.
4797
4798
4799
4800
4801
4802<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p>
4803<span class="apii">[-0, +0, <em>e</em>]</span>
4804<pre>const char *lua_tostring (lua_State *L, int index);</pre>
4805
4806<p>
4807Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4808
4809
4810
4811
4812
4813<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
4814<span class="apii">[-0, +0, &ndash;]</span>
4815<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4816
4817<p>
4818Converts the value at the given index to a Lua thread
4819(represented as <code>lua_State*</code>).
4820This value must be a thread;
4821otherwise, the function returns <code>NULL</code>.
4822
4823
4824
4825
4826
4827<hr><h3><a name="lua_tounsigned"><code>lua_tounsigned</code></a></h3><p>
4828<span class="apii">[-0, +0, &ndash;]</span>
4829<pre>lua_Unsigned lua_tounsigned (lua_State *L, int index);</pre>
4830
4831<p>
4832Equivalent to <a href="#lua_tounsignedx"><code>lua_tounsignedx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4833
4834
4835
4836
4837
4838<hr><h3><a name="lua_tounsignedx"><code>lua_tounsignedx</code></a></h3><p>
4839<span class="apii">[-0, +0, &ndash;]</span>
4840<pre>lua_Unsigned lua_tounsignedx (lua_State *L, int index, int *isnum);</pre>
4841
4842<p>
4843Converts the Lua value at the given index
4844to the unsigned integral type <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
4845The Lua value must be a number or a string convertible to a number
4846(see <a href="#3.4.2">&sect;3.4.2</a>);
4847otherwise, <code>lua_tounsignedx</code> returns&nbsp;0.
4848
4849
4850<p>
4851If the number is not an integer,
4852it is truncated in some non-specified way.
4853If the number is outside the range of representable values,
4854it is normalized to the remainder of its division by
4855one more than the maximum representable value.
4856
4857
4858<p>
4859If <code>isnum</code> is not <code>NULL</code>,
4860its referent is assigned a boolean value that
4861indicates whether the operation succeeded.
4862
4863
4864
4865
4866
4867<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
4868<span class="apii">[-0, +0, &ndash;]</span>
4869<pre>void *lua_touserdata (lua_State *L, int index);</pre>
4870
4871<p>
4872If the value at the given index is a full userdata,
4873returns its block address.
4874If the value is a light userdata,
4875returns its pointer.
4876Otherwise, returns <code>NULL</code>.
4877
4878
4879
4880
4881
4882<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
4883<span class="apii">[-0, +0, &ndash;]</span>
4884<pre>int lua_type (lua_State *L, int index);</pre>
4885
4886<p>
4887Returns the type of the value in the given valid index,
4888or <code>LUA_TNONE</code> for a non-valid (but acceptable) index.
4889The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4890defined in <code>lua.h</code>:
4891<a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a>,
4892<a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>,
4893<a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>,
4894<a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>,
4895<a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>,
4896<a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>,
4897<a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>,
4898<a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>,
4899and
4900<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
4901
4902
4903
4904
4905
4906<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
4907<span class="apii">[-0, +0, &ndash;]</span>
4908<pre>const char *lua_typename (lua_State *L, int tp);</pre>
4909
4910<p>
4911Returns the name of the type encoded by the value <code>tp</code>,
4912which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4913
4914
4915
4916
4917
4918<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
4919<pre>typedef unsigned long lua_Unsigned;</pre>
4920
4921<p>
4922The type used by the Lua API to represent unsigned integral values.
4923It must have at least 32 bits.
4924
4925
4926<p>
4927By default it is an <code>unsigned int</code> or an <code>unsigned long</code>,
4928whichever can hold 32-bit values.
4929
4930
4931
4932
4933
4934<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
4935<span class="apii">[-0, +0, &ndash;]</span>
4936<pre>int lua_upvalueindex (int i);</pre>
4937
4938<p>
4939Returns the pseudo-index that represents the <code>i</code>-th upvalue of
4940the running function (see <a href="#4.4">&sect;4.4</a>).
4941
4942
4943
4944
4945
4946<hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p>
4947<span class="apii">[-0, +0, <em>v</em>]</span>
4948<pre>const lua_Number *lua_version (lua_State *L);</pre>
4949
4950<p>
4951Returns the address of the version number stored in the Lua core.
4952When called with a valid <a href="#lua_State"><code>lua_State</code></a>,
4953returns the address of the version used to create that state.
4954When called with <code>NULL</code>,
4955returns the address of the version running the call.
4956
4957
4958
4959
4960
4961<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4962<pre>typedef int (*lua_Writer) (lua_State *L,
4963 const void* p,
4964 size_t sz,
4965 void* ud);</pre>
4966
4967<p>
4968The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4969Every time it produces another piece of chunk,
4970<a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4971passing along the buffer to be written (<code>p</code>),
4972its size (<code>sz</code>),
4973and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4974
4975
4976<p>
4977The writer returns an error code:
49780&nbsp;means no errors;
4979any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4980calling the writer again.
4981
4982
4983
4984
4985
4986<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
4987<span class="apii">[-?, +?, &ndash;]</span>
4988<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4989
4990<p>
4991Exchange values between different threads of the same state.
4992
4993
4994<p>
4995This function pops <code>n</code> values from the stack <code>from</code>,
4996and pushes them onto the stack <code>to</code>.
4997
4998
4999
5000
5001
5002<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5003<span class="apii">[-?, +?, &ndash;]</span>
5004<pre>int lua_yield (lua_State *L, int nresults);</pre>
5005
5006<p>
5007This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5008but it has no continuation (see <a href="#4.7">&sect;4.7</a>).
5009Therefore, when the thread resumes,
5010it returns to the function that called
5011the function calling <code>lua_yield</code>.
5012
5013
5014
5015
5016
5017<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5018<span class="apii">[-?, +?, &ndash;]</span>
5019<pre>int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k);</pre>
5020
5021<p>
5022Yields a coroutine.
5023
5024
5025<p>
5026This function should only be called as the
5027return expression of a C&nbsp;function, as follows:
5028
5029<pre>
5030 return lua_yieldk (L, n, i, k);
5031</pre><p>
5032When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a> in that way,
5033the running coroutine suspends its execution,
5034and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5035The parameter <code>nresults</code> is the number of values from the stack
5036that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5037
5038
5039<p>
5040When the coroutine is resumed again,
5041Lua calls the given continuation function <code>k</code> to continue
5042the execution of the C function that yielded (see <a href="#4.7">&sect;4.7</a>).
5043This continuation function receives the same stack
5044from the previous function,
5045with the results removed and
5046replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5047Moreover,
5048the continuation function may access the value <code>ctx</code>
5049by calling <a href="#lua_getctx"><code>lua_getctx</code></a>.
5050
5051
5052
5053
5054
5055
5056
5057<h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2>
5058
5059<p>
5060Lua has no built-in debugging facilities.
5061Instead, it offers a special interface
5062by means of functions and <em>hooks</em>.
5063This interface allows the construction of different
5064kinds of debuggers, profilers, and other tools
5065that need "inside information" from the interpreter.
5066
5067
5068
5069<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5070<pre>typedef struct lua_Debug {
5071 int event;
5072 const char *name; /* (n) */
5073 const char *namewhat; /* (n) */
5074 const char *what; /* (S) */
5075 const char *source; /* (S) */
5076 int currentline; /* (l) */
5077 int linedefined; /* (S) */
5078 int lastlinedefined; /* (S) */
5079 unsigned char nups; /* (u) number of upvalues */
5080 unsigned char nparams; /* (u) number of parameters */
5081 char isvararg; /* (u) */
5082 char istailcall; /* (t) */
5083 char short_src[LUA_IDSIZE]; /* (S) */
5084 /* private part */
5085 <em>other fields</em>
5086} lua_Debug;</pre>
5087
5088<p>
5089A structure used to carry different pieces of
5090information about a function or an activation record.
5091<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5092of this structure, for later use.
5093To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5094call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5095
5096
5097<p>
5098The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5099
5100<ul>
5101
5102<li><b><code>source</code>: </b>
5103the source of the chunk that created the function.
5104If <code>source</code> starts with a '<code>@</code>',
5105it means that the function was defined in a file where
5106the file name follows the '<code>@</code>'.
5107If <code>source</code> starts with a '<code>=</code>',
5108the remainder of its contents describe the source in a user-dependent manner.
5109Otherwise,
5110the function was defined in a string where
5111<code>source</code> is that string.
5112</li>
5113
5114<li><b><code>short_src</code>: </b>
5115a "printable" version of <code>source</code>, to be used in error messages.
5116</li>
5117
5118<li><b><code>linedefined</code>: </b>
5119the line number where the definition of the function starts.
5120</li>
5121
5122<li><b><code>lastlinedefined</code>: </b>
5123the line number where the definition of the function ends.
5124</li>
5125
5126<li><b><code>what</code>: </b>
5127the string <code>"Lua"</code> if the function is a Lua function,
5128<code>"C"</code> if it is a C&nbsp;function,
5129<code>"main"</code> if it is the main part of a chunk.
5130</li>
5131
5132<li><b><code>currentline</code>: </b>
5133the current line where the given function is executing.
5134When no line information is available,
5135<code>currentline</code> is set to -1.
5136</li>
5137
5138<li><b><code>name</code>: </b>
5139a reasonable name for the given function.
5140Because functions in Lua are first-class values,
5141they do not have a fixed name:
5142some functions can be the value of multiple global variables,
5143while others can be stored only in a table field.
5144The <code>lua_getinfo</code> function checks how the function was
5145called to find a suitable name.
5146If it cannot find a name,
5147then <code>name</code> is set to <code>NULL</code>.
5148</li>
5149
5150<li><b><code>namewhat</code>: </b>
5151explains the <code>name</code> field.
5152The value of <code>namewhat</code> can be
5153<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
5154<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
5155according to how the function was called.
5156(Lua uses the empty string when no other option seems to apply.)
5157</li>
5158
5159<li><b><code>istailcall</code>: </b>
5160true if this function invocation was called by a tail call.
5161In this case, the caller of this level is not in the stack.
5162</li>
5163
5164<li><b><code>nups</code>: </b>
5165the number of upvalues of the function.
5166</li>
5167
5168<li><b><code>nparams</code>: </b>
5169the number of fixed parameters of the function
5170(always 0&nbsp;for C&nbsp;functions).
5171</li>
5172
5173<li><b><code>isvararg</code>: </b>
5174true if the function is a vararg function
5175(always true for C&nbsp;functions).
5176</li>
5177
5178</ul>
5179
5180
5181
5182
5183<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
5184<span class="apii">[-0, +0, &ndash;]</span>
5185<pre>lua_Hook lua_gethook (lua_State *L);</pre>
5186
5187<p>
5188Returns the current hook function.
5189
5190
5191
5192
5193
5194<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
5195<span class="apii">[-0, +0, &ndash;]</span>
5196<pre>int lua_gethookcount (lua_State *L);</pre>
5197
5198<p>
5199Returns the current hook count.
5200
5201
5202
5203
5204
5205<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
5206<span class="apii">[-0, +0, &ndash;]</span>
5207<pre>int lua_gethookmask (lua_State *L);</pre>
5208
5209<p>
5210Returns the current hook mask.
5211
5212
5213
5214
5215
5216<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p>
5217<span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span>
5218<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
5219
5220<p>
5221Gets information about a specific function or function invocation.
5222
5223
5224<p>
5225To get information about a function invocation,
5226the parameter <code>ar</code> must be a valid activation record that was
5227filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5228given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5229
5230
5231<p>
5232To get information about a function you push it onto the stack
5233and start the <code>what</code> string with the character '<code>&gt;</code>'.
5234(In that case,
5235<code>lua_getinfo</code> pops the function from the top of the stack.)
5236For instance, to know in which line a function <code>f</code> was defined,
5237you can write the following code:
5238
5239<pre>
5240 lua_Debug ar;
5241 lua_getglobal(L, "f"); /* get global 'f' */
5242 lua_getinfo(L, "&gt;S", &amp;ar);
5243 printf("%d\n", ar.linedefined);
5244</pre>
5245
5246<p>
5247Each character in the string <code>what</code>
5248selects some fields of the structure <code>ar</code> to be filled or
5249a value to be pushed on the stack:
5250
5251<ul>
5252
5253<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
5254</li>
5255
5256<li><b>'<code>S</code>': </b>
5257fills in the fields <code>source</code>, <code>short_src</code>,
5258<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
5259</li>
5260
5261<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
5262</li>
5263
5264<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
5265</li>
5266
5267<li><b>'<code>u</code>': </b> fills in the fields
5268<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
5269</li>
5270
5271<li><b>'<code>f</code>': </b>
5272pushes onto the stack the function that is
5273running at the given level;
5274</li>
5275
5276<li><b>'<code>L</code>': </b>
5277pushes onto the stack a table whose indices are the
5278numbers of the lines that are valid on the function.
5279(A <em>valid line</em> is a line with some associated code,
5280that is, a line where you can put a break point.
5281Non-valid lines include empty lines and comments.)
5282</li>
5283
5284</ul>
5285
5286<p>
5287This function returns 0 on error
5288(for instance, an invalid option in <code>what</code>).
5289
5290
5291
5292
5293
5294<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
5295<span class="apii">[-0, +(0|1), &ndash;]</span>
5296<pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5297
5298<p>
5299Gets information about a local variable of
5300a given activation record or a given function.
5301
5302
5303<p>
5304In the first case,
5305the parameter <code>ar</code> must be a valid activation record that was
5306filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5307given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5308The index <code>n</code> selects which local variable to inspect;
5309see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
5310and names.
5311
5312
5313<p>
5314<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
5315and returns its name.
5316
5317
5318<p>
5319In the second case, <code>ar</code> should be <code>NULL</code> and the function
5320to be inspected must be at the top of the stack.
5321In this case, only parameters of Lua functions are visible
5322(as there is no information about what variables are active)
5323and no values are pushed onto the stack.
5324
5325
5326<p>
5327Returns <code>NULL</code> (and pushes nothing)
5328when the index is greater than
5329the number of active local variables.
5330
5331
5332
5333
5334
5335<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
5336<span class="apii">[-0, +0, &ndash;]</span>
5337<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
5338
5339<p>
5340Gets information about the interpreter runtime stack.
5341
5342
5343<p>
5344This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
5345an identification of the <em>activation record</em>
5346of the function executing at a given level.
5347Level&nbsp;0 is the current running function,
5348whereas level <em>n+1</em> is the function that has called level <em>n</em>
5349(except for tail calls, which do not count on the stack).
5350When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
5351when called with a level greater than the stack depth,
5352it returns 0.
5353
5354
5355
5356
5357
5358<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
5359<span class="apii">[-0, +(0|1), &ndash;]</span>
5360<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
5361
5362<p>
5363Gets information about a closure's upvalue.
5364(For Lua functions,
5365upvalues are the external local variables that the function uses,
5366and that are consequently included in its closure.)
5367<a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
5368pushes the upvalue's value onto the stack,
5369and returns its name.
5370<code>funcindex</code> points to the closure in the stack.
5371(Upvalues have no particular order,
5372as they are active through the whole function.
5373So, they are numbered in an arbitrary order.)
5374
5375
5376<p>
5377Returns <code>NULL</code> (and pushes nothing)
5378when the index is greater than the number of upvalues.
5379For C&nbsp;functions, this function uses the empty string <code>""</code>
5380as a name for all upvalues.
5381
5382
5383
5384
5385
5386<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
5387<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
5388
5389<p>
5390Type for debugging hook functions.
5391
5392
5393<p>
5394Whenever a hook is called, its <code>ar</code> argument has its field
5395<code>event</code> set to the specific event that triggered the hook.
5396Lua identifies these events with the following constants:
5397<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
5398<a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
5399and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
5400Moreover, for line events, the field <code>currentline</code> is also set.
5401To get the value of any other field in <code>ar</code>,
5402the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5403
5404
5405<p>
5406For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
5407the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
5408in this case, there will be no corresponding return event.
5409
5410
5411<p>
5412While Lua is running a hook, it disables other calls to hooks.
5413Therefore, if a hook calls back Lua to execute a function or a chunk,
5414this execution occurs without any calls to hooks.
5415
5416
5417<p>
5418Hook functions cannot have continuations,
5419that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5420<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>.
5421
5422
5423<p>
5424Hook functions can yield under the following conditions:
5425Only count and line events can yield
5426and they cannot yield any value;
5427to yield a hook function must finish its execution
5428calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero.
5429
5430
5431
5432
5433
5434<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
5435<span class="apii">[-0, +0, &ndash;]</span>
5436<pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5437
5438<p>
5439Sets the debugging hook function.
5440
5441
5442<p>
5443Argument <code>f</code> is the hook function.
5444<code>mask</code> specifies on which events the hook will be called:
5445it is formed by a bitwise or of the constants
5446<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
5447<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
5448<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
5449and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
5450The <code>count</code> argument is only meaningful when the mask
5451includes <code>LUA_MASKCOUNT</code>.
5452For each event, the hook is called as explained below:
5453
5454<ul>
5455
5456<li><b>The call hook: </b> is called when the interpreter calls a function.
5457The hook is called just after Lua enters the new function,
5458before the function gets its arguments.
5459</li>
5460
5461<li><b>The return hook: </b> is called when the interpreter returns from a function.
5462The hook is called just before Lua leaves the function.
5463There is no standard way to access the values
5464to be returned by the function.
5465</li>
5466
5467<li><b>The line hook: </b> is called when the interpreter is about to
5468start the execution of a new line of code,
5469or when it jumps back in the code (even to the same line).
5470(This event only happens while Lua is executing a Lua function.)
5471</li>
5472
5473<li><b>The count hook: </b> is called after the interpreter executes every
5474<code>count</code> instructions.
5475(This event only happens while Lua is executing a Lua function.)
5476</li>
5477
5478</ul>
5479
5480<p>
5481A hook is disabled by setting <code>mask</code> to zero.
5482
5483
5484
5485
5486
5487<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
5488<span class="apii">[-(0|1), +0, &ndash;]</span>
5489<pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5490
5491<p>
5492Sets the value of a local variable of a given activation record.
5493Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
5494(see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
5495<a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
5496to the variable and returns its name.
5497It also pops the value from the stack.
5498
5499
5500<p>
5501Returns <code>NULL</code> (and pops nothing)
5502when the index is greater than
5503the number of active local variables.
5504
5505
5506
5507
5508
5509<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
5510<span class="apii">[-(0|1), +0, &ndash;]</span>
5511<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
5512
5513<p>
5514Sets the value of a closure's upvalue.
5515It assigns the value at the top of the stack
5516to the upvalue and returns its name.
5517It also pops the value from the stack.
5518Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
5519(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
5520
5521
5522<p>
5523Returns <code>NULL</code> (and pops nothing)
5524when the index is greater than the number of upvalues.
5525
5526
5527
5528
5529
5530<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
5531<span class="apii">[-0, +0, &ndash;]</span>
5532<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
5533
5534<p>
5535Returns an unique identifier for the upvalue numbered <code>n</code>
5536from the closure at index <code>funcindex</code>.
5537Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
5538(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>)
5539(but <code>n</code> cannot be greater than the number of upvalues).
5540
5541
5542<p>
5543These unique identifiers allow a program to check whether different
5544closures share upvalues.
5545Lua closures that share an upvalue
5546(that is, that access a same external local variable)
5547will return identical ids for those upvalue indices.
5548
5549
5550
5551
5552
5553<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
5554<span class="apii">[-0, +0, &ndash;]</span>
5555<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
5556 int funcindex2, int n2);</pre>
5557
5558<p>
5559Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
5560refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
5561
5562
5563
5564
5565
5566
5567
5568<h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1>
5569
5570<p>
5571
5572The <em>auxiliary library</em> provides several convenient functions
5573to interface C with Lua.
5574While the basic API provides the primitive functions for all
5575interactions between C and Lua,
5576the auxiliary library provides higher-level functions for some
5577common tasks.
5578
5579
5580<p>
5581All functions and types from the auxiliary library
5582are defined in header file <code>lauxlib.h</code> and
5583have a prefix <code>luaL_</code>.
5584
5585
5586<p>
5587All functions in the auxiliary library are built on
5588top of the basic API,
5589and so they provide nothing that cannot be done with that API.
5590Nevertheless, the use of the auxiliary library ensures
5591more consistency to your code.
5592
5593
5594<p>
5595Several functions in the auxiliary library use internally some
5596extra stack slots.
5597When a function in the auxiliary library uses less than five slots,
5598it does not check the stack size;
5599it simply assumes that there are enough slots.
5600
5601
5602<p>
5603Several functions in the auxiliary library are used to
5604check C&nbsp;function arguments.
5605Because the error message is formatted for arguments
5606(e.g., "<code>bad argument #1</code>"),
5607you should not use these functions for other stack values.
5608
5609
5610<p>
5611Functions called <code>luaL_check*</code>
5612always throw an error if the check is not satisfied.
5613
5614
5615
5616<h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2>
5617
5618<p>
5619Here we list all functions and types from the auxiliary library
5620in alphabetical order.
5621
5622
5623
5624<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p>
5625<span class="apii">[-?, +?, <em>e</em>]</span>
5626<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
5627
5628<p>
5629Adds the byte <code>c</code> to the buffer <code>B</code>
5630(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5631
5632
5633
5634
5635
5636<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p>
5637<span class="apii">[-?, +?, <em>e</em>]</span>
5638<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
5639
5640<p>
5641Adds the string pointed to by <code>s</code> with length <code>l</code> to
5642the buffer <code>B</code>
5643(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5644The string can contain embedded zeros.
5645
5646
5647
5648
5649
5650<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p>
5651<span class="apii">[-?, +?, <em>e</em>]</span>
5652<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
5653
5654<p>
5655Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
5656a string of length <code>n</code> previously copied to the
5657buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
5658
5659
5660
5661
5662
5663<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p>
5664<span class="apii">[-?, +?, <em>e</em>]</span>
5665<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
5666
5667<p>
5668Adds the zero-terminated string pointed to by <code>s</code>
5669to the buffer <code>B</code>
5670(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5671The string cannot contain embedded zeros.
5672
5673
5674
5675
5676
5677<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p>
5678<span class="apii">[-1, +?, <em>e</em>]</span>
5679<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
5680
5681<p>
5682Adds the value at the top of the stack
5683to the buffer <code>B</code>
5684(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5685Pops the value.
5686
5687
5688<p>
5689This is the only function on string buffers that can (and must)
5690be called with an extra element on the stack,
5691which is the value to be added to the buffer.
5692
5693
5694
5695
5696
5697<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p>
5698<span class="apii">[-0, +0, <em>v</em>]</span>
5699<pre>void luaL_argcheck (lua_State *L,
5700 int cond,
5701 int arg,
5702 const char *extramsg);</pre>
5703
5704<p>
5705Checks whether <code>cond</code> is true.
5706If not, raises an error with a standard message.
5707
5708
5709
5710
5711
5712<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p>
5713<span class="apii">[-0, +0, <em>v</em>]</span>
5714<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
5715
5716<p>
5717Raises an error with a standard message
5718that includes <code>extramsg</code> as a comment.
5719
5720
5721<p>
5722This function never returns,
5723but it is an idiom to use it in C&nbsp;functions
5724as <code>return luaL_argerror(<em>args</em>)</code>.
5725
5726
5727
5728
5729
5730<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
5731<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
5732
5733<p>
5734Type for a <em>string buffer</em>.
5735
5736
5737<p>
5738A string buffer allows C&nbsp;code to build Lua strings piecemeal.
5739Its pattern of use is as follows:
5740
5741<ul>
5742
5743<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
5744
5745<li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
5746
5747<li>
5748Then add string pieces to the buffer calling any of
5749the <code>luaL_add*</code> functions.
5750</li>
5751
5752<li>
5753Finish by calling <code>luaL_pushresult(&amp;b)</code>.
5754This call leaves the final string on the top of the stack.
5755</li>
5756
5757</ul>
5758
5759<p>
5760If you know beforehand the total size of the resulting string,
5761you can use the buffer like this:
5762
5763<ul>
5764
5765<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
5766
5767<li>Then initialize it and preallocate a space of
5768size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li>
5769
5770<li>Then copy the string into that space.</li>
5771
5772<li>
5773Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>,
5774where <code>sz</code> is the total size of the resulting string
5775copied into that space.
5776</li>
5777
5778</ul>
5779
5780<p>
5781During its normal operation,
5782a string buffer uses a variable number of stack slots.
5783So, while using a buffer, you cannot assume that you know where
5784the top of the stack is.
5785You can use the stack between successive calls to buffer operations
5786as long as that use is balanced;
5787that is,
5788when you call a buffer operation,
5789the stack is at the same level
5790it was immediately after the previous buffer operation.
5791(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
5792After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
5793level when the buffer was initialized,
5794plus the final string on its top.
5795
5796
5797
5798
5799
5800<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
5801<span class="apii">[-0, +0, &ndash;]</span>
5802<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
5803
5804<p>
5805Initializes a buffer <code>B</code>.
5806This function does not allocate any space;
5807the buffer must be declared as a variable
5808(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5809
5810
5811
5812
5813
5814<hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p>
5815<span class="apii">[-?, +?, <em>e</em>]</span>
5816<pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre>
5817
5818<p>
5819Equivalent to the sequence
5820<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
5821
5822
5823
5824
5825
5826<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p>
5827<span class="apii">[-0, +(0|1), <em>e</em>]</span>
5828<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
5829
5830<p>
5831Calls a metamethod.
5832
5833
5834<p>
5835If the object at index <code>obj</code> has a metatable and this
5836metatable has a field <code>e</code>,
5837this function calls this field passing the object as its only argument.
5838In this case this function returns true and pushes onto the
5839stack the value returned by the call.
5840If there is no metatable or no metamethod,
5841this function returns false (without pushing any value on the stack).
5842
5843
5844
5845
5846
5847<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p>
5848<span class="apii">[-0, +0, <em>v</em>]</span>
5849<pre>void luaL_checkany (lua_State *L, int arg);</pre>
5850
5851<p>
5852Checks whether the function has an argument
5853of any type (including <b>nil</b>) at position <code>arg</code>.
5854
5855
5856
5857
5858
5859<hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
5860<span class="apii">[-0, +0, <em>v</em>]</span>
5861<pre>int luaL_checkint (lua_State *L, int arg);</pre>
5862
5863<p>
5864Checks whether the function argument <code>arg</code> is a number
5865and returns this number cast to an <code>int</code>.
5866
5867
5868
5869
5870
5871<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
5872<span class="apii">[-0, +0, <em>v</em>]</span>
5873<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
5874
5875<p>
5876Checks whether the function argument <code>arg</code> is a number
5877and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
5878
5879
5880
5881
5882
5883<hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
5884<span class="apii">[-0, +0, <em>v</em>]</span>
5885<pre>long luaL_checklong (lua_State *L, int arg);</pre>
5886
5887<p>
5888Checks whether the function argument <code>arg</code> is a number
5889and returns this number cast to a <code>long</code>.
5890
5891
5892
5893
5894
5895<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
5896<span class="apii">[-0, +0, <em>v</em>]</span>
5897<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
5898
5899<p>
5900Checks whether the function argument <code>arg</code> is a string
5901and returns this string;
5902if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
5903with the string's length.
5904
5905
5906<p>
5907This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5908so all conversions and caveats of that function apply here.
5909
5910
5911
5912
5913
5914<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p>
5915<span class="apii">[-0, +0, <em>v</em>]</span>
5916<pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre>
5917
5918<p>
5919Checks whether the function argument <code>arg</code> is a number
5920and returns this number.
5921
5922
5923
5924
5925
5926<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p>
5927<span class="apii">[-0, +0, <em>v</em>]</span>
5928<pre>int luaL_checkoption (lua_State *L,
5929 int arg,
5930 const char *def,
5931 const char *const lst[]);</pre>
5932
5933<p>
5934Checks whether the function argument <code>arg</code> is a string and
5935searches for this string in the array <code>lst</code>
5936(which must be NULL-terminated).
5937Returns the index in the array where the string was found.
5938Raises an error if the argument is not a string or
5939if the string cannot be found.
5940
5941
5942<p>
5943If <code>def</code> is not <code>NULL</code>,
5944the function uses <code>def</code> as a default value when
5945there is no argument <code>arg</code> or when this argument is <b>nil</b>.
5946
5947
5948<p>
5949This is a useful function for mapping strings to C&nbsp;enums.
5950(The usual convention in Lua libraries is
5951to use strings instead of numbers to select options.)
5952
5953
5954
5955
5956
5957<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p>
5958<span class="apii">[-0, +0, <em>v</em>]</span>
5959<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
5960
5961<p>
5962Grows the stack size to <code>top + sz</code> elements,
5963raising an error if the stack cannot grow to that size.
5964<code>msg</code> is an additional text to go into the error message
5965(or <code>NULL</code> for no additional text).
5966
5967
5968
5969
5970
5971<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p>
5972<span class="apii">[-0, +0, <em>v</em>]</span>
5973<pre>const char *luaL_checkstring (lua_State *L, int arg);</pre>
5974
5975<p>
5976Checks whether the function argument <code>arg</code> is a string
5977and returns this string.
5978
5979
5980<p>
5981This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5982so all conversions and caveats of that function apply here.
5983
5984
5985
5986
5987
5988<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p>
5989<span class="apii">[-0, +0, <em>v</em>]</span>
5990<pre>void luaL_checktype (lua_State *L, int arg, int t);</pre>
5991
5992<p>
5993Checks whether the function argument <code>arg</code> has type <code>t</code>.
5994See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
5995
5996
5997
5998
5999
6000<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p>
6001<span class="apii">[-0, +0, <em>v</em>]</span>
6002<pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre>
6003
6004<p>
6005Checks whether the function argument <code>arg</code> is a userdata
6006of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6007returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
6008
6009
6010
6011
6012
6013<hr><h3><a name="luaL_checkunsigned"><code>luaL_checkunsigned</code></a></h3><p>
6014<span class="apii">[-0, +0, <em>v</em>]</span>
6015<pre>lua_Unsigned luaL_checkunsigned (lua_State *L, int arg);</pre>
6016
6017<p>
6018Checks whether the function argument <code>arg</code> is a number
6019and returns this number cast to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6020
6021
6022
6023
6024
6025<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6026<span class="apii">[-0, +0, &ndash;]</span>
6027<pre>void luaL_checkversion (lua_State *L);</pre>
6028
6029<p>
6030Checks whether the core running the call,
6031the core that created the Lua state,
6032and the code making the call are all using the same version of Lua.
6033Also checks whether the core running the call
6034and the core that created the Lua state
6035are using the same address space.
6036
6037
6038
6039
6040
6041<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p>
6042<span class="apii">[-0, +?, <em>e</em>]</span>
6043<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
6044
6045<p>
6046Loads and runs the given file.
6047It is defined as the following macro:
6048
6049<pre>
6050 (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6051</pre><p>
6052It returns false if there are no errors
6053or true in case of errors.
6054
6055
6056
6057
6058
6059<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6060<span class="apii">[-0, +?, &ndash;]</span>
6061<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6062
6063<p>
6064Loads and runs the given string.
6065It is defined as the following macro:
6066
6067<pre>
6068 (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6069</pre><p>
6070It returns false if there are no errors
6071or true in case of errors.
6072
6073
6074
6075
6076
6077<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p>
6078<span class="apii">[-0, +0, <em>v</em>]</span>
6079<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
6080
6081<p>
6082Raises an error.
6083The error message format is given by <code>fmt</code>
6084plus any extra arguments,
6085following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6086It also adds at the beginning of the message the file name and
6087the line number where the error occurred,
6088if this information is available.
6089
6090
6091<p>
6092This function never returns,
6093but it is an idiom to use it in C&nbsp;functions
6094as <code>return luaL_error(<em>args</em>)</code>.
6095
6096
6097
6098
6099
6100<hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p>
6101<span class="apii">[-0, +3, <em>e</em>]</span>
6102<pre>int luaL_execresult (lua_State *L, int stat);</pre>
6103
6104<p>
6105This function produces the return values for
6106process-related functions in the standard library
6107(<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>).
6108
6109
6110
6111
6112
6113<hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p>
6114<span class="apii">[-0, +(1|3), <em>e</em>]</span>
6115<pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre>
6116
6117<p>
6118This function produces the return values for
6119file-related functions in the standard library
6120(<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.).
6121
6122
6123
6124
6125
6126<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p>
6127<span class="apii">[-0, +(0|1), <em>e</em>]</span>
6128<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
6129
6130<p>
6131Pushes onto the stack the field <code>e</code> from the metatable
6132of the object at index <code>obj</code>.
6133If the object does not have a metatable,
6134or if the metatable does not have this field,
6135returns false and pushes nothing.
6136
6137
6138
6139
6140
6141<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
6142<span class="apii">[-0, +1, &ndash;]</span>
6143<pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
6144
6145<p>
6146Pushes onto the stack the metatable associated with name <code>tname</code>
6147in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6148
6149
6150
6151
6152
6153<hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p>
6154<span class="apii">[-0, +1, <em>e</em>]</span>
6155<pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre>
6156
6157<p>
6158Ensures that the value <code>t[fname]</code>,
6159where <code>t</code> is the value at index <code>idx</code>,
6160is a table,
6161and pushes that table onto the stack.
6162Returns true if it finds a previous table there
6163and false if it creates a new table.
6164
6165
6166
6167
6168
6169<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p>
6170<span class="apii">[-0, +1, <em>e</em>]</span>
6171<pre>const char *luaL_gsub (lua_State *L,
6172 const char *s,
6173 const char *p,
6174 const char *r);</pre>
6175
6176<p>
6177Creates a copy of string <code>s</code> by replacing
6178any occurrence of the string <code>p</code>
6179with the string <code>r</code>.
6180Pushes the resulting string on the stack and returns it.
6181
6182
6183
6184
6185
6186<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
6187<span class="apii">[-0, +0, <em>e</em>]</span>
6188<pre>int luaL_len (lua_State *L, int index);</pre>
6189
6190<p>
6191Returns the "length" of the value at the given index
6192as a number;
6193it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.6">&sect;3.4.6</a>).
6194Raises an error if the result of the operation is not a number.
6195(This case only can happen through metamethods.)
6196
6197
6198
6199
6200
6201<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
6202<span class="apii">[-0, +1, &ndash;]</span>
6203<pre>int luaL_loadbuffer (lua_State *L,
6204 const char *buff,
6205 size_t sz,
6206 const char *name);</pre>
6207
6208<p>
6209Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
6210
6211
6212
6213
6214
6215<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
6216<span class="apii">[-0, +1, &ndash;]</span>
6217<pre>int luaL_loadbufferx (lua_State *L,
6218 const char *buff,
6219 size_t sz,
6220 const char *name,
6221 const char *mode);</pre>
6222
6223<p>
6224Loads a buffer as a Lua chunk.
6225This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
6226buffer pointed to by <code>buff</code> with size <code>sz</code>.
6227
6228
6229<p>
6230This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6231<code>name</code> is the chunk name,
6232used for debug information and error messages.
6233The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6234
6235
6236
6237
6238
6239<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p>
6240<span class="apii">[-0, +1, <em>e</em>]</span>
6241<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
6242
6243<p>
6244Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
6245
6246
6247
6248
6249
6250<hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p>
6251<span class="apii">[-0, +1, <em>e</em>]</span>
6252<pre>int luaL_loadfilex (lua_State *L, const char *filename,
6253 const char *mode);</pre>
6254
6255<p>
6256Loads a file as a Lua chunk.
6257This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
6258named <code>filename</code>.
6259If <code>filename</code> is <code>NULL</code>,
6260then it loads from the standard input.
6261The first line in the file is ignored if it starts with a <code>#</code>.
6262
6263
6264<p>
6265The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6266
6267
6268<p>
6269This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
6270but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
6271if it cannot open/read the file or the file has a wrong mode.
6272
6273
6274<p>
6275As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6276it does not run it.
6277
6278
6279
6280
6281
6282<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
6283<span class="apii">[-0, +1, &ndash;]</span>
6284<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
6285
6286<p>
6287Loads a string as a Lua chunk.
6288This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
6289the zero-terminated string <code>s</code>.
6290
6291
6292<p>
6293This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6294
6295
6296<p>
6297Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6298it does not run it.
6299
6300
6301
6302
6303
6304<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
6305<span class="apii">[-0, +1, <em>e</em>]</span>
6306<pre>void luaL_newlib (lua_State *L, const luaL_Reg *l);</pre>
6307
6308<p>
6309Creates a new table and registers there
6310the functions in list <code>l</code>.
6311It is implemented as the following macro:
6312
6313<pre>
6314 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
6315</pre>
6316
6317
6318
6319
6320<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
6321<span class="apii">[-0, +1, <em>e</em>]</span>
6322<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
6323
6324<p>
6325Creates a new table with a size optimized
6326to store all entries in the array <code>l</code>
6327(but does not actually store them).
6328It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>
6329(see <a href="#luaL_newlib"><code>luaL_newlib</code></a>).
6330
6331
6332<p>
6333It is implemented as a macro.
6334The array <code>l</code> must be the actual array,
6335not a pointer to it.
6336
6337
6338
6339
6340
6341<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p>
6342<span class="apii">[-0, +1, <em>e</em>]</span>
6343<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
6344
6345<p>
6346If the registry already has the key <code>tname</code>,
6347returns 0.
6348Otherwise,
6349creates a new table to be used as a metatable for userdata,
6350adds it to the registry with key <code>tname</code>,
6351and returns 1.
6352
6353
6354<p>
6355In both cases pushes onto the stack the final value associated
6356with <code>tname</code> in the registry.
6357
6358
6359
6360
6361
6362<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
6363<span class="apii">[-0, +0, &ndash;]</span>
6364<pre>lua_State *luaL_newstate (void);</pre>
6365
6366<p>
6367Creates a new Lua state.
6368It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
6369allocator based on the standard&nbsp;C <code>realloc</code> function
6370and then sets a panic function (see <a href="#4.6">&sect;4.6</a>) that prints
6371an error message to the standard error output in case of fatal
6372errors.
6373
6374
6375<p>
6376Returns the new state,
6377or <code>NULL</code> if there is a memory allocation error.
6378
6379
6380
6381
6382
6383<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p>
6384<span class="apii">[-0, +0, <em>e</em>]</span>
6385<pre>void luaL_openlibs (lua_State *L);</pre>
6386
6387<p>
6388Opens all standard Lua libraries into the given state.
6389
6390
6391
6392
6393
6394<hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
6395<span class="apii">[-0, +0, <em>v</em>]</span>
6396<pre>int luaL_optint (lua_State *L, int arg, int d);</pre>
6397
6398<p>
6399If the function argument <code>arg</code> is a number,
6400returns this number cast to an <code>int</code>.
6401If this argument is absent or is <b>nil</b>,
6402returns <code>d</code>.
6403Otherwise, raises an error.
6404
6405
6406
6407
6408
6409<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
6410<span class="apii">[-0, +0, <em>v</em>]</span>
6411<pre>lua_Integer luaL_optinteger (lua_State *L,
6412 int arg,
6413 lua_Integer d);</pre>
6414
6415<p>
6416If the function argument <code>arg</code> is a number,
6417returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6418If this argument is absent or is <b>nil</b>,
6419returns <code>d</code>.
6420Otherwise, raises an error.
6421
6422
6423
6424
6425
6426<hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3><p>
6427<span class="apii">[-0, +0, <em>v</em>]</span>
6428<pre>long luaL_optlong (lua_State *L, int arg, long d);</pre>
6429
6430<p>
6431If the function argument <code>arg</code> is a number,
6432returns this number cast to a <code>long</code>.
6433If this argument is absent or is <b>nil</b>,
6434returns <code>d</code>.
6435Otherwise, raises an error.
6436
6437
6438
6439
6440
6441<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
6442<span class="apii">[-0, +0, <em>v</em>]</span>
6443<pre>const char *luaL_optlstring (lua_State *L,
6444 int arg,
6445 const char *d,
6446 size_t *l);</pre>
6447
6448<p>
6449If the function argument <code>arg</code> is a string,
6450returns this string.
6451If this argument is absent or is <b>nil</b>,
6452returns <code>d</code>.
6453Otherwise, raises an error.
6454
6455
6456<p>
6457If <code>l</code> is not <code>NULL</code>,
6458fills the position <code>*l</code> with the result's length.
6459
6460
6461
6462
6463
6464<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p>
6465<span class="apii">[-0, +0, <em>v</em>]</span>
6466<pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre>
6467
6468<p>
6469If the function argument <code>arg</code> is a number,
6470returns this number.
6471If this argument is absent or is <b>nil</b>,
6472returns <code>d</code>.
6473Otherwise, raises an error.
6474
6475
6476
6477
6478
6479<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p>
6480<span class="apii">[-0, +0, <em>v</em>]</span>
6481<pre>const char *luaL_optstring (lua_State *L,
6482 int arg,
6483 const char *d);</pre>
6484
6485<p>
6486If the function argument <code>arg</code> is a string,
6487returns this string.
6488If this argument is absent or is <b>nil</b>,
6489returns <code>d</code>.
6490Otherwise, raises an error.
6491
6492
6493
6494
6495
6496<hr><h3><a name="luaL_optunsigned"><code>luaL_optunsigned</code></a></h3><p>
6497<span class="apii">[-0, +0, <em>v</em>]</span>
6498<pre>lua_Unsigned luaL_optunsigned (lua_State *L,
6499 int arg,
6500 lua_Unsigned u);</pre>
6501
6502<p>
6503If the function argument <code>arg</code> is a number,
6504returns this number cast to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6505If this argument is absent or is <b>nil</b>,
6506returns <code>u</code>.
6507Otherwise, raises an error.
6508
6509
6510
6511
6512
6513<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
6514<span class="apii">[-?, +?, <em>e</em>]</span>
6515<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
6516
6517<p>
6518Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
6519with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
6520
6521
6522
6523
6524
6525<hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p>
6526<span class="apii">[-?, +?, <em>e</em>]</span>
6527<pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre>
6528
6529<p>
6530Returns an address to a space of size <code>sz</code>
6531where you can copy a string to be added to buffer <code>B</code>
6532(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6533After copying the string into this space you must call
6534<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add
6535it to the buffer.
6536
6537
6538
6539
6540
6541<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p>
6542<span class="apii">[-?, +1, <em>e</em>]</span>
6543<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
6544
6545<p>
6546Finishes the use of buffer <code>B</code> leaving the final string on
6547the top of the stack.
6548
6549
6550
6551
6552
6553<hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p>
6554<span class="apii">[-?, +1, <em>e</em>]</span>
6555<pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre>
6556
6557<p>
6558Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
6559
6560
6561
6562
6563
6564<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p>
6565<span class="apii">[-1, +0, <em>e</em>]</span>
6566<pre>int luaL_ref (lua_State *L, int t);</pre>
6567
6568<p>
6569Creates and returns a <em>reference</em>,
6570in the table at index <code>t</code>,
6571for the object at the top of the stack (and pops the object).
6572
6573
6574<p>
6575A reference is a unique integer key.
6576As long as you do not manually add integer keys into table <code>t</code>,
6577<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
6578You can retrieve an object referred by reference <code>r</code>
6579by calling <code>lua_rawgeti(L, t, r)</code>.
6580Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
6581
6582
6583<p>
6584If the object at the top of the stack is <b>nil</b>,
6585<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
6586The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
6587from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
6588
6589
6590
6591
6592
6593<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
6594<pre>typedef struct luaL_Reg {
6595 const char *name;
6596 lua_CFunction func;
6597} luaL_Reg;</pre>
6598
6599<p>
6600Type for arrays of functions to be registered by
6601<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
6602<code>name</code> is the function name and <code>func</code> is a pointer to
6603the function.
6604Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
6605in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
6606
6607
6608
6609
6610
6611<hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p>
6612<span class="apii">[-0, +1, <em>e</em>]</span>
6613<pre>void luaL_requiref (lua_State *L, const char *modname,
6614 lua_CFunction openf, int glb);</pre>
6615
6616<p>
6617Calls function <code>openf</code> with string <code>modname</code> as an argument
6618and sets the call result in <code>package.loaded[modname]</code>,
6619as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
6620
6621
6622<p>
6623If <code>glb</code> is true,
6624also stores the result into global <code>modname</code>.
6625
6626
6627<p>
6628Leaves a copy of that result on the stack.
6629
6630
6631
6632
6633
6634<hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p>
6635<span class="apii">[-nup, +0, <em>e</em>]</span>
6636<pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre>
6637
6638<p>
6639Registers all functions in the array <code>l</code>
6640(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack
6641(below optional upvalues, see next).
6642
6643
6644<p>
6645When <code>nup</code> is not zero,
6646all functions are created sharing <code>nup</code> upvalues,
6647which must be previously pushed on the stack
6648on top of the library table.
6649These values are popped from the stack after the registration.
6650
6651
6652
6653
6654
6655<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
6656<span class="apii">[-0, +0, &ndash;]</span>
6657<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
6658
6659<p>
6660Sets the metatable of the object at the top of the stack
6661as the metatable associated with name <code>tname</code>
6662in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6663
6664
6665
6666
6667
6668<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
6669<span class="apii">[-0, +0, <em>e</em>]</span>
6670<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
6671
6672<p>
6673This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
6674except that, when the test fails,
6675it returns <code>NULL</code> instead of throwing an error.
6676
6677
6678
6679
6680
6681<hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p>
6682<span class="apii">[-0, +1, <em>e</em>]</span>
6683<pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre>
6684
6685<p>
6686Converts any Lua value at the given index to a C&nbsp;string
6687in a reasonable format.
6688The resulting string is pushed onto the stack and also
6689returned by the function.
6690If <code>len</code> is not <code>NULL</code>,
6691the function also sets <code>*len</code> with the string length.
6692
6693
6694<p>
6695If the value has a metatable with a <code>"__tostring"</code> field,
6696then <code>luaL_tolstring</code> calls the corresponding metamethod
6697with the value as argument,
6698and uses the result of the call as its result.
6699
6700
6701
6702
6703
6704<hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p>
6705<span class="apii">[-0, +1, <em>e</em>]</span>
6706<pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg,
6707 int level);</pre>
6708
6709<p>
6710Creates and pushes a traceback of the stack <code>L1</code>.
6711If <code>msg</code> is not <code>NULL</code> it is appended
6712at the beginning of the traceback.
6713The <code>level</code> parameter tells at which level
6714to start the traceback.
6715
6716
6717
6718
6719
6720<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
6721<span class="apii">[-0, +0, &ndash;]</span>
6722<pre>const char *luaL_typename (lua_State *L, int index);</pre>
6723
6724<p>
6725Returns the name of the type of the value at the given index.
6726
6727
6728
6729
6730
6731<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
6732<span class="apii">[-0, +0, &ndash;]</span>
6733<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
6734
6735<p>
6736Releases reference <code>ref</code> from the table at index <code>t</code>
6737(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
6738The entry is removed from the table,
6739so that the referred object can be collected.
6740The reference <code>ref</code> is also freed to be used again.
6741
6742
6743<p>
6744If <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>,
6745<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
6746
6747
6748
6749
6750
6751<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p>
6752<span class="apii">[-0, +1, <em>e</em>]</span>
6753<pre>void luaL_where (lua_State *L, int lvl);</pre>
6754
6755<p>
6756Pushes onto the stack a string identifying the current position
6757of the control at level <code>lvl</code> in the call stack.
6758Typically this string has the following format:
6759
6760<pre>
6761 <em>chunkname</em>:<em>currentline</em>:
6762</pre><p>
6763Level&nbsp;0 is the running function,
6764level&nbsp;1 is the function that called the running function,
6765etc.
6766
6767
6768<p>
6769This function is used to build a prefix for error messages.
6770
6771
6772
6773
6774
6775
6776
6777<h1>6 &ndash; <a name="6">Standard Libraries</a></h1>
6778
6779<p>
6780The standard Lua libraries provide useful functions
6781that are implemented directly through the C&nbsp;API.
6782Some of these functions provide essential services to the language
6783(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
6784others provide access to "outside" services (e.g., I/O);
6785and others could be implemented in Lua itself,
6786but are quite useful or have critical performance requirements that
6787deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
6788
6789
6790<p>
6791All libraries are implemented through the official C&nbsp;API
6792and are provided as separate C&nbsp;modules.
6793Currently, Lua has the following standard libraries:
6794
6795<ul>
6796
6797<li>basic library (<a href="#6.1">&sect;6.1</a>);</li>
6798
6799<li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li>
6800
6801<li>package library (<a href="#6.3">&sect;6.3</a>);</li>
6802
6803<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
6804
6805<li>table manipulation (<a href="#6.5">&sect;6.5</a>);</li>
6806
6807<li>mathematical functions (<a href="#6.6">&sect;6.6</a>) (sin, log, etc.);</li>
6808
6809<li>bitwise operations (<a href="#6.7">&sect;6.7</a>);</li>
6810
6811<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
6812
6813<li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li>
6814
6815<li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li>
6816
6817</ul><p>
6818Except for the basic and the package libraries,
6819each library provides all its functions as fields of a global table
6820or as methods of its objects.
6821
6822
6823<p>
6824To have access to these libraries,
6825the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
6826which opens all standard libraries.
6827Alternatively,
6828the host program can open them individually by using
6829<a href="#luaL_requiref"><code>luaL_requiref</code></a> to call
6830<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
6831<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
6832<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
6833<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
6834<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
6835<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
6836<a name="pdf-luaopen_bit32"><code>luaopen_bit32</code></a> (for the bit library),
6837<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
6838<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
6839and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
6840These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
6841
6842
6843
6844<h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2>
6845
6846<p>
6847The basic library provides core functions to Lua.
6848If you do not include this library in your application,
6849you should check carefully whether you need to provide
6850implementations for some of its facilities.
6851
6852
6853<p>
6854<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
6855Issues an error when
6856the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
6857otherwise, returns all its arguments.
6858<code>message</code> is an error message;
6859when absent, it defaults to "assertion failed!"
6860
6861
6862
6863
6864<p>
6865<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
6866
6867
6868<p>
6869This function is a generic interface to the garbage collector.
6870It performs different functions according to its first argument, <code>opt</code>:
6871
6872<ul>
6873
6874<li><b>"<code>collect</code>": </b>
6875performs a full garbage-collection cycle.
6876This is the default option.
6877</li>
6878
6879<li><b>"<code>stop</code>": </b>
6880stops automatic execution of the garbage collector.
6881The collector will run only when explicitly invoked,
6882until a call to restart it.
6883</li>
6884
6885<li><b>"<code>restart</code>": </b>
6886restarts automatic execution of the garbage collector.
6887</li>
6888
6889<li><b>"<code>count</code>": </b>
6890returns the total memory in use by Lua (in Kbytes) and
6891a second value with the total memory in bytes modulo 1024.
6892The first value has a fractional part,
6893so the following equality is always true:
6894
6895<pre>
6896 k, b = collectgarbage("count")
6897 assert(k*1024 == math.floor(k)*1024 + b)
6898</pre><p>
6899(The second result is useful when Lua is compiled
6900with a non floating-point type for numbers.)
6901</li>
6902
6903<li><b>"<code>step</code>": </b>
6904performs a garbage-collection step.
6905The step "size" is controlled by <code>arg</code>
6906(larger values mean more steps) in a non-specified way.
6907If you want to control the step size
6908you must experimentally tune the value of <code>arg</code>.
6909Returns <b>true</b> if the step finished a collection cycle.
6910</li>
6911
6912<li><b>"<code>setpause</code>": </b>
6913sets <code>arg</code> as the new value for the <em>pause</em> of
6914the collector (see <a href="#2.5">&sect;2.5</a>).
6915Returns the previous value for <em>pause</em>.
6916</li>
6917
6918<li><b>"<code>setstepmul</code>": </b>
6919sets <code>arg</code> as the new value for the <em>step multiplier</em> of
6920the collector (see <a href="#2.5">&sect;2.5</a>).
6921Returns the previous value for <em>step</em>.
6922</li>
6923
6924<li><b>"<code>isrunning</code>": </b>
6925returns a boolean that tells whether the collector is running
6926(i.e., not stopped).
6927</li>
6928
6929<li><b>"<code>generational</code>": </b>
6930changes the collector to generational mode.
6931This is an experimental feature (see <a href="#2.5">&sect;2.5</a>).
6932</li>
6933
6934<li><b>"<code>incremental</code>": </b>
6935changes the collector to incremental mode.
6936This is the default mode.
6937</li>
6938
6939</ul>
6940
6941
6942
6943<p>
6944<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
6945Opens the named file and executes its contents as a Lua chunk.
6946When called without arguments,
6947<code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
6948Returns all values returned by the chunk.
6949In case of errors, <code>dofile</code> propagates the error
6950to its caller (that is, <code>dofile</code> does not run in protected mode).
6951
6952
6953
6954
6955<p>
6956<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
6957Terminates the last protected function called
6958and returns <code>message</code> as the error message.
6959Function <code>error</code> never returns.
6960
6961
6962<p>
6963Usually, <code>error</code> adds some information about the error position
6964at the beginning of the message, if the message is a string.
6965The <code>level</code> argument specifies how to get the error position.
6966With level&nbsp;1 (the default), the error position is where the
6967<code>error</code> function was called.
6968Level&nbsp;2 points the error to where the function
6969that called <code>error</code> was called; and so on.
6970Passing a level&nbsp;0 avoids the addition of error position information
6971to the message.
6972
6973
6974
6975
6976<p>
6977<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
6978A global variable (not a function) that
6979holds the global environment (see <a href="#2.2">&sect;2.2</a>).
6980Lua itself does not use this variable;
6981changing its value does not affect any environment,
6982nor vice-versa.
6983
6984
6985
6986
6987<p>
6988<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
6989
6990
6991<p>
6992If <code>object</code> does not have a metatable, returns <b>nil</b>.
6993Otherwise,
6994if the object's metatable has a <code>"__metatable"</code> field,
6995returns the associated value.
6996Otherwise, returns the metatable of the given object.
6997
6998
6999
7000
7001<p>
7002<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7003
7004
7005<p>
7006If <code>t</code> has a metamethod <code>__ipairs</code>,
7007calls it with <code>t</code> as argument and returns the first three
7008results from the call.
7009
7010
7011<p>
7012Otherwise,
7013returns three values: an iterator function, the table <code>t</code>, and 0,
7014so that the construction
7015
7016<pre>
7017 for i,v in ipairs(t) do <em>body</em> end
7018</pre><p>
7019will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7020up to the first integer key absent from the table.
7021
7022
7023
7024
7025<p>
7026<hr><h3><a name="pdf-load"><code>load (ld [, source [, mode [, env]]])</code></a></h3>
7027
7028
7029<p>
7030Loads a chunk.
7031
7032
7033<p>
7034If <code>ld</code> is a string, the chunk is this string.
7035If <code>ld</code> is a function,
7036<code>load</code> calls it repeatedly to get the chunk pieces.
7037Each call to <code>ld</code> must return a string that concatenates
7038with previous results.
7039A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
7040
7041
7042<p>
7043If there are no syntactic errors,
7044returns the compiled chunk as a function;
7045otherwise, returns <b>nil</b> plus the error message.
7046
7047
7048<p>
7049If the resulting function has upvalues,
7050the first upvalue is set to the value of <code>env</code>,
7051if that parameter is given,
7052or to the value of the global environment.
7053(When you load a main chunk,
7054the resulting function will always have exactly one upvalue,
7055the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
7056When you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7057the resulting function can have arbitrary upvalues.)
7058
7059
7060<p>
7061<code>source</code> is used as the source of the chunk for error messages
7062and debug information (see <a href="#4.9">&sect;4.9</a>).
7063When absent,
7064it defaults to <code>ld</code>, if <code>ld</code> is a string,
7065or to "<code>=(load)</code>" otherwise.
7066
7067
7068<p>
7069The string <code>mode</code> controls whether the chunk can be text or binary
7070(that is, a precompiled chunk).
7071It may be the string "<code>b</code>" (only binary chunks),
7072"<code>t</code>" (only text chunks),
7073or "<code>bt</code>" (both binary and text).
7074The default is "<code>bt</code>".
7075
7076
7077
7078
7079<p>
7080<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
7081
7082
7083<p>
7084Similar to <a href="#pdf-load"><code>load</code></a>,
7085but gets the chunk from file <code>filename</code>
7086or from the standard input,
7087if no file name is given.
7088
7089
7090
7091
7092<p>
7093<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
7094
7095
7096<p>
7097Allows a program to traverse all fields of a table.
7098Its first argument is a table and its second argument
7099is an index in this table.
7100<code>next</code> returns the next index of the table
7101and its associated value.
7102When called with <b>nil</b> as its second argument,
7103<code>next</code> returns an initial index
7104and its associated value.
7105When called with the last index,
7106or with <b>nil</b> in an empty table,
7107<code>next</code> returns <b>nil</b>.
7108If the second argument is absent, then it is interpreted as <b>nil</b>.
7109In particular,
7110you can use <code>next(t)</code> to check whether a table is empty.
7111
7112
7113<p>
7114The order in which the indices are enumerated is not specified,
7115<em>even for numeric indices</em>.
7116(To traverse a table in numeric order,
7117use a numerical <b>for</b>.)
7118
7119
7120<p>
7121The behavior of <code>next</code> is undefined if,
7122during the traversal,
7123you assign any value to a non-existent field in the table.
7124You may however modify existing fields.
7125In particular, you may clear existing fields.
7126
7127
7128
7129
7130<p>
7131<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
7132
7133
7134<p>
7135If <code>t</code> has a metamethod <code>__pairs</code>,
7136calls it with <code>t</code> as argument and returns the first three
7137results from the call.
7138
7139
7140<p>
7141Otherwise,
7142returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
7143so that the construction
7144
7145<pre>
7146 for k,v in pairs(t) do <em>body</em> end
7147</pre><p>
7148will iterate over all key&ndash;value pairs of table <code>t</code>.
7149
7150
7151<p>
7152See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
7153the table during its traversal.
7154
7155
7156
7157
7158<p>
7159<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3>
7160
7161
7162<p>
7163Calls function <code>f</code> with
7164the given arguments in <em>protected mode</em>.
7165This means that any error inside&nbsp;<code>f</code> is not propagated;
7166instead, <code>pcall</code> catches the error
7167and returns a status code.
7168Its first result is the status code (a boolean),
7169which is true if the call succeeds without errors.
7170In such case, <code>pcall</code> also returns all results from the call,
7171after this first result.
7172In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
7173
7174
7175
7176
7177<p>
7178<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
7179Receives any number of arguments
7180and prints their values to <code>stdout</code>,
7181using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string.
7182<code>print</code> is not intended for formatted output,
7183but only as a quick way to show a value,
7184for instance for debugging.
7185For complete control over the output,
7186use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
7187
7188
7189
7190
7191<p>
7192<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
7193Checks whether <code>v1</code> is equal to <code>v2</code>,
7194without invoking any metamethod.
7195Returns a boolean.
7196
7197
7198
7199
7200<p>
7201<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
7202Gets the real value of <code>table[index]</code>,
7203without invoking any metamethod.
7204<code>table</code> must be a table;
7205<code>index</code> may be any value.
7206
7207
7208
7209
7210<p>
7211<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
7212Returns the length of the object <code>v</code>,
7213which must be a table or a string,
7214without invoking any metamethod.
7215Returns an integer number.
7216
7217
7218
7219
7220<p>
7221<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
7222Sets the real value of <code>table[index]</code> to <code>value</code>,
7223without invoking any metamethod.
7224<code>table</code> must be a table,
7225<code>index</code> any value different from <b>nil</b> and NaN,
7226and <code>value</code> any Lua value.
7227
7228
7229<p>
7230This function returns <code>table</code>.
7231
7232
7233
7234
7235<p>
7236<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
7237
7238
7239<p>
7240If <code>index</code> is a number,
7241returns all arguments after argument number <code>index</code>;
7242a negative number indexes from the end (-1 is the last argument).
7243Otherwise, <code>index</code> must be the string <code>"#"</code>,
7244and <code>select</code> returns the total number of extra arguments it received.
7245
7246
7247
7248
7249<p>
7250<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
7251
7252
7253<p>
7254Sets the metatable for the given table.
7255(You cannot change the metatable of other types from Lua, only from&nbsp;C.)
7256If <code>metatable</code> is <b>nil</b>,
7257removes the metatable of the given table.
7258If the original metatable has a <code>"__metatable"</code> field,
7259raises an error.
7260
7261
7262<p>
7263This function returns <code>table</code>.
7264
7265
7266
7267
7268<p>
7269<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
7270
7271
7272<p>
7273When called with no <code>base</code>,
7274<code>tonumber</code> tries to convert its argument to a number.
7275If the argument is already a number or
7276a string convertible to a number (see <a href="#3.4.2">&sect;3.4.2</a>),
7277then <code>tonumber</code> returns this number;
7278otherwise, it returns <b>nil</b>.
7279
7280
7281<p>
7282When called with <code>base</code>,
7283then <code>e</code> should be a string to be interpreted as
7284an integer numeral in that base.
7285The base may be any integer between 2 and 36, inclusive.
7286In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
7287represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
7288with '<code>Z</code>' representing 35.
7289If the string <code>e</code> is not a valid numeral in the given base,
7290the function returns <b>nil</b>.
7291
7292
7293
7294
7295<p>
7296<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
7297Receives a value of any type and
7298converts it to a string in a reasonable format.
7299(For complete control of how numbers are converted,
7300use <a href="#pdf-string.format"><code>string.format</code></a>.)
7301
7302
7303<p>
7304If the metatable of <code>v</code> has a <code>"__tostring"</code> field,
7305then <code>tostring</code> calls the corresponding value
7306with <code>v</code> as argument,
7307and uses the result of the call as its result.
7308
7309
7310
7311
7312<p>
7313<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
7314Returns the type of its only argument, coded as a string.
7315The possible results of this function are
7316"<code>nil</code>" (a string, not the value <b>nil</b>),
7317"<code>number</code>",
7318"<code>string</code>",
7319"<code>boolean</code>",
7320"<code>table</code>",
7321"<code>function</code>",
7322"<code>thread</code>",
7323and "<code>userdata</code>".
7324
7325
7326
7327
7328<p>
7329<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
7330A global variable (not a function) that
7331holds a string containing the current interpreter version.
7332The current contents of this variable is "<code>Lua 5.2</code>".
7333
7334
7335
7336
7337<p>
7338<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3>
7339
7340
7341<p>
7342This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
7343except that it sets a new message handler <code>msgh</code>.
7344
7345
7346
7347
7348
7349
7350
7351<h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2>
7352
7353<p>
7354The operations related to coroutines comprise a sub-library of
7355the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
7356See <a href="#2.6">&sect;2.6</a> for a general description of coroutines.
7357
7358
7359<p>
7360<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
7361
7362
7363<p>
7364Creates a new coroutine, with body <code>f</code>.
7365<code>f</code> must be a Lua function.
7366Returns this new coroutine,
7367an object with type <code>"thread"</code>.
7368
7369
7370
7371
7372<p>
7373<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
7374
7375
7376<p>
7377Starts or continues the execution of coroutine <code>co</code>.
7378The first time you resume a coroutine,
7379it starts running its body.
7380The values <code>val1</code>, ... are passed
7381as the arguments to the body function.
7382If the coroutine has yielded,
7383<code>resume</code> restarts it;
7384the values <code>val1</code>, ... are passed
7385as the results from the yield.
7386
7387
7388<p>
7389If the coroutine runs without any errors,
7390<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
7391(if the coroutine yields) or any values returned by the body function
7392(if the coroutine terminates).
7393If there is any error,
7394<code>resume</code> returns <b>false</b> plus the error message.
7395
7396
7397
7398
7399<p>
7400<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
7401
7402
7403<p>
7404Returns the running coroutine plus a boolean,
7405true when the running coroutine is the main one.
7406
7407
7408
7409
7410<p>
7411<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
7412
7413
7414<p>
7415Returns the status of coroutine <code>co</code>, as a string:
7416<code>"running"</code>,
7417if the coroutine is running (that is, it called <code>status</code>);
7418<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
7419or if it has not started running yet;
7420<code>"normal"</code> if the coroutine is active but not running
7421(that is, it has resumed another coroutine);
7422and <code>"dead"</code> if the coroutine has finished its body function,
7423or if it has stopped with an error.
7424
7425
7426
7427
7428<p>
7429<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
7430
7431
7432<p>
7433Creates a new coroutine, with body <code>f</code>.
7434<code>f</code> must be a Lua function.
7435Returns a function that resumes the coroutine each time it is called.
7436Any arguments passed to the function behave as the
7437extra arguments to <code>resume</code>.
7438Returns the same values returned by <code>resume</code>,
7439except the first boolean.
7440In case of error, propagates the error.
7441
7442
7443
7444
7445<p>
7446<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
7447
7448
7449<p>
7450Suspends the execution of the calling coroutine.
7451Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
7452
7453
7454
7455
7456
7457
7458
7459<h2>6.3 &ndash; <a name="6.3">Modules</a></h2>
7460
7461<p>
7462The package library provides basic
7463facilities for loading modules in Lua.
7464It exports one function directly in the global environment:
7465<a href="#pdf-require"><code>require</code></a>.
7466Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
7467
7468
7469<p>
7470<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
7471
7472
7473<p>
7474Loads the given module.
7475The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
7476to determine whether <code>modname</code> is already loaded.
7477If it is, then <code>require</code> returns the value stored
7478at <code>package.loaded[modname]</code>.
7479Otherwise, it tries to find a <em>loader</em> for the module.
7480
7481
7482<p>
7483To find a loader,
7484<code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence.
7485By changing this sequence,
7486we can change how <code>require</code> looks for a module.
7487The following explanation is based on the default configuration
7488for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
7489
7490
7491<p>
7492First <code>require</code> queries <code>package.preload[modname]</code>.
7493If it has a value,
7494this value (which should be a function) is the loader.
7495Otherwise <code>require</code> searches for a Lua loader using the
7496path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
7497If that also fails, it searches for a C&nbsp;loader using the
7498path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7499If that also fails,
7500it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
7501
7502
7503<p>
7504Once a loader is found,
7505<code>require</code> calls the loader with two arguments:
7506<code>modname</code> and an extra value dependent on how it got the loader.
7507(If the loader came from a file,
7508this extra value is the file name.)
7509If the loader returns any non-nil value,
7510<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
7511If the loader does not return a non-nil value and
7512has not assigned any value to <code>package.loaded[modname]</code>,
7513then <code>require</code> assigns <b>true</b> to this entry.
7514In any case, <code>require</code> returns the
7515final value of <code>package.loaded[modname]</code>.
7516
7517
7518<p>
7519If there is any error loading or running the module,
7520or if it cannot find any loader for the module,
7521then <code>require</code> raises an error.
7522
7523
7524
7525
7526<p>
7527<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
7528
7529
7530<p>
7531A string describing some compile-time configurations for packages.
7532This string is a sequence of lines:
7533
7534<ul>
7535
7536<li>The first line is the directory separator string.
7537Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
7538
7539<li>The second line is the character that separates templates in a path.
7540Default is '<code>;</code>'.</li>
7541
7542<li>The third line is the string that marks the
7543substitution points in a template.
7544Default is '<code>?</code>'.</li>
7545
7546<li>The fourth line is a string that, in a path in Windows,
7547is replaced by the executable's directory.
7548Default is '<code>!</code>'.</li>
7549
7550<li>The fifth line is a mark to ignore all text before it
7551when building the <code>luaopen_</code> function name.
7552Default is '<code>-</code>'.</li>
7553
7554</ul>
7555
7556
7557
7558<p>
7559<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
7560
7561
7562<p>
7563The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
7564
7565
7566<p>
7567Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
7568it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7569using the environment variable <a name="pdf-LUA_CPATH_5_2"><code>LUA_CPATH_5_2</code></a>
7570or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
7571or a default path defined in <code>luaconf.h</code>.
7572
7573
7574
7575
7576<p>
7577<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
7578
7579
7580<p>
7581A table used by <a href="#pdf-require"><code>require</code></a> to control which
7582modules are already loaded.
7583When you require a module <code>modname</code> and
7584<code>package.loaded[modname]</code> is not false,
7585<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
7586
7587
7588<p>
7589This variable is only a reference to the real table;
7590assignments to this variable do not change the
7591table used by <a href="#pdf-require"><code>require</code></a>.
7592
7593
7594
7595
7596<p>
7597<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
7598
7599
7600<p>
7601Dynamically links the host program with the C&nbsp;library <code>libname</code>.
7602
7603
7604<p>
7605If <code>funcname</code> is "<code>*</code>",
7606then it only links with the library,
7607making the symbols exported by the library
7608available to other dynamically linked libraries.
7609Otherwise,
7610it looks for a function <code>funcname</code> inside the library
7611and returns this function as a C&nbsp;function.
7612So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype
7613(see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
7614
7615
7616<p>
7617This is a low-level function.
7618It completely bypasses the package and module system.
7619Unlike <a href="#pdf-require"><code>require</code></a>,
7620it does not perform any path searching and
7621does not automatically adds extensions.
7622<code>libname</code> must be the complete file name of the C&nbsp;library,
7623including if necessary a path and an extension.
7624<code>funcname</code> must be the exact name exported by the C&nbsp;library
7625(which may depend on the C&nbsp;compiler and linker used).
7626
7627
7628<p>
7629This function is not supported by Standard&nbsp;C.
7630As such, it is only available on some platforms
7631(Windows, Linux, Mac OS X, Solaris, BSD,
7632plus other Unix systems that support the <code>dlfcn</code> standard).
7633
7634
7635
7636
7637<p>
7638<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
7639
7640
7641<p>
7642The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
7643
7644
7645<p>
7646At start-up, Lua initializes this variable with
7647the value of the environment variable <a name="pdf-LUA_PATH_5_2"><code>LUA_PATH_5_2</code></a> or
7648the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
7649with a default path defined in <code>luaconf.h</code>,
7650if those environment variables are not defined.
7651Any "<code>;;</code>" in the value of the environment variable
7652is replaced by the default path.
7653
7654
7655
7656
7657<p>
7658<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
7659
7660
7661<p>
7662A table to store loaders for specific modules
7663(see <a href="#pdf-require"><code>require</code></a>).
7664
7665
7666<p>
7667This variable is only a reference to the real table;
7668assignments to this variable do not change the
7669table used by <a href="#pdf-require"><code>require</code></a>.
7670
7671
7672
7673
7674<p>
7675<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
7676
7677
7678<p>
7679A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
7680
7681
7682<p>
7683Each entry in this table is a <em>searcher function</em>.
7684When looking for a module,
7685<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
7686with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
7687sole parameter.
7688The function can return another function (the module <em>loader</em>)
7689plus an extra value that will be passed to that loader,
7690or a string explaining why it did not find that module
7691(or <b>nil</b> if it has nothing to say).
7692
7693
7694<p>
7695Lua initializes this table with four searcher functions.
7696
7697
7698<p>
7699The first searcher simply looks for a loader in the
7700<a href="#pdf-package.preload"><code>package.preload</code></a> table.
7701
7702
7703<p>
7704The second searcher looks for a loader as a Lua library,
7705using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
7706The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7707
7708
7709<p>
7710The third searcher looks for a loader as a C&nbsp;library,
7711using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7712Again,
7713the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7714For instance,
7715if the C&nbsp;path is the string
7716
7717<pre>
7718 "./?.so;./?.dll;/usr/local/?/init.so"
7719</pre><p>
7720the searcher for module <code>foo</code>
7721will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
7722and <code>/usr/local/foo/init.so</code>, in that order.
7723Once it finds a C&nbsp;library,
7724this searcher first uses a dynamic link facility to link the
7725application with the library.
7726Then it tries to find a C&nbsp;function inside the library to
7727be used as the loader.
7728The name of this C&nbsp;function is the string "<code>luaopen_</code>"
7729concatenated with a copy of the module name where each dot
7730is replaced by an underscore.
7731Moreover, if the module name has a hyphen,
7732its prefix up to (and including) the first hyphen is removed.
7733For instance, if the module name is <code>a.v1-b.c</code>,
7734the function name will be <code>luaopen_b_c</code>.
7735
7736
7737<p>
7738The fourth searcher tries an <em>all-in-one loader</em>.
7739It searches the C&nbsp;path for a library for
7740the root name of the given module.
7741For instance, when requiring <code>a.b.c</code>,
7742it will search for a C&nbsp;library for <code>a</code>.
7743If found, it looks into it for an open function for
7744the submodule;
7745in our example, that would be <code>luaopen_a_b_c</code>.
7746With this facility, a package can pack several C&nbsp;submodules
7747into one single library,
7748with each submodule keeping its original open function.
7749
7750
7751<p>
7752All searchers except the first one (preload) return as the extra value
7753the file name where the module was found,
7754as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7755The first searcher returns no extra value.
7756
7757
7758
7759
7760<p>
7761<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
7762
7763
7764<p>
7765Searches for the given <code>name</code> in the given <code>path</code>.
7766
7767
7768<p>
7769A path is a string containing a sequence of
7770<em>templates</em> separated by semicolons.
7771For each template,
7772the function replaces each interrogation mark (if any)
7773in the template with a copy of <code>name</code>
7774wherein all occurrences of <code>sep</code>
7775(a dot, by default)
7776were replaced by <code>rep</code>
7777(the system's directory separator, by default),
7778and then tries to open the resulting file name.
7779
7780
7781<p>
7782For instance, if the path is the string
7783
7784<pre>
7785 "./?.lua;./?.lc;/usr/local/?/init.lua"
7786</pre><p>
7787the search for the name <code>foo.a</code>
7788will try to open the files
7789<code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and
7790<code>/usr/local/foo/a/init.lua</code>, in that order.
7791
7792
7793<p>
7794Returns the resulting name of the first file that it can
7795open in read mode (after closing the file),
7796or <b>nil</b> plus an error message if none succeeds.
7797(This error message lists all file names it tried to open.)
7798
7799
7800
7801
7802
7803
7804
7805<h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2>
7806
7807<p>
7808This library provides generic functions for string manipulation,
7809such as finding and extracting substrings, and pattern matching.
7810When indexing a string in Lua, the first character is at position&nbsp;1
7811(not at&nbsp;0, as in C).
7812Indices are allowed to be negative and are interpreted as indexing backwards,
7813from the end of the string.
7814Thus, the last character is at position -1, and so on.
7815
7816
7817<p>
7818The string library provides all its functions inside the table
7819<a name="pdf-string"><code>string</code></a>.
7820It also sets a metatable for strings
7821where the <code>__index</code> field points to the <code>string</code> table.
7822Therefore, you can use the string functions in object-oriented style.
7823For instance, <code>string.byte(s,i)</code>
7824can be written as <code>s:byte(i)</code>.
7825
7826
7827<p>
7828The string library assumes one-byte character encodings.
7829
7830
7831<p>
7832<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
7833Returns the internal numerical codes of the characters <code>s[i]</code>,
7834<code>s[i+1]</code>, ..., <code>s[j]</code>.
7835The default value for <code>i</code> is&nbsp;1;
7836the default value for <code>j</code> is&nbsp;<code>i</code>.
7837These indices are corrected
7838following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
7839
7840
7841<p>
7842Numerical codes are not necessarily portable across platforms.
7843
7844
7845
7846
7847<p>
7848<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
7849Receives zero or more integers.
7850Returns a string with length equal to the number of arguments,
7851in which each character has the internal numerical code equal
7852to its corresponding argument.
7853
7854
7855<p>
7856Numerical codes are not necessarily portable across platforms.
7857
7858
7859
7860
7861<p>
7862<hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
7863
7864
7865<p>
7866Returns a string containing a binary representation of the given function,
7867so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
7868a copy of the function (but with new upvalues).
7869
7870
7871
7872
7873<p>
7874<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
7875
7876
7877<p>
7878Looks for the first match of
7879<code>pattern</code> in the string <code>s</code>.
7880If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
7881where this occurrence starts and ends;
7882otherwise, it returns <b>nil</b>.
7883A third, optional numerical argument <code>init</code> specifies
7884where to start the search;
7885its default value is&nbsp;1 and can be negative.
7886A value of <b>true</b> as a fourth, optional argument <code>plain</code>
7887turns off the pattern matching facilities,
7888so the function does a plain "find substring" operation,
7889with no characters in <code>pattern</code> being considered magic.
7890Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
7891
7892
7893<p>
7894If the pattern has captures,
7895then in a successful match
7896the captured values are also returned,
7897after the two indices.
7898
7899
7900
7901
7902<p>
7903<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
7904
7905
7906<p>
7907Returns a formatted version of its variable number of arguments
7908following the description given in its first argument (which must be a string).
7909The format string follows the same rules as the ANSI&nbsp;C function <code>sprintf</code>.
7910The only differences are that the options/modifiers
7911<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
7912and <code>p</code> are not supported
7913and that there is an extra option, <code>q</code>.
7914The <code>q</code> option formats a string between double quotes,
7915using escape sequences when necessary to ensure that
7916it can safely be read back by the Lua interpreter.
7917For instance, the call
7918
7919<pre>
7920 string.format('%q', 'a string with "quotes" and \n new line')
7921</pre><p>
7922may produce the string:
7923
7924<pre>
7925 "a string with \"quotes\" and \
7926 new line"
7927</pre>
7928
7929<p>
7930Options
7931<code>A</code> and <code>a</code> (when available),
7932<code>E</code>, <code>e</code>, <code>f</code>,
7933<code>G</code>, and <code>g</code> all expect a number as argument.
7934Options <code>c</code>, <code>d</code>,
7935<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
7936also expect a number,
7937but the range of that number may be limited by
7938the underlying C&nbsp;implementation.
7939For options <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>,
7940the number cannot be negative.
7941Option <code>q</code> expects a string;
7942option <code>s</code> expects a string without embedded zeros.
7943If the argument to option <code>s</code> is not a string,
7944it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
7945
7946
7947
7948
7949<p>
7950<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
7951Returns an iterator function that,
7952each time it is called,
7953returns the next captures from <code>pattern</code> over the string <code>s</code>.
7954If <code>pattern</code> specifies no captures,
7955then the whole match is produced in each call.
7956
7957
7958<p>
7959As an example, the following loop
7960will iterate over all the words from string <code>s</code>,
7961printing one per line:
7962
7963<pre>
7964 s = "hello world from Lua"
7965 for w in string.gmatch(s, "%a+") do
7966 print(w)
7967 end
7968</pre><p>
7969The next example collects all pairs <code>key=value</code> from the
7970given string into a table:
7971
7972<pre>
7973 t = {}
7974 s = "from=world, to=Lua"
7975 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
7976 t[k] = v
7977 end
7978</pre>
7979
7980<p>
7981For this function, a caret '<code>^</code>' at the start of a pattern does not
7982work as an anchor, as this would prevent the iteration.
7983
7984
7985
7986
7987<p>
7988<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
7989Returns a copy of <code>s</code>
7990in which all (or the first <code>n</code>, if given)
7991occurrences of the <code>pattern</code> have been
7992replaced by a replacement string specified by <code>repl</code>,
7993which can be a string, a table, or a function.
7994<code>gsub</code> also returns, as its second value,
7995the total number of matches that occurred.
7996The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
7997
7998
7999<p>
8000If <code>repl</code> is a string, then its value is used for replacement.
8001The character&nbsp;<code>%</code> works as an escape character:
8002any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
8003with <em>d</em> between 1 and 9,
8004stands for the value of the <em>d</em>-th captured substring.
8005The sequence <code>%0</code> stands for the whole match.
8006The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
8007
8008
8009<p>
8010If <code>repl</code> is a table, then the table is queried for every match,
8011using the first capture as the key.
8012
8013
8014<p>
8015If <code>repl</code> is a function, then this function is called every time a
8016match occurs, with all captured substrings passed as arguments,
8017in order.
8018
8019
8020<p>
8021In any case,
8022if the pattern specifies no captures,
8023then it behaves as if the whole pattern was inside a capture.
8024
8025
8026<p>
8027If the value returned by the table query or by the function call
8028is a string or a number,
8029then it is used as the replacement string;
8030otherwise, if it is <b>false</b> or <b>nil</b>,
8031then there is no replacement
8032(that is, the original match is kept in the string).
8033
8034
8035<p>
8036Here are some examples:
8037
8038<pre>
8039 x = string.gsub("hello world", "(%w+)", "%1 %1")
8040 --&gt; x="hello hello world world"
8041
8042 x = string.gsub("hello world", "%w+", "%0 %0", 1)
8043 --&gt; x="hello hello world"
8044
8045 x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
8046 --&gt; x="world hello Lua from"
8047
8048 x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
8049 --&gt; x="home = /home/roberto, user = roberto"
8050
8051 x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
8052 return load(s)()
8053 end)
8054 --&gt; x="4+5 = 9"
8055
8056 local t = {name="lua", version="5.2"}
8057 x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8058 --&gt; x="lua-5.2.tar.gz"
8059</pre>
8060
8061
8062
8063<p>
8064<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
8065Receives a string and returns its length.
8066The empty string <code>""</code> has length 0.
8067Embedded zeros are counted,
8068so <code>"a\000bc\000"</code> has length 5.
8069
8070
8071
8072
8073<p>
8074<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
8075Receives a string and returns a copy of this string with all
8076uppercase letters changed to lowercase.
8077All other characters are left unchanged.
8078The definition of what an uppercase letter is depends on the current locale.
8079
8080
8081
8082
8083<p>
8084<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
8085Looks for the first <em>match</em> of
8086<code>pattern</code> in the string <code>s</code>.
8087If it finds one, then <code>match</code> returns
8088the captures from the pattern;
8089otherwise it returns <b>nil</b>.
8090If <code>pattern</code> specifies no captures,
8091then the whole match is returned.
8092A third, optional numerical argument <code>init</code> specifies
8093where to start the search;
8094its default value is&nbsp;1 and can be negative.
8095
8096
8097
8098
8099<p>
8100<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
8101Returns a string that is the concatenation of <code>n</code> copies of
8102the string <code>s</code> separated by the string <code>sep</code>.
8103The default value for <code>sep</code> is the empty string
8104(that is, no separator).
8105
8106
8107
8108
8109<p>
8110<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
8111Returns a string that is the string <code>s</code> reversed.
8112
8113
8114
8115
8116<p>
8117<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
8118Returns the substring of <code>s</code> that
8119starts at <code>i</code> and continues until <code>j</code>;
8120<code>i</code> and <code>j</code> can be negative.
8121If <code>j</code> is absent, then it is assumed to be equal to -1
8122(which is the same as the string length).
8123In particular,
8124the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
8125with length <code>j</code>,
8126and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
8127with length <code>i</code>.
8128
8129
8130<p>
8131If, after the translation of negative indices,
8132<code>i</code> is less than 1,
8133it is corrected to 1.
8134If <code>j</code> is greater than the string length,
8135it is corrected to that length.
8136If, after these corrections,
8137<code>i</code> is greater than <code>j</code>,
8138the function returns the empty string.
8139
8140
8141
8142
8143<p>
8144<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
8145Receives a string and returns a copy of this string with all
8146lowercase letters changed to uppercase.
8147All other characters are left unchanged.
8148The definition of what a lowercase letter is depends on the current locale.
8149
8150
8151
8152<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
8153
8154
8155<h4>Character Class:</h4><p>
8156A <em>character class</em> is used to represent a set of characters.
8157The following combinations are allowed in describing a character class:
8158
8159<ul>
8160
8161<li><b><em>x</em>: </b>
8162(where <em>x</em> is not one of the <em>magic characters</em>
8163<code>^$()%.[]*+-?</code>)
8164represents the character <em>x</em> itself.
8165</li>
8166
8167<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
8168
8169<li><b><code>%a</code>: </b> represents all letters.</li>
8170
8171<li><b><code>%c</code>: </b> represents all control characters.</li>
8172
8173<li><b><code>%d</code>: </b> represents all digits.</li>
8174
8175<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
8176
8177<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
8178
8179<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
8180
8181<li><b><code>%s</code>: </b> represents all space characters.</li>
8182
8183<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
8184
8185<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
8186
8187<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
8188
8189<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
8190represents the character <em>x</em>.
8191This is the standard way to escape the magic characters.
8192Any punctuation character (even the non magic)
8193can be preceded by a '<code>%</code>'
8194when used to represent itself in a pattern.
8195</li>
8196
8197<li><b><code>[<em>set</em>]</code>: </b>
8198represents the class which is the union of all
8199characters in <em>set</em>.
8200A range of characters can be specified by
8201separating the end characters of the range,
8202in ascending order, with a '<code>-</code>',
8203All classes <code>%</code><em>x</em> described above can also be used as
8204components in <em>set</em>.
8205All other characters in <em>set</em> represent themselves.
8206For example, <code>[%w_]</code> (or <code>[_%w]</code>)
8207represents all alphanumeric characters plus the underscore,
8208<code>[0-7]</code> represents the octal digits,
8209and <code>[0-7%l%-]</code> represents the octal digits plus
8210the lowercase letters plus the '<code>-</code>' character.
8211
8212
8213<p>
8214The interaction between ranges and classes is not defined.
8215Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
8216have no meaning.
8217</li>
8218
8219<li><b><code>[^<em>set</em>]</code>: </b>
8220represents the complement of <em>set</em>,
8221where <em>set</em> is interpreted as above.
8222</li>
8223
8224</ul><p>
8225For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
8226the corresponding uppercase letter represents the complement of the class.
8227For instance, <code>%S</code> represents all non-space characters.
8228
8229
8230<p>
8231The definitions of letter, space, and other character groups
8232depend on the current locale.
8233In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
8234
8235
8236
8237
8238
8239<h4>Pattern Item:</h4><p>
8240A <em>pattern item</em> can be
8241
8242<ul>
8243
8244<li>
8245a single character class,
8246which matches any single character in the class;
8247</li>
8248
8249<li>
8250a single character class followed by '<code>*</code>',
8251which matches 0 or more repetitions of characters in the class.
8252These repetition items will always match the longest possible sequence;
8253</li>
8254
8255<li>
8256a single character class followed by '<code>+</code>',
8257which matches 1 or more repetitions of characters in the class.
8258These repetition items will always match the longest possible sequence;
8259</li>
8260
8261<li>
8262a single character class followed by '<code>-</code>',
8263which also matches 0 or more repetitions of characters in the class.
8264Unlike '<code>*</code>',
8265these repetition items will always match the shortest possible sequence;
8266</li>
8267
8268<li>
8269a single character class followed by '<code>?</code>',
8270which matches 0 or 1 occurrence of a character in the class;
8271</li>
8272
8273<li>
8274<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
8275such item matches a substring equal to the <em>n</em>-th captured string
8276(see below);
8277</li>
8278
8279<li>
8280<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
8281such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
8282and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
8283This means that, if one reads the string from left to right,
8284counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
8285the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
8286For instance, the item <code>%b()</code> matches expressions with
8287balanced parentheses.
8288</li>
8289
8290<li>
8291<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
8292such item matches an empty string at any position such that
8293the next character belongs to <em>set</em>
8294and the previous character does not belong to <em>set</em>.
8295The set <em>set</em> is interpreted as previously described.
8296The beginning and the end of the subject are handled as if
8297they were the character '<code>\0</code>'.
8298</li>
8299
8300</ul>
8301
8302
8303
8304
8305<h4>Pattern:</h4><p>
8306A <em>pattern</em> is a sequence of pattern items.
8307A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
8308beginning of the subject string.
8309A '<code>$</code>' at the end of a pattern anchors the match at the
8310end of the subject string.
8311At other positions,
8312'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
8313
8314
8315
8316
8317
8318<h4>Captures:</h4><p>
8319A pattern can contain sub-patterns enclosed in parentheses;
8320they describe <em>captures</em>.
8321When a match succeeds, the substrings of the subject string
8322that match captures are stored (<em>captured</em>) for future use.
8323Captures are numbered according to their left parentheses.
8324For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
8325the part of the string matching <code>"a*(.)%w(%s*)"</code> is
8326stored as the first capture (and therefore has number&nbsp;1);
8327the character matching "<code>.</code>" is captured with number&nbsp;2,
8328and the part matching "<code>%s*</code>" has number&nbsp;3.
8329
8330
8331<p>
8332As a special case, the empty capture <code>()</code> captures
8333the current string position (a number).
8334For instance, if we apply the pattern <code>"()aa()"</code> on the
8335string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347<h2>6.5 &ndash; <a name="6.5">Table Manipulation</a></h2>
8348
8349<p>
8350This library provides generic functions for table manipulation.
8351It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
8352
8353
8354<p>
8355Remember that, whenever an operation needs the length of a table,
8356the table should be a proper sequence
8357or have a <code>__len</code> metamethod (see <a href="#3.4.6">&sect;3.4.6</a>).
8358All functions ignore non-numeric keys
8359in tables given as arguments.
8360
8361
8362<p>
8363For performance reasons,
8364all table accesses (get/set) performed by these functions are raw.
8365
8366
8367<p>
8368<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
8369
8370
8371<p>
8372Given a list where all elements are strings or numbers,
8373returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>.
8374The default value for <code>sep</code> is the empty string,
8375the default for <code>i</code> is 1,
8376and the default for <code>j</code> is <code>#list</code>.
8377If <code>i</code> is greater than <code>j</code>, returns the empty string.
8378
8379
8380
8381
8382<p>
8383<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
8384
8385
8386<p>
8387Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
8388shifting up the elements
8389<code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>.
8390The default value for <code>pos</code> is <code>#list+1</code>,
8391so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
8392of list <code>t</code>.
8393
8394
8395
8396
8397<p>
8398<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
8399
8400
8401<p>
8402Returns a new table with all parameters stored into keys 1, 2, etc.
8403and with a field "<code>n</code>" with the total number of parameters.
8404Note that the resulting table may not be a sequence.
8405
8406
8407
8408
8409<p>
8410<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
8411
8412
8413<p>
8414Removes from <code>list</code> the element at position <code>pos</code>,
8415returning the value of the removed element.
8416When <code>pos</code> is an integer between 1 and <code>#list</code>,
8417it shifts down the elements
8418<code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code>
8419and erases element <code>list[#list]</code>;
8420The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
8421or <code>#list + 1</code>;
8422in those cases, the function erases the element <code>list[pos]</code>.
8423
8424
8425<p>
8426The default value for <code>pos</code> is <code>#list</code>,
8427so that a call <code>table.remove(t)</code> removes the last element
8428of list <code>t</code>.
8429
8430
8431
8432
8433<p>
8434<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
8435
8436
8437<p>
8438Sorts list elements in a given order, <em>in-place</em>,
8439from <code>list[1]</code> to <code>list[#list]</code>.
8440If <code>comp</code> is given,
8441then it must be a function that receives two list elements
8442and returns true when the first element must come
8443before the second in the final order
8444(so that <code>not comp(list[i+1],list[i])</code> will be true after the sort).
8445If <code>comp</code> is not given,
8446then the standard Lua operator <code>&lt;</code> is used instead.
8447
8448
8449<p>
8450The sort algorithm is not stable;
8451that is, elements considered equal by the given order
8452may have their relative positions changed by the sort.
8453
8454
8455
8456
8457<p>
8458<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
8459
8460
8461<p>
8462Returns the elements from the given table.
8463This function is equivalent to
8464
8465<pre>
8466 return list[i], list[i+1], &middot;&middot;&middot;, list[j]
8467</pre><p>
8468By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>.
8469
8470
8471
8472
8473
8474
8475
8476<h2>6.6 &ndash; <a name="6.6">Mathematical Functions</a></h2>
8477
8478<p>
8479This library is an interface to the standard C&nbsp;math library.
8480It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
8481
8482
8483<p>
8484<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
8485
8486
8487<p>
8488Returns the absolute value of <code>x</code>.
8489
8490
8491
8492
8493<p>
8494<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
8495
8496
8497<p>
8498Returns the arc cosine of <code>x</code> (in radians).
8499
8500
8501
8502
8503<p>
8504<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
8505
8506
8507<p>
8508Returns the arc sine of <code>x</code> (in radians).
8509
8510
8511
8512
8513<p>
8514<hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
8515
8516
8517<p>
8518Returns the arc tangent of <code>x</code> (in radians).
8519
8520
8521
8522
8523<p>
8524<hr><h3><a name="pdf-math.atan2"><code>math.atan2 (y, x)</code></a></h3>
8525
8526
8527<p>
8528Returns the arc tangent of <code>y/x</code> (in radians),
8529but uses the signs of both parameters to find the
8530quadrant of the result.
8531(It also handles correctly the case of <code>x</code> being zero.)
8532
8533
8534
8535
8536<p>
8537<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
8538
8539
8540<p>
8541Returns the smallest integer larger than or equal to <code>x</code>.
8542
8543
8544
8545
8546<p>
8547<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
8548
8549
8550<p>
8551Returns the cosine of <code>x</code> (assumed to be in radians).
8552
8553
8554
8555
8556<p>
8557<hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
8558
8559
8560<p>
8561Returns the hyperbolic cosine of <code>x</code>.
8562
8563
8564
8565
8566<p>
8567<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
8568
8569
8570<p>
8571Returns the angle <code>x</code> (given in radians) in degrees.
8572
8573
8574
8575
8576<p>
8577<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
8578
8579
8580<p>
8581Returns the value <em>e<sup>x</sup></em>.
8582
8583
8584
8585
8586<p>
8587<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
8588
8589
8590<p>
8591Returns the largest integer smaller than or equal to <code>x</code>.
8592
8593
8594
8595
8596<p>
8597<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
8598
8599
8600<p>
8601Returns the remainder of the division of <code>x</code> by <code>y</code>
8602that rounds the quotient towards zero.
8603
8604
8605
8606
8607<p>
8608<hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
8609
8610
8611<p>
8612Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
8613<code>e</code> is an integer and the absolute value of <code>m</code> is
8614in the range <em>[0.5, 1)</em>
8615(or zero when <code>x</code> is zero).
8616
8617
8618
8619
8620<p>
8621<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
8622
8623
8624<p>
8625The value <code>HUGE_VAL</code>,
8626a value larger than or equal to any other numerical value.
8627
8628
8629
8630
8631<p>
8632<hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
8633
8634
8635<p>
8636Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
8637
8638
8639
8640
8641<p>
8642<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
8643
8644
8645<p>
8646Returns the logarithm of <code>x</code> in the given base.
8647The default for <code>base</code> is <em>e</em>
8648(so that the function returns the natural logarithm of <code>x</code>).
8649
8650
8651
8652
8653<p>
8654<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
8655
8656
8657<p>
8658Returns the maximum value among its arguments.
8659
8660
8661
8662
8663<p>
8664<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
8665
8666
8667<p>
8668Returns the minimum value among its arguments.
8669
8670
8671
8672
8673<p>
8674<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
8675
8676
8677<p>
8678Returns two numbers,
8679the integral part of <code>x</code> and the fractional part of <code>x</code>.
8680
8681
8682
8683
8684<p>
8685<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
8686
8687
8688<p>
8689The value of <em>&pi;</em>.
8690
8691
8692
8693
8694<p>
8695<hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
8696
8697
8698<p>
8699Returns <em>x<sup>y</sup></em>.
8700(You can also use the expression <code>x^y</code> to compute this value.)
8701
8702
8703
8704
8705<p>
8706<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
8707
8708
8709<p>
8710Returns the angle <code>x</code> (given in degrees) in radians.
8711
8712
8713
8714
8715<p>
8716<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
8717
8718
8719<p>
8720This function is an interface to the simple
8721pseudo-random generator function <code>rand</code> provided by Standard&nbsp;C.
8722(No guarantees can be given for its statistical properties.)
8723
8724
8725<p>
8726When called without arguments,
8727returns a uniform pseudo-random real number
8728in the range <em>[0,1)</em>.
8729When called with an integer number <code>m</code>,
8730<code>math.random</code> returns
8731a uniform pseudo-random integer in the range <em>[1, m]</em>.
8732When called with two integer numbers <code>m</code> and <code>n</code>,
8733<code>math.random</code> returns a uniform pseudo-random
8734integer in the range <em>[m, n]</em>.
8735
8736
8737
8738
8739<p>
8740<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
8741
8742
8743<p>
8744Sets <code>x</code> as the "seed"
8745for the pseudo-random generator:
8746equal seeds produce equal sequences of numbers.
8747
8748
8749
8750
8751<p>
8752<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
8753
8754
8755<p>
8756Returns the sine of <code>x</code> (assumed to be in radians).
8757
8758
8759
8760
8761<p>
8762<hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
8763
8764
8765<p>
8766Returns the hyperbolic sine of <code>x</code>.
8767
8768
8769
8770
8771<p>
8772<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
8773
8774
8775<p>
8776Returns the square root of <code>x</code>.
8777(You can also use the expression <code>x^0.5</code> to compute this value.)
8778
8779
8780
8781
8782<p>
8783<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
8784
8785
8786<p>
8787Returns the tangent of <code>x</code> (assumed to be in radians).
8788
8789
8790
8791
8792<p>
8793<hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
8794
8795
8796<p>
8797Returns the hyperbolic tangent of <code>x</code>.
8798
8799
8800
8801
8802
8803
8804
8805<h2>6.7 &ndash; <a name="6.7">Bitwise Operations</a></h2>
8806
8807<p>
8808This library provides bitwise operations.
8809It provides all its functions inside the table <a name="pdf-bit32"><code>bit32</code></a>.
8810
8811
8812<p>
8813Unless otherwise stated,
8814all functions accept numeric arguments in the range
8815<em>(-2<sup>51</sup>,+2<sup>51</sup>)</em>;
8816each argument is normalized to
8817the remainder of its division by <em>2<sup>32</sup></em>
8818and truncated to an integer (in some unspecified way),
8819so that its final value falls in the range <em>[0,2<sup>32</sup> - 1]</em>.
8820Similarly, all results are in the range <em>[0,2<sup>32</sup> - 1]</em>.
8821Note that <code>bit32.bnot(0)</code> is <code>0xFFFFFFFF</code>,
8822which is different from <code>-1</code>.
8823
8824
8825<p>
8826<hr><h3><a name="pdf-bit32.arshift"><code>bit32.arshift (x, disp)</code></a></h3>
8827
8828
8829<p>
8830Returns the number <code>x</code> shifted <code>disp</code> bits to the right.
8831The number <code>disp</code> may be any representable integer.
8832Negative displacements shift to the left.
8833
8834
8835<p>
8836This shift operation is what is called arithmetic shift.
8837Vacant bits on the left are filled
8838with copies of the higher bit of <code>x</code>;
8839vacant bits on the right are filled with zeros.
8840In particular,
8841displacements with absolute values higher than 31
8842result in zero or <code>0xFFFFFFFF</code> (all original bits are shifted out).
8843
8844
8845
8846
8847<p>
8848<hr><h3><a name="pdf-bit32.band"><code>bit32.band (&middot;&middot;&middot;)</code></a></h3>
8849
8850
8851<p>
8852Returns the bitwise <em>and</em> of its operands.
8853
8854
8855
8856
8857<p>
8858<hr><h3><a name="pdf-bit32.bnot"><code>bit32.bnot (x)</code></a></h3>
8859
8860
8861<p>
8862Returns the bitwise negation of <code>x</code>.
8863For any integer <code>x</code>,
8864the following identity holds:
8865
8866<pre>
8867 assert(bit32.bnot(x) == (-1 - x) % 2^32)
8868</pre>
8869
8870
8871
8872<p>
8873<hr><h3><a name="pdf-bit32.bor"><code>bit32.bor (&middot;&middot;&middot;)</code></a></h3>
8874
8875
8876<p>
8877Returns the bitwise <em>or</em> of its operands.
8878
8879
8880
8881
8882<p>
8883<hr><h3><a name="pdf-bit32.btest"><code>bit32.btest (&middot;&middot;&middot;)</code></a></h3>
8884
8885
8886<p>
8887Returns a boolean signaling
8888whether the bitwise <em>and</em> of its operands is different from zero.
8889
8890
8891
8892
8893<p>
8894<hr><h3><a name="pdf-bit32.bxor"><code>bit32.bxor (&middot;&middot;&middot;)</code></a></h3>
8895
8896
8897<p>
8898Returns the bitwise <em>exclusive or</em> of its operands.
8899
8900
8901
8902
8903<p>
8904<hr><h3><a name="pdf-bit32.extract"><code>bit32.extract (n, field [, width])</code></a></h3>
8905
8906
8907<p>
8908Returns the unsigned number formed by the bits
8909<code>field</code> to <code>field + width - 1</code> from <code>n</code>.
8910Bits are numbered from 0 (least significant) to 31 (most significant).
8911All accessed bits must be in the range <em>[0, 31]</em>.
8912
8913
8914<p>
8915The default for <code>width</code> is 1.
8916
8917
8918
8919
8920<p>
8921<hr><h3><a name="pdf-bit32.replace"><code>bit32.replace (n, v, field [, width])</code></a></h3>
8922
8923
8924<p>
8925Returns a copy of <code>n</code> with
8926the bits <code>field</code> to <code>field + width - 1</code>
8927replaced by the value <code>v</code>.
8928See <a href="#pdf-bit32.extract"><code>bit32.extract</code></a> for details about <code>field</code> and <code>width</code>.
8929
8930
8931
8932
8933<p>
8934<hr><h3><a name="pdf-bit32.lrotate"><code>bit32.lrotate (x, disp)</code></a></h3>
8935
8936
8937<p>
8938Returns the number <code>x</code> rotated <code>disp</code> bits to the left.
8939The number <code>disp</code> may be any representable integer.
8940
8941
8942<p>
8943For any valid displacement,
8944the following identity holds:
8945
8946<pre>
8947 assert(bit32.lrotate(x, disp) == bit32.lrotate(x, disp % 32))
8948</pre><p>
8949In particular,
8950negative displacements rotate to the right.
8951
8952
8953
8954
8955<p>
8956<hr><h3><a name="pdf-bit32.lshift"><code>bit32.lshift (x, disp)</code></a></h3>
8957
8958
8959<p>
8960Returns the number <code>x</code> shifted <code>disp</code> bits to the left.
8961The number <code>disp</code> may be any representable integer.
8962Negative displacements shift to the right.
8963In any direction, vacant bits are filled with zeros.
8964In particular,
8965displacements with absolute values higher than 31
8966result in zero (all bits are shifted out).
8967
8968
8969<p>
8970For positive displacements,
8971the following equality holds:
8972
8973<pre>
8974 assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
8975</pre>
8976
8977
8978
8979<p>
8980<hr><h3><a name="pdf-bit32.rrotate"><code>bit32.rrotate (x, disp)</code></a></h3>
8981
8982
8983<p>
8984Returns the number <code>x</code> rotated <code>disp</code> bits to the right.
8985The number <code>disp</code> may be any representable integer.
8986
8987
8988<p>
8989For any valid displacement,
8990the following identity holds:
8991
8992<pre>
8993 assert(bit32.rrotate(x, disp) == bit32.rrotate(x, disp % 32))
8994</pre><p>
8995In particular,
8996negative displacements rotate to the left.
8997
8998
8999
9000
9001<p>
9002<hr><h3><a name="pdf-bit32.rshift"><code>bit32.rshift (x, disp)</code></a></h3>
9003
9004
9005<p>
9006Returns the number <code>x</code> shifted <code>disp</code> bits to the right.
9007The number <code>disp</code> may be any representable integer.
9008Negative displacements shift to the left.
9009In any direction, vacant bits are filled with zeros.
9010In particular,
9011displacements with absolute values higher than 31
9012result in zero (all bits are shifted out).
9013
9014
9015<p>
9016For positive displacements,
9017the following equality holds:
9018
9019<pre>
9020 assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))
9021</pre>
9022
9023<p>
9024This shift operation is what is called logical shift.
9025
9026
9027
9028
9029
9030
9031
9032<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
9033
9034<p>
9035The I/O library provides two different styles for file manipulation.
9036The first one uses implicit file descriptors;
9037that is, there are operations to set a default input file and a
9038default output file,
9039and all input/output operations are over these default files.
9040The second style uses explicit file descriptors.
9041
9042
9043<p>
9044When using implicit file descriptors,
9045all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
9046When using explicit file descriptors,
9047the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
9048and then all operations are supplied as methods of the file descriptor.
9049
9050
9051<p>
9052The table <code>io</code> also provides
9053three predefined file descriptors with their usual meanings from C:
9054<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>.
9055The I/O library never closes these files.
9056
9057
9058<p>
9059Unless otherwise stated,
9060all I/O functions return <b>nil</b> on failure
9061(plus an error message as a second result and
9062a system-dependent error code as a third result)
9063and some value different from <b>nil</b> on success.
9064On non-Posix systems,
9065the computation of the error message and error code
9066in case of errors
9067may be not thread safe,
9068because they rely on the global C variable <code>errno</code>.
9069
9070
9071<p>
9072<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
9073
9074
9075<p>
9076Equivalent to <code>file:close()</code>.
9077Without a <code>file</code>, closes the default output file.
9078
9079
9080
9081
9082<p>
9083<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
9084
9085
9086<p>
9087Equivalent to <code>io.output():flush()</code>.
9088
9089
9090
9091
9092<p>
9093<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
9094
9095
9096<p>
9097When called with a file name, it opens the named file (in text mode),
9098and sets its handle as the default input file.
9099When called with a file handle,
9100it simply sets this file handle as the default input file.
9101When called without parameters,
9102it returns the current default input file.
9103
9104
9105<p>
9106In case of errors this function raises the error,
9107instead of returning an error code.
9108
9109
9110
9111
9112<p>
9113<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename &middot;&middot;&middot;])</code></a></h3>
9114
9115
9116<p>
9117Opens the given file name in read mode
9118and returns an iterator function that
9119works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
9120When the iterator function detects the end of file,
9121it returns <b>nil</b> (to finish the loop) and automatically closes the file.
9122
9123
9124<p>
9125The call <code>io.lines()</code> (with no file name) is equivalent
9126to <code>io.input():lines()</code>;
9127that is, it iterates over the lines of the default input file.
9128In this case it does not close the file when the loop ends.
9129
9130
9131<p>
9132In case of errors this function raises the error,
9133instead of returning an error code.
9134
9135
9136
9137
9138<p>
9139<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
9140
9141
9142<p>
9143This function opens a file,
9144in the mode specified in the string <code>mode</code>.
9145It returns a new file handle,
9146or, in case of errors, <b>nil</b> plus an error message.
9147
9148
9149<p>
9150The <code>mode</code> string can be any of the following:
9151
9152<ul>
9153<li><b>"<code>r</code>": </b> read mode (the default);</li>
9154<li><b>"<code>w</code>": </b> write mode;</li>
9155<li><b>"<code>a</code>": </b> append mode;</li>
9156<li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li>
9157<li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li>
9158<li><b>"<code>a+</code>": </b> append update mode, previous data is preserved,
9159 writing is only allowed at the end of file.</li>
9160</ul><p>
9161The <code>mode</code> string can also have a '<code>b</code>' at the end,
9162which is needed in some systems to open the file in binary mode.
9163
9164
9165
9166
9167<p>
9168<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
9169
9170
9171<p>
9172Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
9173
9174
9175
9176
9177<p>
9178<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
9179
9180
9181<p>
9182This function is system dependent and is not available
9183on all platforms.
9184
9185
9186<p>
9187Starts program <code>prog</code> in a separated process and returns
9188a file handle that you can use to read data from this program
9189(if <code>mode</code> is <code>"r"</code>, the default)
9190or to write data to this program
9191(if <code>mode</code> is <code>"w"</code>).
9192
9193
9194
9195
9196<p>
9197<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
9198
9199
9200<p>
9201Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>.
9202
9203
9204
9205
9206<p>
9207<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
9208
9209
9210<p>
9211Returns a handle for a temporary file.
9212This file is opened in update mode
9213and it is automatically removed when the program ends.
9214
9215
9216
9217
9218<p>
9219<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
9220
9221
9222<p>
9223Checks whether <code>obj</code> is a valid file handle.
9224Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
9225<code>"closed file"</code> if <code>obj</code> is a closed file handle,
9226or <b>nil</b> if <code>obj</code> is not a file handle.
9227
9228
9229
9230
9231<p>
9232<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
9233
9234
9235<p>
9236Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>.
9237
9238
9239
9240
9241<p>
9242<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
9243
9244
9245<p>
9246Closes <code>file</code>.
9247Note that files are automatically closed when
9248their handles are garbage collected,
9249but that takes an unpredictable amount of time to happen.
9250
9251
9252<p>
9253When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>,
9254<a href="#pdf-file:close"><code>file:close</code></a> returns the same values
9255returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
9256
9257
9258
9259
9260<p>
9261<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
9262
9263
9264<p>
9265Saves any written data to <code>file</code>.
9266
9267
9268
9269
9270<p>
9271<hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3>
9272
9273
9274<p>
9275Returns an iterator function that,
9276each time it is called,
9277reads the file according to the given formats.
9278When no format is given,
9279uses "*l" as a default.
9280As an example, the construction
9281
9282<pre>
9283 for c in file:lines(1) do <em>body</em> end
9284</pre><p>
9285will iterate over all characters of the file,
9286starting at the current position.
9287Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
9288when the loop ends.
9289
9290
9291<p>
9292In case of errors this function raises the error,
9293instead of returning an error code.
9294
9295
9296
9297
9298<p>
9299<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
9300
9301
9302<p>
9303Reads the file <code>file</code>,
9304according to the given formats, which specify what to read.
9305For each format,
9306the function returns a string (or a number) with the characters read,
9307or <b>nil</b> if it cannot read data with the specified format.
9308When called without formats,
9309it uses a default format that reads the next line
9310(see below).
9311
9312
9313<p>
9314The available formats are
9315
9316<ul>
9317
9318<li><b>"<code>*n</code>": </b>
9319reads a number;
9320this is the only format that returns a number instead of a string.
9321</li>
9322
9323<li><b>"<code>*a</code>": </b>
9324reads the whole file, starting at the current position.
9325On end of file, it returns the empty string.
9326</li>
9327
9328<li><b>"<code>*l</code>": </b>
9329reads the next line skipping the end of line,
9330returning <b>nil</b> on end of file.
9331This is the default format.
9332</li>
9333
9334<li><b>"<code>*L</code>": </b>
9335reads the next line keeping the end of line (if present),
9336returning <b>nil</b> on end of file.
9337</li>
9338
9339<li><b><em>number</em>: </b>
9340reads a string with up to this number of bytes,
9341returning <b>nil</b> on end of file.
9342If number is zero,
9343it reads nothing and returns an empty string,
9344or <b>nil</b> on end of file.
9345</li>
9346
9347</ul>
9348
9349
9350
9351<p>
9352<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
9353
9354
9355<p>
9356Sets and gets the file position,
9357measured from the beginning of the file,
9358to the position given by <code>offset</code> plus a base
9359specified by the string <code>whence</code>, as follows:
9360
9361<ul>
9362<li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li>
9363<li><b>"<code>cur</code>": </b> base is current position;</li>
9364<li><b>"<code>end</code>": </b> base is end of file;</li>
9365</ul><p>
9366In case of success, <code>seek</code> returns the final file position,
9367measured in bytes from the beginning of the file.
9368If <code>seek</code> fails, it returns <b>nil</b>,
9369plus a string describing the error.
9370
9371
9372<p>
9373The default value for <code>whence</code> is <code>"cur"</code>,
9374and for <code>offset</code> is 0.
9375Therefore, the call <code>file:seek()</code> returns the current
9376file position, without changing it;
9377the call <code>file:seek("set")</code> sets the position to the
9378beginning of the file (and returns 0);
9379and the call <code>file:seek("end")</code> sets the position to the
9380end of the file, and returns its size.
9381
9382
9383
9384
9385<p>
9386<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
9387
9388
9389<p>
9390Sets the buffering mode for an output file.
9391There are three available modes:
9392
9393<ul>
9394
9395<li><b>"<code>no</code>": </b>
9396no buffering; the result of any output operation appears immediately.
9397</li>
9398
9399<li><b>"<code>full</code>": </b>
9400full buffering; output operation is performed only
9401when the buffer is full or when
9402you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>).
9403</li>
9404
9405<li><b>"<code>line</code>": </b>
9406line buffering; output is buffered until a newline is output
9407or there is any input from some special files
9408(such as a terminal device).
9409</li>
9410
9411</ul><p>
9412For the last two cases, <code>size</code>
9413specifies the size of the buffer, in bytes.
9414The default is an appropriate size.
9415
9416
9417
9418
9419<p>
9420<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
9421
9422
9423<p>
9424Writes the value of each of its arguments to <code>file</code>.
9425The arguments must be strings or numbers.
9426
9427
9428<p>
9429In case of success, this function returns <code>file</code>.
9430Otherwise it returns <b>nil</b> plus a string describing the error.
9431
9432
9433
9434
9435
9436
9437
9438<h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2>
9439
9440<p>
9441This library is implemented through table <a name="pdf-os"><code>os</code></a>.
9442
9443
9444<p>
9445<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
9446
9447
9448<p>
9449Returns an approximation of the amount in seconds of CPU time
9450used by the program.
9451
9452
9453
9454
9455<p>
9456<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
9457
9458
9459<p>
9460Returns a string or a table containing date and time,
9461formatted according to the given string <code>format</code>.
9462
9463
9464<p>
9465If the <code>time</code> argument is present,
9466this is the time to be formatted
9467(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
9468Otherwise, <code>date</code> formats the current time.
9469
9470
9471<p>
9472If <code>format</code> starts with '<code>!</code>',
9473then the date is formatted in Coordinated Universal Time.
9474After this optional character,
9475if <code>format</code> is the string "<code>*t</code>",
9476then <code>date</code> returns a table with the following fields:
9477<code>year</code> (four digits), <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31),
9478<code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59), <code>sec</code> (0&ndash;61),
9479<code>wday</code> (weekday, Sunday is&nbsp;1),
9480<code>yday</code> (day of the year),
9481and <code>isdst</code> (daylight saving flag, a boolean).
9482This last field may be absent
9483if the information is not available.
9484
9485
9486<p>
9487If <code>format</code> is not "<code>*t</code>",
9488then <code>date</code> returns the date as a string,
9489formatted according to the same rules as the ANSI&nbsp;C function <code>strftime</code>.
9490
9491
9492<p>
9493When called without arguments,
9494<code>date</code> returns a reasonable date and time representation that depends on
9495the host system and on the current locale
9496(that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
9497
9498
9499<p>
9500On non-Posix systems,
9501this function may be not thread safe
9502because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
9503
9504
9505
9506
9507<p>
9508<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
9509
9510
9511<p>
9512Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
9513In POSIX, Windows, and some other systems,
9514this value is exactly <code>t2</code><em>-</em><code>t1</code>.
9515
9516
9517
9518
9519<p>
9520<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
9521
9522
9523<p>
9524This function is equivalent to the ANSI&nbsp;C function <code>system</code>.
9525It passes <code>command</code> to be executed by an operating system shell.
9526Its first result is <b>true</b>
9527if the command terminated successfully,
9528or <b>nil</b> otherwise.
9529After this first result
9530the function returns a string and a number,
9531as follows:
9532
9533<ul>
9534
9535<li><b>"<code>exit</code>": </b>
9536the command terminated normally;
9537the following number is the exit status of the command.
9538</li>
9539
9540<li><b>"<code>signal</code>": </b>
9541the command was terminated by a signal;
9542the following number is the signal that terminated the command.
9543</li>
9544
9545</ul>
9546
9547<p>
9548When called without a <code>command</code>,
9549<code>os.execute</code> returns a boolean that is true if a shell is available.
9550
9551
9552
9553
9554<p>
9555<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close])</code></a></h3>
9556
9557
9558<p>
9559Calls the ANSI&nbsp;C function <code>exit</code> to terminate the host program.
9560If <code>code</code> is <b>true</b>,
9561the returned status is <code>EXIT_SUCCESS</code>;
9562if <code>code</code> is <b>false</b>,
9563the returned status is <code>EXIT_FAILURE</code>;
9564if <code>code</code> is a number,
9565the returned status is this number.
9566The default value for <code>code</code> is <b>true</b>.
9567
9568
9569<p>
9570If the optional second argument <code>close</code> is true,
9571closes the Lua state before exiting.
9572
9573
9574
9575
9576<p>
9577<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
9578
9579
9580<p>
9581Returns the value of the process environment variable <code>varname</code>,
9582or <b>nil</b> if the variable is not defined.
9583
9584
9585
9586
9587<p>
9588<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
9589
9590
9591<p>
9592Deletes the file (or empty directory, on POSIX systems)
9593with the given name.
9594If this function fails, it returns <b>nil</b>,
9595plus a string describing the error and the error code.
9596
9597
9598
9599
9600<p>
9601<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
9602
9603
9604<p>
9605Renames file or directory named <code>oldname</code> to <code>newname</code>.
9606If this function fails, it returns <b>nil</b>,
9607plus a string describing the error and the error code.
9608
9609
9610
9611
9612<p>
9613<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
9614
9615
9616<p>
9617Sets the current locale of the program.
9618<code>locale</code> is a system-dependent string specifying a locale;
9619<code>category</code> is an optional string describing which category to change:
9620<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
9621<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
9622the default category is <code>"all"</code>.
9623The function returns the name of the new locale,
9624or <b>nil</b> if the request cannot be honored.
9625
9626
9627<p>
9628If <code>locale</code> is the empty string,
9629the current locale is set to an implementation-defined native locale.
9630If <code>locale</code> is the string "<code>C</code>",
9631the current locale is set to the standard C locale.
9632
9633
9634<p>
9635When called with <b>nil</b> as the first argument,
9636this function only returns the name of the current locale
9637for the given category.
9638
9639
9640<p>
9641This function may be not thread safe
9642because of its reliance on C&nbsp;function <code>setlocale</code>.
9643
9644
9645
9646
9647<p>
9648<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
9649
9650
9651<p>
9652Returns the current time when called without arguments,
9653or a time representing the date and time specified by the given table.
9654This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
9655and may have fields
9656<code>hour</code> (default is 12),
9657<code>min</code> (default is 0),
9658<code>sec</code> (default is 0),
9659and <code>isdst</code> (default is <b>nil</b>).
9660For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
9661
9662
9663<p>
9664The returned value is a number, whose meaning depends on your system.
9665In POSIX, Windows, and some other systems,
9666this number counts the number
9667of seconds since some given start time (the "epoch").
9668In other systems, the meaning is not specified,
9669and the number returned by <code>time</code> can be used only as an argument to
9670<a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>.
9671
9672
9673
9674
9675<p>
9676<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
9677
9678
9679<p>
9680Returns a string with a file name that can
9681be used for a temporary file.
9682The file must be explicitly opened before its use
9683and explicitly removed when no longer needed.
9684
9685
9686<p>
9687On POSIX systems,
9688this function also creates a file with that name,
9689to avoid security risks.
9690(Someone else might create the file with wrong permissions
9691in the time between getting the name and creating the file.)
9692You still have to open the file to use it
9693and to remove it (even if you do not use it).
9694
9695
9696<p>
9697When possible,
9698you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
9699which automatically removes the file when the program ends.
9700
9701
9702
9703
9704
9705
9706
9707<h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2>
9708
9709<p>
9710This library provides
9711the functionality of the debug interface (<a href="#4.9">&sect;4.9</a>) to Lua programs.
9712You should exert care when using this library.
9713Several of its functions
9714violate basic assumptions about Lua code
9715(e.g., that variables local to a function
9716cannot be accessed from outside;
9717that userdata metatables cannot be changed by Lua code;
9718that Lua programs do not crash)
9719and therefore can compromise otherwise secure code.
9720Moreover, some functions in this library may be slow.
9721
9722
9723<p>
9724All functions in this library are provided
9725inside the <a name="pdf-debug"><code>debug</code></a> table.
9726All functions that operate over a thread
9727have an optional first argument which is the
9728thread to operate over.
9729The default is always the current thread.
9730
9731
9732<p>
9733<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
9734
9735
9736<p>
9737Enters an interactive mode with the user,
9738running each string that the user enters.
9739Using simple commands and other debug facilities,
9740the user can inspect global and local variables,
9741change their values, evaluate expressions, and so on.
9742A line containing only the word <code>cont</code> finishes this function,
9743so that the caller continues its execution.
9744
9745
9746<p>
9747Note that commands for <code>debug.debug</code> are not lexically nested
9748within any function and so have no direct access to local variables.
9749
9750
9751
9752
9753<p>
9754<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
9755
9756
9757<p>
9758Returns the current hook settings of the thread, as three values:
9759the current hook function, the current hook mask,
9760and the current hook count
9761(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
9762
9763
9764
9765
9766<p>
9767<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
9768
9769
9770<p>
9771Returns a table with information about a function.
9772You can give the function directly
9773or you can give a number as the value of <code>f</code>,
9774which means the function running at level <code>f</code> of the call stack
9775of the given thread:
9776level&nbsp;0 is the current function (<code>getinfo</code> itself);
9777level&nbsp;1 is the function that called <code>getinfo</code>
9778(except for tail calls, which do not count on the stack);
9779and so on.
9780If <code>f</code> is a number larger than the number of active functions,
9781then <code>getinfo</code> returns <b>nil</b>.
9782
9783
9784<p>
9785The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
9786with the string <code>what</code> describing which fields to fill in.
9787The default for <code>what</code> is to get all information available,
9788except the table of valid lines.
9789If present,
9790the option '<code>f</code>'
9791adds a field named <code>func</code> with the function itself.
9792If present,
9793the option '<code>L</code>'
9794adds a field named <code>activelines</code> with the table of
9795valid lines.
9796
9797
9798<p>
9799For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
9800a table with a name for the current function,
9801if a reasonable name can be found,
9802and the expression <code>debug.getinfo(print)</code>
9803returns a table with all available information
9804about the <a href="#pdf-print"><code>print</code></a> function.
9805
9806
9807
9808
9809<p>
9810<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
9811
9812
9813<p>
9814This function returns the name and the value of the local variable
9815with index <code>local</code> of the function at level <code>f</code> of the stack.
9816This function accesses not only explicit local variables,
9817but also parameters, temporaries, etc.
9818
9819
9820<p>
9821The first parameter or local variable has index&nbsp;1, and so on,
9822until the last active variable.
9823Negative indices refer to vararg parameters;
9824-1 is the first vararg parameter.
9825The function returns <b>nil</b> if there is no variable with the given index,
9826and raises an error when called with a level out of range.
9827(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
9828
9829
9830<p>
9831Variable names starting with '<code>(</code>' (open parenthesis)
9832represent internal variables
9833(loop control variables, temporaries, varargs, and C&nbsp;function locals).
9834
9835
9836<p>
9837The parameter <code>f</code> may also be a function.
9838In that case, <code>getlocal</code> returns only the name of function parameters.
9839
9840
9841
9842
9843<p>
9844<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
9845
9846
9847<p>
9848Returns the metatable of the given <code>value</code>
9849or <b>nil</b> if it does not have a metatable.
9850
9851
9852
9853
9854<p>
9855<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
9856
9857
9858<p>
9859Returns the registry table (see <a href="#4.5">&sect;4.5</a>).
9860
9861
9862
9863
9864<p>
9865<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
9866
9867
9868<p>
9869This function returns the name and the value of the upvalue
9870with index <code>up</code> of the function <code>f</code>.
9871The function returns <b>nil</b> if there is no upvalue with the given index.
9872
9873
9874
9875
9876<p>
9877<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
9878
9879
9880<p>
9881Returns the Lua value associated to <code>u</code>.
9882If <code>u</code> is not a userdata,
9883returns <b>nil</b>.
9884
9885
9886
9887
9888<p>
9889<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
9890
9891
9892<p>
9893Sets the given function as a hook.
9894The string <code>mask</code> and the number <code>count</code> describe
9895when the hook will be called.
9896The string mask may have the following characters,
9897with the given meaning:
9898
9899<ul>
9900<li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li>
9901<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
9902<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
9903</ul><p>
9904With a <code>count</code> different from zero,
9905the hook is called after every <code>count</code> instructions.
9906
9907
9908<p>
9909When called without arguments,
9910<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
9911
9912
9913<p>
9914When the hook is called, its first parameter is a string
9915describing the event that has triggered its call:
9916<code>"call"</code> (or <code>"tail call"</code>),
9917<code>"return"</code>,
9918<code>"line"</code>, and <code>"count"</code>.
9919For line events,
9920the hook also gets the new line number as its second parameter.
9921Inside a hook,
9922you can call <code>getinfo</code> with level&nbsp;2 to get more information about
9923the running function
9924(level&nbsp;0 is the <code>getinfo</code> function,
9925and level&nbsp;1 is the hook function).
9926
9927
9928
9929
9930<p>
9931<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
9932
9933
9934<p>
9935This function assigns the value <code>value</code> to the local variable
9936with index <code>local</code> of the function at level <code>level</code> of the stack.
9937The function returns <b>nil</b> if there is no local
9938variable with the given index,
9939and raises an error when called with a <code>level</code> out of range.
9940(You can call <code>getinfo</code> to check whether the level is valid.)
9941Otherwise, it returns the name of the local variable.
9942
9943
9944<p>
9945See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
9946variable indices and names.
9947
9948
9949
9950
9951<p>
9952<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
9953
9954
9955<p>
9956Sets the metatable for the given <code>value</code> to the given <code>table</code>
9957(which can be <b>nil</b>).
9958Returns <code>value</code>.
9959
9960
9961
9962
9963<p>
9964<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
9965
9966
9967<p>
9968This function assigns the value <code>value</code> to the upvalue
9969with index <code>up</code> of the function <code>f</code>.
9970The function returns <b>nil</b> if there is no upvalue
9971with the given index.
9972Otherwise, it returns the name of the upvalue.
9973
9974
9975
9976
9977<p>
9978<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3>
9979
9980
9981<p>
9982Sets the given <code>value</code> as
9983the Lua value associated to the given <code>udata</code>.
9984<code>value</code> must be a table or <b>nil</b>;
9985<code>udata</code> must be a full userdata.
9986
9987
9988<p>
9989Returns <code>udata</code>.
9990
9991
9992
9993
9994<p>
9995<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
9996
9997
9998<p>
9999If <code>message</code> is present but is neither a string nor <b>nil</b>,
10000this function returns <code>message</code> without further processing.
10001Otherwise,
10002it returns a string with a traceback of the call stack.
10003An optional <code>message</code> string is appended
10004at the beginning of the traceback.
10005An optional <code>level</code> number tells at which level
10006to start the traceback
10007(default is 1, the function calling <code>traceback</code>).
10008
10009
10010
10011
10012<p>
10013<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
10014
10015
10016<p>
10017Returns an unique identifier (as a light userdata)
10018for the upvalue numbered <code>n</code>
10019from the given function.
10020
10021
10022<p>
10023These unique identifiers allow a program to check whether different
10024closures share upvalues.
10025Lua closures that share an upvalue
10026(that is, that access a same external local variable)
10027will return identical ids for those upvalue indices.
10028
10029
10030
10031
10032<p>
10033<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
10034
10035
10036<p>
10037Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
10038refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
10039
10040
10041
10042
10043
10044
10045
10046<h1>7 &ndash; <a name="7">Lua Standalone</a></h1>
10047
10048<p>
10049Although Lua has been designed as an extension language,
10050to be embedded in a host C&nbsp;program,
10051it is also frequently used as a standalone language.
10052An interpreter for Lua as a standalone language,
10053called simply <code>lua</code>,
10054is provided with the standard distribution.
10055The standalone interpreter includes
10056all standard libraries, including the debug library.
10057Its usage is:
10058
10059<pre>
10060 lua [options] [script [args]]
10061</pre><p>
10062The options are:
10063
10064<ul>
10065<li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li>
10066<li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em>;</li>
10067<li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li>
10068<li><b><code>-v</code>: </b> prints version information;</li>
10069<li><b><code>-E</code>: </b> ignores environment variables;</li>
10070<li><b><code>--</code>: </b> stops handling options;</li>
10071<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
10072</ul><p>
10073After handling its options, <code>lua</code> runs the given <em>script</em>,
10074passing to it the given <em>args</em> as string arguments.
10075When called without arguments,
10076<code>lua</code> behaves as <code>lua -v -i</code>
10077when the standard input (<code>stdin</code>) is a terminal,
10078and as <code>lua -</code> otherwise.
10079
10080
10081<p>
10082When called without option <code>-E</code>,
10083the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_2"><code>LUA_INIT_5_2</code></a>
10084(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if it is not defined)
10085before running any argument.
10086If the variable content has the format <code>@<em>filename</em></code>,
10087then <code>lua</code> executes the file.
10088Otherwise, <code>lua</code> executes the string itself.
10089
10090
10091<p>
10092When called with option <code>-E</code>,
10093besides ignoring <code>LUA_INIT</code>,
10094Lua also ignores
10095the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>,
10096setting the values of
10097<a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a>
10098with the default paths defined in <code>luaconf.h</code>.
10099
10100
10101<p>
10102All options are handled in order, except <code>-i</code> and <code>-E</code>.
10103For instance, an invocation like
10104
10105<pre>
10106 $ lua -e'a=1' -e 'print(a)' script.lua
10107</pre><p>
10108will first set <code>a</code> to 1, then print the value of <code>a</code>,
10109and finally run the file <code>script.lua</code> with no arguments.
10110(Here <code>$</code> is the shell prompt. Your prompt may be different.)
10111
10112
10113<p>
10114Before starting to run the script,
10115<code>lua</code> collects all arguments in the command line
10116in a global table called <code>arg</code>.
10117The script name is stored at index 0,
10118the first argument after the script name goes to index 1,
10119and so on.
10120Any arguments before the script name
10121(that is, the interpreter name plus the options)
10122go to negative indices.
10123For instance, in the call
10124
10125<pre>
10126 $ lua -la b.lua t1 t2
10127</pre><p>
10128the interpreter first runs the file <code>a.lua</code>,
10129then creates a table
10130
10131<pre>
10132 arg = { [-2] = "lua", [-1] = "-la",
10133 [0] = "b.lua",
10134 [1] = "t1", [2] = "t2" }
10135</pre><p>
10136and finally runs the file <code>b.lua</code>.
10137The script is called with <code>arg[1]</code>, <code>arg[2]</code>, ...
10138as arguments;
10139it can also access these arguments with the vararg expression '<code>...</code>'.
10140
10141
10142<p>
10143In interactive mode,
10144if you write an incomplete statement,
10145the interpreter waits for its completion
10146by issuing a different prompt.
10147
10148
10149<p>
10150In case of unprotected errors in the script,
10151the interpreter reports the error to the standard error stream.
10152If the error object is a string,
10153the interpreter adds a stack traceback to it.
10154Otherwise, if the error object has a metamethod <code>__tostring</code>,
10155the interpreter calls this metamethod to produce the final message.
10156Finally, if the error object is <b>nil</b>,
10157the interpreter does not report the error.
10158
10159
10160<p>
10161When finishing normally,
10162the interpreter closes its main Lua state
10163(see <a href="#lua_close"><code>lua_close</code></a>).
10164The script can avoid this step by
10165calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
10166
10167
10168<p>
10169To allow the use of Lua as a
10170script interpreter in Unix systems,
10171the standalone interpreter skips
10172the first line of a chunk if it starts with <code>#</code>.
10173Therefore, Lua scripts can be made into executable programs
10174by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
10175as in
10176
10177<pre>
10178 #!/usr/local/bin/lua
10179</pre><p>
10180(Of course,
10181the location of the Lua interpreter may be different in your machine.
10182If <code>lua</code> is in your <code>PATH</code>,
10183then
10184
10185<pre>
10186 #!/usr/bin/env lua
10187</pre><p>
10188is a more portable solution.)
10189
10190
10191
10192<h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1>
10193
10194<p>
10195Here we list the incompatibilities that you may find when moving a program
10196from Lua&nbsp;5.1 to Lua&nbsp;5.2.
10197You can avoid some incompatibilities by compiling Lua with
10198appropriate options (see file <code>luaconf.h</code>).
10199However,
10200all these compatibility options will be removed in the next version of Lua.
10201Similarly,
10202all features marked as deprecated in Lua&nbsp;5.1
10203have been removed in Lua&nbsp;5.2.
10204
10205
10206
10207<h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10208<ul>
10209
10210<li>
10211The concept of <em>environment</em> changed.
10212Only Lua functions have environments.
10213To set the environment of a Lua function,
10214use the variable <code>_ENV</code> or the function <a href="#pdf-load"><code>load</code></a>.
10215
10216
10217<p>
10218C functions no longer have environments.
10219Use an upvalue with a shared table if you need to keep
10220shared state among several C functions.
10221(You may use <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> to open a C library
10222with all functions sharing a common upvalue.)
10223
10224
10225<p>
10226To manipulate the "environment" of a userdata
10227(which is now called user value),
10228use the new functions
10229<a href="#lua_getuservalue"><code>lua_getuservalue</code></a> and <a href="#lua_setuservalue"><code>lua_setuservalue</code></a>.
10230</li>
10231
10232<li>
10233Lua identifiers cannot use locale-dependent letters.
10234</li>
10235
10236<li>
10237Doing a step or a full collection in the garbage collector
10238does not restart the collector if it has been stopped.
10239</li>
10240
10241<li>
10242Weak tables with weak keys now perform like <em>ephemeron tables</em>.
10243</li>
10244
10245<li>
10246The event <em>tail return</em> in debug hooks was removed.
10247Instead, tail calls generate a special new event,
10248<em>tail call</em>, so that the debugger can know that
10249there will not be a corresponding return event.
10250</li>
10251
10252<li>
10253Equality between function values has changed.
10254Now, a function definition may not create a new value;
10255it may reuse some previous value if there is no
10256observable difference to the new function.
10257</li>
10258
10259</ul>
10260
10261
10262
10263
10264<h2>8.2 &ndash; <a name="8.2">Changes in the Libraries</a></h2>
10265<ul>
10266
10267<li>
10268Function <code>module</code> is deprecated.
10269It is easy to set up a module with regular Lua code.
10270Modules are not expected to set global variables.
10271</li>
10272
10273<li>
10274Functions <code>setfenv</code> and <code>getfenv</code> were removed,
10275because of the changes in environments.
10276</li>
10277
10278<li>
10279Function <code>math.log10</code> is deprecated.
10280Use <a href="#pdf-math.log"><code>math.log</code></a> with 10 as its second argument, instead.
10281</li>
10282
10283<li>
10284Function <code>loadstring</code> is deprecated.
10285Use <code>load</code> instead; it now accepts string arguments
10286and are exactly equivalent to <code>loadstring</code>.
10287</li>
10288
10289<li>
10290Function <code>table.maxn</code> is deprecated.
10291Write it in Lua if you really need it.
10292</li>
10293
10294<li>
10295Function <code>os.execute</code> now returns <b>true</b> when command
10296terminates successfully and <b>nil</b> plus error information
10297otherwise.
10298</li>
10299
10300<li>
10301Function <code>unpack</code> was moved into the table library
10302and therefore must be called as <a href="#pdf-table.unpack"><code>table.unpack</code></a>.
10303</li>
10304
10305<li>
10306Character class <code>%z</code> in patterns is deprecated,
10307as now patterns may contain '<code>\0</code>' as a regular character.
10308</li>
10309
10310<li>
10311The table <code>package.loaders</code> was renamed <code>package.searchers</code>.
10312</li>
10313
10314<li>
10315Lua does not have bytecode verification anymore.
10316So, all functions that load code
10317(<a href="#pdf-load"><code>load</code></a> and <a href="#pdf-loadfile"><code>loadfile</code></a>)
10318are potentially insecure when loading untrusted binary data.
10319(Actually, those functions were already insecure because
10320of flaws in the verification algorithm.)
10321When in doubt,
10322use the <code>mode</code> argument of those functions
10323to restrict them to loading textual chunks.
10324</li>
10325
10326<li>
10327The standard paths in the official distribution may
10328change between versions.
10329</li>
10330
10331</ul>
10332
10333
10334
10335
10336<h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2>
10337<ul>
10338
10339<li>
10340Pseudoindex <code>LUA_GLOBALSINDEX</code> was removed.
10341You must get the global environment from the registry
10342(see <a href="#4.5">&sect;4.5</a>).
10343</li>
10344
10345<li>
10346Pseudoindex <code>LUA_ENVIRONINDEX</code>
10347and functions <code>lua_getfenv</code>/<code>lua_setfenv</code>
10348were removed,
10349as C&nbsp;functions no longer have environments.
10350</li>
10351
10352<li>
10353Function <code>luaL_register</code> is deprecated.
10354Use <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> so that your module does not create globals.
10355(Modules are not expected to set global variables anymore.)
10356</li>
10357
10358<li>
10359The <code>osize</code> argument to the allocation function
10360may not be zero when creating a new block,
10361that is, when <code>ptr</code> is <code>NULL</code>
10362(see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
10363Use only the test <code>ptr == NULL</code> to check whether
10364the block is new.
10365</li>
10366
10367<li>
10368Finalizers (<code>__gc</code> metamethods) for userdata are called in the
10369reverse order that they were marked for finalization,
10370not that they were created (see <a href="#2.5.1">&sect;2.5.1</a>).
10371(Most userdata are marked immediately after they are created.)
10372Moreover,
10373if the metatable does not have a <code>__gc</code> field when set,
10374the finalizer will not be called,
10375even if it is set later.
10376</li>
10377
10378<li>
10379<code>luaL_typerror</code> was removed.
10380Write your own version if you need it.
10381</li>
10382
10383<li>
10384Function <code>lua_cpcall</code> is deprecated.
10385You can simply push the function with <a href="#lua_pushcfunction"><code>lua_pushcfunction</code></a>
10386and call it with <a href="#lua_pcall"><code>lua_pcall</code></a>.
10387</li>
10388
10389<li>
10390Functions <code>lua_equal</code> and <code>lua_lessthan</code> are deprecated.
10391Use the new <a href="#lua_compare"><code>lua_compare</code></a> with appropriate options instead.
10392</li>
10393
10394<li>
10395Function <code>lua_objlen</code> was renamed <a href="#lua_rawlen"><code>lua_rawlen</code></a>.
10396</li>
10397
10398<li>
10399Function <a href="#lua_load"><code>lua_load</code></a> has an extra parameter, <code>mode</code>.
10400Pass <code>NULL</code> to simulate the old behavior.
10401</li>
10402
10403<li>
10404Function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter, <code>from</code>.
10405Pass <code>NULL</code> or the thread doing the call.
10406</li>
10407
10408</ul>
10409
10410
10411
10412
10413<h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1>
10414
10415<p>
10416Here is the complete syntax of Lua in extended BNF.
10417(It does not describe operator precedences.)
10418
10419
10420
10421
10422<pre>
10423
10424 chunk ::= block
10425
10426 block ::= {stat} [retstat]
10427
10428 stat ::= &lsquo;<b>;</b>&rsquo; |
10429 varlist &lsquo;<b>=</b>&rsquo; explist |
10430 functioncall |
10431 label |
10432 <b>break</b> |
10433 <b>goto</b> Name |
10434 <b>do</b> block <b>end</b> |
10435 <b>while</b> exp <b>do</b> block <b>end</b> |
10436 <b>repeat</b> block <b>until</b> exp |
10437 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> |
10438 <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> |
10439 <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> |
10440 <b>function</b> funcname funcbody |
10441 <b>local</b> <b>function</b> Name funcbody |
10442 <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist]
10443
10444 retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;]
10445
10446 label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo;
10447
10448 funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name]
10449
10450 varlist ::= var {&lsquo;<b>,</b>&rsquo; var}
10451
10452 var ::= Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name
10453
10454 namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name}
10455
10456 explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
10457
10458 exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | &lsquo;<b>...</b>&rsquo; | functiondef |
10459 prefixexp | tableconstructor | exp binop exp | unop exp
10460
10461 prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
10462
10463 functioncall ::= prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
10464
10465 args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | String
10466
10467 functiondef ::= <b>function</b> funcbody
10468
10469 funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b>
10470
10471 parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo;
10472
10473 tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo;
10474
10475 fieldlist ::= field {fieldsep field} [fieldsep]
10476
10477 field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp
10478
10479 fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
10480
10481 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; |
10482 &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; |
10483 <b>and</b> | <b>or</b>
10484
10485 unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo;
10486
10487</pre>
10488
10489<p>
10490
10491
10492
10493
10494
10495
10496
10497<HR>
10498<SMALL CLASS="footer">
10499Last update:
10500Thu Mar 21 12:58:59 BRT 2013
10501</SMALL>
10502<!--
10503Last change: revised for Lua 5.2.2
10504-->
10505
10506</body></html>
10507