-
Notifications
You must be signed in to change notification settings - Fork 1
/
edrxlib.lua
3117 lines (2837 loc) · 99.8 KB
/
edrxlib.lua
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
-- This file: http://angg.twu.net/LUA/lua50init.lua.html
-- http://angg.twu.net/LATEX/dednat6/edrxlib.lua.html
-- http://angg.twu.net/dednat6/dednat6/edrxlib.lua.html
-- http://angg.twu.net/blogme3/edrxlib.lua.html
-- http://angg.twu.net/emlua/edrxlib.lua.html
--
-- This is my "init file" for Lua. As I have LUA_INIT set
-- to "@$HOME/LUA/lua50init.lua", the Lua interpreter loads
-- this on start-up.
-- See: (find-angg ".zshrc" "lua" "LUA_INIT")
-- (find-lua51manual "#6" "LUA_INIT" "@filename")
-- (find-es "lua5" "LUA_INIT")
--
-- This is _also_ the module "edrxlib.lua" in dednat6, blogme3, and emlua!
-- I use these sexps to keep them in sync:
-- (find-tkdiff "~/LUA/lua50init.lua" "~/LATEX/dednat6/edrxlib.lua")
-- (find-tkdiff "~/LUA/lua50init.lua" "~/dednat6/dednat6/edrxlib.lua")
-- (find-sh0 "cp -v ~/LUA/lua50init.lua ~/LATEX/dednat6/edrxlib.lua")
-- (find-sh0 "cp -v ~/LUA/lua50init.lua ~/dednat6/dednat6/edrxlib.lua")
-- (find-sh0 "cp -v ~/LUA/lua50init.lua ~/blogme3/edrxlib.lua")
-- (find-sh0 "cp -v ~/LUA/lua50init.lua ~/emlua/edrxlib.lua")
-- Old way: (find-es "emacs" "hard-links")
-- See also: (to "edrxlib")
--
-- Author: Eduardo Ochs <[email protected]>
-- Version: 2022mar26 <- don't trust this date
-- Public domain.
--
-- Note: "dednat4.lua" and "dednat6.lua" try to load this at startup,
-- with 'require "edrxlib"', just after setting the path; if this has
-- already been loaded by LUA_INIT, then the 'require "edrxlib"' is a
-- no-op, because of the "package.loaded.edrxlib = ..." at the end of
-- this file - otherwise it is loaded, probably from the "~/dednat4/"
-- or "~/LATEX/dednat6/" dirs. See this for the details:
-- (find-dn4 "dednat4.lua" "edrxlib")
-- (find-dn6 "dednat6.lua" "requires")
--
-- Blogme3 does the same trick:
-- (find-blogme3 "blogme3.lua" "edrxlib")
--
-- This init file used to work both on lua-5.0 and lua-5.1...
-- I have stopped using lua-5.0, but I kept the name of this file.
-- This file works on Lua 5.1, 5.2, 5.3, and 5.4.
--
-- This file still has _A LOT_ of cruft!
-- «.compat» (to "compat")
-- «.pack-and-unpack» (to "pack-and-unpack")
-- «.printf» (to "printf")
-- «.ee_expand» (to "ee_expand")
-- «.ee_dofile» (to "ee_dofile")
-- «.readfile» (to "readfile")
-- «.writefile» (to "writefile")
-- «.fileexists» (to "fileexists")
-- «.trim» (to "trim")
-- «.split» (to "split")
-- «.splitlines» (to "splitlines")
-- «.splitlines-5.3» (to "splitlines-5.3")
-- «.getoutput» (to "getoutput")
-- «.map» (to "map")
-- «.sorted» (to "sorted")
-- «.fold» (to "fold")
-- «.min-and-max» (to "min-and-max")
-- «.package.require» (to "package.require")
-- «.edrxlib» (to "edrxlib")
-- «.cow-and-coy» (to "cow-and-coy")
-- «.eval-and-L» (to "eval-and-L")
-- «.eoo» (to "eoo")
-- «.Class» (to "Class")
-- «.over0» (to "over0")
-- «.over» (to "over")
-- «.Code» (to "Code")
-- «.Tos» (to "Tos")
-- «.mytostring» (to "mytostring")
-- «.PP» (to "PP")
-- «.VerticalTable» (to "VerticalTable")
-- «.HTable-and-VTable» (to "HTable-and-VTable")
-- «.Set» (to "Set")
-- «.SetL» (to "SetL")
-- «.Path» (to "Path")
-- «.DGetInfo» (to "DGetInfo")
-- «.DGetInfos» (to "DGetInfos")
-- «.Rect» (to "Rect")
-- «.SynTree» (to "SynTree")
-- «.DedTree» (to "DedTree")
-- «.syntree» (to "syntree")
-- «.re_expand_INFIX» (to "re_expand_INFIX")
-- «.math-grammar» (to "math-grammar")
-- «.Re» (to "Re")
--
-- «.strlen8» (to "strlen8")
-- «.untabify» (to "untabify")
-- «.untabify8» (to "untabify8")
-- «.utf8tohtml» (to "utf8tohtml")
-- «.u8c_to_l1» (to "u8c_to_l1")
-- «.u8_to_l1» (to "u8_to_l1")
-- «.toslashhex» (to "toslashhex")
-- «.divmod» (to "divmod")
-- «.userocks» (to "userocks")
-- «.loadblogme3» (to "loadblogme3")
-- «.savevars» (to "savevars")
-- «.variants-of-format» (to "variants-of-format")
-- «.trailing-zeroes» (to "trailing-zeroes")
-- «.pformat» (to "pformat")
-- «.dformat» (to "dformat")
-- «.gformat» (to "gformat")
--
-- «.loaddednat6» (to "loaddednat6")
-- «.loadluarocks» (to "loadluarocks")
-- «.loadfbcache2» (to "loadfbcache2")
-- «.capitalize» (to "capitalize")
-- «.getinscritos» (to "getinscritos")
--
-- «.string-methods» (to "string-methods")
-- «.otherfunctions» (to "otherfunctions")
-- «.0-based» (to "0-based")
-- «.P-old» (to "P-old")
-- «.P-old-tests» (to "P-old-tests")
-- «.PP-old» (to "PP-old")
-- «.PPP-old» (to "PPP-old")
-- «.follow» (to "follow")
-- «.NamedFunction» (to "NamedFunction")
-- «.envsubst» (to "envsubst")
-- «.mytostring-old» (to "mytostring-old")
-- «.mysortedpairs» (to "mysortedpairs")
-- «.mytostringk2» (to "mytostringk2")
-- «.ee_loadlib» (to "ee_loadlib")
-- «.ee_ls» (to "ee_ls")
-- «.load_dednat4» (to "load_dednat4")
-- «.load_posix» (to "load_posix")
-- «.load_PP» (to "load_PP")
-- «.PPeval» (to "PPeval")
-- «.loadlpeg» (to "loadlpeg")
-- «.loadbitlib» (to "loadbitlib")
-- «.autoload» (to "autoload")
-- «.loadtcl» (to "loadtcl")
-- «.loadldb» (to "loadldb")
-- «.loadpeek» (to "loadpeek")
-- «.loadalarm» (to "loadalarm")
-- «.loadposix» (to "loadposix")
-- «.curl» (to "curl")
-- «.preparef2n» (to "preparef2n")
-- «.each2» (to "each2")
-- «.translatechars» (to "translatechars")
-- «.lpeg» (to "lpeg")
-- «.sbeconcat» (to "sbeconcat")
-- «.concatbestrings» (to "concatbestrings")
-- «.lpeg_togsub» (to "lpeg_togsub")
-- «.lpeg_gsub» (to "lpeg_gsub")
-- «.lpeg_gsub_» (to "lpeg_gsub_")
-- «.lpeg_balanced» (to "lpeg_balanced")
-- «.ee_into» (to "ee_into")
-- «.chdir» (to "chdir")
-- «.hms_to_s» (to "hms_to_s")
-- «.s_to_hms» (to "s_to_hms")
-- «.icollect» (to "icollect")
--
-- «.mytraceback» (to "mytraceback")
-- «.errorfb_line» (to "errorfb_line")
-- «.ee_template» (to "ee_template")
-- «.interactor» (to "interactor")
-- «.MyXpcall» (to "MyXpcall")
-- «.Repl» (to "Repl")
--
-- «.loadluarepl» (to "loadluarepl")
-- «.replaceranges» (to "replaceranges")
-- «.string.replace» (to "string.replace")
--
-- «.Sexp» (to "Sexp")
-- «.youtube_make_url» (to "youtube_make_url")
-- «.youtube_split» (to "youtube_split")
-- «.to_youtube_hash» (to "to_youtube_hash")
-- «.url_split» (to "url_split")
-- «.Blogme» (to "Blogme")
--
-- «.EevIntro» (to "EevIntro")
-- «.ELispH» (to "ELispH")
-- «.ELispHF» (to "ELispHF")
-- «.code_video» (to "code_video")
-- «.getsexp» (to "getsexp")
-- «.SexpSkel» (to "SexpSkel")
-- «.ELispInfo» (to "ELispInfo")
--
-- «.getsexpskel» (to "getsexpskel")
-- «.SexpLine» (to "SexpLine")
--
-- «.fsize» (to "fsize")
--
-- «.findxxxpdf_parse» (to "findxxxpdf_parse")
--
-- «.repltexthis» (to "repltexthis")
-- «compat» (to ".compat")
-- On Lua 4.x these functions had the short names on the left;
-- on Lua-5.0.x a file etc/compat.lua could be used to make the short
-- names work, but on Lua-5.1.x this compat.lua has been dropped...
-- I still like the short names, so:
write = io.write -- (find-lua51manual "#pdf-io.write")
format = string.format -- (find-lua51manual "#pdf-string.format")
gsub = string.gsub -- (find-lua51manual "#pdf-string.gsub")
strfind = string.find -- (find-lua51manual "#pdf-string.find")
strlen = string.len -- (find-lua51manual "#pdf-string.len")
strsub = string.sub -- (find-lua51manual "#pdf-string.sub")
concat = table.concat -- (find-lua51manual "#pdf-table.concat")
tinsert = table.insert -- (find-lua51manual "#pdf-table.insert")
tremove = table.remove -- (find-lua51manual "#pdf-table.remove")
-- foreachi = table.foreachi -- (find-lua51manual "#7.2" "table.foreachi")
-- getn = table.getn -- (find-lua51manual "#7.2" "table.getn")
table.getn = function (tbl) return tbl.n or #tbl end
getn = function (tbl) return tbl.n or #tbl end
-- «pack-and-unpack» (to ".pack-and-unpack")
-- (find-es "lua5" "pack-and-unpack")
-- pack = table.pack or function (...) return arg end -- 5.1 and 5.2
pack = table.pack or function (...) return {n=select("#", ...), ...} end
unpack = unpack or table.unpack
myunpack = function (arg) return unpack(arg, 1, arg.n) end
-- Examples:
-- PP(pack(nil, 22, nil, 44, nil)) --> {2=22, 4=44, "n"=5}
-- PP(unpack({nil, 22, nil, 44, nil, n=5})) --> <nil> 22
-- PP(myunpack({nil, 22, nil, 44, nil, n=5})) --> <nil> 22 <nil> 44 <nil>
-- «printf» (to ".printf")
printf = function (...) write(format(...)) end
-- (find-es "lua5" "loadstring")
loadstring = loadstring or load
-- «ee_expand» (to ".ee_expand")
-- (find-eev "eev.el" "ee-expand")
ee_expand = function (path)
path = string.gsub(path, "^~$", "$HOME/", 1)
path = string.gsub(path, "^~/", "$HOME/", 1)
path = string.gsub(path, "^%$(%w+)", os.getenv, 1)
return path
end
-- «ee_dofile» (to ".ee_dofile")
ee_dofile = function (path) return dofile(ee_expand(path)) end
-- «readfile» (to ".readfile")
-- «writefile» (to ".writefile")
-- (find-es "lua5" "readfile")
-- (find-lua51manual "#pdf-io.open")
-- (find-lua51manual "#pdf-file:read")
-- (find-lua51manual "#pdf-file:write")
readfile = function (fname)
local f = assert(io.open(fname, "r"))
local bigstr = f:read("*a")
f:close()
return bigstr
end
writefile = function (fname, bigstr)
local f = assert(io.open(fname, "w+"))
f:write(bigstr)
f:close()
end
-- «fileexists» (to ".fileexists")
fileexists = function (fname)
local f, err = (io.open(fname, "r"))
if f then io.close(f); return true end
return false
end
-- (find-blogme3file "youtube.lua" "ee_readfile =")
ee_readfile = function (fname) return readfile(ee_expand(fname)) end
ee_writefile = function (fname, str) return writefile(ee_expand(fname), str) end
filecontents0 = function (fname)
local ok,contents = pcall(function () return ee_readfile(fname) end)
if ok then return contents end
end
-- (find-dn4 "dednat4.lua" "dednat4dir")
-- (find-dn6 "dednat6.lua" "package.path")
fnamedirectory = function (fname) return fname:match"^(.*/)[^/]*$" end
fnamenondirectory = function (fname) return fname:match "([^/]*)$" end
-- «trim» (to ".trim")
-- (to "string-methods")
-- (find-lua51manual "#5.4.1" "Patterns")
ltrim = function (str) return str:match"^%s*(.*)$" end
rtrim = function (str) return str:reverse():ltrim():reverse() end
bitrim = function (str) return str:ltrim():rtrim() end
string.ltrim = ltrim
string.rtrim = rtrim
string.bitrim = bitrim
-- «split» (to ".split")
-- (find-es "lua5" "split")
split = function (str, pat)
local arr = {}
string.gsub(str, pat or "([^%s]+)", function (word)
table.insert(arr, word)
end)
return arr
end
-- «splitlines» (to ".splitlines")
splitlines = function (bigstr)
local arr = split(bigstr, "([^\n]*)\n?")
table.remove(arr)
return arr
end
isplitlines = function (bigstr)
return ipairs(splitlines(bigstr))
end
-- «splitlines-5.3» (to ".splitlines-5.3")
-- (find-es "lua5" "splitlines-5.3")
splitlines = function (bigstr)
local arr = split(bigstr, "([^\n]*)\n?")
if _VERSION:sub(5) < "5.3" then
table.remove(arr)
end
return arr
end
-- «getoutput» (to ".getoutput")
-- (find-es "lua5" "getoutput")
getoutput = function (command)
local pipe = assert(io.popen(command))
local output = pipe:read("*a")
pipe:close()
return output
end
-- «map» (to ".map")
--------[ keys, map, seq, nop, each2, splitlines, chartranslator ]--------
keys = function (tbl)
local ks = {}
for k,_ in pairs(tbl) do table.insert(ks,k) end
return ks
end
map = function (f, arr, n)
local brr = {}
for i=1,(n or #arr) do table.insert(brr, (f(arr[i]))) end
return brr
end
seq = function (a, b, c)
local arr = {}
for i=a,b,(c or 1) do table.insert(arr, i) end
return arr
end
nop = function () end
id = function (...) return ... end
copy = function (A)
local B = {}
for k,v in pairs(A) do B[k] = v end
setmetatable(B, getmetatable(A))
return B
end
shallowcopy = function (A, B)
B = B or {}
for k,v in pairs(A) do B[k] = v end
setmetatable(B, getmetatable(A))
return B
end
deepcopy = function (A)
if type(A) ~= "table" then return A end
local B = {}
for k,v in pairs(A) do B[k] = deepcopy(v) end
setmetatable(B, getmetatable(A))
return B
end
deepcopymt = function (A, mt)
if type(A) ~= "table" then return A end
local B = {}
for k,v in pairs(A) do B[k] = deepcopymt(v, mt) end
setmetatable(B, mt) -- use mt
return B
end
uniq = function (A)
local B = {}
for i=1,#A do if A[i] ~= A[i-1] then table.insert(B, A[i]) end end
return B
end
-- (find-efunctiondescr 'mapconcat)
-- (find-elnode "Index" "* mapconcat:")
-- (find-es "lua5" "table.concat")
mapconcat = function (f, tbl, sep, n)
return table.concat(map(f, tbl, n), sep)
end
maplines = function (f, bigstr)
return mapconcat(f, splitlines(bigstr), "\n")
end
transpose = function (A)
local TA = {}
for k,v in pairs(A) do TA[v] = k end
return TA
end
-- «sorted» (to ".sorted")
-- (find-es "lua5" "sorted")
-- (find-lua51manual "#pdf-table.sort")
-- http://lua-users.org/lists/lua-l/2011-04/msg00406.html
sorted = function (tbl, lt) table.sort(tbl, lt); return tbl end
-- «fold» (to ".fold")
-- (find-es "lua5" "fold")
-- (find-hugsbasefile "Prelude.hs" "\nfoldl ")
-- foldl :: (a -> b -> a) -> a -> [b] -> a
foldl = function (f, a, B, i, j)
for k=(i or 1),(j or #B) do a = f(a, B[k]) end
return a
end
-- «min-and-max» (to ".min-and-max")
-- (find-lua51manual "#pdf-math.min")
-- (find-lua51manual "#pdf-math.max")
-- PP(math.min("22", "200")) --> 22
-- PP(min("22", "200")) --> "200"
min = function (a, b)
if a < b then return a else return b end
end
max = function (a, b)
if a < b then return b else return a end
end
Min = function (a, b) return (a and b and min(a, b)) or a or b end
Max = function (a, b) return (a and b and max(a, b)) or a or b end
minmax = function (a, b, c) return Min(a, b), Max(b, c) end
-- «package.require» (to ".package.require")
-- «edrxlib» (to ".edrxlib")
-- Make package.require consider that this file has been loaded when
-- it was loaded by LUA_INIT=@.../LUA/lua50init.lua (see the comments
-- at the top of this file) so that we can do 'require "lua50init"' or
-- 'require "edrxlib"'...
-- (find-lua51manual "#pdf-require")
-- (find-lua51file "")
-- (find-lua51file "src/loadlib.c" "static int ll_require ")
package.loaded.lua50init =
package.loaded.lua50init or "(loaded by LUA_INIT=@...)"
package.loaded.edrxlib =
package.loaded.edrxlib or "(loaded by LUA_INIT=@...)"
-- «cow-and-coy» (to ".cow-and-coy")
-- (find-es "lua5" "cow-and-coy")
coy = coroutine.yield
cow = coroutine.wrap
-- «eval-and-L» (to ".eval-and-L")
-- (find-es "lua5" "lambda-with-L")
-- (find-es "lua5" "lambda-with-Code")
-- (find-LATEX "2014-1-GA-P2-gab.lua")
eval = function (str) return assert(loadstring(str))() end
expr = function (str) return eval("return "..str) end
L00 = function (args, body)
return string.format("function (%s) return %s end", args, body)
end
L0 = function (str)
str = str:gsub("^%s*(%S+)%s+->", "%1 ")
local args, body = str:match("^%s*(%S+)%s+(.*)$")
return L00(args, body)
end
L = function (str) return expr(L0(str)) end
-- «eoo» (to ".eoo")
-- «Class» (to ".Class")
-- For a documented version, see:
-- (find-angg "LUA/eoo.lua")
--
Class = {
type = "Class",
__call = function (class, o) return setmetatable(o, class) end,
}
setmetatable(Class, Class)
otype = function (o) -- works like type, except on my "objects"
local mt = getmetatable(o)
return mt and mt.type or type(o)
end
-- «over0» (to ".over0")
-- Example:
-- A = {a=22}
-- B = over(A, {b=33})
-- PP(B, A, B.b, B.a)
-- --> {"b"=33} {"a"=22} 33 22
--[[
over = function (bottomtable, toptable)
return setmetatable(toptable or {}, {__index = bottomtable})
end
--]]
-- «over» (to ".over")
-- (find-es "lua5" "over")
over = function (B)
return function (A)
return setmetatable(A, {__index=B})
end
end
Over = function (class)
return over(class.__index)
end
-- (find-es "lua5" "rawtostring")
rawtostring = function (o)
if type(o) == "table" then
local mt = getmetatable(o); setmetatable(o, nil)
local rawtos = tostring(o); setmetatable(o, mt)
return rawtos
end
return tostring(o)
end
-- «Code» (to ".Code")
-- The class Code "converts strings to executable code" in nice ways.
-- Commented version: (find-angg "LUA/Code.lua")
--
Code = Class {
type = "Code",
parse2 = function (src)
local vars,rest = src:match("^%s*([%w_,]+)%s*=>(.*)$")
if not vars then error("Code.parse2 can't parse: "..src) end
return vars, rest
end,
format2 = function (fmt, src)
return format(fmt, Code.parse2(src))
end,
ve = function (src) -- src is "vars => expression"
local fmt = "local %s=...; return %s"
return Code {src=src, code=Code.format2(fmt, src)}
end,
vc = function (src) -- src is "vars => code"
local fmt = "local %s=...; %s"
return Code {src=src, code=Code.format2(fmt, src)}
end,
__tostring = function (c) return c.src end,
__call = function (c, ...) return assert(loadstring(c.code))(...) end,
__index = {
},
}
-- «Tos» (to ".Tos")
-- Commented version:
-- (find-angg "LUA/Tos.lua")
--
Tos = Class {
type = "Tos",
__index = {
--
-- Basic methods:
-- o: object (of any type) to string
-- ov: like o, but vertical in a simplistic way
-- t: table to string
-- t0: table to string, low level
-- kvs: listofkeyvaluepairs to string
-- kv: keyvaluepair to string
-- k: key to string
--
o = function (tos, o, a,sep,b,emp)
local ty = type(o)
if ty=="number" then return tostring(o) end
if ty=="string" then return format("%q", o) end
if ty=="table" then return tos:t(o, a,sep,b,emp) end
return "<"..tostring(o)..">"
end,
ov = function (tos, o, a,sep,b,emp)
return tos:o(o, "{ ", ",\n ", "\n}", "{}")
end,
t = function (tos, T, a,sep,b,emp)
return tos:t0(T, a,sep,b,emp)
end,
t0 = function (tos, T, a,sep,b,emp)
local tableisempty = (next(T) == nil)
if tableisempty and emp then return emp end
local body = tos:kvs(tos:getsortedkvs(T), sep)
return (a or "{")..body..(b or "}")
end,
--
kvs = function (tos, ps, sep)
local tos_p = function (p) return tos:kv(p) end
return mapconcat(tos_p, ps, sep or ", ")
end,
kv = function (tos, p) return tos:k(p.key).."="..tos:o(p.val) end,
k = function (tos, k) return tos:o(k) end,
--
-- t0 uses this to sort the key-value pairs of a table.
getsortedkvs = function (tos, T)
return sorted(tos:getkvs(T), tos.comparekvs)
end,
getkvs = function (tos, T)
local kvs = {}
for k,v in pairs(T) do table.insert(kvs, {key=k, val=v}) end
return kvs
end,
comparekvs = function (kv1, kv2) -- not a method!
local k1, k2 = kv1.key, kv2.key
local t1, t2 = type(k1), type(k2)
if t1 == t2 then
if t1 == "number" then return k1 < k2 end
if t1 == "string" then return k1 < k2 end
return rawtostring(k1) < rawtostring(k2) -- fast
else
return t1 < t2 -- numbers before strings before tables, etc
end
end,
--
-- return a tostring-like function
f = function (tos, a,sep,b,emp)
return function (o) return tos:o(o, a,sep,b,emp) end
end,
--
-- An alternative to t. See the object "tosp" below.
tp = function (tos, T, a,sep,b,emp) -- experimental
local mt = getmetatable(T)
local typename = mt and mt.type
local prefix = typename and (typename..":") or ""
return prefix..tos:t0(T, a,sep,b,emp)
end,
},
}
-- Two objects of the class Tos.
tos0 = Tos({})
tosp = Tos({t = Tos.__index.tp})
-- «mytostring» (to ".mytostring")
-- Basic tostring-ish functions.
-- To override them, redefine these functions.
mytostring = function (o) return tos0:o(o) end
mytostringv = function (o) return tos0:ov(o) end
mytabletostring = function (o) return tos0:ov(o) end -- old name
--
mytostringp = function (o) return tosp:o(o) end
mytostringvp = function (o) return tosp:ov(o) end
mytostringpv = function (o) return tosp:ov(o) end
-- «PP» (to ".PP")
-- Basic pretty-printing functions.
-- PPV = function (o) print(mytabletostring(o)); return o end
PPPV = function (o) print(mytostringpv(o)); return o end
PPP = function (o) print(mytostringp (o)); return o end
PPV = function (o) print(mytostringv (o)); return o end
PP = function (...) return PP_(mytostring, ...) end
PP_ = function (tos, ...)
local args = pack(...)
for i=1,args.n do printf(" %s", tos(args[i])) end
print()
return ...
end
-- «VerticalTable» (to ".VerticalTable")
-- Tests: (find-es "lua5" "VerticalTable")
VerticalTable = Class {
type = "VerticalTable",
__tostring = function (vt) return mytabletostring(vt) end,
__index = {
},
}
-- «HTable-and-VTable» (to ".HTable-and-VTable")
-- (find-es "lua5" "Tos-2021")
-- tos_HTable = Tos({}):f()
-- tos_VTable = Tos({}):f("{ ", ",\n ", "\n}", "{}")
HTable = Class {
type = "HTable",
__tostring = mytostring,
__index = {
},
}
HTableP = Class {
type = "HTableP",
__tostring = mytostringp,
__index = {
},
}
VTable = Class {
type = "VTable",
__tostring = mytostringv,
__index = {
},
}
VTableP = Class {
type = "VTableP",
__tostring = mytostringvp,
__index = {
},
}
-- «Set» (to ".Set")
-- Commented version:
-- (find-angg "LUA/Set.lua" "Set")
--
Set = Class {
type = "Set",
new = function () return Set {_={}} end,
from = function (L) return Set.fromarray(L) end,
fromarray = function (L)
local C = Set.new()
for i,v in ipairs(L) do C._[v]=v end
return C
end,
__add = function (A, B) -- union
local C = Set.new()
for k,v in pairs(A._) do C._[k]=v end
for k,v in pairs(B._) do C._[k]=v end
return C
end,
__sub = function (A, B) -- difference
local C = Set.new()
for k,v in pairs(A._) do C._[k]=v end
for k,v in pairs(B._) do C._[k]=nil end
return C
end,
__mul = function (A, B) -- intersection
local C = Set.new()
for k,v in pairs(A._) do if B._[k] then C._[k]=v end end
return C
end,
__len = function (A) print"!" return #(keys(A._)) end, -- number of elements
__tostring = function (A)
return "(Set with "..A:n().." elements)"
end,
--
-- Methods
__index = {
get = function (A, k) return A._[k] end,
has = function (A, k) return A._[k] end,
n = function (A) return #keys(A._) end,
k = function (A) return keys(A._) end,
ks = function (A) return sorted(keys(A._)) end,
ksc = function (A, sep) return table.concat(A:ks(), sep or "\n") end,
gen = function (A)
return cow(function ()
for i,v in ipairs(A:ks()) do coy(v, A:get(v)) end
end)
end,
add = function (A, key, val)
A._[key] = val or key
return A
end,
del = function (A, key)
A._[key] = nil
return A
end,
},
}
-- «SetL» (to ".SetL")
-- Commented version:
-- (find-angg "LUA/SetL.lua")
-- (find-angg "LUA/SetL.lua" "SetL")
--
SetL = Class {
type = "SetL",
new = function () return SetL {keys={}, list={}} end,
from = function (L) return Set.fromarray(L) end,
fromarray = function (L)
local C = Set.new()
for i,k in ipairs(L) do C:add(k) end
return C
end,
__len = function (setl) return setl:n() end,
__tostring = function (setl)
return format("(SetL with %d elements)", setl:n())
end,
__add = function (A, B) -- union
local C = SetL:new()
for k,v in A:gen() do C:add(k, v) end
for k,v in B:gen() do C:add(k, v) end
return C
end,
__mul = function (A, B) -- intersection
local C = SetL:new()
for k,v in A:gen() do if B:has(k) then C:add(k, v) end end
return C
end,
__sub = function (A, B) -- difference
local C = SetL.new()
for k,v in A:gen() do if not B:has(k) then C:add(k, v) end end
return C
end,
--
-- Methods
__index = {
get = function (setl, key) return setl.keys[key] end,
val = function (setl, key) return setl.keys[key] end,
has = function (setl, key) return setl.keys[key] end,
n = function (setl) return #setl.list end,
k = function (setl) return setl.list end,
ks = function (setl) return sorted(keys(setl.keys)) end,
ksc = function (setl, sep) return table.concat(setl:ks(), sep or "\n") end,
gen = function (setl) return cow(function ()
for i,k in ipairs(setl.list) do coy(k, setl:val(k)) end
end) end,
add = function (setl, key, val)
if not setl:has(key) then
setl.keys[key] = val or key
table.insert(setl.list, key)
end
return setl
end,
},
}
-- «Path» (to ".Path")
-- Commented version: (find-angg "LUA/Path.lua")
-- Typical usage: Path.prepend("path", "~/LUA/?.lua")
--
Path = Class {
type = "Path",
from = function (field) return Path {field = field} end,
prepend = function (field, fname) return Path.from(field):prepend(fname) end,
prependtopath = function (fname) return Path.prepend("path", fname) end,
prependtocpath = function (fname) return Path.prepend("cpath", fname) end,
__tostring = function (p) return p:tostring() end,
__index = {
get = function (p) return package[p.field] end,
set = function (p, newvalue) package[p.field] = newvalue end,
tostring = function (p, sep)
return format("package.%s = %s", p.field, p:tostring0(sep))
end,
tostring0 = function (p, sep)
return (p:get():gsub(";", sep or "\n ;"))
end,
toset = function (p)
return Set.from(split(p:get(), "([^;]+)"))
end,
has = function (p, fname)
return p:toset():has(fname)
end,
prepend0 = function (p, fname)
p:set(ee_expand(fname)..";"..p:get())
end,
prepend = function (p, fname)
if not p:has(ee_expand(fname)) then
p:prepend0(fname)
end
return p
end
},
}
-- «DGetInfo» (to ".DGetInfo")
-- Commented version: (find-angg "LUA/GetInfo.lua")
-- Idea: running something like
--
-- dgi = DGetInfo.atlevel(99, "getvalues")
--
-- calls debug.getinfo and debug.getlocal to get a lot of information
-- about the stack frame at level 99, and puts that information in a
-- static object that is easy to inspect. This class is used by the
-- class DGetInfos, defined below.
--
DGetInfo = Class {
type = "DGetInfo",
what = "nSluf",
new = function (A) return DGetInfo(A or {}) end,
--
atlevel = function (lvl, getvalues)
local dgi = debug.getinfo(lvl, DGetInfo.what)
if not dgi then return end
if getvalues then dgi.values = {} end
for i=1,1000 do
local name,value = debug.getlocal(lvl, i)
if not name then break end
dgi[i] = name
if getvalues then dgi.values[i] = value end
end
return DGetInfo(dgi)
end,
--
-- Adapted from (the middle part of) the traceback function
-- of Prosody. See the message by Matthew Wild in
-- http://lua-users.org/lists/lua-l/2022-03/msg00071.html
prosodytraceback = function (info)
local line
local func_type = info.namewhat.." "
local source_desc = (info.short_src == "[C]" and "C code")
or info.short_src or "Unknown"
if func_type == " " then func_type = "" end
if info.short_src == "[C]" then
line = "[ C ] "..func_type.."C function "
..(info.name and ("%q"):format(info.name) or "(unknown name)")
elseif info.what == "main" then
line = "[Lua] "..info.short_src.." line "..info.currentline
else
local name = info.name or " "
if name ~= " "
then name = ("%q"):format(name)
end
if func_type == "global " or func_type == "local "
then func_type = func_type.."function "
end
line = "[Lua] "..info.short_src.." line "..
info.currentline.." in "..func_type..name..
" (defined on line "..info.linedefined..")"
end
return line
end,
--
__tostring = function (dgi)
return dgi:funname().." :: "..dgi:vars()
end,
__index = {
funname = function (dgi) return dgi.name or "(noname)" end,
vars = function (dgi)
return table.concat(dgi, " ")
end,
--
varns = function (dgi)
local namens = {}
for i,name in ipairs(dgi) do namens[name] = i end
return namens
end,
vs = function (dgi)
local values = {}
for i,name in ipairs(dgi) do values[name] = dgi.values[i] end
return values
end,
v = function (dgi, name)
local n = dgi:varns()[name] or error("Bad var name: "..tostring(name))
return dgi.values[n]
end,
--
tb = function (dgi)
return DGetInfo.prosodytraceback(dgi)
end,
},
}
-- «DGetInfos» (to ".DGetInfos")
-- Commented version: (find-angg "LUA/GetInfo.lua" "GetInfos")
-- Idea: running something like
--
-- dgis = DGetInfos.newv()
--
-- runs lots of "debug.getinfo()"s and "debug.getlocal"s via DGetInfo,
-- and returns a static structure that can be inspected in a repl
-- (both inside an error handler and post-mortem).
--
DGetInfos = Class {
type = "DGetInfos",
new = function (getvalues) return DGetInfos({}):getinfos(getvalues) end,
newv = function () return DGetInfos.new("getvalues") end,
__tostring = function (dgis) return dgis:tostring() end,
__index = {
getinfos = function (dgis, getvalues)
dgis.infos = {}
for i=0,1000 do
dgis[i] = DGetInfo.atlevel(i, getvalues)
if not dgis[i] then return dgis end
end
end,
firstsuch = function (dgis, f)
for i=0,#dgis do
if f(dgis[i], i) then return i end
end
end,
setbase = function (dgis, f)
local z = dgis:firstsuch(f)
if not z then error("setbase: not found") end
dgis.base = z
return dgis
end,
--
seq = function (dgis, a, b, dir)
a,b = (a or #dgis),(b or 0)
dir = dir or (a <= b and 1 or -1)
return seq(a, b, dir)
end,
tostring = function (dgis, a, b, dir)
local f = function (i) return format("%d -> %s", i, tostring(dgis[i])) end
return mapconcat(f, dgis:seq(a, b, dir), "\n")
end,
--