Subversion Repositories WoWGM

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 tristanc 1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
2
<html>
3
 
4
<head>
5
<title>Lua 5.1 Reference Manual</title>
6
<link rel="stylesheet" href="lua.css">
7
</head>
8
 
9
<body>
10
 
11
<hr>
12
<h1>
13
<a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
14
Lua 5.1 Reference Manual
15
</h1>
16
 
17
by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
18
<p>
19
<small>
20
<a href="http://www.lua.org/copyright.html">Copyright</a>
21
&copy; 2006 Lua.org, PUC-Rio.  All rights reserved.
22
</small>
23
<hr>
24
 
25
<!-- ====================================================================== -->
26
<p>
27
 
28
 
29
 
30
 
31
 
32
<h1>1 - <a name="1">Introduction</a></h1>
33
 
34
<p>
35
Lua is an extension programming language designed to support
36
general procedural programming with data description
37
facilities.
38
It also offers good support for object-oriented programming,
39
functional programming, and data-driven programming.
40
Lua is intended to be used as a powerful, light-weight
41
scripting language for any program that needs one.
42
Lua is implemented as a library, written in <em>clean</em> C
43
(that is, in the common subset of ANSI&nbsp;C and C++).
44
 
45
 
46
<p>
47
Being an extension language, Lua has no notion of a "main" program:
48
it only works <em>embedded</em> in a host client,
49
called the <em>embedding program</em> or simply the <em>host</em>.
50
This host program can invoke functions to execute a piece of Lua code,
51
can write and read Lua variables,
52
and can register C&nbsp;functions to be called by Lua code.
53
Through the use of C&nbsp;functions, Lua can be augmented to cope with
54
a wide range of different domains,
55
thus creating customized programming languages sharing a syntactical framework.
56
The Lua distribution includes a sample host program called <code>lua</code>,
57
which uses the Lua library to offer a complete, stand-alone Lua interpreter.
58
 
59
 
60
<p>
61
Lua is free software,
62
and is provided as usual with no guarantees,
63
as stated in its license.
64
The implementation described in this manual is available
65
at Lua's official web site, <code>www.lua.org</code>.
66
 
67
 
68
<p>
69
Like any other reference manual,
70
this document is dry in places.
71
For a discussion of the decisions behind the design of Lua,
72
see the technical papers available at Lua's web site.
73
For a detailed introduction to programming in Lua,
74
see Roberto's book, <em>Programming in Lua</em>.
75
 
76
 
77
 
78
<h1>2 - <a name="2">The Language</a></h1>
79
 
80
<p>
81
This section describes the lexis, the syntax, and the semantics of Lua.
82
In other words,
83
this section describes
84
which tokens are valid,
85
how they can be combined,
86
and what their combinations mean.
87
 
88
 
89
<p>
90
The language constructs will be explained using the usual extended BNF notation,
91
in which
92
{<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and
93
[<em>a</em>]&nbsp;means an optional <em>a</em>.
94
Non-terminals are shown like non-terminal,
95
keywords are shown like <b>kword</b>,
96
and other terminal symbols are shown like `<b>=</b>&acute;.
97
The complete syntax of Lua can be found at the end of this manual.
98
 
99
 
100
 
101
<h2>2.1 - <a name="2.1">Lexical Conventions</a></h2>
102
 
103
<p>
104
<em>Names</em>
105
(also called <em>identifiers</em>)
106
in Lua can be any string of letters,
107
digits, and underscores,
108
not beginning with a digit.
109
This coincides with the definition of names in most languages.
110
(The definition of letter depends on the current locale:
111
any character considered alphabetic by the current locale
112
can be used in an identifier.)
113
Identifiers are used to name variables and table fields.
114
 
115
 
116
<p>
117
The following <em>keywords</em> are reserved
118
and cannot be used as names:
119
 
120
 
121
<pre>
122
     and       break     do        else      elseif
123
     end       false     for       function  if
124
     in        local     nil       not       or
125
     repeat    return    then      true      until     while
126
</pre>
127
 
128
<p>
129
Lua is a case-sensitive language:
130
<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
131
are two different, valid names.
132
As a convention, names starting with an underscore followed by
133
uppercase letters (such as <code>_VERSION</code>)
134
are reserved for internal global variables used by Lua.
135
 
136
 
137
<p>
138
The following strings denote other tokens:
139
 
140
<pre>
141
     +     -     *     /     %     ^     #
142
     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
143
     (     )     {     }     [     ]
144
     ;     :     ,     .     ..    ...
145
</pre>
146
 
147
<p>
148
<em>Literal strings</em>
149
can be delimited by matching single or double quotes,
150
and can contain the following C-like escape sequences:
151
'<code>\a</code>' (bell),
152
'<code>\b</code>' (backspace),
153
'<code>\f</code>' (form feed),
154
'<code>\n</code>' (newline),
155
'<code>\r</code>' (carriage return),
156
'<code>\t</code>' (horizontal tab),
157
'<code>\v</code>' (vertical tab),
158
'<code>\\</code>' (backslash),
159
'<code>\"</code>' (quotation mark [double quote]),
160
and '<code>\'</code>' (apostrophe [single quote]).
161
Moreover, a backslash followed by a real newline
162
results in a newline in the string.
163
A character in a string may also be specified by its numerical value
164
using the escape sequence <code>\<em>ddd</em></code>,
165
where <em>ddd</em> is a sequence of up to three decimal digits.
166
(Note that if a numerical escape is to be followed by a digit,
167
it must be expressed using exactly three digits.)
168
Strings in Lua may contain any 8-bit value, including embedded zeros,
169
which can be specified as '<code>\0</code>'.
170
 
171
 
172
<p>
173
To put a double (single) quote, a newline, a backslash,
174
or an embedded zero
175
inside a literal string enclosed by double (single) quotes
176
you must use an escape sequence.
177
Any other character may be directly inserted into the literal.
178
(Some control characters may cause problems for the file system,
179
but Lua has no problem with them.)
180
 
181
 
182
<p>
183
Literal strings can also be defined using a long format
184
enclosed by <em>long brackets</em>.
185
We define an <em>opening long bracket of level <em>n</em></em> as an opening
186
square bracket followed by <em>n</em> equal signs followed by another
187
opening square bracket.
188
So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
189
an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
190
and so on.
191
A <em>closing long bracket</em> is defined similarly;
192
for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
193
A long string starts with an opening long bracket of any level and
194
ends at the first closing long bracket of the same level.
195
Literals in this bracketed form may run for several lines,
196
do not interpret any escape sequences,
197
and ignore long brackets of any other level.
198
They may contain anything except a closing bracket of the proper level.
199
 
200
 
201
<p>
202
For convenience,
203
when the opening long bracket is immediately followed by a newline,
204
the newline is not included in the string.
205
As an example, in a system using ASCII
206
(in which '<code>a</code>' is coded as&nbsp;97,
207
newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49),
208
the five literals below denote the same string:
209
 
210
<pre>
211
     a = 'alo\n123"'
212
     a = "alo\n123\""
213
     a = '\97lo\10\04923"'
214
     a = [[alo
215
     123"]]
216
     a = [==[
217
     alo
218
     123"]==]
219
</pre>
220
 
221
<p>
222
A <em>numerical constant</em> may be written with an optional decimal part
223
and an optional decimal exponent.
224
Lua also accepts integer hexadecimal constants,
225
by prefixing them with <code>0x</code>.
226
Examples of valid numerical constants are
227
 
228
<pre>
229
     3   3.0   3.1416   314.16e-2   0.31416E1   0xff   0x56
230
</pre>
231
 
232
<p>
233
A <em>comment</em> starts with a double hyphen (<code>--</code>)
234
anywhere outside a string.
235
If the text immediately after <code>--</code> is not an opening long bracket,
236
the comment is a <em>short comment</em>,
237
which runs until the end of the line.
238
Otherwise, it is a <em>long comment</em>,
239
which runs until the corresponding closing long bracket.
240
Long comments are frequently used to disable code temporarily.
241
 
242
 
243
 
244
 
245
 
246
<h2>2.2 - <a name="2.2">Values and Types</a></h2>
247
 
248
<p>
249
Lua is a <em>dynamically typed language</em>.
250
This means that
251
variables do not have types; only values do.
252
There are no type definitions in the language.
253
All values carry their own type.
254
 
255
 
256
<p>
257
All values in Lua are <em>first-class values</em>.
258
This means that all values can be stored in variables,
259
passed as arguments to other functions, and returned as results.
260
 
261
 
262
<p>
263
There are eight basic types in Lua:
264
<em>nil</em>, <em>boolean</em>, <em>number</em>,
265
<em>string</em>, <em>function</em>, <em>userdata</em>,
266
<em>thread</em>, and <em>table</em>.
267
<em>Nil</em> is the type of the value <b>nil</b>,
268
whose main property is to be different from any other value;
269
it usually represents the absence of a useful value.
270
<em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
271
Both <b>nil</b> and <b>false</b> make a condition false;
272
any other value makes it true.
273
<em>Number</em> represents real (double-precision floating-point) numbers.
274
(It is easy to build Lua interpreters that use other
275
internal representations for numbers,
276
such as single-precision float or long integers;
277
see file <code>luaconf.h</code>.)
278
<em>String</em> represents arrays of characters.
279
 
280
Lua is 8-bit clean:
281
strings may contain any 8-bit character,
282
including embedded zeros ('<code>\0</code>') (see <a href="#2.1">&sect;2.1</a>).
283
 
284
 
285
<p>
286
Lua can call (and manipulate) functions written in Lua and
287
functions written in C
288
(see <a href="#2.5.8">&sect;2.5.8</a>).
289
 
290
 
291
<p>
292
The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
293
be stored in Lua variables.
294
This type corresponds to a block of raw memory
295
and has no pre-defined operations in Lua,
296
except assignment and identity test.
297
However, by using <em>metatables</em>,
298
the programmer can define operations for userdata values
299
(see <a href="#2.8">&sect;2.8</a>).
300
Userdata values cannot be created or modified in Lua,
301
only through the C&nbsp;API.
302
This guarantees the integrity of data owned by the host program.
303
 
304
 
305
<p>
306
The type <em>thread</em> represents independent threads of execution
307
and it is used to implement coroutines (see <a href="#2.11">&sect;2.11</a>).
308
Do not confuse Lua threads with operating-system threads.
309
Lua supports coroutines on all systems,
310
even those that do not support threads.
311
 
312
 
313
<p>
314
The type <em>table</em> implements associative arrays,
315
that is, arrays that can be indexed not only with numbers,
316
but with any value (except <b>nil</b>).
317
Tables can be <em>heterogeneous</em>;
318
that is, they can contain values of all types (except <b>nil</b>).
319
Tables are the sole data structuring mechanism in Lua;
320
they may be used to represent ordinary arrays,
321
symbol tables, sets, records, graphs, trees, etc.
322
To represent records, Lua uses the field name as an index.
323
The language supports this representation by
324
providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
325
There are several convenient ways to create tables in Lua
326
(see <a href="#2.5.7">&sect;2.5.7</a>).
327
 
328
 
329
<p>
330
Like indices,
331
the value of a table field can be of any type (except <b>nil</b>).
332
In particular,
333
because functions are first-class values,
334
table fields may contain functions.
335
Thus tables may also carry <em>methods</em> (see <a href="#2.5.9">&sect;2.5.9</a>).
336
 
337
 
338
<p>
339
Tables, functions, threads, and (full) userdata values are <em>objects</em>:
340
variables do not actually <em>contain</em> these values,
341
only <em>references</em> to them.
342
Assignment, parameter passing, and function returns
343
always manipulate references to such values;
344
these operations do not imply any kind of copy.
345
 
346
 
347
<p>
348
The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
349
of a given value.
350
 
351
 
352
 
353
<h3>2.2.1 - <a name="2.2.1">Coercion</a></h3>
354
 
355
<p>
356
Lua provides automatic conversion between
357
string and number values at run time.
358
Any arithmetic operation applied to a string tries to convert
359
this string to a number, following the usual conversion rules.
360
Conversely, whenever a number is used where a string is expected,
361
the number is converted to a string, in a reasonable format.
362
For complete control over how numbers are converted to strings,
363
use the <code>format</code> function from the string library
364
(see <a href="#pdf-string.format"><code>string.format</code></a>).
365
 
366
 
367
 
368
 
369
 
370
 
371
 
372
<h2>2.3 - <a name="2.3">Variables</a></h2>
373
 
374
<p>
375
Variables are places that store values.
376
 
377
There are three kinds of variables in Lua:
378
global variables, local variables, and table fields.
379
 
380
 
381
<p>
382
A single name can denote a global variable or a local variable
383
(or a function's formal parameter,
384
which is a particular kind of local variable):
385
 
386
<pre>
387
	var ::= Name
388
</pre><p>
389
Name denotes identifiers, as defined in <a href="#2.1">&sect;2.1</a>.
390
 
391
 
392
<p>
393
Variables are assumed to be global unless explicitly declared local
394
(see <a href="#2.4.7">&sect;2.4.7</a>).
395
Local variables are <em>lexically scoped</em>:
396
local variables can be freely accessed by functions
397
defined inside their scope (see <a href="#2.6">&sect;2.6</a>).
398
 
399
 
400
<p>
401
Before the first assignment to a variable, its value is <b>nil</b>.
402
 
403
 
404
<p>
405
Square brackets are used to index a table:
406
 
407
<pre>
408
	var ::= prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute;
409
</pre><p>
410
The meaning of accesses to global variables 
411
and table fields can be changed via metatables.
412
An access to an indexed variable <code>t[i]</code> is equivalent to
413
a call <code>gettable_event(t,i)</code>.
414
(See <a href="#2.8">&sect;2.8</a> for a complete description of the
415
<code>gettable_event</code> function.
416
This function is not defined or callable in Lua.
417
We use it here only for explanatory purposes.)
418
 
419
 
420
<p>
421
The syntax <code>var.Name</code> is just syntactic sugar for
422
<code>var["Name"]</code>:
423
 
424
<pre>
425
	var ::= prefixexp `<b>.</b>&acute; Name
426
</pre>
427
 
428
<p>
429
All global variables live as fields in ordinary Lua tables,
430
called <em>environment tables</em> or simply
431
<em>environments</em> (see <a href="#2.9">&sect;2.9</a>).
432
Each function has its own reference to an environment,
433
so that all global variables in this function
434
will refer to this environment table.
435
When a function is created,
436
it inherits the environment from the function that created it.
437
To get the environment table of a Lua function,
438
you call <a href="#pdf-getfenv"><code>getfenv</code></a>.
439
To replace it,
440
you call <a href="#pdf-setfenv"><code>setfenv</code></a>.
441
(You can only manipulate the environment of C&nbsp;functions
442
through the debug library; (see <a href="#5.9">&sect;5.9</a>).)
443
 
444
 
445
<p>
446
An access to a global variable <code>x</code>
447
is equivalent to <code>_env.x</code>,
448
which in turn is equivalent to
449
 
450
<pre>
451
     gettable_event(_env, "x")
452
</pre><p>
453
where <code>_env</code> is the environment of the running function.
454
(See <a href="#2.8">&sect;2.8</a> for a complete description of the
455
<code>gettable_event</code> function.
456
This function is not defined or callable in Lua.
457
Similarly, the <code>_env</code> variable is not defined in Lua.
458
We use them here only for explanatory purposes.)
459
 
460
 
461
 
462
 
463
 
464
<h2>2.4 - <a name="2.4">Statements</a></h2>
465
 
466
<p>
467
Lua supports an almost conventional set of statements,
468
similar to those in Pascal or C.
469
This set includes
470
assignment, control structures, function calls,
471
and variable declarations.
472
 
473
 
474
 
475
<h3>2.4.1 - <a name="2.4.1">Chunks</a></h3>
476
 
477
<p>
478
The unit of execution of Lua is called a <em>chunk</em>.
479
A chunk is simply a sequence of statements,
480
which are executed sequentially.
481
Each statement can be optionally followed by a semicolon:
482
 
483
<pre>
484
	chunk ::= {stat [`<b>;</b>&acute;]}
485
</pre><p>
486
There are no empty statements and thus '<code>;;</code>' is not legal.
487
 
488
 
489
<p>
490
Lua handles a chunk as the body of an anonymous function 
491
with a variable number of arguments
492
(see <a href="#2.5.9">&sect;2.5.9</a>).
493
As such, chunks can define local variables,
494
receive arguments, and return values.
495
 
496
 
497
<p>
498
A chunk may be stored in a file or in a string inside the host program.
499
When a chunk is executed, first it is pre-compiled into instructions for
500
a virtual machine,
501
and then the compiled code is executed
502
by an interpreter for the virtual machine.
503
 
504
 
505
<p>
506
Chunks may also be pre-compiled into binary form;
507
see program <code>luac</code> for details.
508
Programs in source and compiled forms are interchangeable;
509
Lua automatically detects the file type and acts accordingly.
510
 
511
 
512
 
513
 
514
 
515
 
516
<h3>2.4.2 - <a name="2.4.2">Blocks</a></h3><p>
517
A block is a list of statements;
518
syntactically, a block is the same as a chunk:
519
 
520
<pre>
521
	block ::= chunk
522
</pre>
523
 
524
<p>
525
A block may be explicitly delimited to produce a single statement:
526
 
527
<pre>
528
	stat ::= <b>do</b> block <b>end</b>
529
</pre><p>
530
Explicit blocks are useful
531
to control the scope of variable declarations.
532
Explicit blocks are also sometimes used to
533
add a <b>return</b> or <b>break</b> statement in the middle
534
of another block (see <a href="#2.4.4">&sect;2.4.4</a>).
535
 
536
 
537
 
538
 
539
 
540
<h3>2.4.3 - <a name="2.4.3">Assignment</a></h3>
541
 
542
<p>
543
Lua allows multiple assignment.
544
Therefore, the syntax for assignment
545
defines a list of variables on the left side
546
and a list of expressions on the right side.
547
The elements in both lists are separated by commas:
548
 
549
<pre>
550
	stat ::= varlist1 `<b>=</b>&acute; explist1
551
	varlist1 ::= var {`<b>,</b>&acute; var}
552
	explist1 ::= exp {`<b>,</b>&acute; exp}
553
</pre><p>
554
Expressions are discussed in <a href="#2.5">&sect;2.5</a>.
555
 
556
 
557
<p>
558
Before the assignment,
559
the list of values is <em>adjusted</em> to the length of
560
the list of variables.
561
If there are more values than needed,
562
the excess values are thrown away.
563
If there are fewer values than needed,
564
the list is extended with as many  <b>nil</b>'s as needed.
565
If the list of expressions ends with a function call,
566
then all values returned by this call enter in the list of values,
567
before the adjustment
568
(except when the call is enclosed in parentheses; see <a href="#2.5">&sect;2.5</a>).
569
 
570
 
571
<p>
572
The assignment statement first evaluates all its expressions
573
and only then are the assignments performed.
574
Thus the code
575
 
576
<pre>
577
     i = 3
578
     i, a[i] = i+1, 20
579
</pre><p>
580
sets <code>a[3]</code> to 20, without affecting <code>a[4]</code>
581
because the <code>i</code> in <code>a[i]</code> is evaluated (to 3)
582
before it is assigned&nbsp;4.
583
Similarly, the line
584
 
585
<pre>
586
     x, y = y, x
587
</pre><p>
588
exchanges the values of <code>x</code> and <code>y</code>.
589
 
590
 
591
<p>
592
The meaning of assignments to global variables
593
and table fields can be changed via metatables.
594
An assignment to an indexed variable <code>t[i] = val</code> is equivalent to
595
<code>settable_event(t,i,val)</code>.
596
(See <a href="#2.8">&sect;2.8</a> for a complete description of the
597
<code>settable_event</code> function.
598
This function is not defined or callable in Lua.
599
We use it here only for explanatory purposes.)
600
 
601
 
602
<p>
603
An assignment to a global variable <code>x = val</code>
604
is equivalent to the assignment
605
<code>_env.x = val</code>,
606
which in turn is equivalent to
607
 
608
<pre>
609
     settable_event(_env, "x", val)
610
</pre><p>
611
where <code>_env</code> is the environment of the running function.
612
(The <code>_env</code> variable is not defined in Lua.
613
We use it here only for explanatory purposes.)
614
 
615
 
616
 
617
 
618
 
619
<h3>2.4.4 - <a name="2.4.4">Control Structures</a></h3><p>
620
The control structures
621
<b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and
622
familiar syntax:
623
 
624
 
625
 
626
 
627
<pre>
628
	stat ::= <b>while</b> exp <b>do</b> block <b>end</b>
629
	stat ::= <b>repeat</b> block <b>until</b> exp
630
	stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b>
631
</pre><p>
632
Lua also has a <b>for</b> statement, in two flavors (see <a href="#2.4.5">&sect;2.4.5</a>).
633
 
634
 
635
<p>
636
The condition expression of a
637
control structure may return any value.
638
Both <b>false</b> and <b>nil</b> are considered false.
639
All values different from <b>nil</b> and <b>false</b> are considered true
640
(in particular, the number 0 and the empty string are also true).
641
 
642
 
643
<p>
644
In the <b>repeat</b>&ndash;<b>until</b> loop,
645
the inner block does not end at the <b>until</b> keyword,
646
but only after the condition.
647
So, the condition can refer to local variables
648
declared inside the loop block.
649
 
650
 
651
<p>
652
The <b>return</b> statement is used to return values
653
from a function or a chunk (which is just a function).
654
 
655
Functions and chunks may return more than one value,
656
so the syntax for the <b>return</b> statement is
657
 
658
<pre>
659
	stat ::= <b>return</b> [explist1]
660
</pre>
661
 
662
<p>
663
The <b>break</b> statement is used to terminate the execution of a
664
<b>while</b>, <b>repeat</b>, or <b>for</b> loop,
665
skipping to the next statement after the loop:
666
 
667
 
668
<pre>
669
	stat ::= <b>break</b>
670
</pre><p>
671
A <b>break</b> ends the innermost enclosing loop.
672
 
673
 
674
<p>
675
The <b>return</b> and <b>break</b>
676
statements can only be written as the <em>last</em> statement of a block.
677
If it is really necessary to <b>return</b> or <b>break</b> in the
678
middle of a block,
679
then an explicit inner block can be used,
680
as in the idioms
681
<code>do return end</code> and <code>do break end</code>,
682
because now <b>return</b> and <b>break</b> are the last statements in
683
their (inner) blocks.
684
 
685
 
686
 
687
 
688
 
689
<h3>2.4.5 - <a name="2.4.5">For Statement</a></h3>
690
 
691
<p>
692
 
693
The <b>for</b> statement has two forms:
694
one numeric and one generic.
695
 
696
 
697
<p>
698
The numeric <b>for</b> loop repeats a block of code while a
699
control variable runs through an arithmetic progression.
700
It has the following syntax:
701
 
702
<pre>
703
	stat ::= <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b>
704
</pre><p>
705
The <em>block</em> is repeated for <em>name</em> starting at the value of
706
the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the
707
third <em>exp</em>.
708
More precisely, a <b>for</b> statement like
709
 
710
<pre>
711
     for var = e1, e2, e3 do block end
712
</pre><p>
713
is equivalent to the code:
714
 
715
<pre>
716
     do
717
       local _var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3)
718
       if not (_var and _limit and _step) then error() end
719
       while (_step&gt;0 and _var&lt;=_limit) or (_step&lt;=0 and _var&gt;=_limit) do
720
         local var = _var
721
         <em>block</em>
722
         _var = _var + _step
723
       end
724
     end
725
</pre><p>
726
Note the following:
727
 
728
<ul>
729
 
730
<li>
731
All three control expressions are evaluated only once,
732
before the loop starts.
733
They must all result in numbers.
734
</li>
735
 
736
<li>
737
<code>_var</code>, <code>_limit</code>, and <code>_step</code> are invisible variables.
738
The names are here for explanatory purposes only.
739
</li>
740
 
741
<li>
742
If the third expression (the step) is absent,
743
then a step of&nbsp;1 is used.
744
</li>
745
 
746
<li>
747
You can use <b>break</b> to exit a <b>for</b> loop.
748
</li>
749
 
750
<li>
751
The loop variable <code>var</code> is local to the loop;
752
you cannot use its value after the <b>for</b> ends or is broken.
753
If you need the value of the loop variable <code>var</code>,
754
then assign it to another variable before breaking or exiting the loop.
755
</li>
756
 
757
</ul>
758
 
759
<p>
760
The generic <b>for</b> statement works over functions,
761
called <em>iterators</em>.
762
On each iteration, the iterator function is called to produce a new value,
763
stopping when this new value is <b>nil</b>.
764
The generic <b>for</b> loop has the following syntax:
765
 
766
<pre>
767
	stat ::= <b>for</b> namelist <b>in</b> explist1 <b>do</b> block <b>end</b>
768
	namelist ::= Name {`<b>,</b>&acute; Name}
769
</pre><p>
770
A <b>for</b> statement like
771
 
772
<pre>
773
     for var_1, &middot;&middot;&middot;, var_n in explist do block end
774
</pre><p>
775
is equivalent to the code:
776
 
777
<pre>
778
     do
779
       local _f, _s, _var = explist
780
       while true do
781
         local var_1, &middot;&middot;&middot;, var_n = _f(_s, _var)
782
         _var = var_1
783
         if _var == nil then break end
784
         block
785
       end
786
     end
787
</pre><p>
788
Note the following:
789
 
790
<ul>
791
 
792
<li>
793
<code>explist</code> is evaluated only once.
794
Its results are an <em>iterator</em> function,
795
a <em>state</em>, and an initial value for the first <em>iterator variable</em>.
796
</li>
797
 
798
<li>
799
<code>_f</code>, <code>_s</code>, and <code>_var</code> are invisible variables.
800
The names are here for explanatory purposes only.
801
</li>
802
 
803
<li>
804
You can use <b>break</b> to exit a <b>for</b> loop.
805
</li>
806
 
807
<li>
808
The loop variables <code>var_i</code> are local to the loop;
809
you cannot use their values after the <b>for</b> ends.
810
If you need these values,
811
then assign them to other variables before breaking or exiting the loop.
812
</li>
813
 
814
</ul>
815
 
816
 
817
 
818
 
819
<h3>2.4.6 - <a name="2.4.6">Function Calls as Statements</a></h3><p>
820
To allow possible side-effects,
821
function calls can be executed as statements:
822
 
823
<pre>
824
	stat ::= functioncall
825
</pre><p>
826
In this case, all returned values are thrown away.
827
Function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>.
828
 
829
 
830
 
831
 
832
 
833
<h3>2.4.7 - <a name="2.4.7">Local Declarations</a></h3><p>
834
Local variables may be declared anywhere inside a block.
835
The declaration may include an initial assignment:
836
 
837
<pre>
838
	stat ::= <b>local</b> namelist [`<b>=</b>&acute; explist1]
839
</pre><p>
840
If present, an initial assignment has the same semantics
841
of a multiple assignment (see <a href="#2.4.3">&sect;2.4.3</a>).
842
Otherwise, all variables are initialized with <b>nil</b>.
843
 
844
 
845
<p>
846
A chunk is also a block (see <a href="#2.4.1">&sect;2.4.1</a>),
847
and so local variables can be declared in a chunk outside any explicit block.
848
The scope of such local variables extends until the end of the chunk.
849
 
850
 
851
<p>
852
The visibility rules for local variables are explained in <a href="#2.6">&sect;2.6</a>.
853
 
854
 
855
 
856
 
857
 
858
 
859
 
860
<h2>2.5 - <a name="2.5">Expressions</a></h2>
861
 
862
<p>
863
The basic expressions in Lua are the following:
864
 
865
<pre>
866
	exp ::= prefixexp
867
	exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
868
	exp ::= Number
869
	exp ::= String
870
	exp ::= function
871
	exp ::= tableconstructor
872
	exp ::= `<b>...</b>&acute;
873
	exp ::= exp binop exp
874
	exp ::= unop exp
875
	prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
876
</pre>
877
 
878
<p>
879
Numbers and literal strings are explained in <a href="#2.1">&sect;2.1</a>;
880
variables are explained in <a href="#2.3">&sect;2.3</a>;
881
function definitions are explained in <a href="#2.5.9">&sect;2.5.9</a>;
882
function calls are explained in <a href="#2.5.8">&sect;2.5.8</a>;
883
table constructors are explained in <a href="#2.5.7">&sect;2.5.7</a>.
884
Vararg expressions,
885
denoted by three dots ('<code>...</code>'), can only be used inside
886
vararg functions;
887
they are explained in <a href="#2.5.9">&sect;2.5.9</a>.
888
 
889
 
890
<p>
891
Binary operators comprise arithmetic operators (see <a href="#2.5.1">&sect;2.5.1</a>),
892
relational operators (see <a href="#2.5.2">&sect;2.5.2</a>), logical operators (see <a href="#2.5.3">&sect;2.5.3</a>),
893
and the concatenation operator (see <a href="#2.5.4">&sect;2.5.4</a>).
894
Unary operators comprise the unary minus (see <a href="#2.5.1">&sect;2.5.1</a>),
895
the unary <b>not</b> (see <a href="#2.5.3">&sect;2.5.3</a>),
896
and the unary <em>length operator</em> (see <a href="#2.5.5">&sect;2.5.5</a>).
897
 
898
 
899
<p>
900
Both function calls and vararg expressions may result in multiple values.
901
If the expression is used as a statement (see <a href="#2.4.6">&sect;2.4.6</a>)
902
(only possible for function calls),
903
then its return list is adjusted to zero elements,
904
thus discarding all returned values.
905
If the expression is used inside another expression
906
or in the middle of a list of expressions,
907
then its result list is adjusted to one element,
908
thus discarding all values except the first one.
909
If the expression is used as the last element of a list of expressions,
910
then no adjustment is made,
911
unless the call is enclosed in parentheses.
912
 
913
 
914
<p>
915
Here are some examples:
916
 
917
<pre>
918
     f()                -- adjusted to 0 results
919
     g(f(), x)          -- f() is adjusted to 1 result
920
     g(x, f())          -- g gets x plus all values returned by f()
921
     a,b,c = f(), x     -- f() is adjusted to 1 result (c gets nil)
922
     a,b = ...          -- a gets the first vararg parameter, b gets
923
                        -- the second (both a and b may get nil if there is
924
                        -- no corresponding vararg parameter)
925
     a,b,c = x, f()     -- f() is adjusted to 2 results
926
     a,b,c = f()        -- f() is adjusted to 3 results
927
     return f()         -- returns all values returned by f()
928
     return ...         -- returns all received vararg parameters
929
     return x,y,f()     -- returns x, y, and all values returned by f()
930
     {f()}              -- creates a list with all values returned by f()
931
     {...}              -- creates a list with all vararg parameters
932
     {f(), nil}         -- f() is adjusted to 1 result
933
</pre>
934
 
935
<p>
936
An expression enclosed in parentheses always results in only one value.
937
Thus,
938
<code>(f(x,y,z))</code> is always a single value,
939
even if <code>f</code> returns several values.
940
(The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code>
941
or <b>nil</b> if <code>f</code> does not return any values.)
942
 
943
 
944
 
945
<h3>2.5.1 - <a name="2.5.1">Arithmetic Operators</a></h3><p>
946
Lua supports the usual arithmetic operators:
947
the binary <code>+</code> (addition),
948
<code>-</code> (subtraction), <code>*</code> (multiplication),
949
<code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
950
and unary <code>-</code> (negation).
951
If the operands are numbers, or strings that can be converted to
952
numbers (see <a href="#2.2.1">&sect;2.2.1</a>),
953
then all operations have the usual meaning.
954
Exponentiation works for any exponent.
955
For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
956
Modulo is defined as
957
 
958
<pre>
959
     a % b == a - math.floor(a/b)*b
960
</pre><p>
961
That is, it is the remainder of a division that rounds
962
the quotient towards minus infinity.
963
 
964
 
965
 
966
 
967
 
968
<h3>2.5.2 - <a name="2.5.2">Relational Operators</a></h3><p>
969
The relational operators in Lua are
970
 
971
<pre>
972
     ==    ~=    &lt;     &gt;     &lt;=    &gt;=
973
</pre><p>
974
These operators always result in <b>false</b> or <b>true</b>.
975
 
976
 
977
<p>
978
Equality (<code>==</code>) first compares the type of its operands.
979
If the types are different, then the result is <b>false</b>.
980
Otherwise, the values of the operands are compared.
981
Numbers and strings are compared in the usual way.
982
Objects (tables, userdata, threads, and functions)
983
are compared by <em>reference</em>:
984
two objects are considered equal only if they are the <em>same</em> object.
985
Every time you create a new object
986
(a table, userdata, thread, or function),
987
this new object is different from any previously existing object.
988
 
989
 
990
<p>
991
You can change the way that Lua compares tables and userdata 
992
by using the "eq" metamethod (see <a href="#2.8">&sect;2.8</a>).
993
 
994
 
995
<p>
996
The conversion rules of <a href="#2.2.1">&sect;2.2.1</a>
997
<em>do not</em> apply to equality comparisons.
998
Thus, <code>"0"==0</code> evaluates to <b>false</b>,
999
and <code>t[0]</code> and <code>t["0"]</code> denote different
1000
entries in a table.
1001
 
1002
 
1003
<p>
1004
The operator <code>~=</code> is exactly the negation of equality (<code>==</code>).
1005
 
1006
 
1007
<p>
1008
The order operators work as follows.
1009
If both arguments are numbers, then they are compared as such.
1010
Otherwise, if both arguments are strings,
1011
then their values are compared according to the current locale.
1012
Otherwise, Lua tries to call the "lt" or the "le"
1013
metamethod (see <a href="#2.8">&sect;2.8</a>).
1014
 
1015
 
1016
 
1017
 
1018
 
1019
<h3>2.5.3 - <a name="2.5.3">Logical Operators</a></h3><p>
1020
The logical operators in Lua are
1021
<b>and</b>, <b>or</b>, and <b>not</b>.
1022
Like the control structures (see <a href="#2.4.4">&sect;2.4.4</a>),
1023
all logical operators consider both <b>false</b> and <b>nil</b> as false
1024
and anything else as true.
1025
 
1026
 
1027
<p>
1028
The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>.
1029
The conjunction operator <b>and</b> returns its first argument
1030
if this value is <b>false</b> or <b>nil</b>;
1031
otherwise, <b>and</b> returns its second argument.
1032
The disjunction operator <b>or</b> returns its first argument
1033
if this value is different from <b>nil</b> and <b>false</b>;
1034
otherwise, <b>or</b> returns its second argument.
1035
Both <b>and</b> and <b>or</b> use short-cut evaluation;
1036
that is,
1037
the second operand is evaluated only if necessary.
1038
Here are some examples:
1039
 
1040
<pre>
1041
     10 or 20            --&gt; 10
1042
     10 or error()       --&gt; 10
1043
     nil or "a"          --&gt; "a"
1044
     nil and 10          --&gt; nil
1045
     false and error()   --&gt; false
1046
     false and nil       --&gt; false
1047
     false or nil        --&gt; nil
1048
     10 and 20           --&gt; 20
1049
</pre><p>
1050
(In this manual,
1051
--> indicates the result of the preceding expression.)
1052
 
1053
 
1054
 
1055
 
1056
 
1057
<h3>2.5.4 - <a name="2.5.4">Concatenation</a></h3><p>
1058
The string concatenation operator in Lua is
1059
denoted by two dots ('<code>..</code>').
1060
If both operands are strings or numbers, then they are converted to
1061
strings according to the rules mentioned in <a href="#2.2.1">&sect;2.2.1</a>.
1062
Otherwise, the "concat" metamethod is called (see <a href="#2.8">&sect;2.8</a>).
1063
 
1064
 
1065
 
1066
 
1067
 
1068
<h3>2.5.5 - <a name="2.5.5">The Length Operator</a></h3>
1069
 
1070
<p>
1071
The length operator is denoted by the unary operator <code>#</code>.
1072
The length of a string is its number of bytes
1073
(that is, the usual meaning of string length when each
1074
character is one byte).
1075
 
1076
 
1077
<p>
1078
The length of a table <code>t</code> is defined to be any
1079
integer index <code>n</code>
1080
such that <code>t[n]</code> is not <b>nil</b> and <code>t[n+1]</code> is <b>nil</b>;
1081
moreover, if <code>t[1]</code> is <b>nil</b>, <code>n</code> may be zero.
1082
For a regular array, with non-nil values from 1 to a given <code>n</code>,
1083
its length is exactly that <code>n</code>,
1084
the index of its last value.
1085
If the array has "holes"
1086
(that is, <b>nil</b> values between other non-nil values),
1087
then <code>#t</code> may be any of the indices that
1088
directly precedes a <b>nil</b> value
1089
(that is, it may consider any such <b>nil</b> value as the end of
1090
the array). 
1091
 
1092
 
1093
 
1094
 
1095
 
1096
<h3>2.5.6 - <a name="2.5.6">Precedence</a></h3><p>
1097
Operator precedence in Lua follows the table below,
1098
from lower to higher priority:
1099
 
1100
<pre>
1101
     or
1102
     and
1103
     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
1104
     ..
1105
     +     -
1106
     *     /     %
1107
     not   #     - (unary)
1108
     ^
1109
</pre><p>
1110
As usual,
1111
you can use parentheses to change the precedences of an expression.
1112
The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>')
1113
operators are right associative.
1114
All other binary operators are left associative.
1115
 
1116
 
1117
 
1118
 
1119
 
1120
<h3>2.5.7 - <a name="2.5.7">Table Constructors</a></h3><p>
1121
Table constructors are expressions that create tables.
1122
Every time a constructor is evaluated, a new table is created.
1123
Constructors can be used to create empty tables,
1124
or to create a table and initialize some of its fields.
1125
The general syntax for constructors is
1126
 
1127
<pre>
1128
	tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
1129
	fieldlist ::= field {fieldsep field} [fieldsep]
1130
	field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
1131
	fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
1132
</pre>
1133
 
1134
<p>
1135
Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry
1136
with key <code>exp1</code> and value <code>exp2</code>.
1137
A field of the form <code>name = exp</code> is equivalent to
1138
<code>["name"] = exp</code>.
1139
Finally, fields of the form <code>exp</code> are equivalent to
1140
<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
1141
starting with 1.
1142
Fields in the other formats do not affect this counting.
1143
For example,
1144
 
1145
<pre>
1146
     a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
1147
</pre><p>
1148
is equivalent to
1149
 
1150
<pre>
1151
     do
1152
       local t = {}
1153
       t[f(1)] = g
1154
       t[1] = "x"         -- 1st exp
1155
       t[2] = "y"         -- 2nd exp
1156
       t.x = 1            -- t["x"] = 1
1157
       t[3] = f(x)        -- 3rd exp
1158
       t[30] = 23
1159
       t[4] = 45          -- 4th exp
1160
       a = t
1161
     end
1162
</pre>
1163
 
1164
<p>
1165
If the last field in the list has the form <code>exp</code>
1166
and the expression is a function call or a vararg expression,
1167
then all values returned by this expression enter the list consecutively
1168
(see <a href="#2.5.8">&sect;2.5.8</a>).
1169
To avoid this,
1170
enclose the function call (or the vararg expression)
1171
in parentheses (see <a href="#2.5">&sect;2.5</a>).
1172
 
1173
 
1174
<p>
1175
The field list may have an optional trailing separator,
1176
as a convenience for machine-generated code.
1177
 
1178
 
1179
 
1180
 
1181
 
1182
<h3>2.5.8 - <a name="2.5.8">Function Calls</a></h3><p>
1183
A function call in Lua has the following syntax:
1184
 
1185
<pre>
1186
	functioncall ::= prefixexp args
1187
</pre><p>
1188
In a function call,
1189
first prefixexp and args are evaluated.
1190
If the value of prefixexp has type <em>function</em>,
1191
then this function is called
1192
with the given arguments.
1193
Otherwise, the prefixexp "call" metamethod is called,
1194
having as first parameter the value of prefixexp,
1195
followed by the original call arguments
1196
(see <a href="#2.8">&sect;2.8</a>).
1197
 
1198
 
1199
<p>
1200
The form
1201
 
1202
<pre>
1203
	functioncall ::= prefixexp `<b>:</b>&acute; Name args
1204
</pre><p>
1205
can be used to call "methods".
1206
A call <code>v:name(<em>args</em>)</code>
1207
is syntactic sugar for <code>v.name(v,<em>args</em>)</code>,
1208
except that <code>v</code> is evaluated only once.
1209
 
1210
 
1211
<p>
1212
Arguments have the following syntax:
1213
 
1214
<pre>
1215
	args ::= `<b>(</b>&acute; [explist1] `<b>)</b>&acute;
1216
	args ::= tableconstructor
1217
	args ::= String
1218
</pre><p>
1219
All argument expressions are evaluated before the call.
1220
A call of the form <code>f{<em>fields</em>}</code> is
1221
syntactic sugar for <code>f({<em>fields</em>})</code>;
1222
that is, the argument list is a single new table.
1223
A call of the form <code>f'<em>string</em>'</code>
1224
(or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>)
1225
is syntactic sugar for <code>f('<em>string</em>')</code>;
1226
that is, the argument list is a single literal string.
1227
 
1228
 
1229
<p>
1230
As an exception to the free-format syntax of Lua,
1231
you cannot put a line break before the '<code>(</code>' in a function call.
1232
This restriction avoids some ambiguities in the language.
1233
If you write
1234
 
1235
<pre>
1236
     a = f
1237
     (g).x(a)
1238
</pre><p>
1239
Lua would see that as a single statement, <code>a = f(g).x(a)</code>.
1240
So, if you want two statements, you must add a semi-colon between them.
1241
If you actually want to call <code>f</code>,
1242
you must remove the line break before <code>(g)</code>.
1243
 
1244
 
1245
<p>
1246
A call of the form <code>return</code> <em>functioncall</em> is called
1247
a <em>tail call</em>.
1248
Lua implements <em>proper tail calls</em>
1249
(or <em>proper tail recursion</em>):
1250
in a tail call,
1251
the called function reuses the stack entry of the calling function.
1252
Therefore, there is no limit on the number of nested tail calls that
1253
a program can execute.
1254
However, a tail call erases any debug information about the
1255
calling function.
1256
Note that a tail call only happens with a particular syntax,
1257
where the <b>return</b> has one single function call as argument;
1258
this syntax makes the calling function return exactly
1259
the returns of the called function.
1260
So, none of the following examples are tail calls:
1261
 
1262
<pre>
1263
     return (f(x))        -- results adjusted to 1
1264
     return 2 * f(x)
1265
     return x, f(x)       -- additional results
1266
     f(x); return         -- results discarded
1267
     return x or f(x)     -- results adjusted to 1
1268
</pre>
1269
 
1270
 
1271
 
1272
 
1273
<h3>2.5.9 - <a name="2.5.9">Function Definitions</a></h3>
1274
 
1275
<p>
1276
The syntax for function definition is
1277
 
1278
<pre>
1279
	function ::= <b>function</b> funcbody
1280
	funcbody ::= `<b>(</b>&acute; [parlist1] `<b>)</b>&acute; block <b>end</b>
1281
</pre>
1282
 
1283
<p>
1284
The following syntactic sugar simplifies function definitions:
1285
 
1286
<pre>
1287
	stat ::= <b>function</b> funcname funcbody
1288
	stat ::= <b>local</b> <b>function</b> Name funcbody
1289
	funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
1290
</pre><p>
1291
The statement
1292
 
1293
<pre>
1294
     function f () <em>body</em> end
1295
</pre><p>
1296
translates to
1297
 
1298
<pre>
1299
     f = function () <em>body</em> end
1300
</pre><p>
1301
The statement
1302
 
1303
<pre>
1304
     function t.a.b.c.f () <em>body</em> end
1305
</pre><p>
1306
translates to
1307
 
1308
<pre>
1309
     t.a.b.c.f = function () <em>body</em> end
1310
</pre><p>
1311
The statement
1312
 
1313
<pre>
1314
     local function f () <em>body</em> end
1315
</pre><p>
1316
translates to
1317
 
1318
<pre>
1319
     local f; f = function () <em>body</em> end
1320
</pre><p>
1321
<em>not</em> to
1322
 
1323
<pre>
1324
     local f = function () <em>body</em> end
1325
</pre><p>
1326
(This only makes a difference when the body of the function
1327
contains references to <code>f</code>.)
1328
 
1329
 
1330
<p>
1331
A function definition is an executable expression,
1332
whose value has type <em>function</em>.
1333
When Lua pre-compiles a chunk,
1334
all its function bodies are pre-compiled too.
1335
Then, whenever Lua executes the function definition,
1336
the function is <em>instantiated</em> (or <em>closed</em>).
1337
This function instance (or <em>closure</em>)
1338
is the final value of the expression.
1339
Different instances of the same function
1340
may refer to different  external local variables
1341
and may have different environment tables.
1342
 
1343
 
1344
<p>
1345
Parameters act as local variables that are
1346
initialized with the argument values:
1347
 
1348
<pre>
1349
	parlist1 ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
1350
</pre><p>
1351
When a function is called,
1352
the list of arguments is adjusted to
1353
the length of the list of parameters,
1354
unless the function is a variadic or <em>vararg function</em>,
1355
which is
1356
indicated by three dots ('<code>...</code>') at the end of its parameter list.
1357
A vararg function does not adjust its argument list;
1358
instead, it collects all extra arguments and supplies them
1359
to the function through a <em>vararg expression</em>,
1360
which is also written as three dots.
1361
The value of this expression is a list of all actual extra arguments,
1362
similar to a function with multiple results.
1363
If a vararg expression is used inside another expression
1364
or in the middle of a list of expressions,
1365
then its return list is adjusted to one element.
1366
If the expression is used as the last element of a list of expressions,
1367
then no adjustment is made
1368
(unless the call is enclosed in parentheses).
1369
 
1370
 
1371
<p>
1372
As an example, consider the following definitions:
1373
 
1374
<pre>
1375
     function f(a, b) end
1376
     function g(a, b, ...) end
1377
     function r() return 1,2,3 end
1378
</pre><p>
1379
Then, we have the following mapping from arguments to parameters and
1380
to the vararg expression:
1381
 
1382
<pre>
1383
     CALL            PARAMETERS
1384
 
1385
     f(3)             a=3, b=nil
1386
     f(3, 4)          a=3, b=4
1387
     f(3, 4, 5)       a=3, b=4
1388
     f(r(), 10)       a=1, b=10
1389
     f(r())           a=1, b=2
1390
 
1391
     g(3)             a=3, b=nil, ... --&gt;  (nothing)
1392
     g(3, 4)          a=3, b=4,   ... --&gt;  (nothing)
1393
     g(3, 4, 5, 8)    a=3, b=4,   ... --&gt;  5  8
1394
     g(5, r())        a=5, b=1,   ... --&gt;  2  3
1395
</pre>
1396
 
1397
<p>
1398
Results are returned using the <b>return</b> statement (see <a href="#2.4.4">&sect;2.4.4</a>).
1399
If control reaches the end of a function
1400
without encountering a <b>return</b> statement,
1401
then the function returns with no results.
1402
 
1403
 
1404
<p>
1405
The <em>colon</em> syntax
1406
is used for defining <em>methods</em>,
1407
that is, functions that have an implicit extra parameter <code>self</code>.
1408
Thus, the statement
1409
 
1410
<pre>
1411
     function t.a.b.c:f (<em>params</em>) <em>body</em> end
1412
</pre><p>
1413
is syntactic sugar for
1414
 
1415
<pre>
1416
     t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end
1417
</pre>
1418
 
1419
 
1420
 
1421
 
1422
 
1423
 
1424
<h2>2.6 - <a name="2.6">Visibility Rules</a></h2>
1425
 
1426
<p>
1427
 
1428
Lua is a lexically scoped language.
1429
The scope of variables begins at the first statement <em>after</em>
1430
their declaration and lasts until the end of the innermost block that
1431
includes the declaration.
1432
Consider the following example:
1433
 
1434
<pre>
1435
     x = 10                -- global variable
1436
     do                    -- new block
1437
       local x = x         -- new 'x', with value 10
1438
       print(x)            --&gt; 10
1439
       x = x+1
1440
       do                  -- another block
1441
         local x = x+1     -- another 'x'
1442
         print(x)          --&gt; 12
1443
       end
1444
       print(x)            --&gt; 11
1445
     end
1446
     print(x)              --&gt; 10  (the global one)
1447
</pre>
1448
 
1449
<p>
1450
Notice that, in a declaration like <code>local x = x</code>,
1451
the new <code>x</code> being declared is not in scope yet,
1452
and so the second <code>x</code> refers to the outside variable.
1453
 
1454
 
1455
<p>
1456
Because of the lexical scoping rules,
1457
local variables can be freely accessed by functions
1458
defined inside their scope.
1459
A local variable used by an inner function is called
1460
an <em>upvalue</em>, or <em>external local variable</em>,
1461
inside the inner function.
1462
 
1463
 
1464
<p>
1465
Notice that each execution of a <b>local</b> statement
1466
defines new local variables.
1467
Consider the following example:
1468
 
1469
<pre>
1470
     a = {}
1471
     local x = 20
1472
     for i=1,10 do
1473
       local y = 0
1474
       a[i] = function () y=y+1; return x+y end
1475
     end
1476
</pre><p>
1477
The loop creates ten closures
1478
(that is, ten instances of the anonymous function).
1479
Each of these closures uses a different <code>y</code> variable,
1480
while all of them share the same <code>x</code>.
1481
 
1482
 
1483
 
1484
 
1485
 
1486
<h2>2.7 - <a name="2.7">Error Handling</a></h2>
1487
 
1488
<p>
1489
Because Lua is an embedded extension language,
1490
all Lua actions start from C&nbsp;code in the host program
1491
calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
1492
Whenever an error occurs during Lua compilation or execution,
1493
control returns to C,
1494
which can take appropriate measures
1495
(such as printing an error message).
1496
 
1497
 
1498
<p>
1499
Lua code can explicitly generate an error by calling the
1500
<a href="#pdf-error"><code>error</code></a> function.
1501
If you need to catch errors in Lua,
1502
you can use the <a href="#pdf-pcall"><code>pcall</code></a> function.
1503
 
1504
 
1505
 
1506
 
1507
 
1508
<h2>2.8 - <a name="2.8">Metatables</a></h2>
1509
 
1510
<p>
1511
Every value in Lua may have a <em>metatable</em>.
1512
This <em>metatable</em> is an ordinary Lua table
1513
that defines the behavior of the original value
1514
under certain special operations.
1515
You can change several aspects of the behavior
1516
of operations over a value by setting specific fields in its metatable.
1517
For instance, when a non-numeric value is the operand of an addition,
1518
Lua checks for a function in the field <code>"__add"</code> in its metatable.
1519
If it finds one,
1520
Lua calls this function to perform the addition.
1521
 
1522
 
1523
<p>
1524
We call the keys in a metatable <em>events</em>
1525
and the values <em>metamethods</em>.
1526
In the previous example, the event is <code>"add"</code> 
1527
and the metamethod is the function that performs the addition.
1528
 
1529
 
1530
<p>
1531
You can query the metatable of any value
1532
through the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
1533
 
1534
 
1535
<p>
1536
You can replace the metatable of tables
1537
through the <a href="#pdf-setmetatable"><code>setmetatable</code></a>
1538
function.
1539
You cannot change the metatable of other types from Lua
1540
(except using the debug library);
1541
you must use the C&nbsp;API for that.
1542
 
1543
 
1544
<p>
1545
Tables and userdata have individual metatables
1546
(although multiple tables and userdata can share
1547
a same table as their metatable);
1548
values of all other types share one single metatable per type.
1549
So, there is one single metatable for all numbers,
1550
and for all strings, etc.
1551
 
1552
 
1553
<p>
1554
A metatable may control how an object behaves in arithmetic operations,
1555
order comparisons, concatenation, length operation, and indexing.
1556
A metatable can also define a function to be called when a userdata
1557
is garbage collected.
1558
For each of these operations Lua associates a specific key
1559
called an <em>event</em>.
1560
When Lua performs one of these operations over a value,
1561
it checks whether this value has a metatable with the corresponding event.
1562
If so, the value associated with that key (the metamethod)
1563
controls how Lua will perform the operation.
1564
 
1565
 
1566
<p>
1567
Metatables control the operations listed next.
1568
Each operation is identified by its corresponding name.
1569
The key for each operation is a string with its name prefixed by
1570
two underscores, '<code>__</code>';
1571
for instance, the key for operation "add" is the
1572
string <code>"__add"</code>.
1573
The semantics of these operations is better explained by a Lua function
1574
describing how the interpreter executes the operation.
1575
 
1576
 
1577
<p>
1578
The code shown here in Lua is only illustrative;
1579
the real behavior is hard coded in the interpreter
1580
and it is much more efficient than this simulation.
1581
All functions used in these descriptions
1582
(<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
1583
are described in <a href="#5.1">&sect;5.1</a>.
1584
In particular, to retrieve the metamethod of a given object,
1585
we use the expression
1586
 
1587
<pre>
1588
     metatable(obj)[event]
1589
</pre><p>
1590
This should be read as
1591
 
1592
<pre>
1593
     rawget(getmetatable(obj) or {}, event)
1594
</pre><p>
1595
That is, the access to a metamethod does not invoke other metamethods,
1596
and the access to objects with no metatables does not fail
1597
(it simply results in <b>nil</b>).
1598
 
1599
 
1600
 
1601
<ul>
1602
 
1603
<li><b>"add":</b>
1604
the <code>+</code> operation.
1605
 
1606
 
1607
 
1608
<p>
1609
The function <code>getbinhandler</code> below defines how Lua chooses a handler
1610
for a binary operation.
1611
First, Lua tries the first operand.
1612
If its type does not define a handler for the operation,
1613
then Lua tries the second operand.
1614
 
1615
<pre>
1616
     function getbinhandler (op1, op2, event)
1617
       return metatable(op1)[event] or metatable(op2)[event]
1618
     end
1619
</pre><p>
1620
By using this function,
1621
the behavior of the <code>op1 + op2</code> is
1622
 
1623
<pre>
1624
     function add_event (op1, op2)
1625
       local o1, o2 = tonumber(op1), tonumber(op2)
1626
       if o1 and o2 then  -- both operands are numeric?
1627
         return o1 + o2   -- '+' here is the primitive 'add'
1628
       else  -- at least one of the operands is not numeric
1629
         local h = getbinhandler(op1, op2, "__add")
1630
         if h then
1631
           -- call the handler with both operands
1632
           return h(op1, op2)
1633
         else  -- no handler available: default behavior
1634
           error(&middot;&middot;&middot;)
1635
         end
1636
       end
1637
     end
1638
</pre><p>
1639
</li>
1640
 
1641
<li><b>"sub":</b>
1642
the <code>-</code> operation.
1643
 
1644
Behavior similar to the "add" operation.
1645
</li>
1646
 
1647
<li><b>"mul":</b>
1648
the <code>*</code> operation.
1649
 
1650
Behavior similar to the "add" operation.
1651
</li>
1652
 
1653
<li><b>"div":</b>
1654
the <code>/</code> operation.
1655
 
1656
Behavior similar to the "add" operation.
1657
</li>
1658
 
1659
<li><b>"mod":</b>
1660
the <code>%</code> operation.
1661
 
1662
Behavior similar to the "add" operation,
1663
with the operation
1664
<code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
1665
</li>
1666
 
1667
<li><b>"pow":</b>
1668
the <code>^</code> (exponentiation) operation.
1669
 
1670
Behavior similar to the "add" operation,
1671
with the function <code>pow</code> (from the C&nbsp;math library)
1672
as the primitive operation.
1673
</li>
1674
 
1675
<li><b>"unm":</b>
1676
the unary <code>-</code> operation.
1677
 
1678
 
1679
<pre>
1680
     function unm_event (op)
1681
       local o = tonumber(op)
1682
       if o then  -- operand is numeric?
1683
         return -o  -- '-' here is the primitive 'unm'
1684
       else  -- the operand is not numeric.
1685
         -- Try to get a handler from the operand
1686
         local h = metatable(op).__unm
1687
         if h then
1688
           -- call the handler with the operand
1689
           return h(op)
1690
         else  -- no handler available: default behavior
1691
           error(&middot;&middot;&middot;)
1692
         end
1693
       end
1694
     end
1695
</pre><p>
1696
</li>
1697
 
1698
<li><b>"concat":</b>
1699
the <code>..</code> (concatenation) operation.
1700
 
1701
 
1702
<pre>
1703
     function concat_event (op1, op2)
1704
       if (type(op1) == "string" or type(op1) == "number") and
1705
          (type(op2) == "string" or type(op2) == "number") then
1706
         return op1 .. op2  -- primitive string concatenation
1707
       else
1708
         local h = getbinhandler(op1, op2, "__concat")
1709
         if h then
1710
           return h(op1, op2)
1711
         else
1712
           error(&middot;&middot;&middot;)
1713
         end
1714
       end
1715
     end
1716
</pre><p>
1717
</li>
1718
 
1719
<li><b>"len":</b>
1720
the <code>#</code> operation.
1721
 
1722
 
1723
<pre>
1724
     function len_event (op)
1725
       if type(op) == "string" then
1726
         return strlen(op)         -- primitive string length
1727
       elseif type(op) == "table" then
1728
         return #op                -- primitive table length
1729
       else
1730
         local h = metatable(op).__len
1731
         if h then
1732
           -- call the handler with the operand
1733
           return h(op)
1734
         else  -- no handler available: default behavior
1735
           error(&middot;&middot;&middot;)
1736
         end
1737
       end
1738
     end
1739
</pre><p>
1740
See <a href="#2.5.5">&sect;2.5.5</a> for a description of the length of a table.
1741
</li>
1742
 
1743
<li><b>"eq":</b>
1744
the <code>==</code> operation.
1745
 
1746
The function <code>getcomphandler</code> defines how Lua chooses a metamethod
1747
for comparison operators.
1748
A metamethod only is selected when both objects
1749
being compared have the same type
1750
and the same metamethod for the selected operation.
1751
 
1752
<pre>
1753
     function getcomphandler (op1, op2, event)
1754
       if type(op1) ~= type(op2) then return nil end
1755
       local mm1 = metatable(op1)[event]
1756
       local mm2 = metatable(op2)[event]
1757
       if mm1 == mm2 then return mm1 else return nil end
1758
     end
1759
</pre><p>
1760
The "eq" event is defined as follows:
1761
 
1762
<pre>
1763
     function eq_event (op1, op2)
1764
       if type(op1) ~= type(op2) then  -- different types?
1765
         return false   -- different objects
1766
       end
1767
       if op1 == op2 then   -- primitive equal?
1768
         return true   -- objects are equal
1769
       end
1770
       -- try metamethod
1771
       local h = getcomphandler(op1, op2, "__eq")
1772
       if h then
1773
         return h(op1, op2)
1774
       else
1775
         return false
1776
       end
1777
     end
1778
</pre><p>
1779
<code>a ~= b</code> is equivalent to <code>not (a == b)</code>.
1780
</li>
1781
 
1782
<li><b>"lt":</b>
1783
the <code>&lt;</code> operation.
1784
 
1785
 
1786
<pre>
1787
     function lt_event (op1, op2)
1788
       if type(op1) == "number" and type(op2) == "number" then
1789
         return op1 &lt; op2   -- numeric comparison
1790
       elseif type(op1) == "string" and type(op2) == "string" then
1791
         return op1 &lt; op2   -- lexicographic comparison
1792
       else
1793
         local h = getcomphandler(op1, op2, "__lt")
1794
         if h then
1795
           return h(op1, op2)
1796
         else
1797
           error(&middot;&middot;&middot;);
1798
         end
1799
       end
1800
     end
1801
</pre><p>
1802
<code>a &gt; b</code> is equivalent to <code>b &lt; a</code>.
1803
</li>
1804
 
1805
<li><b>"le":</b>
1806
the <code>&lt;=</code> operation.
1807
 
1808
 
1809
<pre>
1810
     function le_event (op1, op2)
1811
       if type(op1) == "number" and type(op2) == "number" then
1812
         return op1 &lt;= op2   -- numeric comparison
1813
       elseif type(op1) == "string" and type(op2) == "string" then
1814
         return op1 &lt;= op2   -- lexicographic comparison
1815
       else
1816
         local h = getcomphandler(op1, op2, "__le")
1817
         if h then
1818
           return h(op1, op2)
1819
         else
1820
           h = getcomphandler(op1, op2, "__lt")
1821
           if h then
1822
             return not h(op2, op1)
1823
           else
1824
             error(&middot;&middot;&middot;);
1825
           end
1826
         end
1827
       end
1828
     end
1829
</pre><p>
1830
<code>a &gt;= b</code> is equivalent to <code>b &lt;= a</code>.
1831
Note that, in the absence of a "le" metamethod,
1832
Lua tries the "lt", assuming that <code>a &lt;= b</code> is
1833
equivalent to <code>not (b &lt; a)</code>.
1834
</li>
1835
 
1836
<li><b>"index":</b>
1837
The indexing access <code>table[key]</code>.
1838
 
1839
 
1840
<pre>
1841
     function gettable_event (table, key)
1842
       local h
1843
       if type(table) == "table" then
1844
         local v = rawget(table, key)
1845
         if v ~= nil then return v end
1846
         h = metatable(table).__index
1847
         if h == nil then return nil end
1848
       else
1849
         h = metatable(table).__index
1850
         if h == nil then
1851
           error(&middot;&middot;&middot;);
1852
         end
1853
       end
1854
       if type(h) == "function" then
1855
         return h(table, key)      -- call the handler
1856
       else return h[key]          -- or repeat operation on it
1857
       end
1858
     end
1859
</pre><p>
1860
</li>
1861
 
1862
<li><b>"newindex":</b>
1863
The indexing assignment <code>table[key] = value</code>.
1864
 
1865
 
1866
<pre>
1867
     function settable_event (table, key, value)
1868
       local h
1869
       if type(table) == "table" then
1870
         local v = rawget(table, key)
1871
         if v ~= nil then rawset(table, key, value); return end
1872
         h = metatable(table).__newindex
1873
         if h == nil then rawset(table, key, value); return end
1874
       else
1875
         h = metatable(table).__newindex
1876
         if h == nil then
1877
           error(&middot;&middot;&middot;);
1878
         end
1879
       end
1880
       if type(h) == "function" then
1881
         return h(table, key,value)    -- call the handler
1882
       else h[key] = value             -- or repeat operation on it
1883
       end
1884
     end
1885
</pre><p>
1886
</li>
1887
 
1888
<li><b>"call":</b>
1889
called when Lua calls a value.
1890
 
1891
 
1892
<pre>
1893
     function function_event (func, ...)
1894
       if type(func) == "function" then
1895
         return func(...)   -- primitive call
1896
       else
1897
         local h = metatable(func).__call
1898
         if h then
1899
           return h(func, ...)
1900
         else
1901
           error(&middot;&middot;&middot;)
1902
         end
1903
       end
1904
     end
1905
</pre><p>
1906
</li>
1907
 
1908
</ul>
1909
 
1910
 
1911
 
1912
 
1913
<h2>2.9 - <a name="2.9">Environments</a></h2>
1914
 
1915
<p>
1916
Besides metatables,
1917
objects of types thread, function, and userdata
1918
have another table associated with them,
1919
called their <em>environment</em>.
1920
Like metatables, environments are regular tables and
1921
multiple objects can share the same environment.
1922
 
1923
 
1924
<p>
1925
Environments associated with userdata have no meaning for Lua.
1926
It is only a convenience feature for programmers to associate a table to
1927
a userdata.
1928
 
1929
 
1930
<p>
1931
Environments associated with threads are called
1932
<em>global environments</em>.
1933
They are used as the default environment for their threads and
1934
non-nested functions created by the thread
1935
(through <a href="#pdf-loadfile"><code>loadfile</code></a>, <a href="#pdf-loadstring"><code>loadstring</code></a> or <a href="#pdf-load"><code>load</code></a>)
1936
and can be directly accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1937
 
1938
 
1939
<p>
1940
Environments associated with C&nbsp;functions can be directly
1941
accessed by C&nbsp;code (see <a href="#3.3">&sect;3.3</a>).
1942
They are used as the default environment for other C&nbsp;functions
1943
created by the function.
1944
 
1945
 
1946
<p>
1947
Environments associated with Lua functions are used to resolve
1948
all accesses to global variables within the function (see <a href="#2.3">&sect;2.3</a>).
1949
They are used as the default environment for other Lua functions
1950
created by the function.
1951
 
1952
 
1953
<p>
1954
You can change the environment of a Lua function or the
1955
running thread by calling <a href="#pdf-setfenv"><code>setfenv</code></a>.
1956
You can get the environment of a Lua function or the running thread
1957
by calling <a href="#pdf-getfenv"><code>getfenv</code></a>.
1958
To manipulate the environment of other objects
1959
(userdata, C&nbsp;functions, other threads) you must
1960
use the C&nbsp;API.
1961
 
1962
 
1963
 
1964
 
1965
 
1966
<h2>2.10 - <a name="2.10">Garbage Collection</a></h2>
1967
 
1968
<p>
1969
Lua performs automatic memory management.
1970
This means that
1971
you have to worry neither about allocating memory for new objects
1972
nor about freeing it when the objects are no longer needed.
1973
Lua manages memory automatically by running
1974
a <em>garbage collector</em> from time to time
1975
to collect all <em>dead objects</em>
1976
(that is, these objects that are no longer accessible from Lua).
1977
All objects in Lua are subject to automatic management:
1978
tables, userdata, functions, threads, and strings.
1979
 
1980
 
1981
<p>
1982
Lua implements an incremental mark-and-sweep collector.
1983
It uses two numbers to control its garbage-collection cycles:
1984
the <em>garbage-collector pause</em> and
1985
the <em>garbage-collector step multiplier</em>.
1986
 
1987
 
1988
<p>
1989
The garbage-collector pause
1990
controls how long the collector waits before starting a new cycle.
1991
Larger values make the collector less aggressive.
1992
Values smaller than 1 mean the collector will not wait to
1993
start a new cycle.
1994
A value of 2 means that the collector waits for the total memory in use
1995
to double before starting a new cycle.
1996
 
1997
 
1998
<p>
1999
The step multiplier
2000
controls the relative speed of the collector relative to
2001
memory allocation.
2002
Larger values make the collector more aggressive but also increase
2003
the size of each incremental step.
2004
Values smaller than 1 make the collector too slow and
2005
may result in  the collector never finishing a cycle.
2006
The default, 2, means that the collector runs at "twice"
2007
the speed of memory allocation.
2008
 
2009
 
2010
<p>
2011
You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
2012
or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
2013
Both get percentage points as arguments
2014
(so an argument of 100 means a real value of 1).
2015
With these functions you can also control 
2016
the collector directly (e.g., stop and restart it).
2017
 
2018
 
2019
 
2020
<h3>2.10.1 - <a name="2.10.1">Garbage-Collection Metamethods</a></h3>
2021
 
2022
<p>
2023
Using the C&nbsp;API,
2024
you can set garbage-collector metamethods for userdata (see <a href="#2.8">&sect;2.8</a>).
2025
These metamethods are also called <em>finalizers</em>.
2026
Finalizers allow you to coordinate Lua's garbage collection
2027
with external resource management
2028
(such as closing files, network or database connections,
2029
or freeing your own memory).
2030
 
2031
 
2032
<p>
2033
Garbage userdata with a field <code>__gc</code> in their metatables are not
2034
collected immediately by the garbage collector.
2035
Instead, Lua puts them in a list.
2036
After the collection,
2037
Lua does the equivalent of the following function
2038
for each userdata in that list:
2039
 
2040
<pre>
2041
     function gc_event (udata)
2042
       local h = metatable(udata).__gc
2043
       if h then
2044
         h(udata)
2045
       end
2046
     end
2047
</pre>
2048
 
2049
<p>
2050
At the end of each garbage-collection cycle,
2051
the finalizers for userdata are called in <em>reverse</em>
2052
order of their creation,
2053
among those collected in that cycle.
2054
That is, the first finalizer to be called is the one associated
2055
with the userdata created last in the program.
2056
 
2057
 
2058
 
2059
 
2060
 
2061
<h3>2.10.2 - <a name="2.10.2">Weak Tables</a></h3>
2062
 
2063
<p>
2064
A <em>weak table</em> is a table whose elements are
2065
<em>weak references</em>.
2066
A weak reference is ignored by the garbage collector.
2067
In other words,
2068
if the only references to an object are weak references,
2069
then the garbage collector will collect this object.
2070
 
2071
 
2072
<p>
2073
A weak table can have weak keys, weak values, or both.
2074
A table with weak keys allows the collection of its keys,
2075
but prevents the collection of its values.
2076
A table with both weak keys and weak values allows the collection of
2077
both keys and values.
2078
In any case, if either the key or the value is collected,
2079
the whole pair is removed from the table.
2080
The weakness of a table is controlled by the value of the
2081
<code>__mode</code> field of its metatable.
2082
If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>',
2083
the keys in the table are weak.
2084
If <code>__mode</code> contains '<code>v</code>',
2085
the values in the table are weak.
2086
 
2087
 
2088
<p>
2089
After you use a table as a metatable,
2090
you should not change the value of its field <code>__mode</code>.
2091
Otherwise, the weak behavior of the tables controlled by this
2092
metatable is undefined.
2093
 
2094
 
2095
 
2096
 
2097
 
2098
 
2099
 
2100
<h2>2.11 - <a name="2.11">Coroutines</a></h2>
2101
 
2102
<p>
2103
Lua supports coroutines,
2104
also called <em>collaborative multithreading</em>.
2105
A coroutine in Lua represents an independent thread of execution.
2106
Unlike threads in multithread systems, however,
2107
a coroutine only suspends its execution by explicitly calling
2108
a yield function.
2109
 
2110
 
2111
<p>
2112
You create a coroutine with a call to <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
2113
Its sole argument is a function
2114
that is the main function of the coroutine.
2115
The <code>create</code> function only creates a new coroutine and
2116
returns a handle to it (an object of type <em>thread</em>);
2117
it does not start the coroutine execution.
2118
 
2119
 
2120
<p>
2121
When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2122
passing as its first argument
2123
the thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2124
the coroutine starts its execution,
2125
at the first line of its main function.
2126
Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
2127
to the coroutine main function.
2128
After the coroutine starts running,
2129
it runs until it terminates or <em>yields</em>.
2130
 
2131
 
2132
<p>
2133
A coroutine can terminate its execution in two ways:
2134
normally, when its main function returns
2135
(explicitly or implicitly, after the last instruction);
2136
and abnormally, if there is an unprotected error.
2137
In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
2138
plus any values returned by the coroutine main function.
2139
In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
2140
plus an error message.
2141
 
2142
 
2143
<p>
2144
A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2145
When a coroutine yields,
2146
the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
2147
even if the yield happens inside nested function calls
2148
(that is, not in the main function,
2149
but in a function directly or indirectly called by the main function).
2150
In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
2151
plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
2152
The next time you resume the same coroutine,
2153
it continues its execution from the point where it yielded,
2154
with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
2155
arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2156
 
2157
 
2158
<p>
2159
The <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function creates a coroutine,
2160
just like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
2161
but instead of returning the coroutine itself,
2162
it returns a function that, when called, resumes the coroutine.
2163
Any arguments passed to this function
2164
go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
2165
<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>,
2166
except the first one (the boolean error code).
2167
Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
2168
<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
2169
any error is propagated to the caller.
2170
 
2171
 
2172
<p>
2173
As an example,
2174
consider the following code:
2175
 
2176
<pre>
2177
     function foo (a)
2178
       print("foo", a)
2179
       return coroutine.yield(2*a)
2180
     end
2181
 
2182
     co = coroutine.create(function (a,b)
2183
           print("co-body", a, b)
2184
           local r = foo(a+1)
2185
           print("co-body", r)
2186
           local r, s = coroutine.yield(a+b, a-b)
2187
           print("co-body", r, s)
2188
           return b, "end"
2189
     end)
2190
 
2191
     print("main", coroutine.resume(co, 1, 10))
2192
     print("main", coroutine.resume(co, "r"))
2193
     print("main", coroutine.resume(co, "x", "y"))
2194
     print("main", coroutine.resume(co, "x", "y"))
2195
</pre><p>
2196
When you run it, it produces the following output:
2197
 
2198
<pre>
2199
     co-body 1       10
2200
     foo     2
2201
     main    true    4
2202
     co-body r
2203
     main    true    11      -9
2204
     co-body x       y
2205
     main    true    10      end
2206
     main    false   cannot resume dead coroutine
2207
</pre>
2208
 
2209
 
2210
 
2211
 
2212
<h1>3 - <a name="3">The Application Program Interface</a></h1>
2213
 
2214
<p>
2215
 
2216
This section describes the C&nbsp;API for Lua, that is,
2217
the set of C&nbsp;functions available to the host program to communicate
2218
with Lua.
2219
All API functions and related types and constants
2220
are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>.
2221
 
2222
 
2223
<p>
2224
Even when we use the term "function",
2225
any facility in the API may be provided as a macro instead.
2226
All such macros use each of their arguments exactly once
2227
(except for the first argument, which is always a Lua state),
2228
and so do not generate any hidden side-effects.
2229
 
2230
 
2231
<p>
2232
As in most C&nbsp;libraries,
2233
the Lua API functions do not check their arguments for validity or consistency.
2234
However, you can change this behavior by compiling Lua
2235
with a proper definition for the macro <a name="pdf-luai_apicheck"><code>luai_apicheck</code></a>,
2236
in file <code>luaconf.h</code>.
2237
 
2238
 
2239
 
2240
<h2>3.1 - <a name="3.1">The Stack</a></h2>
2241
 
2242
<p>
2243
Lua uses a <em>virtual stack</em> to pass values to and from C.
2244
Each element in this stack represents a Lua value
2245
(<b>nil</b>, number, string, etc.).
2246
 
2247
 
2248
<p>
2249
Whenever Lua calls C, the called function gets a new stack,
2250
which is independent of previous stacks and of stacks of
2251
C&nbsp;functions that are still active.
2252
This stack initially contains any arguments to the C&nbsp;function
2253
and it is where the C&nbsp;function pushes its results
2254
to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
2255
 
2256
 
2257
<p>
2258
For convenience,
2259
most query operations in the API do not follow a strict stack discipline.
2260
Instead, they can refer to any element in the stack
2261
by using an <em>index</em>:
2262
A positive index represents an <em>absolute</em> stack position
2263
(starting at&nbsp;1);
2264
a negative index represents an <em>offset</em> relative to the top of the stack.
2265
More specifically, if the stack has <em>n</em> elements,
2266
then index&nbsp;1 represents the first element
2267
(that is, the element that was pushed onto the stack first)
2268
and
2269
index&nbsp;<em>n</em> represents the last element;
2270
index&nbsp;-1 also represents the last element
2271
(that is, the element at the top)
2272
and index <em>-n</em> represents the first element.
2273
We say that an index is <em>valid</em>
2274
if it lies between&nbsp;1 and the stack top
2275
(that is, if <code>1 &le; abs(index) &le; top</code>).
2276
 
2277
 
2278
 
2279
 
2280
 
2281
 
2282
<h2>3.2 - <a name="3.2">Stack Size</a></h2>
2283
 
2284
<p>
2285
When you interact with Lua API,
2286
you are responsible for ensuring consistency.
2287
In particular,
2288
<em>you are responsible for controlling stack overflow</em>.
2289
You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2290
to grow the stack size.
2291
 
2292
 
2293
<p>
2294
Whenever Lua calls C,
2295
it ensures that at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> stack positions are available.
2296
<code>LUA_MINSTACK</code> is defined as 20,
2297
so that usually you do not have to worry about stack space
2298
unless your code has loops pushing elements onto the stack.
2299
 
2300
 
2301
<p>
2302
Most query functions accept as indices any value inside the
2303
available stack space, that is, indices up to the maximum stack size
2304
you have set through <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
2305
Such indices are called <em>acceptable indices</em>.
2306
More formally, we define an <em>acceptable index</em>
2307
as follows:
2308
 
2309
<pre>
2310
     (index &lt; 0 &amp;&amp; abs(index) &lt;= top) ||
2311
     (index &gt; 0 &amp;&amp; index &lt;= stackspace)
2312
</pre><p>
2313
Note that 0 is never an acceptable index.
2314
 
2315
 
2316
 
2317
 
2318
 
2319
<h2>3.3 - <a name="3.3">Pseudo-Indices</a></h2>
2320
 
2321
<p>
2322
Unless otherwise noted,
2323
any function that accepts valid indices can also be called with
2324
<em>pseudo-indices</em>,
2325
which represent some Lua values that are accessible to C&nbsp;code
2326
but which are not in the stack.
2327
Pseudo-indices are used to access the thread environment,
2328
the function environment,
2329
the registry,
2330
and the upvalues of a C&nbsp;function (see <a href="#3.4">&sect;3.4</a>).
2331
 
2332
 
2333
<p>
2334
The thread environment (where global variables live) is
2335
always at pseudo-index <a name="pdf-LUA_GLOBALSINDEX"><code>LUA_GLOBALSINDEX</code></a>.
2336
The environment of the running C&nbsp;function is always
2337
at pseudo-index <a name="pdf-LUA_ENVIRONINDEX"><code>LUA_ENVIRONINDEX</code></a>.
2338
 
2339
 
2340
<p>
2341
To access and change the value of global variables,
2342
you can use regular table operations over an environment table.
2343
For instance, to access the value of a global variable, do
2344
 
2345
<pre>
2346
     lua_getfield(L, LUA_GLOBALSINDEX, varname);
2347
</pre>
2348
 
2349
 
2350
 
2351
 
2352
<h2>3.4 - <a name="3.4">C Closures</a></h2>
2353
 
2354
<p>
2355
When a C&nbsp;function is created,
2356
it is possible to associate some values with it,
2357
thus creating a <em>C&nbsp;closure</em>;
2358
these values are called <em>upvalues</em> and are
2359
accessible to the function whenever it is called
2360
(see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>).
2361
 
2362
 
2363
<p>
2364
Whenever a C&nbsp;function is called,
2365
its upvalues are located at specific pseudo-indices.
2366
These pseudo-indices are produced by the macro
2367
<a name="lua_upvalueindex"><code>lua_upvalueindex</code></a>.
2368
The first value associated with a function is at position
2369
<code>lua_upvalueindex(1)</code>, and so on.
2370
Any access to <code>lua_upvalueindex(<em>n</em>)</code>,
2371
where <em>n</em> is greater than the number of upvalues of the
2372
current function,
2373
produces an acceptable (but invalid) index.
2374
 
2375
 
2376
 
2377
 
2378
 
2379
<h2>3.5 - <a name="3.5">Registry</a></h2>
2380
 
2381
<p>
2382
Lua provides a <em>registry</em>,
2383
a pre-defined table that can be used by any C&nbsp;code to
2384
store whatever Lua value it needs to store.
2385
This table is always located at pseudo-index
2386
<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>.
2387
Any C&nbsp;library can store data into this table,
2388
but it should take care to choose keys different from those used
2389
by other libraries, to avoid collisions.
2390
Typically, you should use as key a string containing your library name
2391
or a light userdata with the address of a C&nbsp;object in your code.
2392
 
2393
 
2394
<p>
2395
The integer keys in the registry are used by the reference mechanism,
2396
implemented by the auxiliary library,
2397
and therefore should not be used for other purposes.
2398
 
2399
 
2400
 
2401
 
2402
 
2403
<h2>3.6 - <a name="3.6">Error Handling in C</a></h2>
2404
 
2405
<p>
2406
Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2407
(You can also choose to use exceptions if you use C++;
2408
see file <code>luaconf.h</code>.)
2409
When Lua faces any error
2410
(such as memory allocation errors, type errors, syntax errors,
2411
and runtime errors)
2412
it <em>raises</em> an error;
2413
that is, it does a long jump.
2414
A <em>protected environment</em> uses <code>setjmp</code>
2415
to set a recover point;
2416
any error jumps to the most recent active recover point.
2417
 
2418
 
2419
<p>
2420
Almost any function in the API may raise an error,
2421
for instance due to a memory allocation error.
2422
The following functions run in protected mode
2423
(that is, they create a protected environment to run),
2424
so they never raise an error:
2425
<a href="#lua_newstate"><code>lua_newstate</code></a>, <a href="#lua_close"><code>lua_close</code></a>, <a href="#lua_load"><code>lua_load</code></a>,
2426
<a href="#lua_pcall"><code>lua_pcall</code></a>, and <a href="#lua_cpcall"><code>lua_cpcall</code></a>.
2427
 
2428
 
2429
<p>
2430
Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2431
 
2432
 
2433
 
2434
 
2435
 
2436
<h2>3.7 - <a name="3.7">Functions and Types</a></h2>
2437
 
2438
<p>
2439
Here we list all functions and types from the C&nbsp;API in
2440
alphabetical order.
2441
 
2442
 
2443
 
2444
<hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3>
2445
<pre>typedef void * (*lua_Alloc) (void *ud,
2446
                             void *ptr,
2447
                             size_t osize,
2448
                             size_t nsize);</pre>
2449
 
2450
<p>
2451
The type of the memory-allocation function used by Lua states.
2452
The allocator function must provide a
2453
functionality similar to <code>realloc</code>,
2454
but not exactly the same.
2455
Its arguments are
2456
<code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>;
2457
<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
2458
<code>osize</code>, the original size of the block;
2459
<code>nsize</code>, the new size of the block.
2460
<code>ptr</code> is <code>NULL</code> if and only if <code>osize</code> is zero.
2461
When <code>nsize</code> is zero, the allocator must return <code>NULL</code>;
2462
if <code>osize</code> is not zero,
2463
it should free the block pointed to by <code>ptr</code>.
2464
When <code>nsize</code> is not zero, the allocator returns <code>NULL</code>
2465
if and only if it cannot fill the request.
2466
When <code>nsize</code> is not zero and <code>osize</code> is zero,
2467
the allocator should behave like <code>malloc</code>.
2468
When <code>nsize</code> and <code>osize</code> are not zero,
2469
the allocator behaves like <code>realloc</code>.
2470
Lua assumes that the allocator never fails when
2471
<code>osize &gt;= nsize</code>.
2472
 
2473
 
2474
<p>
2475
Here is a simple implementation for the allocator function.
2476
It is used in the auxiliary library by <a href="#lua_newstate"><code>lua_newstate</code></a>.
2477
 
2478
<pre>
2479
     static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
2480
       (void)ud;     /* not used */
2481
       (void)osize;  /* not used */
2482
       if (nsize == 0) {
2483
         free(ptr);  /* ANSI requires that free(NULL) has no effect */
2484
         return NULL;
2485
       }
2486
       else
2487
         /* ANSI requires that realloc(NULL, size) == malloc(size) */
2488
         return realloc(ptr, nsize);
2489
     }
2490
</pre>
2491
 
2492
 
2493
 
2494
 
2495
<hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3>
2496
<pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre>
2497
 
2498
<p>
2499
Sets a new panic function and returns the old one.
2500
 
2501
 
2502
<p>
2503
If an error happens outside any protected environment,
2504
Lua calls a <em>panic function</em>
2505
and then calls <code>exit(EXIT_FAILURE)</code>,
2506
thus exiting the host application.
2507
Your panic function may avoid this exit by
2508
never returning (e.g., doing a long jump).
2509
 
2510
 
2511
<p>
2512
The panic function can access the error message at the top of the stack.
2513
 
2514
 
2515
 
2516
 
2517
 
2518
<hr><h3><a name="lua_call"><code>lua_call</code></a></h3>
2519
<pre>void lua_call (lua_State *L, int nargs, int nresults);</pre>
2520
 
2521
<p>
2522
Calls a function.
2523
 
2524
 
2525
<p>
2526
To call a function you must use the following protocol:
2527
first, the function to be called is pushed onto the stack;
2528
then, the arguments to the function are pushed
2529
in direct order;
2530
that is, the first argument is pushed first.
2531
Finally you call <a href="#lua_call"><code>lua_call</code></a>;
2532
<code>nargs</code> is the number of arguments that you pushed onto the stack.
2533
All arguments and the function value are popped from the stack
2534
when the function is called.
2535
The function results are pushed onto the stack when the function returns.
2536
The number of results is adjusted to <code>nresults</code>,
2537
unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>.
2538
In this case, <em>all</em> results from the function are pushed.
2539
Lua takes care that the returned values fit into the stack space.
2540
The function results are pushed onto the stack in direct order
2541
(the first result is pushed first),
2542
so that after the call the last result is on the top of the stack.
2543
 
2544
 
2545
<p>
2546
Any error inside the called function is propagated upwards
2547
(with a <code>longjmp</code>).
2548
 
2549
 
2550
<p>
2551
The following example shows how the host program may do the
2552
equivalent to this Lua code:
2553
 
2554
<pre>
2555
     a = f("how", t.x, 14)
2556
</pre><p>
2557
Here it is in&nbsp;C:
2558
 
2559
<pre>
2560
     lua_getfield(L, LUA_GLOBALSINDEX, "f");          /* function to be called */
2561
     lua_pushstring(L, "how");                                 /* 1st argument */
2562
     lua_getfield(L, LUA_GLOBALSINDEX, "t");            /* table to be indexed */
2563
     lua_getfield(L, -1, "x");                 /* push result of t.x (2nd arg) */
2564
     lua_remove(L, -2);                           /* remove 't' from the stack */
2565
     lua_pushinteger(L, 14);                                   /* 3rd argument */
2566
     lua_call(L, 3, 1);         /* call function with 3 arguments and 1 result */
2567
     lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global variable 'a' */
2568
</pre><p>
2569
Note that the code above is "balanced":
2570
at its end, the stack is back to its original configuration.
2571
This is considered good programming practice.
2572
 
2573
 
2574
 
2575
 
2576
 
2577
<hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3>
2578
<pre>typedef int (*lua_CFunction) (lua_State *L);</pre>
2579
 
2580
<p>
2581
Type for C&nbsp;functions.
2582
 
2583
 
2584
<p>
2585
In order to communicate properly with Lua,
2586
a C&nbsp;function must use the following protocol,
2587
which defines the way parameters and results are passed:
2588
a C&nbsp;function receives its arguments from Lua in its stack
2589
in direct order (the first argument is pushed first).
2590
So, when the function starts,
2591
<code>lua_gettop(L)</code> returns the number of arguments received by the function.
2592
The first argument (if any) is at index 1
2593
and its last argument is at index <code>lua_gettop(L)</code>.
2594
To return values to Lua, a C&nbsp;function just pushes them onto the stack,
2595
in direct order (the first result is pushed first),
2596
and returns the number of results.
2597
Any other value in the stack below the results will be properly
2598
discarded by Lua.
2599
Like a Lua function, a C&nbsp;function called by Lua can also return
2600
many results.
2601
 
2602
 
2603
<p>
2604
As an example, the following function receives a variable number
2605
of numerical arguments and returns their average and sum:
2606
 
2607
<pre>
2608
     static int foo (lua_State *L) {
2609
       int n = lua_gettop(L);    /* number of arguments */
2610
       lua_Number sum = 0;
2611
       int i;
2612
       for (i = 1; i &lt;= n; i++) {
2613
         if (!lua_isnumber(L, i)) {
2614
           lua_pushstring(L, "incorrect argument to function 'average'");
2615
           lua_error(L);
2616
         }
2617
         sum += lua_tonumber(L, i);
2618
       }
2619
       lua_pushnumber(L, sum/n);        /* first result */
2620
       lua_pushnumber(L, sum);         /* second result */
2621
       return 2;                   /* number of results */
2622
     }
2623
</pre>
2624
 
2625
 
2626
 
2627
 
2628
<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3>
2629
<pre>int lua_checkstack (lua_State *L, int extra);</pre>
2630
 
2631
<p>
2632
Ensures that there are at least <code>extra</code> free stack slots in the stack.
2633
It returns false if it cannot grow the stack to that size.
2634
This function never shrinks the stack;
2635
if the stack is already larger than the new size,
2636
it is left unchanged.
2637
 
2638
 
2639
 
2640
 
2641
 
2642
<hr><h3><a name="lua_close"><code>lua_close</code></a></h3>
2643
<pre>void lua_close (lua_State *L);</pre>
2644
 
2645
<p>
2646
Destroys all objects in the given Lua state
2647
(calling the corresponding garbage-collection metamethods, if any)
2648
and frees all dynamic memory used by this state.
2649
On several platforms, you may not need to call this function,
2650
because all resources are naturally released when the host program ends.
2651
On the other hand, long-running programs,
2652
such as a daemon or a web server,
2653
might need to release states as soon as they are not needed,
2654
to avoid growing too large.
2655
 
2656
 
2657
 
2658
 
2659
 
2660
<hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3>
2661
<pre>void lua_concat (lua_State *L, int n);</pre>
2662
 
2663
<p>
2664
Concatenates the <code>n</code> values at the top of the stack,
2665
pops them, and leaves the result at the top.
2666
If <code>n</code>&nbsp;is&nbsp;1, the result is the single string on the stack
2667
(that is, the function does nothing);
2668
if <code>n</code> is 0, the result is the empty string.
2669
Concatenation is done following the usual semantics of Lua
2670
(see <a href="#2.5.4">&sect;2.5.4</a>).
2671
 
2672
 
2673
 
2674
 
2675
 
2676
<hr><h3><a name="lua_cpcall"><code>lua_cpcall</code></a></h3>
2677
<pre>int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);</pre>
2678
 
2679
<p>
2680
Calls the C&nbsp;function <code>func</code> in protected mode.
2681
<code>func</code> starts with only one element in its stack,
2682
a light userdata containing <code>ud</code>.
2683
In case of errors,
2684
<a href="#lua_cpcall"><code>lua_cpcall</code></a> returns the same error codes as <a href="#lua_pcall"><code>lua_pcall</code></a>,
2685
plus the error object on the top of the stack;
2686
otherwise, it returns zero, and does not change the stack.
2687
All values returned by <code>func</code> are discarded.
2688
 
2689
 
2690
 
2691
 
2692
 
2693
<hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3>
2694
<pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre>
2695
 
2696
<p>
2697
Creates a new empty table and pushes it onto the stack.
2698
The new table has space pre-allocated
2699
for <code>narr</code> array elements and <code>nrec</code> non-array elements.
2700
This pre-allocation is useful when you know exactly how many elements
2701
the table will have.
2702
Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>.
2703
 
2704
 
2705
 
2706
 
2707
 
2708
<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3>
2709
<pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
2710
 
2711
<p>
2712
Dumps a function as a binary chunk.
2713
Receives a Lua function on the top of the stack
2714
and produces a binary chunk that,
2715
if loaded again,
2716
results in a function equivalent to the one dumped.
2717
As it produces parts of the chunk,
2718
<a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>)
2719
with the given <code>data</code>
2720
to write them.
2721
 
2722
 
2723
<p>
2724
The value returned is the error code returned by the last
2725
call to the writer;
2726
 
2727
 
2728
 
2729
<p>
2730
This function does not pop the Lua function from the stack.
2731
 
2732
 
2733
 
2734
 
2735
 
2736
<hr><h3><a name="lua_equal"><code>lua_equal</code></a></h3>
2737
<pre>int lua_equal (lua_State *L, int index1, int index2);</pre>
2738
 
2739
<p>
2740
Returns 1 if the two values in acceptable indices <code>index1</code> and
2741
<code>index2</code> are equal,
2742
following the semantics of the Lua <code>==</code> operator
2743
(that is, may call metamethods).
2744
Otherwise returns&nbsp;0.
2745
Also returns&nbsp;0 if any of the indices is non valid.
2746
 
2747
 
2748
 
2749
 
2750
 
2751
<hr><h3><a name="lua_error"><code>lua_error</code></a></h3>
2752
<pre>int lua_error (lua_State *L);</pre>
2753
 
2754
<p>
2755
Generates a Lua error.
2756
The error message (which can actually be a Lua value of any type)
2757
must be on the stack top.
2758
This function does a long jump,
2759
and therefore never returns.
2760
(see <a href="#luaL_error"><code>luaL_error</code></a>).
2761
 
2762
 
2763
 
2764
 
2765
 
2766
<hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3>
2767
<pre>int lua_gc (lua_State *L, int what, int data);</pre>
2768
 
2769
<p>
2770
Controls the garbage collector.
2771
 
2772
 
2773
<p>
2774
This function performs several tasks,
2775
according to the value of the parameter <code>what</code>:
2776
 
2777
<ul>
2778
 
2779
<li><b><code>LUA_GCSTOP</code>:</b>
2780
stops the garbage collector.
2781
</li>
2782
 
2783
<li><b><code>LUA_GCRESTART</code>:</b>
2784
restarts the garbage collector.
2785
</li>
2786
 
2787
<li><b><code>LUA_GCCOLLECT</code>:</b>
2788
performs a full garbage-collection cycle.
2789
</li>
2790
 
2791
<li><b><code>LUA_GCCOUNT</code>:</b>
2792
returns the current amount of memory (in Kbytes) in use by Lua.
2793
</li>
2794
 
2795
<li><b><code>LUA_GCCOUNTB</code>:</b>
2796
returns the remainder of dividing the current amount of bytes of
2797
memory in use by Lua by 1024.
2798
</li>
2799
 
2800
<li><b><code>LUA_GCSTEP</code>:</b>
2801
performs an incremental step of garbage collection.
2802
The step "size" is controlled by <code>data</code>
2803
(larger values mean more steps) in a non-specified way.
2804
If you want to control the step size
2805
you must experimentally tune the value of <code>data</code>.
2806
The function returns 1 if the step finished a
2807
garbage-collection cycle.
2808
</li>
2809
 
2810
<li><b><code>LUA_GCSETPAUSE</code>:</b>
2811
sets <code>data</code>/100 as the new value
2812
for the <em>pause</em> of the collector (see <a href="#2.10">&sect;2.10</a>).
2813
The function returns the previous value of the pause.
2814
</li>
2815
 
2816
<li><b><code>LUA_GCSETSTEPMUL</code>:</b>
2817
sets <code>arg</code>/100 as the new value for the <em>step multiplier</em> of
2818
the collector (see <a href="#2.10">&sect;2.10</a>).
2819
The function returns the previous value of the step multiplier.
2820
</li>
2821
 
2822
</ul>
2823
 
2824
 
2825
 
2826
 
2827
<hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3>
2828
<pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre>
2829
 
2830
<p>
2831
Returns the memory-allocation function of a given state.
2832
If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
2833
opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
2834
 
2835
 
2836
 
2837
 
2838
 
2839
<hr><h3><a name="lua_getfenv"><code>lua_getfenv</code></a></h3>
2840
<pre>void lua_getfenv (lua_State *L, int index);</pre>
2841
 
2842
<p>
2843
Pushes onto the stack the environment table of
2844
the value at the given index.
2845
 
2846
 
2847
 
2848
 
2849
 
2850
<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3>
2851
<pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
2852
 
2853
<p>
2854
Pushes onto the stack the value <code>t[k]</code>,
2855
where <code>t</code> is the value at the given valid index <code>index</code>.
2856
As in Lua, this function may trigger a metamethod
2857
for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2858
 
2859
 
2860
 
2861
 
2862
 
2863
<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3>
2864
<pre>void lua_getglobal (lua_State *L, const char *name);</pre>
2865
 
2866
<p>
2867
Pushes onto the stack the value of the global <code>name</code>.
2868
It is defined as a macro:
2869
 
2870
<pre>
2871
     #define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, s)
2872
</pre>
2873
 
2874
 
2875
 
2876
 
2877
<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3>
2878
<pre>int lua_getmetatable (lua_State *L, int index);</pre>
2879
 
2880
<p>
2881
Pushes onto the stack the metatable of the value at the given
2882
acceptable index.
2883
If the index is not valid,
2884
or if the value does not have a metatable,
2885
the function returns&nbsp;0 and pushes nothing on the stack.
2886
 
2887
 
2888
 
2889
 
2890
 
2891
<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3>
2892
<pre>void lua_gettable (lua_State *L, int index);</pre>
2893
 
2894
<p>
2895
Pushes onto the stack the value <code>t[k]</code>,
2896
where <code>t</code> is the value at the given valid index <code>index</code>
2897
and <code>k</code> is the value at the top of the stack.
2898
 
2899
 
2900
<p>
2901
This function pops the key from the stack
2902
(putting the resulting value in its place).
2903
As in Lua, this function may trigger a metamethod
2904
for the "index" event (see <a href="#2.8">&sect;2.8</a>).
2905
 
2906
 
2907
 
2908
 
2909
 
2910
<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3>
2911
<pre>int lua_gettop (lua_State *L);</pre>
2912
 
2913
<p>
2914
Returns the index of the top element in the stack.
2915
Because indices start at&nbsp;1,
2916
this result is equal to the number of elements in the stack
2917
(and so 0&nbsp;means an empty stack).
2918
 
2919
 
2920
 
2921
 
2922
 
2923
<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3>
2924
<pre>void lua_insert (lua_State *L, int index);</pre>
2925
 
2926
<p>
2927
Moves the top element into the given valid index,
2928
shifting up the elements above this index to open space.
2929
Cannot be called with a pseudo-index,
2930
because a pseudo-index is not an actual stack position.
2931
 
2932
 
2933
 
2934
 
2935
 
2936
<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
2937
<pre>typedef ptrdiff_t lua_Integer;</pre>
2938
 
2939
<p>
2940
The type used by the Lua API to represent integral values.
2941
 
2942
 
2943
<p>
2944
By default it is a <code>ptrdiff_t</code>,
2945
which is usually the largest integral type the machine handles
2946
"comfortably".
2947
 
2948
 
2949
 
2950
 
2951
 
2952
<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3>
2953
<pre>int lua_isboolean (lua_State *L, int index);</pre>
2954
 
2955
<p>
2956
Returns 1 if the value at the given acceptable index has type boolean,
2957
and 0 otherwise.
2958
 
2959
 
2960
 
2961
 
2962
 
2963
<hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3>
2964
<pre>int lua_iscfunction (lua_State *L, int index);</pre>
2965
 
2966
<p>
2967
Returns 1 if the value at the given acceptable index is a C&nbsp;function,
2968
and 0 otherwise.
2969
 
2970
 
2971
 
2972
 
2973
 
2974
<hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3>
2975
<pre>int lua_isfunction (lua_State *L, int index);</pre>
2976
 
2977
<p>
2978
Returns 1 if the value at the given acceptable index is a function
2979
(either C or Lua), and 0 otherwise.
2980
 
2981
 
2982
 
2983
 
2984
 
2985
<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3>
2986
<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
2987
 
2988
<p>
2989
Returns 1 if the value at the given acceptable index is a light userdata,
2990
and 0 otherwise.
2991
 
2992
 
2993
 
2994
 
2995
 
2996
<hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3>
2997
<pre>int lua_isnil (lua_State *L, int index);</pre>
2998
 
2999
<p>
3000
Returns 1 if the value at the given acceptable index is <b>nil</b>,
3001
and 0 otherwise.
3002
 
3003
 
3004
 
3005
 
3006
 
3007
<hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3>
3008
<pre>int lua_isnumber (lua_State *L, int index);</pre>
3009
 
3010
<p>
3011
Returns 1 if the value at the given acceptable index is a number
3012
or a string convertible to a number,
3013
and 0 otherwise.
3014
 
3015
 
3016
 
3017
 
3018
 
3019
<hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3>
3020
<pre>int lua_isstring (lua_State *L, int index);</pre>
3021
 
3022
<p>
3023
Returns 1 if the value at the given acceptable index is a string
3024
or a number (which is always convertible to a string),
3025
and 0 otherwise.
3026
 
3027
 
3028
 
3029
 
3030
 
3031
<hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3>
3032
<pre>int lua_istable (lua_State *L, int index);</pre>
3033
 
3034
<p>
3035
Returns 1 if the value at the given acceptable index is a table,
3036
and 0 otherwise.
3037
 
3038
 
3039
 
3040
 
3041
 
3042
<hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3>
3043
<pre>int lua_isthread (lua_State *L, int index);</pre>
3044
 
3045
<p>
3046
Returns 1 if the value at the given acceptable index is a thread,
3047
and 0 otherwise.
3048
 
3049
 
3050
 
3051
 
3052
 
3053
<hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3>
3054
<pre>int lua_isuserdata (lua_State *L, int index);</pre>
3055
 
3056
<p>
3057
Returns 1 if the value at the given acceptable index is a userdata
3058
(either full or light), and 0 otherwise.
3059
 
3060
 
3061
 
3062
 
3063
 
3064
<hr><h3><a name="lua_lessthan"><code>lua_lessthan</code></a></h3>
3065
<pre>int lua_lessthan (lua_State *L, int index1, int index2);</pre>
3066
 
3067
<p>
3068
Returns 1 if the value at acceptable index <code>index1</code> is smaller
3069
than the value at acceptable index <code>index2</code>,
3070
following the semantics of the Lua <code>&lt;</code> operator
3071
(that is, may call metamethods).
3072
Otherwise returns&nbsp;0.
3073
Also returns&nbsp;0 if any of the indices is non valid.
3074
 
3075
 
3076
 
3077
 
3078
 
3079
<hr><h3><a name="lua_load"><code>lua_load</code></a></h3>
3080
<pre>int lua_load (lua_State *L,
3081
              lua_Reader reader,
3082
              void *data,
3083
              const char *chunkname);</pre>
3084
 
3085
<p>
3086
Loads a Lua chunk.
3087
If there are no errors,
3088
<a href="#lua_load"><code>lua_load</code></a> pushes the compiled chunk as a Lua
3089
function on top of the stack.
3090
Otherwise, it pushes an error message.
3091
The return values of <a href="#lua_load"><code>lua_load</code></a> are:
3092
 
3093
<ul>
3094
 
3095
<li><b>0:</b> no errors;</li>
3096
 
3097
<li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>:</b>
3098
syntax error during pre-compilation;</li>
3099
 
3100
<li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3101
memory allocation error.</li>
3102
 
3103
</ul>
3104
 
3105
<p>
3106
This function only loads a chunk;
3107
it does not run it.
3108
 
3109
 
3110
<p>
3111
<a href="#lua_load"><code>lua_load</code></a> automatically detects whether the chunk is text or binary,
3112
and loads it accordingly (see program <code>luac</code>).
3113
 
3114
 
3115
<p>
3116
<a href="#lua_load"><code>lua_load</code></a> uses a user-supplied <code>reader</code> function to read the chunk
3117
(see <a href="#lua_Reader"><code>lua_Reader</code></a>).
3118
The <code>data</code> argument is an opaque value passed to the reader function.
3119
 
3120
 
3121
<p>
3122
The <code>chunkname</code> argument gives a name to the chunk,
3123
which is used for error messages and in debug information (see <a href="#3.8">&sect;3.8</a>).
3124
 
3125
 
3126
 
3127
 
3128
 
3129
<hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3>
3130
<pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre>
3131
 
3132
<p>
3133
Creates a new, independent state.
3134
Returns <code>NULL</code> if cannot create the state
3135
(due to lack of memory).
3136
The argument <code>f</code> is the allocator function;
3137
Lua does all memory allocation for this state through this function.
3138
The second argument, <code>ud</code>, is an opaque pointer that Lua
3139
simply passes to the allocator in every call.
3140
 
3141
 
3142
 
3143
 
3144
 
3145
<hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3>
3146
<pre>void lua_newtable (lua_State *L);</pre>
3147
 
3148
<p>
3149
Creates a new empty table and pushes it onto the stack.
3150
It is equivalent to <code>lua_createtable(L, 0, 0)</code>.
3151
 
3152
 
3153
 
3154
 
3155
 
3156
<hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3>
3157
<pre>lua_State *lua_newthread (lua_State *L);</pre>
3158
 
3159
<p>
3160
Creates a new thread, pushes it on the stack,
3161
and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread.
3162
The new state returned by this function shares with the original state
3163
all global objects (such as tables),
3164
but has an independent execution stack.
3165
 
3166
 
3167
<p>
3168
There is no explicit function to close or to destroy a thread.
3169
Threads are subject to garbage collection,
3170
like any Lua object.
3171
 
3172
 
3173
 
3174
 
3175
 
3176
<hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3>
3177
<pre>void *lua_newuserdata (lua_State *L, size_t size);</pre>
3178
 
3179
<p>
3180
This function allocates a new block of memory with the given size,
3181
pushes onto the stack a new full userdata with the block address,
3182
and returns this address.
3183
 
3184
 
3185
<p>
3186
Userdata represents C&nbsp;values in Lua.
3187
A <em>full userdata</em> represents a block of memory.
3188
It is an object (like a table):
3189
you must create it, it can have its own metatable,
3190
and you can detect when it is being collected.
3191
A full userdata is only equal to itself (under raw equality).
3192
 
3193
 
3194
<p>
3195
When Lua collects a full userdata with a <code>gc</code> metamethod,
3196
Lua calls the metamethod and marks the userdata as finalized.
3197
When this userdata is collected again then
3198
Lua frees its corresponding memory.
3199
 
3200
 
3201
 
3202
 
3203
 
3204
<hr><h3><a name="lua_next"><code>lua_next</code></a></h3>
3205
<pre>int lua_next (lua_State *L, int index);</pre>
3206
 
3207
<p>
3208
Pops a key from the stack,
3209
and pushes a key-value pair from the table at the given index
3210
(the "next" pair after the given key).
3211
If there are no more elements in the table,
3212
then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing).
3213
 
3214
 
3215
<p>
3216
A typical traversal looks like this:
3217
 
3218
<pre>
3219
     /* table is in the stack at index 't' */
3220
     lua_pushnil(L);  /* first key */
3221
     while (lua_next(L, t) != 0) {
3222
       /* 'key' is at index -2 and 'value' at index -1 */
3223
       printf("%s - %s\n",
3224
         lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1)));
3225
       lua_pop(L, 1);  /* removes 'value'; keeps 'key' for next iteration */
3226
     }
3227
</pre>
3228
 
3229
<p>
3230
While traversing a table,
3231
do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key,
3232
unless you know that the key is actually a string.
3233
Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> <em>changes</em>
3234
the value at the given index;
3235
this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>.
3236
 
3237
 
3238
 
3239
 
3240
 
3241
<hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3>
3242
<pre>typedef double lua_Number;</pre>
3243
 
3244
<p>
3245
The type of numbers in Lua.
3246
By default, it is double, but that can be changed in <code>luaconf.h</code>.
3247
 
3248
 
3249
<p>
3250
Through the configuration file you can change
3251
Lua to operate with another type for numbers (e.g., float or long).
3252
 
3253
 
3254
 
3255
 
3256
 
3257
<hr><h3><a name="lua_objlen"><code>lua_objlen</code></a></h3>
3258
<pre>size_t lua_objlen (lua_State *L, int index);</pre>
3259
 
3260
<p>
3261
Returns the "length" of the value at the given acceptable index:
3262
for strings, this is the string length;
3263
for tables, this is the result of the length operator ('<code>#</code>');
3264
for userdata, this is the size of the block of memory allocated
3265
for the userdata;
3266
for other values, it is&nbsp;0.
3267
 
3268
 
3269
 
3270
 
3271
 
3272
<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3>
3273
<pre>lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);</pre>
3274
 
3275
<p>
3276
Calls a function in protected mode.
3277
 
3278
 
3279
<p>
3280
Both <code>nargs</code> and <code>nresults</code> have the same meaning as
3281
in <a href="#lua_call"><code>lua_call</code></a>.
3282
If there are no errors during the call,
3283
<a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>.
3284
However, if there is any error,
3285
<a href="#lua_pcall"><code>lua_pcall</code></a> catches it,
3286
pushes a single value on the stack (the error message),
3287
and returns an error code.
3288
Like <a href="#lua_call"><code>lua_call</code></a>,
3289
<a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function
3290
and its arguments from the stack.
3291
 
3292
 
3293
<p>
3294
If <code>errfunc</code> is 0,
3295
then the error message returned on the stack
3296
is exactly the original error message.
3297
Otherwise, <code>errfunc</code> is the stack index of an
3298
<em>error handler function</em>.
3299
(In the current implementation, this index cannot be a pseudo-index.)
3300
In case of runtime errors,
3301
this function will be called with the error message
3302
and its return value will be the message returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>.
3303
 
3304
 
3305
<p>
3306
Typically, the error handler function is used to add more debug
3307
information to the error message, such as a stack traceback.
3308
Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>,
3309
since by then the stack has unwound.
3310
 
3311
 
3312
<p>
3313
The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns 0 in case of success
3314
or one of the following error codes
3315
(defined in <code>lua.h</code>):
3316
 
3317
<ul>
3318
 
3319
<li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>:</b>
3320
a runtime error.
3321
</li>
3322
 
3323
<li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>:</b>
3324
memory allocation error.
3325
For such errors, Lua does not call the error handler function.
3326
</li>
3327
 
3328
<li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>:</b>
3329
error while running the error handler function.
3330
</li>
3331
 
3332
</ul>
3333
 
3334
 
3335
 
3336
 
3337
<hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3>
3338
<pre>void lua_pop (lua_State *L, int n);</pre>
3339
 
3340
<p>
3341
Pops <code>n</code> elements from the stack.
3342
 
3343
 
3344
 
3345
 
3346
 
3347
<hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3>
3348
<pre>void lua_pushboolean (lua_State *L, int b);</pre>
3349
 
3350
<p>
3351
Pushes a boolean value with value <code>b</code> onto the stack.
3352
 
3353
 
3354
 
3355
 
3356
 
3357
<hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3>
3358
<pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre>
3359
 
3360
<p>
3361
Pushes a new C&nbsp;closure onto the stack.
3362
 
3363
 
3364
<p>
3365
When a C&nbsp;function is created,
3366
it is possible to associate some values with it,
3367
thus creating a C&nbsp;closure (see <a href="#3.4">&sect;3.4</a>);
3368
these values are then accessible to the function whenever it is called.
3369
To associate values with a C&nbsp;function,
3370
first these values should be pushed onto the stack
3371
(when there are multiple values, the first value is pushed first).
3372
Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
3373
is called to create and push the C&nbsp;function onto the stack,
3374
with the argument <code>n</code> telling how many values should be
3375
associated with the function.
3376
<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
3377
 
3378
 
3379
 
3380
 
3381
 
3382
<hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3>
3383
<pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre>
3384
 
3385
<p>
3386
Pushes a C&nbsp;function onto the stack.
3387
This function receives a pointer to a C function
3388
and pushes onto the stack a Lua value of type <code>function</code> that,
3389
when called, invokes the corresponding C&nbsp;function.
3390
 
3391
 
3392
<p>
3393
Any function to be registered in Lua must
3394
follow the correct protocol to receive its parameters
3395
and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>).
3396
 
3397
 
3398
<p>
3399
The call <code>lua_pushcfunction(L, f)</code> is equivalent to
3400
<code>lua_pushcclosure(L, f, 0)</code>.
3401
 
3402
 
3403
 
3404
 
3405
 
3406
<hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3>
3407
<pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre>
3408
 
3409
<p>
3410
Pushes onto the stack a formatted string
3411
and returns a pointer to this string.
3412
It is similar to the C&nbsp;function <code>sprintf</code>,
3413
but has some important differences:
3414
 
3415
<ul>
3416
 
3417
<li>
3418
You do not have to allocate space for the result:
3419
the result is a Lua string and Lua takes care of memory allocation
3420
(and deallocation, through garbage collection).
3421
</li>
3422
 
3423
<li>
3424
The conversion specifiers are quite restricted.
3425
There are no flags, widths, or precisions.
3426
The conversion specifiers can only be
3427
'<code>%%</code>' (inserts a '<code>%</code>' in the string),
3428
'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
3429
'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
3430
'<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
3431
'<code>%d</code>' (inserts an <code>int</code>), and
3432
'<code>%c</code>' (inserts an <code>int</code> as a character).
3433
</li>
3434
 
3435
</ul>
3436
 
3437
 
3438
 
3439
 
3440
<hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3>
3441
<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
3442
 
3443
<p>
3444
Pushes a number with value <code>n</code> onto the stack.
3445
 
3446
 
3447
 
3448
 
3449
 
3450
<hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3>
3451
<pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre>
3452
 
3453
<p>
3454
Pushes a light userdata onto the stack.
3455
 
3456
 
3457
<p>
3458
Userdata represents C&nbsp;values in Lua.
3459
A <em>light userdata</em> represents a pointer.
3460
It is a value (like a number):
3461
you do not create it, it has no individual metatable,
3462
and it is not collected (as it was never created).
3463
A light userdata is equal to "any"
3464
light userdata with the same C&nbsp;address.
3465
 
3466
 
3467
 
3468
 
3469
 
3470
<hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3>
3471
<pre>void lua_pushlstring (lua_State *L, const char *s, size_t len);</pre>
3472
 
3473
<p>
3474
Pushes the string pointed to by <code>s</code> with size <code>len</code>
3475
onto the stack.
3476
Lua makes (or reuses) an internal copy of the given string,
3477
so the memory at <code>s</code> can be freed or reused immediately after
3478
the function returns.
3479
The string can contain embedded zeros.
3480
 
3481
 
3482
 
3483
 
3484
 
3485
<hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3>
3486
<pre>void lua_pushnil (lua_State *L);</pre>
3487
 
3488
<p>
3489
Pushes a nil value onto the stack.
3490
 
3491
 
3492
 
3493
 
3494
 
3495
<hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3>
3496
<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
3497
 
3498
<p>
3499
Pushes a number with value <code>n</code> onto the stack.
3500
 
3501
 
3502
 
3503
 
3504
 
3505
<hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3>
3506
<pre>void lua_pushstring (lua_State *L, const char *s);</pre>
3507
 
3508
<p>
3509
Pushes the zero-terminated string pointed to by <code>s</code>
3510
onto the stack.
3511
Lua makes (or reuses) an internal copy of the given string,
3512
so the memory at <code>s</code> can be freed or reused immediately after
3513
the function returns.
3514
The string cannot contain embedded zeros;
3515
it is assumed to end at the first zero.
3516
 
3517
 
3518
 
3519
 
3520
 
3521
<hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3>
3522
<pre>int lua_pushthread (lua_State *L);</pre>
3523
 
3524
<p>
3525
Pushes the thread represented by <code>L</code> onto the stack.
3526
Returns 1 if this thread is the main thread of its state.
3527
 
3528
 
3529
 
3530
 
3531
 
3532
<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3>
3533
<pre>void lua_pushvalue (lua_State *L, int index);</pre>
3534
 
3535
<p>
3536
Pushes a copy of the element at the given valid index
3537
onto the stack.
3538
 
3539
 
3540
 
3541
 
3542
 
3543
<hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3>
3544
<pre>const char *lua_pushvfstring (lua_State *L,
3545
                              const char *fmt,
3546
                              va_list argp);</pre>
3547
 
3548
<p>
3549
Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code>
3550
instead of a variable number of arguments.
3551
 
3552
 
3553
 
3554
 
3555
 
3556
<hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3>
3557
<pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre>
3558
 
3559
<p>
3560
Returns 1 if the two values in acceptable indices <code>index1</code> and
3561
<code>index2</code> are primitively equal
3562
(that is, without calling metamethods).
3563
Otherwise returns&nbsp;0.
3564
Also returns&nbsp;0 if any of the indices are non valid.
3565
 
3566
 
3567
 
3568
 
3569
 
3570
<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3>
3571
<pre>void lua_rawget (lua_State *L, int index);</pre>
3572
 
3573
<p>
3574
Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
3575
(i.e., without metamethods).
3576
 
3577
 
3578
 
3579
 
3580
 
3581
<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3>
3582
<pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
3583
 
3584
<p>
3585
Pushes onto the stack the value <code>t[n]</code>,
3586
where <code>t</code> is the value at the given valid index <code>index</code>.
3587
The access is raw;
3588
that is, it does not invoke metamethods.
3589
 
3590
 
3591
 
3592
 
3593
 
3594
<hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3>
3595
<pre>void lua_rawset (lua_State *L, int index);</pre>
3596
 
3597
<p>
3598
Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment
3599
(i.e., without metamethods).
3600
 
3601
 
3602
 
3603
 
3604
 
3605
<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3>
3606
<pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
3607
 
3608
<p>
3609
Does the equivalent of <code>t[n] = v</code>,
3610
where <code>t</code> is the value at the given valid index <code>index</code>
3611
and <code>v</code> is the value at the top of the stack,
3612
 
3613
 
3614
<p>
3615
This function pops the value from the stack.
3616
The assignment is raw;
3617
that is, it does not invoke metamethods.
3618
 
3619
 
3620
 
3621
 
3622
 
3623
<hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3>
3624
<pre>typedef const char * (*lua_Reader) (lua_State *L,
3625
                                    void *data,
3626
                                    size_t *size);</pre>
3627
 
3628
<p>
3629
The reader function used by <a href="#lua_load"><code>lua_load</code></a>.
3630
Every time it needs another piece of the chunk,
3631
<a href="#lua_load"><code>lua_load</code></a> calls the reader,
3632
passing along its <code>data</code> parameter.
3633
The reader must return a pointer to a block of memory
3634
with a new piece of the chunk
3635
and set <code>size</code> to the block size.
3636
The block must exist until the reader function is called again.
3637
To signal the end of the chunk, the reader must return <code>NULL</code>.
3638
The reader function may return pieces of any size greater than zero.
3639
 
3640
 
3641
 
3642
 
3643
 
3644
<hr><h3><a name="lua_register"><code>lua_register</code></a></h3>
3645
<pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre>
3646
 
3647
<p>
3648
Sets the C function <code>f</code> as the new value of global <code>name</code>.
3649
It is defined as a macro:
3650
 
3651
<pre>
3652
     #define lua_register(L,n,f)  (lua_pushcfunction(L, f), lua_setglobal(L, n))
3653
</pre>
3654
 
3655
 
3656
 
3657
 
3658
<hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3>
3659
<pre>void lua_remove (lua_State *L, int index);</pre>
3660
 
3661
<p>
3662
Removes the element at the given valid index,
3663
shifting down the elements above this index to fill the gap.
3664
Cannot be called with a pseudo-index,
3665
because a pseudo-index is not an actual stack position.
3666
 
3667
 
3668
 
3669
 
3670
 
3671
<hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3>
3672
<pre>void lua_replace (lua_State *L, int index);</pre>
3673
 
3674
<p>
3675
Moves the top element into the given position (and pops it),
3676
without shifting any element
3677
(therefore replacing the value at the given position).
3678
 
3679
 
3680
 
3681
 
3682
 
3683
<hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3>
3684
<pre>int lua_resume (lua_State *L, int narg);</pre>
3685
 
3686
<p>
3687
Starts and resumes a coroutine in a given thread.
3688
 
3689
 
3690
<p>
3691
To start a coroutine, you first create a new thread
3692
(see <a href="#lua_newthread"><code>lua_newthread</code></a>);
3693
then you push onto its stack the main function plus any arguments;
3694
then you call <a href="#lua_resume"><code>lua_resume</code></a>,
3695
with <code>narg</code> being the number of arguments.
3696
This call returns when the coroutine suspends or finishes its execution.
3697
When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>,
3698
or all values returned by the body function.
3699
<a href="#lua_resume"><code>lua_resume</code></a> returns
3700
<a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields,
3701
 
3702
without errors,
3703
or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
3704
In case of errors,
3705
the stack is not unwound,
3706
so you can use the debug API over it.
3707
The error message is on the top of the stack.
3708
To restart a coroutine, you put on its stack only the values to
3709
be passed as results from <code>yield</code>,
3710
and then call <a href="#lua_resume"><code>lua_resume</code></a>.
3711
 
3712
 
3713
 
3714
 
3715
 
3716
<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3>
3717
<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
3718
 
3719
<p>
3720
Changes the allocator function of a given state to <code>f</code>
3721
with user data <code>ud</code>.
3722
 
3723
 
3724
 
3725
 
3726
 
3727
<hr><h3><a name="lua_setfenv"><code>lua_setfenv</code></a></h3>
3728
<pre>int lua_setfenv (lua_State *L, int index);</pre>
3729
 
3730
<p>
3731
Pops a table from the stack and sets it as
3732
the new environment for the value at the given index.
3733
If the value at the given index is
3734
neither a function nor a thread nor a userdata,
3735
<a href="#lua_setfenv"><code>lua_setfenv</code></a> returns 0.
3736
Otherwise it returns 1.
3737
 
3738
 
3739
 
3740
 
3741
 
3742
<hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3>
3743
<pre>void lua_setfield (lua_State *L, int index, const char *k);</pre>
3744
 
3745
<p>
3746
Does the equivalent to <code>t[k] = v</code>,
3747
where <code>t</code> is the value at the given valid index <code>index</code>
3748
and <code>v</code> is the value at the top of the stack,
3749
 
3750
 
3751
<p>
3752
This function pops the value from the stack.
3753
As in Lua, this function may trigger a metamethod
3754
for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3755
 
3756
 
3757
 
3758
 
3759
 
3760
<hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3>
3761
<pre>void lua_setglobal (lua_State *L, const char *name);</pre>
3762
 
3763
<p>
3764
Pops a value from the stack and
3765
sets it as the new value of global <code>name</code>.
3766
It is defined as a macro:
3767
 
3768
<pre>
3769
     #define lua_setglobal(L,s)   lua_setfield(L, LUA_GLOBALSINDEX, s)
3770
</pre>
3771
 
3772
 
3773
 
3774
 
3775
<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3>
3776
<pre>int lua_setmetatable (lua_State *L, int index);</pre>
3777
 
3778
<p>
3779
Pops a table from the stack and
3780
sets it as the new metatable for the value at the given
3781
acceptable index.
3782
 
3783
 
3784
 
3785
 
3786
 
3787
<hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3>
3788
<pre>void lua_settable (lua_State *L, int index);</pre>
3789
 
3790
<p>
3791
Does the equivalent to <code>t[k] = v</code>,
3792
where <code>t</code> is the value at the given valid index <code>index</code>,
3793
<code>v</code> is the value at the top of the stack,
3794
and <code>k</code> is the value just below the top.
3795
 
3796
 
3797
<p>
3798
This function pops both the key and the value from the stack.
3799
As in Lua, this function may trigger a metamethod
3800
for the "newindex" event (see <a href="#2.8">&sect;2.8</a>).
3801
 
3802
 
3803
 
3804
 
3805
 
3806
<hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3>
3807
<pre>void lua_settop (lua_State *L, int index);</pre>
3808
 
3809
<p>
3810
Accepts any acceptable index, or&nbsp;0,
3811
and sets the stack top to this index.
3812
If the new top is larger than the old one,
3813
then the new elements are filled with <b>nil</b>.
3814
If <code>index</code> is&nbsp;0, then all stack elements are removed.
3815
 
3816
 
3817
 
3818
 
3819
 
3820
<hr><h3><a name="lua_State"><code>lua_State</code></a></h3>
3821
<pre>typedef struct lua_State lua_State;</pre>
3822
 
3823
<p>
3824
Opaque structure that keeps the whole state of a Lua interpreter.
3825
The Lua library is fully reentrant:
3826
it has no global variables.
3827
All information about a state is kept in this structure.
3828
 
3829
 
3830
<p>
3831
A pointer to this state must be passed as the first argument to
3832
every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>,
3833
which creates a Lua state from scratch.
3834
 
3835
 
3836
 
3837
 
3838
 
3839
<hr><h3><a name="lua_status"><code>lua_status</code></a></h3>
3840
<pre>int lua_status (lua_State *L);</pre>
3841
 
3842
<p>
3843
Returns the status of the thread <code>L</code>.
3844
 
3845
 
3846
<p>
3847
The status can be 0 for a normal thread,
3848
an error code if the thread finished its execution with an error,
3849
or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended.
3850
 
3851
 
3852
 
3853
 
3854
 
3855
<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3>
3856
<pre>int lua_toboolean (lua_State *L, int index);</pre>
3857
 
3858
<p>
3859
Converts the Lua value at the given acceptable index to a C&nbsp;boolean
3860
value (0&nbsp;or&nbsp;1).
3861
Like all tests in Lua,
3862
<a href="#lua_toboolean"><code>lua_toboolean</code></a> returns 1 for any Lua value
3863
different from <b>false</b> and <b>nil</b>;
3864
otherwise it returns 0.
3865
It also returns 0 when called with a non-valid index.
3866
(If you want to accept only actual boolean values,
3867
use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.)
3868
 
3869
 
3870
 
3871
 
3872
 
3873
<hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3>
3874
<pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre>
3875
 
3876
<p>
3877
Converts a value at the given acceptable index to a C&nbsp;function.
3878
That value must be a C&nbsp;function;
3879
otherwise, returns <code>NULL</code>.
3880
 
3881
 
3882
 
3883
 
3884
 
3885
<hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3>
3886
<pre>lua_Integer lua_tointeger (lua_State *L, int idx);</pre>
3887
 
3888
<p>
3889
Converts the Lua value at the given acceptable index
3890
to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
3891
The Lua value must be a number or a string convertible to a number
3892
(see <a href="#2.2.1">&sect;2.2.1</a>);
3893
otherwise, <a href="#lua_tointeger"><code>lua_tointeger</code></a> returns&nbsp;0.
3894
 
3895
 
3896
<p>
3897
If the number is not an integer,
3898
it is truncated in some non-specified way.
3899
 
3900
 
3901
 
3902
 
3903
 
3904
<hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3>
3905
<pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre>
3906
 
3907
<p>
3908
Converts the Lua value at the given acceptable index to a string
3909
(<code>const char*</code>).
3910
If <code>len</code> is not <code>NULL</code>,
3911
it also sets <code>*len</code> with the string length.
3912
The Lua value must be a string or a number;
3913
otherwise, the function returns <code>NULL</code>.
3914
If the value is a number,
3915
then <a href="#lua_tolstring"><code>lua_tolstring</code></a> also
3916
<em>changes the actual value in the stack to a string</em>.
3917
(This change confuses <a href="#lua_next"><code>lua_next</code></a>
3918
when <a href="#lua_tolstring"><code>lua_tolstring</code></a> is applied to keys during a table traversal.)
3919
 
3920
 
3921
<p>
3922
<a href="#lua_tolstring"><code>lua_tolstring</code></a> returns a fully aligned pointer
3923
to a string inside the Lua state.
3924
This string always has a zero ('<code>\0</code>')
3925
after its last character (as in&nbsp;C),
3926
but may contain other zeros in its body.
3927
Because Lua has garbage collection,
3928
there is no guarantee that the pointer returned by <a href="#lua_tolstring"><code>lua_tolstring</code></a>
3929
will be valid after the corresponding value is removed from the stack.
3930
 
3931
 
3932
 
3933
 
3934
 
3935
<hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3>
3936
<pre>lua_Number lua_tonumber (lua_State *L, int index);</pre>
3937
 
3938
<p>
3939
Converts the Lua value at the given acceptable index
3940
to a number (see <a href="#lua_Number"><code>lua_Number</code></a>).
3941
The Lua value must be a number or a string convertible to a number
3942
(see <a href="#2.2.1">&sect;2.2.1</a>);
3943
otherwise, <a href="#lua_tonumber"><code>lua_tonumber</code></a> returns&nbsp;0.
3944
 
3945
 
3946
 
3947
 
3948
 
3949
<hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3>
3950
<pre>const void *lua_topointer (lua_State *L, int index);</pre>
3951
 
3952
<p>
3953
Converts the value at the given acceptable index to a generic
3954
C&nbsp;pointer (<code>void*</code>).
3955
The value may be a userdata, a table, a thread, or a function;
3956
otherwise, <a href="#lua_topointer"><code>lua_topointer</code></a> returns <code>NULL</code>.
3957
Different objects will give different pointers.
3958
There is no way to convert the pointer back to its original value.
3959
 
3960
 
3961
<p>
3962
Typically this function is used only for debug information.
3963
 
3964
 
3965
 
3966
 
3967
 
3968
<hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3>
3969
<pre>const char *lua_tostring (lua_State *L, int index);</pre>
3970
 
3971
<p>
3972
Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>.
3973
 
3974
 
3975
 
3976
 
3977
 
3978
<hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3>
3979
<pre>lua_State *lua_tothread (lua_State *L, int index);</pre>
3980
 
3981
<p>
3982
Converts the value at the given acceptable index to a Lua thread
3983
(represented as <code>lua_State*</code>).
3984
This value must be a thread;
3985
otherwise, the function returns <code>NULL</code>.
3986
 
3987
 
3988
 
3989
 
3990
 
3991
<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3>
3992
<pre>void *lua_touserdata (lua_State *L, int index);</pre>
3993
 
3994
<p>
3995
If the value at the given acceptable index is a full userdata,
3996
returns its block address.
3997
If the value is a light userdata,
3998
returns its pointer.
3999
Otherwise, returns <code>NULL</code>.
4000
 
4001
 
4002
 
4003
 
4004
 
4005
<hr><h3><a name="lua_type"><code>lua_type</code></a></h3>
4006
<pre>int lua_type (lua_State *L, int index);</pre>
4007
 
4008
<p>
4009
Returns the type of the value in the given acceptable index,
4010
or <code>LUA_TNONE</code> for a non-valid index
4011
(that is, an index to an "empty" stack position).
4012
The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants
4013
defined in <code>lua.h</code>:
4014
<code>LUA_TNIL</code>,
4015
<code>LUA_TNUMBER</code>,
4016
<code>LUA_TBOOLEAN</code>,
4017
<code>LUA_TSTRING</code>,
4018
<code>LUA_TTABLE</code>,
4019
<code>LUA_TFUNCTION</code>,
4020
<code>LUA_TUSERDATA</code>,
4021
<code>LUA_TTHREAD</code>,
4022
and
4023
<code>LUA_TLIGHTUSERDATA</code>.
4024
 
4025
 
4026
 
4027
 
4028
 
4029
<hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3>
4030
<pre>const char *lua_typename  (lua_State *L, int tp);</pre>
4031
 
4032
<p>
4033
Returns the name of the type encoded by the value <code>tp</code>,
4034
which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>.
4035
 
4036
 
4037
 
4038
 
4039
 
4040
<hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3>
4041
<pre>typedef int (*lua_Writer) (lua_State *L,
4042
                           const void* p,
4043
                           size_t sz,
4044
                           void* ud);</pre>
4045
 
4046
<p>
4047
The writer function used by <a href="#lua_dump"><code>lua_dump</code></a>.
4048
Every time it produces another piece of chunk,
4049
<a href="#lua_dump"><code>lua_dump</code></a> calls the writer,
4050
passing along the buffer to be written (<code>p</code>),
4051
its size (<code>sz</code>),
4052
and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>.
4053
 
4054
 
4055
<p>
4056
The writer returns an error code:
4057
 
4058
any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from
4059
calling the writer again.
4060
 
4061
 
4062
 
4063
 
4064
 
4065
<hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3>
4066
<pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre>
4067
 
4068
<p>
4069
Exchange values between different threads of the <em>same</em> global state.
4070
 
4071
 
4072
<p>
4073
This function pops <code>n</code> values from the stack <code>from</code>,
4074
and pushes them onto the stack <code>to</code>.
4075
 
4076
 
4077
 
4078
 
4079
 
4080
<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3>
4081
<pre>int lua_yield  (lua_State *L, int nresults);</pre>
4082
 
4083
<p>
4084
Yields a coroutine.
4085
 
4086
 
4087
<p>
4088
This function should only be called as the
4089
return expression of a C&nbsp;function, as follows:
4090
 
4091
<pre>
4092
     return lua_yield (L, nresults);
4093
</pre><p>
4094
When a C&nbsp;function calls <a href="#lua_yield"><code>lua_yield</code></a> in that way,
4095
the running coroutine suspends its execution,
4096
and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
4097
The parameter <code>nresults</code> is the number of values from the stack
4098
that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
4099
 
4100
 
4101
 
4102
 
4103
 
4104
 
4105
 
4106
<h2>3.8 - <a name="3.8">The Debug Interface</a></h2>
4107
 
4108
<p>
4109
Lua has no built-in debugging facilities.
4110
Instead, it offers a special interface
4111
by means of functions and <em>hooks</em>.
4112
This interface allows the construction of different
4113
kinds of debuggers, profilers, and other tools
4114
that need "inside information" from the interpreter.
4115
 
4116
 
4117
 
4118
<hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3>
4119
<pre>typedef struct lua_Debug {
4120
  int event;
4121
  const char *name;           /* (n) */
4122
  const char *namewhat;       /* (n) */
4123
  const char *what;           /* (S) */
4124
  const char *source;         /* (S) */
4125
  int currentline;            /* (l) */
4126
  int nups;                   /* (u) number of upvalues */
4127
  int linedefined;            /* (S) */
4128
  int lastlinedefined;        /* (S) */
4129
  char short_src[LUA_IDSIZE]; /* (S) */
4130
  /* private part */
4131
  <em>other fields</em>
4132
} lua_Debug;</pre>
4133
 
4134
<p>
4135
A structure used to carry different pieces of
4136
information about an active function.
4137
<a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part
4138
of this structure, for later use.
4139
To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information,
4140
call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4141
 
4142
 
4143
<p>
4144
The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning:
4145
 
4146
<ul>
4147
 
4148
<li><b><code>source</code>:</b>
4149
If the function was defined in a string,
4150
then <code>source</code> is that string.
4151
If the function was defined in a file,
4152
then <code>source</code> starts with a '<code>@</code>' followed by the file name.
4153
</li>
4154
 
4155
<li><b><code>short_src</code>:</b>
4156
a "printable" version of <code>source</code>, to be used in error messages.
4157
</li>
4158
 
4159
<li><b><code>linedefined</code>:</b>
4160
the line number where the definition of the function starts.
4161
</li>
4162
 
4163
<li><b><code>lastlinedefined</code>:</b>
4164
the line number where the definition of the function ends.
4165
</li>
4166
 
4167
<li><b><code>what</code>:</b>
4168
the string <code>"Lua"</code> if the function is a Lua function,
4169
<code>"C"</code> if it is a C&nbsp;function,
4170
<code>"main"</code> if it is the main part of a chunk,
4171
and <code>"tail"</code> if it was a function that did a tail call.
4172
In the latter case,
4173
Lua has no other information about the function.
4174
</li>
4175
 
4176
<li><b><code>currentline</code>:</b>
4177
the current line where the given function is executing.
4178
When no line information is available,
4179
<code>currentline</code> is set to -1.
4180
</li>
4181
 
4182
<li><b><code>name</code>:</b>
4183
a reasonable name for the given function.
4184
Because functions in Lua are first-class values,
4185
they do not have a fixed name:
4186
some functions may be the value of multiple global variables,
4187
while others may be stored only in a table field.
4188
The <code>lua_getinfo</code> function checks how the function was
4189
called to find a suitable name.
4190
If it cannot find a name,
4191
then <code>name</code> is set to <code>NULL</code>.
4192
</li>
4193
 
4194
<li><b><code>namewhat</code>:</b>
4195
explains the <code>name</code> field.
4196
The value of <code>namewhat</code> can be
4197
<code>"global"</code>, <code>"local"</code>, <code>"method"</code>,
4198
<code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string),
4199
according to how the function was called.
4200
(Lua uses the empty string when no other option seems to apply.)
4201
</li>
4202
 
4203
<li><b><code>nups</code>:</b>
4204
the number of upvalues of the function.
4205
</li>
4206
 
4207
</ul>
4208
 
4209
 
4210
 
4211
 
4212
<hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3>
4213
<pre>lua_Hook lua_gethook (lua_State *L);</pre>
4214
 
4215
<p>
4216
Returns the current hook function.
4217
 
4218
 
4219
 
4220
 
4221
 
4222
<hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3>
4223
<pre>int lua_gethookcount (lua_State *L);</pre>
4224
 
4225
<p>
4226
Returns the current hook count.
4227
 
4228
 
4229
 
4230
 
4231
 
4232
<hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3>
4233
<pre>int lua_gethookmask (lua_State *L);</pre>
4234
 
4235
<p>
4236
Returns the current hook mask.
4237
 
4238
 
4239
 
4240
 
4241
 
4242
<hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3>
4243
<pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre>
4244
 
4245
<p>
4246
Returns information about a specific function or function invocation.
4247
 
4248
 
4249
<p>
4250
To get information about a function invocation,
4251
the parameter <code>ar</code> must be a valid activation record that was
4252
filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4253
given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4254
 
4255
 
4256
<p>
4257
To get information about a function you push it onto the stack
4258
and start the <code>what</code> string with the character '<code>&gt;</code>'.
4259
(In that case,
4260
<code>lua_getinfo</code> pops the function in the top of the stack.)
4261
For instance, to know in which line a function <code>f</code> was defined,
4262
you can write the following code:
4263
 
4264
<pre>
4265
     lua_Debug ar;
4266
     lua_getfield(L, LUA_GLOBALSINDEX, "f");  /* get global 'f' */
4267
     lua_getinfo(L, "&gt;S", &amp;ar);
4268
     printf("%d\n", ar.linedefined);
4269
</pre>
4270
 
4271
<p>
4272
Each character in the string <code>what</code>
4273
selects some fields of the structure <code>ar</code> to be filled or
4274
a value to be pushed on the stack:
4275
 
4276
<ul>
4277
 
4278
<li><b>'<code>n</code>':</b> fills in the field <code>name</code> and <code>namewhat</code>;
4279
</li>
4280
 
4281
<li><b>'<code>S</code>':</b>
4282
fills in the fields <code>source</code>, <code>linedefined</code>,
4283
<code>lastlinedefined</code>, <code>what</code>, and <code>short_src</code>;
4284
</li>
4285
 
4286
<li><b>'<code>l</code>':</b> fills in the field <code>currentline</code>;
4287
</li>
4288
 
4289
<li><b>'<code>u</code>':</b> fills in the field <code>nups</code>;
4290
</li>
4291
 
4292
<li><b>'<code>f</code>':</b>
4293
pushes onto the stack the function that is
4294
running at the given level;
4295
</li>
4296
 
4297
<li><b>'<code>L</code>':</b>
4298
pushes onto the stack a table whose indices are the
4299
numbers of the lines that are valid on the function.
4300
(A <em>valid line</em> is a line with some associated code,
4301
that is, a line where you can put a break point.
4302
Non-valid lines include empty lines and comments.)
4303
</li>
4304
 
4305
</ul>
4306
 
4307
<p>
4308
This function returns 0 on error
4309
(for instance, an invalid option in <code>what</code>).
4310
 
4311
 
4312
 
4313
 
4314
 
4315
<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3>
4316
<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
4317
 
4318
<p>
4319
Gets information about a local variable of a given activation record.
4320
The parameter <code>ar</code> must be a valid activation record that was
4321
filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or
4322
given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>).
4323
The index <code>n</code> selects which local variable to inspect
4324
(1 is the first parameter or active local variable, and so on,
4325
until the last active local variable).
4326
<a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack
4327
and returns its name.
4328
 
4329
 
4330
<p>
4331
Variable names starting with '<code>(</code>' (open parentheses)
4332
represent internal variables
4333
(loop control variables, temporaries, and C&nbsp;function locals).
4334
 
4335
 
4336
<p>
4337
Returns <code>NULL</code> (and pushes nothing)
4338
when the index is greater than
4339
the number of active local variables.
4340
 
4341
 
4342
 
4343
 
4344
 
4345
<hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3>
4346
<pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre>
4347
 
4348
<p>
4349
Get information about the interpreter runtime stack.
4350
 
4351
 
4352
<p>
4353
This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with
4354
an identification of the <em>activation record</em>
4355
of the function executing at a given level.
4356
Level&nbsp;0 is the current running function,
4357
whereas level <em>n+1</em> is the function that has called level <em>n</em>.
4358
When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1;
4359
when called with a level greater than the stack depth,
4360
it returns 0.
4361
 
4362
 
4363
 
4364
 
4365
 
4366
<hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3>
4367
<pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre>
4368
 
4369
<p>
4370
Gets information about a closure's upvalue.
4371
(For Lua functions,
4372
upvalues are the external local variables that the function uses,
4373
and that are consequently included in its closure.)
4374
<a href="#lua_getupvalue"><code>lua_getupvalue</code></a> gets the index <code>n</code> of an upvalue,
4375
pushes the upvalue's value onto the stack,
4376
and returns its name.
4377
<code>funcindex</code> points to the closure in the stack.
4378
(Upvalues have no particular order,
4379
as they are active through the whole function.
4380
So, they are numbered in an arbitrary order.)
4381
 
4382
 
4383
<p>
4384
Returns <code>NULL</code> (and pushes nothing)
4385
when the index is greater than the number of upvalues.
4386
For C&nbsp;functions, this function uses the empty string <code>""</code>
4387
as a name for all upvalues.
4388
 
4389
 
4390
 
4391
 
4392
 
4393
<hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3>
4394
<pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre>
4395
 
4396
<p>
4397
Type for debugging hook functions.
4398
 
4399
 
4400
<p>
4401
Whenever a hook is called, its <code>ar</code> argument has its field
4402
<code>event</code> set to the specific event that triggered the hook.
4403
Lua identifies these events with the following constants:
4404
<a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>,
4405
<a name="pdf-LUA_HOOKTAILRET"><code>LUA_HOOKTAILRET</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>,
4406
and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>.
4407
Moreover, for line events, the field <code>currentline</code> is also set.
4408
To get the value of any other field in <code>ar</code>,
4409
the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4410
For return events, <code>event</code> may be <code>LUA_HOOKRET</code>,
4411
the normal value, or <code>LUA_HOOKTAILRET</code>.
4412
In the latter case, Lua is simulating a return from
4413
a function that did a tail call;
4414
in this case, it is useless to call <a href="#lua_getinfo"><code>lua_getinfo</code></a>.
4415
 
4416
 
4417
<p>
4418
While Lua is running a hook, it disables other calls to hooks.
4419
Therefore, if a hook calls back Lua to execute a function or a chunk,
4420
this execution occurs without any calls to hooks.
4421
 
4422
 
4423
 
4424
 
4425
 
4426
<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3>
4427
<pre>int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);</pre>
4428
 
4429
<p>
4430
Sets the debugging hook function.
4431
 
4432
 
4433
<p>
4434
<code>func</code> is the hook function.
4435
<code>mask</code> specifies on which events the hook will be called:
4436
it is formed by a bitwise or of the constants
4437
<a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>,
4438
<a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>,
4439
<a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>,
4440
and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>.
4441
The <code>count</code> argument is only meaningful when the mask
4442
includes <code>LUA_MASKCOUNT</code>.
4443
For each event, the hook is called as explained below:
4444
 
4445
<ul>
4446
 
4447
<li><b>The call hook:</b> is called when the interpreter calls a function.
4448
The hook is called just after Lua enters the new function,
4449
before the function gets its arguments.
4450
</li>
4451
 
4452
<li><b>The return hook:</b> is called when the interpreter returns from a function.
4453
The hook is called just before Lua leaves the function.
4454
You have no access to the values to be returned by the function.
4455
</li>
4456
 
4457
<li><b>The line hook:</b> is called when the interpreter is about to
4458
start the execution of a new line of code,
4459
or when it jumps back in the code (even to the same line).
4460
(This event only happens while Lua is executing a Lua function.)
4461
</li>
4462
 
4463
<li><b>The count hook:</b> is called after the interpreter executes every
4464
<code>count</code> instructions.
4465
(This event only happens while Lua is executing a Lua function.)
4466
</li>
4467
 
4468
</ul>
4469
 
4470
<p>
4471
A hook is disabled by setting <code>mask</code> to zero.
4472
 
4473
 
4474
 
4475
 
4476
 
4477
<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3>
4478
<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
4479
 
4480
<p>
4481
Sets the value of a local variable of a given activation record.
4482
Parameters <code>ar</code> and <code>n</code> are as in <a href="#lua_getlocal"><code>lua_getlocal</code></a>
4483
(see <a href="#lua_getlocal"><code>lua_getlocal</code></a>).
4484
<a href="#lua_setlocal"><code>lua_setlocal</code></a> assigns the value at the top of the stack
4485
to the variable and returns its name.
4486
It also pops the value from the stack.
4487
 
4488
 
4489
<p>
4490
Returns <code>NULL</code> (and pops nothing)
4491
when the index is greater than
4492
the number of active local variables.
4493
 
4494
 
4495
 
4496
 
4497
 
4498
<hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3>
4499
<pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre>
4500
 
4501
<p>
4502
Sets the value of a closure's upvalue.
4503
Parameters <code>funcindex</code> and <code>n</code> are as in <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
4504
(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>).
4505
It assigns the value at the top of the stack
4506
to the upvalue and returns its name.
4507
It also pops the value from the stack.
4508
 
4509
 
4510
<p>
4511
Returns <code>NULL</code> (and pops nothing)
4512
when the index is greater than the number of upvalues.
4513
 
4514
 
4515
 
4516
 
4517
 
4518
 
4519
 
4520
<h1>4 - <a name="4">The Auxiliary Library</a></h1>
4521
 
4522
<p>
4523
 
4524
The <em>auxiliary library</em> provides several convenient functions
4525
to interface C with Lua.
4526
While the basic API provides the primitive functions for all 
4527
interactions between C and Lua,
4528
the auxiliary library provides higher-level functions for some
4529
common tasks.
4530
 
4531
 
4532
<p>
4533
All functions from the auxiliary library
4534
are defined in header file <code>lauxlib.h</code> and
4535
have a prefix <code>luaL_</code>.
4536
 
4537
 
4538
<p>
4539
All functions in the auxiliary library are built on
4540
top of the basic API,
4541
and so they provide nothing that cannot be done with this API.
4542
 
4543
 
4544
<p>
4545
Several functions in the auxiliary library are used to
4546
check C&nbsp;function arguments.
4547
Their names are always <code>luaL_check*</code> or <code>luaL_opt*</code>.
4548
All of these functions raise an error if the check is not satisfied.
4549
Because the error message is formatted for arguments
4550
(e.g., "<code>bad argument #1</code>"),
4551
you should not use these functions for other stack values.
4552
 
4553
 
4554
 
4555
<h2>4.1 - <a name="4.1">Functions and Types</a></h2>
4556
 
4557
<p>
4558
Here we list all functions and types from the auxiliary library
4559
in alphabetical order.
4560
 
4561
 
4562
 
4563
<hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3>
4564
<pre>void luaL_addchar (luaL_Buffer *B, char c);</pre>
4565
 
4566
<p>
4567
Adds the character <code>c</code> to the buffer <code>B</code>
4568
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4569
 
4570
 
4571
 
4572
 
4573
 
4574
<hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3>
4575
<pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre>
4576
 
4577
<p>
4578
Adds the string pointed to by <code>s</code> with length <code>l</code> to
4579
the buffer <code>B</code>
4580
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4581
The string may contain embedded zeros.
4582
 
4583
 
4584
 
4585
 
4586
 
4587
<hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3>
4588
<pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre>
4589
 
4590
<p>
4591
Adds a string of length <code>n</code> previously copied to the
4592
buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>) to the buffer <code>B</code>
4593
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4594
 
4595
 
4596
 
4597
 
4598
 
4599
<hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3>
4600
<pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre>
4601
 
4602
<p>
4603
Adds the zero-terminated string pointed to by <code>s</code>
4604
to the buffer <code>B</code>
4605
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4606
The string may not contain embedded zeros.
4607
 
4608
 
4609
 
4610
 
4611
 
4612
<hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3>
4613
<pre>void luaL_addvalue (luaL_Buffer *B);</pre>
4614
 
4615
<p>
4616
Adds the value at the top of the stack
4617
to the buffer <code>B</code>
4618
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4619
Pops the value.
4620
 
4621
 
4622
<p>
4623
This is the only function on string buffers that can (and must)
4624
be called with an extra element on the stack,
4625
which is the value to be added to the buffer.
4626
 
4627
 
4628
 
4629
 
4630
 
4631
<hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3>
4632
<pre>void luaL_argcheck (lua_State *L,
4633
                    int cond,
4634
                    int numarg,
4635
                    const char *extramsg);</pre>
4636
 
4637
<p>
4638
Checks whether <code>cond</code> is true.
4639
If not, raises an error with the following message,
4640
where <code>func</code> is retrieved from the call stack:
4641
 
4642
<pre>
4643
     bad argument #&lt;numarg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4644
</pre>
4645
 
4646
 
4647
 
4648
 
4649
<hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3>
4650
<pre>int luaL_argerror (lua_State *L, int numarg, const char *extramsg);</pre>
4651
 
4652
<p>
4653
Raises an error with the following message,
4654
where <code>func</code> is retrieved from the call stack:
4655
 
4656
<pre>
4657
     bad argument #&lt;numarg&gt; to &lt;func&gt; (&lt;extramsg&gt;)
4658
</pre>
4659
 
4660
<p>
4661
This function never returns,
4662
but it is an idiom to use it in C&nbsp;functions
4663
as <code>return luaL_argerror(<em>args</em>)</code>.
4664
 
4665
 
4666
 
4667
 
4668
 
4669
<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
4670
<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
4671
 
4672
<p>
4673
Type for a <em>string buffer</em>.
4674
 
4675
 
4676
<p>
4677
A string buffer allows C&nbsp;code to build Lua strings piecemeal.
4678
Its pattern of use is as follows:
4679
 
4680
<ul>
4681
 
4682
<li>First you declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li>
4683
 
4684
<li>Then you initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li>
4685
 
4686
<li>
4687
Then you add string pieces to the buffer calling any of
4688
the <code>luaL_add*</code> functions.
4689
</li>
4690
 
4691
<li>
4692
You finish by calling <code>luaL_pushresult(&amp;b)</code>.
4693
This call leaves the final string on the top of the stack.
4694
</li>
4695
 
4696
</ul>
4697
 
4698
<p>
4699
During its normal operation,
4700
a string buffer uses a variable number of stack slots.
4701
So, while using a buffer, you cannot assume that you know where
4702
the top of the stack is.
4703
You can use the stack between successive calls to buffer operations
4704
as long as that use is balanced;
4705
that is,
4706
when you call a buffer operation,
4707
the stack is at the same level
4708
it was immediately after the previous buffer operation.
4709
(The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.)
4710
After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its
4711
level when the buffer was initialized,
4712
plus the final string on its top.
4713
 
4714
 
4715
 
4716
 
4717
 
4718
<hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3>
4719
<pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre>
4720
 
4721
<p>
4722
Initializes a buffer <code>B</code>.
4723
This function does not allocate any space;
4724
the buffer must be declared as a variable
4725
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
4726
 
4727
 
4728
 
4729
 
4730
 
4731
<hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3>
4732
<pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre>
4733
 
4734
<p>
4735
Calls a metamethod.
4736
 
4737
 
4738
<p>
4739
If the object at index <code>obj</code> has a metatable and this
4740
metatable has a field <code>e</code>,
4741
this function calls this field and passes the object as its only argument.
4742
In this case this function returns 1 and pushes onto the
4743
stack the value returned by the call.
4744
If there is no metatable or no metamethod,
4745
this function returns 0 (without pushing any value on the stack).
4746
 
4747
 
4748
 
4749
 
4750
 
4751
<hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3>
4752
<pre>void luaL_checkany (lua_State *L, int narg);</pre>
4753
 
4754
<p>
4755
Checks whether the function has an argument
4756
of any type (including <b>nil</b>) at position <code>narg</code>.
4757
 
4758
 
4759
 
4760
 
4761
 
4762
<hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3>
4763
<pre>int luaL_checkint (lua_State *L, int narg);</pre>
4764
 
4765
<p>
4766
Checks whether the function argument <code>narg</code> is a number
4767
and returns this number cast to an <code>int</code>.
4768
 
4769
 
4770
 
4771
 
4772
 
4773
<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3>
4774
<pre>lua_Integer luaL_checkinteger (lua_State *L, int narg);</pre>
4775
 
4776
<p>
4777
Checks whether the function argument <code>narg</code> is a number
4778
and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
4779
 
4780
 
4781
 
4782
 
4783
 
4784
<hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3>
4785
<pre>long luaL_checklong (lua_State *L, int narg);</pre>
4786
 
4787
<p>
4788
Checks whether the function argument <code>narg</code> is a number
4789
and returns this number cast to a <code>long</code>.
4790
 
4791
 
4792
 
4793
 
4794
 
4795
<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3>
4796
<pre>const char *luaL_checklstring (lua_State *L, int narg, size_t *l);</pre>
4797
 
4798
<p>
4799
Checks whether the function argument <code>narg</code> is a string
4800
and returns this string;
4801
if <code>l</code> is not <code>NULL</code> fills <code>*l</code>
4802
with the string's length.
4803
 
4804
 
4805
 
4806
 
4807
 
4808
<hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3>
4809
<pre>lua_Number luaL_checknumber (lua_State *L, int narg);</pre>
4810
 
4811
<p>
4812
Checks whether the function argument <code>narg</code> is a number
4813
and returns this number.
4814
 
4815
 
4816
 
4817
 
4818
 
4819
<hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3>
4820
<pre>int luaL_checkoption (lua_State *L,
4821
                      int narg,
4822
                      const char *def,
4823
                      const char *const lst[]);</pre>
4824
 
4825
<p>
4826
Checks whether the function argument <code>narg</code> is a string and
4827
searches for this string in the array <code>lst</code>
4828
(which must be NULL-terminated).
4829
Returns the index in the array where the string was found.
4830
Raises an error if the argument is not a string or
4831
if the string cannot be found.
4832
 
4833
 
4834
<p>
4835
If <code>def</code> is not <code>NULL</code>,
4836
the function uses <code>def</code> as a default value when
4837
there is no argument <code>narg</code> or if this argument is <b>nil</b>.
4838
 
4839
 
4840
<p>
4841
This is a useful function for mapping strings to C&nbsp;enums.
4842
(The usual convention in Lua libraries is
4843
to use strings instead of numbers to select options.)
4844
 
4845
 
4846
 
4847
 
4848
 
4849
<hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3>
4850
<pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre>
4851
 
4852
<p>
4853
Grows the stack size to <code>top + sz</code> elements,
4854
raising an error if the stack cannot grow to that size.
4855
<code>msg</code> is an additional text to go into the error message.
4856
 
4857
 
4858
 
4859
 
4860
 
4861
<hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3>
4862
<pre>const char *luaL_checkstring (lua_State *L, int narg);</pre>
4863
 
4864
<p>
4865
Checks whether the function argument <code>narg</code> is a string
4866
and returns this string.
4867
 
4868
 
4869
 
4870
 
4871
 
4872
<hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3>
4873
<pre>void luaL_checktype (lua_State *L, int narg, int t);</pre>
4874
 
4875
<p>
4876
Checks whether the function argument <code>narg</code> has type <code>t</code>.
4877
 
4878
 
4879
 
4880
 
4881
 
4882
<hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3>
4883
<pre>void *luaL_checkudata (lua_State *L, int narg, const char *tname);</pre>
4884
 
4885
<p>
4886
Checks whether the function argument <code>narg</code> is a userdata
4887
of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
4888
 
4889
 
4890
 
4891
 
4892
 
4893
<hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3>
4894
<pre>int luaL_dofile (lua_State *L, const char *filename);</pre>
4895
 
4896
<p>
4897
Loads and runs the given file.
4898
It is defined as the following macro:
4899
 
4900
<pre>
4901
     (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
4902
</pre><p>
4903
It returns 0 if there are no errors
4904
or 1 in case of errors.
4905
 
4906
 
4907
 
4908
 
4909
 
4910
<hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3>
4911
<pre>int luaL_dostring (lua_State *L, const char *str);</pre>
4912
 
4913
<p>
4914
Loads and runs the given string.
4915
It is defined as the following macro:
4916
 
4917
<pre>
4918
     (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
4919
</pre><p>
4920
It returns 0 if there are no errors
4921
or 1 in case of errors.
4922
 
4923
 
4924
 
4925
 
4926
 
4927
<hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3>
4928
<pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre>
4929
 
4930
<p>
4931
Raises an error.
4932
The error message format is given by <code>fmt</code>
4933
plus any extra arguments,
4934
following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>.
4935
It also adds at the beginning of the message the file name and
4936
the line number where the error occurred,
4937
if this information is available.
4938
 
4939
 
4940
<p>
4941
This function never returns,
4942
but it is an idiom to use it in C&nbsp;functions
4943
as <code>return luaL_error(<em>args</em>)</code>.
4944
 
4945
 
4946
 
4947
 
4948
 
4949
<hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3>
4950
<pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre>
4951
 
4952
<p>
4953
Pushes onto the stack the field <code>e</code> from the metatable
4954
of the object at index <code>obj</code>.
4955
If the object does not have a metatable,
4956
or if the metatable does not have this field,
4957
returns 0 and pushes nothing.
4958
 
4959
 
4960
 
4961
 
4962
 
4963
<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3>
4964
<pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
4965
 
4966
<p>
4967
Pushes onto the stack the metatable associated with name <code>tname</code>
4968
in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
4969
 
4970
 
4971
 
4972
 
4973
 
4974
<hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3>
4975
<pre>const char *luaL_gsub (lua_State *L,
4976
                       const char *s,
4977
                       const char *p,
4978
                       const char *r);</pre>
4979
 
4980
<p>
4981
Creates a copy of string <code>s</code> by replacing
4982
any occurrence of the string <code>p</code>
4983
with the string <code>r</code>.
4984
Pushes the resulting string on the stack and returns it.
4985
 
4986
 
4987
 
4988
 
4989
 
4990
<hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3>
4991
<pre>int luaL_loadbuffer (lua_State *L,
4992
                     const char *buff,
4993
                     size_t sz,
4994
                     const char *name);</pre>
4995
 
4996
<p>
4997
Loads a buffer as a Lua chunk.
4998
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the
4999
buffer pointed to by <code>buff</code> with size <code>sz</code>.
5000
 
5001
 
5002
<p>
5003
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5004
<code>name</code> is the chunk name,
5005
used for debug information and error messages.
5006
 
5007
 
5008
 
5009
 
5010
 
5011
<hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3>
5012
<pre>int luaL_loadfile (lua_State *L, const char *filename);</pre>
5013
 
5014
<p>
5015
Loads a file as a Lua chunk.
5016
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file
5017
named <code>filename</code>.
5018
If <code>filename</code> is <code>NULL</code>,
5019
then it loads from the standard input.
5020
The first line in the file is ignored if it starts with a <code>#</code>.
5021
 
5022
 
5023
<p>
5024
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>,
5025
but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a>
5026
if it cannot open/read the file.
5027
 
5028
 
5029
<p>
5030
As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5031
it does not run it.
5032
 
5033
 
5034
 
5035
 
5036
 
5037
<hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3>
5038
<pre>int luaL_loadstring (lua_State *L, const char *s);</pre>
5039
 
5040
<p>
5041
Loads a string as a Lua chunk.
5042
This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in
5043
the zero-terminated string <code>s</code>.
5044
 
5045
 
5046
<p>
5047
This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>.
5048
 
5049
 
5050
<p>
5051
Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk;
5052
it does not run it.
5053
 
5054
 
5055
 
5056
 
5057
 
5058
<hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3>
5059
<pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre>
5060
 
5061
<p>
5062
If the registry already has the key <code>tname</code>,
5063
returns 0.
5064
Otherwise,
5065
creates a new table to be used as a metatable for userdata,
5066
adds it to the registry with key <code>tname</code>,
5067
and returns 1.
5068
 
5069
 
5070
<p>
5071
In both cases pushes onto the stack the final value associated
5072
with <code>tname</code> in the registry.
5073
 
5074
 
5075
 
5076
 
5077
 
5078
<hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3>
5079
<pre>lua_State *luaL_newstate (void);</pre>
5080
 
5081
<p>
5082
Creates a new Lua state, calling <a href="#lua_newstate"><code>lua_newstate</code></a> with an
5083
allocation function based on the standard&nbsp;C <code>realloc</code> function
5084
and setting a panic function (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) that prints
5085
an error message to the standard error output in case of fatal
5086
errors.
5087
 
5088
 
5089
<p>
5090
Returns the new state,
5091
or <code>NULL</code> if there is a memory allocation error.
5092
 
5093
 
5094
 
5095
 
5096
 
5097
<hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3>
5098
<pre>void luaL_openlibs (lua_State *L);</pre>
5099
 
5100
<p>
5101
Opens all standard Lua libraries into the given state.
5102
 
5103
 
5104
 
5105
 
5106
 
5107
<hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3>
5108
<pre>int luaL_optint (lua_State *L, int narg, int d);</pre>
5109
 
5110
<p>
5111
If the function argument <code>narg</code> is a number,
5112
returns this number cast to an <code>int</code>.
5113
If this argument is absent or is <b>nil</b>,
5114
returns <code>d</code>.
5115
Otherwise, raises an error.
5116
 
5117
 
5118
 
5119
 
5120
 
5121
<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3>
5122
<pre>lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);</pre>
5123
 
5124
<p>
5125
If the function argument <code>narg</code> is a number,
5126
returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
5127
If this argument is absent or is <b>nil</b>,
5128
returns <code>d</code>.
5129
Otherwise, raises an error.
5130
 
5131
 
5132
 
5133
 
5134
 
5135
<hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3>
5136
<pre>long luaL_optlong (lua_State *L, int narg, long d);</pre>
5137
 
5138
<p>
5139
If the function argument <code>narg</code> is a number,
5140
returns this number cast to a <code>long</code>.
5141
If this argument is absent or is <b>nil</b>,
5142
returns <code>d</code>.
5143
Otherwise, raises an error.
5144
 
5145
 
5146
 
5147
 
5148
 
5149
<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3>
5150
<pre>const char *luaL_optlstring (lua_State *L,
5151
                             int narg,
5152
                             const char *d,
5153
                             size_t *l);</pre>
5154
 
5155
<p>
5156
If the function argument <code>narg</code> is a string,
5157
returns this string.
5158
If this argument is absent or is <b>nil</b>,
5159
returns <code>d</code>.
5160
Otherwise, raises an error.
5161
 
5162
 
5163
<p>
5164
If <code>l</code> is not <code>NULL</code>,
5165
fills the position <code>*l</code> with the results's length.
5166
 
5167
 
5168
 
5169
 
5170
 
5171
<hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3>
5172
<pre>lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);</pre>
5173
 
5174
<p>
5175
If the function argument <code>narg</code> is a number,
5176
returns this number.
5177
If this argument is absent or is <b>nil</b>,
5178
returns <code>d</code>.
5179
Otherwise, raises an error.
5180
 
5181
 
5182
 
5183
 
5184
 
5185
<hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3>
5186
<pre>const char *luaL_optstring (lua_State *L, int narg, const char *d);</pre>
5187
 
5188
<p>
5189
If the function argument <code>narg</code> is a string,
5190
returns this string.
5191
If this argument is absent or is <b>nil</b>,
5192
returns <code>d</code>.
5193
Otherwise, raises an error.
5194
 
5195
 
5196
 
5197
 
5198
 
5199
<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3>
5200
<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
5201
 
5202
<p>
5203
Returns an address to a space of size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>
5204
where you can copy a string to be added to buffer <code>B</code>
5205
(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5206
After copying the string into this space you must call
5207
<a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add 
5208
it to the buffer.
5209
 
5210
 
5211
 
5212
 
5213
 
5214
<hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3>
5215
<pre>void luaL_pushresult (luaL_Buffer *B);</pre>
5216
 
5217
<p>
5218
Finishes the use of buffer <code>B</code> leaving the final string on
5219
the top of the stack.
5220
 
5221
 
5222
 
5223
 
5224
 
5225
<hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3>
5226
<pre>int luaL_ref (lua_State *L, int t);</pre>
5227
 
5228
<p>
5229
Creates and returns a <em>reference</em>,
5230
in the table at index <code>t</code>,
5231
for the object at the top of the stack (and pops the object).
5232
 
5233
 
5234
<p>
5235
A reference is a unique integer key.
5236
As long as you do not manually add integer keys into table <code>t</code>,
5237
<a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns.
5238
You can retrieve an object referred by reference <code>r</code>
5239
by calling <code>lua_rawgeti(L, t, r)</code>.
5240
Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object.
5241
 
5242
 
5243
<p>
5244
If the object at the top of the stack is <b>nil</b>,
5245
<a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>.
5246
The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different
5247
from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>.
5248
 
5249
 
5250
 
5251
 
5252
 
5253
<hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3>
5254
<pre>typedef struct luaL_Reg {
5255
  const char *name;
5256
  lua_CFunction func;
5257
} luaL_Reg;</pre>
5258
 
5259
<p>
5260
Type for arrays of functions to be registered by
5261
<a href="#luaL_register"><code>luaL_register</code></a>.
5262
<code>name</code> is the function name and <code>func</code> is a pointer to
5263
the function.
5264
Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
5265
in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
5266
 
5267
 
5268
 
5269
 
5270
 
5271
<hr><h3><a name="luaL_register"><code>luaL_register</code></a></h3>
5272
<pre>void luaL_register (lua_State *L,
5273
                    const char *libname,
5274
                    const luaL_Reg *l);</pre>
5275
 
5276
<p>
5277
Opens a library.
5278
 
5279
 
5280
<p>
5281
When called with <code>libname</code> equal to <code>NULL</code>,
5282
it simply registers all functions in the list <code>l</code>
5283
(see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack.
5284
 
5285
 
5286
<p>
5287
When called with a non-null <code>libname</code>,
5288
creates a new table <code>t</code>,
5289
sets it as the value of the global variable <code>libname</code>,
5290
sets it as the value of <code>package.loaded[libname]</code>,
5291
and registers on it all functions in the list <code>l</code>.
5292
If there is a table in <code>package.loaded[libname]</code> or in
5293
variable <code>libname</code>,
5294
reuses this table instead of creating a new one.
5295
 
5296
 
5297
<p>
5298
In any case the function leaves the table
5299
on the top of the stack.
5300
 
5301
 
5302
 
5303
 
5304
 
5305
<hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3>
5306
<pre>const char *luaL_typename (lua_State *L, int idx);</pre>
5307
 
5308
<p>
5309
Returns the name of the type of the value at index <code>idx</code>.
5310
 
5311
 
5312
 
5313
 
5314
 
5315
<hr><h3><a name="luaL_typerror"><code>luaL_typerror</code></a></h3>
5316
<pre>int luaL_typerror (lua_State *L, int narg, const char *tname);</pre>
5317
 
5318
<p>
5319
Generates an error with a message like
5320
 
5321
<pre>
5322
     &lt;location&gt;: bad argument &lt;narg&gt; to &lt;function&gt; (&lt;tname&gt; expected, got &lt;realt&gt;)
5323
</pre><p>
5324
where <code>&lt;location&gt;</code> is produced by <a href="#luaL_where"><code>luaL_where</code></a>,
5325
<code>&lt;function&gt;</code> is the name of the current function,
5326
and <code>&lt;realt&gt;</code> is the type name of the actual argument.
5327
 
5328
 
5329
 
5330
 
5331
 
5332
<hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3>
5333
<pre>void luaL_unref (lua_State *L, int t, int ref);</pre>
5334
 
5335
<p>
5336
Releases reference <code>ref</code> from the table at index <code>t</code>
5337
(see <a href="#luaL_ref"><code>luaL_ref</code></a>).
5338
The entry is removed from the table,
5339
so that the referred object can be collected.
5340
The reference <code>ref</code> is also freed to be used again.
5341
 
5342
 
5343
<p>
5344
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>,
5345
<a href="#luaL_unref"><code>luaL_unref</code></a> does nothing.
5346
 
5347
 
5348
 
5349
 
5350
 
5351
<hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3>
5352
<pre>void luaL_where (lua_State *L, int lvl);</pre>
5353
 
5354
<p>
5355
Pushes onto the stack a string identifying the current position
5356
of the control at level <code>lvl</code> in the call stack.
5357
Typically this string has the format <code>&lt;chunkname&gt;:&lt;currentline&gt;:</code>.
5358
Level&nbsp;0 is the running function,
5359
level&nbsp;1 is the function that called the running function,
5360
etc.
5361
 
5362
 
5363
<p>
5364
This function is used to build a prefix for error messages.
5365
 
5366
 
5367
 
5368
 
5369
 
5370
 
5371
 
5372
<h1>5 - <a name="5">Standard Libraries</a></h1>
5373
 
5374
<p>
5375
The standard Lua libraries provide useful functions
5376
that are implemented directly through the C&nbsp;API.
5377
Some of these functions provide essential services to the language
5378
(e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>);
5379
others provide access to "outside" services (e.g., I/O);
5380
and others could be implemented in Lua itself,
5381
but are quite useful or have critical performance requirements that
5382
deserve an implementation in C (e.g., <code>sort</code>).
5383
 
5384
 
5385
<p>
5386
All libraries are implemented through the official C&nbsp;API
5387
and are provided as separate C&nbsp;modules.
5388
Currently, Lua has the following standard libraries:
5389
 
5390
<ul>
5391
 
5392
<li>basic library;</li>
5393
 
5394
<li>package library;</li>
5395
 
5396
<li>string manipulation;</li>
5397
 
5398
<li>table manipulation;</li>
5399
 
5400
<li>mathematical functions (sin, log, etc.);</li>
5401
 
5402
<li>input and output;</li>
5403
 
5404
<li>operating system facilities;</li>
5405
 
5406
<li>debug facilities.</li>
5407
 
5408
</ul><p>
5409
Except for the basic and package libraries,
5410
each library provides all its functions as fields of a global table
5411
or as methods of its objects.
5412
 
5413
 
5414
<p>
5415
To have access to these libraries,
5416
the C&nbsp;host program must call
5417
<a href="#luaL_openlibs"><code>luaL_openlibs</code></a>,
5418
which open all standard libraries.
5419
Alternatively,
5420
it can open them individually by calling
5421
<a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library),
5422
<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
5423
<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
5424
<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
5425
<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
5426
<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O and the Operating System libraries),
5427
and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
5428
These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>
5429
and should not be called directly:
5430
you must call them like any other Lua C&nbsp;function,
5431
e.g., by using <a href="#lua_call"><code>lua_call</code></a>.
5432
 
5433
 
5434
 
5435
<h2>5.1 - <a name="5.1">Basic Functions</a></h2>
5436
 
5437
<p>
5438
The basic library provides some core functions to Lua.
5439
If you do not include this library in your application,
5440
you should check carefully whether you need to provide 
5441
implementations for some of its facilities.
5442
 
5443
 
5444
<p>
5445
<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
5446
Issues an  error when
5447
the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
5448
otherwise, returns all its arguments.
5449
<code>message</code> is an error message;
5450
when absent, it defaults to "assertion failed!"
5451
 
5452
 
5453
 
5454
 
5455
<p>
5456
<hr><h3><a name="pdf-collectgarbage"><code>collectgarbage (opt [, arg])</code></a></h3>
5457
 
5458
 
5459
<p>
5460
This function is a generic interface to the garbage collector.
5461
It performs different functions according to its first argument, <code>opt</code>:
5462
 
5463
<ul>
5464
 
5465
<li><b>"stop":</b>
5466
stops the garbage collector.
5467
</li>
5468
 
5469
<li><b>"restart":</b>
5470
restarts the garbage collector.
5471
</li>
5472
 
5473
<li><b>"collect":</b>
5474
performs a full garbage-collection cycle.
5475
</li>
5476
 
5477
<li><b>"count":</b>
5478
returns the total memory in use by Lua (in Kbytes).
5479
</li>
5480
 
5481
<li><b>"step":</b>
5482
performs a garbage-collection step.
5483
The step "size" is controlled by <code>arg</code>
5484
(larger values mean more steps) in a non-specified way.
5485
If you want to control the step size
5486
you must experimentally tune the value of <code>arg</code>.
5487
Returns <b>true</b> if the step finished a collection cycle.
5488
</li>
5489
 
5490
<li><b>"setpause":</b>
5491
sets <code>arg</code>/100 as the new value for the <em>pause</em> of
5492
the collector (see <a href="#2.10">&sect;2.10</a>).
5493
</li>
5494
 
5495
<li><b>"setstepmul":</b>
5496
sets <code>arg</code>/100 as the new value for the <em>step multiplier</em> of
5497
the collector (see <a href="#2.10">&sect;2.10</a>).
5498
</li>
5499
 
5500
</ul>
5501
 
5502
 
5503
 
5504
<p>
5505
<hr><h3><a name="pdf-dofile"><code>dofile (filename)</code></a></h3>
5506
Opens the named file and executes its contents as a Lua chunk.
5507
When called without arguments,
5508
<code>dofile</code> executes the contents of the standard input (<code>stdin</code>).
5509
Returns all values returned by the chunk.
5510
In case of errors, <code>dofile</code> propagates the error
5511
to its caller (that is, <code>dofile</code> does not run in protected mode).
5512
 
5513
 
5514
 
5515
 
5516
<p>
5517
<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
5518
Terminates the last protected function called
5519
and returns <code>message</code> as the error message.
5520
Function <code>error</code> never returns.
5521
 
5522
 
5523
<p>
5524
Usually, <code>error</code> adds some information about the error position
5525
at the beginning of the message.
5526
The <code>level</code> argument specifies how to get the error position.
5527
With level&nbsp;1 (the default), the error position is where the
5528
<code>error</code> function was called.
5529
Level&nbsp;2 points the error to where the function
5530
that called <code>error</code> was called; and so on.
5531
Passing a level&nbsp;0 avoids the addition of error position information
5532
to the message.
5533
 
5534
 
5535
 
5536
 
5537
<p>
5538
<hr><h3><a name="pdf-_G"><code>_G</code></a></h3>
5539
A global variable (not a function) that
5540
holds the global environment (that is, <code>_G._G = _G</code>).
5541
Lua itself does not use this variable;
5542
changing its value does not affect any environment,
5543
nor vice-versa.
5544
(Use <a href="#pdf-setfenv"><code>setfenv</code></a> to change environments.)
5545
 
5546
 
5547
 
5548
 
5549
<p>
5550
<hr><h3><a name="pdf-getfenv"><code>getfenv (f)</code></a></h3>
5551
Returns the current environment in use by the function.
5552
<code>f</code> can be a Lua function or a number
5553
that specifies the function at that stack level:
5554
Level&nbsp;1 is the function calling <code>getfenv</code>.
5555
If the given function is not a Lua function,
5556
or if <code>f</code> is 0,
5557
<code>getfenv</code> returns the global environment.
5558
The default for <code>f</code> is 1.
5559
 
5560
 
5561
 
5562
 
5563
<p>
5564
<hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3>
5565
 
5566
 
5567
<p>
5568
If <code>object</code> does not have a metatable, returns <b>nil</b>.
5569
Otherwise,
5570
if the object's metatable has a <code>"__metatable"</code> field,
5571
returns the associated value.
5572
Otherwise, returns the metatable of the given object.
5573
 
5574
 
5575
 
5576
 
5577
<p>
5578
<hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3>
5579
 
5580
 
5581
<p>
5582
Returns three values: an iterator function, the table <code>t</code>, and 0,
5583
so that the construction
5584
 
5585
<pre>
5586
     for i,v in ipairs(t) do <em>body</em> end
5587
</pre><p>
5588
will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), &middot;&middot;&middot;,
5589
up to the first integer key absent from the table.
5590
 
5591
 
5592
<p>
5593
See <a href="#pdf-next"><code>next</code></a> for the caveats of modifying the table during its traversal.
5594
 
5595
 
5596
 
5597
 
5598
<p>
5599
<hr><h3><a name="pdf-load"><code>load (func [, chunkname])</code></a></h3>
5600
 
5601
 
5602
<p>
5603
Loads a chunk using function <code>func</code> to get its pieces.
5604
Each call to <code>func</code> must return a string that concatenates
5605
with previous results.
5606
A return of <b>nil</b> (or no value) signals the end of the chunk.
5607
 
5608
 
5609
<p>
5610
If there are no errors, 
5611
returns the compiled chunk as a function;
5612
otherwise, returns <b>nil</b> plus the error message.
5613
The environment of the returned function is the global environment.
5614
 
5615
 
5616
<p>
5617
<code>chunkname</code> is used as the chunk name for error messages
5618
and debug information.
5619
 
5620
 
5621
 
5622
 
5623
<p>
5624
<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename])</code></a></h3>
5625
 
5626
 
5627
<p>
5628
Similar to <a href="#pdf-load"><code>load</code></a>,
5629
but gets the chunk from file <code>filename</code>
5630
or from the standard input,
5631
if no file name is given.
5632
 
5633
 
5634
 
5635
 
5636
<p>
5637
<hr><h3><a name="pdf-loadstring"><code>loadstring (string [, chunkname])</code></a></h3>
5638
 
5639
 
5640
<p>
5641
Similar to <a href="#pdf-load"><code>load</code></a>,
5642
but gets the chunk from the given string.
5643
 
5644
 
5645
<p>
5646
To load and run a given string, use the idiom
5647
 
5648
<pre>
5649
     assert(loadstring(s))()
5650
</pre>
5651
 
5652
 
5653
 
5654
<p>
5655
<hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3>
5656
 
5657
 
5658
<p>
5659
Allows a program to traverse all fields of a table.
5660
Its first argument is a table and its second argument
5661
is an index in this table.
5662
<code>next</code> returns the next index of the table
5663
and its associated value.
5664
When called with <b>nil</b> as its second argument,
5665
<code>next</code> returns an initial index
5666
and its associated value.
5667
When called with the last index,
5668
or with <b>nil</b> in an empty table,
5669
<code>next</code> returns <b>nil</b>.
5670
If the second argument is absent, then it is interpreted as <b>nil</b>.
5671
In particular,
5672
you can use <code>next(t)</code> to check whether a table is empty.
5673
 
5674
 
5675
<p>
5676
The order in which the indices are enumerated is not specified,
5677
<em>even for numeric indices</em>.
5678
(To traverse a table in numeric order,
5679
use a numerical <b>for</b> or the <a href="#pdf-ipairs"><code>ipairs</code></a> function.)
5680
 
5681
 
5682
<p>
5683
The behavior of <code>next</code> is <em>undefined</em> if,
5684
during the traversal,
5685
you assign any value to a non-existent field in the table.
5686
You may however modify existing fields.
5687
In particular, you may clear existing fields.
5688
 
5689
 
5690
 
5691
 
5692
<p>
5693
<hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3>
5694
 
5695
 
5696
<p>
5697
Returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>,
5698
so that the construction
5699
 
5700
<pre>
5701
     for k,v in pairs(t) do <em>body</em> end
5702
</pre><p>
5703
will iterate over all key&ndash;value pairs of table <code>t</code>.
5704
 
5705
 
5706
<p>
5707
See <a href="#pdf-next"><code>next</code></a> for the caveats of modifying the table during its traversal.
5708
 
5709
 
5710
 
5711
 
5712
<p>
5713
<hr><h3><a name="pdf-pcall"><code>pcall (f, arg1, &middot;&middot;&middot;)</code></a></h3>
5714
 
5715
 
5716
<p>
5717
Calls function <code>f</code> with
5718
the given arguments in <em>protected mode</em>.
5719
This means that any error inside&nbsp;<code>f</code> is not propagated;
5720
instead, <code>pcall</code> catches the error
5721
and returns a status code.
5722
Its first result is the status code (a boolean),
5723
which is true if the call succeeds without errors.
5724
In such case, <code>pcall</code> also returns all results from the call,
5725
after this first result.
5726
In case of any error, <code>pcall</code> returns <b>false</b> plus the error message.
5727
 
5728
 
5729
 
5730
 
5731
<p>
5732
<hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3>
5733
Receives any number of arguments,
5734
and prints their values to <code>stdout</code>,
5735
using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert them to strings.
5736
<code>print</code> is not intended for formatted output,
5737
but only as a quick way to show a value,
5738
typically for debugging.
5739
For formatted output, use <a href="#pdf-string.format"><code>string.format</code></a>.
5740
 
5741
 
5742
 
5743
 
5744
<p>
5745
<hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3>
5746
Checks whether <code>v1</code> is equal to <code>v2</code>,
5747
without invoking any metamethod.
5748
Returns a boolean.
5749
 
5750
 
5751
 
5752
 
5753
<p>
5754
<hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3>
5755
Gets the real value of <code>table[index]</code>,
5756
without invoking any metamethod.
5757
<code>table</code> must be a table;
5758
<code>index</code> may be any value.
5759
 
5760
 
5761
 
5762
 
5763
<p>
5764
<hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3>
5765
Sets the real value of <code>table[index]</code> to <code>value</code>,
5766
without invoking any metamethod.
5767
<code>table</code> must be a table,
5768
<code>index</code> any value different from <b>nil</b>,
5769
and <code>value</code> any Lua value.
5770
 
5771
 
5772
<p>
5773
This function returns <code>table</code>.
5774
 
5775
 
5776
 
5777
 
5778
<p>
5779
<hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3>
5780
 
5781
 
5782
<p>
5783
If <code>index</code> is a number,
5784
returns all arguments after argument number <code>index</code>.
5785
Otherwise, <code>index</code> must be the string <code>"#"</code>,
5786
and <code>select</code> returns the total number of extra arguments it received.
5787
 
5788
 
5789
 
5790
 
5791
<p>
5792
<hr><h3><a name="pdf-setfenv"><code>setfenv (f, table)</code></a></h3>
5793
 
5794
 
5795
<p>
5796
Sets the environment to be used by the given function.
5797
<code>f</code> can be a Lua function or a number
5798
that specifies the function at that stack level:
5799
Level&nbsp;1 is the function calling <code>setfenv</code>.
5800
<code>setfenv</code> returns the given function.
5801
 
5802
 
5803
<p>
5804
As a special case, when <code>f</code> is 0 <code>setfenv</code> changes
5805
the environment of the running thread.
5806
In this case, <code>setfenv</code> returns no values.
5807
 
5808
 
5809
 
5810
 
5811
<p>
5812
<hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3>
5813
 
5814
 
5815
<p>
5816
Sets the metatable for the given table.
5817
(You cannot change the metatable of other types from Lua, only from&nbsp;C.)
5818
If <code>metatable</code> is <b>nil</b>,
5819
removes the metatable of the given table.
5820
If the original metatable has a <code>"__metatable"</code> field,
5821
raises an error.
5822
 
5823
 
5824
<p>
5825
This function returns <code>table</code>.
5826
 
5827
 
5828
 
5829
 
5830
<p>
5831
<hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3>
5832
Tries to convert its argument to a number.
5833
If the argument is already a number or a string convertible
5834
to a number, then <code>tonumber</code> returns this number;
5835
otherwise, it returns <b>nil</b>.
5836
 
5837
 
5838
<p>
5839
An optional argument specifies the base to interpret the numeral.
5840
The base may be any integer between 2 and 36, inclusive.
5841
In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
5842
represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth,
5843
with '<code>Z</code>' representing 35.
5844
In base 10 (the default), the number may have a decimal part,
5845
as well as an optional exponent part (see <a href="#2.1">&sect;2.1</a>).
5846
In other bases, only unsigned integers are accepted.
5847
 
5848
 
5849
 
5850
 
5851
<p>
5852
<hr><h3><a name="pdf-tostring"><code>tostring (e)</code></a></h3>
5853
Receives an argument of any type and
5854
converts it to a string in a reasonable format.
5855
For complete control of how numbers are converted,
5856
use <a href="#pdf-string.format"><code>string.format</code></a>.
5857
 
5858
 
5859
<p>
5860
If the metatable of <code>e</code> has a <code>"__tostring"</code> field,
5861
then <code>tostring</code> calls the corresponding value
5862
with <code>e</code> as argument,
5863
and uses the result of the call as its result.
5864
 
5865
 
5866
 
5867
 
5868
<p>
5869
<hr><h3><a name="pdf-type"><code>type (v)</code></a></h3>
5870
Returns the type of its only argument, coded as a string.
5871
The possible results of this function are
5872
"<code>nil</code>" (a string, not the value <b>nil</b>),
5873
"<code>number</code>",
5874
"<code>string</code>",
5875
"<code>boolean</code>",
5876
"<code>table</code>",
5877
"<code>function</code>",
5878
"<code>thread</code>",
5879
and "<code>userdata</code>".
5880
 
5881
 
5882
 
5883
 
5884
<p>
5885
<hr><h3><a name="pdf-unpack"><code>unpack (list [, i [, j]])</code></a></h3>
5886
Returns the elements from the given table.
5887
This function is equivalent to
5888
 
5889
<pre>
5890
     return list[i], list[i+1], &middot;&middot;&middot;, list[j]
5891
</pre><p>
5892
except that the above code can be written only for a fixed number
5893
of elements.
5894
By default, <code>i</code> is&nbsp;1 and <code>j</code> is the length of the list,
5895
as defined by the length operator (see <a href="#2.5.5">&sect;2.5.5</a>).
5896
 
5897
 
5898
 
5899
 
5900
<p>
5901
<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
5902
A global variable (not a function) that
5903
holds a string containing the current interpreter version.
5904
The current contents of this variable is "<code>Lua 5.1</code>".
5905
 
5906
 
5907
 
5908
 
5909
<p>
5910
<hr><h3><a name="pdf-xpcall"><code>xpcall (f, err)</code></a></h3>
5911
 
5912
 
5913
<p>
5914
This function is similar to <code>pcall</code>,
5915
except that you can set a new error handler.
5916
 
5917
 
5918
<p>
5919
<code>xpcall</code> calls function <code>f</code> in protected mode,
5920
using <code>err</code> as the error handler.
5921
Any error inside <code>f</code> is not propagated;
5922
instead, <code>xpcall</code> catches the error,
5923
calls the <code>err</code> function with the original error object,
5924
and returns a status code.
5925
Its first result is the status code (a boolean),
5926
which is true if the call succeeds without errors.
5927
In this case, <code>xpcall</code> also returns all results from the call,
5928
after this first result.
5929
In case of any error,
5930
<code>xpcall</code> returns <b>false</b> plus the result from <code>err</code>.
5931
 
5932
 
5933
 
5934
 
5935
 
5936
 
5937
 
5938
<h2>5.2 - <a name="5.2">Coroutine Manipulation</a></h2>
5939
 
5940
<p>
5941
The operations related to coroutines comprise a sub-library of
5942
the basic library and come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>.
5943
See <a href="#2.11">&sect;2.11</a> for a general description of coroutines.
5944
 
5945
 
5946
<p>
5947
<hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3>
5948
 
5949
 
5950
<p>
5951
Creates a new coroutine, with body <code>f</code>.
5952
<code>f</code> must be a Lua function.
5953
Returns this new coroutine,
5954
an object with type <code>"thread"</code>.
5955
 
5956
 
5957
 
5958
 
5959
<p>
5960
<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
5961
 
5962
 
5963
<p>
5964
Starts or continues the execution of coroutine <code>co</code>.
5965
The first time you resume a coroutine,
5966
it starts running its body.
5967
The values <code>val1</code>, &middot;&middot;&middot; are passed
5968
as the arguments to the body function.
5969
If the coroutine has yielded,
5970
<code>resume</code> restarts it;
5971
the values <code>val1</code>, &middot;&middot;&middot; are passed
5972
as the results from the yield.
5973
 
5974
 
5975
<p>
5976
If the coroutine runs without any errors,
5977
<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
5978
(if the coroutine yields) or any values returned by the body function
5979
(if the coroutine terminates).
5980
If there is any error,
5981
<code>resume</code> returns <b>false</b> plus the error message.
5982
 
5983
 
5984
 
5985
 
5986
<p>
5987
<hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3>
5988
 
5989
 
5990
<p>
5991
Returns the running coroutine,
5992
or <b>nil</b> when called by the main thread.
5993
 
5994
 
5995
 
5996
 
5997
<p>
5998
<hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3>
5999
 
6000
 
6001
<p>
6002
Returns the status of coroutine <code>co</code>, as a string:
6003
<code>"running"</code>,
6004
if the coroutine is running (that is, it called <code>status</code>);
6005
<code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>,
6006
or if it has not started running yet;
6007
<code>"normal"</code> if the coroutine is active but not running
6008
(that is, it has resumed another coroutine);
6009
and <code>"dead"</code> if the coroutine has finished its body function,
6010
or if it has stopped with an error.
6011
 
6012
 
6013
 
6014
 
6015
<p>
6016
<hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3>
6017
 
6018
 
6019
<p>
6020
Creates a new coroutine, with body <code>f</code>.
6021
<code>f</code> must be a Lua function.
6022
Returns a function that resumes the coroutine each time it is called.
6023
Any arguments passed to the function behave as the
6024
extra arguments to <code>resume</code>.
6025
Returns the same values returned by <code>resume</code>,
6026
except the first boolean.
6027
In case of error, propagates the error.
6028
 
6029
 
6030
 
6031
 
6032
<p>
6033
<hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3>
6034
 
6035
 
6036
<p>
6037
Suspends the execution of the calling coroutine.
6038
The coroutine cannot be running a C&nbsp;function,
6039
a metamethod, or an iterator.
6040
Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>.
6041
 
6042
 
6043
 
6044
 
6045
 
6046
 
6047
 
6048
<h2>5.3 - <a name="5.3">Modules</a></h2>
6049
 
6050
<p>
6051
The package library provides basic
6052
facilities for loading and building modules in Lua.
6053
It exports two of its functions directly in the global environment:
6054
<a href="#pdf-require"><code>require</code></a> and <a href="#pdf-module"><code>module</code></a>.
6055
Everything else is exported in a table <a name="pdf-package"><code>package</code></a>.
6056
 
6057
 
6058
<p>
6059
<hr><h3><a name="pdf-module"><code>module (name [, &middot;&middot;&middot;])</code></a></h3>
6060
 
6061
 
6062
<p>
6063
Creates a module.
6064
If there is a table in <code>package.loaded[name]</code>,
6065
this table is the module.
6066
Otherwise, if there is a global table <code>t</code> with the given name,
6067
this table is the module.
6068
Otherwise creates a new table <code>t</code> and
6069
sets it as the value of the global <code>name</code> and
6070
the value of <code>package.loaded[name]</code>.
6071
This function also initializes <code>t._NAME</code> with the given name,
6072
<code>t._M</code> with the module (<code>t</code> itself),
6073
and <code>t._PACKAGE</code> with the package name
6074
(the full module name minus last component; see below).
6075
Finally, <code>module</code> sets <code>t</code> as the new environment
6076
of the current function and the new value of <code>package.loaded[name]</code>,
6077
so that <a href="#pdf-require"><code>require</code></a> returns <code>t</code>.
6078
 
6079
 
6080
<p>
6081
If <code>name</code> is a compound name
6082
(that is, one with components separated by dots),
6083
<code>module</code> creates (or reuses, if they already exist)
6084
tables for each component.
6085
For instance, if <code>name</code> is <code>a.b.c</code>,
6086
then <code>module</code> stores the module table in field <code>c</code> of
6087
field <code>b</code> of global <code>a</code>.
6088
 
6089
 
6090
<p>
6091
This function may receive optional <em>options</em> after
6092
the module name,
6093
where each option is a function to be applied over the module.
6094
 
6095
 
6096
 
6097
 
6098
<p>
6099
<hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3>
6100
 
6101
 
6102
<p>
6103
Loads the given module.
6104
The function starts by looking into the table <a href="#pdf-package.loaded"><code>package.loaded</code></a>
6105
to determine whether <code>modname</code> is already loaded.
6106
If it is, then <code>require</code> returns the value stored
6107
at <code>package.loaded[modname]</code>.
6108
Otherwise, it tries to find a <em>loader</em> for the module.
6109
 
6110
 
6111
<p>
6112
To find a loader,
6113
first <code>require</code> queries <code>package.preload[modname]</code>.
6114
If it has a value,
6115
this value (which should be a function) is the loader.
6116
Otherwise <code>require</code> searches for a Lua loader using the
6117
path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
6118
If that also fails, it searches for a C&nbsp;loader using the
6119
path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>.
6120
If that also fails,
6121
it tries an <em>all-in-one</em> loader (see below).
6122
 
6123
 
6124
<p>
6125
When loading a C&nbsp;library,
6126
<code>require</code> first uses a dynamic link facility to link the
6127
application with the library.
6128
Then it tries to find a C&nbsp;function inside this library to
6129
be used as the loader.
6130
The name of this C&nbsp;function is the string "<code>luaopen_</code>"
6131
concatenated with a copy of the module name where each dot
6132
is replaced by an underscore.
6133
Moreover, if the module name has a hyphen,
6134
its prefix up to (and including) the first hyphen is removed.
6135
For instance, if the module name is <code>a.v1-b.c</code>,
6136
the function name will be <code>luaopen_b_c</code>.
6137
 
6138
 
6139
<p>
6140
If <code>require</code> finds neither a Lua library nor a
6141
C&nbsp;library for a module,
6142
it calls the <em>all-in-one loader</em>.
6143
This loader searches the C&nbsp;path for a library for
6144
the root name of the given module.
6145
For instance, when requiring <code>a.b.c</code>,
6146
it will search for a C&nbsp;library for <code>a</code>.
6147
If found, it looks into it for an open function for
6148
the submodule;
6149
in our example, that would be <code>luaopen_a_b_c</code>.
6150
With this facility, a package can pack several C&nbsp;submodules
6151
into one single library,
6152
with each submodule keeping its original open function.
6153
 
6154
 
6155
<p>
6156
Once a loader is found,
6157
<code>require</code> calls the loader with a single argument, <code>modname</code>.
6158
If the loader returns any value,
6159
<code>require</code> assigns it to <code>package.loaded[modname]</code>.
6160
If the loader returns no value and
6161
has not assigned any value to <code>package.loaded[modname]</code>,
6162
then <code>require</code> assigns <b>true</b> to this entry.
6163
In any case, <code>require</code> returns the
6164
final value of <code>package.loaded[modname]</code>.
6165
 
6166
 
6167
<p>
6168
If there is any error loading or running the module,
6169
or if it cannot find any loader for the module,
6170
then <code>require</code> signals an error. 
6171
 
6172
 
6173
 
6174
 
6175
<p>
6176
<hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3>
6177
 
6178
 
6179
<p>
6180
The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader.
6181
 
6182
 
6183
<p>
6184
Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
6185
it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
6186
using the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
6187
(plus another default path defined in <code>luaconf.h</code>).
6188
 
6189
 
6190
 
6191
 
6192
<p>
6193
<hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3>
6194
 
6195
 
6196
<p>
6197
A table used by <a href="#pdf-require"><code>require</code></a> to control which
6198
modules are already loaded.
6199
When you require a module <code>modname</code> and
6200
<code>package.loaded[modname]</code> is not false,
6201
<a href="#pdf-require"><code>require</code></a> simply returns the value stored there.
6202
 
6203
 
6204
 
6205
 
6206
<p>
6207
<hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3>
6208
 
6209
 
6210
<p>
6211
Dynamically links the host program with the C&nbsp;library <code>libname</code>.
6212
Inside this library, looks for a function <code>funcname</code>
6213
and returns this function as a C&nbsp;function.
6214
(So, <code>funcname</code> must follow the protocol (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>)).
6215
 
6216
 
6217
<p>
6218
This is a low-level function.
6219
It completely bypasses the package and module system.
6220
Unlike <a href="#pdf-require"><code>require</code></a>,
6221
it does not perform any path searching and
6222
does not automatically adds extensions.
6223
<code>libname</code> must be the complete file name of the C&nbsp;library,
6224
including if necessary a path and extension.
6225
<code>funcname</code> must be the exact name exported by the C&nbsp;library
6226
(which may depend on the C&nbsp;compiler and linker used).
6227
 
6228
 
6229
<p>
6230
This function is not supported by ANSI C.
6231
As such, it is only available on some platforms
6232
(Windows, Linux, Mac OS X, Solaris, BSD,
6233
plus other Unix systems that support the <code>dlfcn</code> standard).
6234
 
6235
 
6236
 
6237
 
6238
<p>
6239
<hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3>
6240
 
6241
 
6242
<p>
6243
The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader.
6244
 
6245
 
6246
<p>
6247
At start-up, Lua initializes this variable with
6248
the value of the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
6249
with a default path defined in <code>luaconf.h</code>,
6250
if the environment variable is not defined.
6251
Any "<code>;;</code>" in the value of the environment variable
6252
is replaced by the default path.
6253
 
6254
 
6255
<p>
6256
A path is a sequence of <em>templates</em> separated by semicolons.
6257
For each template, <a href="#pdf-require"><code>require</code></a> will change each interrogation
6258
mark in the template by <code>filename</code>,
6259
which is <code>modname</code> with each dot replaced by a
6260
"directory separator" (such as "<code>/</code>" in Unix);
6261
then it will try to load the resulting file name.
6262
So, for instance, if the Lua path is
6263
 
6264
<pre>
6265
     "./?.lua;./?.lc;/usr/local/?/init.lua"
6266
</pre><p>
6267
the search for a Lua loader for module <code>foo</code>
6268
will try to load the files
6269
<code>./foo.lua</code>, <code>./foo.lc</code>, and
6270
<code>/usr/local/foo/init.lua</code>, in that order.
6271
 
6272
 
6273
 
6274
 
6275
<p>
6276
<hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3>
6277
 
6278
 
6279
<p>
6280
A table to store loaders for specific modules
6281
(see <a href="#pdf-require"><code>require</code></a>).
6282
 
6283
 
6284
 
6285
 
6286
<p>
6287
<hr><h3><a name="pdf-package.seeall"><code>package.seeall (module)</code></a></h3>
6288
 
6289
 
6290
<p>
6291
Sets a metatable for <code>module</code> with
6292
its <code>__index</code> field referring to the global environment,
6293
so that this module inherits values
6294
from the global environment.
6295
To be used as an option to function <a href="#pdf-module"><code>module</code></a>.
6296
 
6297
 
6298
 
6299
 
6300
 
6301
 
6302
 
6303
<h2>5.4 - <a name="5.4">String Manipulation</a></h2>
6304
 
6305
<p>
6306
This library provides generic functions for string manipulation,
6307
such as finding and extracting substrings, and pattern matching.
6308
When indexing a string in Lua, the first character is at position&nbsp;1
6309
(not at&nbsp;0, as in C).
6310
Indices are allowed to be negative and are interpreted as indexing backwards,
6311
from the end of the string.
6312
Thus, the last character is at position -1, and so on.
6313
 
6314
 
6315
<p>
6316
The string library provides all its functions inside the table
6317
<a name="pdf-string"><code>string</code></a>.
6318
It also sets a metatable for strings
6319
where the <code>__index</code> field points to the <code>string</code> table.
6320
Therefore, you can use the string functions in object-oriented style.
6321
For instance, <code>string.byte(s, i)</code>
6322
can be written as <code>s:byte(i)</code>.
6323
 
6324
 
6325
<p>
6326
<hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3>
6327
Returns the internal numerical codes of the characters <code>s[i]</code>,
6328
<code>s[i+1]</code>, &middot;&middot;&middot;, <code>s[j]</code>.
6329
The default value for <code>i</code> is&nbsp;1;
6330
the default value for <code>j</code> is&nbsp;<code>i</code>.
6331
 
6332
 
6333
<p>
6334
Note that numerical codes are not necessarily portable across platforms.
6335
 
6336
 
6337
 
6338
 
6339
<p>
6340
<hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3>
6341
Receives zero or more integers.
6342
Returns a string with length equal to the number of arguments,
6343
in which each character has the internal numerical code equal
6344
to its corresponding argument.
6345
 
6346
 
6347
<p>
6348
Note that numerical codes are not necessarily portable across platforms.
6349
 
6350
 
6351
 
6352
 
6353
<p>
6354
<hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
6355
 
6356
 
6357
<p>
6358
Returns a string containing a binary representation of the given function,
6359
so that a later <a href="#pdf-loadstring"><code>loadstring</code></a> on this string returns
6360
a copy of the function.
6361
<code>function</code> must be a Lua function without upvalues.
6362
 
6363
 
6364
 
6365
 
6366
<p>
6367
<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
6368
Looks for the first match of
6369
<code>pattern</code> in the string <code>s</code>.
6370
If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
6371
where this occurrence starts and ends;
6372
otherwise, it returns <b>nil</b>.
6373
A third, optional numerical argument <code>init</code> specifies
6374
where to start the search;
6375
its default value is&nbsp;1 and may be negative.
6376
A value of <b>true</b> as a fourth, optional argument <code>plain</code>
6377
turns off the pattern matching facilities,
6378
so the function does a plain "find substring" operation,
6379
with no characters in <code>pattern</code> being considered "magic".
6380
Note that if <code>plain</code> is given, then <code>init</code> must be given as well.
6381
 
6382
 
6383
<p>
6384
If the pattern has captures,
6385
then in a successful match
6386
the captured values are also returned,
6387
after the two indices.
6388
 
6389
 
6390
 
6391
 
6392
<p>
6393
<hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3>
6394
Returns a formatted version of its variable number of arguments
6395
following the description given in its first argument (which must be a string).
6396
The format string follows the same rules as the <code>printf</code> family of
6397
standard C&nbsp;functions.
6398
The only differences are that the options/modifiers
6399
<code>*</code>, <code>l</code>, <code>L</code>, <code>n</code>, <code>p</code>,
6400
and <code>h</code> are not supported
6401
and that there is an extra option, <code>q</code>.
6402
The <code>q</code> option formats a string in a form suitable to be safely read
6403
back by the Lua interpreter:
6404
the string is written between double quotes,
6405
and all double quotes, newlines, embedded zeros,
6406
and backslashes in the string
6407
are correctly escaped when written.
6408
For instance, the call
6409
 
6410
<pre>
6411
     string.format('%q', 'a string with "quotes" and \n new line')
6412
</pre><p>
6413
will produce the string:
6414
 
6415
<pre>
6416
     "a string with \"quotes\" and \
6417
      new line"
6418
</pre>
6419
 
6420
<p>
6421
The options <code>c</code>, <code>d</code>, <code>E</code>, <code>e</code>, <code>f</code>,
6422
<code>g</code>, <code>G</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> all
6423
expect a number as argument,
6424
whereas <code>q</code> and <code>s</code> expect a string.
6425
 
6426
 
6427
<p>
6428
This function does not accept string values
6429
containing embedded zeros.
6430
 
6431
 
6432
 
6433
 
6434
<p>
6435
<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
6436
Returns an iterator function that,
6437
each time it is called,
6438
returns the next captures from <code>pattern</code> over string <code>s</code>.
6439
 
6440
 
6441
<p>
6442
If <code>pattern</code> specifies no captures,
6443
then the whole match is produced in each call.
6444
 
6445
 
6446
<p>
6447
As an example, the following loop
6448
 
6449
<pre>
6450
     s = "hello world from Lua"
6451
     for w in string.gmatch(s, "%a+") do
6452
       print(w)
6453
     end
6454
</pre><p>
6455
will iterate over all the words from string <code>s</code>,
6456
printing one per line.
6457
The next example collects all pairs <code>key=value</code> from the
6458
given string into a table:
6459
 
6460
<pre>
6461
     t = {}
6462
     s = "from=world, to=Lua"
6463
     for k, v in string.gmatch(s, "(%w+)=(%w+)") do
6464
       t[k] = v
6465
     end
6466
</pre>
6467
 
6468
 
6469
 
6470
<p>
6471
<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
6472
Returns a copy of <code>s</code>
6473
in which all occurrences of the <code>pattern</code> have been
6474
replaced by a replacement string specified by <code>repl</code>,
6475
which may be a string, a table, or a function.
6476
<code>gsub</code> also returns, as its second value,
6477
the total number of substitutions made.
6478
 
6479
 
6480
<p>
6481
If <code>repl</code> is a string, then its value is used for replacement.
6482
The character&nbsp;<code>%</code> works as an escape character:
6483
any sequence in <code>repl</code> of the form <code>%<em>n</em></code>,
6484
with <em>n</em> between 1 and 9,
6485
stands for the value of the <em>n</em>-th captured substring (see below).
6486
The sequence <code>%0</code> stands for the whole match.
6487
The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>.
6488
 
6489
 
6490
<p>
6491
If <code>repl</code> is a table, then the table is queried for every match,
6492
using the first capture as the key;
6493
if the pattern specifies no captures,
6494
then the whole match is used as the key.
6495
 
6496
 
6497
<p>
6498
If <code>repl</code> is a function, then this function is called every time a
6499
match occurs, with all captured substrings passed as arguments,
6500
in order;
6501
if the pattern specifies no captures,
6502
then the whole match is passed as a sole argument.
6503
 
6504
 
6505
<p>
6506
If the value returned by the table query or by the function call
6507
is a string or a number,
6508
then it is used as the replacement string;
6509
otherwise, if it is <b>false</b> or <b>nil</b>,
6510
then there is no replacement
6511
(that is, the original match is kept in the string).
6512
 
6513
 
6514
<p>
6515
The optional last parameter <code>n</code> limits
6516
the maximum number of substitutions to occur.
6517
For instance, when <code>n</code> is 1 only the first occurrence of
6518
<code>pattern</code> is replaced.
6519
 
6520
 
6521
<p>
6522
Here are some examples:
6523
 
6524
<pre>
6525
     x = string.gsub("hello world", "(%w+)", "%1 %1")
6526
     --&gt; x="hello hello world world"
6527
 
6528
     x = string.gsub("hello world", "%w+", "%0 %0", 1)
6529
     --&gt; x="hello hello world"
6530
 
6531
     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
6532
     --&gt; x="world hello Lua from"
6533
 
6534
     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
6535
     --&gt; x="home = /home/roberto, user = roberto"
6536
 
6537
     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
6538
           return loadstring(s)()
6539
         end)
6540
     --&gt; x="4+5 = 9"
6541
 
6542
     local t = {name="lua", version="5.1"}
6543
     x = string.gsub("$name%-$version.tar.gz", "%$(%w+)", t)
6544
     --&gt; x="lua-5.1.tar.gz"
6545
</pre>
6546
 
6547
 
6548
 
6549
<p>
6550
<hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3>
6551
Receives a string and returns its length.
6552
The empty string <code>""</code> has length 0.
6553
Embedded zeros are counted,
6554
so <code>"a\000bc\000"</code> has length 5.
6555
 
6556
 
6557
 
6558
 
6559
<p>
6560
<hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3>
6561
Receives a string and returns a copy of this string with all
6562
uppercase letters changed to lowercase.
6563
All other characters are left unchanged.
6564
The definition of what an uppercase letter is depends on the current locale.
6565
 
6566
 
6567
 
6568
 
6569
<p>
6570
<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
6571
Looks for the first <em>match</em> of
6572
<code>pattern</code> in the string <code>s</code>.
6573
If it finds one, then <code>match</code> returns
6574
the captures from the pattern;
6575
otherwise it returns <b>nil</b>.
6576
If <code>pattern</code> specifies no captures,
6577
then the whole match is returned.
6578
A third, optional numerical argument <code>init</code> specifies
6579
where to start the search;
6580
its default value is&nbsp;1 and may be negative.
6581
 
6582
 
6583
 
6584
 
6585
<p>
6586
<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n)</code></a></h3>
6587
Returns a string that is the concatenation of <code>n</code> copies of
6588
the string <code>s</code>.
6589
 
6590
 
6591
 
6592
 
6593
<p>
6594
<hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3>
6595
Returns a string that is the string <code>s</code> reversed.
6596
 
6597
 
6598
 
6599
 
6600
<p>
6601
<hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3>
6602
Returns the substring of <code>s</code> that
6603
starts at <code>i</code>  and continues until <code>j</code>;
6604
<code>i</code> and <code>j</code> may be negative.
6605
If <code>j</code> is absent, then it is assumed to be equal to -1
6606
(which is the same as the string length).
6607
In particular,
6608
the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code>
6609
with length <code>j</code>,
6610
and <code>string.sub(s, -i)</code> returns a suffix of <code>s</code>
6611
with length <code>i</code>.
6612
 
6613
 
6614
 
6615
 
6616
<p>
6617
<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
6618
Receives a string and returns a copy of this string with all
6619
lowercase letters changed to uppercase.
6620
All other characters are left unchanged.
6621
The definition of what a lowercase letter is depends on the current locale.
6622
 
6623
 
6624
 
6625
<h3>5.4.1 - <a name="5.4.1">Patterns</a></h3>
6626
 
6627
 
6628
<h4>Character Class:</h4><p>
6629
A <em>character class</em> is used to represent a set of characters.
6630
The following combinations are allowed in describing a character class:
6631
 
6632
<ul>
6633
 
6634
<li><b><em>x</em>:</b>
6635
(where <em>x</em> is not one of the <em>magic characters</em>
6636
<code>^$()%.[]*+-?</code>)
6637
represents the character <em>x</em> itself.
6638
</li>
6639
 
6640
<li><b><code>.</code>:</b> (a dot) represents all characters.</li>
6641
 
6642
<li><b><code>%a</code>:</b> represents all letters.</li>
6643
 
6644
<li><b><code>%c</code>:</b> represents all control characters.</li>
6645
 
6646
<li><b><code>%d</code>:</b> represents all digits.</li>
6647
 
6648
<li><b><code>%l</code>:</b> represents all lowercase letters.</li>
6649
 
6650
<li><b><code>%p</code>:</b> represents all punctuation characters.</li>
6651
 
6652
<li><b><code>%s</code>:</b> represents all space characters.</li>
6653
 
6654
<li><b><code>%u</code>:</b> represents all uppercase letters.</li>
6655
 
6656
<li><b><code>%w</code>:</b> represents all alphanumeric characters.</li>
6657
 
6658
<li><b><code>%x</code>:</b> represents all hexadecimal digits.</li>
6659
 
6660
<li><b><code>%z</code>:</b> represents the character with representation 0.</li>
6661
 
6662
<li><b><code>%<em>x</em></code>:</b> (where <em>x</em> is any non-alphanumeric character)
6663
represents the character <em>x</em>.
6664
This is the standard way to escape the magic characters.
6665
Any punctuation character (even the non magic)
6666
can be preceded by a '<code>%</code>'
6667
when used to represent itself in a pattern.
6668
</li>
6669
 
6670
<li><b><code>[<em>set</em>]</code>:</b>
6671
represents the class which is the union of all
6672
characters in <em>set</em>.
6673
A range of characters may be specified by
6674
separating the end characters of the range with a '<code>-</code>'.
6675
All classes <code>%</code><em>x</em> described above may also be used as
6676
components in <em>set</em>.
6677
All other characters in <em>set</em> represent themselves.
6678
For example, <code>[%w_]</code> (or <code>[_%w]</code>)
6679
represents all alphanumeric characters plus the underscore,
6680
<code>[0-7]</code> represents the octal digits,
6681
and <code>[0-7%l%-]</code> represents the octal digits plus
6682
the lowercase letters plus the '<code>-</code>' character.
6683
 
6684
 
6685
<p>
6686
The interaction between ranges and classes is not defined.
6687
Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code>
6688
have no meaning.
6689
</li>
6690
 
6691
<li><b><code>[^<em>set</em>]</code>:</b>
6692
represents the complement of <em>set</em>,
6693
where <em>set</em> is interpreted as above.
6694
</li>
6695
 
6696
</ul><p>
6697
For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.),
6698
the corresponding uppercase letter represents the complement of the class.
6699
For instance, <code>%S</code> represents all non-space characters.
6700
 
6701
 
6702
<p>
6703
The definitions of letter, space, and other character groups
6704
depend on the current locale.
6705
In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>.
6706
 
6707
 
6708
 
6709
 
6710
 
6711
<h4>Pattern Item:</h4><p>
6712
A <em>pattern item</em> may be
6713
 
6714
<ul>
6715
 
6716
<li>
6717
a single character class,
6718
which matches any single character in the class;
6719
</li>
6720
 
6721
<li>
6722
a single character class followed by '<code>*</code>',
6723
which matches 0 or more repetitions of characters in the class.
6724
These repetition items will always match the longest possible sequence;
6725
</li>
6726
 
6727
<li>
6728
a single character class followed by '<code>+</code>',
6729
which matches 1 or more repetitions of characters in the class.
6730
These repetition items will always match the longest possible sequence;
6731
</li>
6732
 
6733
<li>
6734
a single character class followed by '<code>-</code>',
6735
which also matches 0 or more repetitions of characters in the class.
6736
Unlike '<code>*</code>',
6737
these repetition items will always match the <em>shortest</em> possible sequence;
6738
</li>
6739
 
6740
<li>
6741
a single character class followed by '<code>?</code>',
6742
which matches 0 or 1 occurrence of a character in the class;
6743
</li>
6744
 
6745
<li>
6746
<code>%<em>n</em></code>, for <em>n</em> between 1 and 9;
6747
such item matches a substring equal to the <em>n</em>-th captured string
6748
(see below);
6749
</li>
6750
 
6751
<li>
6752
<code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters;
6753
such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>,
6754
and where the <em>x</em> and <em>y</em> are <em>balanced</em>.
6755
This means that, if one reads the string from left to right,
6756
counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>,
6757
the ending <em>y</em> is the first <em>y</em> where the count reaches 0.
6758
For instance, the item <code>%b()</code> matches expressions with
6759
balanced parentheses.
6760
</li>
6761
 
6762
</ul>
6763
 
6764
 
6765
 
6766
 
6767
<h4>Pattern:</h4><p>
6768
A <em>pattern</em> is a sequence of pattern items.
6769
A '<code>^</code>' at the beginning of a pattern anchors the match at the
6770
beginning of the subject string.
6771
A '<code>$</code>' at the end of a pattern anchors the match at the
6772
end of the subject string.
6773
At other positions,
6774
'<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves.
6775
 
6776
 
6777
 
6778
 
6779
 
6780
<h4>Captures:</h4><p>
6781
A pattern may contain sub-patterns enclosed in parentheses;
6782
they describe <em>captures</em>.
6783
When a match succeeds, the substrings of the subject string
6784
that match captures are stored (<em>captured</em>) for future use.
6785
Captures are numbered according to their left parentheses.
6786
For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>,
6787
the part of the string matching <code>"a*(.)%w(%s*)"</code> is
6788
stored as the first capture (and therefore has number&nbsp;1);
6789
the character matching "<code>.</code>" is captured with number&nbsp;2,
6790
and the part matching "<code>%s*</code>" has number&nbsp;3.
6791
 
6792
 
6793
<p>
6794
As a special case, the empty capture <code>()</code> captures
6795
the current string position (a number).
6796
For instance, if we apply the pattern <code>"()aa()"</code> on the
6797
string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5.
6798
 
6799
 
6800
<p>
6801
A pattern cannot contain embedded zeros.  Use <code>%z</code> instead.
6802
 
6803
 
6804
 
6805
 
6806
 
6807
 
6808
 
6809
 
6810
 
6811
 
6812
 
6813
<h2>5.5 - <a name="5.5">Table Manipulation</a></h2><p>
6814
This library provides generic functions for table manipulation.
6815
It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
6816
 
6817
 
6818
<p>
6819
Most functions in the table library assume that the table
6820
represents an array or a list.
6821
For these functions, when we talk about the "length" of a table
6822
we mean the result of the length operator.
6823
 
6824
 
6825
<p>
6826
<hr><h3><a name="pdf-table.concat"><code>table.concat (table [, sep [, i [, j]]])</code></a></h3>
6827
Returns <code>table[i]..sep..table[i+1] &middot;&middot;&middot; sep..table[j]</code>.
6828
The default value for <code>sep</code> is the empty string,
6829
the default for <code>i</code> is 1,
6830
and the default for <code>j</code> is the length of the table.
6831
If <code>i</code> is greater than <code>j</code>, returns the empty string.
6832
 
6833
 
6834
 
6835
 
6836
<p>
6837
<hr><h3><a name="pdf-table.insert"><code>table.insert (table, [pos,] value)</code></a></h3>
6838
 
6839
 
6840
<p>
6841
Inserts element <code>value</code> at position <code>pos</code> in <code>table</code>,
6842
shifting up other elements to open space, if necessary.
6843
The default value for <code>pos</code> is <code>n+1</code>,
6844
where <code>n</code> is the length of the table (see <a href="#2.5.5">&sect;2.5.5</a>),
6845
so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end
6846
of table <code>t</code>.
6847
 
6848
 
6849
 
6850
 
6851
<p>
6852
<hr><h3><a name="pdf-table.maxn"><code>table.maxn (table)</code></a></h3>
6853
 
6854
 
6855
<p>
6856
Returns the largest positive numerical index of the given table,
6857
or zero if the table has no positive numerical indices.
6858
(To do its job this function does a linear traversal of
6859
the whole table.) 
6860
 
6861
 
6862
 
6863
 
6864
<p>
6865
<hr><h3><a name="pdf-table.remove"><code>table.remove (table [, pos])</code></a></h3>
6866
 
6867
 
6868
<p>
6869
Removes from <code>table</code> the element at position <code>pos</code>,
6870
shifting down other elements to close the space, if necessary.
6871
Returns the value of the removed element.
6872
The default value for <code>pos</code> is <code>n</code>,
6873
where <code>n</code> is the length of the table,
6874
so that a call <code>table.remove(t)</code> removes the last element
6875
of table <code>t</code>.
6876
 
6877
 
6878
 
6879
 
6880
<p>
6881
<hr><h3><a name="pdf-table.sort"><code>table.sort (table [, comp])</code></a></h3>
6882
Sorts table elements in a given order, <em>in-place</em>,
6883
from <code>table[1]</code> to <code>table[n]</code>,
6884
where <code>n</code> is the length of the table.
6885
If <code>comp</code> is given,
6886
then it must be a function that receives two table elements,
6887
and returns true
6888
when the first is less than the second
6889
(so that <code>not comp(a[i+1],a[i])</code> will be true after the sort).
6890
If <code>comp</code> is not given,
6891
then the standard Lua operator <code>&lt;</code> is used instead.
6892
 
6893
 
6894
<p>
6895
The sort algorithm is not stable;
6896
that is, elements considered equal by the given order
6897
may have their relative positions changed by the sort.
6898
 
6899
 
6900
 
6901
 
6902
 
6903
 
6904
 
6905
<h2>5.6 - <a name="5.6">Mathematical Functions</a></h2>
6906
 
6907
<p>
6908
This library is an interface to the standard C&nbsp;math library.
6909
It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
6910
 
6911
 
6912
<p>
6913
<hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3>
6914
 
6915
 
6916
<p>
6917
Returns the absolute value of <code>x</code>.
6918
 
6919
 
6920
 
6921
 
6922
<p>
6923
<hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3>
6924
 
6925
 
6926
<p>
6927
Returns the arc cosine of <code>x</code> (in radians).
6928
 
6929
 
6930
 
6931
 
6932
<p>
6933
<hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3>
6934
 
6935
 
6936
<p>
6937
Returns the arc sine of <code>x</code> (in radians).
6938
 
6939
 
6940
 
6941
 
6942
<p>
6943
<hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
6944
 
6945
 
6946
<p>
6947
Returns the arc tangent of <code>x</code> (in radians).
6948
 
6949
 
6950
 
6951
 
6952
<p>
6953
<hr><h3><a name="pdf-math.atan2"><code>math.atan2 (x, y)</code></a></h3>
6954
 
6955
 
6956
<p>
6957
Returns the arc tangent of <code>x/y</code> (in radians),
6958
but uses the signs of both parameters to find the
6959
quadrant of the result.
6960
(It also handles correctly the case of <code>y</code> being zero.)
6961
 
6962
 
6963
 
6964
 
6965
<p>
6966
<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
6967
 
6968
 
6969
<p>
6970
Returns the smallest integer larger than or equal to <code>x</code>.
6971
 
6972
 
6973
 
6974
 
6975
<p>
6976
<hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3>
6977
 
6978
 
6979
<p>
6980
Returns the cosine of <code>x</code> (assumed to be in radians).
6981
 
6982
 
6983
 
6984
 
6985
<p>
6986
<hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
6987
 
6988
 
6989
<p>
6990
Returns the hyperbolic cosine of <code>x</code>.
6991
 
6992
 
6993
 
6994
 
6995
<p>
6996
<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
6997
 
6998
 
6999
<p>
7000
Returns the angle <code>x</code> (given in radians) in degrees.
7001
 
7002
 
7003
 
7004
 
7005
<p>
7006
<hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3>
7007
 
7008
 
7009
<p>
7010
Returns the the value <em>e<sup>x</sup></em>.
7011
 
7012
 
7013
 
7014
 
7015
<p>
7016
<hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3>
7017
 
7018
 
7019
<p>
7020
Returns the largest integer smaller than or equal to <code>x</code>.
7021
 
7022
 
7023
 
7024
 
7025
<p>
7026
<hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3>
7027
 
7028
 
7029
<p>
7030
Returns the remainder of the division of <code>x</code> by <code>y</code>.
7031
 
7032
 
7033
 
7034
 
7035
<p>
7036
<hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
7037
 
7038
 
7039
<p>
7040
Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
7041
<code>e</code> is an integer and the absolute value of <code>m</code> is
7042
in the range <em>[0.5, 1)</em>
7043
(or zero when <code>x</code> is zero).
7044
 
7045
 
7046
 
7047
 
7048
<p>
7049
<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
7050
 
7051
 
7052
<p>
7053
The value <code>HUGE_VAL</code>,
7054
a value larger than or equal to any other numerical value.
7055
 
7056
 
7057
 
7058
 
7059
<p>
7060
<hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
7061
 
7062
 
7063
<p>
7064
Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
7065
 
7066
 
7067
 
7068
 
7069
<p>
7070
<hr><h3><a name="pdf-math.log"><code>math.log (x)</code></a></h3>
7071
 
7072
 
7073
<p>
7074
Returns the natural logarithm of <code>x</code>.
7075
 
7076
 
7077
 
7078
 
7079
<p>
7080
<hr><h3><a name="pdf-math.log10"><code>math.log10 (x)</code></a></h3>
7081
 
7082
 
7083
<p>
7084
Returns the base-10 logarithm of <code>x</code>.
7085
 
7086
 
7087
 
7088
 
7089
<p>
7090
<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
7091
 
7092
 
7093
<p>
7094
Returns the maximum value among its arguments.
7095
 
7096
 
7097
 
7098
 
7099
<p>
7100
<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
7101
 
7102
 
7103
<p>
7104
Returns the minimum value among its arguments.
7105
 
7106
 
7107
 
7108
 
7109
<p>
7110
<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
7111
 
7112
 
7113
<p>
7114
Returns two numbers,
7115
the integral part of <code>x</code> and the fractional part of <code>x</code>.
7116
 
7117
 
7118
 
7119
 
7120
<p>
7121
<hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3>
7122
 
7123
 
7124
<p>
7125
The value PI.
7126
 
7127
 
7128
 
7129
 
7130
<p>
7131
<hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
7132
 
7133
 
7134
<p>
7135
Returns <em>x<sup>y</sup></em>.
7136
(You can also use the expression <code>x^y</code> to compute this value.)
7137
 
7138
 
7139
 
7140
 
7141
<p>
7142
<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
7143
 
7144
 
7145
<p>
7146
Returns the angle <code>x</code> (given in degrees) in radians.
7147
 
7148
 
7149
 
7150
 
7151
<p>
7152
<hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3>
7153
 
7154
 
7155
<p>
7156
This function is an interface to the simple
7157
pseudo-random generator function <code>rand</code> provided by ANSI&nbsp;C.
7158
(No guarantees can be given for its statistical properties.)
7159
 
7160
 
7161
<p>
7162
When called without arguments,
7163
returns a pseudo-random real number
7164
in the range <em>[0,1)</em>.  
7165
When called with a number <code>m</code>,
7166
<code>math.random</code> returns
7167
a pseudo-random integer in the range <em>[1, m]</em>.
7168
When called with two numbers <code>m</code> and <code>n</code>,
7169
<code>math.random</code> returns a pseudo-random
7170
integer in the range <em>[m, n]</em>.
7171
 
7172
 
7173
 
7174
 
7175
<p>
7176
<hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3>
7177
 
7178
 
7179
<p>
7180
Sets <code>x</code> as the "seed"
7181
for the pseudo-random generator:
7182
equal seeds produce equal sequences of numbers.
7183
 
7184
 
7185
 
7186
 
7187
<p>
7188
<hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3>
7189
 
7190
 
7191
<p>
7192
Returns the sine of <code>x</code> (assumed to be in radians).
7193
 
7194
 
7195
 
7196
 
7197
<p>
7198
<hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
7199
 
7200
 
7201
<p>
7202
Returns the hyperbolic sine of <code>x</code>.
7203
 
7204
 
7205
 
7206
 
7207
<p>
7208
<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
7209
 
7210
 
7211
<p>
7212
Returns the square root of <code>x</code>.
7213
(You can also use the expression <code>x^0.5</code> to compute this value.)
7214
 
7215
 
7216
 
7217
 
7218
<p>
7219
<hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3>
7220
 
7221
 
7222
<p>
7223
Returns the tangent of <code>x</code> (assumed to be in radians).
7224
 
7225
 
7226
 
7227
 
7228
<p>
7229
<hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
7230
 
7231
 
7232
<p>
7233
Returns the hyperbolic tangent of <code>x</code>.
7234
 
7235
 
7236
 
7237
 
7238
 
7239
 
7240
 
7241
<h2>5.7 - <a name="5.7">Input and Output Facilities</a></h2>
7242
 
7243
<p>
7244
The I/O library provides two different styles for file manipulation.
7245
The first one uses implicit file descriptors;
7246
that is, there are operations to set a default input file and a
7247
default output file,
7248
and all input/output operations are over these default files.
7249
The second style uses explicit file descriptors.
7250
 
7251
 
7252
<p>
7253
When using implicit file descriptors,
7254
all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
7255
When using explicit file descriptors,
7256
the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
7257
and then all operations are supplied as methods of the file descriptor.
7258
 
7259
 
7260
<p>
7261
The table <code>io</code> also provides
7262
three predefined file descriptors with their usual meanings from C:
7263
<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>.
7264
 
7265
 
7266
<p>
7267
Unless otherwise stated,
7268
all I/O functions return <b>nil</b> on failure
7269
(plus an error message as a second result)
7270
and some value different from <b>nil</b> on success.
7271
 
7272
 
7273
<p>
7274
<hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3>
7275
 
7276
 
7277
<p>
7278
Equivalent to <code>file:close()</code>.
7279
Without a <code>file</code>, closes the default output file.
7280
 
7281
 
7282
 
7283
 
7284
<p>
7285
<hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3>
7286
 
7287
 
7288
<p>
7289
Equivalent to <code>file:flush</code> over the default output file.
7290
 
7291
 
7292
 
7293
 
7294
<p>
7295
<hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3>
7296
 
7297
 
7298
<p>
7299
When called with a file name, it opens the named file (in text mode),
7300
and sets its handle as the default input file.
7301
When called with a file handle,
7302
it simply sets this file handle as the default input file.
7303
When called without parameters,
7304
it returns the current default input file.
7305
 
7306
 
7307
<p>
7308
In case of errors this function raises the error,
7309
instead of returning an error code.
7310
 
7311
 
7312
 
7313
 
7314
<p>
7315
<hr><h3><a name="pdf-io.lines"><code>io.lines ([filename])</code></a></h3>
7316
 
7317
 
7318
<p>
7319
Opens the given file name in read mode
7320
and returns an iterator function that,
7321
each time it is called,
7322
returns a new line from the file.
7323
Therefore, the construction
7324
 
7325
<pre>
7326
     for line in io.lines(filename) do <em>body</em> end
7327
</pre><p>
7328
will iterate over all lines of the file.
7329
When the iterator function detects the end of file,
7330
it returns <b>nil</b> (to finish the loop) and automatically closes the file.
7331
 
7332
 
7333
<p>
7334
The call <code>io.lines()</code> (without a file name) is equivalent
7335
to <code>io.input():lines()</code>;
7336
that is, it iterates over the lines of the default input file.
7337
In this case it does not close the file when the loop ends.
7338
 
7339
 
7340
 
7341
 
7342
<p>
7343
<hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3>
7344
 
7345
 
7346
<p>
7347
This function opens a file,
7348
in the mode specified in the string <code>mode</code>.
7349
It returns a new file handle,
7350
or, in case of errors, <b>nil</b> plus an error message.
7351
 
7352
 
7353
<p>
7354
The <code>mode</code> string can be any of the following:
7355
 
7356
<ul>
7357
<li><b>"r":</b> read mode (the default);</li>
7358
<li><b>"w":</b> write mode;</li>
7359
<li><b>"a":</b> append mode;</li>
7360
<li><b>"r+":</b> update mode, all previous data is preserved;</li>
7361
<li><b>"w+":</b> update mode, all previous data is erased;</li>
7362
<li><b>"a+":</b> append update mode, previous data is preserved,
7363
  writing is only allowed at the end of file.</li>
7364
</ul><p>
7365
The <code>mode</code> string may also have a '<code>b</code>' at the end,
7366
which is needed in some systems to open the file in binary mode.
7367
This string is exactly what is used in the
7368
standard&nbsp;C function <code>fopen</code>.
7369
 
7370
 
7371
 
7372
 
7373
<p>
7374
<hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3>
7375
 
7376
 
7377
<p>
7378
Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file.
7379
 
7380
 
7381
 
7382
 
7383
<p>
7384
<hr><h3><a name="pdf-io.popen"><code>io.popen ([prog [, mode]])</code></a></h3>
7385
 
7386
 
7387
<p>
7388
Starts program <code>prog</code> in a separated process and returns
7389
a file handle that you can use to read data from this program
7390
(if <code>mode</code> is <code>"r"</code>, the default)
7391
or to write data to this program
7392
(if <code>mode</code> is <code>"w"</code>).
7393
 
7394
 
7395
<p>
7396
This function is system dependent and is not available
7397
on all platforms.
7398
 
7399
 
7400
 
7401
 
7402
<p>
7403
<hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3>
7404
 
7405
 
7406
<p>
7407
Equivalent to <code>io.input():read</code>.
7408
 
7409
 
7410
 
7411
 
7412
<p>
7413
<hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3>
7414
 
7415
 
7416
<p>
7417
Returns a handle for a temporary file.
7418
This file is opened in update mode
7419
and it is automatically removed when the program ends.
7420
 
7421
 
7422
 
7423
 
7424
<p>
7425
<hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3>
7426
 
7427
 
7428
<p>
7429
Checks whether <code>obj</code> is a valid file handle.
7430
Returns the string <code>"file"</code> if <code>obj</code> is an open file handle,
7431
<code>"closed file"</code> if <code>obj</code> is a closed file handle,
7432
or <b>nil</b> if <code>obj</code> is not a file handle.
7433
 
7434
 
7435
 
7436
 
7437
<p>
7438
<hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3>
7439
 
7440
 
7441
<p>
7442
Equivalent to <code>io.output():write</code>.
7443
 
7444
 
7445
 
7446
 
7447
<p>
7448
<hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3>
7449
 
7450
 
7451
<p>
7452
Closes <code>file</code>.
7453
Note that files are automatically closed when
7454
their handles are garbage collected,
7455
but that takes an unpredictable amount of time to happen.
7456
 
7457
 
7458
 
7459
 
7460
<p>
7461
<hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3>
7462
 
7463
 
7464
<p>
7465
Saves any written data to <code>file</code>.
7466
 
7467
 
7468
 
7469
 
7470
<p>
7471
<hr><h3><a name="pdf-file:lines"><code>file:lines ()</code></a></h3>
7472
 
7473
 
7474
<p>
7475
Returns an iterator function that,
7476
each time it is called,
7477
returns a new line from the file.
7478
Therefore, the construction
7479
 
7480
<pre>
7481
     for line in file:lines() do <em>body</em> end
7482
</pre><p>
7483
will iterate over all lines of the file.
7484
(Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file
7485
when the loop ends.)
7486
 
7487
 
7488
 
7489
 
7490
<p>
7491
<hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3>
7492
 
7493
 
7494
<p>
7495
Reads the file <code>file</code>,
7496
according to the given formats, which specify what to read.
7497
For each format,
7498
the function returns a string (or a number) with the characters read,
7499
or <b>nil</b> if it cannot read data with the specified format.
7500
When called without formats,
7501
it uses a default format that reads the entire next line
7502
(see below).
7503
 
7504
 
7505
<p>
7506
The available formats are
7507
 
7508
<ul>
7509
 
7510
<li><b>"*n":</b>
7511
reads a number;
7512
this is the only format that returns a number instead of a string.
7513
</li>
7514
 
7515
<li><b>"*a":</b>
7516
reads the whole file, starting at the current position.
7517
On end of file, it returns the empty string.
7518
</li>
7519
 
7520
<li><b>"*l":</b>
7521
reads the next line (skipping the end of line),
7522
returning <b>nil</b> on end of file.
7523
This is the default format.
7524
</li>
7525
 
7526
<li><b><em>number</em>:</b>
7527
reads a string with up to this number of characters,
7528
returning <b>nil</b> on end of file.
7529
If number is zero,
7530
it reads nothing and returns an empty string,
7531
or <b>nil</b> on end of file.
7532
</li>
7533
 
7534
</ul>
7535
 
7536
 
7537
 
7538
<p>
7539
<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence] [, offset])</code></a></h3>
7540
 
7541
 
7542
<p>
7543
Sets and gets the file position,
7544
measured from the beginning of the file,
7545
to the position given by <code>offset</code> plus a base
7546
specified by the string <code>whence</code>, as follows:
7547
 
7548
<ul>
7549
<li><b>"set":</b> base is position 0 (beginning of the file);</li>
7550
<li><b>"cur":</b> base is current position;</li>
7551
<li><b>"end":</b> base is end of file;</li>
7552
</ul><p>
7553
In case of success, function <code>seek</code> returns the final file position,
7554
measured in bytes from the beginning of the file.
7555
If this function fails, it returns <b>nil</b>,
7556
plus a string describing the error.
7557
 
7558
 
7559
<p>
7560
The default value for <code>whence</code> is <code>"cur"</code>,
7561
and for <code>offset</code> is 0.
7562
Therefore, the call <code>file:seek()</code> returns the current
7563
file position, without changing it;
7564
the call <code>file:seek("set")</code> sets the position to the
7565
beginning of the file (and returns 0);
7566
and the call <code>file:seek("end")</code> sets the position to the
7567
end of the file, and returns its size.
7568
 
7569
 
7570
 
7571
 
7572
<p>
7573
<hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3>
7574
 
7575
 
7576
<p>
7577
Sets the buffering mode for an output file.
7578
There are three available modes:
7579
 
7580
<ul>
7581
 
7582
<li><b>"no":</b>
7583
no buffering; the result of any output operation appears immediately.
7584
</li>
7585
 
7586
<li><b>"full":</b>
7587
full buffering; output operation is performed only
7588
when the buffer is full (or when you explicitly <code>flush</code> the file
7589
(see <a href="#pdf-io.flush"><code>io.flush</code></a>)).
7590
</li>
7591
 
7592
<li><b>"line":</b>
7593
line buffering; output is buffered until a newline is output
7594
or there is any input from some special files
7595
(such as a terminal device).
7596
</li>
7597
 
7598
</ul><p>
7599
For the last two cases, <code>sizes</code>
7600
specifies the size of the buffer, in bytes.
7601
The default is an appropriate size.
7602
 
7603
 
7604
 
7605
 
7606
<p>
7607
<hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3>
7608
 
7609
 
7610
<p>
7611
Writes the value of each of its arguments to
7612
the <code>file</code>.
7613
The arguments must be strings or numbers.
7614
To write other values,
7615
use <a href="#pdf-tostring"><code>tostring</code></a> or <a href="#pdf-string.format"><code>string.format</code></a> before <code>write</code>.
7616
 
7617
 
7618
 
7619
 
7620
 
7621
 
7622
 
7623
<h2>5.8 - <a name="5.8">Operating System Facilities</a></h2>
7624
 
7625
<p>
7626
This library is implemented through table <a name="pdf-os"><code>os</code></a>.
7627
 
7628
 
7629
<p>
7630
<hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3>
7631
 
7632
 
7633
<p>
7634
Returns an approximation of the amount in seconds of CPU time
7635
used by the program.
7636
 
7637
 
7638
 
7639
 
7640
<p>
7641
<hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3>
7642
 
7643
 
7644
<p>
7645
Returns a string or a table containing date and time,
7646
formatted according to the given string <code>format</code>.
7647
 
7648
 
7649
<p>
7650
If the <code>time</code> argument is present,
7651
this is the time to be formatted
7652
(see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value).
7653
Otherwise, <code>date</code> formats the current time.
7654
 
7655
 
7656
<p>
7657
If <code>format</code> starts with '<code>!</code>',
7658
then the date is formatted in Coordinated Universal Time.
7659
After this optional character,
7660
if <code>format</code> is <code>*t</code>,
7661
then <code>date</code> returns a table with the following fields:
7662
<code>year</code> (four digits), <code>month</code> (1--12), <code>day</code> (1--31),
7663
<code>hour</code> (0--23), <code>min</code> (0--59), <code>sec</code> (0--61),
7664
<code>wday</code> (weekday, Sunday is&nbsp;1),
7665
<code>yday</code> (day of the year),
7666
and <code>isdst</code> (daylight saving flag, a boolean).
7667
 
7668
 
7669
<p>
7670
If <code>format</code> is not <code>*t</code>,
7671
then <code>date</code> returns the date as a string,
7672
formatted according to the same rules as the C&nbsp;function <code>strftime</code>.
7673
 
7674
 
7675
<p>
7676
When called without arguments,
7677
<code>date</code> returns a reasonable date and time representation that depends on
7678
the host system and on the current locale
7679
(that is, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>).
7680
 
7681
 
7682
 
7683
 
7684
<p>
7685
<hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3>
7686
 
7687
 
7688
<p>
7689
Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
7690
In POSIX, Windows, and some other systems,
7691
this value is exactly <code>t2</code><em>-</em><code>t1</code>.
7692
 
7693
 
7694
 
7695
 
7696
<p>
7697
<hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3>
7698
 
7699
 
7700
<p>
7701
This function is equivalent to the C&nbsp;function <code>system</code>.
7702
It passes <code>command</code> to be executed by an operating system shell.
7703
It returns a status code, which is system-dependent.
7704
If <code>command</code> is absent, then it returns nonzero if a shell is available
7705
and zero otherwise.
7706
 
7707
 
7708
 
7709
 
7710
<p>
7711
<hr><h3><a name="pdf-os.exit"><code>os.exit ([code])</code></a></h3>
7712
 
7713
 
7714
<p>
7715
Calls the C&nbsp;function <code>exit</code>,
7716
with an optional <code>code</code>,
7717
to terminate the host program.
7718
The default value for <code>code</code> is the success code.
7719
 
7720
 
7721
 
7722
 
7723
<p>
7724
<hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3>
7725
 
7726
 
7727
<p>
7728
Returns the value of the process environment variable <code>varname</code>,
7729
or <b>nil</b> if the variable is not defined.
7730
 
7731
 
7732
 
7733
 
7734
<p>
7735
<hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3>
7736
 
7737
 
7738
<p>
7739
Deletes the file or directory with the given name.
7740
Directories must be empty to be removed.
7741
If this function fails, it returns <b>nil</b>,
7742
plus a string describing the error.
7743
 
7744
 
7745
 
7746
 
7747
<p>
7748
<hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3>
7749
 
7750
 
7751
<p>
7752
Renames file or directory named <code>oldname</code> to <code>newname</code>.
7753
If this function fails, it returns <b>nil</b>,
7754
plus a string describing the error.
7755
 
7756
 
7757
 
7758
 
7759
<p>
7760
<hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3>
7761
 
7762
 
7763
<p>
7764
Sets the current locale of the program.
7765
<code>locale</code> is a string specifying a locale;
7766
<code>category</code> is an optional string describing which category to change:
7767
<code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>,
7768
<code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>;
7769
the default category is <code>"all"</code>.
7770
The function returns the name of the new locale,
7771
or <b>nil</b> if the request cannot be honored.
7772
 
7773
 
7774
<p>
7775
When called with <b>nil</b> as the first argument,
7776
this function only returns the name of the current locale
7777
for the given category.
7778
 
7779
 
7780
 
7781
 
7782
<p>
7783
<hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3>
7784
 
7785
 
7786
<p>
7787
Returns the current time when called without arguments,
7788
or a time representing the date and time specified by the given table.
7789
This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>,
7790
and may have fields <code>hour</code>, <code>min</code>, <code>sec</code>, and <code>isdst</code>
7791
(for a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function).
7792
 
7793
 
7794
<p>
7795
The returned value is a number, whose meaning depends on your system.
7796
In POSIX, Windows, and some other systems, this number counts the number
7797
of seconds since some given start time (the "epoch").
7798
In other systems, the meaning is not specified,
7799
and the number returned by <code>time</code> can be used only as an argument to
7800
<code>date</code> and <code>difftime</code>.
7801
 
7802
 
7803
 
7804
 
7805
<p>
7806
<hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3>
7807
 
7808
 
7809
<p>
7810
Returns a string with a file name that can
7811
be used for a temporary file.
7812
The file must be explicitly opened before its use
7813
and explicitly removed when no longer needed.
7814
 
7815
 
7816
 
7817
 
7818
 
7819
 
7820
 
7821
<h2>5.9 - <a name="5.9">The Debug Library</a></h2>
7822
 
7823
<p>
7824
This library provides
7825
the functionality of the debug interface to Lua programs.
7826
You should exert care when using this library.
7827
The functions provided here should be used exclusively for debugging
7828
and similar tasks, such as profiling.
7829
Please resist the temptation to use them as a
7830
usual programming tool:
7831
they can be very slow.
7832
Moreover, several of its functions
7833
violate some assumptions about Lua code
7834
(e.g., that variables local to a function
7835
cannot be accessed from outside or
7836
that userdata metatables cannot be changed by Lua code)
7837
and therefore can compromise otherwise secure code.
7838
 
7839
 
7840
<p>
7841
All functions in this library are provided
7842
inside the <a name="pdf-debug"><code>debug</code></a> table.
7843
All functions that operate over a thread
7844
have an optional first argument which is the
7845
thread to operate over.
7846
The default is always the current thread.
7847
 
7848
 
7849
<p>
7850
<hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3>
7851
 
7852
 
7853
<p>
7854
Enters an interactive mode with the user,
7855
running each string that the user enters.
7856
Using simple commands and other debug facilities,
7857
the user can inspect global and local variables,
7858
change their values, evaluate expressions, and so on.
7859
A line containing only the word <code>cont</code> finishes this function,
7860
so that the caller continues its execution.
7861
 
7862
 
7863
<p>
7864
Note that commands for <code>debug.debug</code> are not lexically nested
7865
within any function, and so have no direct access to local variables.
7866
 
7867
 
7868
 
7869
 
7870
<p>
7871
<hr><h3><a name="pdf-debug.getfenv"><code>debug.getfenv (o)</code></a></h3>
7872
Returns the environment of object <code>o</code>.
7873
 
7874
 
7875
 
7876
 
7877
<p>
7878
<hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3>
7879
 
7880
 
7881
<p>
7882
Returns the current hook settings of the thread, as three values:
7883
the current hook function, the current hook mask,
7884
and the current hook count
7885
(as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function).
7886
 
7887
 
7888
 
7889
 
7890
<p>
7891
<hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] function [, what])</code></a></h3>
7892
 
7893
 
7894
<p>
7895
Returns a table with information about a function.
7896
You can give the function directly,
7897
or you can give a number as the value of <code>function</code>,
7898
which means the function running at level <code>function</code> of the call stack
7899
of the given thread:
7900
level&nbsp;0 is the current function (<code>getinfo</code> itself);
7901
level&nbsp;1 is the function that called <code>getinfo</code>;
7902
and so on.
7903
If <code>function</code> is a number larger than the number of active functions,
7904
then <code>getinfo</code> returns <b>nil</b>.
7905
 
7906
 
7907
<p>
7908
The returned table may contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>,
7909
with the string <code>what</code> describing which fields to fill in.
7910
The default for <code>what</code> is to get all information available,
7911
except the table of valid lines.
7912
If present,
7913
the option '<code>f</code>'
7914
adds a field named <code>func</code> with the function itself.
7915
If present,
7916
the option '<code>L</code>'
7917
adds a field named <code>activelines</code> with the table of
7918
valid lines.
7919
 
7920
 
7921
<p>
7922
For instance, the expression <code>debug.getinfo(1,"n").name</code> returns
7923
a name of the current function, if a reasonable name can be found,
7924
and <code>debug.getinfo(print)</code> returns a table with all available information
7925
about the <a href="#pdf-print"><code>print</code></a> function.
7926
 
7927
 
7928
 
7929
 
7930
<p>
7931
<hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] level, local)</code></a></h3>
7932
 
7933
 
7934
<p>
7935
This function returns the name and the value of the local variable
7936
with index <code>local</code> of the function at level <code>level</code> of the stack.
7937
(The first parameter or local variable has index&nbsp;1, and so on,
7938
until the last active local variable.)
7939
The function returns <b>nil</b> if there is no local
7940
variable with the given index,
7941
and raises an error when called with a <code>level</code> out of range.
7942
(You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.)
7943
 
7944
 
7945
<p>
7946
Variable names starting with '<code>(</code>' (open parentheses)
7947
represent internal variables
7948
(loop control variables, temporaries, and C&nbsp;function locals).
7949
 
7950
 
7951
 
7952
 
7953
<p>
7954
<hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (object)</code></a></h3>
7955
 
7956
 
7957
<p>
7958
Returns the metatable of the given <code>object</code>
7959
or <b>nil</b> if it does not have a metatable.
7960
 
7961
 
7962
 
7963
 
7964
<p>
7965
<hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3>
7966
 
7967
 
7968
<p>
7969
Returns the registry table (see <a href="#3.5">&sect;3.5</a>).
7970
 
7971
 
7972
 
7973
 
7974
<p>
7975
<hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (func, up)</code></a></h3>
7976
 
7977
 
7978
<p>
7979
This function returns the name and the value of the upvalue
7980
with index <code>up</code> of the function <code>func</code>.
7981
The function returns <b>nil</b> if there is no upvalue with the given index.
7982
 
7983
 
7984
 
7985
 
7986
<p>
7987
<hr><h3><a name="pdf-debug.setfenv"><code>debug.setfenv (object, table)</code></a></h3>
7988
 
7989
 
7990
<p>
7991
Sets the environment of the given <code>object</code> to the given <code>table</code>.
7992
Returns <code>object</code>.
7993
 
7994
 
7995
 
7996
 
7997
<p>
7998
<hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3>
7999
 
8000
 
8001
<p>
8002
Sets the given function as a hook.
8003
The string <code>mask</code> and the number <code>count</code> describe
8004
when the hook will be called.
8005
The string mask may have the following characters,
8006
with the given meaning:
8007
 
8008
<ul>
8009
<li><b><code>"c"</code>:</b> The hook is called every time Lua calls a function;</li>
8010
<li><b><code>"r"</code>:</b> The hook is called every time Lua returns from a function;</li>
8011
<li><b><code>"l"</code>:</b> The hook is called every time Lua enters a new line of code.</li>
8012
</ul><p>
8013
With a <code>count</code> different from zero,
8014
the hook is called after every <code>count</code> instructions.
8015
 
8016
 
8017
<p>
8018
When called without arguments,
8019
<a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook.
8020
 
8021
 
8022
<p>
8023
When the hook is called, its first parameter is a string
8024
describing the event that has triggered its call:
8025
<code>"call"</code>, <code>"return"</code> (or <code>"tail return"</code>),
8026
<code>"line"</code>, and <code>"count"</code>.
8027
For line events,
8028
the hook also gets the new line number as its second parameter.
8029
Inside a hook,
8030
you can call <code>getinfo</code> with level&nbsp;2 to get more information about
8031
the running function
8032
(level&nbsp;0 is the <code>getinfo</code> function,
8033
and level&nbsp;1 is the hook function),
8034
unless the event is <code>"tail return"</code>.
8035
In this case, Lua is only simulating the return,
8036
and a call to <code>getinfo</code> will return invalid data.
8037
 
8038
 
8039
 
8040
 
8041
<p>
8042
<hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3>
8043
 
8044
 
8045
<p>
8046
This function assigns the value <code>value</code> to the local variable
8047
with index <code>local</code> of the function at level <code>level</code> of the stack.
8048
The function returns <b>nil</b> if there is no local
8049
variable with the given index,
8050
and raises an error when called with a <code>level</code> out of range.
8051
(You can call <code>getinfo</code> to check whether the level is valid.)
8052
Otherwise, it returns the name of the local variable.
8053
 
8054
 
8055
 
8056
 
8057
<p>
8058
<hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (object, table)</code></a></h3>
8059
 
8060
 
8061
<p>
8062
Sets the metatable for the given <code>object</code> to the given <code>table</code>
8063
(which can be <b>nil</b>).
8064
 
8065
 
8066
 
8067
 
8068
<p>
8069
<hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (func, up, value)</code></a></h3>
8070
 
8071
 
8072
<p>
8073
This function assigns the value <code>value</code> to the upvalue
8074
with index <code>up</code> of the function <code>func</code>.
8075
The function returns <b>nil</b> if there is no upvalue
8076
with the given index.
8077
Otherwise, it returns the name of the upvalue.
8078
 
8079
 
8080
 
8081
 
8082
<p>
8083
<hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message])</code></a></h3>
8084
 
8085
 
8086
<p>
8087
Returns a string with a traceback of the call stack.
8088
An optional <code>message</code> string is appended
8089
at the beginning of the traceback. 
8090
This function is typically used with <a href="#pdf-xpcall"><code>xpcall</code></a> to produce
8091
better error messages.
8092
 
8093
 
8094
 
8095
 
8096
 
8097
 
8098
 
8099
<h1>6 - <a name="6">Lua Stand-alone</a></h1>
8100
 
8101
<p>
8102
Although Lua has been designed as an extension language,
8103
to be embedded in a host C&nbsp;program,
8104
it is also frequently used as a stand-alone language.
8105
An interpreter for Lua as a stand-alone language,
8106
called simply <code>lua</code>,
8107
is provided with the standard distribution.
8108
The stand-alone interpreter includes
8109
all standard libraries, including the debug library.
8110
Its usage is:
8111
 
8112
<pre>
8113
     lua [options] [script [args]]
8114
</pre><p>
8115
The options are:
8116
 
8117
<ul>
8118
<li><b><code>-e <em>stat</em></code>:</b> executes string <em>stat</em>;</li>
8119
<li><b><code>-l <em>mod</em></code>:</b> "requires" <em>mod</em>;</li>
8120
<li><b><code>-i</code>:</b> enters interactive mode after running <em>script</em>;</li>
8121
<li><b><code>-v</code>:</b> prints version information;</li>
8122
<li><b><code>--</code>:</b> stops handling options;</li>
8123
<li><b><code>-</code>:</b> executes <code>stdin</code> as a file and stops handling options.</li>
8124
</ul><p>
8125
After handling its options, <code>lua</code> runs the given <em>script</em>,
8126
passing to it the given <em>args</em> as string arguments.
8127
When called without arguments,
8128
<code>lua</code> behaves as <code>lua -v -i</code>
8129
when the standard input (<code>stdin</code>) is a terminal,
8130
and as <code>lua -</code> otherwise.
8131
 
8132
 
8133
<p>
8134
Before running any argument,
8135
the interpreter checks for an environment variable <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a>.
8136
If its format is <code>@<em>filename</em></code>,
8137
then <code>lua</code> executes the file.
8138
Otherwise, <code>lua</code> executes the string itself.
8139
 
8140
 
8141
<p>
8142
All options are handled in order, except <code>-i</code>.
8143
For instance, an invocation like
8144
 
8145
<pre>
8146
     $ lua -e'a=1' -e 'print(a)' script.lua
8147
</pre><p>
8148
will first set <code>a</code> to 1, then print the value of <code>a</code> (which is '<code>1</code>'),
8149
and finally run the file <code>script.lua</code> with no arguments.
8150
(Here <code>$</code> is the shell prompt. Your prompt may be different.)
8151
 
8152
 
8153
<p>
8154
Before starting to run the script,
8155
<code>lua</code> collects all arguments in the command line
8156
in a global table called <code>arg</code>.
8157
The script name is stored at index 0,
8158
the first argument after the script name goes to index 1,
8159
and so on.
8160
Any arguments before the script name
8161
(that is, the interpreter name plus the options)
8162
go to negative indices.
8163
For instance, in the call
8164
 
8165
<pre>
8166
     $ lua -la b.lua t1 t2
8167
</pre><p>
8168
the interpreter first runs the file <code>a.lua</code>,
8169
then creates a table
8170
 
8171
<pre>
8172
     arg = { [-2] = "lua", [-1] = "-la",
8173
             [0] = "b.lua",
8174
             [1] = "t1", [2] = "t2" }
8175
</pre><p>
8176
and finally runs the file <code>b.lua</code>.
8177
The script is called with <code>arg[1]</code>, <code>arg[2]</code>, &middot;&middot;&middot;
8178
as arguments;
8179
it can also access these arguments with the vararg expression '<code>...</code>'.
8180
 
8181
 
8182
<p>
8183
In interactive mode,
8184
if you write an incomplete statement,
8185
the interpreter waits for its completion
8186
by issuing a different prompt.
8187
 
8188
 
8189
<p>
8190
If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string,
8191
then its value is used as the prompt.
8192
Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string,
8193
its value is used as the secondary prompt
8194
(issued during incomplete statements).
8195
Therefore, both prompts can be changed directly on the command line.
8196
For instance,
8197
 
8198
<pre>
8199
     $ lua -e"_PROMPT='myprompt&gt; '" -i
8200
</pre><p>
8201
(the outer pair of quotes is for the shell,
8202
the inner pair is for Lua),
8203
or in any Lua programs by assigning to <code>_PROMPT</code>.
8204
Note the use of <code>-i</code> to enter interactive mode; otherwise,
8205
the program would just end silently right after the assignment to <code>_PROMPT</code>.
8206
 
8207
 
8208
<p>
8209
To allow the use of Lua as a
8210
script interpreter in Unix systems,
8211
the stand-alone interpreter skips
8212
the first line of a chunk if it starts with <code>#</code>.
8213
Therefore, Lua scripts can be made into executable programs
8214
by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form,
8215
as in
8216
 
8217
<pre>
8218
     #!/usr/local/bin/lua
8219
</pre><p>
8220
(Of course,
8221
the location of the Lua interpreter may be different in your machine.
8222
If <code>lua</code> is in your <code>PATH</code>,
8223
then 
8224
 
8225
<pre>
8226
     #!/usr/bin/env lua
8227
</pre><p>
8228
is a more portable solution.) 
8229
 
8230
 
8231
 
8232
<h1>7 - <a name="7">Incompatibilities with the Previous Version</a></h1>
8233
 
8234
<p>
8235
Here we list the incompatibilities that may be found when moving a program
8236
from Lua&nbsp;5.0 to Lua&nbsp;5.1.
8237
You can avoid most of the incompatibilities compiling Lua with
8238
appropriate options (see file <code>luaconf.h</code>).
8239
However,
8240
all these compatibility options will be removed in the next version of Lua.
8241
 
8242
 
8243
 
8244
<h2>7.1 - <a name="7.1">Changes in the Language</a></h2>
8245
<ul>
8246
 
8247
<li>
8248
The vararg system changed from the pseudo-argument <code>arg</code> with a
8249
table with the extra arguments to the vararg expression.
8250
(Option <code>LUA_COMPAT_VARARG</code> in <code>luaconf.h</code>.)
8251
</li>
8252
 
8253
<li>
8254
There was a subtle change in the scope of the implicit
8255
variables of the <b>for</b> statement and for the <b>repeat</b> statement.
8256
</li>
8257
 
8258
<li>
8259
The long string/long comment syntax (<code>[[<em>string</em>]]</code>)
8260
does not allow nesting.
8261
You can use the new syntax (<code>[=[<em>string</em>]=]</code>) in these cases.
8262
(Option <code>LUA_COMPAT_LSTR</code> in <code>luaconf.h</code>.)
8263
</li>
8264
 
8265
</ul>
8266
 
8267
 
8268
 
8269
 
8270
<h2>7.2 - <a name="7.2">Changes in the Libraries</a></h2>
8271
<ul>
8272
 
8273
<li>
8274
Function <code>string.gfind</code> was renamed <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>.
8275
(Option <code>LUA_COMPAT_GFIND</code>)
8276
</li>
8277
 
8278
<li>
8279
When <a href="#pdf-string.gsub"><code>string.gsub</code></a> is called with a function as its
8280
third argument,
8281
whenever this function returns <b>nil</b> or <b>false</b> the
8282
replacement string is the whole match,
8283
instead of the empty string.
8284
</li>
8285
 
8286
<li>
8287
Function <code>table.setn</code> was deprecated.
8288
Function <code>table.getn</code> corresponds
8289
to the new length operator (<code>#</code>);
8290
use the operator instead of the function.
8291
(Option <code>LUA_COMPAT_GETN</code>)
8292
</li>
8293
 
8294
<li>
8295
Function <code>loadlib</code> was renamed <a href="#pdf-package.loadlib"><code>package.loadlib</code></a>.
8296
(Option <code>LUA_COMPAT_LOADLIB</code>)
8297
</li>
8298
 
8299
<li>
8300
Function <code>math.mod</code> was renamed <a href="#pdf-math.fmod"><code>math.fmod</code></a>.
8301
(Option <code>LUA_COMPAT_MOD</code>)
8302
</li>
8303
 
8304
<li>
8305
Functions <code>table.foreach</code> and <code>table.foreachi</code> are deprecated.
8306
You can use a for loop with <code>pairs</code> or <code>ipairs</code> instead.
8307
</li>
8308
 
8309
<li>
8310
There were substantial changes in function <a href="#pdf-require"><code>require</code></a> due to
8311
the new module system.
8312
However, the new behavior is mostly compatible with the old,
8313
but <code>require</code> gets the path from <a href="#pdf-package.path"><code>package.path</code></a> instead
8314
of from <code>LUA_PATH</code>.
8315
</li>
8316
 
8317
<li>
8318
Function <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> has different arguments.
8319
Function <code>gcinfo</code> is deprecated;
8320
use <code>collectgarbage("count")</code> instead.
8321
</li>
8322
 
8323
</ul>
8324
 
8325
 
8326
 
8327
 
8328
<h2>7.3 - <a name="7.3">Changes in the API</a></h2>
8329
<ul>
8330
 
8331
<li>
8332
The <code>luaopen_*</code> functions (to open libraries)
8333
cannot be called directly,
8334
like a regular C function.
8335
They must be called through Lua,
8336
like a Lua function.
8337
</li>
8338
 
8339
<li>
8340
Function <code>lua_open</code> was replaced by <a href="#lua_newstate"><code>lua_newstate</code></a> to
8341
allow the user to set a memory-allocation function.
8342
You can use <a href="#luaL_newstate"><code>luaL_newstate</code></a> from the standard library to
8343
create a state with a standard allocation function
8344
(based on <code>realloc</code>).
8345
</li>
8346
 
8347
<li>
8348
Functions <code>luaL_getn</code> and <code>luaL_setn</code>
8349
(from the auxiliary library) are deprecated.
8350
Use <a href="#lua_objlen"><code>lua_objlen</code></a> instead of <code>luaL_getn</code>
8351
and nothing instead of <code>luaL_setn</code>.
8352
</li>
8353
 
8354
<li>
8355
Function <code>luaL_openlib</code> was replaced by <a href="#luaL_register"><code>luaL_register</code></a>.
8356
</li>
8357
 
8358
<li>
8359
Function <code>luaL_checkudata</code> now throws an error when the given value
8360
is not a userdata of the expected type.
8361
(In Lua&nbsp;5.0 it returned <code>NULL</code>.)
8362
</li>
8363
 
8364
</ul>
8365
 
8366
 
8367
 
8368
 
8369
<h1>8 - <a name="8">The Complete Syntax of Lua</a></h1>
8370
 
8371
<p>
8372
Here is the complete syntax of Lua in extended BNF.
8373
(It does not describe operator precedences.)
8374
 
8375
 
8376
 
8377
 
8378
<pre>
8379
 
8380
	chunk ::= {stat [`<b>;</b>&acute;]} [laststat [`<b>;</b>&acute;]]
8381
 
8382
	block ::= chunk
8383
 
8384
	stat ::=  varlist1 `<b>=</b>&acute; explist1 | 
8385
		 functioncall | 
8386
		 <b>do</b> block <b>end</b> | 
8387
		 <b>while</b> exp <b>do</b> block <b>end</b> | 
8388
		 <b>repeat</b> block <b>until</b> exp | 
8389
		 <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | 
8390
		 <b>for</b> Name `<b>=</b>&acute; exp `<b>,</b>&acute; exp [`<b>,</b>&acute; exp] <b>do</b> block <b>end</b> | 
8391
		 <b>for</b> namelist <b>in</b> explist1 <b>do</b> block <b>end</b> | 
8392
		 <b>function</b> funcname funcbody | 
8393
		 <b>local</b> <b>function</b> Name funcbody | 
8394
		 <b>local</b> namelist [`<b>=</b>&acute; explist1] 
8395
 
8396
	laststat ::= <b>return</b> [explist1] | <b>break</b>
8397
 
8398
	funcname ::= Name {`<b>.</b>&acute; Name} [`<b>:</b>&acute; Name]
8399
 
8400
	varlist1 ::= var {`<b>,</b>&acute; var}
8401
 
8402
	var ::=  Name | prefixexp `<b>[</b>&acute; exp `<b>]</b>&acute; | prefixexp `<b>.</b>&acute; Name 
8403
 
8404
	namelist ::= Name {`<b>,</b>&acute; Name}
8405
 
8406
	explist1 ::= {exp `<b>,</b>&acute;} exp
8407
 
8408
	exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | `<b>...</b>&acute; | function | 
8409
		 prefixexp | tableconstructor | exp binop exp | unop exp 
8410
 
8411
	prefixexp ::= var | functioncall | `<b>(</b>&acute; exp `<b>)</b>&acute;
8412
 
8413
	functioncall ::=  prefixexp args | prefixexp `<b>:</b>&acute; Name args 
8414
 
8415
	args ::=  `<b>(</b>&acute; [explist1] `<b>)</b>&acute; | tableconstructor | String 
8416
 
8417
	function ::= <b>function</b> funcbody
8418
 
8419
	funcbody ::= `<b>(</b>&acute; [parlist1] `<b>)</b>&acute; block <b>end</b>
8420
 
8421
	parlist1 ::= namelist [`<b>,</b>&acute; `<b>...</b>&acute;] | `<b>...</b>&acute;
8422
 
8423
	tableconstructor ::= `<b>{</b>&acute; [fieldlist] `<b>}</b>&acute;
8424
 
8425
	fieldlist ::= field {fieldsep field} [fieldsep]
8426
 
8427
	field ::= `<b>[</b>&acute; exp `<b>]</b>&acute; `<b>=</b>&acute; exp | Name `<b>=</b>&acute; exp | exp
8428
 
8429
	fieldsep ::= `<b>,</b>&acute; | `<b>;</b>&acute;
8430
 
8431
	binop ::= `<b>+</b>&acute; | `<b>-</b>&acute; | `<b>*</b>&acute; | `<b>/</b>&acute; | `<b>^</b>&acute; | `<b>%</b>&acute; | `<b>..</b>&acute; | 
8432
		 `<b>&lt;</b>&acute; | `<b>&lt;=</b>&acute; | `<b>&gt;</b>&acute; | `<b>&gt;=</b>&acute; | `<b>==</b>&acute; | `<b>~=</b>&acute; | 
8433
		 <b>and</b> | <b>or</b>
8434
 
8435
	unop ::= `<b>-</b>&acute; | <b>not</b> | `<b>#</b>&acute;
8436
 
8437
</pre>
8438
 
8439
<p>
8440
 
8441
 
8442
 
8443
 
8444
 
8445
 
8446
<HR>
8447
<SMALL>
8448
Last update:
8449
Mon Jun  5 17:05:27 BRT 2006
8450
</SMALL>
8451
<!--
8452
Last change: ready for Lua 5.1.1
8453
-->
8454
 
8455
</body></html>
8456