Skip to content

Commit 99904a4

Browse files
committed
tests: test upvalue debug functions
1 parent 56a8235 commit 99904a4

File tree

2 files changed

+50
-6
lines changed

2 files changed

+50
-6
lines changed

src/tests.zig

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1054,16 +1054,59 @@ test "debug interface" {
10541054
try lua.protectedCall(1, 1, 0);
10551055
}
10561056

1057+
test "debug upvalues" {
1058+
var lua = try Lua.init(testing.allocator);
1059+
defer lua.deinit();
1060+
1061+
try lua.doString(
1062+
\\f = function(x)
1063+
\\ return function(y)
1064+
\\ return x + y
1065+
\\ end
1066+
\\end
1067+
\\addone = f(1)
1068+
);
1069+
_ = lua.getGlobal("addone");
1070+
1071+
// index doesn't exist
1072+
try expectError(Error.Fail, lua.getUpvalue(1, 2));
1073+
1074+
// inspect the upvalue (should be x)
1075+
try expectEqualStrings("x", try lua.getUpvalue(-1, 1));
1076+
try expectEqual(@as(Number, 1), try lua.toNumber(-1));
1077+
lua.pop(1);
1078+
1079+
// now make the function an "add five" function
1080+
lua.pushNumber(5);
1081+
_ = try lua.setUpvalue(-2, 1);
1082+
1083+
// test a bad index (the valid one's result is unpredicable)
1084+
try expectError(Error.Fail, lua.upvalueId(-1, 2));
1085+
1086+
// call the new function (should return 7)
1087+
lua.pushNumber(2);
1088+
try lua.protectedCall(1, 1, 0);
1089+
try expectEqual(@as(Number, 7), try lua.toNumber(-1));
1090+
lua.pop(1);
1091+
1092+
try lua.doString(
1093+
\\addthree = f(3)
1094+
);
1095+
1096+
_ = lua.getGlobal("addone");
1097+
_ = lua.getGlobal("addthree");
1098+
1099+
// now addone and addthree share the same upvalue
1100+
lua.upvalueJoin(-2, 1, -1, 1);
1101+
try expect((try lua.upvalueId(-2, 1)) == try lua.upvalueId(-1, 1));
1102+
}
1103+
10571104
test "refs" {
10581105
// temporary test that includes a reference to all functions so
10591106
// they will be type-checked
10601107

10611108
// debug
10621109
_ = Lua.getStack;
1063-
_ = Lua.getUpvalue;
1064-
_ = Lua.setUpvalue;
1065-
_ = Lua.upvalueId;
1066-
_ = Lua.upvalueJoin;
10671110

10681111
// auxlib
10691112
_ = Lua.argCheck;

src/ziglua.zig

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1229,8 +1229,9 @@ pub const Lua = struct {
12291229
}
12301230

12311231
/// Returns a unique identifier for the upvalue numbered `n` from the closure index `func_index`
1232-
pub fn upvalueId(lua: *Lua, func_index: i32, n: i32) ?*anyopaque {
1233-
return c.lua_upvalueid(lua.state, func_index, n);
1232+
pub fn upvalueId(lua: *Lua, func_index: i32, n: i32) !*anyopaque {
1233+
if (c.lua_upvalueid(lua.state, func_index, n)) |ptr| return ptr;
1234+
return Error.Fail;
12341235
}
12351236

12361237
/// Make the `n1`th upvalue of the Lua closure at index `func_index1` refer to the `n2`th upvalue

0 commit comments

Comments
 (0)