我开始把我的手放在卢阿,并有一个相当令人沮丧的经验到目前为止。我需要加载部分笔录,以便加载需要mine.lua的“pl.import_into”。我需要用C/C++来完成这个任务。
我使用Lua5.1;使用5.2不是自动取款机,所以我没有luaL_requiref
大致上我的代码如下所示:
void luaLoad(lua_State* L, const char* f) {
if (luaL_dofile(L, f) || lua_pcall(L, 0, 0, 0)) {
const char* err = lua_tostring(L, -1);
lua_pop(L, -1);
throw std::runtime_error("Lua load error");
}
}
int main(void) {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaLoad(L, "~/Penlight-1.3.1/lua/pl/compat.lua");
luaLoad(L, "~/Penlight-1.3.1/lua/pl/utils.lua");
luaLoad(L, "~/Penlight-1.3.1/lua/pl/import_into.lua");
luaLoad(L, "mine.lua");
...
}我开始尝试加载import_into.lua,它需要utils.lua和过渡compat.lua。
在我的luaLoad方法中,如果我删除lua_pcall,utils.lua“看不到”compat.lua:
utils.lua : module 'pl.compat' not found`然而,在lua_pcall中,我得到了一个
attempt to call a table value` error.试图从C加载笔杆完全错误吗?
发布于 2014-06-18 18:48:39
首先,lua_pcall是多余的。luaL_dofile已经做了一个lua_pcall。lua_pop调用也是错误的。第二:为什么您不只是修改package.path,以便Lua的require函数可以找到必要的模块?
如果您不能或不想这样做,有两种方法:
除了运行模块代码之外,还需要使用模块名作为键,将其结果存储在package.loaded表中。这样,笔录代码中调用的require函数可以在以后找到这些模块。
void luaLoad(lua_State* L, char const* m, const char* f) {
int top = lua_gettop(L);
if (luaL_dofile(L, f)) {
const char* err = lua_tostring(L, -1);
lua_pop(L, 1); /* the 2nd parameter is a number not a stack index! */
throw std::runtime_error("Lua load error");
} else {
lua_settop(L, top+1); /* discard anything but first return value */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); /* get `package.loaded` */
lua_pushvalue(L, -2); /* `lua_setfield` needs the return value at stack top */
lua_setfield(L, -2, m); /* store return value as `package.loaded[m]` */
lus_settop(L, top); /* restore Lua stack */
}
}优点是可以使用相同的函数来运行mine.lua。缺点是必须按正确的顺序加载模块,如果其中一个模块使用module函数,代码会变得更复杂(基本上是重新实现Lua的require函数的部分)。
第二种方法是加载但不运行模块,并使用模块名作为键将加载的代码(这是Lua函数)放在package.preload表中。require函数稍后可以将它们取出来并从那里运行。
void luaPreload(lua_State* L, char const* m, char const* f) {
if (luaL_loadfile(L, f)) {
char const* err = lua_tostring(L, -1);
lua_pop(L, 1);
throw std:runtime_error("Lua load error");
} else {
lua_getglobal(L, "package"); /* there is no shorthand for `package.preload` */
lua_getfield(L, -1, "preload");
lua_pushvalue(L, -3); /* `lua_setfield` needs the function at stack top */
lua_setfield(L, -2, m); /* store chunk as `package.preload[m]` */
lua_pop(L, 3); /* restore Lua stack */
}
}优点是需要自动按正确的顺序运行模块,并且module函数不需要特殊处理。一个缺点是需要单独的代码来运行mine.lua。
所有这些方法都假设mine.lua使用Lua的require函数来访问笔录模块。
https://stackoverflow.com/questions/24277156
复制相似问题