forked from lua/manual
-
Notifications
You must be signed in to change notification settings - Fork 0
/
manual-fr.of
8574 lines (6702 loc) · 260 KB
/
manual-fr.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.166 2016/12/22 15:46:25 roberto Exp roberto $}
@C{[(-------------------------------------------------------------------------}
@manual{
@sect1{@title{Introduction}
Lua est un langage de script puissant, efficace, léger, embarquable.
Il supporte la programmation procédurale,
la programmation orientée objet, la programmation fonctionnelle,
la programmation data-driven et la description de données.
Lua combine une syntaxe procédurale simple avec une puissante construction de description des données
basée sur des tableaux associatifs et une sémantique extensible.
Lua est typé dynamiquement,
basé sur l'interprétation d'un bytecode et
une machine virtuelle.
Il possède une gestion de la mémoire avec
un garbage collector incrémental,
le rendant idéal comme outil de configuration, pour l'écriture de script
ainsi que pour le prototypage rapide.
Lua est implémenté comme une bibliothèque, écrite en @emphx{clean C},
le sous-ensemble issue du @N{Standard C} et C++.
La distribution du Lua comprend un programme hôte nommé @id{lua},
qui utilise la bibliothèque Lua pour offrir un interpréteur Lua complet,
et autonome,
à utiliser interactivement ou comme interpréteur.
Lua est à la fois pensé pour être un langage de script puissant et léger
pour les besoins d'extension de tout programme,
et comme un langage autonome puissant, léger, et efficace.
En tant que langage d'extension, Lua n'a pas de fonction principale @Q{main} :
il fonctionne comme un langage embarqué sur un hôte,
appelé @emph{programme embarqué}, ou simplement @emphx{hôte}.
(Souvent, cet hôte est un programme @id{lua} autonome.)
Le programme hôte peut appeler des fonctions pour exécuter des blocs (@emph{chunk}) de code Lua,
peut écrire et lire des variables Lua,
peut enregistrer des @N{fonctions C} pour être appelées avec du code Lua.
Avec l'utilisation de @N{fonctions C}, Lua peut être utilisé dans
de nombreux domaines de programmation,
et ainsi créer des langages de programmation partageant une même base syntaxique.
Lua est un logiciel libre,
et est fourni sans aucune garantie,
comme indiqué dans sa licence.
L'implémentation décrite dans ce manuel est disponible
sur le site officiel de Lua, @id{www.lua.org}.
Comme n'importe quel autre manuel de référence,
ce document n'a pas pour but d'enseigner, mais de renseigner.
Pour discuter des décisions à propos du design de Lua,
voir les documents techniques disponibles sur le site de Lua.
Pour une introduction technique à la programmation en Lua,
voir le livre de Roberto, @emphx{Programming in Lua}.
}
@C{-------------------------------------------------------------------------}
@sect1{basic| @title{Concepts de base}
Cette section décrit les concepts de base du langage.
@sect2{TypesSec| @title{Valeurs et types}
Lua est un @emph{langage typé dynamiquement}.
Cela signifie que
les variables n'ont pas de type, seules les valeurs en ont un.
Il n'y a pas de définition de type dans le langage.
Toutes les valeurs portent leur propre type.
Toutes les valeurs dans Lua sont @emph{des valeurs de première classe}.
Cela signifie que toutes les valeurs sont stockées dans des variables,
passées comme arguments à des fonctions, et renvoyées comme résultat.
Il y a huit @x{types de base} en Lua :
@def{nil}, @def{boolean}, @def{number},
@def{string}, @def{function}, @def{userdata},
@def{thread}, et @def{table}.
Le type @emph{nil} ne contient qu'une valeur, @nil,
qui a la principale propriété d'être différente de toutes les autres valeurs ;
il représente usuellement l'absence de valeur utile.
Le type @emph{boolean} contient deux valeurs, @false et @true.
@nil et @false sont des conditions fausses ;
toutes les autres valeurs sont des conditions vraies.
Le type @emph{number} représente à la fois
les nombres entiers et réels.
Le type @emph{string} représente des séquences d'octets immuables.
@index{eight-bin clean}
Lua est 8-bit clean :
Les strings peuvent contenir n'importes quelles valeurs de 8 bits,
incluant le @x{caractère nul} (@Char{\0}).
Lua est aussi indépendant de l'encodage ;
aucune supposition n'est faite sur le contenu d'un string.
Le type @emph{number} utilise deux représentations internes,
ou deux @x{sous-types},
l'une appelée @def{integer}, et une autre appelée @def{float}.
Lua a des règles explicites quant à la représentation à utiliser,
mais peut également les convertir automatiquement quand cela est nécessaire @see{coercion}.
Par conséquent,
le programmeur peut choisir d'ignorer la différence
entre les integers et les floats la plupart du temps,
ou bien contrôler complètement quel type utiliser.
Le Lua standard utilise des integers sur 64 bits et des floats à double précision (64 bits),
mais vous pouvez aussi compiler Lua pour le
faire utiliser des integers sur 32 bits et/ou des floats à simple précision (32 bits).
Le fait d'utiliser 32 bits pour et les integers, et les floats
est particulièrement avantageux
pour les petites machines, et les systèmes embarqués
(voir la macro @id{LUA_32BITS} dans le fichier @id{luaconf.h}).
Lua peut appeler (et manipuler) des fonctions écrites en Lua, et des fonctions écrites en C @see{functioncall}.
Les deux sont représentées par le type @emph{function}.
Le type @emph{userdata} est capable de stocker des @N{données C} dans des variables Lua.
Une variable de type userdata représente un bloc mémoire.
Il y a deux types d'userdata :
@emphx{full userdata}, qui est un objet dont l'emplacement en mémoire est géré par Lua,
et @emphx{light userdata}, qui est simplement une valeur de type @N{pointeur C}.
Le type userdata n'a pas d'opérations prédéfinies en Lua, en dehors de l'affectation et des tests d'identité.
En utilisant les @emph{metatables}, le programmeur peut définir des opérations sur les valeurs de type full userdata @see{metatable}.
Les valeurs de type userdata ne peuvent pas être créer ou modifier en Lua, mais uniquement en utilisant @N{l'API C}.
Cela garantit l'intégrité des données propres au programme hôte.
Le type @def{thread} représente des threads d'exécution indépendants de l'exécution et est utilisé pour implémenter des coroutines @see{coroutine}.
Les threads Lua ne sont pas liés aux threads du système d'exploitation.
Lua supporte les coroutines sur tous les systèmes, même sur ceux qui ne supportent pas les threads nativement.
Le type @emph{table} implémente les @x{tableaux associatifs} c'est à dire des @x{tableaux} qui peuvent être indexés non seulement avec des nombres, mais avec n'importe quelle valeur Lua exceptés @nil et @x{NaN} (@emphx{Not a Number} est une valeur spéciale utilisée pour représenter des résultats numériques indéfinis ou non représentables, comme par exemple @T{0/0}).
Les tables peuvent être @emph{hétérogènes} ; c'est à dire qu'elles peuvent contenir des valeurs de tous les types (excepté @nil).
Les clés de valeur associée @nil ne sont pas considérées comme faisant partie de la table.
Réciproquement, toute clé qui ne fait pas partie de la table a pour valeur associée @nil.
Les tables sont le seul mécanisme de structures de donnée propre à Lua ; elles peuvent être utilisées pour représenter des tableaux ordinaires, des listes, des tables de symboles, des dictionnaires, des enregistrements, des graphes, des arbres, etc.
Pour représenter les @x{enregistrements}, Lua utilise le nom du champs comme un index.
Le langage supporte cette représentation en fournissant un identifiant @id{a.name} comme sucre syntaxique pour @T{a["name"]}.
Il y a plusieurs façons pratiques de créer des tables en Lua @see{tableconstructor}.
Tout comme les indices, les valeurs des champs d'une table peuvent être de tous les types.
En particulier, comme les fonctions sont des valeurs de première classe, elles peuvent être associées aux champs d'une table.
Ainsi, les tables peuvent contenir des @emph{méthodes} @see{func-def}.
L'indexation des tables suit la définition de l'égalité pure dans le langage. Les expressions @T{a[i]} et @T{a[j]} indiquent le même élément de la table si et seulement si @id{i} et @id{j} sont égaux (c'est à dire, égaux sans méta-méthodes).
En particulier, les flottants avec des valeurs entières sont égaux à leur représentation entière respective (e.g., @T{1.0 == 1}).
Afin d'éviter les ambiguïtés, tous les flottants avec une valeur entière sont automatiquement convertis vers leur forme entière respective.
Par exemple, si vous écrivez @T{a[2.0] = true}, la clé insérée dans la table sera l'entier @T{2} (d'un autre côté, 2 et @St{2} sont deux valeurs différentes et pointent ainsi vers deux entrées de la table différentes).
Les valeurs de type table, fonction, thread et (full) userdata sont des @emph{objets} :
les variables ne @emph{contiennent} pas ces valeurs, elles @emph{renvoient} vers elles.
Les affectations, passages de paramètres, et retours de fonctions manipulent toujours des références vers ces valeurs ; ces opérations n'impliquent pas une quelconque copie.
La fonction de bibliothèque @Lid{type} renvoie une chaîne de caractères décrivant le type de la valeur passée en argument @see{predefined}.
}
@sect2{globalenv| @title{Environnements et environnement global}
Comme nous le verrons dans @refsec{variables} et @refsec{assignment},
chaque référence à un nom libre
(c'est à dire, un nom qui n'est lié à aucune déclaration) @id{var}
est syntaxiquement transformé en @T{_ENV.var}.
De plus, chaque bloc de code (@emph{chunk}) est compilé dans la portée d'une
variable locale externe nommée @id{_ENV} @see{chunks},
donc @id{_ENV} lui-même n'est jamais un nom libre.
Malgré l'existence de cette variable externe @id{_ENV} et
la traduction de noms disponible,
@id{_ENV} est un nom complètement normal.
En particulier, vous pouvez définir de nouvelles variables et paramètres avec ce nom.
Chaque référence à un nom disponible utilise le @id{_ENV} qui est
visible à ce stade du programme,
suivant les règles habituelles de visibilité de Lua @see{visibility}.
Toute table utilisée comme valeur de @id{_ENV} s'appelle un @def{environnement}.
Lua garde un environnement distinct appelé @def{environnement global}.
Cette valeur est conservée dans un index spécial dans un registre C @see{registry}.
En Lua, la variable globale @Lid{_G} est initialisée avec cette même valeur.
(@Lid{_G} n'est jamais utilisé en interne.)
Quand Lua charge un chunk,
la valeur par défaut de la variable @id{_ENV}
est l'environnement global @seeF{load}.
Par conséquent, par défaut,
les noms disponibles dans le code Lua se réfèrent aux entrées dans l'environnement global
(et, par conséquent, ils sont également appelés @def{variables globales}).
En outre, toutes les bibliothèques standard sont chargées dans l'environnement global
et certaines fonctions modifient cet environnement.
Les fonctions @Lid{load} (et @Lid{loadfile})
permettent de charger un chunk en spécifiant un environnement.
(En C, vous devez charger le chunk puis modifier la valeur de sa première upvalue. @seeF{lua_load})
}
@sect2{error| @title{Gestion des erreurs}
Parce que Lua est un langage d'extension embarqué,
toutes les actions Lua commencent à partir de @N{code C} dans le programme hôte
appelant une fonction de la bibliothèque Lua.
(Lorsque vous utilisez Lua en mode autonome, l'application @id{lua} est le programme hôte.)
Chaque fois qu'une erreur survient pendant
la compilation ou l'exécution d'un chunk de Lua,
le contrôle revient à l'hôte,
qui peut prendre des mesures appropriées
(comme l'impression d'un message d'erreur).
Le code Lua peut générer explicitement une erreur en appelant la fonction @Lid{error}.
Si vous devez capturer des erreurs en Lua,
vous pouvez utiliser @Lid{pcall} ou @Lid{xpcall}
pour appeler une fonction donnée dans le @emphx{mode protégé}.
Chaque fois qu'il y a une erreur,
un @def{objet d'erreur} (également appelé @def{message d'erreur})
se propage avec des informations sur l'erreur.
Lua lui même génère seulement des erreurs dont l'objet est une chaîne,
mais les programmes peuvent générer des erreurs avec
n'importe quelle valeur comme objet d'erreur.
C'est au programme Lua ou à son hôte de gérer de tels objets d'erreur.
Lorsque vous utilisez @Lid{xpcall} ou @Lid{lua_pcall},
vous pouvez indiquer un @def{gestionnaire de message}
à appeler en cas d'erreurs.
Cette fonction est appelée avec l'objet d'erreur d'origine
et renvoie un nouvel objet d'erreur.
Il est appelé avant que l'erreur déroule la pile,
afin qu'il puisse recueillir plus d'informations sur l'erreur,
par exemple en inspectant la pile et en créant une trace de la pile.
Ce gestionnaire de message est toujours protégé par un appel protégé;
donc, une erreur dans le gestionnaire de messages
appellera à nouveau le gestionnaire de messages.
Si cette boucle dure trop longtemps,
Lua la casse et renvoie un message approprié.
(Le gestionnaire de messages est uniquement appelé pour des erreurs d'exécution régulières.
Il n'est appelé ni pour des erreurs d'allocation mémoire
ni pour des erreurs lors de l'exécution de finalizers @see{finalizers}.)
}
@sect2{metatable| @title{Metatbles et Metamethods}
Toute valeur en Lua peut avoir une @emph{metatable}.
Cette @emph{metatable} est une table Lua ordinaire
qui définit le comportement de la valeur d'origine
sous certaines opérations spéciales.
Vous pouvez modifier plusieurs aspects du comportement
des opérations sur une valeur en définissant des champs spécifiques dans sa metatable.
Par exemple, lorsqu'une valeur non numérique est l'opérande d'une addition,
Lua regarde si le champ de @St{__add} de la metatable de la valeur a pour valeur associée une fonction.
Le cas échéant, Lua appelle cette fonction pour effectuer l'addition.
La clé pour chaque événement dans une metatable est une chaîne
avec le nom de l'événement préfixé par deux caractères de soulignement;
les valeurs correspondantes sont appelées @def{metamethods}.
Dans l'exemple précédent, la clé est @St{__add}
et la metamethod est la fonction qui effectue l'addition.
Vous pouvez obtenir la metatable de n'importe quelle valeur
en utilisant la fonction @Lid{getmetatable}.
Lua interroge les metamethods dans les metatables en utilisant un accès brut @seeF{rawget}.
Donc, pour récupérer la metamethod pour l'événement @id{ev} dans l'objet @id{o},
Lua fait l'équivalent du coude suivant:
@verbatim{
rawget(getmetatable(@rep{o}) or {}, "__@rep{ev}")
}
Vous pouvez remplacer les metatables de tables en utilisant la fonction @Lid{setmetatable}.
Vous ne pouvez pas modifier les metatables d'autres types depuis du code Lua
(sauf en utilisant la @link{debuglib|bibliothèque debug});
vous devrez utiliser @N{l'API C} pour cela.
Les tables et les full userdata ont chacun leur propre metatable
(plusieurs tables ou userdata peuvent cependant partager une même metatable).
Les valeurs des autres types partagent la même metatable par type;
il y a une table pour tous les nombres (type number), une pour les chaines de caractères (type string) etc.
Par défaut, une valeur n'a pas de metatable définie,
cependant la bibliothèque string définit une metatable pour le type string @see{strlib}.
Une metatable contrôle comment se comporte un objet dans les opérations
arithmétiques, les opérations bit à bit, les comparaisons, les concaténations,
les appels, l'indexation et les opérations de longueur.
Elle peut également définir une fonction appelé quand une userdata
ou une table passe au @link{GC|garbage collector}.
Dans le cas des opérateurs unaires (négation, longueur, non bit à bit),
la metamethod est appelé avec un second argument factice égal au premier.
Cet argument supplémentaire est uniquement présent pour simplifier
l'implémentation de Lua (en confondant les opérateurs unaires et binaires)
et peut disparaître dans de prochaines versions de Lua.
(Dans la plupart des cas, cet argument n'a pas d'utilité.)
Voici une liste détaillée des éventements contrôlés par les metatables.
Chaque opération est identifiée par sa clé correspondante.
@description{
@item{@idx{__add}|
Opération d'addition(@T{+}).
Si un opérande pour une addition n'est pas un nombre
(ni une chaîne assimilable à un nombre),
Lua essaiera d'appeler une metamethod.
Tout d'abord, Lua vérifie le première opérande (même s'il est valide).
Si cet opérande ne définit pas une metamethod pour @idx{__add},
alors Lua vérifie le second opérande.
Si Lua peut trouver une metamethod,
il appelle la metamethod avec les deux opérandes comme arguments
et le résultat de l'appel
(ajusté à une valeur)
est le résultat de l'opération.
Autrement,
cela soulève une erreur.
}
@item{@idx{__sub}|
Opération de soustraction (@T{-}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__mul}|
Opération de multiplication (@T{*}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__div}|
Opération de division (@T{/}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__mod}|
Opération modulo (@T{%}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__pow}|
Opération d'exponentiation (@T{^}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__unm}|
Opération négation (unary @T{-}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__idiv}|
Opération floor (@T{//}).
Comportement similaire à l'opération d'addition.
}
@item{@idx{__band}|
Opération AND (@T{&}) bit à bit.
Comportement semblable à l'opération d'addition,
sauf que Lua va essayer une metamethod
si un opérande n'est ni un nombre entier
ni une valeur assimilable à un entier @see{coercion}.
}
@item{@idx{__bor}|
Opération OR (@T{|} bit à bit.
Comportement semblable à l'opération AND bit à bit.
}
@item{@idx{__ bxor}|
Opération OU (binaire @T{~}) externe bit à bit.
Comportement semblable à l'opération AND bit à bit.
}
@item{@idx{__bnot}|
Opération NOT (unaire @T{~}) bit à bit.
Comportement semblable à l'opération AND bit à bit.
}
@item{@idx{__shl}|
Opération de décalage vers la gauche (@T{<<}).
Comportement semblable à l'opération AND bit à bit.
}
@item{@idx{__shr}|
Opération de décalage à droite (@T{>>}).
Comportement semblable à l'opération AND bit à bit.
}
@item{@idx{__concat}|
Opération de concaténation (@T{..}).
Comportement semblable à l'opération d'addition,
sauf que Lua va essayer une metamethod
si un opérande n'est ni une chaîne ni un nombre
(qui est toujours coercible à une chaîne).
}
@item{@idx{__len}|
Opération de longueur (@T{#}).
Si l'objet n'est pas une chaîne,
Lua va essayer sa metamethod.
S'il y a une metamethod,
Lua l'appelle avec l'objet comme argument,
et le résultat de l'appel
(toujours ajusté à une valeur)
est le résultat de l'opération.
S'il n'y a pas de metamethod mais que l'objet est une table,
alors Lua utilise l'opération de longueur de table @see{len-op}.
Sinon, Lua soulève une erreur.
}
@item{@idx{__eq}|
Opération égale (@T{==}).
Comportement semblable à l'opération d'addition,
sauf que Lua essaiera une metamethod uniquement
lorsque les valeurs en comparaison sont soit deux
table, soit deux userdata
et s'ils ne désignent pas la même valeur égaux.
Le résultat de l'appel est toujours
converti en booléen.
}
@item{@idx{__lt}|
Opération moins (@T{<}).
Comportement semblable à l'opération d'addition,
sauf que Lua essaiera une metamethod uniquement lorsque les valeurs
en comparaison ne sont ni les mêmes, ni deux chaînes.
Le résultat de l'appel est toujours converti en booléen.
}
@item{@idx{__le}|
L'opération inférieur ou égal (@T{<=}) operation.
Contrairement aux autres opérations,
l'opération inférieur ou égal peut utiliser deux évenements différents.
Premièrement, Lua cherche la métaméthode @idx{__le} dans les deux operandes,
comme dans l'opération strictement inférieur.
Si il ne peut pas trouver cette métaméthode,
alors il va essayer la métaméthode @idx{__lt},
en supposant que @T{a <= b} est équivalent à @T{not (b < a)}.
Comme les autres opérateurs de comparaison,
le résultat est toujours un booléen.
(Cette utilisation de l'évenement @idx{__lt} peut être supprimée dans des versions futures;
elle est aussi plus lente qu'une vraie métaméthode @idx{__le}.)
}
@item{@idx{__index}|
L'accès par clé @T{table[key]}.
Cet événement arrive quand @id{table} n'est pas une table ou
quand @id{key} n'est pas présent dans @id{table}.
Malgré son nom,
la métaméthode pour cet événement peut être une fonction ou une table.
Si c'est une fonction,
elle est appellée avec @id{table} et @id{key} comme arguments,
et le résultat de l'appel
(ajusté à une seule valeur)
est le résultat de l'opération.
Si c'est une table,
le résultat final est le résultat de l'indexation de cette table avec @id{key}.
(Cet indexation est régulière, pas brute,
et peut donc déclencher une autre métamethode.)
}
@item{@idx{__newindex}|
Modification par indexation @T{table[key] = value}.
Comme l’événement d'indexation,
cet événement arrive quand @id{table} n'est pas une table ou
quand @id{key} n'est pas présent dans @id{table}.
Comme l'indexation,
la métamethode pour cet évenement peut être soit une fonction, soit une table.
Si c'est une fonction,
elle est appellée avec @id{table}, @id{key}, et @id{value} comme arguments.
Si c'est une table,
Lua effectue la même opération mais à cette table avec les même clé et valeur.
(Cet affectation est régulier,
et peut donc déclencher une autre métamethode.)
Dès lors qu'il existe une métaméthode @idx{__newindex},
Lua ne fait aucune affectation par lui même.
(Si necessaire,
la métamethode elle même peut appeller @Lid{rawset}
pour faire l'affectation.)
}
@item{@idx{__call}|
L'opération d'appel @T{func(args)}.
Cet évenement arrive quand Lua essaye d'appeler une valeur qui n'est pas une fonction
(c'est à dire, quand @id{func} n'est pas une fonction).
La métaméthode est cherchée dans la metatable de @id{func}.
Si présente,
la métaméthode est appelée avec @id{func} en tant que premier argument,
suivi par les arguments de l'appel original (@id{args}).
Tous les résultats de l'appel
sont le résultat de l'opération.
(C'est la seule métaméthode qui permet plusieurs résultats.)
}
}
C'est une bonne pratique d'ajouter toutes les metamethod nécessaires à une table
avant de la configurer comme metatable d'un objet quelconque.
En particulier, la metamethod @idx{__gc} fonctionne uniquement dans ce cas @see{finalizers}
Comme les metatables sont des tableaux réguliers,
ils peuvent contenir des champs arbitraires
en plus des noms d'événements définis ci-dessus.
Certaines fonctions de la bibliothèque standard
(e.g., @Lid{tostring})
utilises d'autres champs de la metatable pour leur propre fonctionnement.
}
@sect2{GC| @title{Garbage Collection}
Lua effectue une gestion automatique de la mémoire.
Ceci veut dire que
vous n'avez pas à vous soucier d'allouer de la mémoire pour les nouveaux objets
ou de la libérer lorsque les objets ne sont plus nécessaires.
Lua gère automatiquement la mémoire en exécutant
un @def{garbage collector} pour collecter tous les @emph{objets morts}
(c'est à dire les objets qui ne sont plus accessible depuis Lua).
L'intégralité de la mémoire utilisée par Lua est soumise à une gestion automatique :
chaînes, tables, userdata, fonctions, threads, structures internes, etc.
Lua met en œuvre un collecteur incrémental de mark-and-sweep.
Il utilise deux nombres pour contrôler ses cycles de garbage-collection:
le @def{garbage-collector pause} et
le @def{garbage-collector step multiplier}.
Les deux utilisent des points de pourcentage comme des unités
(par exemple, une valeur de 100 signifie une valeur interne de 1).
Le garbage-collector pause
contrôle la durée pendant laquelle le collecteur attend avant de commencer un nouveau cycle.
Des valeurs plus importantes rendent le collecteur moins agressif.
Les valeurs inférieures à 100 signifient que le collecteur n'attendra pas pour
démarrer un nouveau cycle.
Une valeur de 200 signifie que le collecteur attend que le double de la mémoire total soit utilisé
avant de commencer un nouveau cycle.
Le garbage-collector step multiplier
contrôle la vitesse relative du collecteur par rapport à
l'allocation mémoire.
Des valeurs plus importantes rendent le collecteur plus agressif
mais augmentent aussi la charge de chaque étape d'un cycle de collecte.
Il est déconseillé d'utiliser des valeurs inférieures à 100,
car elles rendent le collecteur trop lent et
il est probable que le collecteur ne terminera jamais un cycle.
La valeur par défaut est de 200,
ce qui signifie que le collecteur fonctionne à @Q{deux fois}
la vitesse d'allocation de la mémoire.
Si vous définissez le multiplicateur de pas à un très grand nombre
(plus de 10% du nombre maximum
d'octets que le programme peut utiliser),
le collecteur se comporte comme un collecteur de stop-the-world
(c'est à dire qu'un pas réalise un cycle complet).
Si vous réglez la pause sur 200,
le collecteur se comporte comme dans les anciennes versions de Lua,
faire une collection complète chaque fois que Lua double son
utilisation mémoire.
Vous pouvez modifier ces nombres en appelant @Lid{lua_gc} en C
ou @Lid{collectgarbage} en Lua.
Vous pouvez également utiliser ces fonctions pour contrôler directement
le collecteur (par exemple, pour l'arrêter et le redémarrer).
@sect3{finalizers| @title{Garbage-Collection Metamethods}
Vous pouvez définir des metamethods pour le garbage-collector dans le cas des tables
et dans le cas des full userdata avec l'@N{API C}.
Ces metamethods sont également appelées @def{finalizers}.
Les finalizers permettent de coordonner le garbage-collector
de Lua avec la gestion de ressources externes, comme la fermeture
de fichiers, celle de connexions réseaux ou sur des bases de donnée
ou bien la libération de la mémoire que vous avez vous même allouée.
Afin qu'un objet (table ou userdata) soit bien finalisé lors du passage
du garbage-collector, il doit être @emph{marqué}.
@index{mark (for finalization)}
Pour marquer un objet, il faut que sa metatable ait un champ
de clé @St{__gc} lors de son attribution.
Si la clé @idx{__gc} n'est présente lors de l'association de la metatable
à un objet, alors celui-ci ne sera pas marqué,
même si cette clé est rajoutée à la metatable ensuite.
Quand un objet marqué devient un objet mort,
il n'est pas immédiatement collecté.
Lua le place tout d'abord dans une liste et,
à la suite de la collecte, Lua parcourt cette liste.
Pour chaque objet, il vérifie le type de sa metamethod @idx{__gc}.
S'il s'agit bien d'une fonction,
Lua l'appelle avec l'objet comme unique argument,
et l'ignore dans le cas contraire.
À la fin du cycle de collecte,
les finalizers des objets sont appelés dans
l'ordre inverse dans lequel les objets ont été marqués.
Autrement dit, le premier objet dont le finalizer est appelé
est le dernier à avoir été marqué dans le programme.
L'exécution d'un finalizer peut intervenir à tout moment
lors de l'exécution d'un programme.
Puisqu'un objet collecté peut encore être utilisé dans son finalizer,
cet objet (et ceux accessibles par son intermédiaire) peuvent
échapper à la collecte.@index{resurrection}
En règle générale, ceci n'est que temporaire avant
le cycle de collecte suivant.
Cependant, si le finalizer stocke l'objet dans un espace global
alors ce dernier peut ne plus être collecté jusqu'à la fin du programme.
De plus, si le finalizer marque à nouveau l'objet, son (nouveau) finalizer
sera appelé au cycle suivant alors que l'objet est inaccessible.
Dans tous les cas,
la mémoire est libéré uniquement quand l'objet est à la fois inaccessible
et non marqué.
Quand un état Lua est fermé @seeF{lua_close},
Lua appelle les finalizers de tous les objets marqués dans
l'ordre inverse de celui dans lequel ils ont été marqués.
Les objets marqués à nouveau lors de cette phase sont ignorés.
}
@sect3{weak-table| @title{Weak Tables}
Une @def{weak table} est une table
dont les éléments sont des @def{weak references}.
Une référence faible est ignorée par le garbage collector.
En d'autres termes, si les seules références à un objet
sont des références faibles, alors le garbage collector
collectera cet objet
Une weak table peut avoir des clés faibles, des valeurs faibles
ou les deux.
Une weak table permet de collecter ses valeurs mais empêche
la collecte de ses clés.
Une table avec, à la fois des clés faibles et des valeurs faibles
permet la collecte de clés valeurs.
Dans tous les cas, si la clé ou la valeur est collectée,
toute la paire est retirée de la table.
La faiblesse d'une table est contrôlée par les @idx{__mode}
domaines de sa métatable.
Si le champ @idx{__mode} est une chaîne contenant le
@N{caractère @Char{k}}, les clés de la table sont faibles.
Si @idx{__mode} contient @Char{v}, les valeurs dans
le tableau sont faibles.
Une table avec des clés faibles et des valeurs fortes est également
appelé @def{ephemoron table}.
Dans une table ephemeron, une valeur n'est considérée comme
accessible que si sa clé est accessible.
En particulier, si la seule référence à une clé vient de sa valeur,
la paire est supprimée.
Toute modification de la faiblesse d'une table peut prendre effet
uniquement au prochain cycle de collecte.
En particulier, si vous modifiez la faiblesse en mode plus fort,
Lua peut encore recueillir des objets de cette table
avant l'entrée en vigueur de la modification.
Seuls les objets ayant une construction explicite sont retirées
des weak tables.
Les valeurs, telles que les nombres et @x{light@N{fonctions C}},
ne sont pas assujettis à la collecte du garbage collector
et ne sont donc pas supprimées des weak tables
(à moins que leurs valeurs associées ne soient collectées).
Bien que les chaînes soient assujetties à la collecte,
elles n'ont pas de construction explicite et ne sont
donc pas supprimées des weak tables.
Les objets ressuscités (c'est à dire que les objets
sont finalisés et accessibles uniquement à travers
des objets en cours de finalisation)
ont un comportement spécial dans les weak tables.
Ils sont retirées des valeurs faibles avant
d'exécuter leurs finaliseurs mais sont retirées
des clés faibles uniquement dans la prochaine collecte
après avoir exécuté leurs finalisations lorsque de tels
objets sont effectivement libérés.
Ce comportement permet et finaliseurs d'accéder
aux propriétés associées à l'objet par des weak tables.
Si une weak tables est parmi les objets ressuscités
dans un cycle de collecte,
il se peut qu'il ne soit pas correctement
effacé jusqu'au prochain cycle.
}
}
@sect2{coroutine|@title{Les coroutines}
Lua supporte les coroutines, également appelé
@emphx{multithreading collaboratif}.
Une coroutine en Lua représente un fil d'exécution indépendant.
Contrairement aux threads dans les systèmes multithread,
une coroutine ne suspend que son exécution en appelant
explicitement la fonction yield.
Vous créez une coroutine en appelant @Lid{coroutine.create}.
Son seul argument est une fonction qui est la fonction principale de la coroutine.
La fonction @id{create} crée uniquement une nouvelle coroutine et
lui renvoie une poignée (objet du type @emph{thread});
Il ne démarre pas la coroutine.
Vous exécutez une coroutine en appelant @Lid{coroutine.resume}.
Lorsque vous appelez tout d'abord @Lid{coroutine.resume},
en passant comme premier argument un thread renvoyé par
@Lid{coroutine.create},
la coroutine commence son exécution en appelant sa fonction principale.
Les arguments supplémentaires transmis à @Lid{coroutine.resume}
sont passés comme arguments de cotte fonction.
Un fois que la coroutine commence son exécution en appelant
sa fonction principale.
Les arguments supplémentaires transmis à @Lid{coroutine.resume}
sont passés comme arguments à cette fonction.
Une fois que la coroutine commence son exécution,
elle s'exécute jusqu'à se terminer ou rencontrer @emph{yields}.
Une coroutine peut terminer son exécution de deux façons:
normalement, lorsque sa fonction principale se termine
(explicitement ou implicitement après la dernière instruction);
et anormalement, s'il existe une erreur non protégée.
En cas de fin normale, @Lid{coroutine.resume} renvoie @true,
plus toutes les valeurs renvoyées par la fonction principale de la coroutine.
En cas d'erreurs, @Lid{coroutine.resume} renvoie @false
pour un objet d'erreur.
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 est un langage @x{free-form}.
Il ignore les espaces (incluant les retours à la ligne) et les commentaires
entre des éléments lexicaux (@x{tokens}),
sauf entre des séparateurs entre des @x{noms} et des @x{mots clés}.
En Lua, les @def{Noms}
(aussi appelés @def{identifiers})
peuvent être n'importe quel combinaison de lettres,
chiffres, et tirets bas,
qui ne commencent ni par un chiffre,
ni par un mot réservé.
Les identifiers sont utilisés pour nommer les variables, les champs de tables et les labels.
Les @def{mots clés} suivants sont réservés
et ne peuvent pas être utilisés comme noms :
@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 est sensible à la casse :
@id{and} est un mot (clé?) réservé, mais @id{And} et @id{AND}
sont deux noms différents et valides.
En tant que convention,
les programmes devraient éviter de créer
des noms qui commencent par un tiret bas suivi par
une ou plusieurs lettres majuscules (comme @Lid{_VERSION}).
Voici quelques autres exemples de @x{tokens} :
@verbatim{
+ - * / % ^ #
& ~ | << >> //
== ~= <= >= < > =
( ) { } [ ] ::
; : , . .. ...
}
Une @def{chaine de caractères littérale courte}
peut être délimitée par des guillemets ou apostrophes (la même chose des deux cotés),
et peut contenir les séquences d'échappement de C suivantes :
@Char{\a} (caractère d'appel [bell]),
@Char{\b} (retour arrière [backspace]),
@Char{\f} (saut de page [form feed]),
@Char{\n} (saut de ligne [line feed]),
@Char{\r} (retour chariot [carriage return]),
@Char{\t} (tabulation horizontale [horizontal tab]),
@Char{\v} (tabulation verticale [vertical tab]),
@Char{\\} (anti-slash [backslash]),
@Char{\"} (guillemets [quotation mark, double quote]),
et @Char{\'} (apostrophe [single quote]).
Un anti-slash suivi par un retour à la ligne
crée un saut de ligne dans la chaîne de caractère.
La séquence d'échappement @Char{\z} saute la prochaine suite
d'espaces, y compris les retours à la ligne;
c'est particulièrement utile pour séparer ou indenter une longue chaîne de caractères littérale
en plusieurs lignes sans ajouter les sauts de lignes et espaces
dans le contenu de la chaîne.
Une chaîne de caractères littérale courte ne peut pas contenir de retours à la ligne non échappés
ni des échappements qui ne forment pas une séquence d'échappement correcte.
On peut spécifier n'importe quel octet dans une chaîne de caractères littérale courte avec sa valeur numérique
(y compris les @x{caractères nuls}).
On peut le faire
avec la séquence d'échappement @T{\x@rep{XX}},
où @rep{XX} est une séquence d’exactement deux chiffres en hexadécimal
ou avec la séquence d'échappement @T{\ddd}},
où @rep{ddd} est une suite de jusqu'à trois chiffres décimaux.
(Notez que si une séquence d'échappement décimale doit être suivie par un chiffre,
elle doit être construite avec exactement trois chiffres.)
L'encodage @x{UTF-8} d'un caractère @x{Unicode}
peut être inséré dans une chaîne de caractères littérale avec
la séquence d'échappement @T{\u{@rep{XXX}}}
(Notez les accolades obligatoires),
où @rep{XXX} est une suite de un ou plusieurs chiffres hexadécimaux
représentant le code point du caractère.
Les chaînes de caractères littérales peuvent aussi être définies avec un format long
entourées par des @x{long brackets}.
On définit un @def{long bracket ouvrant de niveau @rep{n}} comme un crochet
ouvrant suivi par @rep{n} signes égal suivis par un autre crochet ouvrant.
Donc, un long bracket ouvrant de @N{niveau 0} est écrit @T{[[}, @C{]]}
un long bracket ouvrant de @N{niveau 1} est écrit @T{[=[}, @C{]]}
etc…
Un @emph{long bracket fermant} est défini de façon similaire ;
par exemple,
un long bracket fermant s'écrit @C{[[} @T{]====]}.
Une @def{chaîne de caractères littérale longue} commence avec un long bracket ouvrant de n'importe quel niveau et
se termine avec un long bracket? fermant du même niveau.
Elle peut contenir n'importe quel texte à part un long bracket fermant du même niveau.
Les chaînes littérales dans cette forme peuvent continuer sur plusieurs lignes,
n'interprètent pas les séquences d'échappement,
et ignorent les long brackets de n'importe quel autre niveau.
n'importe quel type de séquence de fin de ligne
(retour charriot, saut de ligne, retour charriot suivi par un saut de ligne,
ou saut de ligne suivi par un retour charriot)
est convertit en un seul saut de ligne.
Pour la simplicité,
quand un long bracket ouvrant est immédiatement suivi par un saut de ligne,
le saut de ligne n'est pas inclus dans la chaîne de caractères.
Par exemple, dans un système qui utilise ASCII
(dans lequel @Char{a} est @N{97},
un saut de ligne est @N{10}, et @Char{1} est @N{49}),
les cinq chaînes de caractères littérales suivantes sont équivalentes :
@verbatim{
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]
a = [==[
alo
123"]==]
}
N'importe quel octet dans une chaîne de caractère littérale qui n'est pas
spécifiquement affectée par les règles précédentes est représenté par lui même.
Cependant, Lua ouvre les fichiers à analyser en mode texte,
et les fonctions de fichiers du système peuvent avoir des problèmes avec
certains caractères de contrôle.
Donc, c'est plus sûr de représenter des données n'étant pas du texte comme une chaîne de caractères littérale
en utilisant explicitent des séquences d'échappement pour les caractères n'étant pas du texte.
Une @def{constante numérique} (ou @def{nombre})
peut être écrite avec une partie fractionnelle
et une partie décimale optionnelle,
marquée par une lettre @Char{e} ou @Char{E}.
Lua accepte aussi les @x{constantes hexadécimales},
qui commencent par @T{0x} ou @T{0X}.
Les constantes hexadécimales acceptent aussi une partie fractionnelle optionnelle
plus une partie optionnelle d'exposant,
marquée par une lettre @Char{p} ou @Char{P}.
Une constante numérique avec une racine ou un exposant
deviendra un nombre flottant ;
sinon,
si sa valeur rentre dans un entier,
elle deviendra un entier.
Voici des exemples de constantes de nombre entier valides
@verbatim{
3 345 0xff 0xBEBADA
}
Voici des exemples de constantes à virgule flottante valides
@verbatim{
3.0 3.1416 314.16e-2 0.31416E1 34e1
0x0.1E 0xA23p-4 0X1.921FB54442D18P+1
}
Un @def{commentaire} commence avec deux tirets (@T{--})
n'importe où à l'extérieur d'une chaîne de caractères.
Si le texte immédiatement après @T{--} n'est pas un long bracket ouvrant,
alors le commentaire est un @def{commentaire court},
qui se termine à la fin de la ligne.
Sinon, c'est un @def{commentaire long},
qui se termine au long bracket fermant correspondant.
Les commentaires longs sont souvent utilisés pour désactiver du code temporairement.
}
@sect2{variables| @title{Variables}
Les variables servent à stocker des valeurs.
En Lua, il y a trois types de variables :
les variables globales, les variables locales et les champs de table.
Un nom de variable peut désigner selon le contexte une variable globale ou locale
(ou un argument de fonction, qui est un cas particulier de variable locale) :
@Produc{
@producname{var}@producbody{@bnfNter{Name}}
}
@bnfNter{Name} correspond aux identifiants, comme défini en @See{lexical}.
Tout nom de variable est supposé globale à moins d'être explicitement déclaré local @see{localvar}.
@x{Les variable locales} sont contraintes par leur @emph{portée lexicale} :
elles sont accessibles depuis toutes fonctions définies dans une portée inférieur
@see{visibility}.
Une variable a pour valeur @nil avant sa première affectation.
Le crochet sont utilisés pour accéder au champ d'une table :
@Produc{
@producname{var}@producbody{prefixexp @bnfter{[} exp @bnfter{]}}
}