Skip to content

Commit

Permalink
Add lua_tolightuserdata, optimized lua_topointer (#496)
Browse files Browse the repository at this point in the history
Co-authored-by: Petri Häkkinen <petrih@rmd.remedy.fi>
  • Loading branch information
petrihakkinen and Petri Häkkinen authored May 24, 2022
1 parent 70ff6b4 commit fb9c431
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
1 change: 1 addition & 0 deletions VM/include/lua.h
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ LUA_API const char* lua_tostringatom(lua_State* L, int idx, int* atom);
LUA_API const char* lua_namecallatom(lua_State* L, int* atom);
LUA_API int lua_objlen(lua_State* L, int idx);
LUA_API lua_CFunction lua_tocfunction(lua_State* L, int idx);
LUA_API void* lua_tolightuserdata(lua_State* L, int idx);
LUA_API void* lua_touserdata(lua_State* L, int idx);
LUA_API void* lua_touserdatatagged(lua_State* L, int idx, int tag);
LUA_API int lua_userdatatag(lua_State* L, int idx);
Expand Down
19 changes: 12 additions & 7 deletions VM/src/lapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -478,18 +478,22 @@ lua_CFunction lua_tocfunction(lua_State* L, int idx)
return (!iscfunction(o)) ? NULL : cast_to(lua_CFunction, clvalue(o)->c.f);
}

void* lua_tolightuserdata(lua_State* L, int idx)
{
StkId o = index2addr(L, idx);
return (!ttislightuserdata(o)) ? NULL : pvalue(o);
}

void* lua_touserdata(lua_State* L, int idx)
{
StkId o = index2addr(L, idx);
switch (ttype(o))
{
case LUA_TUSERDATA:
// fast-path: check userdata first since it is most likely the expected result
if (ttisuserdata(o))
return uvalue(o)->data;
case LUA_TLIGHTUSERDATA:
else if (ttislightuserdata(o))
return pvalue(o);
default:
else
return NULL;
}
}

void* lua_touserdatatagged(lua_State* L, int idx, int tag)
Expand Down Expand Up @@ -524,8 +528,9 @@ const void* lua_topointer(lua_State* L, int idx)
case LUA_TTHREAD:
return thvalue(o);
case LUA_TUSERDATA:
return uvalue(o)->data;
case LUA_TLIGHTUSERDATA:
return lua_touserdata(L, idx);
return pvalue(o);
default:
return NULL;
}
Expand Down
2 changes: 2 additions & 0 deletions tests/Conformance.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1066,13 +1066,15 @@ TEST_CASE("UserdataApi")
int lud;
lua_pushlightuserdata(L, &lud);

CHECK(lua_tolightuserdata(L, -1) == &lud);
CHECK(lua_touserdata(L, -1) == &lud);
CHECK(lua_topointer(L, -1) == &lud);

// regular user data
int* ud1 = (int*)lua_newuserdata(L, 4);
*ud1 = 42;

CHECK(lua_tolightuserdata(L, -1) == nullptr);
CHECK(lua_touserdata(L, -1) == ud1);
CHECK(lua_topointer(L, -1) == ud1);

Expand Down

0 comments on commit fb9c431

Please sign in to comment.