设置 Lua 脚本的 require 搜索路径

我正在尝试使用 require 来加载使用 luaL_loadstring 加载的 Lua 脚本。

以下是我的代码:

lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
const char *script = "require('test.lua')";
const int ret = luaL_loadstring(L, script);
if (ret || lua_pcall(L, 0, LUA_MULTRET, 0))
{
    std::cout << "Error: " << lua_tostring(L, -1) << std::endl;
}
lua_close(L);

然而,当我运行代码时,我得到了以下错误:

Error: [string "require('test.lua')"]:1: module 'test.lua' not found:
no field package.preload['test.lua']
no file '/usr/local/share/lua/5.3/test/lua.lua'
no file '/usr/local/share/lua/5.3/test/lua/init.lua'
no file '/usr/local/lib/lua/5.3/test/lua.lua'
no file '/usr/local/lib/lua/5.3/test/lua/init.lua'
no file './test/lua.lua'
no file './test/lua/init.lua'
no file '/usr/local/lib/lua/5.3/test/lua.so'
no file '/usr/local/lib/lua/5.3/loadall.so'
no file './test/lua.so'
no file '/usr/local/lib/lua/5.3/test.so'
no file '/usr/local/lib/lua/5.3/loadall.so'
no file './test.so'

是否可能设置 Lua 脚本的搜索路径,从而可以使用相对路径使用 require

点赞
用户5224286
用户5224286

我能够使用以下代码来运行它,感谢@Henri_Menke。

/* 设置当前工作目录 */
const char *currentDir = "directory/to/script";
chdir(currentDir);
/* 初始化lua并运行脚本 */
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_settop(L, 0);
const char *script = "require('test')";
const int ret = luaL_loadstring(L, script);
if (ret || lua_pcall(L, 0, LUA_MULTRET, 0))
{
    std::cout << "Error: " << lua_tostring(L, -1) << std::endl;
}
lua_close(L);
2018-07-13 11:15:48