Skip to content

Commit

Permalink
Use a negative stack index in examples/zig-fn.zig
Browse files Browse the repository at this point in the history
Closes #114
  • Loading branch information
natecraddock committed Oct 22, 2024
1 parent 5aef782 commit c7d3c53
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions examples/zig-fn.zig
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ pub fn main() anyerror!void {
defer _ = gpa.deinit();

// Initialize The Lua vm and get a reference to the main thread
//
// Passing a Zig allocator to the Lua state requires a stable pointer
var lua = try Lua.init(allocator);
defer lua.deinit();

Expand All @@ -42,8 +40,11 @@ pub fn main() anyerror!void {
lua.protectedCall(.{ .args = 2, .results = 1 }) catch unreachable;

// The result of the function call is on the stack.
// Use toInteger to read the integer at index 1
std.debug.print("the result: {}\n", .{lua.toInteger(1) catch unreachable});
// Use toInteger to read the integer at index -1.
// Using a negative stack offset will get the value relative to the top of the stack.
// Because nothing else is on the stack, index 1 would also work here. The negative index can
// be more reliable when the contents of the stack before the function call are unknown.
std.debug.print("the result: {}\n", .{lua.toInteger(-1) catch unreachable});

// We can also register the function to a global and run from a Lua "program"
lua.pushFunction(ziglua.wrap(adder));
Expand Down

0 comments on commit c7d3c53

Please sign in to comment.