【问题标题】:How to bind a std::map to Lua with LuaBind如何使用 LuaBind 将 std::map 绑定到 Lua
【发布时间】:2013-07-08 20:16:40
【问题描述】:

我正在尝试将我的 std::map<std::string, std::string> 作为类属性公开给 Lua。我已经为我的 getter 和 setter 设置了这个方法:

luabind::object FakeScript::GetSetProperties()
{
    luabind::object table = luabind::newtable(L);
    luabind::object metatable = luabind::newtable(L);

    metatable["__index"] = &this->GetMeta;
    metatable["__newindex"] = &this->SetMeta;

    luabind::setmetatable<luabind::object, luabind::object>(table, metatable);

    return table;
}

这样我就可以在 Lua 中做这样的事情了:

player.scripts["movement"].properties["stat"] = "idle"
print(player.scripts["movement"].properties["stat"])

但是,我在 C++ 中提供的代码没有被编译。它告诉我在这一行 metatable["__index"] = &amp;this-&gt;GetMeta; 及其后的行有一个对重载函数的模棱两可的调用。我不确定我这样做是否正确。

错误信息:

error C2668: 'luabind::detail::check_const_pointer' : 
ambiguous call to overloaded function
c:\libraries\luabind-0.9.1\references\luabind\include\luabind\detail\instance_holder.hpp    75

这些是SetMetaGetMeta 中的FakeScript

static void GetMeta();
static void SetMeta();

以前我是为 getter 方法做的:

luabind::object FakeScript::getProp()
{
    luabind::object obj = luabind::newtable(L);

    for(auto i = this->properties.begin(); i != this->properties.end(); i++)
    {
        obj[i->first] = i->second;
    }

    return obj;
}

这很好用,但它不允许我使用 setter 方法。例如:

player.scripts["movement"].properties["stat"] = "idle"
print(player.scripts["movement"].properties["stat"])

在这段代码中,它只会在两行中触发 getter 方法。虽然如果它让我使用 setter,我将无法从这里的 ["stat"] 属性中获取密钥。

这里有 LuaBind 方面的专家吗?我见过大多数人说他们以前从未使用过它。

【问题讨论】:

  • 请在您的问题中填写完整的错误消息。
  • @greatwolf 我已经写好了。
  • 错误应该显示候选函数是什么。
  • 这就是我所得到的。实际上我需要有人告诉我如何以 LuaBind 的方式为元表字段分配函数。看,我可以将其更改为使用函数而不是属性来访问我的地图,但我担心用户的编程风格。
  • FakeScript::GetMetaFakeScript::SetMeta 看起来像什么?这些不是您要绑定的函数,它们是类方法。

标签: c++ stl lua luabind


【解决方案1】:

您需要使用(未记录的)make_function() 从函数中创建对象。

metatable["__index"] = luabind::make_function(L, &this->GetMeta);
metatable["__newindex"] = luabind::make_function(L, &this->GetMeta);

不幸的是,make_function 的这个(最简单的)重载被破坏了,但您只需要将insert f 作为make_function.hpp 中的第二个参数。

【讨论】:

  • 其实我来之前就试过了。由于过载的损坏,我无法让它工作,所以我把它扔掉了。现在你一直帮助我!我将尝试这样做,但我想出了另一种方法来使用函数重载来满足我的需求。
猜你喜欢
  • 2011-11-20
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
  • 2012-07-21
  • 2011-11-18
  • 2014-08-05
相关资源
最近更新 更多