Skip to content

Commit c5d1432

Browse files
committed
refactor: pass type to checkUserdata and testUserdata
Rather than pass a string and require an opaque cast, the functions now accept a Zig type so the string and cast can be done automatically.
1 parent 150ebe4 commit c5d1432

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

src/tests.zig

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1475,7 +1475,7 @@ test "userdata" {
14751475

14761476
const checkUdata = ziglua.wrap(struct {
14771477
fn inner(l: *Lua) i32 {
1478-
const ptr = ziglua.opaqueCast(Type, l.checkUserdata(1, "Type"));
1478+
const ptr = l.checkUserdata(Type, 1);
14791479
if (ptr.a != 1234) {
14801480
l.pushBytes("error!");
14811481
l.raiseError();
@@ -1497,10 +1497,10 @@ test "userdata" {
14971497

14981498
const testUdata = ziglua.wrap(struct {
14991499
fn inner(l: *Lua) i32 {
1500-
const ptr = ziglua.opaqueCast(Type, l.testUserdata(1, "Type") catch {
1500+
const ptr = l.testUserdata(Type, 1) catch {
15011501
l.pushBytes("error!");
15021502
l.raiseError();
1503-
});
1503+
};
15041504
if (ptr.a != 1234) {
15051505
l.pushBytes("error!");
15061506
l.raiseError();
@@ -1533,6 +1533,4 @@ test "refs" {
15331533
// probably not needed in ziglua
15341534
_ = Lua.execResult;
15351535
_ = Lua.fileResult;
1536-
1537-
_ = Lua.testUserdata;
15381536
}

src/ziglua.zig

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1383,10 +1383,9 @@ pub const Lua = struct {
13831383

13841384
/// Checks whether the function argument `arg` is a userdata of the type `type_name`
13851385
/// Returns the userdata's memory-block address
1386-
/// TODO: accept type as param?
1387-
pub fn checkUserdata(lua: *Lua, arg: i32, type_name: [:0]const u8) *anyopaque {
1386+
pub fn checkUserdata(lua: *Lua, comptime T: type, arg: i32) *T {
13881387
// the returned pointer will not be null
1389-
return c.luaL_checkudata(lua.state, arg, type_name).?;
1388+
return opaqueCast(T, c.luaL_checkudata(lua.state, arg, @typeName(T)).?);
13901389
}
13911390

13921391
/// Checks whether the code making the call and the Lua library being called are using
@@ -1614,9 +1613,9 @@ pub const Lua = struct {
16141613
}
16151614

16161615
/// This function works like `Lua.checkUserdata()` except it returns a Zig error instead of raising a Lua error on fail
1617-
pub fn testUserdata(lua: *Lua, arg: i32, type_name: [:0]const u8) !*anyopaque {
1618-
if (c.luaL_testudata(lua.state, arg, type_name)) |ptr| {
1619-
return ptr;
1616+
pub fn testUserdata(lua: *Lua, comptime T: type, arg: i32) !*T {
1617+
if (c.luaL_testudata(lua.state, arg, @typeName(T))) |ptr| {
1618+
return opaqueCast(T, ptr);
16201619
} else return error.Fail;
16211620
}
16221621

0 commit comments

Comments
 (0)