Lua-C++集成:从C++调用表中的函数
Lua - C++ Integration: Calling function in table from C++
我不是Lua专家,但我已经阅读了一些文章来了解它是如何工作的。然而,我在从C++调用属于表的lua函数时遇到了问题。
在下面描述的例子中,我试图从代码中调用foo:bar。呼叫成功。然而,参数"a"为零(返回值是正确的-当我将返回值更改为例如10时,它显示正确的结果)
在将函数参数推送到脚本的过程中,我是否遗漏了什么?
lua_State* state = LuaIntegration->GetLuaState();
lua_getglobal(state, "foo");
if(lua_istable(state, lua_gettop(state))) {
lua_getfield(state, -1, "bar");
if(lua_isfunction(state, lua_gettop(state))) {
lua_pushinteger(state, 0);
if (lua_pcall(state, 1, 1, 0) != 0) {
ErrorMessage = lua_tostring(state, -1);
}
ReturnValue = lua_tointeger(state, -1);
}
}
它调用lua:中的函数
foo = base_foo:new()
function foo:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function foo:bar(a)
if a==10 then
return a
end
return 0
end
您在C++调用中忘记了糖。
如果你阅读lua手册的函数调用部分,你会看到
调用
v:name(args)
是v.name(v,args)
的语法糖,只是v
只被求值一次。
这意味着base_foo:new()
实际上只是base_foo.new(base_foo)
。
这就是您在C++调用中缺少的内容。
调用该函数时,需要将该表作为第一个参数传递给它。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销