From 5c9498493563c32c42a055cbbf9630818757ad27 Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Fri, 13 Oct 2023 16:47:33 +0100 Subject: [PATCH] Add `lua_getallocf` API function (#1068) 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`. --- VM/include/lua.h | 2 ++ VM/src/lapi.cpp | 8 ++++++++ tests/Conformance.test.cpp | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/VM/include/lua.h b/VM/include/lua.h index 43c60d77..1e8c30ba 100644 --- a/VM/include/lua.h +++ b/VM/include/lua.h @@ -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 */ diff --git a/VM/src/lapi.cpp b/VM/src/lapi.cpp index 2b98e47d..2d714566 100644 --- a/VM/src/lapi.cpp +++ b/VM/src/lapi.cpp @@ -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; +} diff --git a/tests/Conformance.test.cpp b/tests/Conformance.test.cpp index 1e520100..a023840b 100644 --- a/tests/Conformance.test.cpp +++ b/tests/Conformance.test.cpp @@ -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") {