Lua - C++ 集成:从 C++ 调用表中的函数

我不是 Lua 专家,但我读了一些文章来理解它的工作原理。然而,我在从 C++ 中调用属于表的 Lua 函数方面遇到了问题。

在下面描述的示例中,我正在尝试从代码中调用 foo:bar。调用成功。然而,参数“a”是 nil(返回值是正确的 - 当我将返回值更改为例如 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
点赞
用户258523
用户258523

你在 C++ 的调用中忘记了加上语法糖。

如果你阅读了 lua 手册 中的 Function Calls 章节,你会发现:

一个调用 v:name(args) 的语法糖等价于 v.name(v,args),不同的是 v 只会被计算一次。

也就是说,base_foo:new() 实际上是 base_foo.new(base_foo)

这就是你在 C++ 调用中丢失的东西。

当你调用函数时需要将 table 作为第一个参数传递给函数。

2016-08-04 12:56:51