tests: add a metatable test

This commit is contained in:
Nathan Craddock 2022-07-13 19:59:23 -06:00
parent d0d3a95739
commit 7650761d9a
No known key found for this signature in database
GPG Key ID: ABE41A31B52E9DA7
2 changed files with 26 additions and 7 deletions

View File

@ -1228,6 +1228,28 @@ test "get global fail" {
try expectError(Error.Fail, lua.getGlobal("foo"));
}
test "metatables" {
var lua = try Lua.init(testing.allocator);
defer lua.deinit();
try lua.doString("f = function() return 10 end");
try lua.newMetatable("mt");
_ = lua.getMetatableAux("mt");
try expect(lua.compare(1, 2, .eq));
lua.pop(1);
// set the len metamethod to the function f
try lua.getGlobal("f");
lua.setField(1, "__len");
lua.newTable();
lua.setMetatableAux("mt");
try lua.callMeta(-1, "__len");
try expectEqual(@as(Number, 10), try lua.toNumber(-1));
}
test "refs" {
// temporary test that includes a reference to all functions so
// they will be type-checked
@ -1236,7 +1258,6 @@ test "refs" {
_ = Lua.argCheck;
_ = Lua.argError;
_ = Lua.argExpected;
_ = Lua.callMeta;
_ = Lua.checkOption;
_ = Lua.checkUserdata;
_ = Lua.checkVersion;
@ -1244,21 +1265,18 @@ test "refs" {
_ = Lua.raiseErrorAux;
_ = Lua.exeResult;
_ = Lua.fileResult;
_ = Lua.getMetatableAux;
_ = Lua.getSubtable;
_ = Lua.gSub;
_ = Lua.loadBuffer;
_ = Lua.loadBufferX;
_ = Lua.loadFile;
_ = Lua.loadFileX;
_ = Lua.newMetatable;
_ = Lua.optInteger;
_ = Lua.optLString;
_ = Lua.optNumber;
_ = Lua.optString;
_ = Lua.pushFail;
_ = Lua.requireF;
_ = Lua.setMetatableAux;
_ = Lua.testUserdata;
_ = Lua.toLStringAux;
_ = Lua.traceback;

View File

@ -1314,8 +1314,8 @@ pub const Lua = struct {
}
/// Calls a metamethod
pub fn callMeta(lua: *Lua, obj: i32, field: [:0]const u8) bool {
return c.luaL_callmeta(lua.state, obj, field) != 0;
pub fn callMeta(lua: *Lua, obj: i32, field: [:0]const u8) !void {
if (c.luaL_callmeta(lua.state, obj, field) == 0) return Error.Fail;
}
/// Checks whether the function has an argument of any type at position `arg`
@ -1423,6 +1423,7 @@ pub const Lua = struct {
/// Pushes onto the stack the metatable associated with the name `type_name` in the registry
/// or nil if there is no metatable associated with that name. Returns the type of the pushed value
/// TODO: return error when type is nil?
pub fn getMetatableAux(lua: *Lua, type_name: [:0]const u8) LuaType {
return @intToEnum(LuaType, c.luaL_getmetatable(lua.state, type_name));
}
@ -1520,7 +1521,7 @@ pub const Lua = struct {
lua.createTable(0, @intCast(i32, list.len));
}
/// If the registry already has the key `key`, returns 0
/// If the registry already has the key `key`, returns an error
/// Otherwise, creates a new table to be used as a metatable for userdata
pub fn newMetatable(lua: *Lua, key: [:0]const u8) !void {
if (c.luaL_newmetatable(lua.state, key) == 0) return Error.Fail;