gpt4 book ai didi

lua - 设置 Lua 脚本的 require 搜索路径

转载 作者:行者123 更新时间:2023-12-05 06:32:26 24 4
gpt4 key购买 nike

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

这是我的代码:

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 使用相对路径?

最佳答案

感谢@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);

关于lua - 设置 Lua 脚本的 require 搜索路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51320354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com