-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathludo_scripting.htm
More file actions
4860 lines (4201 loc) · 172 KB
/
Copy pathludo_scripting.htm
File metadata and controls
4860 lines (4201 loc) · 172 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ludo Scripting Manual</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1, h2, h3, h4, h5, h6 {
color: #2c3e50;
margin-top: 30px;
margin-bottom: 15px;
}
h1 {
border-bottom: 3px solid #3498db;
padding-bottom: 10px;
font-size: 2.5em;
}
h2 {
border-bottom: 2px solid #3498db;
padding-bottom: 8px;
font-size: 2em;
}
h3 {
color: #34495e;
font-size: 1.5em;
}
h4 {
color: #7f8c8d;
font-size: 1.2em;
}
p {
margin-bottom: 15px;
}
code {
background-color: #f8f8f8;
padding: 2px 6px;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
pre {
background-color: #2c3e50;
color: #ecf0f1;
padding: 15px;
border-radius: 5px;
overflow-x: auto;
margin: 15px 0;
}
pre code {
background-color: transparent;
padding: 0;
border-radius: 0;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
background-color: #fff;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #3498db;
color: white;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:hover {
background-color: #e8f4fd;
}
ul, ol {
margin: 15px 0;
padding-left: 30px;
}
li {
margin-bottom: 8px;
}
blockquote {
border-left: 4px solid #3498db;
padding-left: 15px;
margin: 15px 0;
font-style: italic;
color: #555;
}
a {
color: #3498db;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.toc {
background-color: #ecf0f1;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
}
.toc ul {
list-style-type: none;
padding-left: 0;
}
.toc li {
margin: 5px 0;
}
.toc a {
color: #2c3e50;
}
.note {
background-color: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 5px;
padding: 15px;
margin: 15px 0;
}
.note strong {
color: #856404;
}
.code-block {
position: relative;
}
.code-block::before {
content: attr(data-lang);
position: absolute;
top: 5px;
right: 10px;
color: #95a5a6;
font-size: 0.8em;
font-weight: bold;
}
.highlight {
background-color: #ffff99;
}
.function-signature {
background-color: #e8f5e8;
border-left: 4px solid #27ae60;
padding: 10px 15px;
margin: 10px 0;
font-family: 'Courier New', monospace;
}
.api-table {
font-size: 0.9em;
}
.api-table th {
background-color: #2c3e50;
}
</style>
</head>
<body>
<div class="container">
<h1>Ludo Scripting Manual</h1>
<p>Ludo embeds <strong>Lua 5.2</strong> as its scripting engine. Every plugin and script has access to the full Lua standard library plus five extension libraries provided by Ludo:</p>
<table>
<thead>
<tr>
<th>Module</th>
<th>Global name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>JSON</td>
<td><code>json</code></td>
<td>JSON encode/decode via Lua CJSON</td>
</tr>
<tr>
<td>HTTP</td>
<td><code>http</code></td>
<td>HTTP client powered by libcurl</td>
</tr>
<tr>
<td>Ludo</td>
<td><code>ludo</code></td>
<td>Download manager & application control</td>
</tr>
<tr>
<td>UI</td>
<td><code>ui</code></td>
<td>Native GUI widgets (libui-ng)</td>
</tr>
<tr>
<td>Zip</td>
<td><code>zip</code></td>
<td>ZIP archive creation (zlib deflate)</td>
</tr>
</tbody>
</table>
<p>Scripts are loaded from the <code>plugins/</code> directory. Each plugin is a <code>.lua</code> file that returns a table with two functions: <code>validate(url)</code> and <code>process(url)</code>.</p>
<div class="toc">
<h2>Table of Contents</h2>
<ol>
<li><a href="#1-lua-language-basics">Lua Language Basics</a></li>
<li><a href="#2-standard-lua-library">Standard Lua Library</a></li>
<li><a href="#3-json-library-json">JSON Library (<code>json</code>)</a></li>
<li><a href="#4-http-library-http">HTTP Library (<code>http</code>)</a></li>
<li><a href="#5-zip-library-zip">Zip Library (<code>zip</code>)</a></li>
<li><a href="#6-ludo-library-ludo">Ludo Library (<code>ludo</code>)</a></li>
<li><a href="#7-ui-library-ui">UI Library (<code>ui</code>)</a></li>
<li><a href="#8-plugin-system">Plugin System</a></li>
<li><a href="#9-converting-yt-dlp-extractors-to-ludo-plugins">Converting yt-dlp Extractors to Ludo Plugins</a></li>
<li><a href="#10-testing-and-debugging-plugins">Testing and Debugging Plugins</a></li>
<li><a href="#11-tools-menu">Tools Menu</a></li>
</ol>
</div>
<h2 id="1-lua-language-basics">1. Lua Language Basics</h2>
<h3>1.1 Variables and Types</h3>
<p>Lua is dynamically typed. Variables do not need type declarations.</p>
<pre><code>lua
-- Numbers
local count = 42
local pi = 3.14159
-- Strings
local name = "Ludo"
local path = 'C:\\Downloads'
local multi = [[
This is a
multi-line string.
]]
-- Booleans
local active = true
local done = false
-- Nil (absence of value)
local nothing = nil
</code></pre>
<h3>1.2 Tables</h3>
<p>Tables are Lua's only compound data structure — they serve as arrays, dictionaries, objects, and modules.</p>
<pre><code>lua
-- Array-style (1-indexed)
local fruits = { "apple", "banana", "cherry" }
print(fruits[1]) --> apple
print(#fruits) --> 3
-- Dictionary-style
local config = {
url = "https://example.com",
port = 8080,
}
print(config.url) --> https://example.com
print(config["port"]) --> 8080
-- Mixed
local entry = {
name = "file.zip",
tags = { "release", "stable" },
}
</code></pre>
<h3>1.3 Control Flow</h3>
<pre><code>lua
-- if / elseif / else
if status == 200 then
print("OK")
elseif status == 404 then
print("Not found")
else
print("Error: " .. status)
end
-- while
local i = 1
while i <= 5 do
print(i)
i = i + 1
end
-- for (numeric)
for i = 1, 10 do
print(i)
end
-- for (generic / pairs)
local t = { a = 10, b = 20, c = 3 }
for key, value in pairs(t) do
print(key, value)
end
-- for (array / ipairs)
local list = { "x", "y", "z" }
for index, value in ipairs(list) do
print(index, value)
end
</code></pre>
<h3>1.4 Functions</h3>
<pre><code>lua
-- Named function
function greet(name)
return "Hello, " .. name .. "!"
end
-- Local function
local function add(a, b)
return a + b
end
-- Anonymous / closure
local double = function(x) return x * 2 end
-- Variadic
function printf(fmt, ...)
print(string.format(fmt, ...))
end
-- Multiple return values
function minmax(list)
local lo, hi = list[1], list[1]
for _, v in ipairs(list) do
if v < lo then lo = v end
if v > hi then hi = v end
end
return lo, hi
end
local lo, hi = minmax({3, 1, 4, 1, 5, 9})
print(lo, hi) --> 1 9
</code></pre>
<h3>1.5 String Operations</h3>
<pre><code>lua
local s = "Hello, World!"
print(string.len(s)) --> 13
print(string.upper(s)) --> HELLO, WORLD!
print(string.lower(s)) --> hello, world!
print(string.sub(s, 1, 5)) --> Hello
print(string.rep("ab", 3)) --> ababab
print(string.reverse(s)) --> !dlroW ,olleH
print(string.find(s, "World")) --> 8 12
print(string.format("pi=%.2f", 3.14159)) --> pi=3.14
-- Pattern matching
for word in string.gmatch(s, "%a+") do
print(word)
end
-- Substitution
local result = string.gsub(s, "World", "Lua")
print(result) --> Hello, Lua!
</code></pre>
<h3>1.5.1 Lua Pattern Reference</h3>
<p>Lua does <strong>not</strong> use PCRE/POSIX regular expressions. It has its own lightweight pattern language used by <code>string.match</code>, <code>string.gmatch</code>, <code>string.gsub</code>, and <code>string.find</code>.</p>
<h4>Character Classes</h4>
<table>
<thead>
<tr>
<th>Class</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>.</code></td>
<td>Any character</td>
</tr>
<tr>
<td><code>%a</code></td>
<td>Any letter (A-Z, a-z)</td>
</tr>
<tr>
<td><code>%d</code></td>
<td>Any digit (0-9)</td>
</tr>
<tr>
<td><code>%l</code></td>
<td>Any lowercase letter</td>
</tr>
<tr>
<td><code>%u</code></td>
<td>Any uppercase letter</td>
</tr>
<tr>
<td><code>%w</code></td>
<td>Any alphanumeric character (letter or digit)</td>
</tr>
<tr>
<td><code>%s</code></td>
<td>Any whitespace (space, tab, newline, etc.)</td>
</tr>
<tr>
<td><code>%p</code></td>
<td>Any punctuation character</td>
</tr>
<tr>
<td><code>%c</code></td>
<td>Any control character</td>
</tr>
<tr>
<td><code>%x</code></td>
<td>Any hexadecimal digit (0-9, a-f, A-F)</td>
</tr>
<tr>
<td><code>%A</code></td>
<td>Complement of <code>%a</code> (any non-letter)</td>
</tr>
<tr>
<td><code>%D</code></td>
<td>Complement of <code>%d</code> (any non-digit)</td>
</tr>
</tbody>
</table>
<h4>Quantifiers</h4>
<table>
<thead>
<tr>
<th>Quantifier</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>+</code></td>
<td>1 or more (greedy)</td>
</tr>
<tr>
<td><code>*</code></td>
<td>0 or more (greedy)</td>
</tr>
<tr>
<td><code>-</code></td>
<td>0 or more (lazy / non-greedy)</td>
</tr>
<tr>
<td><code>?</code></td>
<td>0 or 1</td>
</tr>
</tbody>
</table>
<h4>Anchors & Special</h4>
<table>
<thead>
<tr>
<th>Symbol</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>^</code></td>
<td>Start of string (only at the beginning of a pattern)</td>
</tr>
<tr>
<td><code>$</code></td>
<td>End of string (only at the end of a pattern)</td>
</tr>
<tr>
<td><code>%b()</code></td>
<td>Balanced match between two characters, e.g. <code>%b()</code> matches balanced parentheses</td>
</tr>
<tr>
<td><code>%%</code></td>
<td>Literal <code>%</code></td>
</tr>
<tr>
<td><code>%.</code></td>
<td>Literal <code>.</code> (escape any magic character with <code>%</code>)</td>
</tr>
</tbody>
</table>
<h4>Character Sets <code>[ ]</code></h4>
<pre><code>lua
"[aeiou]" -- matches any vowel
"[0-9]" -- matches any digit (same as %d)
"[%w_]" -- matches alphanumeric or underscore
"[^%s]" -- matches any non-whitespace character
"[%w%-_]" -- matches alphanumeric, hyphen, or underscore
</code></pre>
<h4>Captures <code>( )</code></h4>
<p>Parentheses create <strong>captures</strong> — the matched substrings are returned by <code>string.match</code> or passed to replacement functions in <code>string.gsub</code>.</p>
<pre><code>lua
-- Single capture
local year = string.match("Date: 2026-04-05", "(%d%d%d%d)")
print(year) --> 2026
-- Multiple captures
local y, m, d = string.match("2026-04-05", "(%d+)-(%d+)-(%d+)")
print(y, m, d) --> 2026 04 05
-- Non-capturing: use the full match (no parentheses)
local full = string.match("hello world", "%a+")
print(full) --> hello
</code></pre>
<h4>Practical Examples for Plugin Development</h4>
<pre><code>lua
-- Match a URL host
local host = url:match("^https?://([^/?#]+)")
-- "https://www.instagram.com/p/abc" -> "www.instagram.com"
-- Match a path segment
local shortcode = url:match("/p/([%w%-_]+)")
-- "https://www.instagram.com/p/aye83DjauH/" -> "aye83DjauH"
-- Optional path segments (reel or reels)
local id = url:match("/reels?/([%w%-_]+)")
-- matches both /reel/xxx and /reels/xxx
-- Extract JSON value from HTML
local video_id = html:match('"video_id"%s*:%s*"([^"]+)"')
-- Extract an attribute from an HTML tag
local src = html:match('<video[^>]+src="([^"]+)"')
-- Extract query parameter
local v = query:match("[?&]v=([^&]+)")
-- Iterate over all matches (gmatch)
for link in body:gmatch('href="(/[^"]+/download/[^"]+)"') do
print(link)
end
-- Greedy vs lazy
local s = "<div>hello</div><div>world</div>"
print(s:match("<div>(.-)</div>")) --> hello (lazy -)
print(s:match("<div>(.+)</div>")) --> hello</div><div>world (greedy +)
-- Escape literal dots in domain patterns
url:match("instagram%.com") -- correct: matches "instagram.com"
url:match("instagram.com") -- WRONG: '.' matches any character
-- Match colon-separated key-value in text
local key, val = line:match('^([^:]+):%s*(.*)')
-- tab-separated fields (cookie files)
local name, value = line:match("\t([^\t]+)\t([^\t]*)$")
</code></pre>
<h4>Key Differences from Python <code>re</code> / PCRE</h4>
<table>
<thead>
<tr>
<th>Python <code>re</code></th>
<th>Lua pattern</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>\d</code></td>
<td><code>%d</code></td>
<td><code>%</code> instead of <code>\</code> for classes</td>
</tr>
<tr>
<td><code>\w</code></td>
<td><code>%w</code></td>
<td>Lua <code>%w</code> does not include <code>_</code></td>
</tr>
<tr>
<td><code>[\w_]</code> or <code>\w</code></td>
<td><code>[%w_]</code></td>
<td>Add <code>_</code> explicitly in Lua</td>
</tr>
<tr>
<td><code>\s</code></td>
<td><code>%s</code></td>
<td></td>
</tr>
<tr>
<td><code>\b</code></td>
<td>(not available)</td>
<td>No word-boundary anchor</td>
</tr>
<tr>
<td><code>.*?</code></td>
<td><code>.-</code></td>
<td>Lazy quantifier uses <code>-</code></td>
</tr>
<tr>
<td><code>.+?</code></td>
<td><code>.+</code> with <code>-</code></td>
<td>Use <code>(.-)</code> for lazy</td>
</tr>
<tr>
<td><code>(?:...)</code></td>
<td>(not available)</td>
<td>All <code>()</code> are captures</td>
</tr>
<tr>
<td><code>re.IGNORECASE</code></td>
<td>(not available)</td>
<td>Use <code>[Aa]</code> or <code>string.lower()</code> first</td>
</tr>
<tr>
<td><code>|</code> (alternation)</td>
<td>(not available)</td>
<td>Use multiple <code>match()</code> calls</td>
</tr>
<tr>
<td><code>{3,5}</code></td>
<td>(not available)</td>
<td>Manually expand or use loops</td>
</tr>
</tbody>
</table>
<h3>1.6 Error Handling</h3>
<pre><code>lua
-- pcall (protected call)
local ok, err = pcall(function()
error("something went wrong")
end)
if not ok then
print("Caught error: " .. err)
end
-- xpcall (with custom error handler)
local ok, err = xpcall(
function() error("oops") end,
function(e) return "HANDLED: " .. e end
)
print(err) --> HANDLED: ...:oops
</code></pre>
<h2 id="2-standard-lua-library">2. Standard Lua Library</h2>
<p>Ludo opens all standard Lua 5.2 libraries. Below is a summary of each module with usage examples.</p>
<h3>2.1 Base Functions</h3>
<pre><code>lua
print("Hello") -- Print to stdout
type(42) -- "number"
type("hi") -- "string"
type(nil) -- "nil"
tostring(123) -- "123"
tonumber("42") -- 42
tonumber("0xff") -- 255
assert(1 + 1 == 2) -- passes
assert(false, "failed!") -- raises error
-- Iterate table
local t = { a = 10, b = 20 }
for k, v in pairs(t) do print(k, v) end
-- Iterate array
local a = { "x", "y" }
for i, v in ipairs(a) do print(i, v) end
-- Load and execute a string
local f = load("return 2 + 3")
print(f()) --> 5
-- Execute a file
dofile("script.lua")
</code></pre>
<h3>2.2 <code>string</code> Library</h3>
<pre><code>lua
string.byte("A") --> 65
string.char(65) --> "A"
string.len("hello") --> 5
string.rep("-", 40) --> ----------------------------------------
string.format("%d items", 5) --> "5 items"
string.find("foobar", "ob") --> 3 4
string.sub("abcdef", 2, 4) --> "bcd"
string.gsub("aaa", "a", "b") --> "bbb" 3
string.match("2024-01-15", "(%d+)-(%d+)-(%d+)") --> "2024" "01" "15"
string.upper("hello") --> "HELLO"
string.lower("HELLO") --> "hello"
string.reverse("abc") --> "cba"
</code></pre>
<h3>2.3 <code>table</code> Library</h3>
<pre><code>lua
local t = { 3, 1, 4, 1, 5 }
table.insert(t, 9) -- append 9
table.insert(t, 2, 99) -- insert 99 at position 2
table.remove(t, 1) -- remove first element
table.sort(t) -- sort in-place
-- Sort with comparator
table.sort(t, function(a, b) return a > b end)
-- Concatenate array elements
local csv = table.concat({ "a", "b", "c" }, ",")
print(csv) --> a,b,c
-- Unpack
local a, b, c = table.unpack({ 10, 20, 30 })
print(a, b, c) --> 10 20 30
</code></pre>
<h3>2.4 <code>math</code> Library</h3>
<pre><code>lua
math.abs(-7) --> 7
math.ceil(2.3) --> 3
math.floor(2.9) --> 2
math.max(1, 5, 3) --> 5
math.min(1, 5, 3) --> 1
math.sqrt(144) --> 12
math.sin(math.pi/2) --> 1.0
math.cos(0) --> 1.0
math.log(math.exp(1)) --> 1.0
math.random() --> random float [0, 1)
math.random(1, 100) --> random integer [1, 100]
math.randomseed(os.time())
-- Constants
print(math.pi) --> 3.1415926535898
print(math.huge) --> inf
</code></pre>
<h3>2.5 <code>io</code> Library</h3>
<pre><code>lua
-- Read entire file
local f = io.open("data.txt", "r")
if f then
local content = f:read("*a")
f:close()
print(content)
end
-- Write to file
local f = io.open("output.txt", "w")
f:write("line 1\n")
f:write("line 2\n")
f:close()
-- Append to file
local f = io.open("log.txt", "a")
f:write("new entry\n")
f:close()
-- Read line by line
for line in io.lines("data.txt") do
print(line)
end
</code></pre>
<h3>2.6 <code>os</code> Library</h3>
<pre><code>lua
print(os.time()) -- current Unix timestamp
print(os.date("%Y-%m-%d")) -- formatted date: "2026-03-20"
print(os.date("%H:%M:%S")) -- formatted time: "14:30:00"
print(os.clock()) -- CPU time in seconds
os.execute("mkdir new_folder") -- run system command
local tmpname = os.tmpname() -- temporary file path
os.remove("old_file.txt") -- delete a file
os.rename("old.txt", "new.txt") -- rename a file
-- Environment variables
print(os.getenv("PATH"))
-- Measure elapsed time
local start = os.clock()
-- ... work ...
local elapsed = os.clock() - start
print(string.format("Took %.3f seconds", elapsed))
</code></pre>
<h3>2.7 <code>bit32</code> Library (Lua 5.2)</h3>
<pre><code>lua
bit32.band(0xFF, 0x0F) --> 15
bit32.bor(0xF0, 0x0F) --> 255
bit32.bxor(0xFF, 0x0F) --> 240
bit32.bnot(0) --> 4294967295
bit32.lshift(1, 8) --> 256
bit32.rshift(256, 4) --> 16
bit32.btest(0xFF, 0x01) --> true
bit32.extract(0xFF, 4, 4) --> 15 (extract 4 bits from bit 4)
</code></pre>
<h2 id="3-json-library-json">3. JSON Library (<code>json</code>)</h2>
<p>Ludo bundles a fast JSON implementation (Lua CJSON) exposed as the global <code>json</code> module. A "safe" wrapper is also available as <code>cjson_safe</code> which returns <code>nil, err</code> instead of throwing on parse/encode errors.</p>
<p><strong>Key functions:</strong></p>
<ul>
<li><code>json.encode(value)</code> → string: serialise a Lua value (tables, numbers, booleans, strings, <code>json.null</code>) to JSON. Use <code>json.null</code> to represent JSON <code>null</code> in Lua tables.</li>
<li><code>json.decode(text)</code> → lua value: parse a JSON string and return the Lua representation. <code>json.decode</code> raises on malformed input — use <code>pcall(json.decode, text)</code> to catch errors, or use <code>require("cjson_safe")</code> (or the global <code>cjson_safe</code>) to get the safe wrapper that returns <code>nil, err</code>.</li>
<li><code>json.new()</code> → module: create a new isolated <code>json</code> module instance with its own configuration state.</li>
</ul>
<p><strong>Special values & behaviour:</strong></p>
<ul>
<li><code>json.null</code> — a lightuserdata sentinel used to represent JSON <code>null</code>. Compare with <code>if v == json.null then ... end</code>.</li>
<li>The decoder enforces strict JSON syntax and will error on invalid input.</li>
</ul>
<p><strong>Configuration functions:</strong> (each returns the previous/current value)</p>
<ul>
<li><code>json.encode_sparse_array(convert, ratio, safe)</code> — control sparse array handling when encoding.</li>
<li><code>json.encode_max_depth(n)</code> — maximum nesting allowed when encoding.</li>
<li><code>json.decode_max_depth(n)</code> — maximum nesting allowed when decoding.</li>
<li><code>json.encode_number_precision(n)</code> — number-to-string precision for encode.</li>
<li><code>json.encode_keep_buffer(true|false)</code> — reuse internal encode buffer.</li>
<li><code>json.encode_invalid_numbers(option)</code> — how to handle NaN/Inf when encoding (<code>off</code>, <code>on</code>, or <code>null</code>).</li>
<li><code>json.decode_invalid_numbers(option)</code> — whether to accept non-standard numbers when decoding.</li>
</ul>
<p><strong>Examples</strong></p>
<pre><code>lua
local json = json or require("json")
-- Encode a request body (used by plugins/youtube.lua)
local body = json.encode({ videoId = vid, context = { client = { hl = "en" } } })
-- Decode safely
local ok, data = pcall(json.decode, normalize_json_response(response_body))
if not ok then
print("JSON error:", data)
end
</code></pre>
<h3><code>cjson_safe</code> — Safe JSON Wrapper</h3>
<p>In addition to the <code>json</code> global, Ludo also registers <code>cjson_safe</code> as a <strong>global</strong> module (not just via <code>require</code>). It mirrors the full <code>json</code> API but its <code>encode</code> and <code>decode</code> functions return <code>nil, err</code> on failure instead of throwing a Lua error.</p>
<p><strong>Key functions:</strong></p>
<ul>
<li><code>cjson_safe.encode(value)</code> → <code>json_string, nil</code> on success, or <code>nil, err</code> on failure.</li>
<li><code>cjson_safe.decode(text)</code> → <code>lua_value, nil</code> on success, or <code>nil, err</code> on failure.</li>
<li><code>cjson_safe.new()</code> → module: create a new isolated safe module instance.</li>
</ul>
<p>All configuration functions are available on <code>cjson_safe</code> too:</p>
<ul>
<li><code>cjson_safe.encode_sparse_array(convert, ratio, safe)</code></li>
<li><code>cjson_safe.encode_max_depth(n)</code></li>
<li><code>cjson_safe.decode_max_depth(n)</code></li>
<li><code>cjson_safe.encode_number_precision(n)</code></li>
<li><code>cjson_safe.encode_keep_buffer(true|false)</code></li>
<li><code>cjson_safe.encode_invalid_numbers(option)</code></li>
<li><code>cjson_safe.decode_invalid_numbers(option)</code></li>
</ul>
<p><code>cjson_safe.null</code> is the same sentinel as <code>json.null</code>.</p>
<pre><code>lua
-- Safe decode without pcall
local data, err = cjson_safe.decode(body)
if not data then
ludo.logError("JSON error: " .. err)
end
-- Safe encode
local json_str, err = cjson_safe.encode(big_table)
if not json_str then
ludo.logError("Encode error: " .. err)
end
</code></pre>
<h2 id="4-http-library-http">4. HTTP Library (<code>http</code>)</h2>
<p>The <code>http</code> module is registered as a global table. It provides HTTP client functionality backed by libcurl with cookie management, URL utilities, and custom headers.</p>
<h3>4.1 <code>http.get(url [, options])</code> → body, status, headers</h3>
<p>Perform an HTTP GET request.</p>
<p><strong>Parameters:</strong></p>
<ul>
<li><code>url</code> (string) — The URL to fetch.</li>
<li><code>options</code> (table, optional) — Request options (see <a href="#47-options-table">Options Table</a>).</li>
</ul>
<p><strong>Returns:</strong></p>
<ul>
<li><code>body</code> (string|nil) - Response body, or <code>nil</code> when <code>file</code> option is set.</li>
<li><code>status</code> (number) - HTTP status code.</li>
<li><code>headers</code> (table) - Response headers as key-value pairs.</li>
</ul>
<pre><code>lua
-- Simple GET
local body, status, headers = http.get("https://httpbin.org/get")
print(status) --> 200
print(headers["Content-Type"]) --> application/json
-- GET with options
local body, status = http.get("https://api.example.com/data", {
user_agent = "MyBot/1.0",
timeout = 30,
headers = {
["Authorization"] = "Bearer my_token",
["Accept"] = "application/json",
},
})
-- Parse JSON response
if status == 200 then
-- Process body as needed
print("Received " .. #body .. " bytes")
end
</code></pre>
<h3>4.2 <code>http.get_async(url, options, callback)</code> → nothing</h3>
<p>Perform an asynchronous HTTP GET request. The request runs on a background worker thread so the GUI stays responsive. The callback fires on the main thread when the response arrives.</p>
<div class="note">
<p><strong>GUI builds only.</strong> Console builds (<code>ludocon</code>) return <code>nil, "http.get_async requires GUI build"</code>. The callback is <strong>one-shot</strong> — it fires exactly once and is automatically unregistered. The Lua state that calls <code>http.get_async</code> must remain alive until the callback fires (i.e. while <code>ui.Main()</code> is running).</p>
</div>
<p><strong>Parameters:</strong></p>
<ul>
<li><code>url</code> (string) — The URL to fetch.</li>
<li><code>options</code> (table) — Request options (see <a href="#47-options-table">Options Table</a>).</li>
<li><code>callback</code> (function) — Called as <code>callback(body, status, headers)</code>.</li>
</ul>
<p><strong>Callback arguments:</strong></p>
<ul>
<li><code>body</code> (string) — Response body (empty string on error).</li>
<li><code>status</code> (number) — HTTP status code (0 on network error).</li>
<li><code>headers</code> (table) — Response headers as key-value pairs.</li>
</ul>
<pre><code>lua
http.get_async("https://myserver.com/image.png",
{ user_agent = "Ludo/1.0", timeout = 10 },
function(body, status, headers)
if status == 200 then
local ok, img = pcall(ui.LoadImageFromMemory, body)
if ok and img then
-- update table model, etc.
else
ludo.logError("Image load failed: HTTP " .. status)
end
end)
</code></pre>
<h4>Loading images on-the-fly with <code>http.get_async</code> + <code>ui.LoadImageFromMemory</code></h4>
<div class="note">
<p><strong>For displaying a single full-size image</strong> (screenshots, previews), use <code>ui.NewStaticImage()</code> instead (§7.26). Table columns restrict images to icon size. The examples below are for thumbnail grids in Tables.</p>
</div>
<pre><code>lua
local images = {} -- keeps uiImage objects alive for table model
local handler = {
NumColumns = function(m) return 2 end,
ColumnType = function(m, col)
if col == 0 then return ui.TableValueTypeString end
return ui.TableValueTypeImage
end,
NumRows = function(m) return #urls end,