这个问题与 @Henri_Menke 在这个问题中的回答相关:如何在 C++ 中获取预加载模块名称 https://stackoverflow.com/questions/51510308/how-to-get-preloaded-module-name-in-c
我正在尝试覆盖require
使用我自己的版本运行函数,这样我就可以在 Lua 脚本中获取预加载的模块名称。
这是我的代码:
#include "lua.hpp"
void main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
luaL_dostring(L, "local require_original = require\n"
"function require(name, ...)\n"
"current_module = name\n"
"require_original(name, ...)\n"
"current_module = nil\n"
"end\n"); //if I comment out this chunk, it works fine
luaL_dostring(L, "package.preload['test'] = function ()\n"
"local test = {}\n"
"print('While loading:', current_module)\n"
"function test.update() print('Updated!') end\n"
"return test\n"
"end\n");
lua_getglobal(L, "require");
lua_pushstring(L, "test");
if (lua_pcall(L, 1, LUA_MULTRET, 0))
{
std::cout << "Error: " << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1);
}
int top = lua_gettop(L);
lua_getfield(L, -1, "update"); //crashes here
if (lua_isfunction(L, -1))
{
lua_pushnil(L);
if (lua_pcall(L, 1, LUA_MULTRET, 0))
{
std::cout << "Error: " << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1);
}
}
lua_close(L);
}
但是调用的时候就崩溃了lua_getfield(L, -1, "update");
.
当我注释掉 Lua 脚本的第一块(第一个luaL_dostring
).
我不明白为什么如果我使用我自己的版本它会崩溃require
.
我怎样才能解决这个问题?