|
14 | 14 | //! - Work with tuples and table-based structures |
15 | 15 | //! - Control garbage collection for memory management |
16 | 16 | //! - Work with coroutines and threads |
| 17 | +//! - Build strings efficiently with StrBuf |
17 | 18 |
|
18 | 19 | const std = @import("std"); |
19 | 20 | const luaz = @import("luaz"); |
@@ -153,7 +154,7 @@ pub fn main() !void { |
153 | 154 |
|
154 | 155 | // You can create a new Lua state with `Lua.init()`. Pass null to use Luau's |
155 | 156 | // default allocator, or pass a Zig allocator for custom memory management. |
156 | | - const lua = try luaz.Lua.init(&allocator); |
| 157 | + var lua = try luaz.Lua.init(&allocator); |
157 | 158 | defer lua.deinit(); |
158 | 159 |
|
159 | 160 | // Load the standard Lua libraries |
@@ -611,5 +612,41 @@ pub fn main() !void { |
611 | 612 | print("Final: sum={}\n", .{final_result}); |
612 | 613 | } |
613 | 614 |
|
| 615 | + // String Buffer (StrBuf) for efficient string building |
| 616 | + { |
| 617 | + print("\n-- String Buffer (StrBuf) --\n", .{}); |
| 618 | + |
| 619 | + // Build strings efficiently with mixed types |
| 620 | + var buf: luaz.Lua.StrBuf = undefined; |
| 621 | + buf.init(&lua); |
| 622 | + buf.addString("User #"); |
| 623 | + try buf.add(@as(i32, 42)); |
| 624 | + buf.addString(" logged in at "); |
| 625 | + try buf.add(@as(f64, 3.14)); |
| 626 | + buf.addString(" seconds"); |
| 627 | + |
| 628 | + const globals = lua.globals(); |
| 629 | + try globals.set("message", &buf); |
| 630 | + const message = try globals.get("message", []const u8); |
| 631 | + print("Built string: {s}\n", .{message.?}); |
| 632 | + |
| 633 | + // Return StrBuf from Zig functions |
| 634 | + const formatMessage = struct { |
| 635 | + fn call(l: *luaz.Lua, name: []const u8, age: i32) !luaz.Lua.StrBuf { |
| 636 | + var b: luaz.Lua.StrBuf = undefined; |
| 637 | + b.init(l); |
| 638 | + b.addLString(name); |
| 639 | + b.addString(" is "); |
| 640 | + try b.add(age); |
| 641 | + b.addString(" years old"); |
| 642 | + return b; |
| 643 | + } |
| 644 | + }.call; |
| 645 | + |
| 646 | + try globals.setClosure("formatMessage", &lua, formatMessage); |
| 647 | + const result = try lua.eval("return formatMessage('Alice', 25)", .{}, []const u8); |
| 648 | + print("From function: {s}\n", .{result}); |
| 649 | + } |
| 650 | + |
614 | 651 | print("\n=== Tour Complete! ===\n", .{}); |
615 | 652 | } |
0 commit comments