forked from LuaDist/lua
-
Notifications
You must be signed in to change notification settings - Fork 9
/
manual.html
10835 lines (7302 loc) · 314 KB
/
manual.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Lua 5.3 Reference Manual</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
<LINK REL="stylesheet" TYPE="text/css" HREF="manual.css">
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1>
<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A>
Lua 5.3 Reference Manual
</H1>
<P>
by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
<P>
<SMALL>
Copyright © 2015 Lua.org, PUC-Rio.
Freely available under the terms of the
<a href="http://www.lua.org/license.html">Lua license</a>.
</SMALL>
<DIV CLASS="menubar">
<A HREF="contents.html#contents">contents</A>
·
<A HREF="contents.html#index">index</A>
·
<A HREF="http://www.lua.org/manual/">other versions</A>
</DIV>
<!-- ====================================================================== -->
<p>
<!-- $Id: manual.of,v 1.153 2015/11/25 16:57:42 roberto Exp $ -->
<h1>1 – <a name="1">Introduction</a></h1>
<p>
Lua is an extension programming language designed to support
general procedural programming with data description
facilities.
Lua also offers good support for object-oriented programming,
functional programming, and data-driven programming.
Lua is intended to be used as a powerful, lightweight,
embeddable scripting language for any program that needs one.
Lua is implemented as a library, written in <em>clean C</em>,
the common subset of Standard C and C++.
<p>
As an extension language, Lua has no notion of a "main" program:
it only works <em>embedded</em> in a host client,
called the <em>embedding program</em> or simply the <em>host</em>.
The host program can invoke functions to execute a piece of Lua code,
can write and read Lua variables,
and can register C functions to be called by Lua code.
Through the use of C functions, Lua can be augmented to cope with
a wide range of different domains,
thus creating customized programming languages sharing a syntactical framework.
The Lua distribution includes a sample host program called <code>lua</code>,
which uses the Lua library to offer a complete, standalone Lua interpreter,
for interactive or batch use.
<p>
Lua is free software,
and is provided as usual with no guarantees,
as stated in its license.
The implementation described in this manual is available
at Lua's official web site, <code>www.lua.org</code>.
<p>
Like any other reference manual,
this document is dry in places.
For a discussion of the decisions behind the design of Lua,
see the technical papers available at Lua's web site.
For a detailed introduction to programming in Lua,
see Roberto's book, <em>Programming in Lua</em>.
<h1>2 – <a name="2">Basic Concepts</a></h1>
<p>
This section describes the basic concepts of the language.
<h2>2.1 – <a name="2.1">Values and Types</a></h2>
<p>
Lua is a <em>dynamically typed language</em>.
This means that
variables do not have types; only values do.
There are no type definitions in the language.
All values carry their own type.
<p>
All values in Lua are <em>first-class values</em>.
This means that all values can be stored in variables,
passed as arguments to other functions, and returned as results.
<p>
There are eight basic types in Lua:
<em>nil</em>, <em>boolean</em>, <em>number</em>,
<em>string</em>, <em>function</em>, <em>userdata</em>,
<em>thread</em>, and <em>table</em>.
The type <em>nil</em> has one single value, <b>nil</b>,
whose main property is to be different from any other value;
it usually represents the absence of a useful value.
The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>.
Both <b>nil</b> and <b>false</b> make a condition false;
any other value makes it true.
The type <em>number</em> represents both
integer numbers and real (floating-point) numbers.
The type <em>string</em> represents immutable sequences of bytes.
Lua is 8-bit clean:
strings can contain any 8-bit value,
including embedded zeros ('<code>\0</code>').
Lua is also encoding-agnostic;
it makes no assumptions about the contents of a string.
<p>
The type <em>number</em> uses two internal representations,
or two subtypes,
one called <em>integer</em> and the other called <em>float</em>.
Lua has explicit rules about when each representation is used,
but it also converts between them automatically as needed (see <a href="#3.4.3">§3.4.3</a>).
Therefore,
the programmer may choose to mostly ignore the difference
between integers and floats
or to assume complete control over the representation of each number.
Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
but you can also compile Lua so that it
uses 32-bit integers and/or single-precision (32-bit) floats.
The option with 32 bits for both integers and floats
is particularly attractive
for small machines and embedded systems.
(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
<p>
Lua can call (and manipulate) functions written in Lua and
functions written in C (see <a href="#3.4.10">§3.4.10</a>).
Both are represented by the type <em>function</em>.
<p>
The type <em>userdata</em> is provided to allow arbitrary C data to
be stored in Lua variables.
A userdata value represents a block of raw memory.
There are two kinds of userdata:
<em>full userdata</em>,
which is an object with a block of memory managed by Lua,
and <em>light userdata</em>,
which is simply a C pointer value.
Userdata has no predefined operations in Lua,
except assignment and identity test.
By using <em>metatables</em>,
the programmer can define operations for full userdata values
(see <a href="#2.4">§2.4</a>).
Userdata values cannot be created or modified in Lua,
only through the C API.
This guarantees the integrity of data owned by the host program.
<p>
The type <em>thread</em> represents independent threads of execution
and it is used to implement coroutines (see <a href="#2.6">§2.6</a>).
Lua threads are not related to operating-system threads.
Lua supports coroutines on all systems,
even those that do not support threads natively.
<p>
The type <em>table</em> implements associative arrays,
that is, arrays that can be indexed not only with numbers,
but with any Lua value except <b>nil</b> and NaN.
(<em>Not a Number</em> is a special value used to represent
undefined or unrepresentable numerical results, such as <code>0/0</code>.)
Tables can be <em>heterogeneous</em>;
that is, they can contain values of all types (except <b>nil</b>).
Any key with value <b>nil</b> is not considered part of the table.
Conversely, any key that is not part of a table has
an associated value <b>nil</b>.
<p>
Tables are the sole data-structuring mechanism in Lua;
they can be used to represent ordinary arrays, sequences,
symbol tables, sets, records, graphs, trees, etc.
To represent records, Lua uses the field name as an index.
The language supports this representation by
providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
There are several convenient ways to create tables in Lua
(see <a href="#3.4.9">§3.4.9</a>).
<p>
We use the term <em>sequence</em> to denote a table where
the set of all positive numeric keys is equal to {1..<em>n</em>}
for some non-negative integer <em>n</em>,
which is called the length of the sequence (see <a href="#3.4.7">§3.4.7</a>).
<p>
Like indices,
the values of table fields can be of any type.
In particular,
because functions are first-class values,
table fields can contain functions.
Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">§3.4.11</a>).
<p>
The indexing of tables follows
the definition of raw equality in the language.
The expressions <code>a[i]</code> and <code>a[j]</code>
denote the same table element
if and only if <code>i</code> and <code>j</code> are raw equal
(that is, equal without metamethods).
In particular, floats with integral values
are equal to their respective integers
(e.g., <code>1.0 == 1</code>).
To avoid ambiguities,
any float with integral value used as a key
is converted to its respective integer.
For instance, if you write <code>a[2.0] = true</code>,
the actual key inserted into the table will be the
integer <code>2</code>.
(On the other hand,
2 and "<code>2</code>" are different Lua values and therefore
denote different table entries.)
<p>
Tables, functions, threads, and (full) userdata values are <em>objects</em>:
variables do not actually <em>contain</em> these values,
only <em>references</em> to them.
Assignment, parameter passing, and function returns
always manipulate references to such values;
these operations do not imply any kind of copy.
<p>
The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type
of a given value (see <a href="#6.1">§6.1</a>).
<h2>2.2 – <a name="2.2">Environments and the Global Environment</a></h2>
<p>
As will be discussed in <a href="#3.2">§3.2</a> and <a href="#3.3.3">§3.3.3</a>,
any reference to a free name
(that is, a name not bound to any declaration) <code>var</code>
is syntactically translated to <code>_ENV.var</code>.
Moreover, every chunk is compiled in the scope of
an external local variable named <code>_ENV</code> (see <a href="#3.3.2">§3.3.2</a>),
so <code>_ENV</code> itself is never a free name in a chunk.
<p>
Despite the existence of this external <code>_ENV</code> variable and
the translation of free names,
<code>_ENV</code> is a completely regular name.
In particular,
you can define new variables and parameters with that name.
Each reference to a free name uses the <code>_ENV</code> that is
visible at that point in the program,
following the usual visibility rules of Lua (see <a href="#3.5">§3.5</a>).
<p>
Any table used as the value of <code>_ENV</code> is called an <em>environment</em>.
<p>
Lua keeps a distinguished environment called the <em>global environment</em>.
This value is kept at a special index in the C registry (see <a href="#4.5">§4.5</a>).
In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
(<a href="#pdf-_G"><code>_G</code></a> is never used internally.)
<p>
When Lua loads a chunk,
the default value for its <code>_ENV</code> upvalue
is the global environment (see <a href="#pdf-load"><code>load</code></a>).
Therefore, by default,
free names in Lua code refer to entries in the global environment
(and, therefore, they are also called <em>global variables</em>).
Moreover, all standard libraries are loaded in the global environment
and some functions there operate on that environment.
You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
to load a chunk with a different environment.
(In C, you have to load the chunk and then change the value
of its first upvalue.)
<h2>2.3 – <a name="2.3">Error Handling</a></h2>
<p>
Because Lua is an embedded extension language,
all Lua actions start from C code in the host program
calling a function from the Lua library.
(When you use Lua standalone,
the <code>lua</code> application is the host program.)
Whenever an error occurs during
the compilation or execution of a Lua chunk,
control returns to the host,
which can take appropriate measures
(such as printing an error message).
<p>
Lua code can explicitly generate an error by calling the
<a href="#pdf-error"><code>error</code></a> function.
If you need to catch errors in Lua,
you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a>
to call a given function in <em>protected mode</em>.
<p>
Whenever there is an error,
an <em>error object</em> (also called an <em>error message</em>)
is propagated with information about the error.
Lua itself only generates errors whose error object is a string,
but programs may generate errors with
any value as the error object.
It is up to the Lua program or its host to handle such error objects.
<p>
When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>,
you may give a <em>message handler</em>
to be called in case of errors.
This function is called with the original error message
and returns a new error message.
It is called before the error unwinds the stack,
so that it can gather more information about the error,
for instance by inspecting the stack and creating a stack traceback.
This message handler is still protected by the protected call;
so, an error inside the message handler
will call the message handler again.
If this loop goes on for too long,
Lua breaks it and returns an appropriate message.
<h2>2.4 – <a name="2.4">Metatables and Metamethods</a></h2>
<p>
Every value in Lua can have a <em>metatable</em>.
This <em>metatable</em> is an ordinary Lua table
that defines the behavior of the original value
under certain special operations.
You can change several aspects of the behavior
of operations over a value by setting specific fields in its metatable.
For instance, when a non-numeric value is the operand of an addition,
Lua checks for a function in the field "<code>__add</code>" of the value's metatable.
If it finds one,
Lua calls this function to perform the addition.
<p>
The keys in a metatable are derived from the <em>event</em> names;
the corresponding values are called <em>metamethods</em>.
In the previous example, the event is <code>"add"</code>
and the metamethod is the function that performs the addition.
<p>
You can query the metatable of any value
using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function.
<p>
You can replace the metatable of tables
using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
You cannot change the metatable of other types from Lua code
(except by using the debug library (<a href="#6.10">§6.10</a>));
you should use the C API for that.
<p>
Tables and full userdata have individual metatables
(although multiple tables and userdata can share their metatables).
Values of all other types share one single metatable per type;
that is, there is one single metatable for all numbers,
one for all strings, etc.
By default, a value has no metatable,
but the string library sets a metatable for the string type (see <a href="#6.4">§6.4</a>).
<p>
A metatable controls how an object behaves in
arithmetic operations, bitwise operations,
order comparisons, concatenation, length operation, calls, and indexing.
A metatable also can define a function to be called
when a userdata or a table is garbage collected (<a href="#2.5">§2.5</a>).
<p>
A detailed list of events controlled by metatables is given next.
Each operation is identified by its corresponding event name.
The key for each event is a string with its name prefixed by
two underscores, '<code>__</code>';
for instance, the key for operation "add" is the
string "<code>__add</code>".
Note that queries for metamethods are always raw;
the access to a metamethod does not invoke other metamethods.
<p>
For the unary operators (negation, length, and bitwise not),
the metamethod is computed and called with a dummy second operand,
equal to the first one.
This extra operand is only to simplify Lua's internals
(by making these operators behave like a binary operation)
and may be removed in future versions.
(For most uses this extra operand is irrelevant.)
<ul>
<li><b>"add": </b>
the <code>+</code> operation.
If any operand for an addition is not a number
(nor a string coercible to a number),
Lua will try to call a metamethod.
First, Lua will check the first operand (even if it is valid).
If that operand does not define a metamethod for the "<code>__add</code>" event,
then Lua will check the second operand.
If Lua can find a metamethod,
it calls the metamethod with the two operands as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
Otherwise,
it raises an error.
</li>
<li><b>"sub": </b>
the <code>-</code> operation.
Behavior similar to the "add" operation.
</li>
<li><b>"mul": </b>
the <code>*</code> operation.
Behavior similar to the "add" operation.
</li>
<li><b>"div": </b>
the <code>/</code> operation.
Behavior similar to the "add" operation.
</li>
<li><b>"mod": </b>
the <code>%</code> operation.
Behavior similar to the "add" operation.
</li>
<li><b>"pow": </b>
the <code>^</code> (exponentiation) operation.
Behavior similar to the "add" operation.
</li>
<li><b>"unm": </b>
the <code>-</code> (unary minus) operation.
Behavior similar to the "add" operation.
</li>
<li><b>"idiv": </b>
the <code>//</code> (floor division) operation.
Behavior similar to the "add" operation.
</li>
<li><b>"band": </b>
the <code>&</code> (bitwise and) operation.
Behavior similar to the "add" operation,
except that Lua will try a metamethod
if any operand is neither an integer
nor a value coercible to an integer (see <a href="#3.4.3">§3.4.3</a>).
</li>
<li><b>"bor": </b>
the <code>|</code> (bitwise or) operation.
Behavior similar to the "band" operation.
</li>
<li><b>"bxor": </b>
the <code>~</code> (bitwise exclusive or) operation.
Behavior similar to the "band" operation.
</li>
<li><b>"bnot": </b>
the <code>~</code> (bitwise unary not) operation.
Behavior similar to the "band" operation.
</li>
<li><b>"shl": </b>
the <code><<</code> (bitwise left shift) operation.
Behavior similar to the "band" operation.
</li>
<li><b>"shr": </b>
the <code>>></code> (bitwise right shift) operation.
Behavior similar to the "band" operation.
</li>
<li><b>"concat": </b>
the <code>..</code> (concatenation) operation.
Behavior similar to the "add" operation,
except that Lua will try a metamethod
if any operand is neither a string nor a number
(which is always coercible to a string).
</li>
<li><b>"len": </b>
the <code>#</code> (length) operation.
If the object is not a string,
Lua will try its metamethod.
If there is a metamethod,
Lua calls it with the object as argument,
and the result of the call
(always adjusted to one value)
is the result of the operation.
If there is no metamethod but the object is a table,
then Lua uses the table length operation (see <a href="#3.4.7">§3.4.7</a>).
Otherwise, Lua raises an error.
</li>
<li><b>"eq": </b>
the <code>==</code> (equal) operation.
Behavior similar to the "add" operation,
except that Lua will try a metamethod only when the values
being compared are either both tables or both full userdata
and they are not primitively equal.
The result of the call is always converted to a boolean.
</li>
<li><b>"lt": </b>
the <code><</code> (less than) operation.
Behavior similar to the "add" operation,
except that Lua will try a metamethod only when the values
being compared are neither both numbers nor both strings.
The result of the call is always converted to a boolean.
</li>
<li><b>"le": </b>
the <code><=</code> (less equal) operation.
Unlike other operations,
the less-equal operation can use two different events.
First, Lua looks for the "<code>__le</code>" metamethod in both operands,
like in the "lt" operation.
If it cannot find such a metamethod,
then it will try the "<code>__lt</code>" event,
assuming that <code>a <= b</code> is equivalent to <code>not (b < a)</code>.
As with the other comparison operators,
the result is always a boolean.
(This use of the "<code>__lt</code>" event can be removed in future versions;
it is also slower than a real "<code>__le</code>" metamethod.)
</li>
<li><b>"index": </b>
The indexing access <code>table[key]</code>.
This event happens when <code>table</code> is not a table or
when <code>key</code> is not present in <code>table</code>.
The metamethod is looked up in <code>table</code>.
<p>
Despite the name,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with <code>table</code> and <code>key</code> as arguments.
If it is a table,
the final result is the result of indexing this table with <code>key</code>.
(This indexing is regular, not raw,
and therefore can trigger another metamethod.)
</li>
<li><b>"newindex": </b>
The indexing assignment <code>table[key] = value</code>.
Like the index event,
this event happens when <code>table</code> is not a table or
when <code>key</code> is not present in <code>table</code>.
The metamethod is looked up in <code>table</code>.
<p>
Like with indexing,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
If it is a table,
Lua does an indexing assignment to this table with the same key and value.
(This assignment is regular, not raw,
and therefore can trigger another metamethod.)
<p>
Whenever there is a "newindex" metamethod,
Lua does not perform the primitive assignment.
(If necessary,
the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
to do the assignment.)
</li>
<li><b>"call": </b>
The call operation <code>func(args)</code>.
This event happens when Lua tries to call a non-function value
(that is, <code>func</code> is not a function).
The metamethod is looked up in <code>func</code>.
If present,
the metamethod is called with <code>func</code> as its first argument,
followed by the arguments of the original call (<code>args</code>).
</li>
</ul>
<p>
It is a good practice to add all needed metamethods to a table
before setting it as a metatable of some object.
In particular, the "<code>__gc</code>" metamethod works only when this order
is followed (see <a href="#2.5.1">§2.5.1</a>).
<h2>2.5 – <a name="2.5">Garbage Collection</a></h2>
<p>
Lua performs automatic memory management.
This means that
you do not have to worry about allocating memory for new objects
or freeing it when the objects are no longer needed.
Lua manages memory automatically by running
a <em>garbage collector</em> to collect all <em>dead objects</em>
(that is, objects that are no longer accessible from Lua).
All memory used by Lua is subject to automatic management:
strings, tables, userdata, functions, threads, internal structures, etc.
<p>
Lua implements an incremental mark-and-sweep collector.
It uses two numbers to control its garbage-collection cycles:
the <em>garbage-collector pause</em> and
the <em>garbage-collector step multiplier</em>.
Both use percentage points as units
(e.g., a value of 100 means an internal value of 1).
<p>
The garbage-collector pause
controls how long the collector waits before starting a new cycle.
Larger values make the collector less aggressive.
Values smaller than 100 mean the collector will not wait to
start a new cycle.
A value of 200 means that the collector waits for the total memory in use
to double before starting a new cycle.
<p>
The garbage-collector step multiplier
controls the relative speed of the collector relative to
memory allocation.
Larger values make the collector more aggressive but also increase
the size of each incremental step.
You should not use values smaller than 100,
because they make the collector too slow and
can result in the collector never finishing a cycle.
The default is 200,
which means that the collector runs at "twice"
the speed of memory allocation.
<p>
If you set the step multiplier to a very large number
(larger than 10% of the maximum number of
bytes that the program may use),
the collector behaves like a stop-the-world collector.
If you then set the pause to 200,
the collector behaves as in old Lua versions,
doing a complete collection every time Lua doubles its
memory usage.
<p>
You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C
or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua.
You can also use these functions to control
the collector directly (e.g., stop and restart it).
<h3>2.5.1 – <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
<p>
You can set garbage-collector metamethods for tables
and, using the C API,
for full userdata (see <a href="#2.4">§2.4</a>).
These metamethods are also called <em>finalizers</em>.
Finalizers allow you to coordinate Lua's garbage collection
with external resource management
(such as closing files, network or database connections,
or freeing your own memory).
<p>
For an object (table or userdata) to be finalized when collected,
you must <em>mark</em> it for finalization.
You mark an object for finalization when you set its metatable
and the metatable has a field indexed by the string "<code>__gc</code>".
Note that if you set a metatable without a <code>__gc</code> field
and later create that field in the metatable,
the object will not be marked for finalization.
<p>
When a marked object becomes garbage,
it is not collected immediately by the garbage collector.
Instead, Lua puts it in a list.
After the collection,
Lua goes through that list.
For each object in the list,
it checks the object's <code>__gc</code> metamethod:
If it is a function,
Lua calls it with the object as its single argument;
if the metamethod is not a function,
Lua simply ignores it.
<p>
At the end of each garbage-collection cycle,
the finalizers for objects are called in
the reverse order that the objects were marked for finalization,
among those collected in that cycle;
that is, the first finalizer to be called is the one associated
with the object marked last in the program.
The execution of each finalizer may occur at any point during
the execution of the regular code.
<p>
Because the object being collected must still be used by the finalizer,
that object (and other objects accessible only through it)
must be <em>resurrected</em> by Lua.
Usually, this resurrection is transient,
and the object memory is freed in the next garbage-collection cycle.
However, if the finalizer stores the object in some global place
(e.g., a global variable),
then the resurrection is permanent.
Moreover, if the finalizer marks a finalizing object for finalization again,
its finalizer will be called again in the next cycle where the
object is unreachable.
In any case,
the object memory is freed only in a GC cycle where
the object is unreachable and not marked for finalization.
<p>
When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
Lua calls the finalizers of all objects marked for finalization,
following the reverse order that they were marked.
If any finalizer marks objects for collection during that phase,
these marks have no effect.
<h3>2.5.2 – <a name="2.5.2">Weak Tables</a></h3>
<p>
A <em>weak table</em> is a table whose elements are
<em>weak references</em>.
A weak reference is ignored by the garbage collector.
In other words,
if the only references to an object are weak references,
then the garbage collector will collect that object.
<p>
A weak table can have weak keys, weak values, or both.
A table with weak values allows the collection of its values,
but prevents the collection of its keys.
A table with both weak keys and weak values allows the collection of
both keys and values.
In any case, if either the key or the value is collected,
the whole pair is removed from the table.
The weakness of a table is controlled by the
<code>__mode</code> field of its metatable.
If the <code>__mode</code> field is a string containing the character '<code>k</code>',
the keys in the table are weak.
If <code>__mode</code> contains '<code>v</code>',
the values in the table are weak.
<p>
A table with weak keys and strong values
is also called an <em>ephemeron table</em>.
In an ephemeron table,
a value is considered reachable only if its key is reachable.
In particular,
if the only reference to a key comes through its value,
the pair is removed.
<p>
Any change in the weakness of a table may take effect only
at the next collect cycle.
In particular, if you change the weakness to a stronger mode,
Lua may still collect some items from that table
before the change takes effect.
<p>
Only objects that have an explicit construction
are removed from weak tables.
Values, such as numbers and light C functions,
are not subject to garbage collection,
and therefore are not removed from weak tables
(unless their associated values are collected).
Although strings are subject to garbage collection,
they do not have an explicit construction,
and therefore are not removed from weak tables.
<p>
Resurrected objects
(that is, objects being finalized
and objects accessible only through objects being finalized)
have a special behavior in weak tables.
They are removed from weak values before running their finalizers,
but are removed from weak keys only in the next collection
after running their finalizers, when such objects are actually freed.
This behavior allows the finalizer to access properties
associated with the object through weak tables.
<p>
If a weak table is among the resurrected objects in a collection cycle,
it may not be properly cleared until the next cycle.
<h2>2.6 – <a name="2.6">Coroutines</a></h2>
<p>
Lua supports coroutines,
also called <em>collaborative multithreading</em>.
A coroutine in Lua represents an independent thread of execution.
Unlike threads in multithread systems, however,
a coroutine only suspends its execution by explicitly calling
a yield function.
<p>
You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>.
Its sole argument is a function
that is the main function of the coroutine.
The <code>create</code> function only creates a new coroutine and
returns a handle to it (an object of type <em>thread</em>);
it does not start the coroutine.
<p>
You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
passing as its first argument
a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
the coroutine starts its execution by
calling its main function.
Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
as arguments to that function.
After the coroutine starts running,
it runs until it terminates or <em>yields</em>.
<p>
A coroutine can terminate its execution in two ways:
normally, when its main function returns
(explicitly or implicitly, after the last instruction);
and abnormally, if there is an unprotected error.
In case of normal termination,
<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
plus any values returned by the coroutine main function.
In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
plus an error message.
<p>
A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
When a coroutine yields,
the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately,
even if the yield happens inside nested function calls
(that is, not in the main function,
but in a function directly or indirectly called by the main function).
In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>,
plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>.
The next time you resume the same coroutine,
it continues its execution from the point where it yielded,
with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra
arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
<p>
Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine,
but instead of returning the coroutine itself,
it returns a function that, when called, resumes the coroutine.
Any arguments passed to this function
go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>.
<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>,
except the first one (the boolean error code).
Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>,
<a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors;
any error is propagated to the caller.
<p>
As an example of how coroutines work,
consider the following code:
<pre>
function foo (a)
print("foo", a)
return coroutine.yield(2*a)
end
co = coroutine.create(function (a,b)
print("co-body", a, b)
local r = foo(a+1)
print("co-body", r)
local r, s = coroutine.yield(a+b, a-b)
print("co-body", r, s)
return b, "end"
end)
print("main", coroutine.resume(co, 1, 10))
print("main", coroutine.resume(co, "r"))
print("main", coroutine.resume(co, "x", "y"))
print("main", coroutine.resume(co, "x", "y"))
</pre><p>
When you run it, it produces the following output:
<pre>
co-body 1 10
foo 2
main true 4
co-body r