Fix lua_requireinternal to use variable number of stack args

This will allow both `lua_require` and `lua_proxyrequire` work at the same time.
This commit is contained in:
Alex Orlenko 2025-05-03 20:33:05 +01:00
parent 72f6c8b679
commit a03bbef909
No known key found for this signature in database
GPG key ID: 4C150C250863B96D

View file

@ -121,9 +121,9 @@ static int checkRegisteredModules(lua_State* L, const char* path)
int lua_requirecont(lua_State* L, int status) int lua_requirecont(lua_State* L, int status)
{ {
// Number of stack arguments present before this continuation is called. // Number of stack arguments present before this continuation is called.
const int numStackArgs = 2; const int numStackArgs = lua_tointeger(L, 1);
const int numResults = lua_gettop(L) - numStackArgs; const int numResults = lua_gettop(L) - numStackArgs;
const char* cacheKey = luaL_checkstring(L, 2); const char* cacheKey = luaL_checkstring(L, numStackArgs);
if (numResults > 1) if (numResults > 1)
luaL_error(L, "module must return a single value"); luaL_error(L, "module must return a single value");
@ -152,6 +152,8 @@ int lua_requirecont(lua_State* L, int status)
int lua_requireinternal(lua_State* L, const char* requirerChunkname) int lua_requireinternal(lua_State* L, const char* requirerChunkname)
{ {
int stackTop = lua_gettop(L);
// If modifying the state of the stack, please update numStackArgs in the // If modifying the state of the stack, please update numStackArgs in the
// lua_requirecont continuation function. // lua_requirecont continuation function.
@ -171,10 +173,14 @@ int lua_requireinternal(lua_State* L, const char* requirerChunkname)
if (resolvedRequire.status == ResolvedRequire::Status::Cached) if (resolvedRequire.status == ResolvedRequire::Status::Cached)
return 1; return 1;
// (1) path, (2) cacheKey // (1) path, ..., cacheKey
lua_pushstring(L, resolvedRequire.cacheKey.c_str()); lua_pushstring(L, resolvedRequire.cacheKey.c_str());
int numArgsBeforeLoad = lua_gettop(L); // Insert number of arguments before the continuation to check the results.
int numArgsBeforeLoad = stackTop + 2;
lua_pushinteger(L, numArgsBeforeLoad);
lua_insert(L, 1);
int numResults = lrc->load(L, ctx, path, resolvedRequire.chunkname.c_str(), resolvedRequire.contents.c_str()); int numResults = lrc->load(L, ctx, path, resolvedRequire.chunkname.c_str(), resolvedRequire.contents.c_str());
if (numResults == -1) if (numResults == -1)
{ {