-
Notifications
You must be signed in to change notification settings - Fork 5
/
manual.of
8704 lines (6830 loc) · 258 KB
/
manual.of
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
@Ci{$Id: manual.of,v 1.174 2018/06/18 19:14:16 roberto Exp roberto $}
@C{[(-------------------------------------------------------------------------}
@manual{
@sect1{@title{Introduction}
Lua is a powerful, efficient, lightweight, embeddable scripting language.
It supports procedural programming,
object-oriented programming, functional programming,
data-driven programming, and data description.
Lua combines simple procedural syntax with powerful data description
constructs based on associative arrays and extensible semantics.
Lua is dynamically typed,
runs by interpreting bytecode with a register-based
virtual machine,
and has automatic memory management with
incremental garbage collection,
making it ideal for configuration, scripting,
and rapid prototyping.
Lua is implemented as a library, written in @emphx{clean C},
the common subset of @N{Standard C} and C++.
The Lua distribution includes a host program called @id{lua},
which uses the Lua library to offer a complete,
standalone Lua interpreter,
for interactive or batch use.
Lua is intended to be used both as a powerful, lightweight,
embeddable scripting language for any program that needs one,
and as a powerful but lightweight and efficient stand-alone language.
As an extension language, Lua has no notion of a @Q{main} program:
it works @emph{embedded} in a host client,
called the @emph{embedding program} or simply the @emphx{host}.
(Frequently, this host is the stand-alone @id{lua} program.)
The host program can invoke functions to execute a piece of Lua code,
can write and read Lua variables,
and can register @N{C functions} to be called by Lua code.
Through the use of @N{C functions}, Lua can be augmented to cope with
a wide range of different domains,
thus creating customized programming languages sharing a syntactical framework.
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, @id{www.lua.org}.
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, @emphx{Programming in Lua}.
}
@C{-------------------------------------------------------------------------}
@sect1{basic| @title{Basic Concepts}
This section describes the basic concepts of the language.
@sect2{TypesSec| @title{Values and Types}
Lua is a dynamically typed language.
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.
All values in Lua are first-class values.
This means that all values can be stored in variables,
passed as arguments to other functions, and returned as results.
There are eight @x{basic types} in Lua:
@def{nil}, @def{boolean}, @def{number},
@def{string}, @def{function}, @def{userdata},
@def{thread}, and @def{table}.
The type @emph{nil} has one single value, @nil,
whose main property is to be different from any other value;
it usually represents the absence of a useful value.
The type @emph{boolean} has two values, @false and @true.
Both @nil and @false make a condition false;
any other value makes it true.
The type @emph{number} represents both
integer numbers and real (floating-point) numbers.
The type @emph{string} represents immutable sequences of bytes.
@index{eight-bit clean}
Lua is 8-bit clean:
strings can contain any 8-bit value,
including @x{embedded zeros} (@Char{\0}).
Lua is also encoding-agnostic;
it makes no assumptions about the contents of a string.
The type @emph{number} uses two internal representations,
or two @x{subtypes},
one called @def{integer} and the other called @def{float}.
Lua has explicit rules about when each representation is used,
but it also converts between them automatically as needed @see{coercion}.
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 @id{LUA_32BITS} in file @id{luaconf.h}.)
Lua can call (and manipulate) functions written in Lua and
functions written in C @see{functioncall}.
Both are represented by the type @emph{function}.
The type @emph{userdata} is provided to allow arbitrary @N{C data} to
be stored in Lua variables.
A userdata value represents a block of raw memory.
There are two kinds of userdata:
@emphx{full userdata},
which is an object with a block of memory managed by Lua,
and @emphx{light userdata},
which is simply a @N{C pointer} value.
Userdata has no predefined operations in Lua,
except assignment and identity test.
By using @emph{metatables},
the programmer can define operations for full userdata values
@see{metatable}.
Userdata values cannot be created or modified in Lua,
only through the @N{C API}.
This guarantees the integrity of data owned by the host program.
The type @def{thread} represents independent threads of execution
and it is used to implement coroutines @see{coroutine}.
Lua threads are not related to operating-system threads.
Lua supports coroutines on all systems,
even those that do not support threads natively.
The type @emph{table} implements @x{associative arrays},
that is, @x{arrays} that can have as indices not only numbers,
but any Lua value except @nil and @x{NaN}.
(@emphx{Not a Number} is a special floating-point value
used by the @x{IEEE 754} standard to represent
undefined or unrepresentable numerical results, such as @T{0/0}.)
Tables can be @emph{heterogeneous};
that is, they can contain values of all types (except @nil).
Any key with value @nil is not considered part of the table.
Conversely, any key that is not part of a table has
an associated value @nil.
Tables are the sole data-structuring mechanism in Lua;
they can be used to represent ordinary arrays, lists,
symbol tables, sets, records, graphs, trees, etc.
To represent @x{records}, Lua uses the field name as an index.
The language supports this representation by
providing @id{a.name} as syntactic sugar for @T{a["name"]}.
There are several convenient ways to create tables in Lua
@see{tableconstructor}.
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 @emph{methods} @see{func-def}.
The indexing of tables follows
the definition of raw equality in the language.
The expressions @T{a[i]} and @T{a[j]}
denote the same table element
if and only if @id{i} and @id{j} are raw equal
(that is, equal without metamethods).
In particular, floats with integral values
are equal to their respective integers
(e.g., @T{1.0 == 1}).
To avoid ambiguities,
any float with integral value used as a key
is converted to its respective integer.
For instance, if you write @T{a[2.0] = true},
the actual key inserted into the table will be the
integer @T{2}.
(On the other hand,
2 and @St{2} are different Lua values and therefore
denote different table entries.)
Tables, functions, threads, and (full) userdata values are @emph{objects}:
variables do not actually @emph{contain} these values,
only @emph{references} to them.
Assignment, parameter passing, and function returns
always manipulate references to such values;
these operations do not imply any kind of copy.
The library function @Lid{type} returns a string describing the type
of a given value @see{predefined}.
}
@sect2{globalenv| @title{Environments and the Global Environment}
As will be discussed in @refsec{variables} and @refsec{assignment},
any reference to a free name
(that is, a name not bound to any declaration) @id{var}
is syntactically translated to @T{_ENV.var}.
Moreover, every chunk is compiled in the scope of
an external local variable named @id{_ENV} @see{chunks},
so @id{_ENV} itself is never a free name in a chunk.
Despite the existence of this external @id{_ENV} variable and
the translation of free names,
@id{_ENV} 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 @id{_ENV} that is
visible at that point in the program,
following the usual visibility rules of Lua @see{visibility}.
Any table used as the value of @id{_ENV} is called an @def{environment}.
Lua keeps a distinguished environment called the @def{global environment}.
This value is kept at a special index in the C registry @see{registry}.
In Lua, the global variable @Lid{_G} is initialized with this same value.
(@Lid{_G} is never used internally.)
When Lua loads a chunk,
the default value for its @id{_ENV} upvalue
is the global environment @seeF{load}.
Therefore, by default,
free names in Lua code refer to entries in the global environment
(and, therefore, they are also called @def{global variables}).
Moreover, all standard libraries are loaded in the global environment
and some functions there operate on that environment.
You can use @Lid{load} (or @Lid{loadfile})
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.)
}
@sect2{error| @title{Error Handling}
Because Lua is an embedded extension language,
all Lua actions start from @N{C code} in the host program
calling a function from the Lua library.
(When you use Lua standalone,
the @id{lua} 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).
Lua code can explicitly generate an error by calling the
@Lid{error} function.
If you need to catch errors in Lua,
you can use @Lid{pcall} or @Lid{xpcall}
to call a given function in @emphx{protected mode}.
Whenever there is an error,
an @def{error object} (also called an @def{error message})
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.
When you use @Lid{xpcall} or @Lid{lua_pcall},
you may give a @def{message handler}
to be called in case of errors.
This function is called with the original error object
and returns a new error object.
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.
(The message handler is called only for regular runtime errors.
It is not called for memory-allocation errors
nor for errors while running finalizers.)
}
@sect2{metatable| @title{Metatables and Metamethods}
Every value in Lua can have a @emph{metatable}.
This @def{metatable} 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 @St{__add} of the value's metatable.
If it finds one,
Lua calls this function to perform the addition.
The key for each event in a metatable is a string
with the event name prefixed by two underscores;
the corresponding values are called @def{metamethods}.
In the previous example, the key is @St{__add}
and the metamethod is the function that performs the addition.
Unless stated otherwise,
metamethods should be function values.
You can query the metatable of any value
using the @Lid{getmetatable} function.
Lua queries metamethods in metatables using a raw access @seeF{rawget}.
So, to retrieve the metamethod for event @id{ev} in object @id{o},
Lua does the equivalent to the following code:
@verbatim{
rawget(getmetatable(@rep{o}) or {}, "__@rep{ev}")
}
You can replace the metatable of tables
using the @Lid{setmetatable} function.
You cannot change the metatable of other types from Lua code
(except by using the @link{debuglib|debug library});
you should use the @N{C API} for that.
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{strlib}.
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 @link{GC|garbage collected}.
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.)
A detailed list of events controlled by metatables is given next.
Each operation is identified by its corresponding key.
@description{
@item{@idx{__add}|
the addition (@T{+}) 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 @idx{__add},
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.
}
@item{@idx{__sub}|
the subtraction (@T{-}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__mul}|
the multiplication (@T{*}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__div}|
the division (@T{/}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__mod}|
the modulo (@T{%}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__pow}|
the exponentiation (@T{^}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__unm}|
the negation (unary @T{-}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__idiv}|
the floor division (@T{//}) operation.
Behavior similar to the addition operation.
}
@item{@idx{__band}|
the bitwise AND (@T{&}) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod
if any operand is neither an integer
nor a value coercible to an integer @see{coercion}.
}
@item{@idx{__bor}|
the bitwise OR (@T{|}) operation.
Behavior similar to the bitwise AND operation.
}
@item{@idx{__bxor}|
the bitwise exclusive OR (binary @T{~}) operation.
Behavior similar to the bitwise AND operation.
}
@item{@idx{__bnot}|
the bitwise NOT (unary @T{~}) operation.
Behavior similar to the bitwise AND operation.
}
@item{@idx{__shl}|
the bitwise left shift (@T{<<}) operation.
Behavior similar to the bitwise AND operation.
}
@item{@idx{__shr}|
the bitwise right shift (@T{>>}) operation.
Behavior similar to the bitwise AND operation.
}
@item{@idx{__concat}|
the concatenation (@T{..}) operation.
Behavior similar to the addition 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).
}
@item{@idx{__len}|
the length (@T{#}) 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{len-op}.
Otherwise, Lua raises an error.
}
@item{@idx{__eq}|
the equal (@T{==}) operation.
Behavior similar to the addition 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.
}
@item{@idx{__lt}|
the less than (@T{<}) operation.
Behavior similar to the addition 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.
}
@item{@idx{__le}|
the less equal (@T{<=}) operation.
Unlike other operations,
the less-equal operation can use two different events.
First, Lua looks for the @idx{__le} metamethod in both operands,
like in the less than operation.
If it cannot find such a metamethod,
then it will try the @idx{__lt} metamethod,
assuming that @T{a <= b} is equivalent to @T{not (b < a)}.
As with the other comparison operators,
the result is always a boolean.
(This use of the @idx{__lt} event can be removed in future versions;
it is also slower than a real @idx{__le} metamethod.)
}
@item{@idx{__index}|
The indexing access operation @T{table[key]}.
This event happens when @id{table} is not a table or
when @id{key} is not present in @id{table}.
The metamethod is looked up in @id{table}.
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 @id{table} and @id{key} as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
If it is a table,
the final result is the result of indexing this table with @id{key}.
(This indexing is regular, not raw,
and therefore can trigger another metamethod.)
}
@item{@idx{__newindex}|
The indexing assignment @T{table[key] = value}.
Like the index event,
this event happens when @id{table} is not a table or
when @id{key} is not present in @id{table}.
The metamethod is looked up in @id{table}.
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 @id{table}, @id{key}, and @id{value} 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.)
Whenever there is a @idx{__newindex} metamethod,
Lua does not perform the primitive assignment.
(If necessary,
the metamethod itself can call @Lid{rawset}
to do the assignment.)
}
@item{@idx{__call}|
The call operation @T{func(args)}.
This event happens when Lua tries to call a non-function value
(that is, @id{func} is not a function).
The metamethod is looked up in @id{func}.
If present,
the metamethod is called with @id{func} as its first argument,
followed by the arguments of the original call (@id{args}).
All results of the call
are the result of the operation.
(This is the only metamethod that allows multiple results.)
}
}
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 @idx{__gc} metamethod works only when this order
is followed @see{finalizers}.
Because metatables are regular tables,
they can contain arbitrary fields,
not only the event names defined above.
Some functions in the standard library
(e.g., @Lid{tostring})
use other fields in metatables for their own purposes.
}
@sect2{GC| @title{Garbage Collection}
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 @def{garbage collector} to collect all @emph{dead objects}
(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.
The garbage collector (GC) in Lua can work in two modes:
incremental and generational.
The default GC mode with the default parameters
are adequate for most uses.
Programs that waste a large proportion of its time
allocating and freeing memory can benefit from other settings.
Keep in mind that the GC behavior is non-portable
both across platforms and across different Lua releases;
therefore, optimal settings are also non-portable.
You can change the GC mode and parameters by calling
@Lid{lua_gc} in C
or @Lid{collectgarbage} in Lua.
You can also use these functions to control
the collector directly (e.g., stop and restart it).
@sect3{@title{Incremental Garbage Collection}
In incremental mode,
each GC cycle performs a mark-and-sweep collection in small steps
interleaved with the program's execution.
In this mode,
the collector uses three numbers to control its garbage-collection cycles:
the @def{garbage-collector pause},
the @def{garbage-collector step multiplier},
and the @def{garbage-collector step size}.
The garbage-collector pause
controls how long the collector waits before starting a new cycle.
The collector starts a new cycle when the use of memory
hits @M{n%} of the use after the previous collection.
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.
The default value is 200; the maximum value is 1000.
The garbage-collector step multiplier
controls the relative speed of the collector relative to
memory allocation,
that is,
how many elements it marks or sweeps for each
kilobyte of memory allocated.
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 value is 100; the maximum value is 1000.
The garbage-collector step size controls the
size of each incremental step,
specifically how many bytes the interpreter allocates
before performing a step.
This parameter is logarithmic:
A value of @M{n} means the interpreter will allocate @M{2@sp{n}}
bytes between steps and perform equivalent work during the step.
A large value (e.g., 60) makes the collector a stop-the-world
(non-incremental) collector.
The default value is 13,
which makes for steps of approximately @N{8 Kbytes}.
}
@sect3{@title{Generational Garbage Collection}
In generational mode,
the collector does frequent @emph{minor} collections,
which traverses only objects recently created.
If after a minor collection the use of memory is still above a limit,
the collector does a @emph{major} collection,
which traverses all objects.
The generational mode uses two parameters:
the @def{major multiplier} and the @def{the minor multiplier}.
The major multiplier controls the frequency of major collections.
For a major multiplier @M{x},
a new major collection will be done when memory
grows @M{x%} larger than the memory in use after the previous major
collection.
For instance, for a multiplier of 100,
the collector will do a major collection when the use of memory
gets larger than twice the use after the previous collection.
The default value is 100; the maximum value is 1000.
The minor multiplier controls the frequency of minor collections.
For a minor multiplier @M{x},
a new minor collection will be done when memory
grows @M{x%} larger than the memory in use after the previous major
collection.
For instance, for a multiplier of 20,
the collector will do a minor collection when the use of memory
gets 20% larger than the use after the previous major collection.
The default value is 20; the maximum value is 200.
}
@sect3{finalizers| @title{Garbage-Collection Metamethods}
You can set garbage-collector metamethods for tables
and, using the @N{C API},
for full userdata @see{metatable}.
These metamethods are also called @def{finalizers}.
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).
For an object (table or userdata) to be finalized when collected,
you must @emph{mark} it for finalization.
@index{mark (for finalization)}
You mark an object for finalization when you set its metatable
and the metatable has a field indexed by the string @St{__gc}.
Note that if you set a metatable without a @idx{__gc} field
and later create that field in the metatable,
the object will not be marked for finalization.
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 @idx{__gc} 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.
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.
Because the object being collected must still be used by the finalizer,
that object (and other objects accessible only through it)
must be @emph{resurrected} by Lua.@index{resurrection}
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.
When you close a state @seeF{lua_close},
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.
}
@sect3{weak-table| @title{Weak Tables}
A @def{weak table} is a table whose elements are
@def{weak references}.
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.
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
@idx{__mode} field of its metatable.
This field, if present, must be one of the following strings:
@St{k}, for a table with weak keys;
@St{v}, for a table with weak values;
or @St{kv}, for a table with both weak keys and values.
A table with weak keys and strong values
is also called an @def{ephemeron table}.
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.
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.
Only objects that have an explicit construction
are removed from weak tables.
Values, such as numbers and @x{light @N{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.
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.
If a weak table is among the resurrected objects in a collection cycle,
it may not be properly cleared until the next cycle.
}
}
@sect2{coroutine| @title{Coroutines}
Lua supports coroutines,
also called @emphx{collaborative multithreading}.
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.
You create a coroutine by calling @Lid{coroutine.create}.
Its sole argument is a function
that is the main function of the coroutine.
The @id{create} function only creates a new coroutine and
returns a handle to it (an object of type @emph{thread});
it does not start the coroutine.
You execute a coroutine by calling @Lid{coroutine.resume}.
When you first call @Lid{coroutine.resume},
passing as its first argument
a thread returned by @Lid{coroutine.create},
the coroutine starts its execution by
calling its main function.
Extra arguments passed to @Lid{coroutine.resume} are passed
as arguments to that function.
After the coroutine starts running,
it runs until it terminates or @emph{yields}.
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,
@Lid{coroutine.resume} returns @true,
plus any values returned by the coroutine main function.
In case of errors, @Lid{coroutine.resume} returns @false
plus an error object.
A coroutine yields by calling @Lid{coroutine.yield}.
When a coroutine yields,
the corresponding @Lid{coroutine.resume} 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, @Lid{coroutine.resume} also returns @true,
plus any values passed to @Lid{coroutine.yield}.
The next time you resume the same coroutine,
it continues its execution from the point where it yielded,
with the call to @Lid{coroutine.yield} returning any extra
arguments passed to @Lid{coroutine.resume}.
Like @Lid{coroutine.create},
the @Lid{coroutine.wrap} 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 @Lid{coroutine.resume}.
@Lid{coroutine.wrap} returns all the values returned by @Lid{coroutine.resume},
except the first one (the boolean error code).
Unlike @Lid{coroutine.resume},
@Lid{coroutine.wrap} does not catch errors;
any error is propagated to the caller.
As an example of how coroutines work,
consider the following code:
@verbatim{
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"))
}
When you run it, it produces the following output:
@verbatim{
co-body 1 10
foo 2
main true 4
co-body r
main true 11 -9
co-body x y
main true 10 end
main false cannot resume dead coroutine
}
You can also create and manipulate coroutines through the C API:
see functions @Lid{lua_newthread}, @Lid{lua_resume},
and @Lid{lua_yield}.
}
}
@C{-------------------------------------------------------------------------}
@sect1{language| @title{The Language}
This section describes the lexis, the syntax, and the semantics of Lua.
In other words,
this section describes
which tokens are valid,
how they can be combined,
and what their combinations mean.
Language constructs will be explained using the usual extended BNF notation,
in which
@N{@bnfrep{@rep{a}} means 0} or more @rep{a}'s, and
@N{@bnfopt{@rep{a}} means} an optional @rep{a}.
Non-terminals are shown like @bnfNter{non-terminal},
keywords are shown like @rw{kword},
and other terminal symbols are shown like @bnfter{=}.
The complete syntax of Lua can be found in @refsec{BNF}
at the end of this manual.
@sect2{lexical| @title{Lexical Conventions}
Lua is a @x{free-form} language.
It ignores spaces (including new lines) and comments
between lexical elements (@x{tokens}),
except as delimiters between @x{names} and @x{keywords}.
@def{Names}
(also called @def{identifiers})
in Lua can be any string of letters,
digits, and underscores,
not beginning with a digit and
not being a reserved word.
Identifiers are used to name variables, table fields, and labels.
The following @def{keywords} are reserved
and cannot be used as names:
@index{reserved words}
@verbatim{
and break do else elseif end
false for function goto if in
local nil not or repeat return
then true until while
}
Lua is a case-sensitive language:
@id{and} is a reserved word, but @id{And} and @id{AND}
are two different, valid names.
As a convention,
programs should avoid creating
names that start with an underscore followed by
one or more uppercase letters (such as @Lid{_VERSION}).
The following strings denote other @x{tokens}:
@verbatim{
+ - * / % ^ #
& ~ | << >> //
== ~= <= >= < > =
( ) { } [ ] ::
; : , . .. ...
}
A @def{short literal string}
can be delimited by matching single or double quotes,
and can contain the following C-like escape sequences:
@Char{\a} (bell),
@Char{\b} (backspace),
@Char{\f} (form feed),
@Char{\n} (newline),
@Char{\r} (carriage return),
@Char{\t} (horizontal tab),
@Char{\v} (vertical tab),
@Char{\\} (backslash),
@Char{\"} (quotation mark [double quote]),
and @Char{\'} (apostrophe [single quote]).
A backslash followed by a line break
results in a newline in the string.
The escape sequence @Char{\z} skips the following span
of white-space characters,
including line breaks;
it is particularly useful to break and indent a long literal string
into multiple lines without adding the newlines and spaces
into the string contents.
A short literal string cannot contain unescaped line breaks
nor escapes not forming a valid escape sequence.
We can specify any byte in a short literal string,
including @x{embedded zeros},
by its numeric value.
This can be done
with the escape sequence @T{\x@rep{XX}},
where @rep{XX} is a sequence of exactly two hexadecimal digits,
or with the escape sequence @T{\@rep{ddd}},
where @rep{ddd} is a sequence of up to three decimal digits.
(Note that if a decimal escape sequence is to be followed by a digit,
it must be expressed using exactly three digits.)