使用Lua C API调用table中的函数,网上资料较多,几乎都有问题。第3行至关重要,不然参数和返回值乱套,调试了好几天才解决。记录一下帮助其他人出坑。
lua_getglobal(L, table); // 获取表
lua_getfield(L, function); // 获取函数
lua_pushvalue(L, -2); // 获取表作为第一个参数,类似于c++中的this指针
lua_remove(L, -3); // 移除最前面得到的表
// 压入其它参数
// ...
/**
* 调用函数
* 参数2是入参个数
* 参数3是返回值个数,不够会补nil,多余会忽略
*/
int ret = lua_pcall(L, nargs, 1, 0);
if(ret != LUA_OK) {
std::cerr << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1); // 错误出栈
return;
}
// 返回值处理
// ...
lua_pop(L, 1); // 返回值出栈