Repository navigation
Expand file tree
/
Copy pathlibraries.lua
More file actions
7640 lines (6481 loc) · 344 KB
/
Copy pathlibraries.lua
File metadata and controls
7640 lines (6481 loc) · 344 KB
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
-- Structured documentation for the libraries, tools and ZLI-specific topics
-- bundled with ZLI.
--
-- This file is the source of truth for doc/libraries.md and for the library
-- part of the @manual page. It is also loaded by `require "docs"`, which
-- powers `zli @help` and the REPL's `:help` command.
--
-- Entries use GitHub-flavored Markdown (rendered by the bundled md4c binding
-- through src/docs_markdown.lua). The Lua standard library documentation is
-- generated from the Lua 5.5 manual at build time and lives in docs_manual.lua.
local function entry(name, signature, kind, summary, doc, aliases)
return {
name = name,
signature = signature,
kind = kind,
summary = summary,
markdown = doc,
aliases = aliases,
}
end
local function module(name, title, summary, doc, entries, options)
options = options or {}
return {
name = name,
title = title,
summary = summary,
markdown = doc,
entries = entries,
upstream = options.upstream,
license = options.license,
aliases = options.aliases,
}
end
return {
schema = 1,
groups = {
{
id = "zli",
title = "ZLI libraries",
source = "zli",
modules = {
module("auxiliary", "auxiliary", "Extra string, table, file and OS helpers.", [==[
The `auxiliary` module is loaded automatically. It extends the standard
`string`, `table`, `io`, `os` and `math` tables and adds a few global helpers.
]==], {
entry("arg_error", "arg_error(func, narg, message [, level])", "function",
"Raise a Lua argument error.",
"Raises `message` as a bad-argument error for argument `narg` of `func`. `level` is passed to `error`."),
entry("arg_check", "arg_check(func, narg, test, message)", "function",
"Raise an argument error when `test` is false.",
"Convenience wrapper around `arg_error`. `func` and `narg` identify the offending argument."),
entry("arg_check_type", "arg_check_type(func, narg, value, level, ...)", "function",
"Validate the type of an argument.",
"Accepts the value when its type is one of the types passed in `...`; otherwise raises an argument error."),
entry("sorted_pairs", "sorted_pairs(tbl [, comparator])", "function",
"Iterate a table in sorted key order.",
"Returns an iterator like `pairs`, sorted by key. An optional comparator is passed to `table.sort`."),
entry("lambda", "lambda(source) / L(source)", "function",
"Create a Lua function from a short expression.",
[==[
Compile `source` into a callable Lua function. The global helpers `lambda` and
`L`, and the string method `string.L`, are equivalent. The source may read
local variables and upvalues visible where the lambda is created, even after
the creating scope has returned.
The first characters of `source` select one of these styles:
| Source style | Example | Equivalent Lua function |
| --------------------------------------- | ---------------------- | -------------------------------------- |
| Method call | `L(":hello")` | `function(it) return it:hello() end` |
| Method call with arguments (arrow form) | `L("-> it:add(2, 3)")` | `function(it) return it:add(2, 3) end` |
| Field access | `L(".name")` | `function(it) return it.name end` |
| Field call | `L(".hello()")` | `function(it) return it.hello() end` |
| Arrow expression | `L("-> it * 2")` | `function(it) return it * 2 end` |
| Bare expression | `L("it * 2")` | `function(it) return it * 2 end` |
| Parameter list | `L("(a, b) -> a + b")` | `function(a, b) return a + b end` |
| No parameters | `L("() -> 42")` | `function() return 42 end` |
The method shorthand appends `()` to the rest of the source: `":hello"` becomes
`it:hello()`. Use it for zero-argument methods, and do not include the
parentheses in the source. Pass arguments with the arrow form, for example
`L("-> it:add(2, 3)")`.
The field shorthand appends the rest of the source to `it` without adding
parentheses: `".name"` becomes `it.name`, and `".hello()"` becomes
`it.hello()` (a plain function call, not a method call). The arrow and bare
forms provide exactly one parameter named `it`. The parenthesised form is the
only style that chooses its own parameter list.
A source beginning with `(` is always parsed as a parameter list and must
contain `->`. To use an expression that starts with a parenthesis, use the
arrow form: `L("-> (it + 1) * 2")`.
For example, `L("(a, b) -> a + b")` loads a chunk equivalent to this one (with
the captured scope as its environment) and calls it to produce the lambda:
```lua
return function(a, b) return a + b end
```
The aliases can be written in several ways:
```lua
local double = L("it * 2") -- global L
local triple = lambda("it * 3") -- global lambda
local upper = (":upper"):L() -- string method
local negate = L "-> -it" -- function call sugar
```
Typical uses:
```lua
local double = L("it * 2")
print(double(21)) --> 42
local add = L("(a, b) -> a + b")
print(add(20, 22)) --> 42
local user = {
name = "Ada",
hello = function(self) return "Hello " .. self.name end,
}
print(L(":hello")(user)) --> Hello Ada
print(L(".name")(user)) --> Ada
```
Lambdas are also accepted as strings by helpers such as `stream:map`:
```lua
local stream = require "stream"
local multiplier = 3
local result = stream({ 1, 2, 3 }):map("it * multiplier"):toarray()
print(table.concat(result, ",")) --> 3,6,9
```
Because the source is compiled when the lambda is created, a lambda created in
a tail-call position cannot see locals from the discarded caller frame. This
is the same limitation as the f-strings library.
]==]),
entry("string.starts_with", "string.starts_with(value, prefix)", "method",
"Return true when a string starts with `prefix`.",
[[
Return true when the string begins with `prefix`.
The comparison is case-sensitive and literal, not a Lua pattern match. An empty prefix always matches.
```lua
print(("hello"):starts_with("he")) --> true
print(("hello"):starts_with("lo")) --> false
```
]]),
entry("string.ends_with", "string.ends_with(value, suffix)", "method",
"Return true when a string ends with `suffix`.",
[[
Return true when the string ends with `suffix`.
The comparison is case-sensitive and literal. An empty suffix always matches.
```lua
print(("hello"):ends_with("lo")) --> true
print(("hello"):ends_with("he")) --> false
```
]]),
entry("string.contains", "string.contains(value, needle)", "method",
"Return true when a string contains `needle`.",
[[
Return true when the string contains `needle`.
The search is plain text, so pattern characters such as `%` and `.` have no special meaning. Case is significant.
```lua
print(("hello"):contains("ell")) --> true
print(("hello"):contains("ELL")) --> false
```
]]),
entry("string.is_empty", "string.is_empty(value)", "method",
"Return true for `nil` or the empty string.",
[[
Return true when the value is `nil` or the empty string.
Any non-empty string returns false. This helper is convenient for validating optional string arguments.
```lua
print(""):is_empty() --> true
print("x"):is_empty() --> false
```
]]),
entry("string.is_not_empty", "string.is_not_empty(value)", "method",
"Return true for a non-nil, non-empty string.",
[[
Return true when the value is a non-nil, non-empty string.
The logical complement of `string.is_empty`. `nil` and `""` both return false.
```lua
print("x"):is_not_empty() --> true
print(""):is_not_empty() --> false
```
]]),
entry("string.split", "string.split(value [, separator])", "method",
"Split a string into multiple values.",
[[
Split a string into multiple return values.
`separator` defaults to a comma. The separator is literal text, not a Lua pattern, and may contain several characters. Empty fields are preserved, including leading and trailing ones.
```lua
local a, b, c = ("1,2,3"):split(",")
print(a, b, c) --> 1 2 3
local parts = table.pack(("a<>b"):split("<>"))
print(parts.n) --> 2
```
]]),
entry("string.to_table", "string.to_table(value [, separator])", "method",
"Split a string into a table.",
[[
Split a string into an array using a literal separator.
`separator` defaults to a comma. Empty fields are preserved, and the function accepts multi-character separators. Use `string.split` when multiple return values are more convenient.
```lua
table.print(("1,2,3"):to_table()) --> { "1", "2", "3" }
```
]]),
entry("string.trim", "string.trim(value)", "method",
"Remove leading and trailing whitespace.",
[[
Remove leading and trailing whitespace from a string.
Whitespace includes spaces, tabs, carriage returns, newlines and NUL bytes. The argument must be a string; the result is a new string.
```lua
print((" hello\n"):trim()) --> "hello"
```
]]),
entry("string.ltrim", "string.ltrim(value)", "method",
"Remove leading whitespace.",
[[
Remove leading whitespace from a string.
Spaces, tabs, carriage returns, newlines and NUL bytes are stripped from the start only. The trailing part of the string is left untouched.
```lua
print((" hello "):ltrim()) --> "hello "
```
]]),
entry("string.rtrim", "string.rtrim(value)", "method",
"Remove trailing whitespace.",
[[
Remove trailing whitespace from a string.
Spaces, tabs, carriage returns, newlines and NUL bytes are stripped from the end only. The leading part of the string is left untouched.
```lua
print((" hello "):rtrim()) --> " hello"
```
]]),
entry("string.base64encode", "string.base64encode(value)", "method",
"Encode a string as standard Base64.",
[[
Encode a string as standard Base64 using the `A-Z a-z 0-9 + /` alphabet and padding.
The argument must be a string. Binary data, including NUL bytes, is preserved. Use `base64urlEncode` when the result must be URL-safe.
```lua
print(("hello"):base64encode()) --> "aGVsbG8="
```
]]),
entry("string.base64decode", "string.base64decode(value)", "method",
"Decode a standard Base64 string.",
[[
Decode a standard Base64 string, returning the original bytes.
The input must use the standard Base64 alphabet with correct padding. Invalid input raises an error rather than returning a partial result.
```lua
print(("aGVsbG8="):base64decode()) --> "hello"
```
]]),
entry("string.base64urlEncode", "string.base64urlEncode(value)", "method",
"Encode a string as URL-safe Base64.",
[[
Encode a string as URL-safe Base64 using the `-` and `_` characters in place of `+` and `/`.
Padding is included, so the result can be decoded with `base64urlDecode`. The input may contain arbitrary bytes.
```lua
print(("a+b/c?"):base64urlEncode())
```
]]),
entry("string.base64urlDecode", "string.base64urlDecode(value)", "method",
"Decode a URL-safe Base64 string.",
[[
Decode a URL-safe Base64 string, accepting `-` and `_` as the last two alphabet characters.
Invalid input raises an error. Use `base64decode` for the standard alphabet.
```lua
print(("aGVsbG8="):base64urlDecode()) --> "hello"
```
]]),
entry("string.urlEncode", "string.urlEncode(value)", "method",
"Percent-encode a string for use in a URL.",
[[
Percent-encode a string for use in a URL.
Letters, digits, `-`, `_`, `.` and `~` are left unchanged. Every other byte is replaced by `%XX` with uppercase hexadecimal digits, including spaces (which become `%20`).
```lua
print(("a b/c"):urlEncode()) --> "a%20b%2Fc"
```
]]),
entry("string.utf8len", "string.utf8len(value)", "method",
"Return the number of UTF-8 characters in a string.",
[[
Count the number of UTF-8 code points in a string.
The argument must be valid UTF-8; malformed input raises an error. The count is not the byte length: `"ÖÄÜ"` has length 3 even though it occupies more bytes.
```lua
print(("héllo"):utf8len()) --> 5
```
]]),
entry("table.copy", "table.copy(value [, copies])", "function",
"Deep-copy a table.",
"`copies` tracks already copied tables, which also makes the function safe for cyclic tables."),
entry("table.tostring", "table.tostring(value [, name])", "function",
"Pretty-print a table as a string.",
[[
Pretty-print a table as a Lua-like string and return it.
The output is produced by `serpent.block`, with sorted keys, four-space indentation and no comments. When `name` is supplied, the result is prefixed with `name = `.
```lua
print(table.tostring({ b = 2, a = { 1 } }))
```
]]),
entry("table.print", "table.print(value [, name])", "function",
"Pretty-print a table to standard output.",
[[
Pretty-print a table to standard output.
This is equivalent to `print(table.tostring(value, name))`. The table is formatted with sorted keys and four-space indentation.
```lua
table.print({ b = 2, a = 1 }, "config")
```
]]),
entry("table.remove_if", "table.remove_if(value, predicate)", "function",
"Remove elements for which `predicate` is true.",
[[
Remove, in place, every array element for which `predicate(item)` is truthy.
The table is compacted and returned, so the original table keeps its identity. Non-array keys are not inspected.
```lua
local t = { 1, 2, 3, 4 }
table.remove_if(t, function(n) return n % 2 == 0 end)
--> t is { 1, 3 }
```
]]),
entry("table.filter", "table.filter(value, predicate)", "function",
"Return a new table with elements accepted by `predicate`.",
[[
Return a new array containing the elements for which `predicate(item)` is truthy.
The original table is not modified. Only the array part is visited, and the result is a new array with consecutive indexes.
]]),
entry("table.add_all", "table.add_all(target, ...)", "function",
"Append all arguments to a table.",
[[
Append the given values to the end of a table and return that table.
Arguments that are tables are flattened one level: their array parts are appended element by element. Non-table arguments are appended directly. Non-array keys in table arguments are ignored.
```lua
local t = { 1 }
table.add_all(t, 2, { 3, 4 }, 5)
--> t is { 1, 2, 3, 4, 5 }
```
]]),
entry("table.insert_all", "table.insert_all(target, index, ...)", "function",
"Insert all arguments at a position.",
[[
Insert the given values into a table starting at `index`, shifting later elements right.
Table arguments are flattened one level, like `table.add_all`. The table is modified in place and returned.
```lua
local t = { 1, 4 }
table.insert_all(t, 2, 2, 3)
--> t is { 1, 2, 3, 4 }
```
]]),
entry("table.load", "table.load(filename)", "function",
"Load a serialized table from a file.",
[[
Load a serialized table from a file and return the resulting value.
The file contents are prefixed with `return` and evaluated, so the file must contain a Lua expression rather than a statement list. `table.save` produces compatible files.
```lua
local value = table.load("config.lua")
```
]]),
entry("table.save", "table.save(filename, value)", "function",
"Serialize a table to a file.",
[[
Serialize a table and write it to a file.
The output uses `table.tostring`, producing sorted keys, four-space indentation and no comments. The file is replaced if it already exists. The function returns nothing.
```lua
table.save("config.lua", { retries = 3, host = "localhost" })
```
]]),
entry("table.default", "table.default(value, defaults [, error])", "function",
"Fill missing keys from a defaults table.",
"Returns `value`, with each missing key copied from `defaults`. When `error` is true, unexpected keys raise an error."),
entry("table.insert_sorted", "table.insert_sorted(value, item [, comparator])", "function",
"Insert an item while keeping a sorted table ordered.",
[[
Insert `item` into an already sorted array, keeping the array ordered.
The default comparator is `a < b`; pass a custom comparator as the third argument. The insertion position is found with a binary search, and the table is modified in place. The function returns nothing.
```lua
local t = {}
table.insert_sorted(t, 3)
table.insert_sorted(t, 1)
--> t is { 1, 3 }
```
]]),
entry("table.next", "table.next(value)", "function",
"Iterator helper used by `stream`.",
[[
Return a stateless iterator over the array part of a table.
Each call to the iterator returns the next value, or `nil` when there are no more values. This is the iterator used internally by `stream` and is equivalent to `ipairs` for well-formed arrays.
```lua
for value in table.next { "a", "b" } do
print(value)
end
```
]]),
entry("io.read_lines", "io.read_lines(filename)", "function",
"Read all lines from a file into a table.",
[[
Read a text file into an array of lines and return the array.
Line terminators are removed and empty lines are preserved. The file is opened read-only and closed before returning. An open failure raises an error through `assert`.
Local files take priority. If the file does not exist locally, it is read from the payload attached to the executable.
```lua
local lines = io.read_lines("data.txt")
print(lines[1])
```
]]),
entry("io.write_lines", "io.write_lines(filename, lines [, eol])", "function",
"Write a table of lines to a file.",
[[
Write an array of lines to a file, replacing any existing contents.
Each line is written followed by `eol`, which defaults to `"\n"`. The file is opened in binary write mode and closed afterwards. An open failure raises an error through `assert`.
```lua
io.write_lines("out.txt", { "one", "two" })
```
]]),
entry("io.read_file", "io.read_file(filename)", "function",
"Read an entire file as a string.",
[[
Read an entire file as a string.
The file is opened in binary read mode and closed before returning. An open failure raises an error through `assert`, so check the path or wrap the call in `pcall` if missing files are expected.
Local files take priority. If the file does not exist locally, it is read from the payload attached to the executable. The same fallback applies to read-only files opened directly with `io.open` or iterated with `io.lines`.
]]),
entry("io.write_file", "io.write_file(filename, data)", "function",
"Write a string to a file, replacing its contents.",
[[
Write a string to a file, replacing its previous contents.
The file is opened in binary write mode, the data is written, and the file is closed. An open failure raises an error through `assert`.
```lua
io.write_file("out.txt", "hello")
```
]]),
entry("io.append_file", "io.append_file(filename, data)", "function",
"Append a string to a file.",
[[
Append a string to a file, creating the file if it does not exist.
The file is opened in append/update binary mode and closed afterwards. An open failure raises an error through `assert`.
]]),
entry("os.name", "os.name", "field",
"Operating system name.",
"One of `windows`, `linux`, `macos`, or the platform name reported by the interpreter."),
entry("os.home", "os.home", "field",
"The current user's home directory.",
[[
The current user's home directory as a string, or `nil` when it cannot be determined.
On Windows the value is built from `HOMEDRIVE` and `HOMEPATH`; elsewhere it comes from `HOME`.
]]),
entry("os.is_windows", "os.is_windows", "field",
"True on Windows.",
[[
True when the interpreter is running on Windows, false on every other platform.
This is a boolean companion to the `os.name` string.
]]),
entry("os.is_linux", "os.is_linux", "field",
"True on Linux.",
[[
True when the interpreter is running on Linux, false on every other platform.
]]),
entry("os.is_mac", "os.is_mac", "field",
"True on macOS.",
[[
True when the interpreter is running on macOS, false on every other platform.
The field is named `is_mac` even though `os.name` uses the value `"macos"`.
]]),
entry("os.separator", "os.separator", "field",
"The platform path separator (`\\` or `/`).",
[[
The platform's path separator: `\` on Windows and `/` elsewhere.
This is a one-character string intended for building paths, and it matches the separator used by the `filesystem` module.
]]),
entry("os.nanotime", "os.nanotime()", "function",
"Return a monotonic timestamp in nanoseconds.",
[[
Return a monotonic timestamp in nanoseconds.
The value is suitable for measuring elapsed time, not for displaying wall-clock dates. It is used by `timer` and `benchmark`.
```lua
local start = os.nanotime()
-- work
print(os.nanotime() - start)
```
]]),
entry("math.round", "math.round(value)", "function",
"Round a number to the nearest integer.",
[[
Round a number to the nearest integer.
Exact halves are rounded to the nearest even integer (banker's rounding): `0.5` becomes `0`, `1.5` becomes `2`, and `-2.5` becomes `-2`. Non-half values round to the nearest integer. The argument must be a number.
```lua
math.round(2.4) --> 2
math.round(2.5) --> 2
math.round(42.6) --> 43
```
]]),
entry("math.maxdouble", "math.maxdouble", "field",
"The largest finite double.",
[[
The largest finite IEEE-754 double-precision value, approximately `1.7976931348623157e308`.
This is a constant number, useful as an initial value for minimum searches.
]]),
entry("math.mindouble", "math.mindouble", "field",
"The smallest positive normalized double.",
[[
The smallest positive normalized IEEE-754 double-precision value, approximately `2.2250738585072014e-308`.
Denormalized values are smaller. This constant is useful as an initial value for maximum searches.
]]),
}),
module("benchmark", "benchmark", "Small benchmark runner with nanosecond precision.", [==[
`benchmark.run(table [, iterations])` runs every function in a benchmark table and
prints per-run timings and memory use.
Special keys `before_all`, `before_each`, `after_each` and `after_all` are called
around the run. A key `before_<name>` or `after_<name>` is called around the
matching benchmark function. The optional `iterations` argument overrides the
`iter` field of the benchmark table (default 3).
]==], {
entry("benchmark.run", "benchmark.run(bench [, iterations])", "function",
"Run a benchmark table and print the summary.",
"The benchmark table contains functions to measure plus optional setup and teardown hooks."),
}),
module("collection", "collection", "Java-style collections: lists, maps and sets.", [==[
`collection` provides `list`, `map` and `set` factories. All collections support
`size`, `is_empty`, `add_all`, `remove_all`, `contains_all`, `equals`, `copy`,
`stream`, `union`, `intersection` and `difference`. Lists and sets also support
`to_array`; use `map:values():to_array()` for maps.
]==], {
entry("collection:size", "collection:size()", "method",
"Return the number of elements.",
[[
Return the number of elements in the collection.
The value is maintained by the collection implementation, so it is O(1) for lists, maps and sets. Use `#collection` where the metatable provides a length operator.
]]),
entry("collection:is_empty", "collection:is_empty()", "method",
"Return true when the collection has no elements.",
[[
Return true when the collection contains no elements.
This is equivalent to `collection:size() == 0` and is O(1).
]]),
entry("collection:add_all", "collection:add_all(items)", "method",
"Add all items from another collection or table.",
[[
Add every element from another collection or table.
For a collection, its iterator is used, so values (not indexes) are added. For a plain table, the array part is traversed with `next`. Returns the collection itself for chaining.
```lua
local list = require("collection").list
local l = list:new():add_all { 1, 2 }
```
]]),
entry("collection:remove_all", "collection:remove_all(items)", "method",
"Remove all items found in another collection or table.",
[[
Remove every element supplied by another collection or table.
For plain tables the array values are used. The return value follows the first removal attempt: it is true when that first item was present and removed, otherwise false. This means callers should not rely on the result as an "any removed" flag.
```lua
local set = require("collection").set
local s = set:new { 1, 2, 3 }
s:remove_all { 2, 3 }
```
]]),
entry("collection:contains_all", "collection:contains_all(items)", "method",
"Return true when every item is present.",
[[
Return true when every element in the supplied collection or table is present in this collection.
The check stops at the first missing element. An empty input returns true. The input may be any collection or a plain array-like table.
]]),
entry("collection:equals", "collection:equals(other)", "method",
"Compare two collections for equal contents.",
[[
Compare this collection with another collection or plain table for equal contents.
Every element of the other object must be contained in this one, and the element counts must match. Element order is not significant, and duplicate values are compared by simple membership.
```lua
local set = require("collection").set
local s = set:new { 1, 2 }
print(s:equals { 2, 1 }) --> true
```
]]),
entry("collection:copy", "collection:copy()", "method",
"Return a shallow copy.",
[[
Return a shallow copy of the collection.
A new collection of the same kind is created with the current elements. The elements themselves are not copied, so nested tables are shared with the original. Ordered maps and sets are rebuilt through their ordinary constructor, so the copy may not preserve insertion order.
```lua
local l = list:new():add_all { { 1 }, 2 }
local copy = l:copy()
print(copy:get(1) == l:get(1)) --> true (same nested table)
```
]]),
entry("collection:stream", "collection:stream()", "method",
"Return a `stream` over the collection.",
[[
Return a `stream` over the collection's elements.
The stream is built from the collection's iterator, so sets and ordered maps preserve their iteration order. The collection itself is not modified.
```lua
local sum = require("collection").list:new{1,2,3}:stream():sum()
```
]]),
entry("collection:union", "collection:union(...)", "method",
"Return the union with other collections.",
[[
Return a new collection containing this collection's elements plus all elements from the given collections or tables.
The receiver is not modified. The result is created with `self:new(self)`, so it has the same collection type. Ordered variants are rebuilt through their ordinary constructor and may not preserve insertion order. Duplicate values follow the rules of that type (sets deduplicate, lists keep duplicates).
]]),
entry("collection:intersection", "collection:intersection(...)", "method",
"Return the intersection with other collections.",
[[
Return a new collection containing only elements that are present in this collection and in every given collection or table.
The receiver is unchanged. The result is a copy of the receiver reduced with `retain_all` for each argument, so type-specific behavior is preserved, but ordered variants may lose insertion order.
]]),
entry("collection:difference", "collection:difference(...)", "method",
"Return the difference with other collections.",
[[
Return a new collection containing the receiver's elements that are not present in any of the given collections or tables.
The receiver is unchanged. The result starts as a copy and removes each argument's elements in turn. Because the copy uses the ordinary constructor, ordered variants may lose insertion order.
]]),
entry("collection:to_array", "collection:to_array()", "method",
"Return the contents as an array.",
[[
Return the collection's elements as a plain array.
The array is built from `iterate_indexed`, so lists and sets produce consecutive indexes. The bundled map implementation does not define indexed iteration; use `map:values():to_array()` for maps instead of calling this method on a map.
```lua
local items = require("collection").list:new{ "a", "b" }:to_array()
--> { "a", "b" }
```
]]),
}),
module("collection.list", "collection.list", "Ordered list collection.", [==[
A list is an ordered sequence. Methods that mutate a list return the list, so
calls can be chained.
]==], {
entry("collection.list.new", "collection.list.new([initial])", "function",
"Create a new list.",
[[
Create a new empty list, optionally populated from an array or another collection.
The initial values are added through `add_all`, so they become the list's elements in iteration order. A plain list keeps insertion order; use `new_sorted` for automatic sorting.
```lua
local list = require("collection").list
local l = list:new { "a", "b" }
print(l:size()) --> 2
```
]]),
entry("collection.list.new_sorted", "collection.list.new_sorted([initial [, comparator]])", "function",
"Create a list that keeps its elements sorted.",
[[
Create a list that keeps its elements in sorted order.
The optional comparator receives two values and returns true when the first sorts before the second; the default is `a < b`. The optional initial array or collection is inserted one element at a time in sorted position.
```lua
local list = require("collection").list
local l = list:new_sorted { "c", "a", "b" }
print(l:get(1)) --> "a"
```
]]),
entry("collection.list:add", "list:add([index,] item)", "method",
"Add one item, optionally at an index.",
[[
Add one item to the list, optionally at a 1-based index.
With one argument the item is appended, or inserted in sorted position for a sorted list. With two arguments the first is an index and the second is the item; inserting by index is not allowed in a sorted list. Passing more than two arguments raises an error. Returns the list.
```lua
local l = list:new():add("b"):add(1, "a")
--> { "a", "b" }
```
]]),
entry("collection.list:add_all", "list:add_all([index,] items)", "method",
"Add all items from a table or collection.",
[[
Add every item from an array or collection.
With one argument the items are appended (or inserted in sorted order for a sorted list). With two arguments the first is a starting index and the second is the collection; items are inserted from that index onward. Returns the list.
]]),
entry("collection.list:clear", "list:clear([size])", "method",
"Remove all items.",
[[
Remove all items from the list and reset its size to zero.
The optional argument is a size or capacity hint; the bundled implementation accepts a number but does not preallocate storage. Passing a table clears the list and then adds that table's items. Other argument types raise an error. Returns the list.
```lua
local l = list:new { 1, 2, 3 }:clear()
print(l:is_empty()) --> true
```
]]),
entry("collection.list:contains", "list:contains(item)", "method",
"Return true when the item is present.",
[[
Return true when the list contains the given value.
Comparison uses `==`, so table values are found by identity. The search is linear from the beginning of the list.
]]),
entry("collection.list:get", "list:get(index)", "method",
"Return the item at an index.",
[[
Return the item at a 1-based index, or `nil` when the index is outside the list.
A non-number index raises an argument error. Negative and zero indexes simply produce `nil`.
]]),
entry("collection.list:set", "list:set(index, item)", "method",
"Replace the item at an index.",
[[
Replace the item at a 1-based index and return the previous value.
A non-number index raises an argument error. Setting an index outside the current list stores the value there without changing the size; only `add` maintains the list length.
]]),
entry("collection.list:index_of", "list:index_of(item)", "method",
"Return the first index of an item, or 0.",
[[
Return the 1-based index of the first occurrence of an item, or `0` when it is absent.
Comparison uses `==`. The alias semantics are those of a linear forward search.
```lua
local l = list:new { "a", "b", "a" }
print(l:index_of("a")) --> 1
print(l:index_of("z")) --> 0
```
]]),
entry("collection.list:last_index_of", "list:last_index_of(item)", "method",
"Return the last index of an item, or 0.",
[[
Return the 1-based index of the last occurrence of an item, or `0` when it is absent.
The whole list is scanned, with later matches replacing earlier ones.
]]),
entry("collection.list:remove", "list:remove(item)", "method",
"Remove the first occurrence of an item.",
[[
Remove the first occurrence of an item from the list.
Returns true when an item was removed and false when it was not found. Later elements shift down to fill the gap, and the size is decremented.
]]),
entry("collection.list:remove_index", "list:remove_index(index)", "method",
"Remove the item at an index.",
[[
Remove the item at a 1-based index.
The list is compacted and its size is decremented. Returns the list itself, not the removed value, so the call can be chained.
```lua
local l = list:new { "a", "b", "c" }:remove_index(2)
--> { "a", "c" }
```
]]),
entry("collection.list:retain_all", "list:retain_all(items)", "method",
"Keep only items present in another collection.",
[[
Keep only items that are present in another collection or array-like table.
The list is modified in place, preserving the relative order of survivors, and is returned. A plain table is converted to a set for fast membership tests.
]]),
entry("collection.list:sublist", "list:sublist(from, to)", "method",
"Return a new list containing the given range.",
[[
Return a new list containing the inclusive range from `from` through `to`.
Both indexes must be numbers. The result is a new list; the original is unchanged. Values outside the list's current range may leave holes, so callers should pass valid indexes.
```lua
list:new{ "a", "b", "c" }:sublist(2, 3):to_array() --> { "b", "c" }
```
]]),
entry("collection.list:for_each", "list:for_each(func)", "method",
"Call `func` for every item.",
[[
Call `func(item)` for every item in list order.
Returns the list for chaining. Mutating the list during iteration has unspecified results.
]]),
entry("collection.list:for_each_index", "list:for_each_index(func)", "method",
"Call `func(index, item)` for every item.",
[[
Call `func(index, item)` for every item, with 1-based indexes.
Returns the list for chaining. This is useful when the position matters as well as the value.
```lua
list:new{ "a", "b" }:for_each_index(function(i, v) print(i, v) end)
```
]]),
entry("collection.list:iterate", "list:iterate()", "method",
"Return an iterator over items.",
[[
Return an iterator over the list's values.
Each call returns the next value, or `nil` at the end. Values are produced in array order.
```lua
for value in list:new{ "a", "b" }:iterate() do print(value) end
```
]]),
entry("collection.list:iterate_indexed", "list:iterate_indexed()", "method",
"Return an iterator over indexes and items.",
[[
Return an iterator over indexes and values.
Each call yields a 1-based index followed by the corresponding value. This is a thin wrapper over `ipairs` on the internal array.
]]),
entry("collection.list:iterator", "list:iterator(func)", "method",
"Call a function for every item until it returns false.",
[[
Call `func(item)` for every item until the callback returns `false` or `nil`.
Returns true when every callback returned a non-false value, false when iteration stopped early. This is a traversal helper, not an iterator factory.
```lua
local ok = list:new{ 1, 2, 3 }:iterator(function(v) return v < 3 end)
--> false
```
]]),
entry("collection.list:iterator_indexed", "list:iterator_indexed(func)", "method",
"Call an indexed function for every item until it returns false.",
[[
Call `func(index, item)` for every item until the callback returns `false` or `nil`.
Returns true when every callback returned a non-false value, false when iteration stopped early.
]]),
}),
module("collection.map", "collection.map", "Key-value map collection.", [==[
Maps preserve key/value associations and provide ordered variants through
`new_ordered`.
]==], {
entry("collection.map.new", "collection.map.new([initial])", "function",
"Create a new map.",
[[
Create a map from an optional table or existing map.
A plain table's key/value pairs are copied; an existing map's entries are copied through `put_all`. Iteration follows native table order. Use `new_ordered` when insertion order matters.
```lua
local map = require("collection").map
local m = map:new { a = 1, b = 2 }
print(m:get("a")) --> 1
```
]]),
entry("collection.map.new_ordered", "collection.map.new_ordered([initial])", "function",
"Create a map that iterates in insertion order.",
[[
Create a map that remembers insertion order for iteration.
The optional initial table or map is copied in its iteration order. Updating an existing key keeps its original position; removing and re-inserting a key moves it to the end.
```lua
local map = require("collection").map
local m = map:new_ordered { a = 1, b = 2 }
m:put("c", 3)
for k in m:iterate() do print(k) end --> a, b, c
```
]]),
entry("collection.map:put", "map:put(key, value)", "method",
"Associate a key with a value.",
[[
Associate `key` with `value` and return the previous value for that key, or `nil`.
If `value` is `nil`, the key is removed instead of stored. Adding a new non-nil key increments the size; in an ordered map it is appended to the insertion order.
```lua
local m = map:new()
print(m:put("a", 1)) --> nil
print(m:put("a", 2)) --> 1
```
]]),
entry("collection.map:get", "map:get(key)", "method",
"Return the value for a key, or nil.",
[[
Return the value associated with `key`, or `nil` when the key is absent.
Because `nil` is also used for missing entries, `contains_key` is the reliable existence test.
]]),
entry("collection.map:get_or_default", "map:get_or_default(key, default)", "method",
"Return a value or a default.",
[[
Return the value for `key`, or `default` when the key is absent.
A stored `false` value is returned as `false`, not replaced by the default.
]]),
entry("collection.map:put_all", "map:put_all(table)", "method",
"Copy all key/value pairs from a table or map.",
[[
Copy all key/value pairs from a plain table or another map into this map.
A collection argument must be a map; other collection types raise an argument error. Existing keys are overwritten, and the map itself is returned.
```lua
local m = map:new():put_all { a = 1, b = 2 }
```
]]),
entry("collection.map:put_if_absent", "map:put_if_absent(key, value)", "method",
"Insert a key only when it is not present.",
[[
Insert `value` only when `key` is not already present.
Returns `nil` when the value was inserted, or the existing value when the key was already present. A `nil` value is not inserted. Ordered maps append newly inserted keys.
]]),
entry("collection.map:remove", "map:remove(key [, value])", "method",
"Remove a key, optionally only when it has a given value.",
[[
Remove `key`, optionally only when its current value equals `value`.
With one argument, returns the removed value, or `nil` when the key was absent. With two arguments, returns true when the value matched and was removed, false when it did not, and `nil` when the key was absent. Removing the last key shrinks the size; ordered maps also remove it from the order.
]]),
entry("collection.map:merge", "map:merge(key, value, func)", "method",
"Merge a value into an existing key using `func`.",
[[