forked from wippyai/go-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyield_across_boundaries_test.go
More file actions
1794 lines (1493 loc) · 42.9 KB
/
Copy pathyield_across_boundaries_test.go
File metadata and controls
1794 lines (1493 loc) · 42.9 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
package lua
import (
"context"
"strings"
"testing"
)
// Tests for yielding across call boundaries that use callR/Call internally.
// These opcodes use nested mainLoop calls which don't propagate yields correctly.
//
// Affected paths:
// - OP_TFORLOOP: generic for loop iterator calls (callR)
// - getFieldString: __index metamethod (Call)
// - setField: __newindex metamethod (Call)
// - objectArith: __add/__sub/__mul/__div/__mod/__pow metamethods (Call)
// - objectConcat: __concat metamethod (Call)
// - objectRational: __eq/__lt/__le metamethods (Call)
// - OP_UNM: __unm metamethod (Call)
// - OP_LEN: __len metamethod (Call)
// helper: creates a Go function that yields the first argument.
func yieldingGoFunc(L *LState) int {
return L.Yield(L.Get(1))
}
// helper: resume coroutine expecting yield, return yielded values.
func expectYield(t *testing.T, L *LState, co *LState, fn *LFunction, args ...LValue) []LValue {
t.Helper()
state, results, err := L.Resume(co, fn, args...)
if err != nil {
t.Fatalf("Resume failed: %v", err)
}
if state != ResumeYield {
t.Fatalf("Expected ResumeYield, got %v (results: %v)", state, results)
}
return results
}
// helper: resume coroutine expecting completion, return results.
func expectDone(t *testing.T, L *LState, co *LState, fn *LFunction, args ...LValue) []LValue {
t.Helper()
state, results, err := L.Resume(co, fn, args...)
if err != nil {
t.Fatalf("Resume failed: %v", err)
}
if state != ResumeOK {
t.Fatalf("Expected ResumeOK, got %v (results: %v)", state, results)
}
return results
}
// ---------------------------------------------------------------------------
// OP_TFORLOOP: yield from generic for-loop iterator
// ---------------------------------------------------------------------------
func TestYieldFromForInIterator_LuaYield(t *testing.T) {
L := NewState()
defer L.Close()
// Iterator that yields each value before returning it
if err := L.DoString(`
function yielding_iter(items)
local i = 0
return function()
i = i + 1
if i > #items then return nil end
coroutine.yield("producing:" .. items[i])
return items[i]
end
end
function test()
local results = {}
for val in yielding_iter({"a", "b", "c"}) do
results[#results + 1] = val
end
return table.concat(results, ",")
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
// Each iteration yields before returning the value
r := expectYield(t, L, co, fn)
if r[0].String() != "producing:a" {
t.Fatalf("Expected 'producing:a', got %v", r[0])
}
r = expectYield(t, L, co, fn)
if r[0].String() != "producing:b" {
t.Fatalf("Expected 'producing:b', got %v", r[0])
}
r = expectYield(t, L, co, fn)
if r[0].String() != "producing:c" {
t.Fatalf("Expected 'producing:c', got %v", r[0])
}
// Final resume completes
results := expectDone(t, L, co, fn)
if results[0].String() != "a,b,c" {
t.Errorf("Expected 'a,b,c', got %v", results[0])
}
}
func TestYieldFromForInIterator_GoFunctionYield(t *testing.T) {
L := NewState()
defer L.Close()
// Go function that yields its argument
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
function yielding_iter(items)
local i = 0
return function()
i = i + 1
if i > #items then return nil end
go_yield("producing:" .. items[i])
return items[i]
end
end
function test()
local results = {}
for val in yielding_iter({"a", "b", "c"}) do
results[#results + 1] = val
end
return table.concat(results, ",")
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
// Each iteration: Go function yields, then resume returns to iterator
for _, expected := range []string{"producing:a", "producing:b", "producing:c"} {
r := expectYield(t, L, co, fn)
if r[0].String() != expected {
t.Fatalf("Expected %q, got %v", expected, r[0])
}
}
results := expectDone(t, L, co, fn)
if results[0].String() != "a,b,c" {
t.Errorf("Expected 'a,b,c', got %v", results[0])
}
}
func TestYieldFromForInIterator_ResumeValues(t *testing.T) {
L := NewState()
defer L.Close()
// Iterator that yields a request and uses the resume value
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
function lazy_iter(ids)
local i = 0
return function()
i = i + 1
if i > #ids then return nil end
-- yield request, receive loaded data on resume
local data = go_yield("load:" .. ids[i])
return data
end
end
function test()
local results = {}
for val in lazy_iter({"x", "y"}) do
results[#results + 1] = val
end
return table.concat(results, ",")
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
// First iteration yields load request
r := expectYield(t, L, co, fn)
if r[0].String() != "load:x" {
t.Fatalf("Expected 'load:x', got %v", r[0])
}
// Resume with loaded data
r = expectYield(t, L, co, fn, LString("data_x"))
if r[0].String() != "load:y" {
t.Fatalf("Expected 'load:y', got %v", r[0])
}
// Resume with second loaded data, completes
results := expectDone(t, L, co, fn, LString("data_y"))
if results[0].String() != "data_x,data_y" {
t.Errorf("Expected 'data_x,data_y', got %v", results[0])
}
}
func TestYieldFromForInIterator_MultipleReturnValues(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
// Iterator returns key, value pairs (like pairs/ipairs)
if err := L.DoString(`
function kv_iter(tbl)
local keys = {}
for k in pairs(tbl) do keys[#keys + 1] = k end
table.sort(keys)
local i = 0
return function()
i = i + 1
if i > #keys then return nil end
go_yield("fetch:" .. keys[i])
return keys[i], tbl[keys[i]]
end
end
function test()
local results = {}
for k, v in kv_iter({a=1, b=2}) do
results[#results + 1] = k .. "=" .. v
end
table.sort(results)
return table.concat(results, ",")
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn) // fetch:a
expectYield(t, L, co, fn) // fetch:b
results := expectDone(t, L, co, fn)
if results[0].String() != "a=1,b=2" {
t.Errorf("Expected 'a=1,b=2', got %v", results[0])
}
}
func TestYieldFromForInIterator_WithPcall(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
function yielding_iter(n)
local i = 0
return function()
i = i + 1
if i > n then return nil end
go_yield("item:" .. i)
return i
end
end
function test()
local ok, result = pcall(function()
local sum = 0
for v in yielding_iter(3) do
sum = sum + v
end
return sum
end)
return ok, result
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn) // item:1
expectYield(t, L, co, fn) // item:2
expectYield(t, L, co, fn) // item:3
results := expectDone(t, L, co, fn)
if results[0] != LTrue {
t.Errorf("Expected pcall success, got %v", results[0])
}
if LVAsNumber(results[1]) != 6 {
t.Errorf("Expected 6, got %v", results[1])
}
}
func TestYieldFromForInIterator_ErrorAfterYield(t *testing.T) {
L := NewState()
defer L.Close()
// Track how many times the iterator is called per resume cycle.
// The bug causes double-execution: iterator called twice per single resume.
callCount := 0
L.SetGlobal("go_yield", L.NewFunction(func(L *LState) int {
callCount++
return L.Yield(L.Get(1))
}))
if err := L.DoString(`
function failing_iter()
local i = 0
return function()
i = i + 1
if i > 2 then error("iterator exhausted badly") end
go_yield("item:" .. i)
return i
end
end
function test()
local ok, err = pcall(function()
local sum = 0
for v in failing_iter() do
sum = sum + v
end
return sum
end)
return ok, err
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
callCount = 0
r := expectYield(t, L, co, fn)
if r[0].String() != "item:1" {
t.Fatalf("Expected 'item:1', got %v", r[0])
}
if callCount != 1 {
t.Fatalf("Expected go_yield called once per resume, called %d times (double-execution bug)", callCount)
}
callCount = 0
r = expectYield(t, L, co, fn)
if r[0].String() != "item:2" {
t.Fatalf("Expected 'item:2', got %v", r[0])
}
if callCount != 1 {
t.Fatalf("Expected go_yield called once per resume, called %d times (double-execution bug)", callCount)
}
// Third iteration errors before yield
results := expectDone(t, L, co, fn)
if results[0] != LFalse {
t.Errorf("Expected pcall failure, got %v", results[0])
}
}
func TestYieldFromForInIterator_NestedForLoops(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
function yiter(items)
local i = 0
return function()
i = i + 1
if i > #items then return nil end
go_yield("y:" .. items[i])
return items[i]
end
end
function test()
local results = {}
for a in yiter({"x", "y"}) do
for b in yiter({"1", "2"}) do
results[#results + 1] = a .. b
end
end
return table.concat(results, ",")
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
// outer "x", inner "1", inner "2", outer "y", inner "1", inner "2"
expectedYields := []string{"y:x", "y:1", "y:2", "y:y", "y:1", "y:2"}
for _, expected := range expectedYields {
r := expectYield(t, L, co, fn)
if r[0].String() != expected {
t.Fatalf("Expected %q, got %v", expected, r[0])
}
}
results := expectDone(t, L, co, fn)
if results[0].String() != "x1,x2,y1,y2" {
t.Errorf("Expected 'x1,x2,y1,y2', got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __index metamethod: yield from field access
// ---------------------------------------------------------------------------
func TestYieldFromIndexMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__index = function(self, key)
go_yield("index:" .. key)
return rawget(self, "_data")[key]
end
}
function make_proxy(data)
local obj = {_data = data}
setmetatable(obj, mt)
return obj
end
function test()
local p = make_proxy({name = "alice", age = 30})
local n = p.name
local a = p.age
return n .. ":" .. a
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "index:name" {
t.Fatalf("Expected 'index:name', got %v", r[0])
}
r = expectYield(t, L, co, fn)
if r[0].String() != "index:age" {
t.Fatalf("Expected 'index:age', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if results[0].String() != "alice:30" {
t.Errorf("Expected 'alice:30', got %v", results[0])
}
}
func TestYieldFromIndexMetamethod_MethodCall(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
// OP_SELF uses getFieldString which calls __index
if err := L.DoString(`
local mt = {
__index = function(self, key)
go_yield("lookup:" .. key)
if key == "greet" then
return function(self)
return "hello " .. rawget(self, "name")
end
end
return rawget(self, key)
end
}
function test()
local obj = setmetatable({name = "bob"}, mt)
return obj:greet()
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "lookup:greet" {
t.Fatalf("Expected 'lookup:greet', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if results[0].String() != "hello bob" {
t.Errorf("Expected 'hello bob', got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __newindex metamethod: yield from field assignment
// ---------------------------------------------------------------------------
func TestYieldFromNewIndexMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local log = {}
local mt = {
__newindex = function(self, key, value)
go_yield("set:" .. key .. "=" .. tostring(value))
rawset(self, key, value)
end
}
function test()
local obj = setmetatable({}, mt)
obj.x = 10
obj.y = 20
return obj.x + obj.y
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "set:x=10" {
t.Fatalf("Expected 'set:x=10', got %v", r[0])
}
r = expectYield(t, L, co, fn)
if r[0].String() != "set:y=20" {
t.Fatalf("Expected 'set:y=20', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if LVAsNumber(results[0]) != 30 {
t.Errorf("Expected 30, got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __add metamethod: yield from arithmetic
// ---------------------------------------------------------------------------
func TestYieldFromAddMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__add = function(a, b)
go_yield("add:" .. tostring(a.v) .. "+" .. tostring(b.v))
return setmetatable({v = a.v + b.v}, getmetatable(a))
end
}
function num(v)
return setmetatable({v = v}, mt)
end
function test()
local a = num(10)
local b = num(20)
local c = a + b
return c.v
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "add:10+20" {
t.Fatalf("Expected 'add:10+20', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if LVAsNumber(results[0]) != 30 {
t.Errorf("Expected 30, got %v", results[0])
}
}
func TestYieldFromSubMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__sub = function(a, b)
go_yield("sub")
return setmetatable({v = a.v - b.v}, getmetatable(a))
end
}
function num(v) return setmetatable({v = v}, mt) end
function test()
local r = num(50) - num(8)
return r.v
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn)
results := expectDone(t, L, co, fn)
if LVAsNumber(results[0]) != 42 {
t.Errorf("Expected 42, got %v", results[0])
}
}
func TestYieldFromMulMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__mul = function(a, b)
go_yield("mul")
return setmetatable({v = a.v * b.v}, getmetatable(a))
end
}
function num(v) return setmetatable({v = v}, mt) end
function test()
local r = num(6) * num(7)
return r.v
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn)
results := expectDone(t, L, co, fn)
if LVAsNumber(results[0]) != 42 {
t.Errorf("Expected 42, got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __concat metamethod: yield from string concatenation
// ---------------------------------------------------------------------------
func TestYieldFromConcatMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__concat = function(a, b)
local av = type(a) == "table" and a.v or tostring(a)
local bv = type(b) == "table" and b.v or tostring(b)
go_yield("concat:" .. av .. ".." .. bv)
return setmetatable({v = av .. bv}, getmetatable(a) or getmetatable(b))
end
}
function str(v) return setmetatable({v = v}, mt) end
function test()
local r = str("hello") .. str(" world")
return r.v
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "concat:hello.. world" {
t.Fatalf("Expected 'concat:hello.. world', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if results[0].String() != "hello world" {
t.Errorf("Expected 'hello world', got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __unm metamethod: yield from unary minus
// ---------------------------------------------------------------------------
func TestYieldFromUnmMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__unm = function(a)
go_yield("neg:" .. a.v)
return setmetatable({v = -a.v}, getmetatable(a))
end
}
function num(v) return setmetatable({v = v}, mt) end
function test()
local r = -num(42)
return r.v
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "neg:42" {
t.Fatalf("Expected 'neg:42', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if LVAsNumber(results[0]) != -42 {
t.Errorf("Expected -42, got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __len metamethod: yield from # operator
// ---------------------------------------------------------------------------
func TestYieldFromLenMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__len = function(a)
go_yield("len")
return #rawget(a, "items")
end
}
function test()
local obj = setmetatable({items = {1, 2, 3, 4, 5}}, mt)
return #obj
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn)
results := expectDone(t, L, co, fn)
if LVAsNumber(results[0]) != 5 {
t.Errorf("Expected 5, got %v", results[0])
}
}
// ---------------------------------------------------------------------------
// __eq metamethod: yield from equality comparison
// ---------------------------------------------------------------------------
func TestYieldFromEqMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__eq = function(a, b)
go_yield("eq:" .. a.v .. "==" .. b.v)
return a.v == b.v
end
}
function val(v) return setmetatable({v = v}, mt) end
function test()
local a = val(42)
local b = val(42)
local c = val(99)
local r1 = a == b
local r2 = a == c
return r1, r2
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
r := expectYield(t, L, co, fn)
if r[0].String() != "eq:42==42" {
t.Fatalf("Expected 'eq:42==42', got %v", r[0])
}
r = expectYield(t, L, co, fn)
if r[0].String() != "eq:42==99" {
t.Fatalf("Expected 'eq:42==99', got %v", r[0])
}
results := expectDone(t, L, co, fn)
if results[0] != LTrue {
t.Errorf("Expected true for 42==42, got %v", results[0])
}
if results[1] != LFalse {
t.Errorf("Expected false for 42==99, got %v", results[1])
}
}
// ---------------------------------------------------------------------------
// __lt metamethod: yield from less-than comparison
// ---------------------------------------------------------------------------
func TestYieldFromLtMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__lt = function(a, b)
go_yield("lt:" .. a.v .. "<" .. b.v)
return a.v < b.v
end
}
function val(v) return setmetatable({v = v}, mt) end
function test()
local r1 = val(1) < val(2)
local r2 = val(5) < val(3)
return r1, r2
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn) // 1<2
expectYield(t, L, co, fn) // 5<3
results := expectDone(t, L, co, fn)
if results[0] != LTrue {
t.Errorf("Expected true for 1<2, got %v", results[0])
}
if results[1] != LFalse {
t.Errorf("Expected false for 5<3, got %v", results[1])
}
}
// ---------------------------------------------------------------------------
// __le metamethod: yield from less-than-or-equal comparison
// ---------------------------------------------------------------------------
func TestYieldFromLeMetamethod(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__le = function(a, b)
go_yield("le:" .. a.v .. "<=" .. b.v)
return a.v <= b.v
end
}
function val(v) return setmetatable({v = v}, mt) end
function test()
local r1 = val(3) <= val(3)
local r2 = val(4) <= val(3)
return r1, r2
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
expectYield(t, L, co, fn) // 3<=3
expectYield(t, L, co, fn) // 4<=3
results := expectDone(t, L, co, fn)
if results[0] != LTrue {
t.Errorf("Expected true for 3<=3, got %v", results[0])
}
if results[1] != LFalse {
t.Errorf("Expected false for 4<=3, got %v", results[1])
}
}
// ---------------------------------------------------------------------------
// Combined: yield from multiple boundary types in one coroutine
// ---------------------------------------------------------------------------
func TestYieldFromMixedBoundaries(t *testing.T) {
L := NewState()
defer L.Close()
L.SetGlobal("go_yield", L.NewFunction(yieldingGoFunc))
if err := L.DoString(`
local mt = {
__index = function(self, key)
go_yield("index:" .. key)
return rawget(self, "_d")[key]
end,
__add = function(a, b)
go_yield("add")
return a._d.v + b._d.v
end
}
function wrap(tbl)
return setmetatable({_d = tbl}, mt)
end
function yielding_iter(items)
local i = 0
return function()
i = i + 1
if i > #items then return nil end
go_yield("iter:" .. i)
return items[i]
end
end
function test()
local a = wrap({v = 10})
local b = wrap({v = 20})
-- triggers __index yield
local av = a.v
-- triggers __add yield
local sum = a + b
-- triggers iterator yield
local items = {}
for val in yielding_iter({av, sum}) do
items[#items + 1] = val
end
return table.concat(items, ",")
end
`); err != nil {
t.Fatal(err)
}
co := L.NewThreadWithContext(context.TODO())
fn := L.GetGlobal("test").(*LFunction)
// __index for a.v
r := expectYield(t, L, co, fn)
if r[0].String() != "index:v" {
t.Fatalf("Expected 'index:v', got %v", r[0])
}
// __add for a + b
r = expectYield(t, L, co, fn)
if r[0].String() != "add" {
t.Fatalf("Expected 'add', got %v", r[0])
}
// iterator yields
r = expectYield(t, L, co, fn)