设置Lua脚本的require搜索路径

时间:2018-07-13 07:59:36

标签: lua require

我正在尝试从我使用require加载的Lua脚本中使用luaL_loadstring

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

由于@Henri_Menke,我可以使用以下代码使其工作。

/* set the current working directory */
const char *currentDir = "directory/to/script";
chdir(currentDir);
/* init lua and run script */
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);