@@ -1389,6 +1389,19 @@ fn closureSingle(increment: i32, x: i32) i32 {
13891389 return x + increment ;
13901390}
13911391
1392+ const ClosureCounter = struct {
1393+ count : i32 ,
1394+
1395+ fn increment (self : * @This (), amount : i32 ) i32 {
1396+ self .count += amount ;
1397+ return self .count ;
1398+ }
1399+
1400+ fn getValue (self : * const @This ()) i32 {
1401+ return self .count ;
1402+ }
1403+ };
1404+
13921405test "table setClosure" {
13931406 const lua = try Lua .init (& std .testing .allocator );
13941407 defer lua .deinit ();
@@ -1439,3 +1452,33 @@ test "table setClosure" {
14391452 _ = try lua .eval ("config.mult = 7" , .{}, void );
14401453 try expect (try lua .eval ("return f.multiply(5)" , .{}, i32 ) == 35 );
14411454}
1455+
1456+ test "setClosure with pointer receiver" {
1457+ const lua = try Lua .init (& std .testing .allocator );
1458+ defer lua .deinit ();
1459+
1460+ const table = lua .createTable (.{});
1461+ defer table .deinit ();
1462+
1463+ // Create a counter instance
1464+ var counter = ClosureCounter { .count = 10 };
1465+
1466+ // Register methods with *Self receivers as closures (direct pointer)
1467+ // Note: User is responsible for ensuring the pointer remains valid for the lifetime of the closure
1468+ try table .setClosure ("increment" , & counter , ClosureCounter .increment );
1469+ try table .setClosure ("getValue" , & counter , ClosureCounter .getValue );
1470+
1471+ try lua .globals ().set ("counter" , table );
1472+
1473+ // Test initial value
1474+ try expect (try lua .eval ("return counter.getValue()" , .{}, i32 ) == 10 );
1475+
1476+ // Test increment with mutable *Self
1477+ try expect (try lua .eval ("return counter.increment(5)" , .{}, i32 ) == 15 );
1478+ try expect (try lua .eval ("return counter.getValue()" , .{}, i32 ) == 15 );
1479+
1480+ // Test multiple increments
1481+ try expect (try lua .eval ("return counter.increment(3)" , .{}, i32 ) == 18 );
1482+ try expect (try lua .eval ("return counter.increment(2)" , .{}, i32 ) == 20 );
1483+ try expect (try lua .eval ("return counter.getValue()" , .{}, i32 ) == 20 );
1484+ }
0 commit comments