From b1d318de623f0112036aef4fea2b2da15d51ed86 Mon Sep 17 00:00:00 2001 From: Nathaniel Wesley Filardo Date: Thu, 24 Dec 2020 07:39:08 +0000 Subject: [PATCH] NFC: Backport luaL_testudata to Lua 5.1 (#3352) And move luaL_checkudata to it, as in 5.3. --- app/lua/lauxlib.c | 18 +++++++++++------- app/lua/lauxlib.h | 1 + 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/app/lua/lauxlib.c b/app/lua/lauxlib.c index ff7bee2d..73b971f3 100644 --- a/app/lua/lauxlib.c +++ b/app/lua/lauxlib.c @@ -285,21 +285,25 @@ LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, const ROTable return 1; } -LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { +LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { void *p = lua_touserdata(L, ud); if (p != NULL) { /* value is a userdata? */ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */ - if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */ - lua_pop(L, 2); /* remove both metatables */ - return p; - } + if (!lua_rawequal(L, -1, -2)) /* not the same? */ + p = NULL; /* value is a userdata with wrong metatable */ + lua_pop(L, 2); /* remove both metatables */ + return p; } } - luaL_typerror(L, ud, tname); /* else error */ - return NULL; /* to avoid warnings */ + return NULL; /* value is not a userdata with a metatable */ } +LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { + void *p = luaL_testudata(L, ud, tname); + if (p == NULL) luaL_typerror(L, ud, tname); + return p; +} LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) { if (!lua_checkstack(L, space)) diff --git a/app/lua/lauxlib.h b/app/lua/lauxlib.h index 6708aaec..83ecd932 100644 --- a/app/lua/lauxlib.h +++ b/app/lua/lauxlib.h @@ -66,6 +66,7 @@ LUALIB_API void (luaL_checkany) (lua_State *L, int narg); LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname); LUALIB_API int (luaL_rometatable) (lua_State *L, const char* tname, const ROTable *p); +LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); LUALIB_API void (luaL_where) (lua_State *L, int lvl);