-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.lua
More file actions
1719 lines (1409 loc) · 49.6 KB
/
Copy pathtest.lua
File metadata and controls
1719 lines (1409 loc) · 49.6 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
-- test.lua — Cross-implementation compatibility tests for Lua 5.5
-- Run: swift run LuaREPL test.lua
--
-- POLICY: Only add tests that pass when run with the official Lua 5.5 reference
-- implementation (lua5.5 / lua). Do not add interpreter-specific extensions,
-- typed-syntax features, or other behaviour not in standard Lua 5.5 — use Swift
-- tests instead (e.g. Tests/LuaInterpreterTests/).
--------------------------------------------------------------------------------
-- Test harness
--------------------------------------------------------------------------------
local pass_count = 0
local fail_count = 0
local current_section = ""
local function section(name)
current_section = name
print("--- " .. name .. " ---")
end
local function test(description, condition)
if condition then
pass_count = pass_count + 1
else
fail_count = fail_count + 1
print(" FAIL: " .. description)
end
end
local function test_error(description, fn)
local ok, err = pcall(fn)
if not ok then
pass_count = pass_count + 1
else
fail_count = fail_count + 1
print(" FAIL (expected error): " .. description)
end
end
;(function()
--------------------------------------------------------------------------------
-- 1. Literals and Types
--------------------------------------------------------------------------------
section("Literals and Types")
test("nil literal", type(nil) == "nil")
test("true literal", true == true)
test("false literal", false == false)
test("integer literal", 42 == 42)
test("negative integer", -1 == -1)
test("hex integer", 0xFF == 255)
test("float literal", 3.14 > 3.13 and 3.14 < 3.15)
test("float with exponent", 1e2 == 100.0)
test("hex float", 0x1p4 == 16.0)
test("double-quoted string", "hello" == "hello")
test("single-quoted string", 'world' == "world")
test("long string", [[long]] == "long")
test("long string level 1", [=[bracket]=] == "bracket")
test("empty string", "" == "")
test("string escape newline", "\n" ~= "n")
test("string escape tab", "\t" ~= "t")
test("string escape backslash", "\\" ~= "")
test("type of nil", type(nil) == "nil")
test("type of boolean", type(true) == "boolean")
test("type of integer", type(42) == "number")
test("type of float", type(3.14) == "number")
test("type of string", type("hi") == "string")
test("type of table", type({}) == "table")
test("type of function", type(print) == "function")
end)()
;(function()
--------------------------------------------------------------------------------
-- 2. Arithmetic Operators
--------------------------------------------------------------------------------
section("Arithmetic Operators")
-- Integer arithmetic
test("addition", 2 + 3 == 5)
test("subtraction", 10 - 4 == 6)
test("multiplication", 3 * 7 == 21)
test("floor division", 7 // 2 == 3)
test("modulo", 7 % 3 == 1)
test("power", 2 ^ 10 == 1024.0)
test("unary minus", -(5) == -5)
-- Float arithmetic
test("float addition", 1.5 + 2.5 == 4.0)
test("float division always float", type(10 / 3) == "number")
test("division result", 10 / 4 == 2.5)
test("float floor division", 7.0 // 2 == 3.0)
test("float modulo", 7.5 % 2.0 == 1.5)
-- Mixed int/float
test("int + float promotes", 1 + 1.0 == 2.0)
test("int * float promotes", 2 * 3.5 == 7.0)
-- String-to-number coercion in arithmetic
test("string + int coercion", "10" + 5 == 15)
test("string * string coercion", "3" * "4" == 12)
-- Negative floor division and modulo
test("negative floor div", -7 // 2 == -4)
test("negative modulo", -7 % 3 == 2)
end)()
;(function()
--------------------------------------------------------------------------------
-- 3. Comparison Operators
--------------------------------------------------------------------------------
section("Comparison Operators")
test("equal integers", 1 == 1)
test("not equal integers", 1 ~= 2)
test("less than", 1 < 2)
test("greater than", 3 > 2)
test("less or equal", 2 <= 2)
test("greater or equal", 3 >= 2)
test("int-float equality", 1 == 1.0)
test("int-float not equal", 1 ~= 1.5)
-- String comparisons
test("string equal", "abc" == "abc")
test("string not equal", "abc" ~= "def")
test("string less than", "abc" < "abd")
test("string greater than", "b" > "a")
-- Nil comparisons
test("nil == nil", nil == nil)
test("nil ~= false", nil ~= false)
test("nil ~= 0", nil ~= 0)
end)()
;(function()
--------------------------------------------------------------------------------
-- 4. Logical Operators
--------------------------------------------------------------------------------
section("Logical Operators")
test("true and true", (true and true) == true)
test("true and false", (true and false) == false)
test("false and true", (false and true) == false)
test("true or false", (true or false) == true)
test("false or true", (false or true) == true)
test("false or false", (false or false) == false)
test("not true", not true == false)
test("not false", not false == true)
test("not nil", not nil == true)
-- Short-circuit and value semantics
test("and returns first falsy", (nil and 5) == nil)
test("and returns last truthy", (1 and 2) == 2)
test("or returns first truthy", (1 or 2) == 1)
test("or returns last falsy", (false or nil) == nil)
-- Truthiness
test("0 is truthy", (0 and true) == true)
test("empty string is truthy", ("" and true) == true)
test("empty table is truthy", ({} and true) == true)
end)()
;(function()
--------------------------------------------------------------------------------
-- 5. Bitwise Operators
--------------------------------------------------------------------------------
section("Bitwise Operators")
test("bitwise and", 0xFF & 0x0F == 0x0F)
test("bitwise or", 0xF0 | 0x0F == 0xFF)
test("bitwise xor", 0xFF ~ 0x0F == 0xF0)
test("left shift", 1 << 4 == 16)
test("right shift", 16 >> 4 == 1)
test("bitwise not", ~0 == -1)
test("bitwise not of 1", ~1 == -2)
end)()
;(function()
--------------------------------------------------------------------------------
-- 6. String Operations
--------------------------------------------------------------------------------
section("String Operations")
test("concatenation", "hello" .. " " .. "world" == "hello world")
test("concat with number", "val=" .. 42 == "val=42")
test("concat with float", "pi=" .. 3.14 ~= "pi=")
test("length operator", #"hello" == 5)
test("empty string length", #"" == 0)
test("concat right-assoc", "a" .. "b" .. "c" == "abc")
end)()
;(function()
--------------------------------------------------------------------------------
-- 7. Variables and Scoping
--------------------------------------------------------------------------------
section("Variables and Scoping")
-- Global variables
x_global = 10
test("global assignment", x_global == 10)
x_global = 20
test("global reassignment", x_global == 20)
plain_implicit = 5
test("implicit global plain assignment", plain_implicit == 5)
-- Local variables
local a = 5
test("local variable", a == 5)
-- Multiple assignment
local m1, m2, m3 = 1, 2, 3
test("multiple assignment first", m1 == 1)
test("multiple assignment second", m2 == 2)
test("multiple assignment third", m3 == 3)
-- Fewer values than variables
local f1, f2 = 10
test("missing values are nil", f2 == nil)
-- Swap via multiple assignment
local sw1, sw2 = 1, 2
sw1, sw2 = sw2, sw1
test("swap via multiple assignment", sw1 == 2 and sw2 == 1)
-- Block scoping
do
local inner = 99
test("inner scope visible", inner == 99)
end
-- inner should not be visible here
test("outer scope unchanged", type(inner) == "nil" or inner == nil)
-- Variable shadowing
local shadow = 1
do
local shadow = 2
test("shadow in block", shadow == 2)
end
test("shadow restored", shadow == 1)
-- Const variable
local MAX <const> = 100
test("const variable readable", MAX == 100)
end)()
;(function()
--------------------------------------------------------------------------------
-- 8. Control Flow — if/elseif/else
--------------------------------------------------------------------------------
section("Control Flow — if/elseif/else")
local r1
if true then r1 = "yes" end
test("if true", r1 == "yes")
local r2
if false then r2 = "yes" else r2 = "no" end
test("if false else", r2 == "no")
local r3 = "none"
local val = 2
if val == 1 then r3 = "one"
elseif val == 2 then r3 = "two"
elseif val == 3 then r3 = "three"
else r3 = "other"
end
test("elseif chain", r3 == "two")
end)()
;(function()
--------------------------------------------------------------------------------
-- 9. Control Flow — while loop
--------------------------------------------------------------------------------
section("Control Flow — while loop")
local sum = 0
local i = 1
while i <= 5 do
sum = sum + i
i = i + 1
end
test("while loop sum 1..5", sum == 15)
-- While with break
local bk = 0
while true do
bk = bk + 1
if bk == 3 then break end
end
test("while break", bk == 3)
end)()
;(function()
--------------------------------------------------------------------------------
-- 10. Control Flow — repeat-until
--------------------------------------------------------------------------------
section("Control Flow — repeat-until")
local rp = 0
repeat
rp = rp + 1
until rp >= 5
test("repeat until", rp == 5)
-- Repeat accesses loop body locals in condition
local rv = 0
repeat
local x = rv + 1
rv = x
until x == 3
test("repeat-until sees body locals", rv == 3)
end)()
;(function()
--------------------------------------------------------------------------------
-- 11. Control Flow — numeric for
--------------------------------------------------------------------------------
section("Control Flow — numeric for")
local nf_sum = 0
for i = 1, 5 do
nf_sum = nf_sum + i
end
test("numeric for 1..5", nf_sum == 15)
-- With step
local nf_step = 0
for i = 0, 10, 2 do
nf_step = nf_step + 1
end
test("numeric for with step", nf_step == 6) -- 0,2,4,6,8,10
-- Negative step
local nf_neg = 0
for i = 5, 1, -1 do
nf_neg = nf_neg + i
end
test("numeric for negative step", nf_neg == 15)
-- Break in for
local nf_break = 0
for i = 1, 100 do
if i > 3 then break end
nf_break = nf_break + 1
end
test("numeric for with break", nf_break == 3)
-- Loop variable is local
do
for j = 1, 1 do end
test("for loop var is local", type(j) == "nil" or j == nil)
end
end)()
;(function()
--------------------------------------------------------------------------------
-- 12. Control Flow — generic for
--------------------------------------------------------------------------------
section("Control Flow — generic for")
-- ipairs
local arr = {10, 20, 30}
local ip_sum = 0
for i, v in ipairs(arr) do
ip_sum = ip_sum + v
end
test("generic for ipairs", ip_sum == 60)
-- pairs
local dict = {a = 1, b = 2, c = 3}
local p_sum = 0
for k, v in pairs(dict) do
p_sum = p_sum + v
end
test("generic for pairs", p_sum == 6)
end)()
do
--------------------------------------------------------------------------------
-- 13. Control Flow — goto and labels
--------------------------------------------------------------------------------
section("Control Flow — goto and labels")
local g = 0
g = g + 1
goto skip
g = g + 100
::skip::
g = g + 1
test("goto skips code", g == 2)
-- Goto forward over blocks
local g2 = "start"
goto done
do
g2 = "should not reach"
end
::done::
test("goto forward over block", g2 == "start")
end
;(function()
--------------------------------------------------------------------------------
-- 14. Functions
--------------------------------------------------------------------------------
section("Functions")
-- Basic function
local function add(a, b)
return a + b
end
test("function call", add(2, 3) == 5)
-- Recursive function
local function fib(n)
if n <= 1 then return n end
return fib(n - 1) + fib(n - 2)
end
test("recursion", fib(10) == 55)
-- Anonymous function
local mul = function(a, b) return a * b end
test("anonymous function", mul(3, 4) == 12)
-- Multiple return values
local function multi()
return 1, 2, 3
end
local mr1, mr2, mr3 = multi()
test("multiple return first", mr1 == 1)
test("multiple return second", mr2 == 2)
test("multiple return third", mr3 == 3)
-- Varargs
local function vsum(...)
local s = 0
local args = {...}
for i = 1, #args do
s = s + args[i]
end
return s
end
test("varargs", vsum(1, 2, 3, 4) == 10)
-- Varargs with leading params
local function vfirst(first, ...)
return first, select("#", ...)
end
local vf1, vf2 = vfirst(10, 20, 30)
test("vararg with leading param", vf1 == 10)
test("vararg count via select", vf2 == 2)
-- Higher-order function
local function apply(f, x)
return f(x)
end
test("higher-order function", apply(function(x) return x * 2 end, 5) == 10)
end)()
;(function()
--------------------------------------------------------------------------------
-- 15. Closures
--------------------------------------------------------------------------------
section("Closures")
local function counter()
local n = 0
return function()
n = n + 1
return n
end
end
local c = counter()
test("closure first call", c() == 1)
test("closure second call", c() == 2)
test("closure third call", c() == 3)
-- Shared state between closures
local function make_pair()
local val = 0
local function get() return val end
local function set(v) val = v end
return get, set
end
local get, set = make_pair()
test("closure shared state initial", get() == 0)
set(42)
test("closure shared state after set", get() == 42)
-- Independent closure instances
local c2 = counter()
test("independent closure", c2() == 1)
test("original closure preserved", c() == 4)
end)()
;(function()
--------------------------------------------------------------------------------
-- 16. Tables — Construction
--------------------------------------------------------------------------------
section("Tables — Construction")
local empty = {}
test("empty table", type(empty) == "table")
test("empty table length", #empty == 0)
local arr2 = {10, 20, 30}
test("array constructor", arr2[1] == 10 and arr2[2] == 20 and arr2[3] == 30)
test("array length", #arr2 == 3)
local rec = {x = 1, y = 2}
test("record constructor x", rec.x == 1)
test("record constructor y", rec.y == 2)
local mixed = {10, x = "a", 20, y = "b"}
test("mixed table array", mixed[1] == 10 and mixed[2] == 20)
test("mixed table record", mixed.x == "a" and mixed.y == "b")
local indexed = {[3] = "three", [1] = "one"}
test("indexed constructor", indexed[3] == "three" and indexed[1] == "one")
-- Trailing separator
local trail = {1, 2, 3,}
test("trailing comma", #trail == 3)
-- Semicolon separator
local semi = {1; 2; 3}
test("semicolon separator", #semi == 3)
end)()
;(function()
--------------------------------------------------------------------------------
-- 17. Tables — Access and Assignment
--------------------------------------------------------------------------------
section("Tables — Access and Assignment")
local t = {}
t.name = "lua"
test("field assignment", t.name == "lua")
t["key"] = "value"
test("bracket assignment", t["key"] == "value")
t[1] = "first"
test("integer key assignment", t[1] == "first")
-- Nested tables
local nested = {inner = {val = 42}}
test("nested field access", nested.inner.val == 42)
-- Nil for missing keys
test("missing key is nil", t.nonexistent == nil)
-- Delete by setting nil
t.name = nil
test("delete by nil", t.name == nil)
end)()
;(function()
--------------------------------------------------------------------------------
-- 18. Tables — Methods
--------------------------------------------------------------------------------
section("Tables — Methods")
local obj = {value = 10}
function obj:getValue()
return self.value
end
function obj:setValue(v)
self.value = v
end
test("method call get", obj:getValue() == 10)
obj:setValue(99)
test("method call set", obj:getValue() == 99)
-- Dot-name function definition
local mod = {}
function mod.greet(name)
return "hi " .. name
end
test("dotted function name", mod.greet("lua") == "hi lua")
end)()
;(function()
--------------------------------------------------------------------------------
-- 19. Metatables — Arithmetic
--------------------------------------------------------------------------------
section("Metatables — Arithmetic")
local Vec = {}
Vec.__index = Vec
function Vec.new(x, y)
return setmetatable({x = x, y = y}, Vec)
end
Vec.__add = function(a, b)
return Vec.new(a.x + b.x, a.y + b.y)
end
Vec.__sub = function(a, b)
return Vec.new(a.x - b.x, a.y - b.y)
end
Vec.__mul = function(a, b)
if type(a) == "number" then return Vec.new(a * b.x, a * b.y) end
if type(b) == "number" then return Vec.new(a.x * b, a.y * b) end
return a.x * b.x + a.y * b.y -- dot product
end
Vec.__unm = function(a)
return Vec.new(-a.x, -a.y)
end
local v1 = Vec.new(1, 2)
local v2 = Vec.new(3, 4)
local v3 = v1 + v2
test("__add", v3.x == 4 and v3.y == 6)
local v4 = v2 - v1
test("__sub", v4.x == 2 and v4.y == 2)
local v5 = v1 * 3
test("__mul scalar", v5.x == 3 and v5.y == 6)
local v6 = -v1
test("__unm", v6.x == -1 and v6.y == -2)
end)()
;(function()
--------------------------------------------------------------------------------
-- 20. Metatables — Comparison and Equality
--------------------------------------------------------------------------------
section("Metatables — Comparison and Equality")
local Num = {}
Num.__index = Num
function Num.new(v) return setmetatable({v = v}, Num) end
Num.__eq = function(a, b) return a.v == b.v end
Num.__lt = function(a, b) return a.v < b.v end
Num.__le = function(a, b) return a.v <= b.v end
local n1 = Num.new(5)
local n2 = Num.new(5)
local n3 = Num.new(10)
test("__eq true", n1 == n2)
test("__eq false", n1 ~= n3)
test("__lt true", n1 < n3)
test("__lt false", n3 < n1 == false)
test("__le true", n1 <= n2)
end)()
;(function()
--------------------------------------------------------------------------------
-- 21. Metatables — Index and Newindex
--------------------------------------------------------------------------------
section("Metatables — Index and Newindex")
-- __index as table (prototype chain)
local proto = {greet = function() return "hello" end}
local child = setmetatable({}, {__index = proto})
test("__index table lookup", child.greet() == "hello")
-- __index as function
local defaults = setmetatable({}, {
__index = function(t, k)
return "default:" .. k
end
})
test("__index function", defaults.foo == "default:foo")
-- __newindex as function
local log = {}
local logged = setmetatable({}, {
__newindex = function(t, k, v)
log[#log + 1] = k
rawset(t, k, v)
end
})
logged.x = 1
logged.y = 2
test("__newindex function", #log == 2)
test("__newindex stored value", logged.x == 1)
end)()
;(function()
--------------------------------------------------------------------------------
-- 22. Metatables — Other
--------------------------------------------------------------------------------
section("Metatables — Other")
-- __len
local custom_len = setmetatable({}, {__len = function() return 42 end})
test("__len", #custom_len == 42)
-- __concat
local Str = {}
Str.__index = Str
function Str.new(s) return setmetatable({s = s}, Str) end
Str.__concat = function(a, b)
local as = type(a) == "table" and a.s or a
local bs = type(b) == "table" and b.s or b
return Str.new(as .. bs)
end
local s1 = Str.new("hello")
local s2 = Str.new(" world")
local s3 = s1 .. s2
test("__concat", s3.s == "hello world")
-- __call
local callable = setmetatable({}, {
__call = function(self, x)
return x * 2
end
})
test("__call", callable(5) == 10)
-- __tostring
local ts = setmetatable({}, {
__tostring = function() return "custom_tostring" end
})
test("__tostring", tostring(ts) == "custom_tostring")
-- getmetatable / setmetatable
local mt = {}
local obj2 = setmetatable({}, mt)
test("getmetatable", getmetatable(obj2) == mt)
-- __metatable guard
local guarded = setmetatable({}, {__metatable = "protected"})
test("__metatable hides real mt", getmetatable(guarded) == "protected")
test_error("__metatable blocks setmetatable", function()
setmetatable(guarded, {})
end)
end)()
;(function()
--------------------------------------------------------------------------------
-- 23. Error Handling
--------------------------------------------------------------------------------
section("Error Handling")
-- pcall success
local ok, val = pcall(function() return 42 end)
test("pcall success ok", ok == true)
test("pcall success value", val == 42)
-- pcall failure
local ok2, err2 = pcall(function() error("boom") end)
test("pcall failure ok", ok2 == false)
test("pcall failure message", type(err2) == "string")
-- pcall with args
local ok3, val3 = pcall(function(a, b) return a + b end, 10, 20)
test("pcall with args", ok3 == true and val3 == 30)
-- xpcall with handler
local ok4, val4 = xpcall(
function() error("oops") end,
function(e) return "handled: " .. e end
)
test("xpcall handler called", ok4 == false)
test("xpcall handler result", type(val4) == "string")
-- error with non-string
local ok5, val5 = pcall(function() error(123) end)
test("error with number", val5 == 123)
-- assert success
local ok6, val6 = pcall(function() return assert(42, "msg") end)
test("assert success", ok6 == true and val6 == 42)
-- assert failure
local ok7, err7 = pcall(function() assert(false, "fail msg") end)
test("assert failure", ok7 == false)
end)()
;(function()
--------------------------------------------------------------------------------
-- 24. Standard Library — type, tostring, tonumber
--------------------------------------------------------------------------------
section("Standard Library — Conversion")
test("tostring nil", tostring(nil) == "nil")
test("tostring true", tostring(true) == "true")
test("tostring false", tostring(false) == "false")
test("tostring int", tostring(42) == "42")
test("tostring float", tostring(3.5) == "3.5")
test("tostring string", tostring("hi") == "hi")
test("tonumber int string", tonumber("42") == 42)
test("tonumber float string", tonumber("3.14") == 3.14)
test("tonumber hex string", tonumber("0xFF") == 255)
test("tonumber nil for bad input", tonumber("abc") == nil)
test("tonumber identity int", tonumber(42) == 42)
test("tonumber with base", tonumber("ff", 16) == 255)
test("tonumber base 2", tonumber("1010", 2) == 10)
end)()
;(function()
--------------------------------------------------------------------------------
-- 25. Standard Library — select, unpack
--------------------------------------------------------------------------------
section("Standard Library — select, unpack")
test("select index", select(2, "a", "b", "c") == "b")
test("select count", select("#", "a", "b", "c") == 3)
local u1, u2, u3 = table.unpack({10, 20, 30})
test("table.unpack all", u1 == 10 and u2 == 20 and u3 == 30)
local u4, u5 = table.unpack({10, 20, 30}, 2, 3)
test("table.unpack range", u4 == 20 and u5 == 30)
end)()
;(function()
--------------------------------------------------------------------------------
-- 26. Standard Library — raw functions
--------------------------------------------------------------------------------
section("Standard Library — Raw Access")
local raw_t = setmetatable({}, {
__index = function() return "meta" end,
__newindex = function() end,
__eq = function() return true end,
__len = function() return 999 end
})
test("rawget bypasses __index", rawget(raw_t, "x") == nil)
rawset(raw_t, "x", 42)
test("rawset bypasses __newindex", rawget(raw_t, "x") == 42)
test("rawequal bypasses __eq", rawequal(raw_t, raw_t) == true)
test("rawequal different", rawequal(raw_t, {}) == false)
test("rawlen bypasses __len", rawlen({1, 2, 3}) == 3)
end)()
;(function()
--------------------------------------------------------------------------------
-- 27. Standard Library — String Library
--------------------------------------------------------------------------------
section("Standard Library — String")
test("string.len", string.len("hello") == 5)
test("string.len empty", string.len("") == 0)
test("string.sub", string.sub("hello", 2, 4) == "ell")
test("string.sub negative", string.sub("hello", -3) == "llo")
test("string.sub from start", string.sub("hello", 1, 1) == "h")
test("string.rep", string.rep("ab", 3) == "ababab")
test("string.rep with sep", string.rep("a", 3, ",") == "a,a,a")
test("string.reverse", string.reverse("hello") == "olleh")
test("string.upper", string.upper("hello") == "HELLO")
test("string.lower", string.lower("HELLO") == "hello")
-- byte and char
test("string.byte", string.byte("A") == 65)
test("string.byte with index", string.byte("ABC", 2) == 66)
test("string.char", string.char(65, 66, 67) == "ABC")
-- format
test("string.format %d", string.format("%d", 42) == "42")
test("string.format %s", string.format("%s", "hi") == "hi")
test("string.format %f", string.format("%.2f", 3.14) == "3.14")
test("string.format %x", string.format("%x", 255) == "ff")
test("string.format %%", string.format("100%%") == "100%")
test("string.format multiple", string.format("%s=%d", "x", 5) == "x=5")
-- find
local s, e = string.find("hello world", "world")
test("string.find found", s == 7 and e == 11)
local s2 = string.find("hello", "xyz")
test("string.find not found", s2 == nil)
local s3, e3 = string.find("hello", "ll", 1, true)
test("string.find plain", s3 == 3 and e3 == 4)
end)()
;(function()
--------------------------------------------------------------------------------
-- 28. Standard Library — Table Library
--------------------------------------------------------------------------------
section("Standard Library — Table")
-- insert and remove
local ti = {1, 2, 3}
table.insert(ti, 4)
test("table.insert append", ti[4] == 4 and #ti == 4)
table.insert(ti, 1, 0)
test("table.insert at pos", ti[1] == 0 and #ti == 5)
local removed = table.remove(ti)
test("table.remove last", removed == 4 and #ti == 4)
local removed2 = table.remove(ti, 1)
test("table.remove at pos", removed2 == 0 and #ti == 3)
-- concat
local tc = {"a", "b", "c"}
test("table.concat", table.concat(tc, ", ") == "a, b, c")
test("table.concat no sep", table.concat(tc) == "abc")
test("table.concat range", table.concat(tc, "-", 2, 3) == "b-c")
-- move
local src = {1, 2, 3, 4, 5}
local dst = {0, 0, 0, 0, 0}
table.move(src, 2, 4, 1, dst)
test("table.move", dst[1] == 2 and dst[2] == 3 and dst[3] == 4)
-- sort
local ts = {3, 1, 4, 1, 5, 9}
table.sort(ts)
test("table.sort ascending", ts[1] == 1 and ts[2] == 1 and ts[6] == 9)
local ts2 = {5, 3, 1, 4, 2}
table.sort(ts2)
test("table.sort default asc", ts2[1] == 1 and ts2[5] == 5)
-- unpack (table.unpack alias)
local tu1, tu2 = table.unpack({10, 20})
test("table.unpack", tu1 == 10 and tu2 == 20)
end)()
;(function()
--------------------------------------------------------------------------------
-- 29. Standard Library — Math Library
--------------------------------------------------------------------------------
section("Standard Library — Math")
-- Constants
test("math.pi", math.pi > 3.14 and math.pi < 3.15)
test("math.huge", math.huge > 1e308)
test("math.maxinteger", math.maxinteger > 0)
test("math.mininteger", math.mininteger < 0)
-- Basic functions
test("math.abs positive", math.abs(5) == 5)
test("math.abs negative", math.abs(-5) == 5)
test("math.ceil", math.ceil(2.3) == 3)
test("math.floor", math.floor(2.9) == 2)
test("math.max", math.max(1, 5, 3) == 5)
test("math.min", math.min(4, 1, 7) == 1)
test("math.sqrt", math.sqrt(16) == 4.0)
-- Trig
test("math.sin(0)", math.sin(0) == 0.0)
test("math.cos(0)", math.cos(0) == 1.0)
test("math.tan(0)", math.tan(0) == 0.0)
-- Exp and log
test("math.exp(0)", math.exp(0) == 1.0)
test("math.log(1)", math.log(1) == 0.0)
test("math.log with base", math.log(8, 2) == 3.0)
-- Integer conversion
test("math.tointeger from int", math.tointeger(5) == 5)
test("math.tointeger from float", math.tointeger(5.0) == 5)
test("math.tointeger non-int float", math.tointeger(5.5) == nil)
-- math.type
test("math.type integer", math.type(1) == "integer")
test("math.type float", math.type(1.0) == "float")
test("math.type non-number", math.type("x") == nil)
-- random (just ensure it doesn't error)
local r = math.random()
test("math.random [0,1)", r >= 0 and r < 1)
local ri = math.random(1, 10)
test("math.random range", ri >= 1 and ri <= 10)
end)()
;(function()
--------------------------------------------------------------------------------
-- 30. Iterators — pairs and ipairs
--------------------------------------------------------------------------------
section("Iterators — pairs and ipairs")
-- ipairs stops at first nil
local sparse = {1, 2, nil, 4}
local ip_count = 0
for _ in ipairs(sparse) do ip_count = ip_count + 1 end
test("ipairs stops at nil", ip_count == 2)