Skip to content

Commit c69428c

Browse files
committed
Update guided tour
Signed-off-by: Maksym Pavlenko <pavlenko.maksym@gmail.com>
1 parent e954c48 commit c69428c

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

examples/guided_tour.zig

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
//! - Work with tuples and table-based structures
1515
//! - Control garbage collection for memory management
1616
//! - Work with coroutines and threads
17+
//! - Build strings efficiently with StrBuf
1718

1819
const std = @import("std");
1920
const luaz = @import("luaz");
@@ -153,7 +154,7 @@ pub fn main() !void {
153154

154155
// You can create a new Lua state with `Lua.init()`. Pass null to use Luau's
155156
// 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);
157158
defer lua.deinit();
158159

159160
// Load the standard Lua libraries
@@ -611,5 +612,41 @@ pub fn main() !void {
611612
print("Final: sum={}\n", .{final_result});
612613
}
613614

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+
614651
print("\n=== Tour Complete! ===\n", .{});
615652
}

0 commit comments

Comments
 (0)