1

我正在学习 luabind 并尝试使用 luabind::object 从 C++ 访问 Lua 中的变量。

当我将 int 分配给“对象”时,编译失败。

编码:

int main()
{
    using namespace luabind;
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);
    open(L);
    luaL_dofile(L, "./test.lua"); // a = 5
    object g = globals(L);
    object num = g["a"];
    num = 6; // Failed to compile
    return 0;
}

错误消息:

luatets.cpp:21:6: error: no match for ‘operator=’ (operand types are ‘luabind::adl::object’ and ‘int’)
  num = 6;
/usr/include/luabind/object.hpp:731:9: note: luabind::adl::object& luabind::adl::object::operator=(const luabind::adl::object&)
   class object : public object_interface<object>
/usr/include/luabind/object.hpp:731:9: note:   no known conversion for argument 1 from ‘int’ to ‘const luabind::adl::object&’

但是在我合并这两行之后,代码就起作用了:

g["a"] = 6;

我不知道为什么会这样。在 luabind 文档中,据说:

当你有一个 Lua 对象时,你可以用赋值运算符 (=) 给它赋一个新值。执行此操作时,将使用 default_policy 将 C++ 值转换为 Lua。

并且在类声明中,赋值运算符被重载为任意类型,而不仅仅是object&:

template <class T>
object& operator=(T const&);

object& operator=(object const&); 

顺便说一句,我发现我的问题与类似,但没有人回答。

我查看了 luabind 标头,但在那些可怕的代理中找不到任何线索。

谁能告诉我为什么第一个代码不正确以及是否operator=(T const &)超载?

非常感谢!!

4

1 回答 1

0

Luabind 0.9.1 在对象中没有这样的 operator= 重载,无论(可能已过时?!)文档说什么。事实上,object 根本没有 operator= 重载(也没有 object_interface,object 是从哪个派生而来的)。

但是,它具有:

template<class T>
    index_proxy<object> operator[](T const& key) const

这就是为什么g["a"] = 6;index_proxy 有:

template<class T>
    this_type& operator=(T const& value)

可以为 int 实例化。

于 2014-09-19T01:34:18.590 回答