1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
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">
15
<a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
16
Lua 5.2 Reference Manual
19
by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
22
Copyright © 2011–2013 Lua.org, PUC-Rio.
23
Freely available under the terms of the
24
<a href="http://www.lua.org/license.html">Lua license</a>.
29
<a href="contents.html#contents">contents</A>
31
<a href="contents.html#index">index</A>
33
<!-- ====================================================================== -->
36
<!-- $Id: manual.of,v 1.103 2013/03/14 18:51:56 roberto Exp $ -->
41
<h1>1 – <a name="1">Introduction</a></h1>
44
Lua is an extension programming language designed to support
45
general procedural programming with data description
47
It also offers good support for object-oriented programming,
48
functional programming, and data-driven programming.
49
Lua is intended to be used as a powerful, lightweight,
50
embeddable scripting language for any program that needs one.
51
Lua is implemented as a library, written in <em>clean C</em>,
52
the common subset of Standard C and C++.
56
Being an extension language, Lua has no notion of a "main" program:
57
it only works <em>embedded</em> in a host client,
58
called the <em>embedding program</em> or simply the <em>host</em>.
59
The host program can invoke functions to execute a piece of Lua code,
60
can write and read Lua variables,
61
and can register C functions to be called by Lua code.
62
Through the use of C functions, Lua can be augmented to cope with
63
a wide range of different domains,
64
thus creating customized programming languages sharing a syntactical framework.
65
The Lua distribution includes a sample host program called <code>lua</code>,
66
which uses the Lua library to offer a complete, standalone Lua interpreter,
67
for interactive or batch use.
72
and is provided as usual with no guarantees,
73
as stated in its license.
74
The implementation described in this manual is available
75
at Lua's official web site, <code>www.lua.org</code>.
79
Like any other reference manual,
80
this document is dry in places.
81
For a discussion of the decisions behind the design of Lua,
82
see the technical papers available at Lua's web site.
83
For a detailed introduction to programming in Lua,
84
see Roberto's book, <em>Programming in Lua</em>.
88
<h1>2 – <a name="2">Basic Concepts</a></h1>
91
This section describes the basic concepts of the language.
95
<h2>2.1 – <a name="2.1">Values and Types</a></h2>
98
Lua is a <em>dynamically typed language</em>.
100
variables do not have types; only values do.
101
There are no type definitions in the language.
102
All values carry their own type.
106
All values in Lua are <em>first-class values</em>.
107
This means that all values can be stored in variables,
108
passed as arguments to other functions, and returned as results.
112
There 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>,
117
whose main property is to be different from any other value;
118
it 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>.
120
Both <b>nil</b> and <b>false</b> make a condition false;
121
any other value makes it true.
122
<em>Number</em> represents real (double-precision floating-point) numbers.
123
Operations on numbers follow the same rules of
124
the underlying C implementation,
125
which, in turn, usually follows the IEEE 754 standard.
126
(It is easy to build Lua interpreters that use other
127
internal representations for numbers,
128
such as single-precision floats or long integers;
129
see file <code>luaconf.h</code>.)
130
<em>String</em> represents immutable sequences of bytes.
133
strings can contain any 8-bit value,
134
including embedded zeros ('<code>\0</code>').
138
Lua can call (and manipulate) functions written in Lua and
139
functions written in C
140
(see <a href="#3.4.9">§3.4.9</a>).
144
The type <em>userdata</em> is provided to allow arbitrary C data to
145
be stored in Lua variables.
146
A userdata value is a pointer to a block of raw memory.
147
There are two kinds of userdata:
148
full userdata, where the block of memory is managed by Lua,
149
and light userdata, where the block of memory is managed by the host.
150
Userdata has no predefined operations in Lua,
151
except assignment and identity test.
152
By using <em>metatables</em>,
153
the programmer can define operations for full userdata values
154
(see <a href="#2.4">§2.4</a>).
155
Userdata values cannot be created or modified in Lua,
156
only through the C API.
157
This guarantees the integrity of data owned by the host program.
161
The type <em>thread</em> represents independent threads of execution
162
and it is used to implement coroutines (see <a href="#2.6">§2.6</a>).
163
Do not confuse Lua threads with operating-system threads.
164
Lua supports coroutines on all systems,
165
even those that do not support threads.
169
The type <em>table</em> implements associative arrays,
170
that is, arrays that can be indexed not only with numbers,
171
but with any Lua value except <b>nil</b> and NaN
172
(<em>Not a Number</em>, a special numeric value used to represent
173
undefined or unrepresentable results, such as <code>0/0</code>).
174
Tables can be <em>heterogeneous</em>;
175
that is, they can contain values of all types (except <b>nil</b>).
176
Any key with value <b>nil</b> is not considered part of the table.
177
Conversely, any key that is not part of a table has
178
an associated value <b>nil</b>.
182
Tables are the sole data structuring mechanism in Lua;
183
they can be used to represent ordinary arrays, sequences,
184
symbol tables, sets, records, graphs, trees, etc.
185
To represent records, Lua uses the field name as an index.
186
The language supports this representation by
187
providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
188
There are several convenient ways to create tables in Lua
189
(see <a href="#3.4.8">§3.4.8</a>).
193
We use the term <em>sequence</em> to denote a table where
194
the set of all positive numeric keys is equal to <em>{1..n}</em>
195
for some integer <em>n</em>,
196
which is called the length of the sequence (see <a href="#3.4.6">§3.4.6</a>).
201
the values of table fields can be of any type.
203
because functions are first-class values,
204
table fields can contain functions.
205
Thus tables can also carry <em>methods</em> (see <a href="#3.4.10">§3.4.10</a>).
209
The indexing of tables follows
210
the definition of raw equality in the language.
211
The expressions <code>a[i]</code> and <code>a[j]</code>
212
denote the same table element
213
if and only if <code>i</code> and <code>j</code> are raw equal
214
(that is, equal without metamethods).
218
Tables, functions, threads, and (full) userdata values are <em>objects</em>:
219
variables do not actually <em>contain</em> these values,
220
only <em>references</em> to them.
221
Assignment, parameter passing, and function returns
222
always manipulate references to such values;
223
these operations do not imply any kind of copy.
227
The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
228
of a given value (see <a href="#6.1">§6.1</a>).
234
<h2>2.2 – <a name="2.2">Environments and the Global Environment</a></h2>
237
As will be discussed in <a href="#3.2">§3.2</a> and <a href="#3.3.3">§3.3.3</a>,
238
any reference to a global name <code>var</code> is syntactically translated
239
to <code>_ENV.var</code>.
240
Moreover, every chunk is compiled in the scope of
241
an external local variable called <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>),
242
so <code>_ENV</code> itself is never a global name in a chunk.
246
Despite the existence of this external <code>_ENV</code> variable and
247
the translation of global names,
248
<code>_ENV</code> is a completely regular name.
250
you can define new variables and parameters with that name.
251
Each reference to a global name uses the <code>_ENV</code> that is
252
visible at that point in the program,
253
following the usual visibility rules of Lua (see <a href="#3.5">§3.5</a>).
257
Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
261
Lua keeps a distinguished environment called the <em>global environment</em>.
262
This value is kept at a special index in the C registry (see <a href="#4.5">§4.5</a>).
263
In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
267
When Lua compiles a chunk,
268
it initializes the value of its <code>_ENV</code> upvalue
269
with the global environment (see <a href="#pdf-load"><code>load</code></a>).
270
Therefore, by default,
271
global variables in Lua code refer to entries in the global environment.
272
Moreover, all standard libraries are loaded in the global environment
273
and several functions there operate on that environment.
274
You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
275
to load a chunk with a different environment.
276
(In C, you have to load the chunk and then change the value
277
of its first upvalue.)
281
If you change the global environment in the registry
282
(through C code or the debug library),
283
all chunks loaded after the change will get the new environment.
284
Previously loaded chunks are not affected, however,
285
as each has its own reference to the environment in its <code>_ENV</code> variable.
286
Moreover, the variable <a href="#pdf-_G"><code>_G</code></a>
287
(which is stored in the original global environment)
288
is never updated by Lua.
294
<h2>2.3 – <a name="2.3">Error Handling</a></h2>
297
Because Lua is an embedded extension language,
298
all Lua actions start from C code in the host program
299
calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
300
Whenever an error occurs during
301
the compilation or execution of a Lua chunk,
302
control returns to the host,
303
which can take appropriate measures
304
(such as printing an error message).
308
Lua code can explicitly generate an error by calling the
309
<a href="#pdf-error"><code>error</code></a> function.
310
If you need to catch errors in Lua,
311
you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
312
to call a given function in <em>protected mode</em>.
316
Whenever there is an error,
317
an <em>error object</em> (also called an <em>error message</em>)
318
is propagated with information about the error.
319
Lua itself only generates errors where the error object is a string,
320
but programs may generate errors with
321
any value for the error object.
325
When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
326
you may give a <em>message handler</em>
327
to be called in case of errors.
328
This function is called with the original error message
329
and returns a new error message.
330
It is called before the error unwinds the stack,
331
so that it can gather more information about the error,
332
for instance by inspecting the stack and creating a stack traceback.
333
This message handler is still protected by the protected call;
334
so, an error inside the message handler
335
will call the message handler again.
336
If this loop goes on, Lua breaks it and returns an appropriate message.
342
<h2>2.4 – <a name="2.4">Metatables and Metamethods</a></h2>
345
Every value in Lua can have a <em>metatable</em>.
346
This <em>metatable</em> is an ordinary Lua table
347
that defines the behavior of the original value
348
under certain special operations.
349
You can change several aspects of the behavior
350
of operations over a value by setting specific fields in its metatable.
351
For instance, when a non-numeric value is the operand of an addition,
352
Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
354
Lua calls this function to perform the addition.
358
The keys in a metatable are derived from the <em>event</em> names;
359
the corresponding values are called <em>metamethods</em>.
360
In the previous example, the event is <code>"add"</code>
361
and the metamethod is the function that performs the addition.
365
You can query the metatable of any value
366
using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
370
You can replace the metatable of tables
371
using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
372
You cannot change the metatable of other types from Lua
373
(except by using the debug library);
374
you must use the C API for that.
378
Tables and full userdata have individual metatables
379
(although multiple tables and userdata can share their metatables).
380
Values of all other types share one single metatable per type;
381
that is, there is one single metatable for all numbers,
382
one for all strings, etc.
383
By default, a value has no metatable,
384
but the string library sets a metatable for the string type (see <a href="#6.4">§6.4</a>).
388
A metatable controls how an object behaves in arithmetic operations,
389
order comparisons, concatenation, length operation, and indexing.
390
A metatable also can define a function to be called
391
when a userdata or a table is garbage collected.
392
When Lua performs one of these operations over a value,
393
it checks whether this value has a metatable with the corresponding event.
394
If so, the value associated with that key (the metamethod)
395
controls how Lua will perform the operation.
399
Metatables control the operations listed next.
400
Each operation is identified by its corresponding name.
401
The key for each operation is a string with its name prefixed by
402
two underscores, '<code>__</code>';
403
for instance, the key for operation "add" is the
404
string "<code>__add</code>".
408
The semantics of these operations is better explained by a Lua function
409
describing how the interpreter executes the operation.
410
The code shown here in Lua is only illustrative;
411
the real behavior is hard coded in the interpreter
412
and it is much more efficient than this simulation.
413
All functions used in these descriptions
414
(<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
415
are described in <a href="#6.1">§6.1</a>.
416
In particular, to retrieve the metamethod of a given object,
417
we use the expression
420
metatable(obj)[event]
422
This should be read as
425
rawget(getmetatable(obj) or {}, event)
427
This means that the access to a metamethod does not invoke other metamethods,
428
and access to objects with no metatables does not fail
429
(it simply results in <b>nil</b>).
433
For the unary <code>-</code> and <code>#</code> operators,
434
the metamethod is called with a dummy second argument.
435
This extra argument is only to simplify Lua's internals;
436
it may be removed in future versions and therefore it is not present
437
in the following code.
438
(For most uses this extra argument is irrelevant.)
445
the <code>+</code> operation.
450
The function <code>getbinhandler</code> below defines how Lua chooses a handler
451
for a binary operation.
452
First, Lua tries the first operand.
453
If its type does not define a handler for the operation,
454
then Lua tries the second operand.
457
function getbinhandler (op1, op2, event)
458
return metatable(op1)[event] or metatable(op2)[event]
461
By using this function,
462
the behavior of the <code>op1 + op2</code> is
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")
472
-- call the handler with both operands
474
else -- no handler available: default behavior
475
error(···)
483
the <code>-</code> operation.
485
Behavior similar to the "add" operation.
489
the <code>*</code> operation.
491
Behavior similar to the "add" operation.
495
the <code>/</code> operation.
497
Behavior similar to the "add" operation.
501
the <code>%</code> operation.
503
Behavior similar to the "add" operation,
505
<code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
509
the <code>^</code> (exponentiation) operation.
511
Behavior similar to the "add" operation,
512
with the function <code>pow</code> (from the C math library)
513
as the primitive operation.
517
the unary <code>-</code> operation.
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
529
-- call the handler with the operand
531
else -- no handler available: default behavior
532
error(···)
539
<li><b>"concat": </b>
540
the <code>..</code> (concatenation) operation.
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
549
local h = getbinhandler(op1, op2, "__concat")
553
error(···)
561
the <code>#</code> operation.
565
function len_event (op)
566
if type(op) == "string" then
567
return strlen(op) -- primitive string length
569
local h = metatable(op).__len
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(···)
580
See <a href="#3.4.6">§3.4.6</a> for a description of the length of a table.
584
the <code>==</code> operation.
586
The function <code>getequalhandler</code> defines how Lua chooses a metamethod
588
A metamethod is selected only when both values
589
being compared have the same type
590
and the same metamethod for the selected operation,
591
and the values are either tables or full userdata.
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
599
local mm1 = metatable(op1).__eq
600
local mm2 = metatable(op2).__eq
601
if mm1 == mm2 then return mm1 else return nil end
604
The "eq" event is defined as follows:
607
function eq_event (op1, op2)
608
if op1 == op2 then -- primitive equal?
609
return true -- values are equal
612
local h = getequalhandler(op1, op2)
614
return not not h(op1, op2)
620
Note that the result is always a boolean.
624
the <code><</code> operation.
628
function lt_event (op1, op2)
629
if type(op1) == "number" and type(op2) == "number" then
630
return op1 < op2 -- numeric comparison
631
elseif type(op1) == "string" and type(op2) == "string" then
632
return op1 < op2 -- lexicographic comparison
634
local h = getbinhandler(op1, op2, "__lt")
636
return not not h(op1, op2)
638
error(···)
643
Note that the result is always a boolean.
647
the <code><=</code> operation.
651
function le_event (op1, op2)
652
if type(op1) == "number" and type(op2) == "number" then
653
return op1 <= op2 -- numeric comparison
654
elseif type(op1) == "string" and type(op2) == "string" then
655
return op1 <= op2 -- lexicographic comparison
657
local h = getbinhandler(op1, op2, "__le")
659
return not not h(op1, op2)
661
h = getbinhandler(op1, op2, "__lt")
663
return not h(op2, op1)
665
error(···)
671
Note that, in the absence of a "le" metamethod,
672
Lua tries the "lt", assuming that <code>a <= b</code> is
673
equivalent to <code>not (b < a)</code>.
677
As with the other comparison operators,
678
the result is always a boolean.
682
The indexing access <code>table[key]</code>.
683
Note that the metamethod is tried only
684
when <code>key</code> is not present in <code>table</code>.
685
(When <code>table</code> is not a table,
686
no key is ever present,
687
so the metamethod is always tried.)
691
function gettable_event (table, key)
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
700
h = metatable(table).__index
702
error(···)
705
if type(h) == "function" then
706
return (h(table, key)) -- call the handler
707
else return h[key] -- or repeat operation on it
713
<li><b>"newindex": </b>
714
The indexing assignment <code>table[key] = value</code>.
715
Note that the metamethod is tried only
716
when <code>key</code> is not present in <code>table</code>.
720
function settable_event (table, key, value)
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
729
h = metatable(table).__newindex
731
error(···)
734
if type(h) == "function" then
735
h(table, key,value) -- call the handler
736
else h[key] = value -- or repeat operation on it
743
called when Lua calls a value.
747
function function_event (func, ...)
748
if type(func) == "function" then
749
return func(...) -- primitive call
751
local h = metatable(func).__call
755
error(···)
767
<h2>2.5 – <a name="2.5">Garbage Collection</a></h2>
770
Lua performs automatic memory management.
772
you have to worry neither about allocating memory for new objects
773
nor about freeing it when the objects are no longer needed.
774
Lua manages memory automatically by running
775
a <em>garbage collector</em> to collect all <em>dead objects</em>
776
(that is, objects that are no longer accessible from Lua).
777
All memory used by Lua is subject to automatic management:
778
strings, tables, userdata, functions, threads, internal structures, etc.
782
Lua implements an incremental mark-and-sweep collector.
783
It uses two numbers to control its garbage-collection cycles:
784
the <em>garbage-collector pause</em> and
785
the <em>garbage-collector step multiplier</em>.
786
Both use percentage points as units
787
(e.g., a value of 100 means an internal value of 1).
791
The garbage-collector pause
792
controls how long the collector waits before starting a new cycle.
793
Larger values make the collector less aggressive.
794
Values smaller than 100 mean the collector will not wait to
796
A value of 200 means that the collector waits for the total memory in use
797
to double before starting a new cycle.
801
The garbage-collector step multiplier
802
controls the relative speed of the collector relative to
804
Larger values make the collector more aggressive but also increase
805
the size of each incremental step.
806
Values smaller than 100 make the collector too slow and
807
can result in the collector never finishing a cycle.
809
which means that the collector runs at "twice"
810
the speed of memory allocation.
814
If you set the step multiplier to a very large number
815
(larger than 10% of the maximum number of
816
bytes that the program may use),
817
the collector behaves like a stop-the-world collector.
818
If you then set the pause to 200,
819
the collector behaves as in old Lua versions,
820
doing a complete collection every time Lua doubles its
825
You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
826
or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
827
You can also use these functions to control
828
the collector directly (e.g., stop and restart it).
832
As an experimental feature in Lua 5.2,
833
you can change the collector's operation mode
834
from incremental to <em>generational</em>.
835
A <em>generational collector</em> assumes that most objects die young,
836
and therefore it traverses only young (recently created) objects.
837
This behavior can reduce the time used by the collector,
838
but also increases memory usage (as old dead objects may accumulate).
839
To mitigate this second problem,
840
from time to time the generational collector performs a full collection.
841
Remember that this is an experimental feature;
842
you are welcome to try it,
843
but check your gains.
847
<h3>2.5.1 – <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
850
You can set garbage-collector metamethods for tables
851
and, using the C API,
852
for full userdata (see <a href="#2.4">§2.4</a>).
853
These metamethods are also called <em>finalizers</em>.
854
Finalizers allow you to coordinate Lua's garbage collection
855
with external resource management
856
(such as closing files, network or database connections,
857
or freeing your own memory).
861
For an object (table or userdata) to be finalized when collected,
862
you must <em>mark</em> it for finalization.
864
You mark an object for finalization when you set its metatable
865
and the metatable has a field indexed by the string "<code>__gc</code>".
866
Note that if you set a metatable without a <code>__gc</code> field
867
and later create that field in the metatable,
868
the object will not be marked for finalization.
869
However, after an object is marked,
870
you can freely change the <code>__gc</code> field of its metatable.
874
When a marked object becomes garbage,
875
it is not collected immediately by the garbage collector.
876
Instead, Lua puts it in a list.
877
After the collection,
878
Lua does the equivalent of the following function
879
for each object in that list:
882
function gc_event (obj)
883
local h = metatable(obj).__gc
884
if type(h) == "function" then
891
At the end of each garbage-collection cycle,
892
the finalizers for objects are called in
893
the reverse order that they were marked for collection,
894
among those collected in that cycle;
895
that is, the first finalizer to be called is the one associated
896
with the object marked last in the program.
897
The execution of each finalizer may occur at any point during
898
the execution of the regular code.
902
Because the object being collected must still be used by the finalizer,
903
it (and other objects accessible only through it)
904
must be <em>resurrected</em> by Lua.
905
Usually, this resurrection is transient,
906
and the object memory is freed in the next garbage-collection cycle.
907
However, if the finalizer stores the object in some global place
908
(e.g., a global variable),
909
then there is a permanent resurrection.
911
the object memory is freed only when it becomes completely inaccessible;
912
its finalizer will never be called twice.
916
When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
917
Lua calls the finalizers of all objects marked for finalization,
918
following the reverse order that they were marked.
919
If any finalizer marks new objects for collection during that phase,
920
these new objects will not be finalized.
926
<h3>2.5.2 – <a name="2.5.2">Weak Tables</a></h3>
929
A <em>weak table</em> is a table whose elements are
930
<em>weak references</em>.
931
A weak reference is ignored by the garbage collector.
933
if the only references to an object are weak references,
934
then the garbage collector will collect that object.
938
A weak table can have weak keys, weak values, or both.
939
A table with weak keys allows the collection of its keys,
940
but prevents the collection of its values.
941
A table with both weak keys and weak values allows the collection of
942
both keys and values.
943
In any case, if either the key or the value is collected,
944
the whole pair is removed from the table.
945
The weakness of a table is controlled by the
946
<code>__mode</code> field of its metatable.
947
If the <code>__mode</code> field is a string containing the character '<code>k</code>',
948
the keys in the table are weak.
949
If <code>__mode</code> contains '<code>v</code>',
950
the values in the table are weak.
954
A table with weak keys and strong values
955
is also called an <em>ephemeron table</em>.
956
In an ephemeron table,
957
a value is considered reachable only if its key is reachable.
959
if the only reference to a key comes through its value,
964
Any change in the weakness of a table may take effect only
965
at the next collect cycle.
966
In particular, if you change the weakness to a stronger mode,
967
Lua may still collect some items from that table
968
before the change takes effect.
972
Only objects that have an explicit construction
973
are removed from weak tables.
974
Values, such as numbers and light C functions,
975
are not subject to garbage collection,
976
and therefore are not removed from weak tables
977
(unless its associated value is collected).
978
Although strings are subject to garbage collection,
979
they do not have an explicit construction,
980
and therefore are not removed from weak tables.
985
(that is, objects being finalized
986
and objects accessible only through objects being finalized)
987
have a special behavior in weak tables.
988
They are removed from weak values before running their finalizers,
989
but are removed from weak keys only in the next collection
990
after running their finalizers, when such objects are actually freed.
991
This behavior allows the finalizer to access properties
992
associated with the object through weak tables.
996
If a weak table is among the resurrected objects in a collection cycle,
997
it may not be properly cleared until the next cycle.
1005
<h2>2.6 – <a name="2.6">Coroutines</a></h2>
1008
Lua supports coroutines,
1009
also called <em>collaborative multithreading</em>.
1010
A coroutine in Lua represents an independent thread of execution.
1011
Unlike threads in multithread systems, however,
1012
a coroutine only suspends its execution by explicitly calling
1017
You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
1018
Its sole argument is a function
1019
that is the main function of the coroutine.
1020
The <code>create</code> function only creates a new coroutine and
1021
returns a handle to it (an object of type <em>thread</em>);
1022
it does not start the coroutine.
1026
You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1027
When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
1028
passing as its first argument
1029
a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1030
the coroutine starts its execution,
1031
at the first line of its main function.
1032
Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
1033
to the coroutine main function.
1034
After the coroutine starts running,
1035
it runs until it terminates or <em>yields</em>.
1039
A coroutine can terminate its execution in two ways:
1040
normally, when its main function returns
1041
(explicitly or implicitly, after the last instruction);
1042
and abnormally, if there is an unprotected error.
1043
In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1044
plus any values returned by the coroutine main function.
1045
In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1046
plus an error message.
1050
A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1051
When a coroutine yields,
1052
the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
1053
even if the yield happens inside nested function calls
1054
(that is, not in the main function,
1055
but in a function directly or indirectly called by the main function).
1056
In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
1057
plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
1058
The next time you resume the same coroutine,
1059
it continues its execution from the point where it yielded,
1060
with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
1061
arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
1065
Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1066
the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
1067
but instead of returning the coroutine itself,
1068
it returns a function that, when called, resumes the coroutine.
1069
Any arguments passed to this function
1070
go 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>,
1072
except the first one (the boolean error code).
1073
Unlike <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;
1075
any error is propagated to the caller.
1079
As an example of how coroutines work,
1080
consider the following code:
1085
return coroutine.yield(2*a)
1088
co = coroutine.create(function (a,b)
1089
print("co-body", a, b)
1092
local r, s = coroutine.yield(a+b, a-b)
1093
print("co-body", r, s)
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"))
1102
When you run it, it produces the following output:
1112
main false cannot resume dead coroutine
1116
You can also create and manipulate coroutines through the C API:
1117
see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>,
1118
and <a href="#lua_yield"><code>lua_yield</code></a>.
1124
<h1>3 – <a name="3">The Language</a></h1>
1127
This section describes the lexis, the syntax, and the semantics of Lua.
1129
this section describes
1130
which tokens are valid,
1131
how they can be combined,
1132
and what their combinations mean.
1136
Language constructs will be explained using the usual extended BNF notation,
1138
{<em>a</em>} means 0 or more <em>a</em>'s, and
1139
[<em>a</em>] means an optional <em>a</em>.
1140
Non-terminals are shown like non-terminal,
1141
keywords are shown like <b>kword</b>,
1142
and other terminal symbols are shown like ‘<b>=</b>’.
1143
The complete syntax of Lua can be found in <a href="#9">§9</a>
1144
at the end of this manual.
1148
<h2>3.1 – <a name="3.1">Lexical Conventions</a></h2>
1151
Lua is a free-form language.
1152
It ignores spaces (including new lines) and comments
1153
between lexical elements (tokens),
1154
except as delimiters between names and keywords.
1159
(also called <em>identifiers</em>)
1160
in Lua can be any string of letters,
1161
digits, and underscores,
1162
not beginning with a digit.
1163
Identifiers are used to name variables, table fields, and labels.
1167
The following <em>keywords</em> are reserved
1168
and cannot be used as names:
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
1179
Lua is a case-sensitive language:
1180
<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
1181
are two different, valid names.
1182
As a convention, names starting with an underscore followed by
1183
uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
1184
are reserved for variables used by Lua.
1188
The following strings denote other tokens:
1192
== ~= <= >= < > =
1198
<em>Literal strings</em>
1199
can be delimited by matching single or double quotes,
1200
and 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]),
1210
and '<code>\'</code>' (apostrophe [single quote]).
1211
A backslash followed by a real newline
1212
results in a newline in the string.
1213
The escape sequence '<code>\z</code>' skips the following span
1214
of white-space characters,
1215
including line breaks;
1216
it is particularly useful to break and indent a long literal string
1217
into multiple lines without adding the newlines and spaces
1218
into the string contents.
1222
A byte in a literal string can also be specified by its numerical value.
1223
This can be done with the escape sequence <code>\x<em>XX</em></code>,
1224
where <em>XX</em> is a sequence of exactly two hexadecimal digits,
1225
or with the escape sequence <code>\<em>ddd</em></code>,
1226
where <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,
1228
it must be expressed using exactly three digits.)
1229
Strings in Lua can contain any 8-bit value, including embedded zeros,
1230
which can be specified as '<code>\0</code>'.
1234
Literal strings can also be defined using a long format
1235
enclosed by <em>long brackets</em>.
1236
We define an <em>opening long bracket of level <em>n</em></em> as an opening
1237
square bracket followed by <em>n</em> equal signs followed by another
1238
opening square bracket.
1239
So, an opening long bracket of level 0 is written as <code>[[</code>,
1240
an opening long bracket of level 1 is written as <code>[=[</code>,
1242
A <em>closing long bracket</em> is defined similarly;
1243
for instance, a closing long bracket of level 4 is written as <code>]====]</code>.
1244
A <em>long literal</em> starts with an opening long bracket of any level and
1245
ends at the first closing long bracket of the same level.
1246
It can contain any text except a closing bracket of the proper level.
1247
Literals in this bracketed form can run for several lines,
1248
do not interpret any escape sequences,
1249
and ignore long brackets of any other level.
1250
Any kind of end-of-line sequence
1251
(carriage return, newline, carriage return followed by newline,
1252
or newline followed by carriage return)
1253
is converted to a simple newline.
1257
Any byte in a literal string not
1258
explicitly affected by the previous rules represents itself.
1259
However, Lua opens files for parsing in text mode,
1260
and the system file functions may have problems with
1261
some control characters.
1262
So, it is safer to represent
1263
non-text data as a quoted literal with
1264
explicit escape sequences for non-text characters.
1269
when the opening long bracket is immediately followed by a newline,
1270
the newline is not included in the string.
1271
As an example, in a system using ASCII
1272
(in which '<code>a</code>' is coded as 97,
1273
newline is coded as 10, and '<code>1</code>' is coded as 49),
1274
the five literal strings below denote the same string:
1279
a = '\97lo\10\04923"'
1288
A <em>numerical constant</em> can be written with an optional fractional part
1289
and an optional decimal exponent,
1290
marked by a letter '<code>e</code>' or '<code>E</code>'.
1291
Lua also accepts hexadecimal constants,
1292
which start with <code>0x</code> or <code>0X</code>.
1293
Hexadecimal constants also accept an optional fractional part
1294
plus an optional binary exponent,
1295
marked by a letter '<code>p</code>' or '<code>P</code>'.
1296
Examples of valid numerical constants are
1299
3 3.0 3.1416 314.16e-2 0.31416E1
1300
0xff 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
1304
A <em>comment</em> starts with a double hyphen (<code>--</code>)
1305
anywhere outside a string.
1306
If the text immediately after <code>--</code> is not an opening long bracket,
1307
the comment is a <em>short comment</em>,
1308
which runs until the end of the line.
1309
Otherwise, it is a <em>long comment</em>,
1310
which runs until the corresponding closing long bracket.
1311
Long comments are frequently used to disable code temporarily.
1317
<h2>3.2 – <a name="3.2">Variables</a></h2>
1320
Variables are places that store values.
1321
There are three kinds of variables in Lua:
1322
global variables, local variables, and table fields.
1326
A single name can denote a global variable or a local variable
1327
(or a function's formal parameter,
1328
which is a particular kind of local variable):
1333
Name denotes identifiers, as defined in <a href="#3.1">§3.1</a>.
1337
Any variable name is assumed to be global unless explicitly declared
1338
as a local (see <a href="#3.3.7">§3.3.7</a>).
1339
Local variables are <em>lexically scoped</em>:
1340
local variables can be freely accessed by functions
1341
defined inside their scope (see <a href="#3.5">§3.5</a>).
1345
Before the first assignment to a variable, its value is <b>nil</b>.
1349
Square brackets are used to index a table:
1352
var ::= prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’
1354
The meaning of accesses to table fields can be changed via metatables.
1355
An access to an indexed variable <code>t[i]</code> is equivalent to
1356
a call <code>gettable_event(t,i)</code>.
1357
(See <a href="#2.4">§2.4</a> for a complete description of the
1358
<code>gettable_event</code> function.
1359
This function is not defined or callable in Lua.
1360
We use it here only for explanatory purposes.)
1364
The syntax <code>var.Name</code> is just syntactic sugar for
1365
<code>var["Name"]</code>:
1368
var ::= prefixexp ‘<b>.</b>’ Name
1372
An access to a global variable <code>x</code>
1373
is equivalent to <code>_ENV.x</code>.
1374
Due to the way that chunks are compiled,
1375
<code>_ENV</code> is never a global name (see <a href="#2.2">§2.2</a>).
1381
<h2>3.3 – <a name="3.3">Statements</a></h2>
1384
Lua supports an almost conventional set of statements,
1385
similar to those in Pascal or C.
1387
assignments, control structures, function calls,
1388
and variable declarations.
1392
<h3>3.3.1 – <a name="3.3.1">Blocks</a></h3>
1395
A block is a list of statements,
1396
which are executed sequentially:
1401
Lua has <em>empty statements</em>
1402
that allow you to separate statements with semicolons,
1403
start a block with a semicolon
1404
or write two semicolons in sequence:
1407
stat ::= ‘<b>;</b>’
1411
Function calls and assignments
1412
can start with an open parenthesis.
1413
This possibility leads to an ambiguity in Lua's grammar.
1414
Consider the following fragment:
1418
(print or io.write)('done')
1420
The grammar could see it in two ways:
1423
a = b + c(print or io.write)('done')
1425
a = b + c; (print or io.write)('done')
1427
The current parser always sees such constructions
1429
interpreting the open parenthesis
1430
as the start of the arguments to a call.
1431
To avoid this ambiguity,
1432
it is a good practice to always precede with a semicolon
1433
statements that start with a parenthesis:
1436
;(print or io.write)('done')
1440
A block can be explicitly delimited to produce a single statement:
1443
stat ::= <b>do</b> block <b>end</b>
1445
Explicit blocks are useful
1446
to control the scope of variable declarations.
1447
Explicit blocks are also sometimes used to
1448
add a <b>return</b> statement in the middle
1449
of another block (see <a href="#3.3.4">§3.3.4</a>).
1455
<h3>3.3.2 – <a name="3.3.2">Chunks</a></h3>
1458
The unit of compilation of Lua is called a <em>chunk</em>.
1460
a chunk is simply a block:
1467
Lua handles a chunk as the body of an anonymous function
1468
with a variable number of arguments
1469
(see <a href="#3.4.10">§3.4.10</a>).
1470
As such, chunks can define local variables,
1471
receive arguments, and return values.
1472
Moreover, such anonymous function is compiled as in the
1473
scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">§2.2</a>).
1474
The resulting function always has <code>_ENV</code> as its only upvalue,
1475
even if it does not use that variable.
1479
A chunk can be stored in a file or in a string inside the host program.
1481
Lua first precompiles the chunk into instructions for a virtual machine,
1482
and then it executes the compiled code
1483
with an interpreter for the virtual machine.
1487
Chunks can also be precompiled into binary form;
1488
see program <code>luac</code> for details.
1489
Programs in source and compiled forms are interchangeable;
1490
Lua automatically detects the file type and acts accordingly.
1497
<h3>3.3.3 – <a name="3.3.3">Assignment</a></h3>
1500
Lua allows multiple assignments.
1501
Therefore, the syntax for assignment
1502
defines a list of variables on the left side
1503
and a list of expressions on the right side.
1504
The elements in both lists are separated by commas:
1507
stat ::= varlist ‘<b>=</b>’ explist
1508
varlist ::= var {‘<b>,</b>’ var}
1509
explist ::= exp {‘<b>,</b>’ exp}
1511
Expressions are discussed in <a href="#3.4">§3.4</a>.
1515
Before the assignment,
1516
the list of values is <em>adjusted</em> to the length of
1517
the list of variables.
1518
If there are more values than needed,
1519
the excess values are thrown away.
1520
If there are fewer values than needed,
1521
the list is extended with as many <b>nil</b>'s as needed.
1522
If the list of expressions ends with a function call,
1523
then all values returned by that call enter the list of values,
1524
before the adjustment
1525
(except when the call is enclosed in parentheses; see <a href="#3.4">§3.4</a>).
1529
The assignment statement first evaluates all its expressions
1530
and only then are the assignments performed.
1537
sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
1538
because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
1539
before it is assigned 4.
1545
exchanges the values of <code>x</code> and <code>y</code>,
1551
cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>.
1555
The meaning of assignments to global variables
1556
and table fields can be changed via metatables.
1557
An 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">§2.4</a> for a complete description of the
1560
<code>settable_event</code> function.
1561
This function is not defined or callable in Lua.
1562
We use it here only for explanatory purposes.)
1566
An assignment to a global variable <code>x = val</code>
1567
is equivalent to the assignment
1568
<code>_ENV.x = val</code> (see <a href="#2.2">§2.2</a>).
1574
<h3>3.3.4 – <a name="3.3.4">Control Structures</a></h3><p>
1575
The control structures
1576
<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
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>
1587
Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">§3.3.5</a>).
1591
The condition expression of a
1592
control structure can return any value.
1593
Both <b>false</b> and <b>nil</b> are considered false.
1594
All 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).
1599
In the <b>repeat</b>–<b>until</b> loop,
1600
the inner block does not end at the <b>until</b> keyword,
1601
but only after the condition.
1602
So, the condition can refer to local variables
1603
declared inside the loop block.
1607
The <b>goto</b> statement transfers the program control to a label.
1608
For syntactical reasons,
1609
labels in Lua are considered statements too:
1614
stat ::= <b>goto</b> Name
1616
label ::= ‘<b>::</b>’ Name ‘<b>::</b>’
1620
A label is visible in the entire block where it is defined,
1622
inside nested blocks where a label with the same name is defined and
1623
inside nested functions.
1624
A goto may jump to any visible label as long as it does not
1625
enter into the scope of a local variable.
1629
Labels and empty statements are called <em>void statements</em>,
1630
as they perform no actions.
1634
The <b>break</b> statement terminates the execution of a
1635
<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
1636
skipping to the next statement after the loop:
1640
stat ::= <b>break</b>
1642
A <b>break</b> ends the innermost enclosing loop.
1646
The <b>return</b> statement is used to return values
1647
from a function or a chunk (which is a function in disguise).
1649
Functions can return more than one value,
1650
so the syntax for the <b>return</b> statement is
1653
stat ::= <b>return</b> [explist] [‘<b>;</b>’]
1657
The <b>return</b> statement can only be written
1658
as the last statement of a block.
1659
If it is really necessary to <b>return</b> in the middle of a block,
1660
then an explicit inner block can be used,
1661
as in the idiom <code>do return end</code>,
1662
because now <b>return</b> is the last statement in its (inner) block.
1668
<h3>3.3.5 – <a name="3.3.5">For Statement</a></h3>
1672
The <b>for</b> statement has two forms:
1673
one numeric and one generic.
1677
The numeric <b>for</b> loop repeats a block of code while a
1678
control variable runs through an arithmetic progression.
1679
It has the following syntax:
1682
stat ::= <b>for</b> Name ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ exp] <b>do</b> block <b>end</b>
1684
The <em>block</em> is repeated for <em>name</em> starting at the value of
1685
the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
1687
More precisely, a <b>for</b> statement like
1690
for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end
1692
is equivalent to the code:
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> > 0 and <em>var</em> <= <em>limit</em>) or (<em>step</em> <= 0 and <em>var</em> >= <em>limit</em>) do
1699
local v = <em>var</em>
1701
<em>var</em> = <em>var</em> + <em>step</em>
1710
All three control expressions are evaluated only once,
1711
before the loop starts.
1712
They must all result in numbers.
1716
<code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables.
1717
The names shown here are for explanatory purposes only.
1721
If the third expression (the step) is absent,
1722
then a step of 1 is used.
1726
You can use <b>break</b> to exit a <b>for</b> loop.
1730
The loop variable <code>v</code> is local to the loop;
1731
you cannot use its value after the <b>for</b> ends or is broken.
1732
If you need this value,
1733
assign it to another variable before breaking or exiting the loop.
1739
The generic <b>for</b> statement works over functions,
1740
called <em>iterators</em>.
1741
On each iteration, the iterator function is called to produce a new value,
1742
stopping when this new value is <b>nil</b>.
1743
The generic <b>for</b> loop has the following syntax:
1746
stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b>
1747
namelist ::= Name {‘<b>,</b>’ Name}
1749
A <b>for</b> statement like
1752
for <em>var_1</em>, ···, <em>var_n</em> in <em>explist</em> do <em>block</em> end
1754
is equivalent to the code:
1758
local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em>
1760
local <em>var_1</em>, ···, <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>
1772
<code><em>explist</em></code> is evaluated only once.
1773
Its results are an <em>iterator</em> function,
1775
and an initial value for the first <em>iterator variable</em>.
1779
<code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables.
1780
The names are here for explanatory purposes only.
1784
You can use <b>break</b> to exit a <b>for</b> loop.
1788
The loop variables <code><em>var_i</em></code> are local to the loop;
1789
you cannot use their values after the <b>for</b> ends.
1790
If you need these values,
1791
then assign them to other variables before breaking or exiting the loop.
1799
<h3>3.3.6 – <a name="3.3.6">Function Calls as Statements</a></h3><p>
1800
To allow possible side-effects,
1801
function calls can be executed as statements:
1804
stat ::= functioncall
1806
In this case, all returned values are thrown away.
1807
Function calls are explained in <a href="#3.4.9">§3.4.9</a>.
1813
<h3>3.3.7 – <a name="3.3.7">Local Declarations</a></h3><p>
1814
Local variables can be declared anywhere inside a block.
1815
The declaration can include an initial assignment:
1818
stat ::= <b>local</b> namelist [‘<b>=</b>’ explist]
1820
If present, an initial assignment has the same semantics
1821
of a multiple assignment (see <a href="#3.3.3">§3.3.3</a>).
1822
Otherwise, all variables are initialized with <b>nil</b>.
1826
A chunk is also a block (see <a href="#3.3.2">§3.3.2</a>),
1827
and so local variables can be declared in a chunk outside any explicit block.
1831
The visibility rules for local variables are explained in <a href="#3.5">§3.5</a>.
1839
<h2>3.4 – <a name="3.4">Expressions</a></h2>
1842
The basic expressions in Lua are the following:
1846
exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1850
exp ::= tableconstructor
1851
exp ::= ‘<b>...</b>’
1852
exp ::= exp binop exp
1854
prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’
1858
Numbers and literal strings are explained in <a href="#3.1">§3.1</a>;
1859
variables are explained in <a href="#3.2">§3.2</a>;
1860
function definitions are explained in <a href="#3.4.10">§3.4.10</a>;
1861
function calls are explained in <a href="#3.4.9">§3.4.9</a>;
1862
table constructors are explained in <a href="#3.4.8">§3.4.8</a>.
1864
denoted by three dots ('<code>...</code>'), can only be used when
1865
directly inside a vararg function;
1866
they are explained in <a href="#3.4.10">§3.4.10</a>.
1870
Binary operators comprise arithmetic operators (see <a href="#3.4.1">§3.4.1</a>),
1871
relational operators (see <a href="#3.4.3">§3.4.3</a>), logical operators (see <a href="#3.4.4">§3.4.4</a>),
1872
and the concatenation operator (see <a href="#3.4.5">§3.4.5</a>).
1873
Unary operators comprise the unary minus (see <a href="#3.4.1">§3.4.1</a>),
1874
the unary <b>not</b> (see <a href="#3.4.4">§3.4.4</a>),
1875
and the unary <em>length operator</em> (see <a href="#3.4.6">§3.4.6</a>).
1879
Both function calls and vararg expressions can result in multiple values.
1880
If a function call is used as a statement (see <a href="#3.3.6">§3.3.6</a>),
1881
then its return list is adjusted to zero elements,
1882
thus discarding all returned values.
1883
If an expression is used as the last (or the only) element
1884
of a list of expressions,
1885
then no adjustment is made
1886
(unless the expression is enclosed in parentheses).
1887
In all other contexts,
1888
Lua adjusts the result list to one element,
1889
either discarding all values except the first one
1890
or adding a single <b>nil</b> if there are no values.
1894
Here are some examples:
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)
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
1916
Any expression enclosed in parentheses always results in only one value.
1918
<code>(f(x,y,z))</code> is always a single value,
1919
even 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>
1921
or <b>nil</b> if <code>f</code> does not return any values.)
1925
<h3>3.4.1 – <a name="3.4.1">Arithmetic Operators</a></h3><p>
1926
Lua supports the usual arithmetic operators:
1927
the binary <code>+</code> (addition),
1928
<code>-</code> (subtraction), <code>*</code> (multiplication),
1929
<code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
1930
and unary <code>-</code> (mathematical negation).
1931
If the operands are numbers, or strings that can be converted to
1932
numbers (see <a href="#3.4.2">§3.4.2</a>),
1933
then all operations have the usual meaning.
1934
Exponentiation works for any exponent.
1935
For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
1936
Modulo is defined as
1939
a % b == a - math.floor(a/b)*b
1941
That is, it is the remainder of a division that rounds
1942
the quotient towards minus infinity.
1948
<h3>3.4.2 – <a name="3.4.2">Coercion</a></h3>
1951
Lua provides automatic conversion between
1952
string and number values at run time.
1953
Any arithmetic operation applied to a string tries to convert
1954
this string to a number, following the rules of the Lua lexer.
1955
(The string may have leading and trailing spaces and a sign.)
1956
Conversely, whenever a number is used where a string is expected,
1957
the number is converted to a string, in a reasonable format.
1958
For complete control over how numbers are converted to strings,
1959
use the <code>format</code> function from the string library
1960
(see <a href="#pdf-string.format"><code>string.format</code></a>).
1966
<h3>3.4.3 – <a name="3.4.3">Relational Operators</a></h3><p>
1967
The relational operators in Lua are
1970
== ~= < > <= >=
1972
These operators always result in <b>false</b> or <b>true</b>.
1976
Equality (<code>==</code>) first compares the type of its operands.
1977
If the types are different, then the result is <b>false</b>.
1978
Otherwise, the values of the operands are compared.
1979
Numbers and strings are compared in the usual way.
1980
Tables, userdata, and threads
1981
are compared by reference:
1982
two objects are considered equal only if they are the same object.
1983
Every time you create a new object
1984
(a table, userdata, or thread),
1985
this new object is different from any previously existing object.
1986
Closures with the same reference are always equal.
1987
Closures with any detectable difference
1988
(different behavior, different definition) are always different.
1992
You can change the way that Lua compares tables and userdata
1993
by using the "eq" metamethod (see <a href="#2.4">§2.4</a>).
1997
The conversion rules of <a href="#3.4.2">§3.4.2</a>
1998
do not apply to equality comparisons.
1999
Thus, <code>"0"==0</code> evaluates to <b>false</b>,
2000
and <code>t[0]</code> and <code>t["0"]</code> denote different
2005
The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
2009
The order operators work as follows.
2010
If both arguments are numbers, then they are compared as such.
2011
Otherwise, if both arguments are strings,
2012
then their values are compared according to the current locale.
2013
Otherwise, Lua tries to call the "lt" or the "le"
2014
metamethod (see <a href="#2.4">§2.4</a>).
2015
A comparison <code>a > b</code> is translated to <code>b < a</code>
2016
and <code>a >= b</code> is translated to <code>b <= a</code>.
2022
<h3>3.4.4 – <a name="3.4.4">Logical Operators</a></h3><p>
2023
The logical operators in Lua are
2024
<b>and</b>, <b>or</b>, and <b>not</b>.
2025
Like the control structures (see <a href="#3.3.4">§3.3.4</a>),
2026
all logical operators consider both <b>false</b> and <b>nil</b> as false
2027
and anything else as true.
2031
The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
2032
The conjunction operator <b>and</b> returns its first argument
2033
if this value is <b>false</b> or <b>nil</b>;
2034
otherwise, <b>and</b> returns its second argument.
2035
The disjunction operator <b>or</b> returns its first argument
2036
if this value is different from <b>nil</b> and <b>false</b>;
2037
otherwise, <b>or</b> returns its second argument.
2038
Both <b>and</b> and <b>or</b> use short-cut evaluation;
2040
the second operand is evaluated only if necessary.
2041
Here are some examples:
2045
10 or error() --> 10
2046
nil or "a" --> "a"
2047
nil and 10 --> nil
2048
false and error() --> false
2049
false and nil --> false
2050
false or nil --> nil
2054
<code>--></code> indicates the result of the preceding expression.)
2060
<h3>3.4.5 – <a name="3.4.5">Concatenation</a></h3><p>
2061
The string concatenation operator in Lua is
2062
denoted by two dots ('<code>..</code>').
2063
If both operands are strings or numbers, then they are converted to
2064
strings according to the rules mentioned in <a href="#3.4.2">§3.4.2</a>.
2065
Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">§2.4</a>).
2071
<h3>3.4.6 – <a name="3.4.6">The Length Operator</a></h3>
2074
The length operator is denoted by the unary prefix operator <code>#</code>.
2075
The length of a string is its number of bytes
2076
(that is, the usual meaning of string length when each
2077
character is one byte).
2081
A program can modify the behavior of the length operator for
2082
any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">§2.4</a>).
2086
Unless a <code>__len</code> metamethod is given,
2087
the length of a table <code>t</code> is only defined if the
2088
table is a <em>sequence</em>,
2090
the set of its positive numeric keys is equal to <em>{1..n}</em>
2091
for some integer <em>n</em>.
2092
In that case, <em>n</em> is its length.
2093
Note that a table like
2098
is not a sequence, because it has the key <code>4</code>
2099
but 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
2101
to the set of positive numeric keys of that table.)
2102
Note, however, that non-numeric keys do not interfere
2103
with whether a table is a sequence.
2109
<h3>3.4.7 – <a name="3.4.7">Precedence</a></h3><p>
2110
Operator precedence in Lua follows the table below,
2111
from lower to higher priority:
2116
< > <= >= ~= ==
2124
you can use parentheses to change the precedences of an expression.
2125
The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
2126
operators are right associative.
2127
All other binary operators are left associative.
2133
<h3>3.4.8 – <a name="3.4.8">Table Constructors</a></h3><p>
2134
Table constructors are expressions that create tables.
2135
Every time a constructor is evaluated, a new table is created.
2136
A constructor can be used to create an empty table
2137
or to create a table and initialize some of its fields.
2138
The general syntax for constructors is
2141
tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’
2142
fieldlist ::= field {fieldsep field} [fieldsep]
2143
field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp
2144
fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’
2148
Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
2149
with key <code>exp1</code> and value <code>exp2</code>.
2150
A field of the form <code>name = exp</code> is equivalent to
2151
<code>["name"] = exp</code>.
2152
Finally, fields of the form <code>exp</code> are equivalent to
2153
<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
2155
Fields in the other formats do not affect this counting.
2159
a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
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
2172
t[4] = 45 -- 4th exp
2178
If the last field in the list has the form <code>exp</code>
2179
and the expression is a function call or a vararg expression,
2180
then all values returned by this expression enter the list consecutively
2181
(see <a href="#3.4.9">§3.4.9</a>).
2185
The field list can have an optional trailing separator,
2186
as a convenience for machine-generated code.
2192
<h3>3.4.9 – <a name="3.4.9">Function Calls</a></h3><p>
2193
A function call in Lua has the following syntax:
2196
functioncall ::= prefixexp args
2199
first prefixexp and args are evaluated.
2200
If the value of prefixexp has type <em>function</em>,
2201
then this function is called
2202
with the given arguments.
2203
Otherwise, the prefixexp "call" metamethod is called,
2204
having as first parameter the value of prefixexp,
2205
followed by the original call arguments
2206
(see <a href="#2.4">§2.4</a>).
2213
functioncall ::= prefixexp ‘<b>:</b>’ Name args
2215
can be used to call "methods".
2216
A call <code>v:name(<em>args</em>)</code>
2217
is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
2218
except that <code>v</code> is evaluated only once.
2222
Arguments have the following syntax:
2225
args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’
2226
args ::= tableconstructor
2229
All argument expressions are evaluated before the call.
2230
A call of the form <code>f{<em>fields</em>}</code> is
2231
syntactic sugar for <code>f({<em>fields</em>})</code>;
2232
that is, the argument list is a single new table.
2233
A 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>)
2235
is syntactic sugar for <code>f('<em>string</em>')</code>;
2236
that is, the argument list is a single literal string.
2240
A call of the form <code>return <em>functioncall</em></code> is called
2241
a <em>tail call</em>.
2242
Lua implements <em>proper tail calls</em>
2243
(or <em>proper tail recursion</em>):
2245
the called function reuses the stack entry of the calling function.
2246
Therefore, there is no limit on the number of nested tail calls that
2247
a program can execute.
2248
However, a tail call erases any debug information about the
2250
Note that a tail call only happens with a particular syntax,
2251
where the <b>return</b> has one single function call as argument;
2252
this syntax makes the calling function return exactly
2253
the returns of the called function.
2254
So, none of the following examples are tail calls:
2257
return (f(x)) -- results adjusted to 1
2259
return x, f(x) -- additional results
2260
f(x); return -- results discarded
2261
return x or f(x) -- results adjusted to 1
2267
<h3>3.4.10 – <a name="3.4.10">Function Definitions</a></h3>
2270
The syntax for function definition is
2273
functiondef ::= <b>function</b> funcbody
2274
funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b>
2278
The following syntactic sugar simplifies function definitions:
2281
stat ::= <b>function</b> funcname funcbody
2282
stat ::= <b>local</b> <b>function</b> Name funcbody
2283
funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name]
2288
function f () <em>body</em> end
2293
f = function () <em>body</em> end
2298
function t.a.b.c.f () <em>body</em> end
2303
t.a.b.c.f = function () <em>body</em> end
2308
local function f () <em>body</em> end
2313
local f; f = function () <em>body</em> end
2318
local f = function () <em>body</em> end
2320
(This only makes a difference when the body of the function
2321
contains references to <code>f</code>.)
2325
A function definition is an executable expression,
2326
whose value has type <em>function</em>.
2327
When Lua precompiles a chunk,
2328
all its function bodies are precompiled too.
2329
Then, whenever Lua executes the function definition,
2330
the function is <em>instantiated</em> (or <em>closed</em>).
2331
This function instance (or <em>closure</em>)
2332
is the final value of the expression.
2336
Parameters act as local variables that are
2337
initialized with the argument values:
2340
parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’
2342
When a function is called,
2343
the list of arguments is adjusted to
2344
the length of the list of parameters,
2345
unless the function is a <em>vararg function</em>,
2346
which is indicated by three dots ('<code>...</code>')
2347
at the end of its parameter list.
2348
A vararg function does not adjust its argument list;
2349
instead, it collects all extra arguments and supplies them
2350
to the function through a <em>vararg expression</em>,
2351
which is also written as three dots.
2352
The value of this expression is a list of all actual extra arguments,
2353
similar to a function with multiple results.
2354
If a vararg expression is used inside another expression
2355
or in the middle of a list of expressions,
2356
then its return list is adjusted to one element.
2357
If the expression is used as the last element of a list of expressions,
2358
then no adjustment is made
2359
(unless that last expression is enclosed in parentheses).
2363
As an example, consider the following definitions:
2366
function f(a, b) end
2367
function g(a, b, ...) end
2368
function r() return 1,2,3 end
2370
Then, we have the following mapping from arguments to parameters and
2371
to the vararg expression:
2379
f(r(), 10) a=1, b=10
2382
g(3) a=3, b=nil, ... --> (nothing)
2383
g(3, 4) a=3, b=4, ... --> (nothing)
2384
g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
2385
g(5, r()) a=5, b=1, ... --> 2 3
2389
Results are returned using the <b>return</b> statement (see <a href="#3.3.4">§3.3.4</a>).
2390
If control reaches the end of a function
2391
without encountering a <b>return</b> statement,
2392
then the function returns with no results.
2397
There is a system-dependent limit on the number of values
2398
that a function may return.
2399
This limit is guaranteed to be larger than 1000.
2403
The <em>colon</em> syntax
2404
is used for defining <em>methods</em>,
2405
that is, functions that have an implicit extra parameter <code>self</code>.
2409
function t.a.b.c:f (<em>params</em>) <em>body</em> end
2411
is syntactic sugar for
2414
t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
2422
<h2>3.5 – <a name="3.5">Visibility Rules</a></h2>
2426
Lua is a lexically scoped language.
2427
The scope of a local variable begins at the first statement after
2428
its declaration and lasts until the last non-void statement
2429
of the innermost block that includes the declaration.
2430
Consider the following example:
2433
x = 10 -- global variable
2435
local x = x -- new 'x', with value 10
2439
local x = x+1 -- another 'x'
2444
print(x) --> 10 (the global one)
2448
Notice that, in a declaration like <code>local x = x</code>,
2449
the new <code>x</code> being declared is not in scope yet,
2450
and so the second <code>x</code> refers to the outside variable.
2454
Because of the lexical scoping rules,
2455
local variables can be freely accessed by functions
2456
defined inside their scope.
2457
A local variable used by an inner function is called
2458
an <em>upvalue</em>, or <em>external local variable</em>,
2459
inside the inner function.
2463
Notice that each execution of a <b>local</b> statement
2464
defines new local variables.
2465
Consider the following example:
2472
a[i] = function () y=y+1; return x+y end
2475
The loop creates ten closures
2476
(that is, ten instances of the anonymous function).
2477
Each of these closures uses a different <code>y</code> variable,
2478
while all of them share the same <code>x</code>.
2484
<h1>4 – <a name="4">The Application Program Interface</a></h1>
2488
This section describes the C API for Lua, that is,
2489
the set of C functions available to the host program to communicate
2491
All API functions and related types and constants
2492
are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2496
Even when we use the term "function",
2497
any facility in the API may be provided as a macro instead.
2498
Except where stated otherwise,
2499
all such macros use each of their arguments exactly once
2500
(except for the first argument, which is always a Lua state),
2501
and so do not generate any hidden side-effects.
2505
As in most C libraries,
2506
the Lua API functions do not check their arguments for validity or consistency.
2507
However, you can change this behavior by compiling Lua
2508
with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined.
2512
<h2>4.1 – <a name="4.1">The Stack</a></h2>
2515
Lua uses a <em>virtual stack</em> to pass values to and from C.
2516
Each element in this stack represents a Lua value
2517
(<b>nil</b>, number, string, etc.).
2521
Whenever Lua calls C, the called function gets a new stack,
2522
which is independent of previous stacks and of stacks of
2523
C functions that are still active.
2524
This stack initially contains any arguments to the C function
2525
and it is where the C function pushes its results
2526
to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2531
most query operations in the API do not follow a strict stack discipline.
2532
Instead, they can refer to any element in the stack
2533
by using an <em>index</em>:
2534
A positive index represents an absolute stack position
2535
(starting at 1);
2536
a negative index represents an offset relative to the top of the stack.
2537
More specifically, if the stack has <em>n</em> elements,
2538
then index 1 represents the first element
2539
(that is, the element that was pushed onto the stack first)
2541
index <em>n</em> represents the last element;
2542
index -1 also represents the last element
2543
(that is, the element at the top)
2544
and index <em>-n</em> represents the first element.
2550
<h2>4.2 – <a name="4.2">Stack Size</a></h2>
2553
When you interact with the Lua API,
2554
you are responsible for ensuring consistency.
2556
<em>you are responsible for controlling stack overflow</em>.
2557
You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2558
to ensure that the stack has extra slots when pushing new elements.
2562
Whenever Lua calls C,
2563
it 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,
2565
so that usually you do not have to worry about stack space
2566
unless your code has loops pushing elements onto the stack.
2570
When you call a Lua function
2571
without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2572
Lua ensures that the stack has enough size for all results,
2573
but it does not ensure any extra space.
2574
So, before pushing anything in the stack after such a call
2575
you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2581
<h2>4.3 – <a name="4.3">Valid and Acceptable Indices</a></h2>
2584
Any function in the API that receives stack indices
2585
works only with <em>valid indices</em> or <em>acceptable indices</em>.
2589
A <em>valid index</em> is an index that refers to a
2590
real position within the stack, that is,
2591
its position lies between 1 and the stack top
2592
(<code>1 ≤ abs(index) ≤ top</code>).
2594
Usually, functions that can modify the value at an index
2595
require valid indices.
2599
Unless otherwise noted,
2600
any function that accepts valid indices also accepts <em>pseudo-indices</em>,
2601
which represent some Lua values that are accessible to C code
2602
but which are not in the stack.
2603
Pseudo-indices are used to access the registry
2604
and the upvalues of a C function (see <a href="#4.4">§4.4</a>).
2608
Functions that do not need a specific stack position,
2609
but only a value in the stack (e.g., query functions),
2610
can be called with acceptable indices.
2611
An <em>acceptable index</em> can be any valid index,
2612
including the pseudo-indices,
2613
but it also can be any positive index after the stack top
2614
within the space allocated for the stack,
2615
that is, indices up to the stack size.
2616
(Note that 0 is never an acceptable index.)
2617
Except when noted otherwise,
2618
functions in the API work with acceptable indices.
2622
Acceptable indices serve to avoid extra tests
2623
against the stack top when querying the stack.
2624
For instance, a C function can query its third argument
2625
without the need to first check whether there is a third argument,
2626
that is, without the need to check whether 3 is a valid index.
2630
For functions that can be called with acceptable indices,
2631
any non-valid index is treated as if it
2632
contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>,
2633
which behaves like a nil value.
2639
<h2>4.4 – <a name="4.4">C Closures</a></h2>
2642
When a C function is created,
2643
it is possible to associate some values with it,
2644
thus creating a <em>C closure</em>
2645
(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>);
2646
these values are called <em>upvalues</em> and are
2647
accessible to the function whenever it is called.
2651
Whenever a C function is called,
2652
its upvalues are located at specific pseudo-indices.
2653
These pseudo-indices are produced by the macro
2654
<a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2655
The first value associated with a function is at position
2656
<code>lua_upvalueindex(1)</code>, and so on.
2657
Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2658
where <em>n</em> is greater than the number of upvalues of the
2659
current function (but not greater than 256),
2660
produces an acceptable but invalid index.
2666
<h2>4.5 – <a name="4.5">Registry</a></h2>
2669
Lua provides a <em>registry</em>,
2670
a predefined table that can be used by any C code to
2671
store whatever Lua values it needs to store.
2672
The registry table is always located at pseudo-index
2673
<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
2674
which is a valid index.
2675
Any C library can store data into this table,
2676
but it should take care to choose keys
2677
that are different from those used
2678
by other libraries, to avoid collisions.
2679
Typically, you should use as key a string containing your library name,
2680
or a light userdata with the address of a C object in your code,
2681
or any Lua object created by your code.
2682
As with global names,
2683
string keys starting with an underscore followed by
2684
uppercase letters are reserved for Lua.
2688
The integer keys in the registry are used by the reference mechanism,
2689
implemented by the auxiliary library,
2690
and by some predefined values.
2691
Therefore, integer keys should not be used for other purposes.
2695
When you create a new Lua state,
2696
its registry comes with some predefined values.
2697
These predefined values are indexed with integer keys
2698
defined as constants in <code>lua.h</code>.
2699
The following constants are defined:
2702
<li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has
2703
the main thread of the state.
2704
(The main thread is the one created together with the state.)
2707
<li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has
2708
the global environment.
2715
<h2>4.6 – <a name="4.6">Error Handling in C</a></h2>
2718
Internally, 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++;
2720
search for <code>LUAI_THROW</code> in the source code.)
2721
When Lua faces any error
2722
(such as a memory allocation error, type errors, syntax errors,
2724
it <em>raises</em> an error;
2725
that is, it does a long jump.
2726
A <em>protected environment</em> uses <code>setjmp</code>
2727
to set a recovery point;
2728
any error jumps to the most recent active recovery point.
2732
If an error happens outside any protected environment,
2733
Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>)
2734
and then calls <code>abort</code>,
2735
thus exiting the host application.
2736
Your panic function can avoid this exit by
2738
(e.g., doing a long jump to your own recovery point outside Lua).
2742
The panic function runs as if it were a message handler (see <a href="#2.3">§2.3</a>);
2743
in particular, the error message is at the top of the stack.
2744
However, there is no guarantees about stack space.
2745
To push anything on the stack,
2746
the panic function should first check the available space (see <a href="#4.2">§4.2</a>).
2750
Most functions in the API can throw an error,
2751
for instance due to a memory allocation error.
2752
The documentation for each function indicates whether
2753
it can throw errors.
2757
Inside a C function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2763
<h2>4.7 – <a name="4.7">Handling Yields in C</a></h2>
2766
Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2767
Therefore, if a function <code>foo</code> calls an API function
2768
and this API function yields
2769
(directly or indirectly by calling another function that yields),
2770
Lua cannot return to <code>foo</code> any more,
2771
because the <code>longjmp</code> removes its frame from the C stack.
2775
To avoid this kind of problem,
2776
Lua raises an error whenever it tries to yield across an API call,
2777
except 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>.
2779
All those functions receive a <em>continuation function</em>
2780
(as a parameter called <code>k</code>) to continue execution after a yield.
2784
We need to set some terminology to explain continuations.
2785
We have a C function called from Lua which we will call
2786
the <em>original function</em>.
2787
This original function then calls one of those three functions in the C API,
2788
which we will call the <em>callee function</em>,
2789
that then yields the current thread.
2790
(This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
2791
or when the callee function is either <a href="#lua_callk"><code>lua_callk</code></a> or <a href="#lua_pcallk"><code>lua_pcallk</code></a>
2792
and the function called by them yields.)
2796
Suppose the running thread yields while executing the callee function.
2797
After the thread resumes,
2798
it eventually will finish running the callee function.
2800
the callee function cannot return to the original function,
2801
because its frame in the C stack was destroyed by the yield.
2802
Instead, Lua calls a <em>continuation function</em>,
2803
which was given as an argument to the callee function.
2804
As the name implies,
2805
the continuation function should continue the task
2806
of the original function.
2810
Lua treats the continuation function as if it were the original function.
2811
The continuation function receives the same Lua stack
2812
from the original function,
2813
in the same state it would be if the callee function had returned.
2815
after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are
2816
removed from the stack and replaced by the results from the call.)
2817
It also has the same upvalues.
2818
Whatever it returns is handled by Lua as if it were the return
2819
of the original function.
2823
The only difference in the Lua state between the original function
2824
and its continuation is the result of a call to <a href="#lua_getctx"><code>lua_getctx</code></a>.
2830
<h2>4.8 – <a name="4.8">Functions and Types</a></h2>
2833
Here we list all functions and types from the C API in
2835
Each function has an indicator like this:
2836
<span class="apii">[-o, +p, <em>x</em>]</span>
2840
The first field, <code>o</code>,
2841
is how many elements the function pops from the stack.
2842
The second field, <code>p</code>,
2843
is how many elements the function pushes onto the stack.
2844
(Any function always pushes its results after popping its arguments.)
2845
A field in the form <code>x|y</code> means the function can push (or pop)
2846
<code>x</code> or <code>y</code> elements,
2847
depending on the situation;
2848
an interrogation mark '<code>?</code>' means that
2849
we cannot know how many elements the function pops/pushes
2850
by looking only at its arguments
2851
(e.g., they may depend on what is on the stack).
2852
The third field, <code>x</code>,
2853
tells 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.
2860
<hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p>
2861
<span class="apii">[-0, +0, –]</span>
2862
<pre>int lua_absindex (lua_State *L, int idx);</pre>
2865
Converts the acceptable index <code>idx</code> into an absolute index
2866
(that is, one that does not depend on the stack top).
2872
<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2873
<pre>typedef void * (*lua_Alloc) (void *ud,
2876
size_t nsize);</pre>
2879
The type of the memory-allocation function used by Lua states.
2880
The allocator function must provide a
2881
functionality similar to <code>realloc</code>,
2882
but not exactly the same.
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
2888
<code>nsize</code>, the new size of the block.
2892
When <code>ptr</code> is not <code>NULL</code>,
2893
<code>osize</code> is the size of the block pointed by <code>ptr</code>,
2894
that is, the size given when it was allocated or reallocated.
2898
When <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)
2903
Lua is creating a new object of that type.
2904
When <code>osize</code> is some other value,
2905
Lua is allocating memory for something else.
2909
Lua assumes the following behavior from the allocator function:
2913
When <code>nsize</code> is zero,
2914
the allocator should behave like <code>free</code>
2915
and return <code>NULL</code>.
2919
When <code>nsize</code> is not zero,
2920
the allocator should behave like <code>realloc</code>.
2921
The allocator returns <code>NULL</code>
2922
if and only if it cannot fulfill the request.
2923
Lua assumes that the allocator never fails when
2924
<code>osize >= nsize</code>.
2928
Here is a simple implementation for the allocator function.
2929
It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>.
2932
static void *l_alloc (void *ud, void *ptr, size_t osize,
2934
(void)ud; (void)osize; /* not used */
2940
return realloc(ptr, nsize);
2943
Note that Standard C ensures
2944
that <code>free(NULL)</code> has no effect and that
2945
<code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
2946
This code assumes that <code>realloc</code> does not fail when shrinking a block.
2947
(Although Standard C does not ensure this behavior,
2948
it seems to be a safe assumption.)
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>
2959
Performs an arithmetic operation over the two values
2960
(or one, in the case of negation)
2961
at the top of the stack,
2962
with the value at the top being the second operand,
2963
pops these values, and pushes the result of the operation.
2964
The function follows the semantics of the corresponding Lua operator
2965
(that is, it may call metamethods).
2969
The value of <code>op</code> must be one of the following constants:
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>
2986
<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p>
2987
<span class="apii">[-0, +0, –]</span>
2988
<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2991
Sets a new panic function and returns the old one (see <a href="#4.6">§4.6</a>).
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>
3006
To call a function you must use the following protocol:
3007
first, the function to be called is pushed onto the stack;
3008
then, the arguments to the function are pushed
3010
that is, the first argument is pushed first.
3011
Finally 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.
3013
All arguments and the function value are popped from the stack
3014
when the function is called.
3015
The function results are pushed onto the stack when the function returns.
3016
The number of results is adjusted to <code>nresults</code>,
3017
unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
3018
In this case, all results from the function are pushed.
3019
Lua takes care that the returned values fit into the stack space.
3020
The function results are pushed onto the stack in direct order
3021
(the first result is pushed first),
3022
so that after the call the last result is on the top of the stack.
3026
Any error inside the called function is propagated upwards
3027
(with a <code>longjmp</code>).
3031
The following example shows how the host program can do the
3032
equivalent to this Lua code:
3035
a = f("how", t.x, 14)
3037
Here it is in C:
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' */
3049
Note that the code above is "balanced":
3050
at its end, the stack is back to its original configuration.
3051
This is considered good programming practice.
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>
3063
This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
3064
but allows the called function to yield (see <a href="#4.7">§4.7</a>).
3070
<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
3071
<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
3074
Type for C functions.
3078
In order to communicate properly with Lua,
3079
a C function must use the following protocol,
3080
which defines the way parameters and results are passed:
3081
a C function receives its arguments from Lua in its stack
3082
in direct order (the first argument is pushed first).
3083
So, when the function starts,
3084
<code>lua_gettop(L)</code> returns the number of arguments received by the function.
3085
The first argument (if any) is at index 1
3086
and its last argument is at index <code>lua_gettop(L)</code>.
3087
To return values to Lua, a C function just pushes them onto the stack,
3088
in direct order (the first result is pushed first),
3089
and returns the number of results.
3090
Any other value in the stack below the results will be properly
3092
Like a Lua function, a C function called by Lua can also return
3097
As an example, the following function receives a variable number
3098
of numerical arguments and returns their average and sum:
3101
static int foo (lua_State *L) {
3102
int n = lua_gettop(L); /* number of arguments */
3105
for (i = 1; i <= n; i++) {
3106
if (!lua_isnumber(L, i)) {
3107
lua_pushstring(L, "incorrect argument");
3110
sum += lua_tonumber(L, i);
3112
lua_pushnumber(L, sum/n); /* first result */
3113
lua_pushnumber(L, sum); /* second result */
3114
return 2; /* number of results */
3121
<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
3122
<span class="apii">[-0, +0, –]</span>
3123
<pre>int lua_checkstack (lua_State *L, int extra);</pre>
3126
Ensures that there are at least <code>extra</code> free stack slots in the stack.
3127
It returns false if it cannot fulfill the request,
3128
because it would cause the stack to be larger than a fixed maximum size
3129
(typically at least a few thousand elements) or
3130
because it cannot allocate memory for the new stack size.
3131
This function never shrinks the stack;
3132
if the stack is already larger than the new size,
3133
it is left unchanged.
3139
<hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p>
3140
<span class="apii">[-0, +0, –]</span>
3141
<pre>void lua_close (lua_State *L);</pre>
3144
Destroys all objects in the given Lua state
3145
(calling the corresponding garbage-collection metamethods, if any)
3146
and frees all dynamic memory used by this state.
3147
On several platforms, you may not need to call this function,
3148
because all resources are naturally released when the host program ends.
3149
On the other hand, long-running programs that create multiple states,
3150
such as daemons or web servers,
3151
might need to close states as soon as they are not needed.
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>
3162
Compares two Lua values.
3163
Returns 1 if the value at index <code>index1</code> satisfies <code>op</code>
3164
when compared with the value at index <code>index2</code>,
3165
following the semantics of the corresponding Lua operator
3166
(that is, it may call metamethods).
3167
Otherwise returns 0.
3168
Also returns 0 if any of the indices is non valid.
3172
The value of <code>op</code> must be one of the following constants:
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><</code>)</li>
3178
<li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code><=</code>)</li>
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>
3190
Concatenates the <code>n</code> values at the top of the stack,
3191
pops them, and leaves the result at the top.
3192
If <code>n</code> is 1, the result is the single value on the stack
3193
(that is, the function does nothing);
3194
if <code>n</code> is 0, the result is the empty string.
3195
Concatenation is performed following the usual semantics of Lua
3196
(see <a href="#3.4.5">§3.4.5</a>).
3202
<hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p>
3203
<span class="apii">[-0, +0, –]</span>
3204
<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
3207
Moves the element at index <code>fromidx</code>
3208
into the valid index <code>toidx</code>
3209
without shifting any element
3210
(therefore replacing the value at that position).
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>
3221
Creates a new empty table and pushes it onto the stack.
3222
Parameter <code>narr</code> is a hint for how many elements the table
3223
will have as a sequence;
3224
parameter <code>nrec</code> is a hint for how many other elements
3225
the table will have.
3226
Lua may use these hints to preallocate memory for the new table.
3227
This pre-allocation is useful for performance when you know in advance
3228
how many elements the table will have.
3229
Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
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>
3240
Dumps a function as a binary chunk.
3241
Receives a Lua function on the top of the stack
3242
and produces a binary chunk that,
3244
results in a function equivalent to the one dumped.
3245
As 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>)
3247
with the given <code>data</code>
3252
The value returned is the error code returned by the last
3254
0 means no errors.
3258
This function does not pop the Lua function from the stack.
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>
3269
Generates a Lua error.
3270
The error message (which can actually be a Lua value of any type)
3271
must be on the stack top.
3272
This function does a long jump,
3273
and therefore never returns
3274
(see <a href="#luaL_error"><code>luaL_error</code></a>).
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>
3285
Controls the garbage collector.
3289
This function performs several tasks,
3290
according to the value of the parameter <code>what</code>:
3294
<li><b><code>LUA_GCSTOP</code>: </b>
3295
stops the garbage collector.
3298
<li><b><code>LUA_GCRESTART</code>: </b>
3299
restarts the garbage collector.
3302
<li><b><code>LUA_GCCOLLECT</code>: </b>
3303
performs a full garbage-collection cycle.
3306
<li><b><code>LUA_GCCOUNT</code>: </b>
3307
returns the current amount of memory (in Kbytes) in use by Lua.
3310
<li><b><code>LUA_GCCOUNTB</code>: </b>
3311
returns the remainder of dividing the current amount of bytes of
3312
memory in use by Lua by 1024.
3315
<li><b><code>LUA_GCSTEP</code>: </b>
3316
performs an incremental step of garbage collection.
3317
The step "size" is controlled by <code>data</code>
3318
(larger values mean more steps) in a non-specified way.
3319
If you want to control the step size
3320
you must experimentally tune the value of <code>data</code>.
3321
The function returns 1 if the step finished a
3322
garbage-collection cycle.
3325
<li><b><code>LUA_GCSETPAUSE</code>: </b>
3326
sets <code>data</code> as the new value
3327
for the <em>pause</em> of the collector (see <a href="#2.5">§2.5</a>).
3328
The function returns the previous value of the pause.
3331
<li><b><code>LUA_GCSETSTEPMUL</code>: </b>
3332
sets <code>data</code> as the new value for the <em>step multiplier</em> of
3333
the collector (see <a href="#2.5">§2.5</a>).
3334
The function returns the previous value of the step multiplier.
3337
<li><b><code>LUA_GCISRUNNING</code>: </b>
3338
returns a boolean that tells whether the collector is running
3339
(i.e., not stopped).
3342
<li><b><code>LUA_GCGEN</code>: </b>
3343
changes the collector to generational mode
3344
(see <a href="#2.5">§2.5</a>).
3347
<li><b><code>LUA_GCINC</code>: </b>
3348
changes the collector to incremental mode.
3349
This is the default mode.
3355
For more details about these options,
3356
see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>.
3362
<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p>
3363
<span class="apii">[-0, +0, –]</span>
3364
<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
3367
Returns the memory-allocation function of a given state.
3368
If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3369
opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
3375
<hr><h3><a name="lua_getctx"><code>lua_getctx</code></a></h3><p>
3376
<span class="apii">[-0, +0, –]</span>
3377
<pre>int lua_getctx (lua_State *L, int *ctx);</pre>
3380
This function is called by a continuation function (see <a href="#4.7">§4.7</a>)
3381
to retrieve the status of the thread and a context information.
3385
When 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>
3387
and does not change the value of its argument <code>ctx</code>.
3388
When 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
3390
the value of <code>ctx</code> to be the context information
3391
(the value passed as the <code>ctx</code> argument
3392
to the callee together with the continuation function).
3396
When the callee is <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3397
Lua may also call its continuation function
3398
to handle errors during the call.
3399
That is, upon an error in the function called by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3400
Lua may not return to the original function
3401
but instead may call the continuation function.
3402
In 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>);
3404
the value of <code>ctx</code> will be set to the context information,
3405
as in the case of a yield.
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>
3416
Pushes onto the stack the value <code>t[k]</code>,
3417
where <code>t</code> is the value at the given index.
3418
As in Lua, this function may trigger a metamethod
3419
for the "index" event (see <a href="#2.4">§2.4</a>).
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>
3430
Pushes onto the stack the value of the global <code>name</code>.
3436
<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
3437
<span class="apii">[-0, +(0|1), –]</span>
3438
<pre>int lua_getmetatable (lua_State *L, int index);</pre>
3441
Pushes onto the stack the metatable of the value at the given index.
3442
If the value does not have a metatable,
3443
the function returns 0 and pushes nothing on the stack.
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>
3454
Pushes onto the stack the value <code>t[k]</code>,
3455
where <code>t</code> is the value at the given index
3456
and <code>k</code> is the value at the top of the stack.
3460
This function pops the key from the stack
3461
(putting the resulting value in its place).
3462
As in Lua, this function may trigger a metamethod
3463
for the "index" event (see <a href="#2.4">§2.4</a>).
3469
<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
3470
<span class="apii">[-0, +0, –]</span>
3471
<pre>int lua_gettop (lua_State *L);</pre>
3474
Returns the index of the top element in the stack.
3475
Because indices start at 1,
3476
this result is equal to the number of elements in the stack
3477
(and so 0 means an empty stack).
3483
<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
3484
<span class="apii">[-0, +1, –]</span>
3485
<pre>void lua_getuservalue (lua_State *L, int index);</pre>
3488
Pushes onto the stack the Lua value associated with the userdata
3490
This Lua value must be a table or <b>nil</b>.
3496
<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
3497
<span class="apii">[-1, +1, –]</span>
3498
<pre>void lua_insert (lua_State *L, int index);</pre>
3501
Moves the top element into the given valid index,
3502
shifting up the elements above this index to open space.
3503
This function cannot be called with a pseudo-index,
3504
because a pseudo-index is not an actual stack position.
3510
<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3511
<pre>typedef ptrdiff_t lua_Integer;</pre>
3514
The type used by the Lua API to represent signed integral values.
3518
By default it is a <code>ptrdiff_t</code>,
3519
which is usually the largest signed integral type the machine handles
3526
<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
3527
<span class="apii">[-0, +0, –]</span>
3528
<pre>int lua_isboolean (lua_State *L, int index);</pre>
3531
Returns 1 if the value at the given index is a boolean,
3532
and 0 otherwise.
3538
<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p>
3539
<span class="apii">[-0, +0, –]</span>
3540
<pre>int lua_iscfunction (lua_State *L, int index);</pre>
3543
Returns 1 if the value at the given index is a C function,
3544
and 0 otherwise.
3550
<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p>
3551
<span class="apii">[-0, +0, –]</span>
3552
<pre>int lua_isfunction (lua_State *L, int index);</pre>
3555
Returns 1 if the value at the given index is a function
3556
(either C or Lua), and 0 otherwise.
3562
<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
3563
<span class="apii">[-0, +0, –]</span>
3564
<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
3567
Returns 1 if the value at the given index is a light userdata,
3568
and 0 otherwise.
3574
<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p>
3575
<span class="apii">[-0, +0, –]</span>
3576
<pre>int lua_isnil (lua_State *L, int index);</pre>
3579
Returns 1 if the value at the given index is <b>nil</b>,
3580
and 0 otherwise.
3586
<hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p>
3587
<span class="apii">[-0, +0, –]</span>
3588
<pre>int lua_isnone (lua_State *L, int index);</pre>
3591
Returns 1 if the given index is not valid,
3592
and 0 otherwise.
3598
<hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p>
3599
<span class="apii">[-0, +0, –]</span>
3600
<pre>int lua_isnoneornil (lua_State *L, int index);</pre>
3603
Returns 1 if the given index is not valid
3604
or if the value at this index is <b>nil</b>,
3605
and 0 otherwise.
3611
<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p>
3612
<span class="apii">[-0, +0, –]</span>
3613
<pre>int lua_isnumber (lua_State *L, int index);</pre>
3616
Returns 1 if the value at the given index is a number
3617
or a string convertible to a number,
3618
and 0 otherwise.
3624
<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p>
3625
<span class="apii">[-0, +0, –]</span>
3626
<pre>int lua_isstring (lua_State *L, int index);</pre>
3629
Returns 1 if the value at the given index is a string
3630
or a number (which is always convertible to a string),
3631
and 0 otherwise.
3637
<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p>
3638
<span class="apii">[-0, +0, –]</span>
3639
<pre>int lua_istable (lua_State *L, int index);</pre>
3642
Returns 1 if the value at the given index is a table,
3643
and 0 otherwise.
3649
<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p>
3650
<span class="apii">[-0, +0, –]</span>
3651
<pre>int lua_isthread (lua_State *L, int index);</pre>
3654
Returns 1 if the value at the given index is a thread,
3655
and 0 otherwise.
3661
<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p>
3662
<span class="apii">[-0, +0, –]</span>
3663
<pre>int lua_isuserdata (lua_State *L, int index);</pre>
3666
Returns 1 if the value at the given index is a userdata
3667
(either full or light), and 0 otherwise.
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>
3678
Returns the "length" of the value at the given index;
3679
it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.6">§3.4.6</a>).
3680
The result is pushed on the stack.
3686
<hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p>
3687
<span class="apii">[-0, +1, –]</span>
3688
<pre>int lua_load (lua_State *L,
3692
const char *mode);</pre>
3695
Loads a Lua chunk (without running it).
3696
If there are no errors,
3697
<code>lua_load</code> pushes the compiled chunk as a Lua
3698
function on top of the stack.
3699
Otherwise, it pushes an error message.
3703
The return values of <code>lua_load</code> are:
3707
<li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li>
3709
<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b>
3710
syntax error during precompilation;</li>
3712
<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3713
memory allocation error;</li>
3715
<li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
3716
error while running a <code>__gc</code> metamethod.
3717
(This error has no relation with the chunk being loaded.
3718
It is generated by the garbage collector.)
3724
The <code>lua_load</code> function uses a user-supplied <code>reader</code> function
3725
to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3726
The <code>data</code> argument is an opaque value passed to the reader function.
3730
The <code>source</code> argument gives a name to the chunk,
3731
which is used for error messages and in debug information (see <a href="#4.9">§4.9</a>).
3735
<code>lua_load</code> automatically detects whether the chunk is text or binary
3736
and loads it accordingly (see program <code>luac</code>).
3737
The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>,
3738
with the addition that
3739
a <code>NULL</code> value is equivalent to the string "<code>bt</code>".
3743
<code>lua_load</code> uses the stack internally,
3744
so the reader function should always leave the stack
3745
unmodified when returning.
3749
If the resulting function has one upvalue,
3750
this upvalue is set to the value of the global environment
3751
stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">§4.5</a>).
3752
When loading main chunks,
3753
this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>).
3759
<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p>
3760
<span class="apii">[-0, +0, –]</span>
3761
<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3764
Creates a new thread running in a new, independent state.
3765
Returns <code>NULL</code> if cannot create the thread or the state
3766
(due to lack of memory).
3767
The argument <code>f</code> is the allocator function;
3768
Lua does all memory allocation for this state through this function.
3769
The second argument, <code>ud</code>, is an opaque pointer that Lua
3770
passes to the allocator in every call.
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>
3781
Creates a new empty table and pushes it onto the stack.
3782
It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
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>
3793
Creates a new thread, pushes it on the stack,
3794
and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3795
The new thread returned by this function shares with the original thread
3796
its global environment,
3797
but has an independent execution stack.
3801
There is no explicit function to close or to destroy a thread.
3802
Threads are subject to garbage collection,
3803
like any Lua object.
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>
3814
This function allocates a new block of memory with the given size,
3815
pushes onto the stack a new full userdata with the block address,
3816
and returns this address.
3817
The host program can freely use this memory.
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>
3828
Pops a key from the stack,
3829
and pushes a key–value pair from the table at the given index
3830
(the "next" pair after the given key).
3831
If there are no more elements in the table,
3832
then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3836
A typical traversal looks like this:
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) */
3844
lua_typename(L, lua_type(L, -2)),
3845
lua_typename(L, lua_type(L, -1)));
3846
/* removes 'value'; keeps 'key' for next iteration */
3852
While traversing a table,
3853
do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3854
unless you know that the key is actually a string.
3855
Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change
3856
the value at the given index;
3857
this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3861
See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
3862
the table during its traversal.
3868
<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3869
<pre>typedef double lua_Number;</pre>
3872
The type of numbers in Lua.
3873
By default, it is double, but that can be changed in <code>luaconf.h</code>.
3874
Through this configuration file you can change
3875
Lua to operate with another type for numbers (e.g., float or long).
3881
<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
3882
<span class="apii">[-(nargs + 1), +(nresults|1), –]</span>
3883
<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
3886
Calls a function in protected mode.
3890
Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3891
in <a href="#lua_call"><code>lua_call</code></a>.
3892
If 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>.
3894
However, if there is any error,
3895
<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3896
pushes a single value on the stack (the error message),
3897
and returns an error code.
3898
Like <a href="#lua_call"><code>lua_call</code></a>,
3899
<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3900
and its arguments from the stack.
3904
If <code>msgh</code> is 0,
3905
then the error message returned on the stack
3906
is exactly the original error message.
3907
Otherwise, <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.)
3910
In case of runtime errors,
3911
this function will be called with the error message
3912
and its return value will be the message
3913
returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3917
Typically, the message handler is used to add more debug
3918
information to the error message, such as a stack traceback.
3919
Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3920
since by then the stack has unwound.
3924
The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following codes
3925
(defined in <code>lua.h</code>):
3929
<li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b>
3932
<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b>
3936
<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b>
3937
memory allocation error.
3938
For such errors, Lua does not call the message handler.
3941
<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b>
3942
error while running the message handler.
3945
<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
3946
error while running a <code>__gc</code> metamethod.
3947
(This error typically has no relation with the function being called.
3948
It is generated by the garbage collector.)
3956
<hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p>
3957
<span class="apii">[-(nargs + 1), +(nresults|1), –]</span>
3958
<pre>int lua_pcallk (lua_State *L,
3963
lua_CFunction k);</pre>
3966
This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
3967
but allows the called function to yield (see <a href="#4.7">§4.7</a>).
3973
<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p>
3974
<span class="apii">[-n, +0, –]</span>
3975
<pre>void lua_pop (lua_State *L, int n);</pre>
3978
Pops <code>n</code> elements from the stack.
3984
<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p>
3985
<span class="apii">[-0, +1, –]</span>
3986
<pre>void lua_pushboolean (lua_State *L, int b);</pre>
3989
Pushes a boolean value with value <code>b</code> onto the stack.
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>
4000
Pushes a new C closure onto the stack.
4004
When a C function is created,
4005
it is possible to associate some values with it,
4006
thus creating a C closure (see <a href="#4.4">§4.4</a>);
4007
these values are then accessible to the function whenever it is called.
4008
To associate values with a C function,
4009
first these values should be pushed onto the stack
4010
(when there are multiple values, the first value is pushed first).
4011
Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
4012
is called to create and push the C function onto the stack,
4013
with the argument <code>n</code> telling how many values should be
4014
associated with the function.
4015
<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
4019
The maximum value for <code>n</code> is 255.
4023
When <code>n</code> is zero,
4024
this function creates a <em>light C function</em>,
4025
which is just a pointer to the C function.
4026
In that case, it never throws a memory error.
4032
<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p>
4033
<span class="apii">[-0, +1, –]</span>
4034
<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
4037
Pushes a C function onto the stack.
4038
This function receives a pointer to a C function
4039
and pushes onto the stack a Lua value of type <code>function</code> that,
4040
when called, invokes the corresponding C function.
4044
Any function to be registered in Lua must
4045
follow the correct protocol to receive its parameters
4046
and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
4050
<code>lua_pushcfunction</code> is defined as a macro:
4053
#define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
4055
Note that <code>f</code> is used twice.
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>
4066
Pushes onto the stack a formatted string
4067
and returns a pointer to this string.
4068
It is similar to the ANSI C function <code>sprintf</code>,
4069
but has some important differences:
4074
You do not have to allocate space for the result:
4075
the result is a Lua string and Lua takes care of memory allocation
4076
(and deallocation, through garbage collection).
4080
The conversion specifiers are quite restricted.
4081
There are no flags, widths, or precisions.
4082
The 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).
4096
<hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p>
4097
<span class="apii">[-0, +1, –]</span>
4098
<pre>void lua_pushglobaltable (lua_State *L);</pre>
4101
Pushes the global environment onto the stack.
4107
<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p>
4108
<span class="apii">[-0, +1, –]</span>
4109
<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
4112
Pushes a number with value <code>n</code> onto the stack.
4118
<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p>
4119
<span class="apii">[-0, +1, –]</span>
4120
<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
4123
Pushes a light userdata onto the stack.
4127
Userdata represent C values in Lua.
4128
A <em>light userdata</em> represents a pointer, a <code>void*</code>.
4129
It is a value (like a number):
4130
you do not create it, it has no individual metatable,
4131
and it is not collected (as it was never created).
4132
A light userdata is equal to "any"
4133
light userdata with the same C address.
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>
4144
This macro is equivalent to <a href="#lua_pushlstring"><code>lua_pushlstring</code></a>,
4145
but can be used only when <code>s</code> is a literal string.
4146
It automatically provides the string length.
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>
4157
Pushes the string pointed to by <code>s</code> with size <code>len</code>
4159
Lua makes (or reuses) an internal copy of the given string,
4160
so the memory at <code>s</code> can be freed or reused immediately after
4161
the function returns.
4162
The string can contain any binary data,
4163
including embedded zeros.
4167
Returns a pointer to the internal copy of the string.
4173
<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p>
4174
<span class="apii">[-0, +1, –]</span>
4175
<pre>void lua_pushnil (lua_State *L);</pre>
4178
Pushes a nil value onto the stack.
4184
<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p>
4185
<span class="apii">[-0, +1, –]</span>
4186
<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
4189
Pushes a number with value <code>n</code> onto the stack.
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>
4200
Pushes the zero-terminated string pointed to by <code>s</code>
4202
Lua makes (or reuses) an internal copy of the given string,
4203
so the memory at <code>s</code> can be freed or reused immediately after
4204
the function returns.
4208
Returns a pointer to the internal copy of the string.
4212
If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>.
4218
<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p>
4219
<span class="apii">[-0, +1, –]</span>
4220
<pre>int lua_pushthread (lua_State *L);</pre>
4223
Pushes the thread represented by <code>L</code> onto the stack.
4224
Returns 1 if this thread is the main thread of its state.
4230
<hr><h3><a name="lua_pushunsigned"><code>lua_pushunsigned</code></a></h3><p>
4231
<span class="apii">[-0, +1, –]</span>
4232
<pre>void lua_pushunsigned (lua_State *L, lua_Unsigned n);</pre>
4235
Pushes a number with value <code>n</code> onto the stack.
4241
<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
4242
<span class="apii">[-0, +1, –]</span>
4243
<pre>void lua_pushvalue (lua_State *L, int index);</pre>
4246
Pushes a copy of the element at the given index
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,
4257
va_list argp);</pre>
4260
Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
4261
instead of a variable number of arguments.
4267
<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p>
4268
<span class="apii">[-0, +0, –]</span>
4269
<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
4272
Returns 1 if the two values in indices <code>index1</code> and
4273
<code>index2</code> are primitively equal
4274
(that is, without calling metamethods).
4275
Otherwise returns 0.
4276
Also returns 0 if any of the indices are non valid.
4282
<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
4283
<span class="apii">[-1, +1, –]</span>
4284
<pre>void lua_rawget (lua_State *L, int index);</pre>
4287
Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
4288
(i.e., without metamethods).
4294
<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
4295
<span class="apii">[-0, +1, –]</span>
4296
<pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
4299
Pushes onto the stack the value <code>t[n]</code>,
4300
where <code>t</code> is the table at the given index.
4302
that is, it does not invoke metamethods.
4308
<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
4309
<span class="apii">[-0, +1, –]</span>
4310
<pre>void lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4313
Pushes onto the stack the value <code>t[k]</code>,
4314
where <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.
4317
that is, it does not invoke metamethods.
4323
<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
4324
<span class="apii">[-0, +0, –]</span>
4325
<pre>size_t lua_rawlen (lua_State *L, int index);</pre>
4328
Returns the raw "length" of the value at the given index:
4329
for strings, this is the string length;
4330
for tables, this is the result of the length operator ('<code>#</code>')
4331
with no metamethods;
4332
for userdata, this is the size of the block of memory allocated
4334
for other values, it is 0.
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>
4345
Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
4346
(i.e., without metamethods).
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>
4357
Does the equivalent of <code>t[n] = v</code>,
4358
where <code>t</code> is the table at the given index
4359
and <code>v</code> is the value at the top of the stack.
4363
This function pops the value from the stack.
4364
The assignment is raw;
4365
that is, it does not invoke metamethods.
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>
4376
Does the equivalent of <code>t[k] = v</code>,
4377
where <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,
4379
and <code>v</code> is the value at the top of the stack.
4383
This function pops the value from the stack.
4384
The assignment is raw;
4385
that is, it does not invoke metamethods.
4391
<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
4392
<pre>typedef const char * (*lua_Reader) (lua_State *L,
4394
size_t *size);</pre>
4397
The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
4398
Every time it needs another piece of the chunk,
4399
<a href="#lua_load"><code>lua_load</code></a> calls the reader,
4400
passing along its <code>data</code> parameter.
4401
The reader must return a pointer to a block of memory
4402
with a new piece of the chunk
4403
and set <code>size</code> to the block size.
4404
The block must exist until the reader function is called again.
4405
To signal the end of the chunk,
4406
the reader must return <code>NULL</code> or set <code>size</code> to zero.
4407
The reader function may return pieces of any size greater than zero.
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>
4418
Sets the C function <code>f</code> as the new value of global <code>name</code>.
4419
It is defined as a macro:
4422
#define lua_register(L,n,f) \
4423
(lua_pushcfunction(L, f), lua_setglobal(L, n))
4429
<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p>
4430
<span class="apii">[-1, +0, –]</span>
4431
<pre>void lua_remove (lua_State *L, int index);</pre>
4434
Removes the element at the given valid index,
4435
shifting down the elements above this index to fill the gap.
4436
This function cannot be called with a pseudo-index,
4437
because a pseudo-index is not an actual stack position.
4443
<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p>
4444
<span class="apii">[-1, +0, –]</span>
4445
<pre>void lua_replace (lua_State *L, int index);</pre>
4448
Moves the top element into the given valid index
4449
without shifting any element
4450
(therefore replacing the value at the given index),
4451
and then pops the top element.
4457
<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p>
4458
<span class="apii">[-?, +?, –]</span>
4459
<pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre>
4462
Starts and resumes a coroutine in a given thread.
4466
To start a coroutine,
4467
you push onto the thread stack the main function plus any arguments;
4468
then you call <a href="#lua_resume"><code>lua_resume</code></a>,
4469
with <code>nargs</code> being the number of arguments.
4470
This call returns when the coroutine suspends or finishes its execution.
4471
When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
4472
or 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
4477
or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
4482
the stack is not unwound,
4483
so you can use the debug API over it.
4484
The error message is on the top of the stack.
4488
To resume a coroutine,
4489
you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>,
4490
put on its stack only the values to
4491
be passed as results from <code>yield</code>,
4492
and then call <a href="#lua_resume"><code>lua_resume</code></a>.
4496
The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>.
4497
If there is no such coroutine,
4498
this parameter can be <code>NULL</code>.
4504
<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
4505
<span class="apii">[-0, +0, –]</span>
4506
<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
4509
Changes the allocator function of a given state to <code>f</code>
4510
with user data <code>ud</code>.
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>
4521
Does the equivalent to <code>t[k] = v</code>,
4522
where <code>t</code> is the value at the given index
4523
and <code>v</code> is the value at the top of the stack.
4527
This function pops the value from the stack.
4528
As in Lua, this function may trigger a metamethod
4529
for the "newindex" event (see <a href="#2.4">§2.4</a>).
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>
4540
Pops a value from the stack and
4541
sets it as the new value of global <code>name</code>.
4547
<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
4548
<span class="apii">[-1, +0, –]</span>
4549
<pre>void lua_setmetatable (lua_State *L, int index);</pre>
4552
Pops a table from the stack and
4553
sets it as the new metatable for the value at the given index.
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>
4564
Does the equivalent to <code>t[k] = v</code>,
4565
where <code>t</code> is the value at the given index,
4566
<code>v</code> is the value at the top of the stack,
4567
and <code>k</code> is the value just below the top.
4571
This function pops both the key and the value from the stack.
4572
As in Lua, this function may trigger a metamethod
4573
for the "newindex" event (see <a href="#2.4">§2.4</a>).
4579
<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p>
4580
<span class="apii">[-?, +?, –]</span>
4581
<pre>void lua_settop (lua_State *L, int index);</pre>
4584
Accepts any index, or 0,
4585
and sets the stack top to this index.
4586
If the new top is larger than the old one,
4587
then the new elements are filled with <b>nil</b>.
4588
If <code>index</code> is 0, then all stack elements are removed.
4594
<hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p>
4595
<span class="apii">[-1, +0, –]</span>
4596
<pre>void lua_setuservalue (lua_State *L, int index);</pre>
4599
Pops a table or <b>nil</b> from the stack and sets it as
4600
the new value associated to the userdata at the given index.
4606
<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
4607
<pre>typedef struct lua_State lua_State;</pre>
4610
An opaque structure that points to a thread and indirectly
4611
(through the thread) to the whole state of a Lua interpreter.
4612
The Lua library is fully reentrant:
4613
it has no global variables.
4614
All information about a state is accessible through this structure.
4618
A pointer to this structure must be passed as the first argument to
4619
every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
4620
which creates a Lua state from scratch.
4626
<hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p>
4627
<span class="apii">[-0, +0, –]</span>
4628
<pre>int lua_status (lua_State *L);</pre>
4631
Returns the status of the thread <code>L</code>.
4635
The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread,
4636
an error code if the thread finished the execution
4637
of a <a href="#lua_resume"><code>lua_resume</code></a> with an error,
4638
or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
4642
You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>.
4643
You 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).
4651
<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
4652
<span class="apii">[-0, +0, –]</span>
4653
<pre>int lua_toboolean (lua_State *L, int index);</pre>
4656
Converts the Lua value at the given index to a C boolean
4657
value (0 or 1).
4658
Like all tests in Lua,
4659
<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value
4660
different from <b>false</b> and <b>nil</b>;
4661
otherwise it returns false.
4662
(If you want to accept only actual boolean values,
4663
use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
4669
<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p>
4670
<span class="apii">[-0, +0, –]</span>
4671
<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
4674
Converts a value at the given index to a C function.
4675
That value must be a C function;
4676
otherwise, returns <code>NULL</code>.
4682
<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p>
4683
<span class="apii">[-0, +0, –]</span>
4684
<pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre>
4687
Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4693
<hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p>
4694
<span class="apii">[-0, +0, –]</span>
4695
<pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre>
4698
Converts the Lua value at the given index
4699
to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4700
The Lua value must be a number or a string convertible to a number
4701
(see <a href="#3.4.2">§3.4.2</a>);
4702
otherwise, <code>lua_tointegerx</code> returns 0.
4706
If the number is not an integer,
4707
it is truncated in some non-specified way.
4711
If <code>isnum</code> is not <code>NULL</code>,
4712
its referent is assigned a boolean value that
4713
indicates whether the operation succeeded.
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>
4724
Converts the Lua value at the given index to a C string.
4725
If <code>len</code> is not <code>NULL</code>,
4726
it also sets <code>*len</code> with the string length.
4727
The Lua value must be a string or a number;
4728
otherwise, the function returns <code>NULL</code>.
4729
If the value is a number,
4730
then <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>
4733
when <code>lua_tolstring</code> is applied to keys during a table traversal.)
4737
<code>lua_tolstring</code> returns a fully aligned pointer
4738
to a string inside the Lua state.
4739
This string always has a zero ('<code>\0</code>')
4740
after its last character (as in C),
4741
but can contain other zeros in its body.
4742
Because Lua has garbage collection,
4743
there is no guarantee that the pointer returned by <code>lua_tolstring</code>
4744
will be valid after the corresponding value is removed from the stack.
4750
<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p>
4751
<span class="apii">[-0, +0, –]</span>
4752
<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
4755
Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4761
<hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p>
4762
<span class="apii">[-0, +0, –]</span>
4763
<pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre>
4766
Converts the Lua value at the given index
4767
to the C type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
4768
The Lua value must be a number or a string convertible to a number
4769
(see <a href="#3.4.2">§3.4.2</a>);
4770
otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns 0.
4774
If <code>isnum</code> is not <code>NULL</code>,
4775
its referent is assigned a boolean value that
4776
indicates whether the operation succeeded.
4782
<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p>
4783
<span class="apii">[-0, +0, –]</span>
4784
<pre>const void *lua_topointer (lua_State *L, int index);</pre>
4787
Converts the value at the given index to a generic
4788
C pointer (<code>void*</code>).
4789
The value can be a userdata, a table, a thread, or a function;
4790
otherwise, <code>lua_topointer</code> returns <code>NULL</code>.
4791
Different objects will give different pointers.
4792
There is no way to convert the pointer back to its original value.
4796
Typically this function is used only for debug information.
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>
4807
Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
4813
<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p>
4814
<span class="apii">[-0, +0, –]</span>
4815
<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
4818
Converts the value at the given index to a Lua thread
4819
(represented as <code>lua_State*</code>).
4820
This value must be a thread;
4821
otherwise, the function returns <code>NULL</code>.
4827
<hr><h3><a name="lua_tounsigned"><code>lua_tounsigned</code></a></h3><p>
4828
<span class="apii">[-0, +0, –]</span>
4829
<pre>lua_Unsigned lua_tounsigned (lua_State *L, int index);</pre>
4832
Equivalent to <a href="#lua_tounsignedx"><code>lua_tounsignedx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4838
<hr><h3><a name="lua_tounsignedx"><code>lua_tounsignedx</code></a></h3><p>
4839
<span class="apii">[-0, +0, –]</span>
4840
<pre>lua_Unsigned lua_tounsignedx (lua_State *L, int index, int *isnum);</pre>
4843
Converts the Lua value at the given index
4844
to the unsigned integral type <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
4845
The Lua value must be a number or a string convertible to a number
4846
(see <a href="#3.4.2">§3.4.2</a>);
4847
otherwise, <code>lua_tounsignedx</code> returns 0.
4851
If the number is not an integer,
4852
it is truncated in some non-specified way.
4853
If the number is outside the range of representable values,
4854
it is normalized to the remainder of its division by
4855
one more than the maximum representable value.
4859
If <code>isnum</code> is not <code>NULL</code>,
4860
its referent is assigned a boolean value that
4861
indicates whether the operation succeeded.
4867
<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
4868
<span class="apii">[-0, +0, –]</span>
4869
<pre>void *lua_touserdata (lua_State *L, int index);</pre>
4872
If the value at the given index is a full userdata,
4873
returns its block address.
4874
If the value is a light userdata,
4875
returns its pointer.
4876
Otherwise, returns <code>NULL</code>.
4882
<hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p>
4883
<span class="apii">[-0, +0, –]</span>
4884
<pre>int lua_type (lua_State *L, int index);</pre>
4887
Returns the type of the value in the given valid index,
4888
or <code>LUA_TNONE</code> for a non-valid (but acceptable) index.
4889
The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4890
defined 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>,
4900
<a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>.
4906
<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p>
4907
<span class="apii">[-0, +0, –]</span>
4908
<pre>const char *lua_typename (lua_State *L, int tp);</pre>
4911
Returns the name of the type encoded by the value <code>tp</code>,
4912
which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4918
<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
4919
<pre>typedef unsigned long lua_Unsigned;</pre>
4922
The type used by the Lua API to represent unsigned integral values.
4923
It must have at least 32 bits.
4927
By default it is an <code>unsigned int</code> or an <code>unsigned long</code>,
4928
whichever can hold 32-bit values.
4934
<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
4935
<span class="apii">[-0, +0, –]</span>
4936
<pre>int lua_upvalueindex (int i);</pre>
4939
Returns the pseudo-index that represents the <code>i</code>-th upvalue of
4940
the running function (see <a href="#4.4">§4.4</a>).
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>
4951
Returns the address of the version number stored in the Lua core.
4952
When called with a valid <a href="#lua_State"><code>lua_State</code></a>,
4953
returns the address of the version used to create that state.
4954
When called with <code>NULL</code>,
4955
returns the address of the version running the call.
4961
<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4962
<pre>typedef int (*lua_Writer) (lua_State *L,
4968
The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4969
Every time it produces another piece of chunk,
4970
<a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4971
passing along the buffer to be written (<code>p</code>),
4972
its size (<code>sz</code>),
4973
and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4977
The writer returns an error code:
4978
0 means no errors;
4979
any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4980
calling the writer again.
4986
<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p>
4987
<span class="apii">[-?, +?, –]</span>
4988
<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4991
Exchange values between different threads of the same state.
4995
This function pops <code>n</code> values from the stack <code>from</code>,
4996
and pushes them onto the stack <code>to</code>.
5002
<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5003
<span class="apii">[-?, +?, –]</span>
5004
<pre>int lua_yield (lua_State *L, int nresults);</pre>
5007
This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
5008
but it has no continuation (see <a href="#4.7">§4.7</a>).
5009
Therefore, when the thread resumes,
5010
it returns to the function that called
5011
the function calling <code>lua_yield</code>.
5017
<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5018
<span class="apii">[-?, +?, –]</span>
5019
<pre>int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k);</pre>
5026
This function should only be called as the
5027
return expression of a C function, as follows:
5030
return lua_yieldk (L, n, i, k);
5032
When a C function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a> in that way,
5033
the running coroutine suspends its execution,
5034
and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
5035
The parameter <code>nresults</code> is the number of values from the stack
5036
that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5040
When the coroutine is resumed again,
5041
Lua calls the given continuation function <code>k</code> to continue
5042
the execution of the C function that yielded (see <a href="#4.7">§4.7</a>).
5043
This continuation function receives the same stack
5044
from the previous function,
5045
with the results removed and
5046
replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
5048
the continuation function may access the value <code>ctx</code>
5049
by calling <a href="#lua_getctx"><code>lua_getctx</code></a>.
5057
<h2>4.9 – <a name="4.9">The Debug Interface</a></h2>
5060
Lua has no built-in debugging facilities.
5061
Instead, it offers a special interface
5062
by means of functions and <em>hooks</em>.
5063
This interface allows the construction of different
5064
kinds of debuggers, profilers, and other tools
5065
that need "inside information" from the interpreter.
5069
<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
5070
<pre>typedef struct lua_Debug {
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) */
5085
<em>other fields</em>
5089
A structure used to carry different pieces of
5090
information about a function or an activation record.
5091
<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
5092
of this structure, for later use.
5093
To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
5094
call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5098
The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
5102
<li><b><code>source</code>: </b>
5103
the source of the chunk that created the function.
5104
If <code>source</code> starts with a '<code>@</code>',
5105
it means that the function was defined in a file where
5106
the file name follows the '<code>@</code>'.
5107
If <code>source</code> starts with a '<code>=</code>',
5108
the remainder of its contents describe the source in a user-dependent manner.
5110
the function was defined in a string where
5111
<code>source</code> is that string.
5114
<li><b><code>short_src</code>: </b>
5115
a "printable" version of <code>source</code>, to be used in error messages.
5118
<li><b><code>linedefined</code>: </b>
5119
the line number where the definition of the function starts.
5122
<li><b><code>lastlinedefined</code>: </b>
5123
the line number where the definition of the function ends.
5126
<li><b><code>what</code>: </b>
5127
the string <code>"Lua"</code> if the function is a Lua function,
5128
<code>"C"</code> if it is a C function,
5129
<code>"main"</code> if it is the main part of a chunk.
5132
<li><b><code>currentline</code>: </b>
5133
the current line where the given function is executing.
5134
When no line information is available,
5135
<code>currentline</code> is set to -1.
5138
<li><b><code>name</code>: </b>
5139
a reasonable name for the given function.
5140
Because functions in Lua are first-class values,
5141
they do not have a fixed name:
5142
some functions can be the value of multiple global variables,
5143
while others can be stored only in a table field.
5144
The <code>lua_getinfo</code> function checks how the function was
5145
called to find a suitable name.
5146
If it cannot find a name,
5147
then <code>name</code> is set to <code>NULL</code>.
5150
<li><b><code>namewhat</code>: </b>
5151
explains the <code>name</code> field.
5152
The 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),
5155
according to how the function was called.
5156
(Lua uses the empty string when no other option seems to apply.)
5159
<li><b><code>istailcall</code>: </b>
5160
true if this function invocation was called by a tail call.
5161
In this case, the caller of this level is not in the stack.
5164
<li><b><code>nups</code>: </b>
5165
the number of upvalues of the function.
5168
<li><b><code>nparams</code>: </b>
5169
the number of fixed parameters of the function
5170
(always 0 for C functions).
5173
<li><b><code>isvararg</code>: </b>
5174
true if the function is a vararg function
5175
(always true for C functions).
5183
<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p>
5184
<span class="apii">[-0, +0, –]</span>
5185
<pre>lua_Hook lua_gethook (lua_State *L);</pre>
5188
Returns the current hook function.
5194
<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p>
5195
<span class="apii">[-0, +0, –]</span>
5196
<pre>int lua_gethookcount (lua_State *L);</pre>
5199
Returns the current hook count.
5205
<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p>
5206
<span class="apii">[-0, +0, –]</span>
5207
<pre>int lua_gethookmask (lua_State *L);</pre>
5210
Returns the current hook mask.
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>
5221
Gets information about a specific function or function invocation.
5225
To get information about a function invocation,
5226
the parameter <code>ar</code> must be a valid activation record that was
5227
filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5228
given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5232
To get information about a function you push it onto the stack
5233
and start the <code>what</code> string with the character '<code>></code>'.
5235
<code>lua_getinfo</code> pops the function from the top of the stack.)
5236
For instance, to know in which line a function <code>f</code> was defined,
5237
you can write the following code:
5241
lua_getglobal(L, "f"); /* get global 'f' */
5242
lua_getinfo(L, ">S", &ar);
5243
printf("%d\n", ar.linedefined);
5247
Each character in the string <code>what</code>
5248
selects some fields of the structure <code>ar</code> to be filled or
5249
a value to be pushed on the stack:
5253
<li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>;
5256
<li><b>'<code>S</code>': </b>
5257
fills in the fields <code>source</code>, <code>short_src</code>,
5258
<code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>;
5261
<li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>;
5264
<li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>;
5267
<li><b>'<code>u</code>': </b> fills in the fields
5268
<code>nups</code>, <code>nparams</code>, and <code>isvararg</code>;
5271
<li><b>'<code>f</code>': </b>
5272
pushes onto the stack the function that is
5273
running at the given level;
5276
<li><b>'<code>L</code>': </b>
5277
pushes onto the stack a table whose indices are the
5278
numbers of the lines that are valid on the function.
5279
(A <em>valid line</em> is a line with some associated code,
5280
that is, a line where you can put a break point.
5281
Non-valid lines include empty lines and comments.)
5287
This function returns 0 on error
5288
(for instance, an invalid option in <code>what</code>).
5294
<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
5295
<span class="apii">[-0, +(0|1), –]</span>
5296
<pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5299
Gets information about a local variable of
5300
a given activation record or a given function.
5305
the parameter <code>ar</code> must be a valid activation record that was
5306
filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
5307
given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
5308
The index <code>n</code> selects which local variable to inspect;
5309
see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices
5314
<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
5315
and returns its name.
5319
In the second case, <code>ar</code> should be <code>NULL</code> and the function
5320
to be inspected must be at the top of the stack.
5321
In this case, only parameters of Lua functions are visible
5322
(as there is no information about what variables are active)
5323
and no values are pushed onto the stack.
5327
Returns <code>NULL</code> (and pushes nothing)
5328
when the index is greater than
5329
the number of active local variables.
5335
<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p>
5336
<span class="apii">[-0, +0, –]</span>
5337
<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
5340
Gets information about the interpreter runtime stack.
5344
This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
5345
an identification of the <em>activation record</em>
5346
of the function executing at a given level.
5347
Level 0 is the current running function,
5348
whereas 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).
5350
When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
5351
when called with a level greater than the stack depth,
5358
<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p>
5359
<span class="apii">[-0, +(0|1), –]</span>
5360
<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
5363
Gets information about a closure's upvalue.
5365
upvalues are the external local variables that the function uses,
5366
and 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,
5368
pushes the upvalue's value onto the stack,
5369
and returns its name.
5370
<code>funcindex</code> points to the closure in the stack.
5371
(Upvalues have no particular order,
5372
as they are active through the whole function.
5373
So, they are numbered in an arbitrary order.)
5377
Returns <code>NULL</code> (and pushes nothing)
5378
when the index is greater than the number of upvalues.
5379
For C functions, this function uses the empty string <code>""</code>
5380
as a name for all upvalues.
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>
5390
Type for debugging hook functions.
5394
Whenever 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.
5396
Lua 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>,
5399
and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
5400
Moreover, for line events, the field <code>currentline</code> is also set.
5401
To get the value of any other field in <code>ar</code>,
5402
the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
5406
For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>,
5407
the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call;
5408
in this case, there will be no corresponding return event.
5412
While Lua is running a hook, it disables other calls to hooks.
5413
Therefore, if a hook calls back Lua to execute a function or a chunk,
5414
this execution occurs without any calls to hooks.
5418
Hook functions cannot have continuations,
5419
that 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>.
5424
Hook functions can yield under the following conditions:
5425
Only count and line events can yield
5426
and they cannot yield any value;
5427
to yield a hook function must finish its execution
5428
calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero.
5434
<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
5435
<span class="apii">[-0, +0, –]</span>
5436
<pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5439
Sets the debugging hook function.
5443
Argument <code>f</code> is the hook function.
5444
<code>mask</code> specifies on which events the hook will be called:
5445
it 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>,
5449
and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
5450
The <code>count</code> argument is only meaningful when the mask
5451
includes <code>LUA_MASKCOUNT</code>.
5452
For each event, the hook is called as explained below:
5456
<li><b>The call hook: </b> is called when the interpreter calls a function.
5457
The hook is called just after Lua enters the new function,
5458
before the function gets its arguments.
5461
<li><b>The return hook: </b> is called when the interpreter returns from a function.
5462
The hook is called just before Lua leaves the function.
5463
There is no standard way to access the values
5464
to be returned by the function.
5467
<li><b>The line hook: </b> is called when the interpreter is about to
5468
start the execution of a new line of code,
5469
or when it jumps back in the code (even to the same line).
5470
(This event only happens while Lua is executing a Lua function.)
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.)
5481
A hook is disabled by setting <code>mask</code> to zero.
5487
<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
5488
<span class="apii">[-(0|1), +0, –]</span>
5489
<pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5492
Sets the value of a local variable of a given activation record.
5493
Parameters <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
5496
to the variable and returns its name.
5497
It also pops the value from the stack.
5501
Returns <code>NULL</code> (and pops nothing)
5502
when the index is greater than
5503
the number of active local variables.
5509
<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p>
5510
<span class="apii">[-(0|1), +0, –]</span>
5511
<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
5514
Sets the value of a closure's upvalue.
5515
It assigns the value at the top of the stack
5516
to the upvalue and returns its name.
5517
It also pops the value from the stack.
5518
Parameters <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>).
5523
Returns <code>NULL</code> (and pops nothing)
5524
when the index is greater than the number of upvalues.
5530
<hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p>
5531
<span class="apii">[-0, +0, –]</span>
5532
<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
5535
Returns an unique identifier for the upvalue numbered <code>n</code>
5536
from the closure at index <code>funcindex</code>.
5537
Parameters <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).
5543
These unique identifiers allow a program to check whether different
5544
closures share upvalues.
5545
Lua closures that share an upvalue
5546
(that is, that access a same external local variable)
5547
will return identical ids for those upvalue indices.
5553
<hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p>
5554
<span class="apii">[-0, +0, –]</span>
5555
<pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1,
5556
int funcindex2, int n2);</pre>
5559
Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code>
5560
refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>.
5568
<h1>5 – <a name="5">The Auxiliary Library</a></h1>
5572
The <em>auxiliary library</em> provides several convenient functions
5573
to interface C with Lua.
5574
While the basic API provides the primitive functions for all
5575
interactions between C and Lua,
5576
the auxiliary library provides higher-level functions for some
5581
All functions and types from the auxiliary library
5582
are defined in header file <code>lauxlib.h</code> and
5583
have a prefix <code>luaL_</code>.
5587
All functions in the auxiliary library are built on
5588
top of the basic API,
5589
and so they provide nothing that cannot be done with that API.
5590
Nevertheless, the use of the auxiliary library ensures
5591
more consistency to your code.
5595
Several functions in the auxiliary library use internally some
5597
When a function in the auxiliary library uses less than five slots,
5598
it does not check the stack size;
5599
it simply assumes that there are enough slots.
5603
Several functions in the auxiliary library are used to
5604
check C function arguments.
5605
Because the error message is formatted for arguments
5606
(e.g., "<code>bad argument #1</code>"),
5607
you should not use these functions for other stack values.
5611
Functions called <code>luaL_check*</code>
5612
always throw an error if the check is not satisfied.
5616
<h2>5.1 – <a name="5.1">Functions and Types</a></h2>
5619
Here we list all functions and types from the auxiliary library
5620
in alphabetical order.
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>
5629
Adds the byte <code>c</code> to the buffer <code>B</code>
5630
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
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>
5641
Adds the string pointed to by <code>s</code> with length <code>l</code> to
5642
the buffer <code>B</code>
5643
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5644
The string can contain embedded zeros.
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>
5655
Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>)
5656
a string of length <code>n</code> previously copied to the
5657
buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>).
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>
5668
Adds the zero-terminated string pointed to by <code>s</code>
5669
to the buffer <code>B</code>
5670
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5671
The string cannot contain embedded zeros.
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>
5682
Adds the value at the top of the stack
5683
to the buffer <code>B</code>
5684
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5689
This is the only function on string buffers that can (and must)
5690
be called with an extra element on the stack,
5691
which is the value to be added to the buffer.
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,
5702
const char *extramsg);</pre>
5705
Checks whether <code>cond</code> is true.
5706
If not, raises an error with a standard message.
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>
5717
Raises an error with a standard message
5718
that includes <code>extramsg</code> as a comment.
5722
This function never returns,
5723
but it is an idiom to use it in C functions
5724
as <code>return luaL_argerror(<em>args</em>)</code>.
5730
<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
5731
<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
5734
Type for a <em>string buffer</em>.
5738
A string buffer allows C code to build Lua strings piecemeal.
5739
Its pattern of use is as follows:
5743
<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
5745
<li>Then initialize it with a call <code>luaL_buffinit(L, &b)</code>.</li>
5748
Then add string pieces to the buffer calling any of
5749
the <code>luaL_add*</code> functions.
5753
Finish by calling <code>luaL_pushresult(&b)</code>.
5754
This call leaves the final string on the top of the stack.
5760
If you know beforehand the total size of the resulting string,
5761
you can use the buffer like this:
5765
<li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
5767
<li>Then initialize it and preallocate a space of
5768
size <code>sz</code> with a call <code>luaL_buffinitsize(L, &b, sz)</code>.</li>
5770
<li>Then copy the string into that space.</li>
5773
Finish by calling <code>luaL_pushresultsize(&b, sz)</code>,
5774
where <code>sz</code> is the total size of the resulting string
5775
copied into that space.
5781
During its normal operation,
5782
a string buffer uses a variable number of stack slots.
5783
So, while using a buffer, you cannot assume that you know where
5784
the top of the stack is.
5785
You can use the stack between successive calls to buffer operations
5786
as long as that use is balanced;
5788
when you call a buffer operation,
5789
the stack is at the same level
5790
it was immediately after the previous buffer operation.
5791
(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
5792
After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
5793
level when the buffer was initialized,
5794
plus the final string on its top.
5800
<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p>
5801
<span class="apii">[-0, +0, –]</span>
5802
<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
5805
Initializes a buffer <code>B</code>.
5806
This function does not allocate any space;
5807
the buffer must be declared as a variable
5808
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
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>
5819
Equivalent to the sequence
5820
<a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>.
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>
5835
If the object at index <code>obj</code> has a metatable and this
5836
metatable has a field <code>e</code>,
5837
this function calls this field passing the object as its only argument.
5838
In this case this function returns true and pushes onto the
5839
stack the value returned by the call.
5840
If there is no metatable or no metamethod,
5841
this function returns false (without pushing any value on the stack).
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>
5852
Checks whether the function has an argument
5853
of any type (including <b>nil</b>) at position <code>arg</code>.
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>
5864
Checks whether the function argument <code>arg</code> is a number
5865
and returns this number cast to an <code>int</code>.
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>
5876
Checks whether the function argument <code>arg</code> is a number
5877
and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
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>
5888
Checks whether the function argument <code>arg</code> is a number
5889
and returns this number cast to a <code>long</code>.
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>
5900
Checks whether the function argument <code>arg</code> is a string
5901
and returns this string;
5902
if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
5903
with the string's length.
5907
This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5908
so all conversions and caveats of that function apply here.
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>
5919
Checks whether the function argument <code>arg</code> is a number
5920
and returns this number.
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,
5931
const char *const lst[]);</pre>
5934
Checks whether the function argument <code>arg</code> is a string and
5935
searches for this string in the array <code>lst</code>
5936
(which must be NULL-terminated).
5937
Returns the index in the array where the string was found.
5938
Raises an error if the argument is not a string or
5939
if the string cannot be found.
5943
If <code>def</code> is not <code>NULL</code>,
5944
the function uses <code>def</code> as a default value when
5945
there is no argument <code>arg</code> or when this argument is <b>nil</b>.
5949
This is a useful function for mapping strings to C enums.
5950
(The usual convention in Lua libraries is
5951
to use strings instead of numbers to select options.)
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>
5962
Grows the stack size to <code>top + sz</code> elements,
5963
raising 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).
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>
5976
Checks whether the function argument <code>arg</code> is a string
5977
and returns this string.
5981
This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result,
5982
so all conversions and caveats of that function apply here.
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>
5993
Checks whether the function argument <code>arg</code> has type <code>t</code>.
5994
See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>.
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>
6005
Checks whether the function argument <code>arg</code> is a userdata
6006
of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and
6007
returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>).
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>
6018
Checks whether the function argument <code>arg</code> is a number
6019
and returns this number cast to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6025
<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
6026
<span class="apii">[-0, +0, –]</span>
6027
<pre>void luaL_checkversion (lua_State *L);</pre>
6030
Checks whether the core running the call,
6031
the core that created the Lua state,
6032
and the code making the call are all using the same version of Lua.
6033
Also checks whether the core running the call
6034
and the core that created the Lua state
6035
are using the same address space.
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>
6046
Loads and runs the given file.
6047
It is defined as the following macro:
6050
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
6052
It returns false if there are no errors
6053
or true in case of errors.
6059
<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p>
6060
<span class="apii">[-0, +?, –]</span>
6061
<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
6064
Loads and runs the given string.
6065
It is defined as the following macro:
6068
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
6070
It returns false if there are no errors
6071
or true in case of errors.
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>
6083
The error message format is given by <code>fmt</code>
6084
plus any extra arguments,
6085
following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
6086
It also adds at the beginning of the message the file name and
6087
the line number where the error occurred,
6088
if this information is available.
6092
This function never returns,
6093
but it is an idiom to use it in C functions
6094
as <code>return luaL_error(<em>args</em>)</code>.
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>
6105
This function produces the return values for
6106
process-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>).
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>
6118
This function produces the return values for
6119
file-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.).
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>
6131
Pushes onto the stack the field <code>e</code> from the metatable
6132
of the object at index <code>obj</code>.
6133
If the object does not have a metatable,
6134
or if the metatable does not have this field,
6135
returns false and pushes nothing.
6141
<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
6142
<span class="apii">[-0, +1, –]</span>
6143
<pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
6146
Pushes onto the stack the metatable associated with name <code>tname</code>
6147
in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
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>
6158
Ensures that the value <code>t[fname]</code>,
6159
where <code>t</code> is the value at index <code>idx</code>,
6161
and pushes that table onto the stack.
6162
Returns true if it finds a previous table there
6163
and false if it creates a new table.
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,
6174
const char *r);</pre>
6177
Creates a copy of string <code>s</code> by replacing
6178
any occurrence of the string <code>p</code>
6179
with the string <code>r</code>.
6180
Pushes the resulting string on the stack and returns it.
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>
6191
Returns the "length" of the value at the given index
6193
it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.6">§3.4.6</a>).
6194
Raises an error if the result of the operation is not a number.
6195
(This case only can happen through metamethods.)
6201
<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p>
6202
<span class="apii">[-0, +1, –]</span>
6203
<pre>int luaL_loadbuffer (lua_State *L,
6206
const char *name);</pre>
6209
Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>.
6215
<hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p>
6216
<span class="apii">[-0, +1, –]</span>
6217
<pre>int luaL_loadbufferx (lua_State *L,
6221
const char *mode);</pre>
6224
Loads a buffer as a Lua chunk.
6225
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
6226
buffer pointed to by <code>buff</code> with size <code>sz</code>.
6230
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6231
<code>name</code> is the chunk name,
6232
used for debug information and error messages.
6233
The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
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>
6244
Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>.
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>
6256
Loads a file as a Lua chunk.
6257
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
6258
named <code>filename</code>.
6259
If <code>filename</code> is <code>NULL</code>,
6260
then it loads from the standard input.
6261
The first line in the file is ignored if it starts with a <code>#</code>.
6265
The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>.
6269
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
6270
but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
6271
if it cannot open/read the file or the file has a wrong mode.
6275
As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
6282
<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p>
6283
<span class="apii">[-0, +1, –]</span>
6284
<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
6287
Loads a string as a Lua chunk.
6288
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
6289
the zero-terminated string <code>s</code>.
6293
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
6297
Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
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>
6309
Creates a new table and registers there
6310
the functions in list <code>l</code>.
6311
It is implemented as the following macro:
6314
(luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
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>
6325
Creates a new table with a size optimized
6326
to store all entries in the array <code>l</code>
6327
(but does not actually store them).
6328
It 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>).
6333
It is implemented as a macro.
6334
The array <code>l</code> must be the actual array,
6335
not a pointer to it.
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>
6346
If the registry already has the key <code>tname</code>,
6349
creates a new table to be used as a metatable for userdata,
6350
adds it to the registry with key <code>tname</code>,
6355
In both cases pushes onto the stack the final value associated
6356
with <code>tname</code> in the registry.
6362
<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p>
6363
<span class="apii">[-0, +0, –]</span>
6364
<pre>lua_State *luaL_newstate (void);</pre>
6367
Creates a new Lua state.
6368
It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an
6369
allocator based on the standard C <code>realloc</code> function
6370
and then sets a panic function (see <a href="#4.6">§4.6</a>) that prints
6371
an error message to the standard error output in case of fatal
6376
Returns the new state,
6377
or <code>NULL</code> if there is a memory allocation error.
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>
6388
Opens all standard Lua libraries into the given state.
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>
6399
If the function argument <code>arg</code> is a number,
6400
returns this number cast to an <code>int</code>.
6401
If this argument is absent or is <b>nil</b>,
6402
returns <code>d</code>.
6403
Otherwise, raises an error.
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,
6413
lua_Integer d);</pre>
6416
If the function argument <code>arg</code> is a number,
6417
returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6418
If this argument is absent or is <b>nil</b>,
6419
returns <code>d</code>.
6420
Otherwise, raises an error.
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>
6431
If the function argument <code>arg</code> is a number,
6432
returns this number cast to a <code>long</code>.
6433
If this argument is absent or is <b>nil</b>,
6434
returns <code>d</code>.
6435
Otherwise, raises an error.
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,
6449
If the function argument <code>arg</code> is a string,
6450
returns this string.
6451
If this argument is absent or is <b>nil</b>,
6452
returns <code>d</code>.
6453
Otherwise, raises an error.
6457
If <code>l</code> is not <code>NULL</code>,
6458
fills the position <code>*l</code> with the result's length.
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>
6469
If the function argument <code>arg</code> is a number,
6470
returns this number.
6471
If this argument is absent or is <b>nil</b>,
6472
returns <code>d</code>.
6473
Otherwise, raises an error.
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,
6483
const char *d);</pre>
6486
If the function argument <code>arg</code> is a string,
6487
returns this string.
6488
If this argument is absent or is <b>nil</b>,
6489
returns <code>d</code>.
6490
Otherwise, raises an error.
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,
6500
lua_Unsigned u);</pre>
6503
If the function argument <code>arg</code> is a number,
6504
returns this number cast to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6505
If this argument is absent or is <b>nil</b>,
6506
returns <code>u</code>.
6507
Otherwise, raises an error.
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>
6518
Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>
6519
with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>.
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>
6530
Returns an address to a space of size <code>sz</code>
6531
where you can copy a string to be added to buffer <code>B</code>
6532
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
6533
After 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
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>
6546
Finishes the use of buffer <code>B</code> leaving the final string on
6547
the top of the stack.
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>
6558
Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>.
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>
6569
Creates and returns a <em>reference</em>,
6570
in the table at index <code>t</code>,
6571
for the object at the top of the stack (and pops the object).
6575
A reference is a unique integer key.
6576
As 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.
6578
You can retrieve an object referred by reference <code>r</code>
6579
by calling <code>lua_rawgeti(L, t, r)</code>.
6580
Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
6584
If 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>.
6586
The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
6587
from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
6593
<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
6594
<pre>typedef struct luaL_Reg {
6600
Type 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
6604
Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
6605
in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
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>
6617
Calls function <code>openf</code> with string <code>modname</code> as an argument
6618
and sets the call result in <code>package.loaded[modname]</code>,
6619
as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
6623
If <code>glb</code> is true,
6624
also stores the result into global <code>modname</code>.
6628
Leaves a copy of that result on the stack.
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>
6639
Registers 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).
6645
When <code>nup</code> is not zero,
6646
all functions are created sharing <code>nup</code> upvalues,
6647
which must be previously pushed on the stack
6648
on top of the library table.
6649
These values are popped from the stack after the registration.
6655
<hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p>
6656
<span class="apii">[-0, +0, –]</span>
6657
<pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre>
6660
Sets the metatable of the object at the top of the stack
6661
as the metatable associated with name <code>tname</code>
6662
in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
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>
6673
This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
6674
except that, when the test fails,
6675
it returns <code>NULL</code> instead of throwing an error.
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>
6686
Converts any Lua value at the given index to a C string
6687
in a reasonable format.
6688
The resulting string is pushed onto the stack and also
6689
returned by the function.
6690
If <code>len</code> is not <code>NULL</code>,
6691
the function also sets <code>*len</code> with the string length.
6695
If the value has a metatable with a <code>"__tostring"</code> field,
6696
then <code>luaL_tolstring</code> calls the corresponding metamethod
6697
with the value as argument,
6698
and uses the result of the call as its result.
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,
6710
Creates and pushes a traceback of the stack <code>L1</code>.
6711
If <code>msg</code> is not <code>NULL</code> it is appended
6712
at the beginning of the traceback.
6713
The <code>level</code> parameter tells at which level
6714
to start the traceback.
6720
<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p>
6721
<span class="apii">[-0, +0, –]</span>
6722
<pre>const char *luaL_typename (lua_State *L, int index);</pre>
6725
Returns the name of the type of the value at the given index.
6731
<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p>
6732
<span class="apii">[-0, +0, –]</span>
6733
<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
6736
Releases reference <code>ref</code> from the table at index <code>t</code>
6737
(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
6738
The entry is removed from the table,
6739
so that the referred object can be collected.
6740
The reference <code>ref</code> is also freed to be used again.
6744
If <code>ref</code> is <a href="#pdf-LUA_NOREF"><code>LUA_NOREF</code></a> or <a href="#pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>,
6745
<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
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>
6756
Pushes onto the stack a string identifying the current position
6757
of the control at level <code>lvl</code> in the call stack.
6758
Typically this string has the following format:
6761
<em>chunkname</em>:<em>currentline</em>:
6763
Level 0 is the running function,
6764
level 1 is the function that called the running function,
6769
This function is used to build a prefix for error messages.
6777
<h1>6 – <a name="6">Standard Libraries</a></h1>
6780
The standard Lua libraries provide useful functions
6781
that are implemented directly through the C API.
6782
Some 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>);
6784
others provide access to "outside" services (e.g., I/O);
6785
and others could be implemented in Lua itself,
6786
but are quite useful or have critical performance requirements that
6787
deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>).
6791
All libraries are implemented through the official C API
6792
and are provided as separate C modules.
6793
Currently, Lua has the following standard libraries:
6797
<li>basic library (<a href="#6.1">§6.1</a>);</li>
6799
<li>coroutine library (<a href="#6.2">§6.2</a>);</li>
6801
<li>package library (<a href="#6.3">§6.3</a>);</li>
6803
<li>string manipulation (<a href="#6.4">§6.4</a>);</li>
6805
<li>table manipulation (<a href="#6.5">§6.5</a>);</li>
6807
<li>mathematical functions (<a href="#6.6">§6.6</a>) (sin, log, etc.);</li>
6809
<li>bitwise operations (<a href="#6.7">§6.7</a>);</li>
6811
<li>input and output (<a href="#6.8">§6.8</a>);</li>
6813
<li>operating system facilities (<a href="#6.9">§6.9</a>);</li>
6815
<li>debug facilities (<a href="#6.10">§6.10</a>).</li>
6818
Except for the basic and the package libraries,
6819
each library provides all its functions as fields of a global table
6820
or as methods of its objects.
6824
To have access to these libraries,
6825
the C host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function,
6826
which opens all standard libraries.
6828
the 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),
6839
and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
6840
These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
6844
<h2>6.1 – <a name="6.1">Basic Functions</a></h2>
6847
The basic library provides core functions to Lua.
6848
If you do not include this library in your application,
6849
you should check carefully whether you need to provide
6850
implementations for some of its facilities.
6854
<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
6855
Issues an error when
6856
the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
6857
otherwise, returns all its arguments.
6858
<code>message</code> is an error message;
6859
when absent, it defaults to "assertion failed!"
6865
<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3>
6869
This function is a generic interface to the garbage collector.
6870
It performs different functions according to its first argument, <code>opt</code>:
6874
<li><b>"<code>collect</code>": </b>
6875
performs a full garbage-collection cycle.
6876
This is the default option.
6879
<li><b>"<code>stop</code>": </b>
6880
stops automatic execution of the garbage collector.
6881
The collector will run only when explicitly invoked,
6882
until a call to restart it.
6885
<li><b>"<code>restart</code>": </b>
6886
restarts automatic execution of the garbage collector.
6889
<li><b>"<code>count</code>": </b>
6890
returns the total memory in use by Lua (in Kbytes) and
6891
a second value with the total memory in bytes modulo 1024.
6892
The first value has a fractional part,
6893
so the following equality is always true:
6896
k, b = collectgarbage("count")
6897
assert(k*1024 == math.floor(k)*1024 + b)
6899
(The second result is useful when Lua is compiled
6900
with a non floating-point type for numbers.)
6903
<li><b>"<code>step</code>": </b>
6904
performs a garbage-collection step.
6905
The step "size" is controlled by <code>arg</code>
6906
(larger values mean more steps) in a non-specified way.
6907
If you want to control the step size
6908
you must experimentally tune the value of <code>arg</code>.
6909
Returns <b>true</b> if the step finished a collection cycle.
6912
<li><b>"<code>setpause</code>": </b>
6913
sets <code>arg</code> as the new value for the <em>pause</em> of
6914
the collector (see <a href="#2.5">§2.5</a>).
6915
Returns the previous value for <em>pause</em>.
6918
<li><b>"<code>setstepmul</code>": </b>
6919
sets <code>arg</code> as the new value for the <em>step multiplier</em> of
6920
the collector (see <a href="#2.5">§2.5</a>).
6921
Returns the previous value for <em>step</em>.
6924
<li><b>"<code>isrunning</code>": </b>
6925
returns a boolean that tells whether the collector is running
6926
(i.e., not stopped).
6929
<li><b>"<code>generational</code>": </b>
6930
changes the collector to generational mode.
6931
This is an experimental feature (see <a href="#2.5">§2.5</a>).
6934
<li><b>"<code>incremental</code>": </b>
6935
changes the collector to incremental mode.
6936
This is the default mode.
6944
<hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3>
6945
Opens the named file and executes its contents as a Lua chunk.
6946
When called without arguments,
6947
<code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
6948
Returns all values returned by the chunk.
6949
In case of errors, <code>dofile</code> propagates the error
6950
to its caller (that is, <code>dofile</code> does not run in protected mode).
6956
<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
6957
Terminates the last protected function called
6958
and returns <code>message</code> as the error message.
6959
Function <code>error</code> never returns.
6963
Usually, <code>error</code> adds some information about the error position
6964
at the beginning of the message, if the message is a string.
6965
The <code>level</code> argument specifies how to get the error position.
6966
With level 1 (the default), the error position is where the
6967
<code>error</code> function was called.
6968
Level 2 points the error to where the function
6969
that called <code>error</code> was called; and so on.
6970
Passing a level 0 avoids the addition of error position information
6977
<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
6978
A global variable (not a function) that
6979
holds the global environment (see <a href="#2.2">§2.2</a>).
6980
Lua itself does not use this variable;
6981
changing its value does not affect any environment,
6988
<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
6992
If <code>object</code> does not have a metatable, returns <b>nil</b>.
6994
if the object's metatable has a <code>"__metatable"</code> field,
6995
returns the associated value.
6996
Otherwise, returns the metatable of the given object.
7002
<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
7006
If <code>t</code> has a metamethod <code>__ipairs</code>,
7007
calls it with <code>t</code> as argument and returns the first three
7008
results from the call.
7013
returns three values: an iterator function, the table <code>t</code>, and 0,
7014
so that the construction
7017
for i,v in ipairs(t) do <em>body</em> end
7019
will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7020
up to the first integer key absent from the table.
7026
<hr><h3><a name="pdf-load"><code>load (ld [, source [, mode [, env]]])</code></a></h3>
7034
If <code>ld</code> is a string, the chunk is this string.
7035
If <code>ld</code> is a function,
7036
<code>load</code> calls it repeatedly to get the chunk pieces.
7037
Each call to <code>ld</code> must return a string that concatenates
7038
with previous results.
7039
A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
7043
If there are no syntactic errors,
7044
returns the compiled chunk as a function;
7045
otherwise, returns <b>nil</b> plus the error message.
7049
If the resulting function has upvalues,
7050
the first upvalue is set to the value of <code>env</code>,
7051
if that parameter is given,
7052
or to the value of the global environment.
7053
(When you load a main chunk,
7054
the resulting function will always have exactly one upvalue,
7055
the <code>_ENV</code> variable (see <a href="#2.2">§2.2</a>).
7056
When you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7057
the resulting function can have arbitrary upvalues.)
7061
<code>source</code> is used as the source of the chunk for error messages
7062
and debug information (see <a href="#4.9">§4.9</a>).
7064
it defaults to <code>ld</code>, if <code>ld</code> is a string,
7065
or to "<code>=(load)</code>" otherwise.
7069
The string <code>mode</code> controls whether the chunk can be text or binary
7070
(that is, a precompiled chunk).
7071
It may be the string "<code>b</code>" (only binary chunks),
7072
"<code>t</code>" (only text chunks),
7073
or "<code>bt</code>" (both binary and text).
7074
The default is "<code>bt</code>".
7080
<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
7084
Similar to <a href="#pdf-load"><code>load</code></a>,
7085
but gets the chunk from file <code>filename</code>
7086
or from the standard input,
7087
if no file name is given.
7093
<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
7097
Allows a program to traverse all fields of a table.
7098
Its first argument is a table and its second argument
7099
is an index in this table.
7100
<code>next</code> returns the next index of the table
7101
and its associated value.
7102
When called with <b>nil</b> as its second argument,
7103
<code>next</code> returns an initial index
7104
and its associated value.
7105
When called with the last index,
7106
or with <b>nil</b> in an empty table,
7107
<code>next</code> returns <b>nil</b>.
7108
If the second argument is absent, then it is interpreted as <b>nil</b>.
7110
you can use <code>next(t)</code> to check whether a table is empty.
7114
The 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,
7117
use a numerical <b>for</b>.)
7121
The behavior of <code>next</code> is undefined if,
7122
during the traversal,
7123
you assign any value to a non-existent field in the table.
7124
You may however modify existing fields.
7125
In particular, you may clear existing fields.
7131
<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
7135
If <code>t</code> has a metamethod <code>__pairs</code>,
7136
calls it with <code>t</code> as argument and returns the first three
7137
results from the call.
7142
returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
7143
so that the construction
7146
for k,v in pairs(t) do <em>body</em> end
7148
will iterate over all key–value pairs of table <code>t</code>.
7152
See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying
7153
the table during its traversal.
7159
<hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, ···])</code></a></h3>
7163
Calls function <code>f</code> with
7164
the given arguments in <em>protected mode</em>.
7165
This means that any error inside <code>f</code> is not propagated;
7166
instead, <code>pcall</code> catches the error
7167
and returns a status code.
7168
Its first result is the status code (a boolean),
7169
which is true if the call succeeds without errors.
7170
In such case, <code>pcall</code> also returns all results from the call,
7171
after this first result.
7172
In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
7178
<hr><h3><a name="pdf-print"><code>print (···)</code></a></h3>
7179
Receives any number of arguments
7180
and prints their values to <code>stdout</code>,
7181
using 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,
7183
but only as a quick way to show a value,
7184
for instance for debugging.
7185
For complete control over the output,
7186
use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>.
7192
<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
7193
Checks whether <code>v1</code> is equal to <code>v2</code>,
7194
without invoking any metamethod.
7201
<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
7202
Gets the real value of <code>table[index]</code>,
7203
without invoking any metamethod.
7204
<code>table</code> must be a table;
7205
<code>index</code> may be any value.
7211
<hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3>
7212
Returns the length of the object <code>v</code>,
7213
which must be a table or a string,
7214
without invoking any metamethod.
7215
Returns an integer number.
7221
<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
7222
Sets the real value of <code>table[index]</code> to <code>value</code>,
7223
without invoking any metamethod.
7224
<code>table</code> must be a table,
7225
<code>index</code> any value different from <b>nil</b> and NaN,
7226
and <code>value</code> any Lua value.
7230
This function returns <code>table</code>.
7236
<hr><h3><a name="pdf-select"><code>select (index, ···)</code></a></h3>
7240
If <code>index</code> is a number,
7241
returns all arguments after argument number <code>index</code>;
7242
a negative number indexes from the end (-1 is the last argument).
7243
Otherwise, <code>index</code> must be the string <code>"#"</code>,
7244
and <code>select</code> returns the total number of extra arguments it received.
7250
<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
7254
Sets the metatable for the given table.
7255
(You cannot change the metatable of other types from Lua, only from C.)
7256
If <code>metatable</code> is <b>nil</b>,
7257
removes the metatable of the given table.
7258
If the original metatable has a <code>"__metatable"</code> field,
7263
This function returns <code>table</code>.
7269
<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
7273
When called with no <code>base</code>,
7274
<code>tonumber</code> tries to convert its argument to a number.
7275
If the argument is already a number or
7276
a string convertible to a number (see <a href="#3.4.2">§3.4.2</a>),
7277
then <code>tonumber</code> returns this number;
7278
otherwise, it returns <b>nil</b>.
7282
When called with <code>base</code>,
7283
then <code>e</code> should be a string to be interpreted as
7284
an integer numeral in that base.
7285
The base may be any integer between 2 and 36, inclusive.
7286
In bases above 10, the letter '<code>A</code>' (in either upper or lower case)
7287
represents 10, '<code>B</code>' represents 11, and so forth,
7288
with '<code>Z</code>' representing 35.
7289
If the string <code>e</code> is not a valid numeral in the given base,
7290
the function returns <b>nil</b>.
7296
<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
7297
Receives a value of any type and
7298
converts it to a string in a reasonable format.
7299
(For complete control of how numbers are converted,
7300
use <a href="#pdf-string.format"><code>string.format</code></a>.)
7304
If the metatable of <code>v</code> has a <code>"__tostring"</code> field,
7305
then <code>tostring</code> calls the corresponding value
7306
with <code>v</code> as argument,
7307
and uses the result of the call as its result.
7313
<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
7314
Returns the type of its only argument, coded as a string.
7315
The 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>",
7323
and "<code>userdata</code>".
7329
<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
7330
A global variable (not a function) that
7331
holds a string containing the current interpreter version.
7332
The current contents of this variable is "<code>Lua 5.2</code>".
7338
<hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, ···])</code></a></h3>
7342
This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>,
7343
except that it sets a new message handler <code>msgh</code>.
7351
<h2>6.2 – <a name="6.2">Coroutine Manipulation</a></h2>
7354
The operations related to coroutines comprise a sub-library of
7355
the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
7356
See <a href="#2.6">§2.6</a> for a general description of coroutines.
7360
<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
7364
Creates a new coroutine, with body <code>f</code>.
7365
<code>f</code> must be a Lua function.
7366
Returns this new coroutine,
7367
an object with type <code>"thread"</code>.
7373
<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, ···])</code></a></h3>
7377
Starts or continues the execution of coroutine <code>co</code>.
7378
The first time you resume a coroutine,
7379
it starts running its body.
7380
The values <code>val1</code>, ... are passed
7381
as the arguments to the body function.
7382
If the coroutine has yielded,
7383
<code>resume</code> restarts it;
7384
the values <code>val1</code>, ... are passed
7385
as the results from the yield.
7389
If 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).
7393
If there is any error,
7394
<code>resume</code> returns <b>false</b> plus the error message.
7400
<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
7404
Returns the running coroutine plus a boolean,
7405
true when the running coroutine is the main one.
7411
<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
7415
Returns the status of coroutine <code>co</code>, as a string:
7416
<code>"running"</code>,
7417
if 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>,
7419
or 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);
7422
and <code>"dead"</code> if the coroutine has finished its body function,
7423
or if it has stopped with an error.
7429
<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
7433
Creates a new coroutine, with body <code>f</code>.
7434
<code>f</code> must be a Lua function.
7435
Returns a function that resumes the coroutine each time it is called.
7436
Any arguments passed to the function behave as the
7437
extra arguments to <code>resume</code>.
7438
Returns the same values returned by <code>resume</code>,
7439
except the first boolean.
7440
In case of error, propagates the error.
7446
<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (···)</code></a></h3>
7450
Suspends the execution of the calling coroutine.
7451
Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
7459
<h2>6.3 – <a name="6.3">Modules</a></h2>
7462
The package library provides basic
7463
facilities for loading modules in Lua.
7464
It exports one function directly in the global environment:
7465
<a href="#pdf-require"><code>require</code></a>.
7466
Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
7470
<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
7474
Loads the given module.
7475
The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table
7476
to determine whether <code>modname</code> is already loaded.
7477
If it is, then <code>require</code> returns the value stored
7478
at <code>package.loaded[modname]</code>.
7479
Otherwise, it tries to find a <em>loader</em> for the module.
7484
<code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence.
7485
By changing this sequence,
7486
we can change how <code>require</code> looks for a module.
7487
The following explanation is based on the default configuration
7488
for <a href="#pdf-package.searchers"><code>package.searchers</code></a>.
7492
First <code>require</code> queries <code>package.preload[modname]</code>.
7494
this value (which should be a function) is the loader.
7495
Otherwise <code>require</code> searches for a Lua loader using the
7496
path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
7497
If that also fails, it searches for a C loader using the
7498
path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7500
it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>).
7504
Once 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,
7508
this extra value is the file name.)
7509
If the loader returns any non-nil value,
7510
<code>require</code> assigns the returned value to <code>package.loaded[modname]</code>.
7511
If the loader does not return a non-nil value and
7512
has not assigned any value to <code>package.loaded[modname]</code>,
7513
then <code>require</code> assigns <b>true</b> to this entry.
7514
In any case, <code>require</code> returns the
7515
final value of <code>package.loaded[modname]</code>.
7519
If there is any error loading or running the module,
7520
or if it cannot find any loader for the module,
7521
then <code>require</code> raises an error.
7527
<hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3>
7531
A string describing some compile-time configurations for packages.
7532
This string is a sequence of lines:
7536
<li>The first line is the directory separator string.
7537
Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li>
7539
<li>The second line is the character that separates templates in a path.
7540
Default is '<code>;</code>'.</li>
7542
<li>The third line is the string that marks the
7543
substitution points in a template.
7544
Default is '<code>?</code>'.</li>
7546
<li>The fourth line is a string that, in a path in Windows,
7547
is replaced by the executable's directory.
7548
Default is '<code>!</code>'.</li>
7550
<li>The fifth line is a mark to ignore all text before it
7551
when building the <code>luaopen_</code> function name.
7552
Default is '<code>-</code>'.</li>
7559
<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
7563
The path used by <a href="#pdf-require"><code>require</code></a> to search for a C loader.
7567
Lua initializes the C path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
7568
it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7569
using the environment variable <a name="pdf-LUA_CPATH_5_2"><code>LUA_CPATH_5_2</code></a>
7570
or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
7571
or a default path defined in <code>luaconf.h</code>.
7577
<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
7581
A table used by <a href="#pdf-require"><code>require</code></a> to control which
7582
modules are already loaded.
7583
When 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.
7589
This variable is only a reference to the real table;
7590
assignments to this variable do not change the
7591
table used by <a href="#pdf-require"><code>require</code></a>.
7597
<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
7601
Dynamically links the host program with the C library <code>libname</code>.
7605
If <code>funcname</code> is "<code>*</code>",
7606
then it only links with the library,
7607
making the symbols exported by the library
7608
available to other dynamically linked libraries.
7610
it looks for a function <code>funcname</code> inside the library
7611
and returns this function as a C function.
7612
So, <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>).
7617
This is a low-level function.
7618
It completely bypasses the package and module system.
7619
Unlike <a href="#pdf-require"><code>require</code></a>,
7620
it does not perform any path searching and
7621
does not automatically adds extensions.
7622
<code>libname</code> must be the complete file name of the C library,
7623
including if necessary a path and an extension.
7624
<code>funcname</code> must be the exact name exported by the C library
7625
(which may depend on the C compiler and linker used).
7629
This function is not supported by Standard C.
7630
As such, it is only available on some platforms
7631
(Windows, Linux, Mac OS X, Solaris, BSD,
7632
plus other Unix systems that support the <code>dlfcn</code> standard).
7638
<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
7642
The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
7646
At start-up, Lua initializes this variable with
7647
the value of the environment variable <a name="pdf-LUA_PATH_5_2"><code>LUA_PATH_5_2</code></a> or
7648
the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
7649
with a default path defined in <code>luaconf.h</code>,
7650
if those environment variables are not defined.
7651
Any "<code>;;</code>" in the value of the environment variable
7652
is replaced by the default path.
7658
<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
7662
A table to store loaders for specific modules
7663
(see <a href="#pdf-require"><code>require</code></a>).
7667
This variable is only a reference to the real table;
7668
assignments to this variable do not change the
7669
table used by <a href="#pdf-require"><code>require</code></a>.
7675
<hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3>
7679
A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules.
7683
Each entry in this table is a <em>searcher function</em>.
7684
When looking for a module,
7685
<a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order,
7686
with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its
7688
The function can return another function (the module <em>loader</em>)
7689
plus an extra value that will be passed to that loader,
7690
or a string explaining why it did not find that module
7691
(or <b>nil</b> if it has nothing to say).
7695
Lua initializes this table with four searcher functions.
7699
The first searcher simply looks for a loader in the
7700
<a href="#pdf-package.preload"><code>package.preload</code></a> table.
7704
The second searcher looks for a loader as a Lua library,
7705
using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>.
7706
The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7710
The third searcher looks for a loader as a C library,
7711
using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
7713
the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7715
if the C path is the string
7718
"./?.so;./?.dll;/usr/local/?/init.so"
7720
the searcher for module <code>foo</code>
7721
will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>,
7722
and <code>/usr/local/foo/init.so</code>, in that order.
7723
Once it finds a C library,
7724
this searcher first uses a dynamic link facility to link the
7725
application with the library.
7726
Then it tries to find a C function inside the library to
7727
be used as the loader.
7728
The name of this C function is the string "<code>luaopen_</code>"
7729
concatenated with a copy of the module name where each dot
7730
is replaced by an underscore.
7731
Moreover, if the module name has a hyphen,
7732
its prefix up to (and including) the first hyphen is removed.
7733
For instance, if the module name is <code>a.v1-b.c</code>,
7734
the function name will be <code>luaopen_b_c</code>.
7738
The fourth searcher tries an <em>all-in-one loader</em>.
7739
It searches the C path for a library for
7740
the root name of the given module.
7741
For instance, when requiring <code>a.b.c</code>,
7742
it will search for a C library for <code>a</code>.
7743
If found, it looks into it for an open function for
7745
in our example, that would be <code>luaopen_a_b_c</code>.
7746
With this facility, a package can pack several C submodules
7747
into one single library,
7748
with each submodule keeping its original open function.
7752
All searchers except the first one (preload) return as the extra value
7753
the file name where the module was found,
7754
as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>.
7755
The first searcher returns no extra value.
7761
<hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3>
7765
Searches for the given <code>name</code> in the given <code>path</code>.
7769
A path is a string containing a sequence of
7770
<em>templates</em> separated by semicolons.
7772
the function replaces each interrogation mark (if any)
7773
in the template with a copy of <code>name</code>
7774
wherein all occurrences of <code>sep</code>
7776
were replaced by <code>rep</code>
7777
(the system's directory separator, by default),
7778
and then tries to open the resulting file name.
7782
For instance, if the path is the string
7785
"./?.lua;./?.lc;/usr/local/?/init.lua"
7787
the search for the name <code>foo.a</code>
7788
will 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.
7794
Returns the resulting name of the first file that it can
7795
open in read mode (after closing the file),
7796
or <b>nil</b> plus an error message if none succeeds.
7797
(This error message lists all file names it tried to open.)
7805
<h2>6.4 – <a name="6.4">String Manipulation</a></h2>
7808
This library provides generic functions for string manipulation,
7809
such as finding and extracting substrings, and pattern matching.
7810
When indexing a string in Lua, the first character is at position 1
7811
(not at 0, as in C).
7812
Indices are allowed to be negative and are interpreted as indexing backwards,
7813
from the end of the string.
7814
Thus, the last character is at position -1, and so on.
7818
The string library provides all its functions inside the table
7819
<a name="pdf-string"><code>string</code></a>.
7820
It also sets a metatable for strings
7821
where the <code>__index</code> field points to the <code>string</code> table.
7822
Therefore, you can use the string functions in object-oriented style.
7823
For instance, <code>string.byte(s,i)</code>
7824
can be written as <code>s:byte(i)</code>.
7828
The string library assumes one-byte character encodings.
7832
<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
7833
Returns the internal numerical codes of the characters <code>s[i]</code>,
7834
<code>s[i+1]</code>, ..., <code>s[j]</code>.
7835
The default value for <code>i</code> is 1;
7836
the default value for <code>j</code> is <code>i</code>.
7837
These indices are corrected
7838
following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>.
7842
Numerical codes are not necessarily portable across platforms.
7848
<hr><h3><a name="pdf-string.char"><code>string.char (···)</code></a></h3>
7849
Receives zero or more integers.
7850
Returns a string with length equal to the number of arguments,
7851
in which each character has the internal numerical code equal
7852
to its corresponding argument.
7856
Numerical codes are not necessarily portable across platforms.
7862
<hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
7866
Returns a string containing a binary representation of the given function,
7867
so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
7868
a copy of the function (but with new upvalues).
7874
<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
7878
Looks for the first match of
7879
<code>pattern</code> in the string <code>s</code>.
7880
If it finds a match, then <code>find</code> returns the indices of <code>s</code>
7881
where this occurrence starts and ends;
7882
otherwise, it returns <b>nil</b>.
7883
A third, optional numerical argument <code>init</code> specifies
7884
where to start the search;
7885
its default value is 1 and can be negative.
7886
A value of <b>true</b> as a fourth, optional argument <code>plain</code>
7887
turns off the pattern matching facilities,
7888
so the function does a plain "find substring" operation,
7889
with no characters in <code>pattern</code> being considered magic.
7890
Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
7894
If the pattern has captures,
7895
then in a successful match
7896
the captured values are also returned,
7897
after the two indices.
7903
<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, ···)</code></a></h3>
7907
Returns a formatted version of its variable number of arguments
7908
following the description given in its first argument (which must be a string).
7909
The format string follows the same rules as the ANSI C function <code>sprintf</code>.
7910
The only differences are that the options/modifiers
7911
<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
7912
and <code>p</code> are not supported
7913
and that there is an extra option, <code>q</code>.
7914
The <code>q</code> option formats a string between double quotes,
7915
using escape sequences when necessary to ensure that
7916
it can safely be read back by the Lua interpreter.
7917
For instance, the call
7920
string.format('%q', 'a string with "quotes" and \n new line')
7922
may produce the string:
7925
"a string with \"quotes\" and \
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.
7934
Options <code>c</code>, <code>d</code>,
7935
<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
7936
also expect a number,
7937
but the range of that number may be limited by
7938
the underlying C implementation.
7939
For options <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>,
7940
the number cannot be negative.
7941
Option <code>q</code> expects a string;
7942
option <code>s</code> expects a string without embedded zeros.
7943
If the argument to option <code>s</code> is not a string,
7944
it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>.
7950
<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
7951
Returns an iterator function that,
7952
each time it is called,
7953
returns the next captures from <code>pattern</code> over the string <code>s</code>.
7954
If <code>pattern</code> specifies no captures,
7955
then the whole match is produced in each call.
7959
As an example, the following loop
7960
will iterate over all the words from string <code>s</code>,
7961
printing one per line:
7964
s = "hello world from Lua"
7965
for w in string.gmatch(s, "%a+") do
7969
The next example collects all pairs <code>key=value</code> from the
7970
given string into a table:
7974
s = "from=world, to=Lua"
7975
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
7981
For this function, a caret '<code>^</code>' at the start of a pattern does not
7982
work as an anchor, as this would prevent the iteration.
7988
<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
7989
Returns a copy of <code>s</code>
7990
in which all (or the first <code>n</code>, if given)
7991
occurrences of the <code>pattern</code> have been
7992
replaced by a replacement string specified by <code>repl</code>,
7993
which can be a string, a table, or a function.
7994
<code>gsub</code> also returns, as its second value,
7995
the total number of matches that occurred.
7996
The name <code>gsub</code> comes from <em>Global SUBstitution</em>.
8000
If <code>repl</code> is a string, then its value is used for replacement.
8001
The character <code>%</code> works as an escape character:
8002
any sequence in <code>repl</code> of the form <code>%<em>d</em></code>,
8003
with <em>d</em> between 1 and 9,
8004
stands for the value of the <em>d</em>-th captured substring.
8005
The sequence <code>%0</code> stands for the whole match.
8006
The sequence <code>%%</code> stands for a single <code>%</code>.
8010
If <code>repl</code> is a table, then the table is queried for every match,
8011
using the first capture as the key.
8015
If <code>repl</code> is a function, then this function is called every time a
8016
match occurs, with all captured substrings passed as arguments,
8022
if the pattern specifies no captures,
8023
then it behaves as if the whole pattern was inside a capture.
8027
If the value returned by the table query or by the function call
8028
is a string or a number,
8029
then it is used as the replacement string;
8030
otherwise, if it is <b>false</b> or <b>nil</b>,
8031
then there is no replacement
8032
(that is, the original match is kept in the string).
8036
Here are some examples:
8039
x = string.gsub("hello world", "(%w+)", "%1 %1")
8040
--> x="hello hello world world"
8042
x = string.gsub("hello world", "%w+", "%0 %0", 1)
8043
--> x="hello hello world"
8045
x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
8046
--> x="world hello Lua from"
8048
x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
8049
--> x="home = /home/roberto, user = roberto"
8051
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
8056
local t = {name="lua", version="5.2"}
8057
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8058
--> x="lua-5.2.tar.gz"
8064
<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
8065
Receives a string and returns its length.
8066
The empty string <code>""</code> has length 0.
8067
Embedded zeros are counted,
8068
so <code>"a\000bc\000"</code> has length 5.
8074
<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
8075
Receives a string and returns a copy of this string with all
8076
uppercase letters changed to lowercase.
8077
All other characters are left unchanged.
8078
The definition of what an uppercase letter is depends on the current locale.
8084
<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
8085
Looks for the first <em>match</em> of
8086
<code>pattern</code> in the string <code>s</code>.
8087
If it finds one, then <code>match</code> returns
8088
the captures from the pattern;
8089
otherwise it returns <b>nil</b>.
8090
If <code>pattern</code> specifies no captures,
8091
then the whole match is returned.
8092
A third, optional numerical argument <code>init</code> specifies
8093
where to start the search;
8094
its default value is 1 and can be negative.
8100
<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
8101
Returns a string that is the concatenation of <code>n</code> copies of
8102
the string <code>s</code> separated by the string <code>sep</code>.
8103
The default value for <code>sep</code> is the empty string
8104
(that is, no separator).
8110
<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
8111
Returns a string that is the string <code>s</code> reversed.
8117
<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
8118
Returns the substring of <code>s</code> that
8119
starts at <code>i</code> and continues until <code>j</code>;
8120
<code>i</code> and <code>j</code> can be negative.
8121
If <code>j</code> is absent, then it is assumed to be equal to -1
8122
(which is the same as the string length).
8124
the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
8125
with length <code>j</code>,
8126
and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
8127
with length <code>i</code>.
8131
If, after the translation of negative indices,
8132
<code>i</code> is less than 1,
8133
it is corrected to 1.
8134
If <code>j</code> is greater than the string length,
8135
it is corrected to that length.
8136
If, after these corrections,
8137
<code>i</code> is greater than <code>j</code>,
8138
the function returns the empty string.
8144
<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
8145
Receives a string and returns a copy of this string with all
8146
lowercase letters changed to uppercase.
8147
All other characters are left unchanged.
8148
The definition of what a lowercase letter is depends on the current locale.
8152
<h3>6.4.1 – <a name="6.4.1">Patterns</a></h3>
8155
<h4>Character Class:</h4><p>
8156
A <em>character class</em> is used to represent a set of characters.
8157
The following combinations are allowed in describing a character class:
8161
<li><b><em>x</em>: </b>
8162
(where <em>x</em> is not one of the <em>magic characters</em>
8163
<code>^$()%.[]*+-?</code>)
8164
represents the character <em>x</em> itself.
8167
<li><b><code>.</code>: </b> (a dot) represents all characters.</li>
8169
<li><b><code>%a</code>: </b> represents all letters.</li>
8171
<li><b><code>%c</code>: </b> represents all control characters.</li>
8173
<li><b><code>%d</code>: </b> represents all digits.</li>
8175
<li><b><code>%g</code>: </b> represents all printable characters except space.</li>
8177
<li><b><code>%l</code>: </b> represents all lowercase letters.</li>
8179
<li><b><code>%p</code>: </b> represents all punctuation characters.</li>
8181
<li><b><code>%s</code>: </b> represents all space characters.</li>
8183
<li><b><code>%u</code>: </b> represents all uppercase letters.</li>
8185
<li><b><code>%w</code>: </b> represents all alphanumeric characters.</li>
8187
<li><b><code>%x</code>: </b> represents all hexadecimal digits.</li>
8189
<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
8190
represents the character <em>x</em>.
8191
This is the standard way to escape the magic characters.
8192
Any punctuation character (even the non magic)
8193
can be preceded by a '<code>%</code>'
8194
when used to represent itself in a pattern.
8197
<li><b><code>[<em>set</em>]</code>: </b>
8198
represents the class which is the union of all
8199
characters in <em>set</em>.
8200
A range of characters can be specified by
8201
separating the end characters of the range,
8202
in ascending order, with a '<code>-</code>',
8203
All classes <code>%</code><em>x</em> described above can also be used as
8204
components in <em>set</em>.
8205
All other characters in <em>set</em> represent themselves.
8206
For example, <code>[%w_]</code> (or <code>[_%w]</code>)
8207
represents all alphanumeric characters plus the underscore,
8208
<code>[0-7]</code> represents the octal digits,
8209
and <code>[0-7%l%-]</code> represents the octal digits plus
8210
the lowercase letters plus the '<code>-</code>' character.
8214
The interaction between ranges and classes is not defined.
8215
Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
8219
<li><b><code>[^<em>set</em>]</code>: </b>
8220
represents the complement of <em>set</em>,
8221
where <em>set</em> is interpreted as above.
8225
For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
8226
the corresponding uppercase letter represents the complement of the class.
8227
For instance, <code>%S</code> represents all non-space characters.
8231
The definitions of letter, space, and other character groups
8232
depend on the current locale.
8233
In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
8239
<h4>Pattern Item:</h4><p>
8240
A <em>pattern item</em> can be
8245
a single character class,
8246
which matches any single character in the class;
8250
a single character class followed by '<code>*</code>',
8251
which matches 0 or more repetitions of characters in the class.
8252
These repetition items will always match the longest possible sequence;
8256
a single character class followed by '<code>+</code>',
8257
which matches 1 or more repetitions of characters in the class.
8258
These repetition items will always match the longest possible sequence;
8262
a single character class followed by '<code>-</code>',
8263
which also matches 0 or more repetitions of characters in the class.
8264
Unlike '<code>*</code>',
8265
these repetition items will always match the shortest possible sequence;
8269
a single character class followed by '<code>?</code>',
8270
which matches 0 or 1 occurrence of a character in the class;
8274
<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
8275
such item matches a substring equal to the <em>n</em>-th captured string
8280
<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
8281
such item matches strings that start with <em>x</em>, end with <em>y</em>,
8282
and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
8283
This means that, if one reads the string from left to right,
8284
counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
8285
the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
8286
For instance, the item <code>%b()</code> matches expressions with
8287
balanced parentheses.
8291
<code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>;
8292
such item matches an empty string at any position such that
8293
the next character belongs to <em>set</em>
8294
and the previous character does not belong to <em>set</em>.
8295
The set <em>set</em> is interpreted as previously described.
8296
The beginning and the end of the subject are handled as if
8297
they were the character '<code>\0</code>'.
8305
<h4>Pattern:</h4><p>
8306
A <em>pattern</em> is a sequence of pattern items.
8307
A caret '<code>^</code>' at the beginning of a pattern anchors the match at the
8308
beginning of the subject string.
8309
A '<code>$</code>' at the end of a pattern anchors the match at the
8310
end of the subject string.
8312
'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
8318
<h4>Captures:</h4><p>
8319
A pattern can contain sub-patterns enclosed in parentheses;
8320
they describe <em>captures</em>.
8321
When a match succeeds, the substrings of the subject string
8322
that match captures are stored (<em>captured</em>) for future use.
8323
Captures are numbered according to their left parentheses.
8324
For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
8325
the part of the string matching <code>"a*(.)%w(%s*)"</code> is
8326
stored as the first capture (and therefore has number 1);
8327
the character matching "<code>.</code>" is captured with number 2,
8328
and the part matching "<code>%s*</code>" has number 3.
8332
As a special case, the empty capture <code>()</code> captures
8333
the current string position (a number).
8334
For instance, if we apply the pattern <code>"()aa()"</code> on the
8335
string <code>"flaaap"</code>, there will be two captures: 3 and 5.
8347
<h2>6.5 – <a name="6.5">Table Manipulation</a></h2>
8350
This library provides generic functions for table manipulation.
8351
It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
8355
Remember that, whenever an operation needs the length of a table,
8356
the table should be a proper sequence
8357
or have a <code>__len</code> metamethod (see <a href="#3.4.6">§3.4.6</a>).
8358
All functions ignore non-numeric keys
8359
in tables given as arguments.
8363
For performance reasons,
8364
all table accesses (get/set) performed by these functions are raw.
8368
<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
8372
Given a list where all elements are strings or numbers,
8373
returns the string <code>list[i]..sep..list[i+1] ··· sep..list[j]</code>.
8374
The default value for <code>sep</code> is the empty string,
8375
the default for <code>i</code> is 1,
8376
and the default for <code>j</code> is <code>#list</code>.
8377
If <code>i</code> is greater than <code>j</code>, returns the empty string.
8383
<hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3>
8387
Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>,
8388
shifting up the elements
8389
<code>list[pos], list[pos+1], ···, list[#list]</code>.
8390
The default value for <code>pos</code> is <code>#list+1</code>,
8391
so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
8392
of list <code>t</code>.
8398
<hr><h3><a name="pdf-table.pack"><code>table.pack (···)</code></a></h3>
8402
Returns a new table with all parameters stored into keys 1, 2, etc.
8403
and with a field "<code>n</code>" with the total number of parameters.
8404
Note that the resulting table may not be a sequence.
8410
<hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3>
8414
Removes from <code>list</code> the element at position <code>pos</code>,
8415
returning the value of the removed element.
8416
When <code>pos</code> is an integer between 1 and <code>#list</code>,
8417
it shifts down the elements
8418
<code>list[pos+1], list[pos+2], ···, list[#list]</code>
8419
and erases element <code>list[#list]</code>;
8420
The index <code>pos</code> can also be 0 when <code>#list</code> is 0,
8421
or <code>#list + 1</code>;
8422
in those cases, the function erases the element <code>list[pos]</code>.
8426
The default value for <code>pos</code> is <code>#list</code>,
8427
so that a call <code>table.remove(t)</code> removes the last element
8428
of list <code>t</code>.
8434
<hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3>
8438
Sorts list elements in a given order, <em>in-place</em>,
8439
from <code>list[1]</code> to <code>list[#list]</code>.
8440
If <code>comp</code> is given,
8441
then it must be a function that receives two list elements
8442
and returns true when the first element must come
8443
before the second in the final order
8444
(so that <code>not comp(list[i+1],list[i])</code> will be true after the sort).
8445
If <code>comp</code> is not given,
8446
then the standard Lua operator <code><</code> is used instead.
8450
The sort algorithm is not stable;
8451
that is, elements considered equal by the given order
8452
may have their relative positions changed by the sort.
8458
<hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3>
8462
Returns the elements from the given table.
8463
This function is equivalent to
8466
return list[i], list[i+1], ···, list[j]
8468
By default, <code>i</code> is 1 and <code>j</code> is <code>#list</code>.
8476
<h2>6.6 – <a name="6.6">Mathematical Functions</a></h2>
8479
This library is an interface to the standard C math library.
8480
It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
8484
<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
8488
Returns the absolute value of <code>x</code>.
8494
<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
8498
Returns the arc cosine of <code>x</code> (in radians).
8504
<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
8508
Returns the arc sine of <code>x</code> (in radians).
8514
<hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
8518
Returns the arc tangent of <code>x</code> (in radians).
8524
<hr><h3><a name="pdf-math.atan2"><code>math.atan2 (y, x)</code></a></h3>
8528
Returns the arc tangent of <code>y/x</code> (in radians),
8529
but uses the signs of both parameters to find the
8530
quadrant of the result.
8531
(It also handles correctly the case of <code>x</code> being zero.)
8537
<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
8541
Returns the smallest integer larger than or equal to <code>x</code>.
8547
<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
8551
Returns the cosine of <code>x</code> (assumed to be in radians).
8557
<hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
8561
Returns the hyperbolic cosine of <code>x</code>.
8567
<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
8571
Returns the angle <code>x</code> (given in radians) in degrees.
8577
<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
8581
Returns the value <em>e<sup>x</sup></em>.
8587
<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
8591
Returns the largest integer smaller than or equal to <code>x</code>.
8597
<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
8601
Returns the remainder of the division of <code>x</code> by <code>y</code>
8602
that rounds the quotient towards zero.
8608
<hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
8612
Returns <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
8614
in the range <em>[0.5, 1)</em>
8615
(or zero when <code>x</code> is zero).
8621
<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
8625
The value <code>HUGE_VAL</code>,
8626
a value larger than or equal to any other numerical value.
8632
<hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
8636
Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
8642
<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
8646
Returns the logarithm of <code>x</code> in the given base.
8647
The default for <code>base</code> is <em>e</em>
8648
(so that the function returns the natural logarithm of <code>x</code>).
8654
<hr><h3><a name="pdf-math.max"><code>math.max (x, ···)</code></a></h3>
8658
Returns the maximum value among its arguments.
8664
<hr><h3><a name="pdf-math.min"><code>math.min (x, ···)</code></a></h3>
8668
Returns the minimum value among its arguments.
8674
<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
8678
Returns two numbers,
8679
the integral part of <code>x</code> and the fractional part of <code>x</code>.
8685
<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
8689
The value of <em>π</em>.
8695
<hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
8699
Returns <em>x<sup>y</sup></em>.
8700
(You can also use the expression <code>x^y</code> to compute this value.)
8706
<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
8710
Returns the angle <code>x</code> (given in degrees) in radians.
8716
<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
8720
This function is an interface to the simple
8721
pseudo-random generator function <code>rand</code> provided by Standard C.
8722
(No guarantees can be given for its statistical properties.)
8726
When called without arguments,
8727
returns a uniform pseudo-random real number
8728
in the range <em>[0,1)</em>.
8729
When called with an integer number <code>m</code>,
8730
<code>math.random</code> returns
8731
a uniform pseudo-random integer in the range <em>[1, m]</em>.
8732
When called with two integer numbers <code>m</code> and <code>n</code>,
8733
<code>math.random</code> returns a uniform pseudo-random
8734
integer in the range <em>[m, n]</em>.
8740
<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
8744
Sets <code>x</code> as the "seed"
8745
for the pseudo-random generator:
8746
equal seeds produce equal sequences of numbers.
8752
<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
8756
Returns the sine of <code>x</code> (assumed to be in radians).
8762
<hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
8766
Returns the hyperbolic sine of <code>x</code>.
8772
<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
8776
Returns the square root of <code>x</code>.
8777
(You can also use the expression <code>x^0.5</code> to compute this value.)
8783
<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
8787
Returns the tangent of <code>x</code> (assumed to be in radians).
8793
<hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
8797
Returns the hyperbolic tangent of <code>x</code>.
8805
<h2>6.7 – <a name="6.7">Bitwise Operations</a></h2>
8808
This library provides bitwise operations.
8809
It provides all its functions inside the table <a name="pdf-bit32"><code>bit32</code></a>.
8813
Unless otherwise stated,
8814
all functions accept numeric arguments in the range
8815
<em>(-2<sup>51</sup>,+2<sup>51</sup>)</em>;
8816
each argument is normalized to
8817
the remainder of its division by <em>2<sup>32</sup></em>
8818
and truncated to an integer (in some unspecified way),
8819
so that its final value falls in the range <em>[0,2<sup>32</sup> - 1]</em>.
8820
Similarly, all results are in the range <em>[0,2<sup>32</sup> - 1]</em>.
8821
Note that <code>bit32.bnot(0)</code> is <code>0xFFFFFFFF</code>,
8822
which is different from <code>-1</code>.
8826
<hr><h3><a name="pdf-bit32.arshift"><code>bit32.arshift (x, disp)</code></a></h3>
8830
Returns the number <code>x</code> shifted <code>disp</code> bits to the right.
8831
The number <code>disp</code> may be any representable integer.
8832
Negative displacements shift to the left.
8836
This shift operation is what is called arithmetic shift.
8837
Vacant bits on the left are filled
8838
with copies of the higher bit of <code>x</code>;
8839
vacant bits on the right are filled with zeros.
8841
displacements with absolute values higher than 31
8842
result in zero or <code>0xFFFFFFFF</code> (all original bits are shifted out).
8848
<hr><h3><a name="pdf-bit32.band"><code>bit32.band (···)</code></a></h3>
8852
Returns the bitwise <em>and</em> of its operands.
8858
<hr><h3><a name="pdf-bit32.bnot"><code>bit32.bnot (x)</code></a></h3>
8862
Returns the bitwise negation of <code>x</code>.
8863
For any integer <code>x</code>,
8864
the following identity holds:
8867
assert(bit32.bnot(x) == (-1 - x) % 2^32)
8873
<hr><h3><a name="pdf-bit32.bor"><code>bit32.bor (···)</code></a></h3>
8877
Returns the bitwise <em>or</em> of its operands.
8883
<hr><h3><a name="pdf-bit32.btest"><code>bit32.btest (···)</code></a></h3>
8887
Returns a boolean signaling
8888
whether the bitwise <em>and</em> of its operands is different from zero.
8894
<hr><h3><a name="pdf-bit32.bxor"><code>bit32.bxor (···)</code></a></h3>
8898
Returns the bitwise <em>exclusive or</em> of its operands.
8904
<hr><h3><a name="pdf-bit32.extract"><code>bit32.extract (n, field [, width])</code></a></h3>
8908
Returns the unsigned number formed by the bits
8909
<code>field</code> to <code>field + width - 1</code> from <code>n</code>.
8910
Bits are numbered from 0 (least significant) to 31 (most significant).
8911
All accessed bits must be in the range <em>[0, 31]</em>.
8915
The default for <code>width</code> is 1.
8921
<hr><h3><a name="pdf-bit32.replace"><code>bit32.replace (n, v, field [, width])</code></a></h3>
8925
Returns a copy of <code>n</code> with
8926
the bits <code>field</code> to <code>field + width - 1</code>
8927
replaced by the value <code>v</code>.
8928
See <a href="#pdf-bit32.extract"><code>bit32.extract</code></a> for details about <code>field</code> and <code>width</code>.
8934
<hr><h3><a name="pdf-bit32.lrotate"><code>bit32.lrotate (x, disp)</code></a></h3>
8938
Returns the number <code>x</code> rotated <code>disp</code> bits to the left.
8939
The number <code>disp</code> may be any representable integer.
8943
For any valid displacement,
8944
the following identity holds:
8947
assert(bit32.lrotate(x, disp) == bit32.lrotate(x, disp % 32))
8950
negative displacements rotate to the right.
8956
<hr><h3><a name="pdf-bit32.lshift"><code>bit32.lshift (x, disp)</code></a></h3>
8960
Returns the number <code>x</code> shifted <code>disp</code> bits to the left.
8961
The number <code>disp</code> may be any representable integer.
8962
Negative displacements shift to the right.
8963
In any direction, vacant bits are filled with zeros.
8965
displacements with absolute values higher than 31
8966
result in zero (all bits are shifted out).
8970
For positive displacements,
8971
the following equality holds:
8974
assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
8980
<hr><h3><a name="pdf-bit32.rrotate"><code>bit32.rrotate (x, disp)</code></a></h3>
8984
Returns the number <code>x</code> rotated <code>disp</code> bits to the right.
8985
The number <code>disp</code> may be any representable integer.
8989
For any valid displacement,
8990
the following identity holds:
8993
assert(bit32.rrotate(x, disp) == bit32.rrotate(x, disp % 32))
8996
negative displacements rotate to the left.
9002
<hr><h3><a name="pdf-bit32.rshift"><code>bit32.rshift (x, disp)</code></a></h3>
9006
Returns the number <code>x</code> shifted <code>disp</code> bits to the right.
9007
The number <code>disp</code> may be any representable integer.
9008
Negative displacements shift to the left.
9009
In any direction, vacant bits are filled with zeros.
9011
displacements with absolute values higher than 31
9012
result in zero (all bits are shifted out).
9016
For positive displacements,
9017
the following equality holds:
9020
assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))
9024
This shift operation is what is called logical shift.
9032
<h2>6.8 – <a name="6.8">Input and Output Facilities</a></h2>
9035
The I/O library provides two different styles for file manipulation.
9036
The first one uses implicit file descriptors;
9037
that is, there are operations to set a default input file and a
9038
default output file,
9039
and all input/output operations are over these default files.
9040
The second style uses explicit file descriptors.
9044
When using implicit file descriptors,
9045
all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
9046
When using explicit file descriptors,
9047
the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
9048
and then all operations are supplied as methods of the file descriptor.
9052
The table <code>io</code> also provides
9053
three 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>.
9055
The I/O library never closes these files.
9059
Unless otherwise stated,
9060
all I/O functions return <b>nil</b> on failure
9061
(plus an error message as a second result and
9062
a system-dependent error code as a third result)
9063
and some value different from <b>nil</b> on success.
9064
On non-Posix systems,
9065
the computation of the error message and error code
9067
may be not thread safe,
9068
because they rely on the global C variable <code>errno</code>.
9072
<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
9076
Equivalent to <code>file:close()</code>.
9077
Without a <code>file</code>, closes the default output file.
9083
<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
9087
Equivalent to <code>io.output():flush()</code>.
9093
<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
9097
When called with a file name, it opens the named file (in text mode),
9098
and sets its handle as the default input file.
9099
When called with a file handle,
9100
it simply sets this file handle as the default input file.
9101
When called without parameters,
9102
it returns the current default input file.
9106
In case of errors this function raises the error,
9107
instead of returning an error code.
9113
<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename ···])</code></a></h3>
9117
Opens the given file name in read mode
9118
and returns an iterator function that
9119
works like <code>file:lines(···)</code> over the opened file.
9120
When the iterator function detects the end of file,
9121
it returns <b>nil</b> (to finish the loop) and automatically closes the file.
9125
The call <code>io.lines()</code> (with no file name) is equivalent
9126
to <code>io.input():lines()</code>;
9127
that is, it iterates over the lines of the default input file.
9128
In this case it does not close the file when the loop ends.
9132
In case of errors this function raises the error,
9133
instead of returning an error code.
9139
<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
9143
This function opens a file,
9144
in the mode specified in the string <code>mode</code>.
9145
It returns a new file handle,
9146
or, in case of errors, <b>nil</b> plus an error message.
9150
The <code>mode</code> string can be any of the following:
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>
9161
The <code>mode</code> string can also have a '<code>b</code>' at the end,
9162
which is needed in some systems to open the file in binary mode.
9168
<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
9172
Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
9178
<hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3>
9182
This function is system dependent and is not available
9187
Starts program <code>prog</code> in a separated process and returns
9188
a file handle that you can use to read data from this program
9189
(if <code>mode</code> is <code>"r"</code>, the default)
9190
or to write data to this program
9191
(if <code>mode</code> is <code>"w"</code>).
9197
<hr><h3><a name="pdf-io.read"><code>io.read (···)</code></a></h3>
9201
Equivalent to <code>io.input():read(···)</code>.
9207
<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
9211
Returns a handle for a temporary file.
9212
This file is opened in update mode
9213
and it is automatically removed when the program ends.
9219
<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
9223
Checks whether <code>obj</code> is a valid file handle.
9224
Returns 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,
9226
or <b>nil</b> if <code>obj</code> is not a file handle.
9232
<hr><h3><a name="pdf-io.write"><code>io.write (···)</code></a></h3>
9236
Equivalent to <code>io.output():write(···)</code>.
9242
<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
9246
Closes <code>file</code>.
9247
Note that files are automatically closed when
9248
their handles are garbage collected,
9249
but that takes an unpredictable amount of time to happen.
9253
When 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
9255
returned by <a href="#pdf-os.execute"><code>os.execute</code></a>.
9261
<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
9265
Saves any written data to <code>file</code>.
9271
<hr><h3><a name="pdf-file:lines"><code>file:lines (···)</code></a></h3>
9275
Returns an iterator function that,
9276
each time it is called,
9277
reads the file according to the given formats.
9278
When no format is given,
9279
uses "*l" as a default.
9280
As an example, the construction
9283
for c in file:lines(1) do <em>body</em> end
9285
will iterate over all characters of the file,
9286
starting at the current position.
9287
Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
9292
In case of errors this function raises the error,
9293
instead of returning an error code.
9299
<hr><h3><a name="pdf-file:read"><code>file:read (···)</code></a></h3>
9303
Reads the file <code>file</code>,
9304
according to the given formats, which specify what to read.
9306
the function returns a string (or a number) with the characters read,
9307
or <b>nil</b> if it cannot read data with the specified format.
9308
When called without formats,
9309
it uses a default format that reads the next line
9314
The available formats are
9318
<li><b>"<code>*n</code>": </b>
9320
this is the only format that returns a number instead of a string.
9323
<li><b>"<code>*a</code>": </b>
9324
reads the whole file, starting at the current position.
9325
On end of file, it returns the empty string.
9328
<li><b>"<code>*l</code>": </b>
9329
reads the next line skipping the end of line,
9330
returning <b>nil</b> on end of file.
9331
This is the default format.
9334
<li><b>"<code>*L</code>": </b>
9335
reads the next line keeping the end of line (if present),
9336
returning <b>nil</b> on end of file.
9339
<li><b><em>number</em>: </b>
9340
reads a string with up to this number of bytes,
9341
returning <b>nil</b> on end of file.
9343
it reads nothing and returns an empty string,
9344
or <b>nil</b> on end of file.
9352
<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
9356
Sets and gets the file position,
9357
measured from the beginning of the file,
9358
to the position given by <code>offset</code> plus a base
9359
specified by the string <code>whence</code>, as follows:
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>
9366
In case of success, <code>seek</code> returns the final file position,
9367
measured in bytes from the beginning of the file.
9368
If <code>seek</code> fails, it returns <b>nil</b>,
9369
plus a string describing the error.
9373
The default value for <code>whence</code> is <code>"cur"</code>,
9374
and for <code>offset</code> is 0.
9375
Therefore, the call <code>file:seek()</code> returns the current
9376
file position, without changing it;
9377
the call <code>file:seek("set")</code> sets the position to the
9378
beginning of the file (and returns 0);
9379
and the call <code>file:seek("end")</code> sets the position to the
9380
end of the file, and returns its size.
9386
<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
9390
Sets the buffering mode for an output file.
9391
There are three available modes:
9395
<li><b>"<code>no</code>": </b>
9396
no buffering; the result of any output operation appears immediately.
9399
<li><b>"<code>full</code>": </b>
9400
full buffering; output operation is performed only
9401
when the buffer is full or when
9402
you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>).
9405
<li><b>"<code>line</code>": </b>
9406
line buffering; output is buffered until a newline is output
9407
or there is any input from some special files
9408
(such as a terminal device).
9412
For the last two cases, <code>size</code>
9413
specifies the size of the buffer, in bytes.
9414
The default is an appropriate size.
9420
<hr><h3><a name="pdf-file:write"><code>file:write (···)</code></a></h3>
9424
Writes the value of each of its arguments to <code>file</code>.
9425
The arguments must be strings or numbers.
9429
In case of success, this function returns <code>file</code>.
9430
Otherwise it returns <b>nil</b> plus a string describing the error.
9438
<h2>6.9 – <a name="6.9">Operating System Facilities</a></h2>
9441
This library is implemented through table <a name="pdf-os"><code>os</code></a>.
9445
<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
9449
Returns an approximation of the amount in seconds of CPU time
9450
used by the program.
9456
<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
9460
Returns a string or a table containing date and time,
9461
formatted according to the given string <code>format</code>.
9465
If the <code>time</code> argument is present,
9466
this 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).
9468
Otherwise, <code>date</code> formats the current time.
9472
If <code>format</code> starts with '<code>!</code>',
9473
then the date is formatted in Coordinated Universal Time.
9474
After this optional character,
9475
if <code>format</code> is the string "<code>*t</code>",
9476
then <code>date</code> returns a table with the following fields:
9477
<code>year</code> (four digits), <code>month</code> (1–12), <code>day</code> (1–31),
9478
<code>hour</code> (0–23), <code>min</code> (0–59), <code>sec</code> (0–61),
9479
<code>wday</code> (weekday, Sunday is 1),
9480
<code>yday</code> (day of the year),
9481
and <code>isdst</code> (daylight saving flag, a boolean).
9482
This last field may be absent
9483
if the information is not available.
9487
If <code>format</code> is not "<code>*t</code>",
9488
then <code>date</code> returns the date as a string,
9489
formatted according to the same rules as the ANSI C function <code>strftime</code>.
9493
When called without arguments,
9494
<code>date</code> returns a reasonable date and time representation that depends on
9495
the host system and on the current locale
9496
(that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
9500
On non-Posix systems,
9501
this function may be not thread safe
9502
because of its reliance on C function <code>gmtime</code> and C function <code>localtime</code>.
9508
<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
9512
Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
9513
In POSIX, Windows, and some other systems,
9514
this value is exactly <code>t2</code><em>-</em><code>t1</code>.
9520
<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
9524
This function is equivalent to the ANSI C function <code>system</code>.
9525
It passes <code>command</code> to be executed by an operating system shell.
9526
Its first result is <b>true</b>
9527
if the command terminated successfully,
9528
or <b>nil</b> otherwise.
9529
After this first result
9530
the function returns a string and a number,
9535
<li><b>"<code>exit</code>": </b>
9536
the command terminated normally;
9537
the following number is the exit status of the command.
9540
<li><b>"<code>signal</code>": </b>
9541
the command was terminated by a signal;
9542
the following number is the signal that terminated the command.
9548
When called without a <code>command</code>,
9549
<code>os.execute</code> returns a boolean that is true if a shell is available.
9555
<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close])</code></a></h3>
9559
Calls the ANSI C function <code>exit</code> to terminate the host program.
9560
If <code>code</code> is <b>true</b>,
9561
the returned status is <code>EXIT_SUCCESS</code>;
9562
if <code>code</code> is <b>false</b>,
9563
the returned status is <code>EXIT_FAILURE</code>;
9564
if <code>code</code> is a number,
9565
the returned status is this number.
9566
The default value for <code>code</code> is <b>true</b>.
9570
If the optional second argument <code>close</code> is true,
9571
closes the Lua state before exiting.
9577
<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
9581
Returns the value of the process environment variable <code>varname</code>,
9582
or <b>nil</b> if the variable is not defined.
9588
<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
9592
Deletes the file (or empty directory, on POSIX systems)
9593
with the given name.
9594
If this function fails, it returns <b>nil</b>,
9595
plus a string describing the error and the error code.
9601
<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
9605
Renames file or directory named <code>oldname</code> to <code>newname</code>.
9606
If this function fails, it returns <b>nil</b>,
9607
plus a string describing the error and the error code.
9613
<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
9617
Sets 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>;
9622
the default category is <code>"all"</code>.
9623
The function returns the name of the new locale,
9624
or <b>nil</b> if the request cannot be honored.
9628
If <code>locale</code> is the empty string,
9629
the current locale is set to an implementation-defined native locale.
9630
If <code>locale</code> is the string "<code>C</code>",
9631
the current locale is set to the standard C locale.
9635
When called with <b>nil</b> as the first argument,
9636
this function only returns the name of the current locale
9637
for the given category.
9641
This function may be not thread safe
9642
because of its reliance on C function <code>setlocale</code>.
9648
<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
9652
Returns the current time when called without arguments,
9653
or a time representing the date and time specified by the given table.
9654
This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
9656
<code>hour</code> (default is 12),
9657
<code>min</code> (default is 0),
9658
<code>sec</code> (default is 0),
9659
and <code>isdst</code> (default is <b>nil</b>).
9660
For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function.
9664
The returned value is a number, whose meaning depends on your system.
9665
In POSIX, Windows, and some other systems,
9666
this number counts the number
9667
of seconds since some given start time (the "epoch").
9668
In other systems, the meaning is not specified,
9669
and 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>.
9676
<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
9680
Returns a string with a file name that can
9681
be used for a temporary file.
9682
The file must be explicitly opened before its use
9683
and explicitly removed when no longer needed.
9688
this function also creates a file with that name,
9689
to avoid security risks.
9690
(Someone else might create the file with wrong permissions
9691
in the time between getting the name and creating the file.)
9692
You still have to open the file to use it
9693
and to remove it (even if you do not use it).
9698
you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>,
9699
which automatically removes the file when the program ends.
9707
<h2>6.10 – <a name="6.10">The Debug Library</a></h2>
9710
This library provides
9711
the functionality of the debug interface (<a href="#4.9">§4.9</a>) to Lua programs.
9712
You should exert care when using this library.
9713
Several of its functions
9714
violate basic assumptions about Lua code
9715
(e.g., that variables local to a function
9716
cannot be accessed from outside;
9717
that userdata metatables cannot be changed by Lua code;
9718
that Lua programs do not crash)
9719
and therefore can compromise otherwise secure code.
9720
Moreover, some functions in this library may be slow.
9724
All functions in this library are provided
9725
inside the <a name="pdf-debug"><code>debug</code></a> table.
9726
All functions that operate over a thread
9727
have an optional first argument which is the
9728
thread to operate over.
9729
The default is always the current thread.
9733
<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
9737
Enters an interactive mode with the user,
9738
running each string that the user enters.
9739
Using simple commands and other debug facilities,
9740
the user can inspect global and local variables,
9741
change their values, evaluate expressions, and so on.
9742
A line containing only the word <code>cont</code> finishes this function,
9743
so that the caller continues its execution.
9747
Note that commands for <code>debug.debug</code> are not lexically nested
9748
within any function and so have no direct access to local variables.
9754
<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
9758
Returns the current hook settings of the thread, as three values:
9759
the current hook function, the current hook mask,
9760
and the current hook count
9761
(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
9767
<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3>
9771
Returns a table with information about a function.
9772
You can give the function directly
9773
or you can give a number as the value of <code>f</code>,
9774
which means the function running at level <code>f</code> of the call stack
9775
of the given thread:
9776
level 0 is the current function (<code>getinfo</code> itself);
9777
level 1 is the function that called <code>getinfo</code>
9778
(except for tail calls, which do not count on the stack);
9780
If <code>f</code> is a number larger than the number of active functions,
9781
then <code>getinfo</code> returns <b>nil</b>.
9785
The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
9786
with the string <code>what</code> describing which fields to fill in.
9787
The default for <code>what</code> is to get all information available,
9788
except the table of valid lines.
9790
the option '<code>f</code>'
9791
adds a field named <code>func</code> with the function itself.
9793
the option '<code>L</code>'
9794
adds a field named <code>activelines</code> with the table of
9799
For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
9800
a table with a name for the current function,
9801
if a reasonable name can be found,
9802
and the expression <code>debug.getinfo(print)</code>
9803
returns a table with all available information
9804
about the <a href="#pdf-print"><code>print</code></a> function.
9810
<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3>
9814
This function returns the name and the value of the local variable
9815
with index <code>local</code> of the function at level <code>f</code> of the stack.
9816
This function accesses not only explicit local variables,
9817
but also parameters, temporaries, etc.
9821
The first parameter or local variable has index 1, and so on,
9822
until the last active variable.
9823
Negative indices refer to vararg parameters;
9824
-1 is the first vararg parameter.
9825
The function returns <b>nil</b> if there is no variable with the given index,
9826
and 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.)
9831
Variable names starting with '<code>(</code>' (open parenthesis)
9832
represent internal variables
9833
(loop control variables, temporaries, varargs, and C function locals).
9837
The parameter <code>f</code> may also be a function.
9838
In that case, <code>getlocal</code> returns only the name of function parameters.
9844
<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3>
9848
Returns the metatable of the given <code>value</code>
9849
or <b>nil</b> if it does not have a metatable.
9855
<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
9859
Returns the registry table (see <a href="#4.5">§4.5</a>).
9865
<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3>
9869
This function returns the name and the value of the upvalue
9870
with index <code>up</code> of the function <code>f</code>.
9871
The function returns <b>nil</b> if there is no upvalue with the given index.
9877
<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
9881
Returns the Lua value associated to <code>u</code>.
9882
If <code>u</code> is not a userdata,
9889
<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
9893
Sets the given function as a hook.
9894
The string <code>mask</code> and the number <code>count</code> describe
9895
when the hook will be called.
9896
The string mask may have the following characters,
9897
with the given meaning:
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>
9904
With a <code>count</code> different from zero,
9905
the hook is called after every <code>count</code> instructions.
9909
When called without arguments,
9910
<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
9914
When the hook is called, its first parameter is a string
9915
describing 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>.
9920
the hook also gets the new line number as its second parameter.
9922
you can call <code>getinfo</code> with level 2 to get more information about
9923
the running function
9924
(level 0 is the <code>getinfo</code> function,
9925
and level 1 is the hook function).
9931
<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
9935
This function assigns the value <code>value</code> to the local variable
9936
with index <code>local</code> of the function at level <code>level</code> of the stack.
9937
The function returns <b>nil</b> if there is no local
9938
variable with the given index,
9939
and 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.)
9941
Otherwise, it returns the name of the local variable.
9945
See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about
9946
variable indices and names.
9952
<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3>
9956
Sets the metatable for the given <code>value</code> to the given <code>table</code>
9957
(which can be <b>nil</b>).
9958
Returns <code>value</code>.
9964
<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3>
9968
This function assigns the value <code>value</code> to the upvalue
9969
with index <code>up</code> of the function <code>f</code>.
9970
The function returns <b>nil</b> if there is no upvalue
9971
with the given index.
9972
Otherwise, it returns the name of the upvalue.
9978
<hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3>
9982
Sets the given <code>value</code> as
9983
the 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.
9989
Returns <code>udata</code>.
9995
<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3>
9999
If <code>message</code> is present but is neither a string nor <b>nil</b>,
10000
this function returns <code>message</code> without further processing.
10002
it returns a string with a traceback of the call stack.
10003
An optional <code>message</code> string is appended
10004
at the beginning of the traceback.
10005
An optional <code>level</code> number tells at which level
10006
to start the traceback
10007
(default is 1, the function calling <code>traceback</code>).
10013
<hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3>
10017
Returns an unique identifier (as a light userdata)
10018
for the upvalue numbered <code>n</code>
10019
from the given function.
10023
These unique identifiers allow a program to check whether different
10024
closures share upvalues.
10025
Lua closures that share an upvalue
10026
(that is, that access a same external local variable)
10027
will return identical ids for those upvalue indices.
10033
<hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3>
10037
Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code>
10038
refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>.
10046
<h1>7 – <a name="7">Lua Standalone</a></h1>
10049
Although Lua has been designed as an extension language,
10050
to be embedded in a host C program,
10051
it is also frequently used as a standalone language.
10052
An interpreter for Lua as a standalone language,
10053
called simply <code>lua</code>,
10054
is provided with the standard distribution.
10055
The standalone interpreter includes
10056
all standard libraries, including the debug library.
10060
lua [options] [script [args]]
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>
10073
After handling its options, <code>lua</code> runs the given <em>script</em>,
10074
passing to it the given <em>args</em> as string arguments.
10075
When called without arguments,
10076
<code>lua</code> behaves as <code>lua -v -i</code>
10077
when the standard input (<code>stdin</code>) is a terminal,
10078
and as <code>lua -</code> otherwise.
10082
When called without option <code>-E</code>,
10083
the 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)
10085
before running any argument.
10086
If the variable content has the format <code>@<em>filename</em></code>,
10087
then <code>lua</code> executes the file.
10088
Otherwise, <code>lua</code> executes the string itself.
10092
When called with option <code>-E</code>,
10093
besides ignoring <code>LUA_INIT</code>,
10095
the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>,
10096
setting 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>
10098
with the default paths defined in <code>luaconf.h</code>.
10102
All options are handled in order, except <code>-i</code> and <code>-E</code>.
10103
For instance, an invocation like
10106
$ lua -e'a=1' -e 'print(a)' script.lua
10108
will first set <code>a</code> to 1, then print the value of <code>a</code>,
10109
and finally run the file <code>script.lua</code> with no arguments.
10110
(Here <code>$</code> is the shell prompt. Your prompt may be different.)
10114
Before starting to run the script,
10115
<code>lua</code> collects all arguments in the command line
10116
in a global table called <code>arg</code>.
10117
The script name is stored at index 0,
10118
the first argument after the script name goes to index 1,
10120
Any arguments before the script name
10121
(that is, the interpreter name plus the options)
10122
go to negative indices.
10123
For instance, in the call
10126
$ lua -la b.lua t1 t2
10128
the interpreter first runs the file <code>a.lua</code>,
10129
then creates a table
10132
arg = { [-2] = "lua", [-1] = "-la",
10134
[1] = "t1", [2] = "t2" }
10136
and finally runs the file <code>b.lua</code>.
10137
The script is called with <code>arg[1]</code>, <code>arg[2]</code>, ...
10139
it can also access these arguments with the vararg expression '<code>...</code>'.
10143
In interactive mode,
10144
if you write an incomplete statement,
10145
the interpreter waits for its completion
10146
by issuing a different prompt.
10150
In case of unprotected errors in the script,
10151
the interpreter reports the error to the standard error stream.
10152
If the error object is a string,
10153
the interpreter adds a stack traceback to it.
10154
Otherwise, if the error object has a metamethod <code>__tostring</code>,
10155
the interpreter calls this metamethod to produce the final message.
10156
Finally, if the error object is <b>nil</b>,
10157
the interpreter does not report the error.
10161
When finishing normally,
10162
the interpreter closes its main Lua state
10163
(see <a href="#lua_close"><code>lua_close</code></a>).
10164
The script can avoid this step by
10165
calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate.
10169
To allow the use of Lua as a
10170
script interpreter in Unix systems,
10171
the standalone interpreter skips
10172
the first line of a chunk if it starts with <code>#</code>.
10173
Therefore, Lua scripts can be made into executable programs
10174
by using <code>chmod +x</code> and the <code>#!</code> form,
10178
#!/usr/local/bin/lua
10181
the location of the Lua interpreter may be different in your machine.
10182
If <code>lua</code> is in your <code>PATH</code>,
10188
is a more portable solution.)
10192
<h1>8 – <a name="8">Incompatibilities with the Previous Version</a></h1>
10195
Here we list the incompatibilities that you may find when moving a program
10196
from Lua 5.1 to Lua 5.2.
10197
You can avoid some incompatibilities by compiling Lua with
10198
appropriate options (see file <code>luaconf.h</code>).
10200
all these compatibility options will be removed in the next version of Lua.
10202
all features marked as deprecated in Lua 5.1
10203
have been removed in Lua 5.2.
10207
<h2>8.1 – <a name="8.1">Changes in the Language</a></h2>
10211
The concept of <em>environment</em> changed.
10212
Only Lua functions have environments.
10213
To set the environment of a Lua function,
10214
use the variable <code>_ENV</code> or the function <a href="#pdf-load"><code>load</code></a>.
10218
C functions no longer have environments.
10219
Use an upvalue with a shared table if you need to keep
10220
shared state among several C functions.
10221
(You may use <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> to open a C library
10222
with all functions sharing a common upvalue.)
10226
To manipulate the "environment" of a userdata
10227
(which is now called user value),
10228
use the new functions
10229
<a href="#lua_getuservalue"><code>lua_getuservalue</code></a> and <a href="#lua_setuservalue"><code>lua_setuservalue</code></a>.
10233
Lua identifiers cannot use locale-dependent letters.
10237
Doing a step or a full collection in the garbage collector
10238
does not restart the collector if it has been stopped.
10242
Weak tables with weak keys now perform like <em>ephemeron tables</em>.
10246
The event <em>tail return</em> in debug hooks was removed.
10247
Instead, tail calls generate a special new event,
10248
<em>tail call</em>, so that the debugger can know that
10249
there will not be a corresponding return event.
10253
Equality between function values has changed.
10254
Now, a function definition may not create a new value;
10255
it may reuse some previous value if there is no
10256
observable difference to the new function.
10264
<h2>8.2 – <a name="8.2">Changes in the Libraries</a></h2>
10268
Function <code>module</code> is deprecated.
10269
It is easy to set up a module with regular Lua code.
10270
Modules are not expected to set global variables.
10274
Functions <code>setfenv</code> and <code>getfenv</code> were removed,
10275
because of the changes in environments.
10279
Function <code>math.log10</code> is deprecated.
10280
Use <a href="#pdf-math.log"><code>math.log</code></a> with 10 as its second argument, instead.
10284
Function <code>loadstring</code> is deprecated.
10285
Use <code>load</code> instead; it now accepts string arguments
10286
and are exactly equivalent to <code>loadstring</code>.
10290
Function <code>table.maxn</code> is deprecated.
10291
Write it in Lua if you really need it.
10295
Function <code>os.execute</code> now returns <b>true</b> when command
10296
terminates successfully and <b>nil</b> plus error information
10301
Function <code>unpack</code> was moved into the table library
10302
and therefore must be called as <a href="#pdf-table.unpack"><code>table.unpack</code></a>.
10306
Character class <code>%z</code> in patterns is deprecated,
10307
as now patterns may contain '<code>\0</code>' as a regular character.
10311
The table <code>package.loaders</code> was renamed <code>package.searchers</code>.
10315
Lua does not have bytecode verification anymore.
10316
So, all functions that load code
10317
(<a href="#pdf-load"><code>load</code></a> and <a href="#pdf-loadfile"><code>loadfile</code></a>)
10318
are potentially insecure when loading untrusted binary data.
10319
(Actually, those functions were already insecure because
10320
of flaws in the verification algorithm.)
10322
use the <code>mode</code> argument of those functions
10323
to restrict them to loading textual chunks.
10327
The standard paths in the official distribution may
10328
change between versions.
10336
<h2>8.3 – <a name="8.3">Changes in the API</a></h2>
10340
Pseudoindex <code>LUA_GLOBALSINDEX</code> was removed.
10341
You must get the global environment from the registry
10342
(see <a href="#4.5">§4.5</a>).
10346
Pseudoindex <code>LUA_ENVIRONINDEX</code>
10347
and functions <code>lua_getfenv</code>/<code>lua_setfenv</code>
10349
as C functions no longer have environments.
10353
Function <code>luaL_register</code> is deprecated.
10354
Use <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.)
10359
The <code>osize</code> argument to the allocation function
10360
may not be zero when creating a new block,
10361
that is, when <code>ptr</code> is <code>NULL</code>
10362
(see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
10363
Use only the test <code>ptr == NULL</code> to check whether
10368
Finalizers (<code>__gc</code> metamethods) for userdata are called in the
10369
reverse order that they were marked for finalization,
10370
not that they were created (see <a href="#2.5.1">§2.5.1</a>).
10371
(Most userdata are marked immediately after they are created.)
10373
if the metatable does not have a <code>__gc</code> field when set,
10374
the finalizer will not be called,
10375
even if it is set later.
10379
<code>luaL_typerror</code> was removed.
10380
Write your own version if you need it.
10384
Function <code>lua_cpcall</code> is deprecated.
10385
You can simply push the function with <a href="#lua_pushcfunction"><code>lua_pushcfunction</code></a>
10386
and call it with <a href="#lua_pcall"><code>lua_pcall</code></a>.
10390
Functions <code>lua_equal</code> and <code>lua_lessthan</code> are deprecated.
10391
Use the new <a href="#lua_compare"><code>lua_compare</code></a> with appropriate options instead.
10395
Function <code>lua_objlen</code> was renamed <a href="#lua_rawlen"><code>lua_rawlen</code></a>.
10399
Function <a href="#lua_load"><code>lua_load</code></a> has an extra parameter, <code>mode</code>.
10400
Pass <code>NULL</code> to simulate the old behavior.
10404
Function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter, <code>from</code>.
10405
Pass <code>NULL</code> or the thread doing the call.
10413
<h1>9 – <a name="9">The Complete Syntax of Lua</a></h1>
10416
Here is the complete syntax of Lua in extended BNF.
10417
(It does not describe operator precedences.)
10426
block ::= {stat} [retstat]
10428
stat ::= ‘<b>;</b>’ |
10429
varlist ‘<b>=</b>’ explist |
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 ‘<b>=</b>’ exp ‘<b>,</b>’ exp [‘<b>,</b>’ 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 [‘<b>=</b>’ explist]
10444
retstat ::= <b>return</b> [explist] [‘<b>;</b>’]
10446
label ::= ‘<b>::</b>’ Name ‘<b>::</b>’
10448
funcname ::= Name {‘<b>.</b>’ Name} [‘<b>:</b>’ Name]
10450
varlist ::= var {‘<b>,</b>’ var}
10452
var ::= Name | prefixexp ‘<b>[</b>’ exp ‘<b>]</b>’ | prefixexp ‘<b>.</b>’ Name
10454
namelist ::= Name {‘<b>,</b>’ Name}
10456
explist ::= exp {‘<b>,</b>’ exp}
10458
exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | ‘<b>...</b>’ | functiondef |
10459
prefixexp | tableconstructor | exp binop exp | unop exp
10461
prefixexp ::= var | functioncall | ‘<b>(</b>’ exp ‘<b>)</b>’
10463
functioncall ::= prefixexp args | prefixexp ‘<b>:</b>’ Name args
10465
args ::= ‘<b>(</b>’ [explist] ‘<b>)</b>’ | tableconstructor | String
10467
functiondef ::= <b>function</b> funcbody
10469
funcbody ::= ‘<b>(</b>’ [parlist] ‘<b>)</b>’ block <b>end</b>
10471
parlist ::= namelist [‘<b>,</b>’ ‘<b>...</b>’] | ‘<b>...</b>’
10473
tableconstructor ::= ‘<b>{</b>’ [fieldlist] ‘<b>}</b>’
10475
fieldlist ::= field {fieldsep field} [fieldsep]
10477
field ::= ‘<b>[</b>’ exp ‘<b>]</b>’ ‘<b>=</b>’ exp | Name ‘<b>=</b>’ exp | exp
10479
fieldsep ::= ‘<b>,</b>’ | ‘<b>;</b>’
10481
binop ::= ‘<b>+</b>’ | ‘<b>-</b>’ | ‘<b>*</b>’ | ‘<b>/</b>’ | ‘<b>^</b>’ | ‘<b>%</b>’ | ‘<b>..</b>’ |
10482
‘<b><</b>’ | ‘<b><=</b>’ | ‘<b>></b>’ | ‘<b>>=</b>’ | ‘<b>==</b>’ | ‘<b>~=</b>’ |
10483
<b>and</b> | <b>or</b>
10485
unop ::= ‘<b>-</b>’ | <b>not</b> | ‘<b>#</b>’
10498
<SMALL CLASS="footer">
10500
Thu Mar 21 12:58:59 BRT 2013
10503
Last change: revised for Lua 5.2.2