如何使用LuaBind将std::map绑定到Lua



我正试图将我的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"] = &this->GetMeta;行及其后的行有一个对重载函数的模糊调用。我不确定我做得是否正确。

错误消息:

error C2668: 'luabind::detail::check_const_pointer' : 
ambiguous call to overloaded function
c:librariesluabind-0.9.1referencesluabindincludeluabinddetailinstance_holder.hpp    75

它们是FakeScript:中的SetMetaGetMeta

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"]

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

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

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

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

最新更新