Zack Lee
Zack Lee

Reputation: 3044

Setting the require search path for Lua scripts

I'm trying to use require from a Lua script which I load using luaL_loadstring.

Here's my code:

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);

However, when I run the code, I get the following error.

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'

Is it possible to set the search path for Lua scripts so I can use require using the relative path?

Upvotes: 3

Views: 3027

Answers (1)

Zack Lee
Zack Lee

Reputation: 3044

I could make it to work using the following code thanks to @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);

Upvotes: 1

Related Questions