Skip to content

Commit

Permalink
Add lua_getallocf API function (#1068)
Browse files Browse the repository at this point in the history
This function matches the corresponding Lua 5.1-5.4 function:

[`lua_getallocf`](https://www.lua.org/manual/5.4/manual.html#lua_getallocf)
and [source](https://www.lua.org/source/5.4/lapi.c.html#lua_getallocf)

It would be useful to get/manipulate auxiliary "userdata" pointer that was originally passed to `lua_newstate`.
  • Loading branch information
khvzak authored Oct 13, 2023
1 parent 1173e41 commit 5c94984
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions VM/include/lua.h
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,8 @@ LUA_API void lua_clonefunction(lua_State* L, int idx);

LUA_API void lua_cleartable(lua_State* L, int idx);

LUA_API lua_Alloc lua_getallocf(lua_State* L, void** ud);

/*
** reference system, can be used to pin objects
*/
Expand Down
8 changes: 8 additions & 0 deletions VM/src/lapi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1432,3 +1432,11 @@ size_t lua_totalbytes(lua_State* L, int category)
api_check(L, category < LUA_MEMORY_CATEGORIES);
return category < 0 ? L->global->totalbytes : L->global->memcatbytes[category];
}

lua_Alloc lua_getallocf(lua_State* L, void** ud)
{
lua_Alloc f = L->global->frealloc;
if (ud)
*ud = L->global->ud;
return f;
}
12 changes: 12 additions & 0 deletions tests/Conformance.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1163,6 +1163,18 @@ TEST_CASE("ApiType")
CHECK(lua_type(L, -1) == LUA_TUSERDATA);
}

TEST_CASE("AllocApi")
{
int ud = 0;
StateRef globalState(lua_newstate(limitedRealloc, &ud), lua_close);
lua_State* L = globalState.get();

void* udCheck = nullptr;
bool allocfIsSet = lua_getallocf(L, &udCheck) == limitedRealloc;
CHECK(allocfIsSet);
CHECK(udCheck == &ud);
}

#if !LUA_USE_LONGJMP
TEST_CASE("ExceptionObject")
{
Expand Down

0 comments on commit 5c94984

Please sign in to comment.